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