1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #include "node_buffer.h"
24 #include "slab_allocator.h"
26 #include "handle_wrap.h"
31 #define SLAB_SIZE (1024 * 1024)
33 // Temporary hack: libuv should provide uv_inet_pton and uv_inet_ntop.
34 // Clean this up in tcp_wrap.cc too.
35 #if defined(__MINGW32__) || defined(_MSC_VER)
37 # include <inet_net_pton.h>
38 # include <inet_ntop.h>
40 # define uv_inet_pton ares_inet_pton
41 # define uv_inet_ntop ares_inet_ntop
44 # include <arpa/inet.h>
45 # define uv_inet_pton inet_pton
46 # define uv_inet_ntop inet_ntop
53 typedef ReqWrap<uv_udp_send_t> SendWrap;
56 Local<Object> AddressToJS(const sockaddr* addr);
58 static Persistent<String> buffer_sym;
59 static Persistent<String> oncomplete_sym;
60 static Persistent<String> onmessage_sym;
61 static SlabAllocator* slab_allocator;
64 static void DeleteSlabAllocator(void*) {
65 delete slab_allocator;
66 slab_allocator = NULL;
70 UDPWrap::UDPWrap(Handle<Object> object): HandleWrap(object,
71 (uv_handle_t*)&handle_) {
72 int r = uv_udp_init(uv_default_loop(), &handle_);
73 assert(r == 0); // can't fail anyway
74 handle_.data = reinterpret_cast<void*>(this);
82 void UDPWrap::Initialize(Handle<Object> target) {
83 HandleWrap::Initialize(target);
85 slab_allocator = new SlabAllocator(SLAB_SIZE);
86 AtExit(DeleteSlabAllocator, NULL);
90 buffer_sym = NODE_PSYMBOL("buffer");
91 oncomplete_sym = NODE_PSYMBOL("oncomplete");
92 onmessage_sym = NODE_PSYMBOL("onmessage");
94 Local<FunctionTemplate> t = FunctionTemplate::New(New);
95 t->InstanceTemplate()->SetInternalFieldCount(1);
96 t->SetClassName(String::NewSymbol("UDP"));
98 NODE_SET_PROTOTYPE_METHOD(t, "bind", Bind);
99 NODE_SET_PROTOTYPE_METHOD(t, "send", Send);
100 NODE_SET_PROTOTYPE_METHOD(t, "bind6", Bind6);
101 NODE_SET_PROTOTYPE_METHOD(t, "send6", Send6);
102 NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
103 NODE_SET_PROTOTYPE_METHOD(t, "recvStart", RecvStart);
104 NODE_SET_PROTOTYPE_METHOD(t, "recvStop", RecvStop);
105 NODE_SET_PROTOTYPE_METHOD(t, "getsockname", GetSockName);
106 NODE_SET_PROTOTYPE_METHOD(t, "addMembership", AddMembership);
107 NODE_SET_PROTOTYPE_METHOD(t, "dropMembership", DropMembership);
108 NODE_SET_PROTOTYPE_METHOD(t, "setMulticastTTL", SetMulticastTTL);
109 NODE_SET_PROTOTYPE_METHOD(t, "setMulticastLoopback", SetMulticastLoopback);
110 NODE_SET_PROTOTYPE_METHOD(t, "setBroadcast", SetBroadcast);
111 NODE_SET_PROTOTYPE_METHOD(t, "setTTL", SetTTL);
113 NODE_SET_PROTOTYPE_METHOD(t, "ref", HandleWrap::Ref);
114 NODE_SET_PROTOTYPE_METHOD(t, "unref", HandleWrap::Unref);
116 target->Set(String::NewSymbol("UDP"),
117 Persistent<FunctionTemplate>::New(t)->GetFunction());
121 Handle<Value> UDPWrap::New(const Arguments& args) {
124 assert(args.IsConstructCall());
125 new UDPWrap(args.This());
127 return scope.Close(args.This());
130 Handle<Value> UDPWrap::DoBind(const Arguments& args, int family) {
136 // bind(ip, port, flags)
137 assert(args.Length() == 3);
139 String::Utf8Value address(args[0]);
140 const int port = args[1]->Uint32Value();
141 const int flags = args[2]->Uint32Value();
145 r = uv_udp_bind(&wrap->handle_, uv_ip4_addr(*address, port), flags);
148 r = uv_udp_bind6(&wrap->handle_, uv_ip6_addr(*address, port), flags);
151 assert(0 && "unexpected address family");
156 SetErrno(uv_last_error(uv_default_loop()));
158 return scope.Close(Integer::New(r));
162 Handle<Value> UDPWrap::Bind(const Arguments& args) {
163 return DoBind(args, AF_INET);
167 Handle<Value> UDPWrap::Bind6(const Arguments& args) {
168 return DoBind(args, AF_INET6);
172 #define X(name, fn) \
173 Handle<Value> UDPWrap::name(const Arguments& args) { \
176 assert(args.Length() == 1); \
177 int flag = args[0]->Int32Value(); \
178 int r = fn(&wrap->handle_, flag); \
179 if (r) SetErrno(uv_last_error(uv_default_loop())); \
180 return scope.Close(Integer::New(r)); \
183 X(SetTTL, uv_udp_set_ttl)
184 X(SetBroadcast, uv_udp_set_broadcast)
185 X(SetMulticastTTL, uv_udp_set_multicast_ttl)
186 X(SetMulticastLoopback, uv_udp_set_multicast_loop)
191 Handle<Value> UDPWrap::SetMembership(const Arguments& args,
192 uv_membership membership) {
196 assert(args.Length() == 2);
198 String::Utf8Value address(args[0]);
199 String::Utf8Value iface(args[1]);
201 const char* iface_cstr = *iface;
202 if (args[1]->IsUndefined() || args[1]->IsNull()) {
206 int r = uv_udp_set_membership(&wrap->handle_, *address, iface_cstr,
210 SetErrno(uv_last_error(uv_default_loop()));
212 return scope.Close(Integer::New(r));
216 Handle<Value> UDPWrap::AddMembership(const Arguments& args) {
217 return SetMembership(args, UV_JOIN_GROUP);
221 Handle<Value> UDPWrap::DropMembership(const Arguments& args) {
222 return SetMembership(args, UV_LEAVE_GROUP);
226 Handle<Value> UDPWrap::DoSend(const Arguments& args, int family) {
230 // send(buffer, offset, length, port, address)
231 assert(args.Length() == 5);
235 assert(Buffer::HasInstance(args[0]));
236 Local<Object> buffer_obj = args[0]->ToObject();
238 size_t offset = args[1]->Uint32Value();
239 size_t length = args[2]->Uint32Value();
240 assert(offset < Buffer::Length(buffer_obj));
241 assert(length <= Buffer::Length(buffer_obj) - offset);
243 SendWrap* req_wrap = new SendWrap();
244 req_wrap->object_->SetHiddenValue(buffer_sym, buffer_obj);
246 uv_buf_t buf = uv_buf_init(Buffer::Data(buffer_obj) + offset,
249 const unsigned short port = args[3]->Uint32Value();
250 String::Utf8Value address(args[4]);
254 r = uv_udp_send(&req_wrap->req_, &wrap->handle_, &buf, 1,
255 uv_ip4_addr(*address, port), OnSend);
258 r = uv_udp_send6(&req_wrap->req_, &wrap->handle_, &buf, 1,
259 uv_ip6_addr(*address, port), OnSend);
262 assert(0 && "unexpected address family");
266 req_wrap->Dispatched();
269 SetErrno(uv_last_error(uv_default_loop()));
274 return scope.Close(req_wrap->object_);
279 Handle<Value> UDPWrap::Send(const Arguments& args) {
280 return DoSend(args, AF_INET);
284 Handle<Value> UDPWrap::Send6(const Arguments& args) {
285 return DoSend(args, AF_INET6);
289 Handle<Value> UDPWrap::RecvStart(const Arguments& args) {
294 // UV_EALREADY means that the socket is already bound but that's okay
295 int r = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv);
296 if (r && uv_last_error(uv_default_loop()).code != UV_EALREADY) {
297 SetErrno(uv_last_error(uv_default_loop()));
305 Handle<Value> UDPWrap::RecvStop(const Arguments& args) {
310 int r = uv_udp_recv_stop(&wrap->handle_);
312 return scope.Close(Integer::New(r));
316 Handle<Value> UDPWrap::GetSockName(const Arguments& args) {
318 struct sockaddr_storage address;
322 int addrlen = sizeof(address);
323 int r = uv_udp_getsockname(&wrap->handle_,
324 reinterpret_cast<sockaddr*>(&address),
328 SetErrno(uv_last_error(uv_default_loop()));
332 const sockaddr* addr = reinterpret_cast<const sockaddr*>(&address);
333 return scope.Close(AddressToJS(addr));
337 // TODO share with StreamWrap::AfterWrite() in stream_wrap.cc
338 void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
343 SendWrap* req_wrap = reinterpret_cast<SendWrap*>(req->data);
344 UDPWrap* wrap = reinterpret_cast<UDPWrap*>(req->handle->data);
346 assert(req_wrap->object_.IsEmpty() == false);
347 assert(wrap->object_.IsEmpty() == false);
350 SetErrno(uv_last_error(uv_default_loop()));
353 Local<Value> argv[4] = {
354 Integer::New(status),
355 Local<Value>::New(wrap->object_),
356 Local<Value>::New(req_wrap->object_),
357 req_wrap->object_->GetHiddenValue(buffer_sym),
360 MakeCallback(req_wrap->object_, oncomplete_sym, ARRAY_SIZE(argv), argv);
365 uv_buf_t UDPWrap::OnAlloc(uv_handle_t* handle, size_t suggested_size) {
366 UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
367 char* buf = slab_allocator->Allocate(wrap->object_, suggested_size);
368 return uv_buf_init(buf, suggested_size);
372 void UDPWrap::OnRecv(uv_udp_t* handle,
375 struct sockaddr* addr,
379 UDPWrap* wrap = reinterpret_cast<UDPWrap*>(handle->data);
380 Local<Object> slab = slab_allocator->Shrink(wrap->object_,
382 nread < 0 ? 0 : nread);
383 if (nread == 0) return;
386 Local<Value> argv[] = { Local<Object>::New(wrap->object_) };
387 SetErrno(uv_last_error(uv_default_loop()));
388 MakeCallback(wrap->object_, onmessage_sym, ARRAY_SIZE(argv), argv);
392 Local<Value> argv[] = {
393 Local<Object>::New(wrap->object_),
395 Integer::NewFromUnsigned(buf.base - Buffer::Data(slab)),
396 Integer::NewFromUnsigned(nread),
399 MakeCallback(wrap->object_, onmessage_sym, ARRAY_SIZE(argv), argv);
403 UDPWrap* UDPWrap::Unwrap(Local<Object> obj) {
404 assert(!obj.IsEmpty());
405 assert(obj->InternalFieldCount() > 0);
406 return static_cast<UDPWrap*>(obj->GetPointerFromInternalField(0));
410 uv_udp_t* UDPWrap::UVHandle() {
417 NODE_MODULE(node_udp_wrap, node::UDPWrap::Initialize)