1 // Copyright Joyent, Inc. and other Node contributors.
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:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
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.
25 #include "node_buffer.h"
26 #include "handle_wrap.h"
38 using v8::FunctionCallbackInfo;
39 using v8::FunctionTemplate;
41 using v8::HandleScope;
45 using v8::PropertyAttribute;
46 using v8::PropertyCallbackInfo;
53 class SendWrap : public ReqWrap<uv_udp_send_t> {
55 SendWrap(Environment* env, Local<Object> req_wrap_obj, bool have_callback);
56 inline bool have_callback() const;
58 const bool have_callback_;
62 SendWrap::SendWrap(Environment* env,
63 Local<Object> req_wrap_obj,
65 : ReqWrap<uv_udp_send_t>(env, req_wrap_obj),
66 have_callback_(have_callback) {
70 inline bool SendWrap::have_callback() const {
71 return have_callback_;
75 UDPWrap::UDPWrap(Environment* env, Handle<Object> 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
89 void UDPWrap::Initialize(Handle<Object> target,
91 Handle<Context> context) {
92 Environment* env = Environment::GetCurrent(context);
94 Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(), New);
95 t->InstanceTemplate()->SetInternalFieldCount(1);
96 t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "UDP"));
98 enum PropertyAttribute attributes =
99 static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
100 t->InstanceTemplate()->SetAccessor(env->fd_string(),
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);
122 NODE_SET_PROTOTYPE_METHOD(t, "ref", HandleWrap::Ref);
123 NODE_SET_PROTOTYPE_METHOD(t, "unref", HandleWrap::Unref);
125 target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "UDP"), t->GetFunction());
126 env->set_udp_constructor_function(t->GetFunction());
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());
138 void UDPWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) {
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);
149 void UDPWrap::DoBind(const FunctionCallbackInfo<Value>& args, int family) {
150 Environment* env = Environment::GetCurrent(args.GetIsolate());
151 HandleScope scope(env->isolate());
153 UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
155 // bind(ip, port, flags)
156 assert(args.Length() == 3);
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)];
166 err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
169 err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
172 assert(0 && "unexpected address family");
177 err = uv_udp_bind(&wrap->handle_,
178 reinterpret_cast<const sockaddr*>(&addr),
182 args.GetReturnValue().Set(err);
186 void UDPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
187 DoBind(args, AF_INET);
191 void UDPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
192 DoBind(args, AF_INET6);
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); \
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)
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());
220 assert(args.Length() == 2);
222 String::Utf8Value address(args[0]);
223 String::Utf8Value iface(args[1]);
225 const char* iface_cstr = *iface;
226 if (args[1]->IsUndefined() || args[1]->IsNull()) {
230 int err = uv_udp_set_membership(&wrap->handle_,
234 args.GetReturnValue().Set(err);
238 void UDPWrap::AddMembership(const FunctionCallbackInfo<Value>& args) {
239 SetMembership(args, UV_JOIN_GROUP);
243 void UDPWrap::DropMembership(const FunctionCallbackInfo<Value>& args) {
244 SetMembership(args, UV_LEAVE_GROUP);
248 void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {
249 HandleScope handle_scope(args.GetIsolate());
250 Environment* env = Environment::GetCurrent(args.GetIsolate());
252 UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
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());
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();
271 assert(offset < Buffer::Length(buffer_obj));
272 assert(length <= Buffer::Length(buffer_obj) - offset);
274 SendWrap* req_wrap = new SendWrap(env, req_wrap_obj, have_callback);
276 uv_buf_t buf = uv_buf_init(Buffer::Data(buffer_obj) + offset,
278 char addr[sizeof(sockaddr_in6)];
283 err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
286 err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
289 assert(0 && "unexpected address family");
294 err = uv_udp_send(&req_wrap->req_,
298 reinterpret_cast<const sockaddr*>(&addr),
302 req_wrap->Dispatched();
306 args.GetReturnValue().Set(err);
310 void UDPWrap::Send(const FunctionCallbackInfo<Value>& args) {
311 DoSend(args, AF_INET);
315 void UDPWrap::Send6(const FunctionCallbackInfo<Value>& args) {
316 DoSend(args, AF_INET6);
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());
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)
329 args.GetReturnValue().Set(err);
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());
338 int r = uv_udp_recv_stop(&wrap->handle_);
339 args.GetReturnValue().Set(r);
343 void UDPWrap::GetSockName(const FunctionCallbackInfo<Value>& args) {
344 HandleScope handle_scope(args.GetIsolate());
345 Environment* env = Environment::GetCurrent(args.GetIsolate());
347 struct sockaddr_storage address;
348 UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
350 assert(args[0]->IsObject());
351 Local<Object> obj = args[0].As<Object>();
353 int addrlen = sizeof(address);
354 int err = uv_udp_getsockname(&wrap->handle_,
355 reinterpret_cast<sockaddr*>(&address),
359 const sockaddr* addr = reinterpret_cast<const sockaddr*>(&address);
360 AddressToJS(env, addr, obj);
363 args.GetReturnValue().Set(err);
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);
381 void UDPWrap::OnAlloc(uv_handle_t* handle,
382 size_t suggested_size,
384 buf->base = static_cast<char*>(malloc(suggested_size));
385 buf->len = suggested_size;
387 if (buf->base == NULL && suggested_size > 0) {
388 FatalError("node::UDPWrap::OnAlloc(uv_handle_t*, size_t, uv_buf_t*)",
394 void UDPWrap::OnRecv(uv_udp_t* handle,
397 const struct sockaddr* addr,
398 unsigned int flags) {
400 if (buf->base != NULL)
405 UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
406 Environment* env = wrap->env();
408 HandleScope handle_scope(env->isolate());
409 Context::Scope context_scope(env->context());
411 Local<Object> wrap_obj = wrap->object();
412 Local<Value> argv[] = {
413 Integer::New(env->isolate(), nread),
415 Undefined(env->isolate()),
416 Undefined(env->isolate())
420 if (buf->base != NULL)
422 wrap->MakeCallback(env->onmessage_string(), ARRAY_SIZE(argv), argv);
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);
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();
440 uv_udp_t* UDPWrap::UVHandle() {
447 NODE_MODULE_CONTEXT_AWARE_BUILTIN(udp_wrap, node::UDPWrap::Initialize)