Merge branch 'v0.8'
[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 #include "udp_wrap.h"
28
29 #include <stdlib.h>
30
31 #define SLAB_SIZE (1024 * 1024)
32
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)
36   extern "C" {
37 #   include <inet_net_pton.h>
38 #   include <inet_ntop.h>
39   }
40 # define uv_inet_pton ares_inet_pton
41 # define uv_inet_ntop ares_inet_ntop
42
43 #else // __POSIX__
44 # include <arpa/inet.h>
45 # define uv_inet_pton inet_pton
46 # define uv_inet_ntop inet_ntop
47 #endif
48
49 using namespace v8;
50
51 namespace node {
52
53 typedef ReqWrap<uv_udp_send_t> SendWrap;
54
55 // see tcp_wrap.cc
56 Local<Object> AddressToJS(const sockaddr* addr);
57
58 static Persistent<String> buffer_sym;
59 static Persistent<String> oncomplete_sym;
60 static Persistent<String> onmessage_sym;
61 static SlabAllocator* slab_allocator;
62
63
64 static void DeleteSlabAllocator(void*) {
65   delete slab_allocator;
66   slab_allocator = NULL;
67 }
68
69
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);
75 }
76
77
78 UDPWrap::~UDPWrap() {
79 }
80
81
82 void UDPWrap::Initialize(Handle<Object> target) {
83   HandleWrap::Initialize(target);
84
85   slab_allocator = new SlabAllocator(SLAB_SIZE);
86   AtExit(DeleteSlabAllocator, NULL);
87
88   HandleScope scope;
89
90   buffer_sym = NODE_PSYMBOL("buffer");
91   oncomplete_sym = NODE_PSYMBOL("oncomplete");
92   onmessage_sym = NODE_PSYMBOL("onmessage");
93
94   Local<FunctionTemplate> t = FunctionTemplate::New(New);
95   t->InstanceTemplate()->SetInternalFieldCount(1);
96   t->SetClassName(String::NewSymbol("UDP"));
97
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);
112
113   NODE_SET_PROTOTYPE_METHOD(t, "ref", HandleWrap::Ref);
114   NODE_SET_PROTOTYPE_METHOD(t, "unref", HandleWrap::Unref);
115
116   target->Set(String::NewSymbol("UDP"),
117               Persistent<FunctionTemplate>::New(t)->GetFunction());
118 }
119
120
121 Handle<Value> UDPWrap::New(const Arguments& args) {
122   HandleScope scope;
123
124   assert(args.IsConstructCall());
125   new UDPWrap(args.This());
126
127   return scope.Close(args.This());
128 }
129
130 Handle<Value> UDPWrap::DoBind(const Arguments& args, int family) {
131   HandleScope scope;
132   int r;
133
134   UNWRAP(UDPWrap)
135
136   // bind(ip, port, flags)
137   assert(args.Length() == 3);
138
139   String::Utf8Value address(args[0]);
140   const int port = args[1]->Uint32Value();
141   const int flags = args[2]->Uint32Value();
142
143   switch (family) {
144   case AF_INET:
145     r = uv_udp_bind(&wrap->handle_, uv_ip4_addr(*address, port), flags);
146     break;
147   case AF_INET6:
148     r = uv_udp_bind6(&wrap->handle_, uv_ip6_addr(*address, port), flags);
149     break;
150   default:
151     assert(0 && "unexpected address family");
152     abort();
153   }
154
155   if (r)
156     SetErrno(uv_last_error(uv_default_loop()));
157
158   return scope.Close(Integer::New(r));
159 }
160
161
162 Handle<Value> UDPWrap::Bind(const Arguments& args) {
163   return DoBind(args, AF_INET);
164 }
165
166
167 Handle<Value> UDPWrap::Bind6(const Arguments& args) {
168   return DoBind(args, AF_INET6);
169 }
170
171
172 #define X(name, fn)                                                           \
173   Handle<Value> UDPWrap::name(const Arguments& args) {                        \
174     HandleScope scope;                                                        \
175     UNWRAP(UDPWrap)                                                                    \
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));                                      \
181   }
182
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)
187
188 #undef X
189
190
191 Handle<Value> UDPWrap::SetMembership(const Arguments& args,
192                                      uv_membership membership) {
193   HandleScope scope;
194   UNWRAP(UDPWrap)
195
196   assert(args.Length() == 2);
197
198   String::Utf8Value address(args[0]);
199   String::Utf8Value iface(args[1]);
200
201   const char* iface_cstr = *iface;
202   if (args[1]->IsUndefined() || args[1]->IsNull()) {
203       iface_cstr = NULL;
204   }
205
206   int r = uv_udp_set_membership(&wrap->handle_, *address, iface_cstr,
207                                 membership);
208
209   if (r)
210     SetErrno(uv_last_error(uv_default_loop()));
211
212   return scope.Close(Integer::New(r));
213 }
214
215
216 Handle<Value> UDPWrap::AddMembership(const Arguments& args) {
217   return SetMembership(args, UV_JOIN_GROUP);
218 }
219
220
221 Handle<Value> UDPWrap::DropMembership(const Arguments& args) {
222   return SetMembership(args, UV_LEAVE_GROUP);
223 }
224
225
226 Handle<Value> UDPWrap::DoSend(const Arguments& args, int family) {
227   HandleScope scope;
228   int r;
229
230   // send(buffer, offset, length, port, address)
231   assert(args.Length() == 5);
232
233   UNWRAP(UDPWrap)
234
235   assert(Buffer::HasInstance(args[0]));
236   Local<Object> buffer_obj = args[0]->ToObject();
237
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);
242
243   SendWrap* req_wrap = new SendWrap();
244   req_wrap->object_->SetHiddenValue(buffer_sym, buffer_obj);
245
246   uv_buf_t buf = uv_buf_init(Buffer::Data(buffer_obj) + offset,
247                              length);
248
249   const unsigned short port = args[3]->Uint32Value();
250   String::Utf8Value address(args[4]);
251
252   switch (family) {
253   case AF_INET:
254     r = uv_udp_send(&req_wrap->req_, &wrap->handle_, &buf, 1,
255                     uv_ip4_addr(*address, port), OnSend);
256     break;
257   case AF_INET6:
258     r = uv_udp_send6(&req_wrap->req_, &wrap->handle_, &buf, 1,
259                      uv_ip6_addr(*address, port), OnSend);
260     break;
261   default:
262     assert(0 && "unexpected address family");
263     abort();
264   }
265
266   req_wrap->Dispatched();
267
268   if (r) {
269     SetErrno(uv_last_error(uv_default_loop()));
270     delete req_wrap;
271     return Null();
272   }
273   else {
274     return scope.Close(req_wrap->object_);
275   }
276 }
277
278
279 Handle<Value> UDPWrap::Send(const Arguments& args) {
280   return DoSend(args, AF_INET);
281 }
282
283
284 Handle<Value> UDPWrap::Send6(const Arguments& args) {
285   return DoSend(args, AF_INET6);
286 }
287
288
289 Handle<Value> UDPWrap::RecvStart(const Arguments& args) {
290   HandleScope scope;
291
292   UNWRAP(UDPWrap)
293
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()));
298     return False();
299   }
300
301   return True();
302 }
303
304
305 Handle<Value> UDPWrap::RecvStop(const Arguments& args) {
306   HandleScope scope;
307
308   UNWRAP(UDPWrap)
309
310   int r = uv_udp_recv_stop(&wrap->handle_);
311
312   return scope.Close(Integer::New(r));
313 }
314
315
316 Handle<Value> UDPWrap::GetSockName(const Arguments& args) {
317   HandleScope scope;
318   struct sockaddr_storage address;
319
320   UNWRAP(UDPWrap)
321
322   int addrlen = sizeof(address);
323   int r = uv_udp_getsockname(&wrap->handle_,
324                              reinterpret_cast<sockaddr*>(&address),
325                              &addrlen);
326
327   if (r) {
328     SetErrno(uv_last_error(uv_default_loop()));
329     return Null();
330   }
331
332   const sockaddr* addr = reinterpret_cast<const sockaddr*>(&address);
333   return scope.Close(AddressToJS(addr));
334 }
335
336
337 // TODO share with StreamWrap::AfterWrite() in stream_wrap.cc
338 void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
339   HandleScope scope;
340
341   assert(req != NULL);
342
343   SendWrap* req_wrap = reinterpret_cast<SendWrap*>(req->data);
344   UDPWrap* wrap = reinterpret_cast<UDPWrap*>(req->handle->data);
345
346   assert(req_wrap->object_.IsEmpty() == false);
347   assert(wrap->object_.IsEmpty() == false);
348
349   if (status) {
350     SetErrno(uv_last_error(uv_default_loop()));
351   }
352
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),
358   };
359
360   MakeCallback(req_wrap->object_, oncomplete_sym, ARRAY_SIZE(argv), argv);
361   delete req_wrap;
362 }
363
364
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);
369 }
370
371
372 void UDPWrap::OnRecv(uv_udp_t* handle,
373                      ssize_t nread,
374                      uv_buf_t buf,
375                      struct sockaddr* addr,
376                      unsigned flags) {
377   HandleScope scope;
378
379   UDPWrap* wrap = reinterpret_cast<UDPWrap*>(handle->data);
380   Local<Object> slab = slab_allocator->Shrink(wrap->object_,
381                                               buf.base,
382                                               nread < 0 ? 0 : nread);
383   if (nread == 0) return;
384
385   if (nread < 0) {
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);
389     return;
390   }
391
392   Local<Value> argv[] = {
393     Local<Object>::New(wrap->object_),
394     slab,
395     Integer::NewFromUnsigned(buf.base - Buffer::Data(slab)),
396     Integer::NewFromUnsigned(nread),
397     AddressToJS(addr)
398   };
399   MakeCallback(wrap->object_, onmessage_sym, ARRAY_SIZE(argv), argv);
400 }
401
402
403 UDPWrap* UDPWrap::Unwrap(Local<Object> obj) {
404   assert(!obj.IsEmpty());
405   assert(obj->InternalFieldCount() > 0);
406   return static_cast<UDPWrap*>(obj->GetPointerFromInternalField(0));
407 }
408
409
410 uv_udp_t* UDPWrap::UVHandle() {
411   return &handle_;
412 }
413
414
415 } // namespace node
416
417 NODE_MODULE(node_udp_wrap, node::UDPWrap::Initialize)