Merge branch 'v0.6'
[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 #include "slab_allocator.h"
25 #include "req_wrap.h"
26 #include "handle_wrap.h"
27
28 #include <stdlib.h>
29
30 #define SLAB_SIZE (1024 * 1024)
31
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)
35   extern "C" {
36 #   include <inet_net_pton.h>
37 #   include <inet_ntop.h>
38   }
39 # define uv_inet_pton ares_inet_pton
40 # define uv_inet_ntop ares_inet_ntop
41
42 #else // __POSIX__
43 # include <arpa/inet.h>
44 # define uv_inet_pton inet_pton
45 # define uv_inet_ntop inet_ntop
46 #endif
47
48 using namespace v8;
49
50 namespace node {
51
52 #define UNWRAP                                                              \
53   assert(!args.Holder().IsEmpty());                                         \
54   assert(args.Holder()->InternalFieldCount() > 0);                          \
55   UDPWrap* wrap =                                                           \
56       static_cast<UDPWrap*>(args.Holder()->GetPointerFromInternalField(0)); \
57   if (!wrap) {                                                              \
58     uv_err_t err;                                                           \
59     err.code = UV_EBADF;                                                    \
60     SetErrno(err);                                                          \
61     return scope.Close(Integer::New(-1));                                   \
62   }
63
64 typedef ReqWrap<uv_udp_send_t> SendWrap;
65
66 Local<Object> AddressToJS(const sockaddr* addr);
67
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);
74
75
76 class UDPWrap: public HandleWrap {
77 public:
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);
93
94 private:
95   UDPWrap(Handle<Object> object);
96   virtual ~UDPWrap();
97
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);
102
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,
106                      ssize_t nread,
107                      uv_buf_t buf,
108                      struct sockaddr* addr,
109                      unsigned flags);
110
111   uv_udp_t handle_;
112 };
113
114
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);
120 }
121
122
123 UDPWrap::~UDPWrap() {
124 }
125
126
127 void UDPWrap::Initialize(Handle<Object> target) {
128   HandleWrap::Initialize(target);
129
130   HandleScope scope;
131
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");
137
138   Local<FunctionTemplate> t = FunctionTemplate::New(New);
139   t->InstanceTemplate()->SetInternalFieldCount(1);
140   t->SetClassName(String::NewSymbol("UDP"));
141
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);
156
157   target->Set(String::NewSymbol("UDP"),
158               Persistent<FunctionTemplate>::New(t)->GetFunction());
159 }
160
161
162 Handle<Value> UDPWrap::New(const Arguments& args) {
163   HandleScope scope;
164
165   assert(args.IsConstructCall());
166   new UDPWrap(args.This());
167
168   return scope.Close(args.This());
169 }
170
171 Handle<Value> UDPWrap::DoBind(const Arguments& args, int family) {
172   HandleScope scope;
173   int r;
174
175   UNWRAP
176
177   // bind(ip, port, flags)
178   assert(args.Length() == 3);
179
180   String::Utf8Value address(args[0]);
181   const int port = args[1]->Uint32Value();
182   const int flags = args[2]->Uint32Value();
183
184   switch (family) {
185   case AF_INET:
186     r = uv_udp_bind(&wrap->handle_, uv_ip4_addr(*address, port), flags);
187     break;
188   case AF_INET6:
189     r = uv_udp_bind6(&wrap->handle_, uv_ip6_addr(*address, port), flags);
190     break;
191   default:
192     assert(0 && "unexpected address family");
193     abort();
194   }
195
196   if (r)
197     SetErrno(uv_last_error(uv_default_loop()));
198
199   return scope.Close(Integer::New(r));
200 }
201
202
203 Handle<Value> UDPWrap::Bind(const Arguments& args) {
204   return DoBind(args, AF_INET);
205 }
206
207
208 Handle<Value> UDPWrap::Bind6(const Arguments& args) {
209   return DoBind(args, AF_INET6);
210 }
211
212
213 #define X(name, fn)                                                           \
214   Handle<Value> UDPWrap::name(const Arguments& args) {                        \
215     HandleScope scope;                                                        \
216     UNWRAP                                                                    \
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));                                      \
222   }
223
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)
228
229 #undef X
230
231
232 Handle<Value> UDPWrap::SetMembership(const Arguments& args,
233                                      uv_membership membership) {
234   HandleScope scope;
235   UNWRAP
236
237   assert(args.Length() == 2);
238
239   String::Utf8Value address(args[0]);
240   String::Utf8Value iface(args[1]);
241
242   const char* iface_cstr = *iface;
243   if (args[1]->IsUndefined() || args[1]->IsNull()) {
244       iface_cstr = NULL;
245   }
246
247   int r = uv_udp_set_membership(&wrap->handle_, *address, iface_cstr,
248                                 membership);
249
250   if (r)
251     SetErrno(uv_last_error(uv_default_loop()));
252
253   return scope.Close(Integer::New(r));
254 }
255
256
257 Handle<Value> UDPWrap::AddMembership(const Arguments& args) {
258   return SetMembership(args, UV_JOIN_GROUP);
259 }
260
261
262 Handle<Value> UDPWrap::DropMembership(const Arguments& args) {
263   return SetMembership(args, UV_LEAVE_GROUP);
264 }
265
266
267 Handle<Value> UDPWrap::DoSend(const Arguments& args, int family) {
268   HandleScope scope;
269   int r;
270
271   // send(buffer, offset, length, port, address)
272   assert(args.Length() == 5);
273
274   UNWRAP
275
276   assert(Buffer::HasInstance(args[0]));
277   Local<Object> buffer_obj = args[0]->ToObject();
278
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);
283
284   SendWrap* req_wrap = new SendWrap();
285   req_wrap->object_->SetHiddenValue(buffer_sym, buffer_obj);
286
287   uv_buf_t buf = uv_buf_init(Buffer::Data(buffer_obj) + offset,
288                              length);
289
290   const unsigned short port = args[3]->Uint32Value();
291   String::Utf8Value address(args[4]);
292
293   switch (family) {
294   case AF_INET:
295     r = uv_udp_send(&req_wrap->req_, &wrap->handle_, &buf, 1,
296                     uv_ip4_addr(*address, port), OnSend);
297     break;
298   case AF_INET6:
299     r = uv_udp_send6(&req_wrap->req_, &wrap->handle_, &buf, 1,
300                      uv_ip6_addr(*address, port), OnSend);
301     break;
302   default:
303     assert(0 && "unexpected address family");
304     abort();
305   }
306
307   req_wrap->Dispatched();
308
309   if (r) {
310     SetErrno(uv_last_error(uv_default_loop()));
311     delete req_wrap;
312     return Null();
313   }
314   else {
315     return scope.Close(req_wrap->object_);
316   }
317 }
318
319
320 Handle<Value> UDPWrap::Send(const Arguments& args) {
321   return DoSend(args, AF_INET);
322 }
323
324
325 Handle<Value> UDPWrap::Send6(const Arguments& args) {
326   return DoSend(args, AF_INET6);
327 }
328
329
330 Handle<Value> UDPWrap::RecvStart(const Arguments& args) {
331   HandleScope scope;
332
333   UNWRAP
334
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()));
339     return False();
340   }
341
342   return True();
343 }
344
345
346 Handle<Value> UDPWrap::RecvStop(const Arguments& args) {
347   HandleScope scope;
348
349   UNWRAP
350
351   int r = uv_udp_recv_stop(&wrap->handle_);
352
353   return scope.Close(Integer::New(r));
354 }
355
356
357 Handle<Value> UDPWrap::GetSockName(const Arguments& args) {
358   HandleScope scope;
359   struct sockaddr_storage address;
360
361   UNWRAP
362
363   int addrlen = sizeof(address);
364   int r = uv_udp_getsockname(&wrap->handle_,
365                              reinterpret_cast<sockaddr*>(&address),
366                              &addrlen);
367
368   if (r) {
369     SetErrno(uv_last_error(uv_default_loop()));
370     return Null();
371   }
372
373   const sockaddr* addr = reinterpret_cast<const sockaddr*>(&address);
374   return scope.Close(AddressToJS(addr));
375 }
376
377
378 // TODO share with StreamWrap::AfterWrite() in stream_wrap.cc
379 void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
380   HandleScope scope;
381
382   assert(req != NULL);
383
384   SendWrap* req_wrap = reinterpret_cast<SendWrap*>(req->data);
385   UDPWrap* wrap = reinterpret_cast<UDPWrap*>(req->handle->data);
386
387   assert(req_wrap->object_.IsEmpty() == false);
388   assert(wrap->object_.IsEmpty() == false);
389
390   if (status) {
391     SetErrno(uv_last_error(uv_default_loop()));
392   }
393
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),
399   };
400
401   MakeCallback(req_wrap->object_, oncomplete_sym, ARRAY_SIZE(argv), argv);
402   delete req_wrap;
403 }
404
405
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);
410 }
411
412
413 void UDPWrap::OnRecv(uv_udp_t* handle,
414                      ssize_t nread,
415                      uv_buf_t buf,
416                      struct sockaddr* addr,
417                      unsigned flags) {
418   HandleScope scope;
419
420   UDPWrap* wrap = reinterpret_cast<UDPWrap*>(handle->data);
421   Local<Object> slab = slab_allocator.Shrink(wrap->object_,
422                                              buf.base,
423                                              nread < 0 ? 0 : nread);
424   if (nread == 0) return;
425
426   if (nread < 0) {
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);
430     return;
431   }
432
433   Local<Value> argv[] = {
434     Local<Object>::New(wrap->object_),
435     slab,
436     Integer::NewFromUnsigned(buf.base - Buffer::Data(slab)),
437     Integer::NewFromUnsigned(nread),
438     AddressToJS(addr)
439   };
440   MakeCallback(wrap->object_, onmessage_sym, ARRAY_SIZE(argv), argv);
441 }
442
443
444 Local<Object> AddressToJS(const sockaddr* addr) {
445   HandleScope scope;
446   char ip[INET6_ADDRSTRLEN];
447   const sockaddr_in *a4;
448   const sockaddr_in6 *a6;
449   int port;
450
451   Local<Object> info = Object::New();
452
453   switch (addr->sa_family) {
454   case AF_INET6:
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));
460     break;
461
462   case AF_INET:
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));
468     break;
469
470   default:
471     info->Set(address_symbol, String::Empty());
472   }
473
474   return scope.Close(info);
475 }
476
477
478 } // namespace node
479
480 NODE_MODULE(node_udp_wrap, node::UDPWrap::Initialize)