6cb2bb65bb3e85f8700c801723a04484ca068598
[platform/upstream/nodejs.git] / src / udp_wrap.cc
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
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:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
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.
21
22 #include "node.h"
23 #include "node_buffer.h"
24
25 #include "req_wrap.h"
26 #include "handle_wrap.h"
27
28 #include <stdlib.h>
29
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)
33   extern "C" {
34 #   include <inet_net_pton.h>
35 #   include <inet_ntop.h>
36   }
37 # define uv_inet_pton ares_inet_pton
38 # define uv_inet_ntop ares_inet_ntop
39
40 #else // __POSIX__
41 # include <arpa/inet.h>
42 # define uv_inet_pton inet_pton
43 # define uv_inet_ntop inet_ntop
44 #endif
45
46 using namespace v8;
47
48 namespace node {
49
50 #define UNWRAP                                                              \
51   assert(!args.Holder().IsEmpty());                                         \
52   assert(args.Holder()->InternalFieldCount() > 0);                          \
53   UDPWrap* wrap =                                                           \
54       static_cast<UDPWrap*>(args.Holder()->GetPointerFromInternalField(0)); \
55   if (!wrap) {                                                              \
56     uv_err_t err;                                                           \
57     err.code = UV_EBADF;                                                    \
58     SetErrno(err);                                                          \
59     return scope.Close(Integer::New(-1));                                   \
60   }
61
62 // TODO share with tcp_wrap.cc
63 Persistent<String> address_symbol;
64 Persistent<String> port_symbol;
65 Persistent<String> buffer_sym;
66
67 void AddressToJS(Handle<Object> info,
68                  const sockaddr* addr,
69                  int addrlen);
70
71 typedef ReqWrap<uv_udp_send_t> SendWrap;
72
73
74 class UDPWrap: public HandleWrap {
75 public:
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);
91
92 private:
93   UDPWrap(Handle<Object> object);
94   virtual ~UDPWrap();
95
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);
100
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,
104                      ssize_t nread,
105                      uv_buf_t buf,
106                      struct sockaddr* addr,
107                      unsigned flags);
108
109   uv_udp_t handle_;
110 };
111
112
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);
118 }
119
120
121 UDPWrap::~UDPWrap() {
122 }
123
124
125 void UDPWrap::Initialize(Handle<Object> target) {
126   HandleWrap::Initialize(target);
127
128   HandleScope scope;
129
130   buffer_sym = NODE_PSYMBOL("buffer");
131   port_symbol = NODE_PSYMBOL("port");
132   address_symbol = NODE_PSYMBOL("address");
133
134   Local<FunctionTemplate> t = FunctionTemplate::New(New);
135   t->InstanceTemplate()->SetInternalFieldCount(1);
136   t->SetClassName(String::NewSymbol("UDP"));
137
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);
152
153   target->Set(String::NewSymbol("UDP"),
154               Persistent<FunctionTemplate>::New(t)->GetFunction());
155 }
156
157
158 Handle<Value> UDPWrap::New(const Arguments& args) {
159   HandleScope scope;
160
161   assert(args.IsConstructCall());
162   new UDPWrap(args.This());
163
164   return scope.Close(args.This());
165 }
166
167 Handle<Value> UDPWrap::DoBind(const Arguments& args, int family) {
168   HandleScope scope;
169   int r;
170
171   UNWRAP
172
173   // bind(ip, port, flags)
174   assert(args.Length() == 3);
175
176   String::Utf8Value address(args[0]);
177   const int port = args[1]->Uint32Value();
178   const int flags = args[2]->Uint32Value();
179
180   switch (family) {
181   case AF_INET:
182     r = uv_udp_bind(&wrap->handle_, uv_ip4_addr(*address, port), flags);
183     break;
184   case AF_INET6:
185     r = uv_udp_bind6(&wrap->handle_, uv_ip6_addr(*address, port), flags);
186     break;
187   default:
188     assert(0 && "unexpected address family");
189     abort();
190   }
191
192   if (r)
193     SetErrno(uv_last_error(uv_default_loop()));
194
195   return scope.Close(Integer::New(r));
196 }
197
198
199 Handle<Value> UDPWrap::Bind(const Arguments& args) {
200   return DoBind(args, AF_INET);
201 }
202
203
204 Handle<Value> UDPWrap::Bind6(const Arguments& args) {
205   return DoBind(args, AF_INET6);
206 }
207
208
209 #define X(name, fn)                                                           \
210   Handle<Value> UDPWrap::name(const Arguments& args) {                        \
211     HandleScope scope;                                                        \
212     UNWRAP                                                                    \
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));                                      \
218   }
219
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)
224
225 #undef X
226
227
228 Handle<Value> UDPWrap::SetMembership(const Arguments& args,
229                                      uv_membership membership) {
230   HandleScope scope;
231   UNWRAP
232
233   assert(args.Length() == 2);
234
235   String::Utf8Value address(args[0]);
236   String::Utf8Value iface(args[1]);
237
238   const char* iface_cstr = *iface;
239   if (args[1]->IsUndefined() || args[1]->IsNull()) {
240       iface_cstr = NULL;
241   }
242
243   int r = uv_udp_set_membership(&wrap->handle_, *address, iface_cstr,
244                                 membership);
245
246   if (r)
247     SetErrno(uv_last_error(uv_default_loop()));
248
249   return scope.Close(Integer::New(r));
250 }
251
252
253 Handle<Value> UDPWrap::AddMembership(const Arguments& args) {
254   return SetMembership(args, UV_JOIN_GROUP);
255 }
256
257
258 Handle<Value> UDPWrap::DropMembership(const Arguments& args) {
259   return SetMembership(args, UV_LEAVE_GROUP);
260 }
261
262
263 Handle<Value> UDPWrap::DoSend(const Arguments& args, int family) {
264   HandleScope scope;
265   int r;
266
267   // send(buffer, offset, length, port, address)
268   assert(args.Length() == 5);
269
270   UNWRAP
271
272   assert(Buffer::HasInstance(args[0]));
273   Local<Object> buffer_obj = args[0]->ToObject();
274
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);
279
280   SendWrap* req_wrap = new SendWrap();
281   req_wrap->object_->SetHiddenValue(buffer_sym, buffer_obj);
282
283   uv_buf_t buf = uv_buf_init(Buffer::Data(buffer_obj) + offset,
284                              length);
285
286   const unsigned short port = args[3]->Uint32Value();
287   String::Utf8Value address(args[4]);
288
289   switch (family) {
290   case AF_INET:
291     r = uv_udp_send(&req_wrap->req_, &wrap->handle_, &buf, 1,
292                     uv_ip4_addr(*address, port), OnSend);
293     break;
294   case AF_INET6:
295     r = uv_udp_send6(&req_wrap->req_, &wrap->handle_, &buf, 1,
296                      uv_ip6_addr(*address, port), OnSend);
297     break;
298   default:
299     assert(0 && "unexpected address family");
300     abort();
301   }
302
303   req_wrap->Dispatched();
304
305   if (r) {
306     SetErrno(uv_last_error(uv_default_loop()));
307     delete req_wrap;
308     return Null();
309   }
310   else {
311     return scope.Close(req_wrap->object_);
312   }
313 }
314
315
316 Handle<Value> UDPWrap::Send(const Arguments& args) {
317   return DoSend(args, AF_INET);
318 }
319
320
321 Handle<Value> UDPWrap::Send6(const Arguments& args) {
322   return DoSend(args, AF_INET6);
323 }
324
325
326 Handle<Value> UDPWrap::RecvStart(const Arguments& args) {
327   HandleScope scope;
328
329   UNWRAP
330
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()));
335     return False();
336   }
337
338   return True();
339 }
340
341
342 Handle<Value> UDPWrap::RecvStop(const Arguments& args) {
343   HandleScope scope;
344
345   UNWRAP
346
347   int r = uv_udp_recv_stop(&wrap->handle_);
348
349   return scope.Close(Integer::New(r));
350 }
351
352
353 Handle<Value> UDPWrap::GetSockName(const Arguments& args) {
354   HandleScope scope;
355   struct sockaddr_storage address;
356
357   UNWRAP
358
359   int addrlen = sizeof(address);
360   int r = uv_udp_getsockname(&wrap->handle_,
361                              reinterpret_cast<sockaddr*>(&address),
362                              &addrlen);
363
364   if (r == 0) {
365     Local<Object> sockname = Object::New();
366     AddressToJS(sockname, reinterpret_cast<sockaddr*>(&address), addrlen);
367     return scope.Close(sockname);
368   }
369   else {
370     SetErrno(uv_last_error(uv_default_loop()));
371     return Null();
372   }
373 }
374
375
376 // TODO share with StreamWrap::AfterWrite() in stream_wrap.cc
377 void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
378   HandleScope scope;
379
380   assert(req != NULL);
381
382   SendWrap* req_wrap = reinterpret_cast<SendWrap*>(req->data);
383   UDPWrap* wrap = reinterpret_cast<UDPWrap*>(req->handle->data);
384
385   assert(req_wrap->object_.IsEmpty() == false);
386   assert(wrap->object_.IsEmpty() == false);
387
388   if (status) {
389     SetErrno(uv_last_error(uv_default_loop()));
390   }
391
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),
397   };
398
399   MakeCallback(req_wrap->object_, "oncomplete", 4, argv);
400   delete req_wrap;
401 }
402
403
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);
406 }
407
408
409 void UDPWrap::OnRecv(uv_udp_t* handle,
410                      ssize_t nread,
411                      uv_buf_t buf,
412                      struct sockaddr* addr,
413                      unsigned flags) {
414   HandleScope scope;
415
416   if (nread == 0) {
417     free(buf.base);
418     return;
419   }
420
421   UDPWrap* wrap = reinterpret_cast<UDPWrap*>(handle->data);
422
423   Local<Value> argv[4] = {
424     Local<Object>::New(wrap->object_),
425     Integer::New(nread),
426     Local<Value>::New(Null()),
427     Local<Value>::New(Null())
428   };
429
430   if (nread == -1) {
431     SetErrno(uv_last_error(uv_default_loop()));
432   }
433   else {
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_);
438     argv[3] = rinfo;
439   }
440   free(buf.base);
441
442   MakeCallback(wrap->object_, "onmessage", ARRAY_SIZE(argv), argv);
443 }
444
445
446 void AddressToJS(Handle<Object> info,
447                  const sockaddr* addr,
448                  int addrlen) {
449   char ip[INET6_ADDRSTRLEN];
450   const sockaddr_in *a4;
451   const sockaddr_in6 *a6;
452   int port;
453
454   assert(addr != NULL);
455
456   if (addrlen == 0) {
457     info->Set(address_symbol, String::Empty());
458     return;
459   }
460
461   switch (addr->sa_family) {
462   case AF_INET6:
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));
468     break;
469
470   case AF_INET:
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));
476     break;
477
478   default:
479     info->Set(address_symbol, String::Empty());
480   }
481 }
482
483
484 } // namespace node
485
486 NODE_MODULE(node_udp_wrap, node::UDPWrap::Initialize)