From 0dee60740917cc9034497a60c6d7227cb2ec9682 Mon Sep 17 00:00:00 2001 From: Jon Moss Date: Tue, 14 Aug 2018 10:35:40 -0400 Subject: [PATCH] src: extract common Bind method `TCPWrap::Bind` and `TCPWrap::Bind6` share a large amount of functionality, so a common `Bind` was extracted to remove duplication. Backport-PR-URL: https://github.com/nodejs/node/pull/28222 PR-URL: https://github.com/nodejs/node/pull/22315 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Fedor Indutny Reviewed-By: Denys Otrishko --- src/tcp_wrap.cc | 39 +++++++++++++++++++-------------------- src/tcp_wrap.h | 5 +++++ 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/src/tcp_wrap.cc b/src/tcp_wrap.cc index a6cc01f1288928..8eb940034de264 100644 --- a/src/tcp_wrap.cc +++ b/src/tcp_wrap.cc @@ -219,8 +219,11 @@ void TCPWrap::Open(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(err); } - -void TCPWrap::Bind(const FunctionCallbackInfo& args) { +template +void TCPWrap::Bind( + const FunctionCallbackInfo& args, + int family, + std::function uv_ip_addr) { TCPWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder(), @@ -228,9 +231,16 @@ void TCPWrap::Bind(const FunctionCallbackInfo& args) { Environment* env = wrap->env(); node::Utf8Value ip_address(env->isolate(), args[0]); int port; + unsigned int flags = 0; if (!args[1]->Int32Value(env->context()).To(&port)) return; - sockaddr_in addr; - int err = uv_ip4_addr(*ip_address, port, &addr); + if (family == AF_INET6 && + !args[2]->Uint32Value(env->context()).To(&flags)) { + return; + } + + T addr; + int err = uv_ip_addr(*ip_address, port, &addr); + if (err == 0) { err = uv_tcp_bind(&wrap->handle_, reinterpret_cast(&addr), @@ -239,24 +249,13 @@ void TCPWrap::Bind(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(err); } +void TCPWrap::Bind(const FunctionCallbackInfo& args) { + Bind(args, AF_INET, uv_ip4_addr); +} + void TCPWrap::Bind6(const FunctionCallbackInfo& args) { - TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); - Environment* env = wrap->env(); - node::Utf8Value ip6_address(env->isolate(), args[0]); - int port; - if (!args[1]->Int32Value(env->context()).To(&port)) return; - sockaddr_in6 addr; - int err = uv_ip6_addr(*ip6_address, port, &addr); - if (err == 0) { - err = uv_tcp_bind(&wrap->handle_, - reinterpret_cast(&addr), - 0); - } - args.GetReturnValue().Set(err); + Bind(args, AF_INET6, uv_ip6_addr); } diff --git a/src/tcp_wrap.h b/src/tcp_wrap.h index 3cbeae6d64a949..62176c002d2b98 100644 --- a/src/tcp_wrap.h +++ b/src/tcp_wrap.h @@ -79,6 +79,11 @@ class TCPWrap : public ConnectionWrap { static void Connect(const v8::FunctionCallbackInfo& args, std::function uv_ip_addr); static void Open(const v8::FunctionCallbackInfo& args); + template + static void Bind( + const v8::FunctionCallbackInfo& args, + int family, + std::function uv_ip_addr); #ifdef _WIN32 static void SetSimultaneousAccepts(