src: add multi-context support
[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 "udp_wrap.h"
23 #include "env.h"
24 #include "env-inl.h"
25 #include "node_buffer.h"
26 #include "handle_wrap.h"
27 #include "req_wrap.h"
28
29 #include <stdlib.h>
30
31
32 namespace node {
33
34 using v8::Context;
35 using v8::Function;
36 using v8::FunctionCallbackInfo;
37 using v8::FunctionTemplate;
38 using v8::Handle;
39 using v8::HandleScope;
40 using v8::Integer;
41 using v8::Local;
42 using v8::Object;
43 using v8::PropertyAttribute;
44 using v8::PropertyCallbackInfo;
45 using v8::String;
46 using v8::Uint32;
47 using v8::Undefined;
48 using v8::Value;
49
50
51 class SendWrap : public ReqWrap<uv_udp_send_t> {
52  public:
53   SendWrap(Environment* env, Local<Object> req_wrap_obj, bool have_callback);
54   inline bool have_callback() const;
55  private:
56   const bool have_callback_;
57 };
58
59
60 SendWrap::SendWrap(Environment* env,
61                    Local<Object> req_wrap_obj,
62                    bool have_callback)
63     : ReqWrap<uv_udp_send_t>(env, req_wrap_obj)
64     , have_callback_(have_callback) {
65 }
66
67
68 inline bool SendWrap::have_callback() const {
69   return have_callback_;
70 }
71
72
73 UDPWrap::UDPWrap(Environment* env, Handle<Object> object)
74     : HandleWrap(env, object, reinterpret_cast<uv_handle_t*>(&handle_)) {
75   int r = uv_udp_init(env->event_loop(), &handle_);
76   assert(r == 0);  // can't fail anyway
77 }
78
79
80 UDPWrap::~UDPWrap() {
81 }
82
83
84 void UDPWrap::Initialize(Handle<Object> target,
85                          Handle<Value> unused,
86                          Handle<Context> context) {
87   Environment* env = Environment::GetCurrent(context);
88
89   Local<FunctionTemplate> t = FunctionTemplate::New(New);
90   t->InstanceTemplate()->SetInternalFieldCount(1);
91   t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "UDP"));
92
93   enum PropertyAttribute attributes =
94       static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
95   t->InstanceTemplate()->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "fd"),
96                                      UDPWrap::GetFD,
97                                      NULL,
98                                      Handle<Value>(),
99                                      v8::DEFAULT,
100                                      attributes);
101
102   NODE_SET_PROTOTYPE_METHOD(t, "bind", Bind);
103   NODE_SET_PROTOTYPE_METHOD(t, "send", Send);
104   NODE_SET_PROTOTYPE_METHOD(t, "bind6", Bind6);
105   NODE_SET_PROTOTYPE_METHOD(t, "send6", Send6);
106   NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
107   NODE_SET_PROTOTYPE_METHOD(t, "recvStart", RecvStart);
108   NODE_SET_PROTOTYPE_METHOD(t, "recvStop", RecvStop);
109   NODE_SET_PROTOTYPE_METHOD(t, "getsockname", GetSockName);
110   NODE_SET_PROTOTYPE_METHOD(t, "addMembership", AddMembership);
111   NODE_SET_PROTOTYPE_METHOD(t, "dropMembership", DropMembership);
112   NODE_SET_PROTOTYPE_METHOD(t, "setMulticastTTL", SetMulticastTTL);
113   NODE_SET_PROTOTYPE_METHOD(t, "setMulticastLoopback", SetMulticastLoopback);
114   NODE_SET_PROTOTYPE_METHOD(t, "setBroadcast", SetBroadcast);
115   NODE_SET_PROTOTYPE_METHOD(t, "setTTL", SetTTL);
116
117   NODE_SET_PROTOTYPE_METHOD(t, "ref", HandleWrap::Ref);
118   NODE_SET_PROTOTYPE_METHOD(t, "unref", HandleWrap::Unref);
119
120   target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "UDP"), t->GetFunction());
121   env->set_udp_constructor_function(t->GetFunction());
122 }
123
124
125 void UDPWrap::New(const FunctionCallbackInfo<Value>& args) {
126   assert(args.IsConstructCall());
127   Environment* env = Environment::GetCurrent(args.GetIsolate());
128   HandleScope handle_scope(args.GetIsolate());
129   new UDPWrap(env, args.This());
130 }
131
132
133 void UDPWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) {
134 #if !defined(_WIN32)
135   HandleScope scope(node_isolate);
136   UDPWrap* wrap;
137   NODE_UNWRAP(args.This(), UDPWrap, wrap);
138   int fd = (wrap == NULL) ? -1 : wrap->handle_.io_watcher.fd;
139   args.GetReturnValue().Set(fd);
140 #endif
141 }
142
143
144 void UDPWrap::DoBind(const FunctionCallbackInfo<Value>& args, int family) {
145   HandleScope scope(node_isolate);
146
147   UDPWrap* wrap;
148   NODE_UNWRAP(args.This(), UDPWrap, wrap);
149
150   // bind(ip, port, flags)
151   assert(args.Length() == 3);
152
153   String::Utf8Value address(args[0]);
154   const int port = args[1]->Uint32Value();
155   const int flags = args[2]->Uint32Value();
156   char addr[sizeof(sockaddr_in6)];
157   int err;
158
159   switch (family) {
160   case AF_INET:
161     err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
162     break;
163   case AF_INET6:
164     err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
165     break;
166   default:
167     assert(0 && "unexpected address family");
168     abort();
169   }
170
171   if (err == 0) {
172     err = uv_udp_bind(&wrap->handle_,
173                       reinterpret_cast<const sockaddr*>(&addr),
174                       flags);
175   }
176
177   args.GetReturnValue().Set(err);
178 }
179
180
181 void UDPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
182   DoBind(args, AF_INET);
183 }
184
185
186 void UDPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
187   DoBind(args, AF_INET6);
188 }
189
190
191 #define X(name, fn)                                                           \
192   void UDPWrap::name(const FunctionCallbackInfo<Value>& args) {               \
193     HandleScope scope(node_isolate);                                          \
194     UDPWrap* wrap;                                                            \
195     NODE_UNWRAP(args.This(), UDPWrap, wrap);                                  \
196     assert(args.Length() == 1);                                               \
197     int flag = args[0]->Int32Value();                                         \
198     int err = fn(&wrap->handle_, flag);                                       \
199     args.GetReturnValue().Set(err);                                           \
200   }
201
202 X(SetTTL, uv_udp_set_ttl)
203 X(SetBroadcast, uv_udp_set_broadcast)
204 X(SetMulticastTTL, uv_udp_set_multicast_ttl)
205 X(SetMulticastLoopback, uv_udp_set_multicast_loop)
206
207 #undef X
208
209
210 void UDPWrap::SetMembership(const FunctionCallbackInfo<Value>& args,
211                             uv_membership membership) {
212   HandleScope scope(node_isolate);
213   UDPWrap* wrap;
214   NODE_UNWRAP(args.This(), UDPWrap, wrap);
215
216   assert(args.Length() == 2);
217
218   String::Utf8Value address(args[0]);
219   String::Utf8Value iface(args[1]);
220
221   const char* iface_cstr = *iface;
222   if (args[1]->IsUndefined() || args[1]->IsNull()) {
223       iface_cstr = NULL;
224   }
225
226   int err = uv_udp_set_membership(&wrap->handle_,
227                                   *address,
228                                   iface_cstr,
229                                   membership);
230   args.GetReturnValue().Set(err);
231 }
232
233
234 void UDPWrap::AddMembership(const FunctionCallbackInfo<Value>& args) {
235   SetMembership(args, UV_JOIN_GROUP);
236 }
237
238
239 void UDPWrap::DropMembership(const FunctionCallbackInfo<Value>& args) {
240   SetMembership(args, UV_LEAVE_GROUP);
241 }
242
243
244 void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {
245   Environment* env = Environment::GetCurrent(args.GetIsolate());
246   HandleScope handle_scope(args.GetIsolate());
247
248   UDPWrap* wrap;
249   NODE_UNWRAP(args.This(), UDPWrap, wrap);
250
251   // send(req, buffer, offset, length, port, address)
252   assert(args[0]->IsObject());
253   assert(Buffer::HasInstance(args[1]));
254   assert(args[2]->IsUint32());
255   assert(args[3]->IsUint32());
256   assert(args[4]->IsUint32());
257   assert(args[5]->IsString());
258   assert(args[6]->IsBoolean());
259
260   Local<Object> req_wrap_obj = args[0].As<Object>();
261   Local<Object> buffer_obj = args[1].As<Object>();
262   size_t offset = args[2]->Uint32Value();
263   size_t length = args[3]->Uint32Value();
264   const unsigned short port = args[4]->Uint32Value();
265   String::Utf8Value address(args[5]);
266   const bool have_callback = args[6]->IsTrue();
267
268   assert(offset < Buffer::Length(buffer_obj));
269   assert(length <= Buffer::Length(buffer_obj) - offset);
270
271   SendWrap* req_wrap = new SendWrap(env, req_wrap_obj, have_callback);
272
273   uv_buf_t buf = uv_buf_init(Buffer::Data(buffer_obj) + offset,
274                              length);
275   char addr[sizeof(sockaddr_in6)];
276   int err;
277
278   switch (family) {
279   case AF_INET:
280     err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
281     break;
282   case AF_INET6:
283     err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
284     break;
285   default:
286     assert(0 && "unexpected address family");
287     abort();
288   }
289
290   if (err == 0) {
291     err = uv_udp_send(&req_wrap->req_,
292                       &wrap->handle_,
293                       &buf,
294                       1,
295                       reinterpret_cast<const sockaddr*>(&addr),
296                       OnSend);
297   }
298
299   req_wrap->Dispatched();
300   if (err) delete req_wrap;
301
302   args.GetReturnValue().Set(err);
303 }
304
305
306 void UDPWrap::Send(const FunctionCallbackInfo<Value>& args) {
307   DoSend(args, AF_INET);
308 }
309
310
311 void UDPWrap::Send6(const FunctionCallbackInfo<Value>& args) {
312   DoSend(args, AF_INET6);
313 }
314
315
316 void UDPWrap::RecvStart(const FunctionCallbackInfo<Value>& args) {
317   HandleScope scope(node_isolate);
318   UDPWrap* wrap;
319   NODE_UNWRAP(args.This(), UDPWrap, wrap);
320
321   int err = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv);
322   // UV_EALREADY means that the socket is already bound but that's okay
323   if (err == UV_EALREADY) err = 0;
324   args.GetReturnValue().Set(err);
325 }
326
327
328 void UDPWrap::RecvStop(const FunctionCallbackInfo<Value>& args) {
329   HandleScope scope(node_isolate);
330   UDPWrap* wrap;
331   NODE_UNWRAP(args.This(), UDPWrap, wrap);
332
333   int r = uv_udp_recv_stop(&wrap->handle_);
334   args.GetReturnValue().Set(r);
335 }
336
337
338 void UDPWrap::GetSockName(const FunctionCallbackInfo<Value>& args) {
339   Environment* env = Environment::GetCurrent(args.GetIsolate());
340   HandleScope handle_scope(args.GetIsolate());
341
342   struct sockaddr_storage address;
343   UDPWrap* wrap;
344   NODE_UNWRAP(args.This(), UDPWrap, wrap);
345
346   assert(args[0]->IsObject());
347   Local<Object> obj = args[0].As<Object>();
348
349   int addrlen = sizeof(address);
350   int err = uv_udp_getsockname(&wrap->handle_,
351                                reinterpret_cast<sockaddr*>(&address),
352                                &addrlen);
353
354   if (err == 0) {
355     const sockaddr* addr = reinterpret_cast<const sockaddr*>(&address);
356     AddressToJS(env, addr, obj);
357   }
358
359   args.GetReturnValue().Set(err);
360 }
361
362
363 // TODO(bnoordhuis) share with StreamWrap::AfterWrite() in stream_wrap.cc
364 void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
365   SendWrap* req_wrap = static_cast<SendWrap*>(req->data);
366   if (req_wrap->have_callback()) {
367     Environment* env = req_wrap->env();
368     Context::Scope context_scope(env->context());
369     HandleScope handle_scope(env->isolate());
370     Local<Object> req_wrap_obj = req_wrap->object();
371     Local<Value> arg = Integer::New(status, node_isolate);
372     MakeCallback(env, req_wrap_obj, env->oncomplete_string(), 1, &arg);
373   }
374   delete req_wrap;
375 }
376
377
378 void UDPWrap::OnAlloc(uv_handle_t* handle,
379                       size_t suggested_size,
380                       uv_buf_t* buf) {
381   buf->base = static_cast<char*>(malloc(suggested_size));
382   buf->len = suggested_size;
383
384   if (buf->base == NULL && suggested_size > 0) {
385     FatalError("node::UDPWrap::OnAlloc(uv_handle_t*, size_t, uv_buf_t*)",
386                "Out Of Memory");
387   }
388 }
389
390
391 void UDPWrap::OnRecv(uv_udp_t* handle,
392                      ssize_t nread,
393                      const uv_buf_t* buf,
394                      const struct sockaddr* addr,
395                      unsigned int flags) {
396   if (nread == 0) {
397     if (buf->base != NULL)
398       free(buf->base);
399     return;
400   }
401
402   UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
403   Environment* env = wrap->env();
404
405   Context::Scope context_scope(env->context());
406   HandleScope handle_scope(env->isolate());
407
408   Local<Object> wrap_obj = wrap->object();
409   Local<Value> argv[] = {
410     Integer::New(nread, node_isolate),
411     wrap_obj,
412     Undefined(),
413     Undefined()
414   };
415
416   if (nread < 0) {
417     if (buf->base != NULL)
418       free(buf->base);
419     MakeCallback(env,
420                  wrap_obj,
421                  env->onmessage_string(),
422                  ARRAY_SIZE(argv),
423                  argv);
424     return;
425   }
426
427   char* base = static_cast<char*>(realloc(buf->base, nread));
428   argv[2] = Buffer::Use(env, base, nread);
429   argv[3] = AddressToJS(env, addr);
430   MakeCallback(env, wrap_obj, env->onmessage_string(), ARRAY_SIZE(argv), argv);
431 }
432
433
434 UDPWrap* UDPWrap::Unwrap(Local<Object> obj) {
435   UDPWrap* wrap;
436   NODE_UNWRAP(obj, UDPWrap, wrap);
437   return wrap;
438 }
439
440
441 Local<Object> UDPWrap::Instantiate(Environment* env) {
442   // If this assert fires then Initialize hasn't been called yet.
443   assert(env->udp_constructor_function().IsEmpty() == false);
444   return env->udp_constructor_function()->NewInstance();
445 }
446
447
448 uv_udp_t* UDPWrap::UVHandle() {
449   return &handle_;
450 }
451
452
453 }  // namespace node
454
455 NODE_MODULE_CONTEXT_AWARE(node_udp_wrap, node::UDPWrap::Initialize)