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"
26 #include "handle_wrap.h"
30 // Temporary hack: libuv should provide uv_inet_pton and uv_inet_ntop.
31 // Clean this up in tcp_wrap.cc too.
32 #if defined(__MINGW32__) || defined(_MSC_VER)
34 # include <inet_net_pton.h>
35 # include <inet_ntop.h>
37 # define uv_inet_pton ares_inet_pton
38 # define uv_inet_ntop ares_inet_ntop
41 # include <arpa/inet.h>
42 # define uv_inet_pton inet_pton
43 # define uv_inet_ntop inet_ntop
51 assert(!args.Holder().IsEmpty()); \
52 assert(args.Holder()->InternalFieldCount() > 0); \
54 static_cast<UDPWrap*>(args.Holder()->GetPointerFromInternalField(0)); \
57 err.code = UV_EBADF; \
59 return scope.Close(Integer::New(-1)); \
62 // TODO share with tcp_wrap.cc
63 Persistent<String> address_symbol;
64 Persistent<String> port_symbol;
65 Persistent<String> buffer_sym;
67 void AddressToJS(Handle<Object> info,
71 typedef ReqWrap<uv_udp_send_t> SendWrap;
74 class UDPWrap: public HandleWrap {
76 static void Initialize(Handle<Object> target);
77 static Handle<Value> New(const Arguments& args);
78 static Handle<Value> Bind(const Arguments& args);
79 static Handle<Value> Send(const Arguments& args);
80 static Handle<Value> Bind6(const Arguments& args);
81 static Handle<Value> Send6(const Arguments& args);
82 static Handle<Value> RecvStart(const Arguments& args);
83 static Handle<Value> RecvStop(const Arguments& args);
84 static Handle<Value> GetSockName(const Arguments& args);
85 static Handle<Value> AddMembership(const Arguments& args);
86 static Handle<Value> DropMembership(const Arguments& args);
87 static Handle<Value> SetMulticastTTL(const Arguments& args);
88 static Handle<Value> SetMulticastLoopback(const Arguments& args);
89 static Handle<Value> SetBroadcast(const Arguments& args);
90 static Handle<Value> SetTTL(const Arguments& args);
93 UDPWrap(Handle<Object> object);
96 static Handle<Value> DoBind(const Arguments& args, int family);
97 static Handle<Value> DoSend(const Arguments& args, int family);
98 static Handle<Value> SetMembership(const Arguments& args,
99 uv_membership membership);
101 static uv_buf_t OnAlloc(uv_handle_t* handle, size_t suggested_size);
102 static void OnSend(uv_udp_send_t* req, int status);
103 static void OnRecv(uv_udp_t* handle,
106 struct sockaddr* addr,
113 UDPWrap::UDPWrap(Handle<Object> object): HandleWrap(object,
114 (uv_handle_t*)&handle_) {
115 int r = uv_udp_init(uv_default_loop(), &handle_);
116 assert(r == 0); // can't fail anyway
117 handle_.data = reinterpret_cast<void*>(this);
121 UDPWrap::~UDPWrap() {
125 void UDPWrap::Initialize(Handle<Object> target) {
126 HandleWrap::Initialize(target);
130 buffer_sym = NODE_PSYMBOL("buffer");
131 port_symbol = NODE_PSYMBOL("port");
132 address_symbol = NODE_PSYMBOL("address");
134 Local<FunctionTemplate> t = FunctionTemplate::New(New);
135 t->InstanceTemplate()->SetInternalFieldCount(1);
136 t->SetClassName(String::NewSymbol("UDP"));
138 NODE_SET_PROTOTYPE_METHOD(t, "bind", Bind);
139 NODE_SET_PROTOTYPE_METHOD(t, "send", Send);
140 NODE_SET_PROTOTYPE_METHOD(t, "bind6", Bind6);
141 NODE_SET_PROTOTYPE_METHOD(t, "send6", Send6);
142 NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
143 NODE_SET_PROTOTYPE_METHOD(t, "recvStart", RecvStart);
144 NODE_SET_PROTOTYPE_METHOD(t, "recvStop", RecvStop);
145 NODE_SET_PROTOTYPE_METHOD(t, "getsockname", GetSockName);
146 NODE_SET_PROTOTYPE_METHOD(t, "addMembership", AddMembership);
147 NODE_SET_PROTOTYPE_METHOD(t, "dropMembership", DropMembership);
148 NODE_SET_PROTOTYPE_METHOD(t, "setMulticastTTL", SetMulticastTTL);
149 NODE_SET_PROTOTYPE_METHOD(t, "setMulticastLoopback", SetMulticastLoopback);
150 NODE_SET_PROTOTYPE_METHOD(t, "setBroadcast", SetBroadcast);
151 NODE_SET_PROTOTYPE_METHOD(t, "setTTL", SetTTL);
153 target->Set(String::NewSymbol("UDP"),
154 Persistent<FunctionTemplate>::New(t)->GetFunction());
158 Handle<Value> UDPWrap::New(const Arguments& args) {
161 assert(args.IsConstructCall());
162 new UDPWrap(args.This());
164 return scope.Close(args.This());
167 Handle<Value> UDPWrap::DoBind(const Arguments& args, int family) {
173 // bind(ip, port, flags)
174 assert(args.Length() == 3);
176 String::Utf8Value address(args[0]);
177 const int port = args[1]->Uint32Value();
178 const int flags = args[2]->Uint32Value();
182 r = uv_udp_bind(&wrap->handle_, uv_ip4_addr(*address, port), flags);
185 r = uv_udp_bind6(&wrap->handle_, uv_ip6_addr(*address, port), flags);
188 assert(0 && "unexpected address family");
193 SetErrno(uv_last_error(uv_default_loop()));
195 return scope.Close(Integer::New(r));
199 Handle<Value> UDPWrap::Bind(const Arguments& args) {
200 return DoBind(args, AF_INET);
204 Handle<Value> UDPWrap::Bind6(const Arguments& args) {
205 return DoBind(args, AF_INET6);
209 #define X(name, fn) \
210 Handle<Value> UDPWrap::name(const Arguments& args) { \
213 assert(args.Length() == 1); \
214 int flag = args[0]->Int32Value(); \
215 int r = fn(&wrap->handle_, flag); \
216 if (r) SetErrno(uv_last_error(uv_default_loop())); \
217 return scope.Close(Integer::New(r)); \
220 X(SetTTL, uv_udp_set_ttl)
221 X(SetBroadcast, uv_udp_set_broadcast)
222 X(SetMulticastTTL, uv_udp_set_multicast_ttl)
223 X(SetMulticastLoopback, uv_udp_set_multicast_loop)
228 Handle<Value> UDPWrap::SetMembership(const Arguments& args,
229 uv_membership membership) {
233 assert(args.Length() == 2);
235 String::Utf8Value address(args[0]);
236 String::Utf8Value iface(args[1]);
238 const char* iface_cstr = *iface;
239 if (args[1]->IsUndefined() || args[1]->IsNull()) {
243 int r = uv_udp_set_membership(&wrap->handle_, *address, iface_cstr,
247 SetErrno(uv_last_error(uv_default_loop()));
249 return scope.Close(Integer::New(r));
253 Handle<Value> UDPWrap::AddMembership(const Arguments& args) {
254 return SetMembership(args, UV_JOIN_GROUP);
258 Handle<Value> UDPWrap::DropMembership(const Arguments& args) {
259 return SetMembership(args, UV_LEAVE_GROUP);
263 Handle<Value> UDPWrap::DoSend(const Arguments& args, int family) {
267 // send(buffer, offset, length, port, address)
268 assert(args.Length() == 5);
272 assert(Buffer::HasInstance(args[0]));
273 Local<Object> buffer_obj = args[0]->ToObject();
275 size_t offset = args[1]->Uint32Value();
276 size_t length = args[2]->Uint32Value();
277 assert(offset < Buffer::Length(buffer_obj));
278 assert(length <= Buffer::Length(buffer_obj) - offset);
280 SendWrap* req_wrap = new SendWrap();
281 req_wrap->object_->SetHiddenValue(buffer_sym, buffer_obj);
283 uv_buf_t buf = uv_buf_init(Buffer::Data(buffer_obj) + offset,
286 const unsigned short port = args[3]->Uint32Value();
287 String::Utf8Value address(args[4]);
291 r = uv_udp_send(&req_wrap->req_, &wrap->handle_, &buf, 1,
292 uv_ip4_addr(*address, port), OnSend);
295 r = uv_udp_send6(&req_wrap->req_, &wrap->handle_, &buf, 1,
296 uv_ip6_addr(*address, port), OnSend);
299 assert(0 && "unexpected address family");
303 req_wrap->Dispatched();
306 SetErrno(uv_last_error(uv_default_loop()));
311 return scope.Close(req_wrap->object_);
316 Handle<Value> UDPWrap::Send(const Arguments& args) {
317 return DoSend(args, AF_INET);
321 Handle<Value> UDPWrap::Send6(const Arguments& args) {
322 return DoSend(args, AF_INET6);
326 Handle<Value> UDPWrap::RecvStart(const Arguments& args) {
331 // UV_EALREADY means that the socket is already bound but that's okay
332 int r = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv);
333 if (r && uv_last_error(uv_default_loop()).code != UV_EALREADY) {
334 SetErrno(uv_last_error(uv_default_loop()));
342 Handle<Value> UDPWrap::RecvStop(const Arguments& args) {
347 int r = uv_udp_recv_stop(&wrap->handle_);
349 return scope.Close(Integer::New(r));
353 Handle<Value> UDPWrap::GetSockName(const Arguments& args) {
355 struct sockaddr_storage address;
359 int addrlen = sizeof(address);
360 int r = uv_udp_getsockname(&wrap->handle_,
361 reinterpret_cast<sockaddr*>(&address),
365 Local<Object> sockname = Object::New();
366 AddressToJS(sockname, reinterpret_cast<sockaddr*>(&address), addrlen);
367 return scope.Close(sockname);
370 SetErrno(uv_last_error(uv_default_loop()));
376 // TODO share with StreamWrap::AfterWrite() in stream_wrap.cc
377 void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
382 SendWrap* req_wrap = reinterpret_cast<SendWrap*>(req->data);
383 UDPWrap* wrap = reinterpret_cast<UDPWrap*>(req->handle->data);
385 assert(req_wrap->object_.IsEmpty() == false);
386 assert(wrap->object_.IsEmpty() == false);
389 SetErrno(uv_last_error(uv_default_loop()));
392 Local<Value> argv[4] = {
393 Integer::New(status),
394 Local<Value>::New(wrap->object_),
395 Local<Value>::New(req_wrap->object_),
396 req_wrap->object_->GetHiddenValue(buffer_sym),
399 MakeCallback(req_wrap->object_, "oncomplete", 4, argv);
404 uv_buf_t UDPWrap::OnAlloc(uv_handle_t* handle, size_t suggested_size) {
405 return uv_buf_init(new char[suggested_size], suggested_size);
409 void UDPWrap::OnRecv(uv_udp_t* handle,
412 struct sockaddr* addr,
421 UDPWrap* wrap = reinterpret_cast<UDPWrap*>(handle->data);
423 Local<Value> argv[4] = {
424 Local<Object>::New(wrap->object_),
426 Local<Value>::New(Null()),
427 Local<Value>::New(Null())
431 SetErrno(uv_last_error(uv_default_loop()));
434 Local<Object> rinfo = Object::New();
435 AddressToJS(rinfo, addr, sizeof *addr);
436 argv[2] = Local<Object>::New(
437 Buffer::New(buf.base, nread, NULL, NULL)->handle_);
442 MakeCallback(wrap->object_, "onmessage", ARRAY_SIZE(argv), argv);
446 void AddressToJS(Handle<Object> info,
447 const sockaddr* addr,
449 char ip[INET6_ADDRSTRLEN];
450 const sockaddr_in *a4;
451 const sockaddr_in6 *a6;
454 assert(addr != NULL);
457 info->Set(address_symbol, String::Empty());
461 switch (addr->sa_family) {
463 a6 = reinterpret_cast<const sockaddr_in6*>(addr);
464 uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip);
465 port = ntohs(a6->sin6_port);
466 info->Set(address_symbol, String::New(ip));
467 info->Set(port_symbol, Integer::New(port));
471 a4 = reinterpret_cast<const sockaddr_in*>(addr);
472 uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip);
473 port = ntohs(a4->sin_port);
474 info->Set(address_symbol, String::New(ip));
475 info->Set(port_symbol, Integer::New(port));
479 info->Set(address_symbol, String::Empty());
486 NODE_MODULE(node_udp_wrap, node::UDPWrap::Initialize)