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.
23 #include "node_buffer.h"
24 #include "slab_allocator.h"
26 #include "handle_wrap.h"
31 #define SLAB_SIZE (1024 * 1024)
38 typedef ReqWrap<uv_udp_send_t> SendWrap;
41 Local<Object> AddressToJS(const sockaddr* addr);
43 static Persistent<String> buffer_sym;
44 static Persistent<String> oncomplete_sym;
45 static Persistent<String> onmessage_sym;
46 static SlabAllocator* slab_allocator;
49 static void DeleteSlabAllocator(void*) {
50 delete slab_allocator;
51 slab_allocator = NULL;
55 UDPWrap::UDPWrap(Handle<Object> object): HandleWrap(object,
56 (uv_handle_t*)&handle_) {
57 int r = uv_udp_init(uv_default_loop(), &handle_);
58 assert(r == 0); // can't fail anyway
59 handle_.data = reinterpret_cast<void*>(this);
67 void UDPWrap::Initialize(Handle<Object> target) {
68 HandleWrap::Initialize(target);
70 slab_allocator = new SlabAllocator(SLAB_SIZE);
71 AtExit(DeleteSlabAllocator, NULL);
75 buffer_sym = NODE_PSYMBOL("buffer");
76 oncomplete_sym = NODE_PSYMBOL("oncomplete");
77 onmessage_sym = NODE_PSYMBOL("onmessage");
79 Local<FunctionTemplate> t = FunctionTemplate::New(New);
80 t->InstanceTemplate()->SetInternalFieldCount(1);
81 t->SetClassName(String::NewSymbol("UDP"));
83 NODE_SET_PROTOTYPE_METHOD(t, "bind", Bind);
84 NODE_SET_PROTOTYPE_METHOD(t, "send", Send);
85 NODE_SET_PROTOTYPE_METHOD(t, "bind6", Bind6);
86 NODE_SET_PROTOTYPE_METHOD(t, "send6", Send6);
87 NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
88 NODE_SET_PROTOTYPE_METHOD(t, "recvStart", RecvStart);
89 NODE_SET_PROTOTYPE_METHOD(t, "recvStop", RecvStop);
90 NODE_SET_PROTOTYPE_METHOD(t, "getsockname", GetSockName);
91 NODE_SET_PROTOTYPE_METHOD(t, "addMembership", AddMembership);
92 NODE_SET_PROTOTYPE_METHOD(t, "dropMembership", DropMembership);
93 NODE_SET_PROTOTYPE_METHOD(t, "setMulticastTTL", SetMulticastTTL);
94 NODE_SET_PROTOTYPE_METHOD(t, "setMulticastLoopback", SetMulticastLoopback);
95 NODE_SET_PROTOTYPE_METHOD(t, "setBroadcast", SetBroadcast);
96 NODE_SET_PROTOTYPE_METHOD(t, "setTTL", SetTTL);
98 NODE_SET_PROTOTYPE_METHOD(t, "ref", HandleWrap::Ref);
99 NODE_SET_PROTOTYPE_METHOD(t, "unref", HandleWrap::Unref);
101 target->Set(String::NewSymbol("UDP"),
102 Persistent<FunctionTemplate>::New(t)->GetFunction());
106 Handle<Value> UDPWrap::New(const Arguments& args) {
109 assert(args.IsConstructCall());
110 new UDPWrap(args.This());
112 return scope.Close(args.This());
115 Handle<Value> UDPWrap::DoBind(const Arguments& args, int family) {
121 // bind(ip, port, flags)
122 assert(args.Length() == 3);
124 String::Utf8Value address(args[0]);
125 const int port = args[1]->Uint32Value();
126 const int flags = args[2]->Uint32Value();
130 r = uv_udp_bind(&wrap->handle_, uv_ip4_addr(*address, port), flags);
133 r = uv_udp_bind6(&wrap->handle_, uv_ip6_addr(*address, port), flags);
136 assert(0 && "unexpected address family");
141 SetErrno(uv_last_error(uv_default_loop()));
143 return scope.Close(Integer::New(r));
147 Handle<Value> UDPWrap::Bind(const Arguments& args) {
148 return DoBind(args, AF_INET);
152 Handle<Value> UDPWrap::Bind6(const Arguments& args) {
153 return DoBind(args, AF_INET6);
157 #define X(name, fn) \
158 Handle<Value> UDPWrap::name(const Arguments& args) { \
161 assert(args.Length() == 1); \
162 int flag = args[0]->Int32Value(); \
163 int r = fn(&wrap->handle_, flag); \
164 if (r) SetErrno(uv_last_error(uv_default_loop())); \
165 return scope.Close(Integer::New(r)); \
168 X(SetTTL, uv_udp_set_ttl)
169 X(SetBroadcast, uv_udp_set_broadcast)
170 X(SetMulticastTTL, uv_udp_set_multicast_ttl)
171 X(SetMulticastLoopback, uv_udp_set_multicast_loop)
176 Handle<Value> UDPWrap::SetMembership(const Arguments& args,
177 uv_membership membership) {
181 assert(args.Length() == 2);
183 String::Utf8Value address(args[0]);
184 String::Utf8Value iface(args[1]);
186 const char* iface_cstr = *iface;
187 if (args[1]->IsUndefined() || args[1]->IsNull()) {
191 int r = uv_udp_set_membership(&wrap->handle_, *address, iface_cstr,
195 SetErrno(uv_last_error(uv_default_loop()));
197 return scope.Close(Integer::New(r));
201 Handle<Value> UDPWrap::AddMembership(const Arguments& args) {
202 return SetMembership(args, UV_JOIN_GROUP);
206 Handle<Value> UDPWrap::DropMembership(const Arguments& args) {
207 return SetMembership(args, UV_LEAVE_GROUP);
211 Handle<Value> UDPWrap::DoSend(const Arguments& args, int family) {
215 // send(buffer, offset, length, port, address)
216 assert(args.Length() == 5);
220 assert(Buffer::HasInstance(args[0]));
221 Local<Object> buffer_obj = args[0]->ToObject();
223 size_t offset = args[1]->Uint32Value();
224 size_t length = args[2]->Uint32Value();
225 assert(offset < Buffer::Length(buffer_obj));
226 assert(length <= Buffer::Length(buffer_obj) - offset);
228 SendWrap* req_wrap = new SendWrap();
229 req_wrap->object_->SetHiddenValue(buffer_sym, buffer_obj);
231 uv_buf_t buf = uv_buf_init(Buffer::Data(buffer_obj) + offset,
234 const unsigned short port = args[3]->Uint32Value();
235 String::Utf8Value address(args[4]);
239 r = uv_udp_send(&req_wrap->req_, &wrap->handle_, &buf, 1,
240 uv_ip4_addr(*address, port), OnSend);
243 r = uv_udp_send6(&req_wrap->req_, &wrap->handle_, &buf, 1,
244 uv_ip6_addr(*address, port), OnSend);
247 assert(0 && "unexpected address family");
251 req_wrap->Dispatched();
254 SetErrno(uv_last_error(uv_default_loop()));
259 return scope.Close(req_wrap->object_);
264 Handle<Value> UDPWrap::Send(const Arguments& args) {
265 return DoSend(args, AF_INET);
269 Handle<Value> UDPWrap::Send6(const Arguments& args) {
270 return DoSend(args, AF_INET6);
274 Handle<Value> UDPWrap::RecvStart(const Arguments& args) {
279 // UV_EALREADY means that the socket is already bound but that's okay
280 int r = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv);
281 if (r && uv_last_error(uv_default_loop()).code != UV_EALREADY) {
282 SetErrno(uv_last_error(uv_default_loop()));
290 Handle<Value> UDPWrap::RecvStop(const Arguments& args) {
295 int r = uv_udp_recv_stop(&wrap->handle_);
297 return scope.Close(Integer::New(r));
301 Handle<Value> UDPWrap::GetSockName(const Arguments& args) {
303 struct sockaddr_storage address;
307 int addrlen = sizeof(address);
308 int r = uv_udp_getsockname(&wrap->handle_,
309 reinterpret_cast<sockaddr*>(&address),
313 SetErrno(uv_last_error(uv_default_loop()));
317 const sockaddr* addr = reinterpret_cast<const sockaddr*>(&address);
318 return scope.Close(AddressToJS(addr));
322 // TODO share with StreamWrap::AfterWrite() in stream_wrap.cc
323 void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
328 SendWrap* req_wrap = reinterpret_cast<SendWrap*>(req->data);
329 UDPWrap* wrap = reinterpret_cast<UDPWrap*>(req->handle->data);
331 assert(req_wrap->object_.IsEmpty() == false);
332 assert(wrap->object_.IsEmpty() == false);
335 SetErrno(uv_last_error(uv_default_loop()));
338 Local<Value> argv[4] = {
339 Integer::New(status),
340 Local<Value>::New(wrap->object_),
341 Local<Value>::New(req_wrap->object_),
342 req_wrap->object_->GetHiddenValue(buffer_sym),
345 MakeCallback(req_wrap->object_, oncomplete_sym, ARRAY_SIZE(argv), argv);
350 uv_buf_t UDPWrap::OnAlloc(uv_handle_t* handle, size_t suggested_size) {
351 UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
352 char* buf = slab_allocator->Allocate(wrap->object_, suggested_size);
353 return uv_buf_init(buf, suggested_size);
357 void UDPWrap::OnRecv(uv_udp_t* handle,
360 struct sockaddr* addr,
364 UDPWrap* wrap = reinterpret_cast<UDPWrap*>(handle->data);
365 Local<Object> slab = slab_allocator->Shrink(wrap->object_,
367 nread < 0 ? 0 : nread);
368 if (nread == 0) return;
371 Local<Value> argv[] = { Local<Object>::New(wrap->object_) };
372 SetErrno(uv_last_error(uv_default_loop()));
373 MakeCallback(wrap->object_, onmessage_sym, ARRAY_SIZE(argv), argv);
377 Local<Value> argv[] = {
378 Local<Object>::New(wrap->object_),
380 Integer::NewFromUnsigned(buf.base - Buffer::Data(slab)),
381 Integer::NewFromUnsigned(nread),
384 MakeCallback(wrap->object_, onmessage_sym, ARRAY_SIZE(argv), argv);
388 UDPWrap* UDPWrap::Unwrap(Local<Object> obj) {
389 assert(!obj.IsEmpty());
390 assert(obj->InternalFieldCount() > 0);
391 return static_cast<UDPWrap*>(obj->GetPointerFromInternalField(0));
395 uv_udp_t* UDPWrap::UVHandle() {
402 NODE_MODULE(node_udp_wrap, node::UDPWrap::Initialize)