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