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"
30 #define SLAB_SIZE (1024 * 1024)
32 // Temporary hack: libuv should provide uv_inet_pton and uv_inet_ntop.
33 // Clean this up in tcp_wrap.cc too.
34 #if defined(__MINGW32__) || defined(_MSC_VER)
36 # include <inet_net_pton.h>
37 # include <inet_ntop.h>
39 # define uv_inet_pton ares_inet_pton
40 # define uv_inet_ntop ares_inet_ntop
43 # include <arpa/inet.h>
44 # define uv_inet_pton inet_pton
45 # define uv_inet_ntop inet_ntop
53 assert(!args.Holder().IsEmpty()); \
54 assert(args.Holder()->InternalFieldCount() > 0); \
56 static_cast<UDPWrap*>(args.Holder()->GetPointerFromInternalField(0)); \
59 err.code = UV_EBADF; \
61 return scope.Close(Integer::New(-1)); \
64 typedef ReqWrap<uv_udp_send_t> SendWrap;
66 Local<Object> AddressToJS(const sockaddr* addr);
68 static Persistent<String> address_symbol;
69 static Persistent<String> port_symbol;
70 static Persistent<String> buffer_sym;
71 static Persistent<String> oncomplete_sym;
72 static Persistent<String> onmessage_sym;
73 static SlabAllocator slab_allocator(SLAB_SIZE);
76 class UDPWrap: public HandleWrap {
78 static void Initialize(Handle<Object> target);
79 static Handle<Value> New(const Arguments& args);
80 static Handle<Value> Bind(const Arguments& args);
81 static Handle<Value> Send(const Arguments& args);
82 static Handle<Value> Bind6(const Arguments& args);
83 static Handle<Value> Send6(const Arguments& args);
84 static Handle<Value> RecvStart(const Arguments& args);
85 static Handle<Value> RecvStop(const Arguments& args);
86 static Handle<Value> GetSockName(const Arguments& args);
87 static Handle<Value> AddMembership(const Arguments& args);
88 static Handle<Value> DropMembership(const Arguments& args);
89 static Handle<Value> SetMulticastTTL(const Arguments& args);
90 static Handle<Value> SetMulticastLoopback(const Arguments& args);
91 static Handle<Value> SetBroadcast(const Arguments& args);
92 static Handle<Value> SetTTL(const Arguments& args);
95 UDPWrap(Handle<Object> object);
98 static Handle<Value> DoBind(const Arguments& args, int family);
99 static Handle<Value> DoSend(const Arguments& args, int family);
100 static Handle<Value> SetMembership(const Arguments& args,
101 uv_membership membership);
103 static uv_buf_t OnAlloc(uv_handle_t* handle, size_t suggested_size);
104 static void OnSend(uv_udp_send_t* req, int status);
105 static void OnRecv(uv_udp_t* handle,
108 struct sockaddr* addr,
115 UDPWrap::UDPWrap(Handle<Object> object): HandleWrap(object,
116 (uv_handle_t*)&handle_) {
117 int r = uv_udp_init(uv_default_loop(), &handle_);
118 assert(r == 0); // can't fail anyway
119 handle_.data = reinterpret_cast<void*>(this);
123 UDPWrap::~UDPWrap() {
127 void UDPWrap::Initialize(Handle<Object> target) {
128 HandleWrap::Initialize(target);
132 buffer_sym = NODE_PSYMBOL("buffer");
133 port_symbol = NODE_PSYMBOL("port");
134 address_symbol = NODE_PSYMBOL("address");
135 oncomplete_sym = NODE_PSYMBOL("oncomplete");
136 onmessage_sym = NODE_PSYMBOL("onmessage");
138 Local<FunctionTemplate> t = FunctionTemplate::New(New);
139 t->InstanceTemplate()->SetInternalFieldCount(1);
140 t->SetClassName(String::NewSymbol("UDP"));
142 NODE_SET_PROTOTYPE_METHOD(t, "bind", Bind);
143 NODE_SET_PROTOTYPE_METHOD(t, "send", Send);
144 NODE_SET_PROTOTYPE_METHOD(t, "bind6", Bind6);
145 NODE_SET_PROTOTYPE_METHOD(t, "send6", Send6);
146 NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
147 NODE_SET_PROTOTYPE_METHOD(t, "recvStart", RecvStart);
148 NODE_SET_PROTOTYPE_METHOD(t, "recvStop", RecvStop);
149 NODE_SET_PROTOTYPE_METHOD(t, "getsockname", GetSockName);
150 NODE_SET_PROTOTYPE_METHOD(t, "addMembership", AddMembership);
151 NODE_SET_PROTOTYPE_METHOD(t, "dropMembership", DropMembership);
152 NODE_SET_PROTOTYPE_METHOD(t, "setMulticastTTL", SetMulticastTTL);
153 NODE_SET_PROTOTYPE_METHOD(t, "setMulticastLoopback", SetMulticastLoopback);
154 NODE_SET_PROTOTYPE_METHOD(t, "setBroadcast", SetBroadcast);
155 NODE_SET_PROTOTYPE_METHOD(t, "setTTL", SetTTL);
157 target->Set(String::NewSymbol("UDP"),
158 Persistent<FunctionTemplate>::New(t)->GetFunction());
162 Handle<Value> UDPWrap::New(const Arguments& args) {
165 assert(args.IsConstructCall());
166 new UDPWrap(args.This());
168 return scope.Close(args.This());
171 Handle<Value> UDPWrap::DoBind(const Arguments& args, int family) {
177 // bind(ip, port, flags)
178 assert(args.Length() == 3);
180 String::Utf8Value address(args[0]);
181 const int port = args[1]->Uint32Value();
182 const int flags = args[2]->Uint32Value();
186 r = uv_udp_bind(&wrap->handle_, uv_ip4_addr(*address, port), flags);
189 r = uv_udp_bind6(&wrap->handle_, uv_ip6_addr(*address, port), flags);
192 assert(0 && "unexpected address family");
197 SetErrno(uv_last_error(uv_default_loop()));
199 return scope.Close(Integer::New(r));
203 Handle<Value> UDPWrap::Bind(const Arguments& args) {
204 return DoBind(args, AF_INET);
208 Handle<Value> UDPWrap::Bind6(const Arguments& args) {
209 return DoBind(args, AF_INET6);
213 #define X(name, fn) \
214 Handle<Value> UDPWrap::name(const Arguments& args) { \
217 assert(args.Length() == 1); \
218 int flag = args[0]->Int32Value(); \
219 int r = fn(&wrap->handle_, flag); \
220 if (r) SetErrno(uv_last_error(uv_default_loop())); \
221 return scope.Close(Integer::New(r)); \
224 X(SetTTL, uv_udp_set_ttl)
225 X(SetBroadcast, uv_udp_set_broadcast)
226 X(SetMulticastTTL, uv_udp_set_multicast_ttl)
227 X(SetMulticastLoopback, uv_udp_set_multicast_loop)
232 Handle<Value> UDPWrap::SetMembership(const Arguments& args,
233 uv_membership membership) {
237 assert(args.Length() == 2);
239 String::Utf8Value address(args[0]);
240 String::Utf8Value iface(args[1]);
242 const char* iface_cstr = *iface;
243 if (args[1]->IsUndefined() || args[1]->IsNull()) {
247 int r = uv_udp_set_membership(&wrap->handle_, *address, iface_cstr,
251 SetErrno(uv_last_error(uv_default_loop()));
253 return scope.Close(Integer::New(r));
257 Handle<Value> UDPWrap::AddMembership(const Arguments& args) {
258 return SetMembership(args, UV_JOIN_GROUP);
262 Handle<Value> UDPWrap::DropMembership(const Arguments& args) {
263 return SetMembership(args, UV_LEAVE_GROUP);
267 Handle<Value> UDPWrap::DoSend(const Arguments& args, int family) {
271 // send(buffer, offset, length, port, address)
272 assert(args.Length() == 5);
276 assert(Buffer::HasInstance(args[0]));
277 Local<Object> buffer_obj = args[0]->ToObject();
279 size_t offset = args[1]->Uint32Value();
280 size_t length = args[2]->Uint32Value();
281 assert(offset < Buffer::Length(buffer_obj));
282 assert(length <= Buffer::Length(buffer_obj) - offset);
284 SendWrap* req_wrap = new SendWrap();
285 req_wrap->object_->SetHiddenValue(buffer_sym, buffer_obj);
287 uv_buf_t buf = uv_buf_init(Buffer::Data(buffer_obj) + offset,
290 const unsigned short port = args[3]->Uint32Value();
291 String::Utf8Value address(args[4]);
295 r = uv_udp_send(&req_wrap->req_, &wrap->handle_, &buf, 1,
296 uv_ip4_addr(*address, port), OnSend);
299 r = uv_udp_send6(&req_wrap->req_, &wrap->handle_, &buf, 1,
300 uv_ip6_addr(*address, port), OnSend);
303 assert(0 && "unexpected address family");
307 req_wrap->Dispatched();
310 SetErrno(uv_last_error(uv_default_loop()));
315 return scope.Close(req_wrap->object_);
320 Handle<Value> UDPWrap::Send(const Arguments& args) {
321 return DoSend(args, AF_INET);
325 Handle<Value> UDPWrap::Send6(const Arguments& args) {
326 return DoSend(args, AF_INET6);
330 Handle<Value> UDPWrap::RecvStart(const Arguments& args) {
335 // UV_EALREADY means that the socket is already bound but that's okay
336 int r = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv);
337 if (r && uv_last_error(uv_default_loop()).code != UV_EALREADY) {
338 SetErrno(uv_last_error(uv_default_loop()));
346 Handle<Value> UDPWrap::RecvStop(const Arguments& args) {
351 int r = uv_udp_recv_stop(&wrap->handle_);
353 return scope.Close(Integer::New(r));
357 Handle<Value> UDPWrap::GetSockName(const Arguments& args) {
359 struct sockaddr_storage address;
363 int addrlen = sizeof(address);
364 int r = uv_udp_getsockname(&wrap->handle_,
365 reinterpret_cast<sockaddr*>(&address),
369 SetErrno(uv_last_error(uv_default_loop()));
373 const sockaddr* addr = reinterpret_cast<const sockaddr*>(&address);
374 return scope.Close(AddressToJS(addr));
378 // TODO share with StreamWrap::AfterWrite() in stream_wrap.cc
379 void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
384 SendWrap* req_wrap = reinterpret_cast<SendWrap*>(req->data);
385 UDPWrap* wrap = reinterpret_cast<UDPWrap*>(req->handle->data);
387 assert(req_wrap->object_.IsEmpty() == false);
388 assert(wrap->object_.IsEmpty() == false);
391 SetErrno(uv_last_error(uv_default_loop()));
394 Local<Value> argv[4] = {
395 Integer::New(status),
396 Local<Value>::New(wrap->object_),
397 Local<Value>::New(req_wrap->object_),
398 req_wrap->object_->GetHiddenValue(buffer_sym),
401 MakeCallback(req_wrap->object_, oncomplete_sym, ARRAY_SIZE(argv), argv);
406 uv_buf_t UDPWrap::OnAlloc(uv_handle_t* handle, size_t suggested_size) {
407 UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
408 char* buf = slab_allocator.Allocate(wrap->object_, suggested_size);
409 return uv_buf_init(buf, suggested_size);
413 void UDPWrap::OnRecv(uv_udp_t* handle,
416 struct sockaddr* addr,
420 UDPWrap* wrap = reinterpret_cast<UDPWrap*>(handle->data);
421 Local<Object> slab = slab_allocator.Shrink(wrap->object_,
423 nread < 0 ? 0 : nread);
424 if (nread == 0) return;
427 Local<Value> argv[] = { Local<Object>::New(wrap->object_) };
428 SetErrno(uv_last_error(uv_default_loop()));
429 MakeCallback(wrap->object_, onmessage_sym, ARRAY_SIZE(argv), argv);
433 Local<Value> argv[] = {
434 Local<Object>::New(wrap->object_),
436 Integer::NewFromUnsigned(buf.base - Buffer::Data(slab)),
437 Integer::NewFromUnsigned(nread),
440 MakeCallback(wrap->object_, onmessage_sym, ARRAY_SIZE(argv), argv);
444 Local<Object> AddressToJS(const sockaddr* addr) {
446 char ip[INET6_ADDRSTRLEN];
447 const sockaddr_in *a4;
448 const sockaddr_in6 *a6;
451 Local<Object> info = Object::New();
453 switch (addr->sa_family) {
455 a6 = reinterpret_cast<const sockaddr_in6*>(addr);
456 uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip);
457 port = ntohs(a6->sin6_port);
458 info->Set(address_symbol, String::New(ip));
459 info->Set(port_symbol, Integer::New(port));
463 a4 = reinterpret_cast<const sockaddr_in*>(addr);
464 uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip);
465 port = ntohs(a4->sin_port);
466 info->Set(address_symbol, String::New(ip));
467 info->Set(port_symbol, Integer::New(port));
471 info->Set(address_symbol, String::Empty());
474 return scope.Close(info);
480 NODE_MODULE(node_udp_wrap, node::UDPWrap::Initialize)