• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "socket_exec.h"
17 
18 #include <arpa/inet.h>
19 #include <atomic>
20 #include <cerrno>
21 #include <condition_variable>
22 #include <fcntl.h>
23 #include <map>
24 #include <memory>
25 #include <mutex>
26 #include <netinet/tcp.h>
27 #include <poll.h>
28 #include <sys/socket.h>
29 #include <thread>
30 #include <unistd.h>
31 
32 #include "context_key.h"
33 #include "event_list.h"
34 #include "napi_utils.h"
35 #include "netstack_common_utils.h"
36 #include "netstack_log.h"
37 #include "securec.h"
38 #include "socket_async_work.h"
39 #include "socket_module.h"
40 
41 static constexpr const int DEFAULT_BUFFER_SIZE = 8192;
42 
43 static constexpr const int DEFAULT_POLL_TIMEOUT = 500; // 0.5 Seconds
44 
45 static constexpr const int ADDRESS_INVALID = 99;
46 
47 static constexpr const int OTHER_ERROR = 100;
48 
49 static constexpr const int SOCKET_ENOTSTR = 60;
50 
51 static constexpr const int UNKNOW_ERROR = -1;
52 
53 static constexpr const int NO_MEMORY = -2;
54 
55 static constexpr const int MSEC_TO_USEC = 1000;
56 
57 static constexpr const int MAX_SEC = 999999999;
58 
59 static constexpr const int USER_LIMIT = 511;
60 
61 static constexpr const int MAX_CLIENTS = 1024;
62 
63 static constexpr const char *TCP_SOCKET_CONNECTION = "TCPSocketConnection";
64 
65 static constexpr const char *TCP_SERVER_ACCEPT_RECV_DATA = "TCPServerAcceptRecvData";
66 
67 static constexpr const char *TCP_SERVER_HANDLE_CLIENT = "TCPServerHandleClient";
68 
69 namespace OHOS::NetStack::Socket::SocketExec {
70 std::map<int32_t, int32_t> g_clientFDs;
71 std::map<int32_t, EventManager *> g_clientEventManagers;
72 std::condition_variable g_cv;
73 std::mutex g_mutex;
74 std::atomic_int g_userCounter = 0;
75 
76 struct MessageData {
77     MessageData() = delete;
MessageDataOHOS::NetStack::Socket::SocketExec::MessageData78     MessageData(void *d, size_t l, const SocketRemoteInfo &info) : data(d), len(l), remoteInfo(info) {}
~MessageDataOHOS::NetStack::Socket::SocketExec::MessageData79     ~MessageData()
80     {
81         if (data) {
82             free(data);
83         }
84     }
85 
86     void *data;
87     size_t len;
88     SocketRemoteInfo remoteInfo;
89 };
90 
91 struct TcpConnection {
92     TcpConnection() = delete;
TcpConnectionOHOS::NetStack::Socket::SocketExec::TcpConnection93     explicit TcpConnection(int32_t clientid) : clientId(clientid) {}
94     ~TcpConnection() = default;
95 
96     int32_t clientId;
97 };
98 
SetIsBound(sa_family_t family,GetStateContext * context,const sockaddr_in * addr4,const sockaddr_in6 * addr6)99 static void SetIsBound(sa_family_t family, GetStateContext *context, const sockaddr_in *addr4,
100                        const sockaddr_in6 *addr6)
101 {
102     if (family == AF_INET) {
103         context->state_.SetIsBound(ntohs(addr4->sin_port) != 0);
104     } else if (family == AF_INET6) {
105         context->state_.SetIsBound(ntohs(addr6->sin6_port) != 0);
106     }
107 }
108 
SetIsConnected(sa_family_t family,GetStateContext * context,const sockaddr_in * addr4,const sockaddr_in6 * addr6)109 static void SetIsConnected(sa_family_t family, GetStateContext *context, const sockaddr_in *addr4,
110                            const sockaddr_in6 *addr6)
111 {
112     if (family == AF_INET) {
113         context->state_.SetIsConnected(ntohs(addr4->sin_port) != 0);
114     } else if (family == AF_INET6) {
115         context->state_.SetIsConnected(ntohs(addr6->sin6_port) != 0);
116     }
117 }
118 
CallbackTemplate(uv_work_t * work,int status)119 template <napi_value (*MakeJsValue)(napi_env, void *)> static void CallbackTemplate(uv_work_t *work, int status)
120 {
121     (void)status;
122 
123     auto workWrapper = static_cast<UvWorkWrapper *>(work->data);
124     napi_env env = workWrapper->env;
125     auto closeScope = [env](napi_handle_scope scope) { NapiUtils::CloseScope(env, scope); };
126     std::unique_ptr<napi_handle_scope__, decltype(closeScope)> scope(NapiUtils::OpenScope(env), closeScope);
127 
128     napi_value obj = MakeJsValue(env, workWrapper->data);
129 
130     std::pair<napi_value, napi_value> arg = {NapiUtils::GetUndefined(workWrapper->env), obj};
131     workWrapper->manager->Emit(workWrapper->type, arg);
132 
133     delete workWrapper;
134     delete work;
135 }
136 
MakeError(napi_env env,void * errCode)137 static napi_value MakeError(napi_env env, void *errCode)
138 {
139     auto code = reinterpret_cast<int32_t *>(errCode);
140     auto deleter = [](const int32_t *p) { delete p; };
141     std::unique_ptr<int32_t, decltype(deleter)> handler(code, deleter);
142 
143     napi_value err = NapiUtils::CreateObject(env);
144     if (NapiUtils::GetValueType(env, err) != napi_object) {
145         return NapiUtils::GetUndefined(env);
146     }
147     NapiUtils::SetInt32Property(env, err, KEY_ERROR_CODE, *code);
148     return err;
149 }
150 
MakeClose(napi_env env,void * data)151 static napi_value MakeClose(napi_env env, void *data)
152 {
153     (void)data;
154     NETSTACK_LOGI("go to MakeClose");
155     napi_value obj = NapiUtils::CreateObject(env);
156     if (NapiUtils::GetValueType(env, obj) != napi_object) {
157         return NapiUtils::GetUndefined(env);
158     }
159 
160     return obj;
161 }
162 
TcpServerConnectionFinalize(napi_env,void * data,void *)163 void TcpServerConnectionFinalize(napi_env, void *data, void *)
164 {
165     NETSTACK_LOGI("socket handle is finalized");
166     auto manager = static_cast<EventManager *>(data);
167     if (manager != nullptr) {
168         NETSTACK_LOGI("manager != nullpt");
169         int clientIndex = -1;
170         std::lock_guard<std::mutex> lock(g_mutex);
171         for (auto it = g_clientEventManagers.begin(); it != g_clientEventManagers.end(); ++it) {
172             if (it->second == manager) {
173                 clientIndex = it->first;
174                 g_clientEventManagers.erase(it);
175                 break;
176             }
177         }
178         auto clientIter = g_clientFDs.find(clientIndex);
179         if (clientIter != g_clientFDs.end()) {
180             if (clientIter->second != -1) {
181                 NETSTACK_LOGI("close socketfd %{public}d", clientIter->second);
182                 close(clientIter->second);
183                 clientIter->second = -1;
184             }
185         }
186     }
187     EventManager::SetInvalid(manager);
188 }
189 
NewInstanceWithConstructor(napi_env env,napi_callback_info info,napi_value jsConstructor,int32_t counter)190 napi_value NewInstanceWithConstructor(napi_env env, napi_callback_info info, napi_value jsConstructor, int32_t counter)
191 {
192     napi_value result = nullptr;
193     NAPI_CALL(env, napi_new_instance(env, jsConstructor, 0, nullptr, &result));
194 
195     EventManager *manager = new EventManager();
196     {
197         std::lock_guard<std::mutex> lock(g_mutex);
198         g_clientEventManagers.insert(std::pair<int32_t, EventManager *>(counter, manager));
199         g_cv.notify_one();
200     }
201 
202     manager->SetData(reinterpret_cast<void *>(counter));
203     EventManager::SetValid(manager);
204     napi_wrap(env, result, reinterpret_cast<void *>(manager), TcpServerConnectionFinalize, nullptr, nullptr);
205     return result;
206 } // namespace OHOS::NetStack::Socket::SocketExec
207 
ConstructTCPSocketConnection(napi_env env,napi_callback_info info,int32_t counter)208 napi_value ConstructTCPSocketConnection(napi_env env, napi_callback_info info, int32_t counter)
209 {
210     napi_value jsConstructor = nullptr;
211     std::initializer_list<napi_property_descriptor> properties = {
212         DECLARE_NAPI_FUNCTION(SocketModuleExports::TCPConnection::FUNCTION_SEND,
213                               SocketModuleExports::TCPConnection::Send),
214         DECLARE_NAPI_FUNCTION(SocketModuleExports::TCPConnection::FUNCTION_CLOSE,
215                               SocketModuleExports::TCPConnection::Close),
216         DECLARE_NAPI_FUNCTION(SocketModuleExports::TCPConnection::FUNCTION_GET_REMOTE_ADDRESS,
217                               SocketModuleExports::TCPConnection::GetRemoteAddress),
218         DECLARE_NAPI_FUNCTION(SocketModuleExports::TCPConnection::FUNCTION_ON, SocketModuleExports::TCPConnection::On),
219         DECLARE_NAPI_FUNCTION(SocketModuleExports::TCPConnection::FUNCTION_OFF,
220                               SocketModuleExports::TCPConnection::Off),
221     };
222 
223     auto constructor = [](napi_env env, napi_callback_info info) -> napi_value {
224         napi_value thisVal = nullptr;
225         NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVal, nullptr));
226 
227         return thisVal;
228     };
229 
230     napi_property_descriptor descriptors[properties.size()];
231     std::copy(properties.begin(), properties.end(), descriptors);
232 
233     NAPI_CALL_BASE(env,
234                    napi_define_class(env, TCP_SOCKET_CONNECTION, NAPI_AUTO_LENGTH, constructor, nullptr,
235                                      properties.size(), descriptors, &jsConstructor),
236                    NapiUtils::GetUndefined(env));
237 
238     if (jsConstructor != nullptr) {
239         napi_value result = NewInstanceWithConstructor(env, info, jsConstructor, counter);
240         NapiUtils::SetInt32Property(env, result, SocketModuleExports::TCPConnection::PROPERTY_CLIENT_ID, counter);
241         return result;
242     }
243     return NapiUtils::GetUndefined(env);
244 }
245 
MakeTcpConnectionMessage(napi_env env,void * para)246 static napi_value MakeTcpConnectionMessage(napi_env env, void *para)
247 {
248     auto netConnection = reinterpret_cast<TcpConnection *>(para);
249     auto deleter = [](const TcpConnection *p) { delete p; };
250     std::unique_ptr<TcpConnection, decltype(deleter)> handler(netConnection, deleter);
251 
252     napi_callback_info info = nullptr;
253     return ConstructTCPSocketConnection(env, info, netConnection->clientId);
254 }
255 
MakeAddressString(sockaddr * addr)256 static std::string MakeAddressString(sockaddr *addr)
257 {
258     if (addr->sa_family == AF_INET) {
259         auto *addr4 = reinterpret_cast<sockaddr_in *>(addr);
260         const char *str = inet_ntoa(addr4->sin_addr);
261         if (str == nullptr || strlen(str) == 0) {
262             return {};
263         }
264         return str;
265     } else if (addr->sa_family == AF_INET6) {
266         auto *addr6 = reinterpret_cast<sockaddr_in6 *>(addr);
267         char str[INET6_ADDRSTRLEN] = {0};
268         if (inet_ntop(AF_INET6, &addr6->sin6_addr, str, INET6_ADDRSTRLEN) == nullptr || strlen(str) == 0) {
269             return {};
270         }
271         return str;
272     }
273     return {};
274 }
275 
MakeJsMessageParam(napi_env env,napi_value msgBuffer,SocketRemoteInfo * remoteInfo)276 static napi_value MakeJsMessageParam(napi_env env, napi_value msgBuffer, SocketRemoteInfo *remoteInfo)
277 {
278     napi_value obj = NapiUtils::CreateObject(env);
279     if (NapiUtils::GetValueType(env, obj) != napi_object) {
280         return nullptr;
281     }
282     if (NapiUtils::ValueIsArrayBuffer(env, msgBuffer)) {
283         NapiUtils::SetNamedProperty(env, obj, KEY_MESSAGE, msgBuffer);
284     }
285     napi_value jsRemoteInfo = NapiUtils::CreateObject(env);
286     if (NapiUtils::GetValueType(env, jsRemoteInfo) != napi_object) {
287         return nullptr;
288     }
289     NapiUtils::SetStringPropertyUtf8(env, jsRemoteInfo, KEY_ADDRESS, remoteInfo->GetAddress());
290     NapiUtils::SetStringPropertyUtf8(env, jsRemoteInfo, KEY_FAMILY, remoteInfo->GetFamily());
291     NapiUtils::SetUint32Property(env, jsRemoteInfo, KEY_PORT, remoteInfo->GetPort());
292     NapiUtils::SetUint32Property(env, jsRemoteInfo, KEY_SIZE, remoteInfo->GetSize());
293 
294     NapiUtils::SetNamedProperty(env, obj, KEY_REMOTE_INFO, jsRemoteInfo);
295     return obj;
296 }
297 
MakeMessage(napi_env env,void * para)298 static napi_value MakeMessage(napi_env env, void *para)
299 {
300     auto manager = reinterpret_cast<EventManager *>(para);
301     auto messageData = reinterpret_cast<MessageData *>(manager->GetQueueData());
302     manager->PopQueueData();
303     auto deleter = [](const MessageData *p) { delete p; };
304     std::unique_ptr<MessageData, decltype(deleter)> handler(messageData, deleter);
305 
306     if (messageData == nullptr || messageData->data == nullptr || messageData->len == 0) {
307         return MakeJsMessageParam(env, NapiUtils::GetUndefined(env), &messageData->remoteInfo);
308     }
309 
310     void *dataHandle = nullptr;
311     napi_value msgBuffer = NapiUtils::CreateArrayBuffer(env, messageData->len, &dataHandle);
312     if (dataHandle == nullptr || !NapiUtils::ValueIsArrayBuffer(env, msgBuffer)) {
313         return MakeJsMessageParam(env, NapiUtils::GetUndefined(env), &messageData->remoteInfo);
314     }
315 
316     int result = memcpy_s(dataHandle, messageData->len, messageData->data, messageData->len);
317     if (result != EOK) {
318         NETSTACK_LOGI("copy ret %{public}d", result);
319         return NapiUtils::GetUndefined(env);
320     }
321 
322     return MakeJsMessageParam(env, msgBuffer, &messageData->remoteInfo);
323 }
324 
OnRecvMessage(EventManager * manager,void * data,size_t len,sockaddr * addr)325 static bool OnRecvMessage(EventManager *manager, void *data, size_t len, sockaddr *addr)
326 {
327     if (data == nullptr || len == 0) {
328         return false;
329     }
330 
331     SocketRemoteInfo remoteInfo;
332     std::string address = MakeAddressString(addr);
333     if (address.empty()) {
334         manager->EmitByUv(EVENT_ERROR, new int32_t(ADDRESS_INVALID), CallbackTemplate<MakeError>);
335         return false;
336     }
337     remoteInfo.SetAddress(address);
338     remoteInfo.SetFamily(addr->sa_family);
339     if (addr->sa_family == AF_INET) {
340         auto *addr4 = reinterpret_cast<sockaddr_in *>(addr);
341         remoteInfo.SetPort(ntohs(addr4->sin_port));
342     } else if (addr->sa_family == AF_INET6) {
343         auto *addr6 = reinterpret_cast<sockaddr_in6 *>(addr);
344         remoteInfo.SetPort(ntohs(addr6->sin6_port));
345     }
346     remoteInfo.SetSize(len);
347 
348     auto *messageStruct = new MessageData(data, len, remoteInfo);
349     manager->SetQueueData(reinterpret_cast<void *>(messageStruct));
350     manager->EmitByUv(EVENT_MESSAGE, manager, CallbackTemplate<MakeMessage>);
351     return true;
352 }
353 
354 class MessageCallback {
355 public:
356     MessageCallback() = delete;
357 
358     virtual ~MessageCallback() = default;
359 
MessageCallback(EventManager * manager)360     explicit MessageCallback(EventManager *manager) : manager_(manager) {}
361 
362     virtual void OnError(int err) const = 0;
363 
364     virtual void OnCloseMessage(EventManager *manager) const = 0;
365 
366     virtual bool OnMessage(void *data, size_t dataLen, sockaddr *addr) const = 0;
367 
368     virtual bool OnMessage(int sock, void *data, size_t dataLen, sockaddr *addr, EventManager *manager) const = 0;
369 
370     virtual void OnTcpConnectionMessage(int32_t id) const = 0;
371 
372     [[nodiscard]] EventManager *GetEventManager() const;
373 
374 protected:
375     EventManager *manager_;
376 };
377 
GetEventManager() const378 EventManager *MessageCallback::GetEventManager() const
379 {
380     return manager_;
381 }
382 
383 class TcpMessageCallback final : public MessageCallback {
384 public:
385     TcpMessageCallback() = delete;
386 
387     ~TcpMessageCallback() override = default;
388 
TcpMessageCallback(EventManager * manager)389     explicit TcpMessageCallback(EventManager *manager) : MessageCallback(manager) {}
390 
OnError(int err) const391     void OnError(int err) const override
392     {
393         manager_->EmitByUv(EVENT_ERROR, new int(err), CallbackTemplate<MakeError>);
394     }
395 
OnCloseMessage(EventManager * manager) const396     void OnCloseMessage(EventManager *manager) const override
397     {
398         manager->EmitByUv(EVENT_CLOSE, nullptr, CallbackTemplate<MakeClose>);
399     }
400 
OnMessage(void * data,size_t dataLen,sockaddr * addr) const401     bool OnMessage(void *data, size_t dataLen, sockaddr *addr) const override
402     {
403         (void)addr;
404         int sock = static_cast<int>(reinterpret_cast<uint64_t>(manager_->GetData()));
405         if (sock == 0) {
406             return false;
407         }
408         sockaddr sockAddr = {0};
409         socklen_t len = sizeof(sockaddr);
410         int ret = getsockname(sock, &sockAddr, &len);
411         if (ret < 0) {
412             return false;
413         }
414 
415         if (sockAddr.sa_family == AF_INET) {
416             sockaddr_in addr4 = {0};
417             socklen_t len4 = sizeof(sockaddr_in);
418 
419             ret = getpeername(sock, reinterpret_cast<sockaddr *>(&addr4), &len4);
420             if (ret < 0) {
421                 return false;
422             }
423             return OnRecvMessage(manager_, data, dataLen, reinterpret_cast<sockaddr *>(&addr4));
424         } else if (sockAddr.sa_family == AF_INET6) {
425             sockaddr_in6 addr6 = {0};
426             socklen_t len6 = sizeof(sockaddr_in6);
427 
428             ret = getpeername(sock, reinterpret_cast<sockaddr *>(&addr6), &len6);
429             if (ret < 0) {
430                 return false;
431             }
432             return OnRecvMessage(manager_, data, dataLen, reinterpret_cast<sockaddr *>(&addr6));
433         }
434         return false;
435     }
436 
OnMessage(int sock,void * data,size_t dataLen,sockaddr * addr,EventManager * manager) const437     bool OnMessage(int sock, void *data, size_t dataLen, sockaddr *addr, EventManager *manager) const override
438     {
439         (void)addr;
440         if (static_cast<int>(reinterpret_cast<uint64_t>(manager_->GetData())) == 0) {
441             return false;
442         }
443         sockaddr sockAddr = {0};
444         socklen_t len = sizeof(sockaddr);
445         int ret = getsockname(sock, &sockAddr, &len);
446         if (ret < 0) {
447             return false;
448         }
449 
450         if (sockAddr.sa_family == AF_INET) {
451             sockaddr_in addr4 = {0};
452             socklen_t len4 = sizeof(sockaddr_in);
453 
454             ret = getpeername(sock, reinterpret_cast<sockaddr *>(&addr4), &len4);
455             if (ret < 0) {
456                 return false;
457             }
458             return OnRecvMessage(manager, data, dataLen, reinterpret_cast<sockaddr *>(&addr4));
459         } else if (sockAddr.sa_family == AF_INET6) {
460             sockaddr_in6 addr6 = {0};
461             socklen_t len6 = sizeof(sockaddr_in6);
462 
463             ret = getpeername(sock, reinterpret_cast<sockaddr *>(&addr6), &len6);
464             if (ret < 0) {
465                 return false;
466             }
467             return OnRecvMessage(manager, data, dataLen, reinterpret_cast<sockaddr *>(&addr6));
468         }
469         return false;
470     }
471 
OnTcpConnectionMessage(int32_t id) const472     void OnTcpConnectionMessage(int32_t id) const override
473     {
474         manager_->EmitByUv(EVENT_CONNECT, new TcpConnection(id), CallbackTemplate<MakeTcpConnectionMessage>);
475     }
476 };
477 
478 class UdpMessageCallback final : public MessageCallback {
479 public:
480     UdpMessageCallback() = delete;
481 
482     ~UdpMessageCallback() override = default;
483 
UdpMessageCallback(EventManager * manager)484     explicit UdpMessageCallback(EventManager *manager) : MessageCallback(manager) {}
485 
OnError(int err) const486     void OnError(int err) const override
487     {
488         manager_->EmitByUv(EVENT_ERROR, new int(err), CallbackTemplate<MakeError>);
489     }
490 
OnCloseMessage(EventManager * manager) const491     void OnCloseMessage(EventManager *manager) const override {}
492 
OnMessage(void * data,size_t dataLen,sockaddr * addr) const493     bool OnMessage(void *data, size_t dataLen, sockaddr *addr) const override
494     {
495         int sock = static_cast<int>(reinterpret_cast<uint64_t>(manager_->GetData()));
496         if (sock == 0) {
497             return false;
498         }
499         return OnRecvMessage(manager_, data, dataLen, addr);
500     }
501 
OnMessage(int sock,void * data,size_t dataLen,sockaddr * addr,EventManager * manager) const502     bool OnMessage(int sock, void *data, size_t dataLen, sockaddr *addr, EventManager *manager) const override
503     {
504         if (static_cast<int>(reinterpret_cast<uint64_t>(manager_->GetData())) == 0) {
505             return false;
506         }
507         return true;
508     }
509 
OnTcpConnectionMessage(int32_t id) const510     void OnTcpConnectionMessage(int32_t id) const override {}
511 };
512 
GetAddr(NetAddress * address,sockaddr_in * addr4,sockaddr_in6 * addr6,sockaddr ** addr,socklen_t * len)513 static void GetAddr(NetAddress *address, sockaddr_in *addr4, sockaddr_in6 *addr6, sockaddr **addr, socklen_t *len)
514 {
515     sa_family_t family = address->GetSaFamily();
516     if (family == AF_INET) {
517         addr4->sin_family = AF_INET;
518         addr4->sin_port = htons(address->GetPort());
519         addr4->sin_addr.s_addr = inet_addr(address->GetAddress().c_str());
520         *addr = reinterpret_cast<sockaddr *>(addr4);
521         *len = sizeof(sockaddr_in);
522     } else if (family == AF_INET6) {
523         addr6->sin6_family = AF_INET6;
524         addr6->sin6_port = htons(address->GetPort());
525         inet_pton(AF_INET6, address->GetAddress().c_str(), &addr6->sin6_addr);
526         *addr = reinterpret_cast<sockaddr *>(addr6);
527         *len = sizeof(sockaddr_in6);
528     }
529 }
530 
MakeNonBlock(int sock)531 static bool MakeNonBlock(int sock)
532 {
533     int flags = fcntl(sock, F_GETFL, 0);
534     while (flags == -1 && errno == EINTR) {
535         flags = fcntl(sock, F_GETFL, 0);
536     }
537     if (flags == -1) {
538         NETSTACK_LOGE("make non block failed, socket is %{public}d, errno is %{public}d", sock, errno);
539         return false;
540     }
541     int ret = fcntl(sock, F_SETFL, flags | O_NONBLOCK);
542     while (ret == -1 && errno == EINTR) {
543         ret = fcntl(sock, F_SETFL, flags | O_NONBLOCK);
544     }
545     if (ret == -1) {
546         NETSTACK_LOGE("make non block failed, socket is %{public}d, errno is %{public}d", sock, errno);
547         return false;
548     }
549     return true;
550 }
551 
PollFd(pollfd * fds,nfds_t num,int timeout)552 static bool PollFd(pollfd *fds, nfds_t num, int timeout)
553 {
554     int ret = poll(fds, num, timeout);
555     if (ret == -1) {
556         NETSTACK_LOGE("poll to send failed, socket is %{public}d, errno is %{public}d", fds->fd, errno);
557         return false;
558     }
559     if (ret == 0) {
560         NETSTACK_LOGE("poll to send timeout, socket is %{public}d, errno is %{public}d", fds->fd, errno);
561         return false;
562     }
563     return true;
564 }
565 
PollSendData(int sock,const char * data,size_t size,sockaddr * addr,socklen_t addrLen)566 static bool PollSendData(int sock, const char *data, size_t size, sockaddr *addr, socklen_t addrLen)
567 {
568     int bufferSize = DEFAULT_BUFFER_SIZE;
569     int opt = 0;
570     socklen_t optLen = sizeof(opt);
571     if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<void *>(&opt), &optLen) >= 0 && opt > 0) {
572         bufferSize = opt;
573     }
574     int sockType = 0;
575     optLen = sizeof(sockType);
576     if (getsockopt(sock, SOL_SOCKET, SO_TYPE, reinterpret_cast<void *>(&sockType), &optLen) < 0) {
577         NETSTACK_LOGI("get sock opt sock type failed, socket is %{public}d, errno is %{public}d", sock, errno);
578         return false;
579     }
580 
581     auto curPos = data;
582     auto leftSize = size;
583     nfds_t num = 1;
584     pollfd fds[1] = {{0}};
585     fds[0].fd = sock;
586     fds[0].events = 0;
587     fds[0].events |= POLLOUT;
588 
589     while (leftSize > 0) {
590         if (!PollFd(fds, num, DEFAULT_BUFFER_SIZE)) {
591             return false;
592         }
593         size_t sendSize = (sockType == SOCK_STREAM ? leftSize : std::min<size_t>(leftSize, bufferSize));
594         auto sendLen = sendto(sock, curPos, sendSize, 0, addr, addrLen);
595         if (sendLen < 0) {
596             if (errno == EAGAIN) {
597                 continue;
598             }
599             NETSTACK_LOGE("send failed, socket is %{public}d, errno is %{public}d", sock, errno);
600             return false;
601         }
602         if (sendLen == 0) {
603             break;
604         }
605         curPos += sendLen;
606         leftSize -= sendLen;
607     }
608 
609     if (leftSize != 0) {
610         NETSTACK_LOGE("send not complete, socket is %{public}d, errno is %{public}d", sock, errno);
611         return false;
612     }
613     return true;
614 }
615 
TcpSendEvent(TcpSendContext * context)616 static bool TcpSendEvent(TcpSendContext *context)
617 {
618     std::string encoding = context->options.GetEncoding();
619     (void)encoding;
620     /* no use for now */
621 
622     sockaddr sockAddr = {0};
623     socklen_t len = sizeof(sockaddr);
624     if (getsockname(context->GetSocketFd(), &sockAddr, &len) < 0) {
625         NETSTACK_LOGE("get sock name failed, socket is %{public}d, errno is %{public}d", context->GetSocketFd(), errno);
626         context->SetErrorCode(SOCKET_ENOTSTR);
627         // reason: Crossplatform; Possible causes: socketfd error, socket type error, socket status error
628         // socket net connect, socket closed, socket option error
629         NETSTACK_LOGE("set errorCode is %{public}d", SOCKET_ENOTSTR);
630         return false;
631     }
632     bool connected = false;
633     if (sockAddr.sa_family == AF_INET) {
634         sockaddr_in addr4 = {0};
635         socklen_t len4 = sizeof(addr4);
636         int ret = getpeername(context->GetSocketFd(), reinterpret_cast<sockaddr *>(&addr4), &len4);
637         if (ret >= 0 && addr4.sin_port != 0) {
638             connected = true;
639         }
640     } else if (sockAddr.sa_family == AF_INET6) {
641         sockaddr_in6 addr6 = {0};
642         socklen_t len6 = sizeof(addr6);
643         int ret = getpeername(context->GetSocketFd(), reinterpret_cast<sockaddr *>(&addr6), &len6);
644         if (ret >= 0 && addr6.sin6_port != 0) {
645             connected = true;
646         }
647     }
648 
649     if (!connected) {
650         NETSTACK_LOGE("sock is not connect to remote, socket is %{public}d, errno is %{public}d",
651                       context->GetSocketFd(), errno);
652         context->SetErrorCode(errno);
653         return false;
654     }
655 
656     if (!PollSendData(context->GetSocketFd(), context->options.GetData().c_str(), context->options.GetData().size(),
657                       nullptr, 0)) {
658         NETSTACK_LOGE("send failed, socket is %{public}d, errno is %{public}d", context->GetSocketFd(), errno);
659         context->SetErrorCode(errno);
660         return false;
661     }
662     return true;
663 }
664 
UdpSendEvent(UdpSendContext * context)665 static bool UdpSendEvent(UdpSendContext *context)
666 {
667     sockaddr_in addr4 = {0};
668     sockaddr_in6 addr6 = {0};
669     sockaddr *addr = nullptr;
670     socklen_t len;
671     GetAddr(&context->options.address, &addr4, &addr6, &addr, &len);
672     if (addr == nullptr) {
673         NETSTACK_LOGE("get sock name failed, socket is %{public}d, errno is %{public}d", context->GetSocketFd(), errno);
674         context->SetErrorCode(ADDRESS_INVALID);
675         return false;
676     }
677 
678     if (!PollSendData(context->GetSocketFd(), context->options.GetData().c_str(), context->options.GetData().size(),
679                       addr, len)) {
680         NETSTACK_LOGE("send failed, socket is %{public}d, errno is %{public}d", context->GetSocketFd(), errno);
681         context->SetErrorCode(errno);
682         return false;
683     }
684     return true;
685 }
686 
ConfirmBufferSize(int sock)687 static int ConfirmBufferSize(int sock)
688 {
689     int bufferSize = DEFAULT_BUFFER_SIZE;
690     int opt = 0;
691     socklen_t optLen = sizeof(opt);
692     if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<void *>(&opt), &optLen) >= 0 && opt > 0) {
693         bufferSize = opt;
694     }
695     return bufferSize;
696 }
697 
PollRecvData(int sock,sockaddr * addr,socklen_t addrLen,const MessageCallback & callback)698 static void PollRecvData(int sock, sockaddr *addr, socklen_t addrLen, const MessageCallback &callback)
699 {
700     int bufferSize = ConfirmBufferSize(sock);
701 
702     auto deleter = [](char *s) { free(reinterpret_cast<void *>(s)); };
703     std::unique_ptr<char, decltype(deleter)> buf(reinterpret_cast<char *>(malloc(bufferSize)), deleter);
704     if (buf == nullptr) {
705         callback.OnError(NO_MEMORY);
706         return;
707     }
708 
709     auto addrDeleter = [](sockaddr *a) { free(reinterpret_cast<void *>(a)); };
710     std::unique_ptr<sockaddr, decltype(addrDeleter)> pAddr(addr, addrDeleter);
711 
712     nfds_t num = 1;
713     pollfd fds[1] = {{0}};
714     fds[0].fd = sock;
715     fds[0].events = 0;
716     fds[0].events |= POLLIN;
717 
718     while (true) {
719         int ret = poll(fds, num, DEFAULT_POLL_TIMEOUT);
720         if (ret < 0) {
721             NETSTACK_LOGE("poll to recv failed, socket is %{public}d, errno is %{public}d", sock, errno);
722             callback.OnError(errno);
723             return;
724         }
725         if (ret == 0) {
726             continue;
727         }
728         if (static_cast<int>(reinterpret_cast<uint64_t>(callback.GetEventManager()->GetData())) == 0) {
729             return;
730         }
731         (void)memset_s(buf.get(), bufferSize, 0, bufferSize);
732         socklen_t tempAddrLen = addrLen;
733         auto recvLen = recvfrom(sock, buf.get(), bufferSize, 0, addr, &tempAddrLen);
734         if (recvLen < 0) {
735             if (errno == EAGAIN) {
736                 continue;
737             }
738             NETSTACK_LOGE("recv failed, socket is %{public}d, errno is %{public}d", sock, errno);
739             callback.OnError(errno);
740             return;
741         }
742         if (recvLen == 0) {
743             continue;
744         }
745 
746         void *data = malloc(recvLen);
747         if (data == nullptr) {
748             callback.OnError(NO_MEMORY);
749             return;
750         }
751         if (memcpy_s(data, recvLen, buf.get(), recvLen) != EOK || !callback.OnMessage(data, recvLen, addr)) {
752             free(data);
753         }
754     }
755 }
756 
NonBlockConnect(int sock,sockaddr * addr,socklen_t addrLen,uint32_t timeoutMSec)757 static bool NonBlockConnect(int sock, sockaddr *addr, socklen_t addrLen, uint32_t timeoutMSec)
758 {
759     int ret = connect(sock, addr, addrLen);
760     if (ret >= 0) {
761         return true;
762     }
763     if (errno != EINPROGRESS) {
764         return false;
765     }
766 
767     fd_set set = {0};
768     FD_ZERO(&set);
769     FD_SET(sock, &set);
770     if (timeoutMSec == 0) {
771         timeoutMSec = DEFAULT_CONNECT_TIMEOUT;
772     }
773 
774     timeval timeout = {
775         .tv_sec = (timeoutMSec / MSEC_TO_USEC) % MAX_SEC,
776         .tv_usec = (timeoutMSec % MSEC_TO_USEC) * MSEC_TO_USEC,
777     };
778 
779     ret = select(sock + 1, nullptr, &set, nullptr, &timeout);
780     if (ret < 0) {
781         NETSTACK_LOGE("select failed, socket is %{public}d, errno is %{public}d", sock, errno);
782         return false;
783     } else if (ret == 0) {
784         NETSTACK_LOGE("timeout!");
785         return false;
786     }
787 
788     int err = 0;
789     socklen_t optLen = sizeof(err);
790     ret = getsockopt(sock, SOL_SOCKET, SO_ERROR, reinterpret_cast<void *>(&err), &optLen);
791     if (ret < 0) {
792         return false;
793     }
794     if (err != 0) {
795         NETSTACK_LOGE("NonBlockConnect exec failed, socket is %{public}d, errno is %{public}d", sock, errno);
796         return false;
797     }
798     return true;
799 }
800 
SetBaseOptions(int sock,ExtraOptionsBase * option)801 static bool SetBaseOptions(int sock, ExtraOptionsBase *option)
802 {
803     if (option->GetReceiveBufferSize() != 0) {
804         int size = (int)option->GetReceiveBufferSize();
805         if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<void *>(&size), sizeof(size)) < 0) {
806             return false;
807         }
808     }
809 
810     if (option->GetSendBufferSize() != 0) {
811         int size = (int)option->GetSendBufferSize();
812         if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<void *>(&size), sizeof(size)) < 0) {
813             return false;
814         }
815     }
816 
817     if (option->IsReuseAddress()) {
818         int reuse = 1;
819         if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<void *>(&reuse), sizeof(reuse)) < 0) {
820             return false;
821         }
822     }
823 
824     if (option->GetSocketTimeout() != 0) {
825         timeval timeout = {(int)option->GetSocketTimeout(), 0};
826         if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<void *>(&timeout), sizeof(timeout)) < 0) {
827             return false;
828         }
829         if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<void *>(&timeout), sizeof(timeout)) < 0) {
830             return false;
831         }
832     }
833 
834     return true;
835 }
836 
MakeTcpSocket(sa_family_t family)837 int MakeTcpSocket(sa_family_t family)
838 {
839     if (family != AF_INET && family != AF_INET6) {
840         return -1;
841     }
842     int sock = socket(family, SOCK_STREAM, IPPROTO_TCP);
843     NETSTACK_LOGI("new tcp socket is %{public}d", sock);
844     if (sock < 0) {
845         NETSTACK_LOGE("make tcp socket failed, errno is %{public}d", errno);
846         return -1;
847     }
848     if (!MakeNonBlock(sock)) {
849         close(sock);
850         return -1;
851     }
852     return sock;
853 }
854 
MakeUdpSocket(sa_family_t family)855 int MakeUdpSocket(sa_family_t family)
856 {
857     if (family != AF_INET && family != AF_INET6) {
858         return -1;
859     }
860     int sock = socket(family, SOCK_DGRAM, IPPROTO_UDP);
861     NETSTACK_LOGI("new udp socket is %{public}d", sock);
862     if (sock < 0) {
863         NETSTACK_LOGE("make udp socket failed, errno is %{public}d", errno);
864         return -1;
865     }
866     if (!MakeNonBlock(sock)) {
867         close(sock);
868         return -1;
869     }
870     return sock;
871 }
872 
ExecBind(BindContext * context)873 bool ExecBind(BindContext *context)
874 {
875     sockaddr_in addr4 = {0};
876     sockaddr_in6 addr6 = {0};
877     sockaddr *addr = nullptr;
878     socklen_t len;
879     GetAddr(&context->address_, &addr4, &addr6, &addr, &len);
880     if (addr == nullptr) {
881         NETSTACK_LOGE("addr family error, address invalid");
882         context->SetErrorCode(ADDRESS_INVALID);
883         return false;
884     }
885 
886     if (bind(context->GetSocketFd(), addr, len) < 0) {
887         if (errno != EADDRINUSE) {
888             NETSTACK_LOGE("bind failed, socket is %{public}d, errno is %{public}d", context->GetSocketFd(), errno);
889             context->SetErrorCode(errno);
890             return false;
891         }
892         if (addr->sa_family == AF_INET) {
893             NETSTACK_LOGI("distribute a random port");
894             addr4.sin_port = 0; /* distribute a random port */
895         } else if (addr->sa_family == AF_INET6) {
896             NETSTACK_LOGI("distribute a random port");
897             addr6.sin6_port = 0; /* distribute a random port */
898         }
899         if (bind(context->GetSocketFd(), addr, len) < 0) {
900             NETSTACK_LOGE("rebind failed, socket is %{public}d, errno is %{public}d", context->GetSocketFd(), errno);
901             context->SetErrorCode(errno);
902             return false;
903         }
904         NETSTACK_LOGI("rebind success");
905     }
906     NETSTACK_LOGI("bind success");
907 
908     return true;
909 }
910 
ExecUdpBind(BindContext * context)911 bool ExecUdpBind(BindContext *context)
912 {
913     if (!ExecBind(context)) {
914         return false;
915     }
916 
917     sockaddr_in addr4 = {0};
918     sockaddr_in6 addr6 = {0};
919     sockaddr *addr = nullptr;
920     socklen_t len;
921     GetAddr(&context->address_, &addr4, &addr6, &addr, &len);
922     if (addr == nullptr) {
923         NETSTACK_LOGE("get addr failed, addr family error, address invalid");
924         context->SetErrorCode(ADDRESS_INVALID);
925         return false;
926     }
927 
928     if (addr->sa_family == AF_INET) {
929         void *pTmpAddr = malloc(sizeof(addr4));
930         auto pAddr4 = reinterpret_cast<sockaddr *>(pTmpAddr);
931         if (pAddr4 == nullptr) {
932             NETSTACK_LOGE("no memory!");
933             return false;
934         }
935         NETSTACK_LOGI("copy ret = %{public}d", memcpy_s(pAddr4, sizeof(addr4), &addr4, sizeof(addr4)));
936         std::thread serviceThread(PollRecvData, context->GetSocketFd(), pAddr4, sizeof(addr4),
937                                   UdpMessageCallback(context->GetManager()));
938         serviceThread.detach();
939     } else if (addr->sa_family == AF_INET6) {
940         void *pTmpAddr = malloc(len);
941         auto pAddr6 = reinterpret_cast<sockaddr *>(pTmpAddr);
942         if (pAddr6 == nullptr) {
943             NETSTACK_LOGE("no memory!");
944             return false;
945         }
946         NETSTACK_LOGI("copy ret = %{public}d", memcpy_s(pAddr6, sizeof(addr6), &addr6, sizeof(addr6)));
947         std::thread serviceThread(PollRecvData, context->GetSocketFd(), pAddr6, sizeof(addr6),
948                                   UdpMessageCallback(context->GetManager()));
949         serviceThread.detach();
950     }
951 
952     return true;
953 }
954 
ExecUdpSend(UdpSendContext * context)955 bool ExecUdpSend(UdpSendContext *context)
956 {
957     if (!CommonUtils::HasInternetPermission()) {
958         context->SetPermissionDenied(true);
959         return false;
960     }
961     bool result = true;
962 #ifdef ENABLE_EVENT_HANDLER
963     auto manager = context->GetManager();
964     auto eventHandler = manager->GetNetstackEventHandler();
965     if (!eventHandler) {
966         NETSTACK_LOGE("netstack eventHandler is nullptr");
967         return false;
968     }
969     eventHandler->PostSyncTask([&result, context]() { result = UdpSendEvent(context); });
970     NapiUtils::CreateUvQueueWorkEnhanced(context->GetEnv(), context, SocketAsyncWork::UdpSendCallback);
971 #endif
972     return result;
973 }
974 
ExecTcpBind(BindContext * context)975 bool ExecTcpBind(BindContext *context)
976 {
977     return ExecBind(context);
978 }
979 
ExecConnect(ConnectContext * context)980 bool ExecConnect(ConnectContext *context)
981 {
982     if (!CommonUtils::HasInternetPermission()) {
983         context->SetPermissionDenied(true);
984         return false;
985     }
986 
987     sockaddr_in addr4 = {0};
988     sockaddr_in6 addr6 = {0};
989     sockaddr *addr = nullptr;
990     socklen_t len;
991     GetAddr(&context->options.address, &addr4, &addr6, &addr, &len);
992     if (addr == nullptr) {
993         NETSTACK_LOGE("addr family error, address invalid");
994         context->SetErrorCode(ADDRESS_INVALID);
995         return false;
996     }
997 
998     if (!NonBlockConnect(context->GetSocketFd(), addr, len, context->options.GetTimeout())) {
999         NETSTACK_LOGE("connect errno %{public}d", errno);
1000         context->SetErrorCode(errno);
1001         return false;
1002     }
1003 
1004     NETSTACK_LOGI("connect success");
1005     std::thread serviceThread(PollRecvData, context->GetSocketFd(), nullptr, 0,
1006                               TcpMessageCallback(context->GetManager()));
1007     serviceThread.detach();
1008     return true;
1009 }
1010 
ExecTcpSend(TcpSendContext * context)1011 bool ExecTcpSend(TcpSendContext *context)
1012 {
1013     if (!CommonUtils::HasInternetPermission()) {
1014         context->SetPermissionDenied(true);
1015         return false;
1016     }
1017 
1018     bool result = true;
1019 #ifdef ENABLE_EVENT_HANDLER
1020     auto manager = context->GetManager();
1021     auto eventHandler = manager->GetNetstackEventHandler();
1022     if (!eventHandler) {
1023         NETSTACK_LOGE("netstack eventHandler is nullptr");
1024         return false;
1025     }
1026     eventHandler->PostSyncTask([&result, context]() { result = TcpSendEvent(context); });
1027     NapiUtils::CreateUvQueueWorkEnhanced(context->GetEnv(), context, SocketAsyncWork::TcpSendCallback);
1028 #endif
1029     return result;
1030 }
1031 
ExecClose(CloseContext * context)1032 bool ExecClose(CloseContext *context)
1033 {
1034     if (!CommonUtils::HasInternetPermission()) {
1035         context->SetPermissionDenied(true);
1036         return false;
1037     }
1038 
1039     int ret = close(context->GetSocketFd());
1040     if (ret < 0) {
1041         NETSTACK_LOGE("sock closed failed , socket is %{public}d, errno is %{public}d", context->GetSocketFd(), errno);
1042         context->SetErrorCode(UNKNOW_ERROR);
1043         return false;
1044     }
1045     NETSTACK_LOGI("sock %{public}d closed success", context->GetSocketFd());
1046 
1047     context->state_.SetIsClose(true);
1048     context->SetSocketFd(0);
1049 
1050     return true;
1051 }
1052 
CheckClosed(GetStateContext * context,int & opt)1053 static bool CheckClosed(GetStateContext *context, int &opt)
1054 {
1055     socklen_t optLen = sizeof(int);
1056     int r = getsockopt(context->GetSocketFd(), SOL_SOCKET, SO_TYPE, &opt, &optLen);
1057     if (r < 0) {
1058         context->state_.SetIsClose(true);
1059         return true;
1060     }
1061     return false;
1062 }
1063 
CheckSocketFd(GetStateContext * context,sockaddr & sockAddr)1064 static bool CheckSocketFd(GetStateContext *context, sockaddr &sockAddr)
1065 {
1066     socklen_t len = sizeof(sockaddr);
1067     int ret = getsockname(context->GetSocketFd(), &sockAddr, &len);
1068     if (ret < 0) {
1069         context->SetErrorCode(errno);
1070         return false;
1071     }
1072     return true;
1073 }
1074 
ExecGetState(GetStateContext * context)1075 bool ExecGetState(GetStateContext *context)
1076 {
1077     if (!CommonUtils::HasInternetPermission()) {
1078         context->SetPermissionDenied(true);
1079         return false;
1080     }
1081 
1082     int opt;
1083     if (CheckClosed(context, opt)) {
1084         return true;
1085     }
1086 
1087     sockaddr sockAddr = {0};
1088     if (!CheckSocketFd(context, sockAddr)) {
1089         return false;
1090     }
1091 
1092     sockaddr_in addr4 = {0};
1093     sockaddr_in6 addr6 = {0};
1094     sockaddr *addr = nullptr;
1095     socklen_t addrLen;
1096     if (sockAddr.sa_family == AF_INET) {
1097         addr = reinterpret_cast<sockaddr *>(&addr4);
1098         addrLen = sizeof(addr4);
1099     } else if (sockAddr.sa_family == AF_INET6) {
1100         addr = reinterpret_cast<sockaddr *>(&addr6);
1101         addrLen = sizeof(addr6);
1102     }
1103 
1104     if (addr == nullptr) {
1105         NETSTACK_LOGE("addr family error, address invalid");
1106         context->SetErrorCode(ADDRESS_INVALID);
1107         return false;
1108     }
1109 
1110     (void)memset_s(addr, addrLen, 0, addrLen);
1111     socklen_t len = addrLen;
1112     int ret = getsockname(context->GetSocketFd(), addr, &len);
1113     if (ret < 0) {
1114         context->SetErrorCode(errno);
1115         return false;
1116     }
1117 
1118     SetIsBound(sockAddr.sa_family, context, &addr4, &addr6);
1119 
1120     if (opt != SOCK_STREAM) {
1121         return true;
1122     }
1123 
1124     (void)memset_s(addr, addrLen, 0, addrLen);
1125     len = addrLen;
1126     (void)getpeername(context->GetSocketFd(), addr, &len);
1127     SetIsConnected(sockAddr.sa_family, context, &addr4, &addr6);
1128     return true;
1129 }
1130 
IsAddressAndRetValid(const int & ret,const std::string & address,GetRemoteAddressContext * context)1131 bool IsAddressAndRetValid(const int &ret, const std::string &address, GetRemoteAddressContext *context)
1132 {
1133     if (ret < 0) {
1134         context->SetErrorCode(errno);
1135         return false;
1136     }
1137     if (address.empty()) {
1138         NETSTACK_LOGE("addr family error, address invalid");
1139         context->SetErrorCode(ADDRESS_INVALID);
1140         return false;
1141     }
1142     return true;
1143 }
1144 
ExecGetRemoteAddress(GetRemoteAddressContext * context)1145 bool ExecGetRemoteAddress(GetRemoteAddressContext *context)
1146 {
1147     if (!CommonUtils::HasInternetPermission()) {
1148         context->SetPermissionDenied(true);
1149         return false;
1150     }
1151 
1152     sockaddr sockAddr = {0};
1153     socklen_t len = sizeof(sockaddr);
1154     int ret = getsockname(context->GetSocketFd(), &sockAddr, &len);
1155     if (ret < 0) {
1156         context->SetErrorCode(errno);
1157         return false;
1158     }
1159 
1160     if (sockAddr.sa_family == AF_INET) {
1161         sockaddr_in addr4 = {0};
1162         socklen_t len4 = sizeof(sockaddr_in);
1163 
1164         ret = getpeername(context->GetSocketFd(), reinterpret_cast<sockaddr *>(&addr4), &len4);
1165         std::string address = MakeAddressString(reinterpret_cast<sockaddr *>(&addr4));
1166         if (!IsAddressAndRetValid(ret, address, context)) {
1167             return false;
1168         }
1169         context->address_.SetAddress(address);
1170         context->address_.SetFamilyBySaFamily(sockAddr.sa_family);
1171         context->address_.SetPort(ntohs(addr4.sin_port));
1172         return true;
1173     } else if (sockAddr.sa_family == AF_INET6) {
1174         sockaddr_in6 addr6 = {0};
1175         socklen_t len6 = sizeof(sockaddr_in6);
1176 
1177         ret = getpeername(context->GetSocketFd(), reinterpret_cast<sockaddr *>(&addr6), &len6);
1178         std::string address = MakeAddressString(reinterpret_cast<sockaddr *>(&addr6));
1179         if (!IsAddressAndRetValid(ret, address, context)) {
1180             return false;
1181         }
1182         context->address_.SetAddress(address);
1183         context->address_.SetFamilyBySaFamily(sockAddr.sa_family);
1184         context->address_.SetPort(ntohs(addr6.sin6_port));
1185         return true;
1186     }
1187 
1188     return false;
1189 }
1190 
ExecTcpSetExtraOptions(TcpSetExtraOptionsContext * context)1191 bool ExecTcpSetExtraOptions(TcpSetExtraOptionsContext *context)
1192 {
1193     if (!CommonUtils::HasInternetPermission()) {
1194         context->SetPermissionDenied(true);
1195         return false;
1196     }
1197 
1198     if (!SetBaseOptions(context->GetSocketFd(), &context->options_)) {
1199         context->SetErrorCode(errno);
1200         return false;
1201     }
1202 
1203     if (context->options_.IsKeepAlive()) {
1204         int keepalive = 1;
1205         if (setsockopt(context->GetSocketFd(), SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)) < 0) {
1206             context->SetErrorCode(errno);
1207             return false;
1208         }
1209     }
1210 
1211     if (context->options_.IsOOBInline()) {
1212         int oobInline = 1;
1213         if (setsockopt(context->GetSocketFd(), SOL_SOCKET, SO_OOBINLINE, &oobInline, sizeof(oobInline)) < 0) {
1214             context->SetErrorCode(errno);
1215             return false;
1216         }
1217     }
1218 
1219     if (context->options_.IsTCPNoDelay()) {
1220         int tcpNoDelay = 1;
1221         if (setsockopt(context->GetSocketFd(), IPPROTO_TCP, TCP_NODELAY, &tcpNoDelay, sizeof(tcpNoDelay)) < 0) {
1222             context->SetErrorCode(errno);
1223             return false;
1224         }
1225     }
1226 
1227     linger soLinger = {0};
1228     soLinger.l_onoff = context->options_.socketLinger.IsOn();
1229     soLinger.l_linger = (int)context->options_.socketLinger.GetLinger();
1230     if (setsockopt(context->GetSocketFd(), SOL_SOCKET, SO_LINGER, &soLinger, sizeof(soLinger)) < 0) {
1231         context->SetErrorCode(errno);
1232         return false;
1233     }
1234 
1235     return true;
1236 }
1237 
ExecUdpSetExtraOptions(UdpSetExtraOptionsContext * context)1238 bool ExecUdpSetExtraOptions(UdpSetExtraOptionsContext *context)
1239 {
1240     if (!CommonUtils::HasInternetPermission()) {
1241         context->SetPermissionDenied(true);
1242         return false;
1243     }
1244 
1245     if (!SetBaseOptions(context->GetSocketFd(), &context->options)) {
1246         context->SetErrorCode(errno);
1247         return false;
1248     }
1249 
1250     if (context->options.IsBroadcast()) {
1251         int broadcast = 1;
1252         if (setsockopt(context->GetSocketFd(), SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) < 0) {
1253             context->SetErrorCode(errno);
1254             return false;
1255         }
1256     }
1257 
1258     return true;
1259 }
1260 
ExecTcpGetSocketFd(GetSocketFdContext * context)1261 bool ExecTcpGetSocketFd(GetSocketFdContext *context)
1262 {
1263     return true;
1264 }
1265 
ExecUdpGetSocketFd(GetSocketFdContext * context)1266 bool ExecUdpGetSocketFd(GetSocketFdContext *context)
1267 {
1268     return true;
1269 }
1270 
GetIPv4Address(TcpServerGetRemoteAddressContext * context,int32_t fd,sockaddr sockAddr)1271 static bool GetIPv4Address(TcpServerGetRemoteAddressContext *context, int32_t fd, sockaddr sockAddr)
1272 {
1273     sockaddr_in addr4 = {0};
1274     socklen_t len4 = sizeof(sockaddr_in);
1275 
1276     int ret = getpeername(fd, reinterpret_cast<sockaddr *>(&addr4), &len4);
1277     if (ret < 0) {
1278         context->SetErrorCode(errno);
1279         return false;
1280     }
1281 
1282     std::string address = MakeAddressString(reinterpret_cast<sockaddr *>(&addr4));
1283     if (address.empty()) {
1284         NETSTACK_LOGE("addr family error, address invalid");
1285         context->SetErrorCode(ADDRESS_INVALID);
1286         return false;
1287     }
1288     context->address_.SetAddress(address);
1289     context->address_.SetFamilyBySaFamily(sockAddr.sa_family);
1290     context->address_.SetPort(ntohs(addr4.sin_port));
1291     return true;
1292 }
1293 
GetIPv6Address(TcpServerGetRemoteAddressContext * context,int32_t fd,sockaddr sockAddr)1294 static bool GetIPv6Address(TcpServerGetRemoteAddressContext *context, int32_t fd, sockaddr sockAddr)
1295 {
1296     sockaddr_in6 addr6 = {0};
1297     socklen_t len6 = sizeof(sockaddr_in6);
1298 
1299     int ret = getpeername(fd, reinterpret_cast<sockaddr *>(&addr6), &len6);
1300     if (ret < 0) {
1301         context->SetErrorCode(errno);
1302         return false;
1303     }
1304 
1305     std::string address = MakeAddressString(reinterpret_cast<sockaddr *>(&addr6));
1306     if (address.empty()) {
1307         NETSTACK_LOGE("addr family error, address invalid");
1308         context->SetErrorCode(ADDRESS_INVALID);
1309         return false;
1310     }
1311     context->address_.SetAddress(address);
1312     context->address_.SetFamilyBySaFamily(sockAddr.sa_family);
1313     context->address_.SetPort(ntohs(addr6.sin6_port));
1314     return true;
1315 }
1316 
ExecTcpConnectionGetRemoteAddress(TcpServerGetRemoteAddressContext * context)1317 bool ExecTcpConnectionGetRemoteAddress(TcpServerGetRemoteAddressContext *context)
1318 {
1319     if (!CommonUtils::HasInternetPermission()) {
1320         context->SetPermissionDenied(true);
1321         return false;
1322     }
1323 
1324     int32_t clientFd = -1;
1325     bool fdValid = false;
1326 
1327     {
1328         std::lock_guard<std::mutex> lock(g_mutex);
1329         auto iter = g_clientFDs.find(context->clientId_);
1330         if (iter != g_clientFDs.end()) {
1331             fdValid = true;
1332             clientFd = iter->second;
1333         } else {
1334             NETSTACK_LOGE("not find clientId");
1335         }
1336     }
1337 
1338     if (!fdValid) {
1339         NETSTACK_LOGE("client fd is invalid");
1340         context->SetError(OTHER_ERROR, "client fd is invalid");
1341         return false;
1342     }
1343 
1344     sockaddr sockAddr = {0};
1345     socklen_t len = sizeof(sockaddr);
1346     int ret = getsockname(clientFd, &sockAddr, &len);
1347     if (ret < 0) {
1348         context->SetError(errno, strerror(errno));
1349         return false;
1350     }
1351 
1352     if (sockAddr.sa_family == AF_INET) {
1353         return GetIPv4Address(context, clientFd, sockAddr);
1354     } else if (sockAddr.sa_family == AF_INET6) {
1355         return GetIPv6Address(context, clientFd, sockAddr);
1356     }
1357 
1358     return false;
1359 }
1360 
IsRemoteConnect(TcpServerSendContext * context,int32_t clientFd)1361 static bool IsRemoteConnect(TcpServerSendContext *context, int32_t clientFd)
1362 {
1363     sockaddr sockAddr = {0};
1364     socklen_t len = sizeof(sockaddr);
1365     if (getsockname(clientFd, &sockAddr, &len) < 0) {
1366         NETSTACK_LOGE("get sock name failed, address invalid");
1367         context->SetErrorCode(ADDRESS_INVALID);
1368         return false;
1369     }
1370     bool connected = false;
1371     if (sockAddr.sa_family == AF_INET) {
1372         sockaddr_in addr4 = {0};
1373         socklen_t len4 = sizeof(addr4);
1374         int ret = getpeername(clientFd, reinterpret_cast<sockaddr *>(&addr4), &len4);
1375         if (ret >= 0 && addr4.sin_port != 0) {
1376             connected = true;
1377         }
1378     } else if (sockAddr.sa_family == AF_INET6) {
1379         sockaddr_in6 addr6 = {0};
1380         socklen_t len6 = sizeof(addr6);
1381         int ret = getpeername(clientFd, reinterpret_cast<sockaddr *>(&addr6), &len6);
1382         if (ret >= 0 && addr6.sin6_port != 0) {
1383             connected = true;
1384         }
1385     }
1386 
1387     if (!connected) {
1388         NETSTACK_LOGE("sock is not connect to remote, socket is %{public}d, errno is %{public}d", clientFd, errno);
1389         context->SetErrorCode(errno);
1390         return false;
1391     }
1392     return true;
1393 }
1394 
ExecTcpConnectionSend(TcpServerSendContext * context)1395 bool ExecTcpConnectionSend(TcpServerSendContext *context)
1396 {
1397     if (!CommonUtils::HasInternetPermission()) {
1398         context->SetPermissionDenied(true);
1399         return false;
1400     }
1401 
1402     int32_t clientFd = -1;
1403     bool fdValid = false;
1404 
1405     {
1406         std::lock_guard<std::mutex> lock(g_mutex);
1407         auto iter = g_clientFDs.find(context->clientId_);
1408         if (iter != g_clientFDs.end()) {
1409             fdValid = true;
1410             clientFd = iter->second;
1411         } else {
1412             NETSTACK_LOGE("not find clientId");
1413         }
1414     }
1415 
1416     if (!fdValid) {
1417         NETSTACK_LOGE("client fd is invalid");
1418         context->SetError(OTHER_ERROR, "client fd is invalid");
1419         return false;
1420     }
1421 
1422     std::string encoding = context->options.GetEncoding();
1423     (void)encoding;
1424     /* no use for now */
1425 
1426     if (!IsRemoteConnect(context, clientFd)) {
1427         return false;
1428     }
1429 
1430     if (!PollSendData(clientFd, context->options.GetData().c_str(), context->options.GetData().size(), nullptr, 0)) {
1431         NETSTACK_LOGE("send failed, , socket is %{public}d, errno is %{public}d", clientFd, errno);
1432         context->SetError(errno, strerror(errno));
1433         return false;
1434     }
1435     return true;
1436 }
1437 
ExecTcpConnectionClose(TcpServerCloseContext * context)1438 bool ExecTcpConnectionClose(TcpServerCloseContext *context)
1439 {
1440     if (!CommonUtils::HasInternetPermission()) {
1441         context->SetPermissionDenied(true);
1442         return false;
1443     }
1444     bool fdValid = false;
1445 
1446     {
1447         std::lock_guard<std::mutex> lock(g_mutex);
1448         auto iter = g_clientFDs.find(context->clientId_);
1449         if (iter != g_clientFDs.end()) {
1450             fdValid = true;
1451         } else {
1452             NETSTACK_LOGE("not find clientId");
1453         }
1454     }
1455 
1456     if (!fdValid) {
1457         NETSTACK_LOGE("client fd is invalid");
1458         context->SetError(OTHER_ERROR, "client fd is invalid");
1459         return false;
1460     }
1461 
1462     return true;
1463 }
1464 
ServerBind(TcpServerListenContext * context)1465 static bool ServerBind(TcpServerListenContext *context)
1466 {
1467     sockaddr_in addr4 = {0};
1468     sockaddr_in6 addr6 = {0};
1469     sockaddr *addr = nullptr;
1470     socklen_t len;
1471     GetAddr(&context->address_, &addr4, &addr6, &addr, &len);
1472     if (addr == nullptr) {
1473         NETSTACK_LOGE("addr family error, address invalid");
1474         context->SetError(ADDRESS_INVALID, "addr family error, address invalid");
1475         return false;
1476     }
1477 
1478     if (bind(context->GetSocketFd(), addr, len) < 0) {
1479         if (errno != EADDRINUSE) {
1480             NETSTACK_LOGE("bind failed, socket is %{public}d, errno is %{public}d", context->GetSocketFd(), errno);
1481             context->SetError(errno, strerror(errno));
1482             return false;
1483         }
1484         if (addr->sa_family == AF_INET) {
1485             NETSTACK_LOGI("distribute a random port");
1486             addr4.sin_port = 0; /* distribute a random port */
1487         } else if (addr->sa_family == AF_INET6) {
1488             NETSTACK_LOGI("distribute a random port");
1489             addr6.sin6_port = 0; /* distribute a random port */
1490         }
1491         if (bind(context->GetSocketFd(), addr, len) < 0) {
1492             NETSTACK_LOGE("rebind failed, socket is %{public}d, errno is %{public}d", context->GetSocketFd(), errno);
1493             context->SetError(errno, strerror(errno));
1494             return false;
1495         }
1496         NETSTACK_LOGI("rebind success");
1497     }
1498     NETSTACK_LOGI("bind success");
1499 
1500     return true;
1501 }
1502 
IsClientFdClosed(int32_t clientFd)1503 static bool IsClientFdClosed(int32_t clientFd)
1504 {
1505     return (fcntl(clientFd, F_GETFL) == -1 && errno == EBADF);
1506 }
1507 
RemoveClientConnection(int32_t clientId)1508 static void RemoveClientConnection(int32_t clientId)
1509 {
1510     std::lock_guard<std::mutex> lock(g_mutex);
1511     for (auto it = g_clientFDs.begin(); it != g_clientFDs.end(); ++it) {
1512         if (it->first == clientId) {
1513             NETSTACK_LOGI("remove clientfd and eventmanager clientid: %{public}d clientFd:%{public}d", it->second,
1514                           it->first);
1515             if (!IsClientFdClosed(it->second)) {
1516                 NETSTACK_LOGE("connectFD not close should close");
1517                 shutdown(it->second, SHUT_RDWR);
1518                 close(it->second);
1519             }
1520 
1521             g_clientFDs.erase(it->first);
1522             break;
1523         }
1524     }
1525 }
1526 
ClientHandler(int32_t clientId,sockaddr * addr,socklen_t addrLen,const TcpMessageCallback & callback)1527 static void ClientHandler(int32_t clientId, sockaddr *addr, socklen_t addrLen, const TcpMessageCallback &callback)
1528 {
1529     char buffer[DEFAULT_BUFFER_SIZE];
1530 
1531     EventManager *manager = nullptr;
1532     {
1533         std::unique_lock<std::mutex> lock(g_mutex);
1534         g_cv.wait(lock, [&manager, &clientId]() {
1535             auto iter = g_clientEventManagers.find(clientId);
1536             if (iter != g_clientEventManagers.end()) {
1537                 manager = iter->second;
1538                 NETSTACK_LOGE("manager!=nullptr");
1539                 return true;
1540             } else {
1541                 NETSTACK_LOGE("iter==g_clientEventManagers.end()");
1542                 return false;
1543             }
1544         });
1545     }
1546 
1547     auto connectFD = g_clientFDs[clientId]; // std::lock_guard<std::mutex> lock(g_mutex);]
1548 
1549     while (true) {
1550         if (memset_s(buffer, sizeof(buffer), 0, sizeof(buffer)) != EOK) {
1551             NETSTACK_LOGE("memset_s failed!");
1552             break;
1553         }
1554         int32_t recvSize = recv(connectFD, buffer, sizeof(buffer), 0);
1555         NETSTACK_LOGI("ClientRecv: fd is %{public}d, buf is %{public}s, size is %{public}d bytes", connectFD, buffer,
1556                       recvSize);
1557         if (recvSize <= 0) {
1558             NETSTACK_LOGE("close ClientHandler: recvSize is %{public}d, errno is %{public}d", recvSize, errno);
1559 
1560             if (errno != EAGAIN) {
1561                 callback.OnCloseMessage(manager);
1562                 RemoveClientConnection(clientId);
1563                 break;
1564             }
1565         } else {
1566             void *data = malloc(recvSize);
1567             if (data == nullptr) {
1568                 callback.OnError(NO_MEMORY);
1569                 break;
1570             }
1571             if (memcpy_s(data, recvSize, buffer, recvSize) != EOK ||
1572                 !callback.OnMessage(connectFD, data, recvSize, addr, manager)) {
1573                 free(data);
1574             }
1575         }
1576     }
1577 }
1578 
AcceptRecvData(int sock,sockaddr * addr,socklen_t addrLen,const TcpMessageCallback & callback)1579 static void AcceptRecvData(int sock, sockaddr *addr, socklen_t addrLen, const TcpMessageCallback &callback)
1580 {
1581     while (true) {
1582         sockaddr_in clientAddress;
1583         socklen_t clientAddrLength = sizeof(clientAddress);
1584         int32_t connectFD = accept(sock, reinterpret_cast<sockaddr *>(&clientAddress), &clientAddrLength);
1585         if (connectFD < 0) {
1586             continue;
1587         }
1588         {
1589             std::lock_guard<std::mutex> lock(g_mutex);
1590             if (g_clientFDs.size() >= MAX_CLIENTS) {
1591                 NETSTACK_LOGE("Maximum number of clients reached, connection rejected");
1592                 close(connectFD);
1593                 continue;
1594             }
1595             NETSTACK_LOGI("Server accept new client SUCCESS, fd = %{public}d", connectFD);
1596             g_userCounter++;
1597             g_clientFDs[g_userCounter] = connectFD;
1598         }
1599         callback.OnTcpConnectionMessage(g_userCounter);
1600         int clientId = g_userCounter;
1601         std::thread handlerThread(ClientHandler, clientId, nullptr, 0, callback);
1602 #if defined(MAC_PLATFORM) || defined(IOS_PLATFORM)
1603         pthread_setname_np(TCP_SERVER_HANDLE_CLIENT);
1604 #else
1605         pthread_setname_np(handlerThread.native_handle(), TCP_SERVER_HANDLE_CLIENT);
1606 #endif
1607         handlerThread.detach();
1608     }
1609 }
1610 
ExecTcpServerListen(TcpServerListenContext * context)1611 bool ExecTcpServerListen(TcpServerListenContext *context)
1612 {
1613     int ret = 0;
1614     if (!ServerBind(context)) {
1615         return false;
1616     }
1617 
1618     ret = listen(context->GetSocketFd(), USER_LIMIT);
1619     if (ret < 0) {
1620         NETSTACK_LOGE("tcp server listen error");
1621         return false;
1622     }
1623 
1624     NETSTACK_LOGI("listen success");
1625     std::thread serviceThread(AcceptRecvData, context->GetSocketFd(), nullptr, 0,
1626                               TcpMessageCallback(context->GetManager()));
1627 #if defined(MAC_PLATFORM) || defined(IOS_PLATFORM)
1628     pthread_setname_np(TCP_SERVER_ACCEPT_RECV_DATA);
1629 #else
1630     pthread_setname_np(serviceThread.native_handle(), TCP_SERVER_ACCEPT_RECV_DATA);
1631 #endif
1632     serviceThread.detach();
1633     return true;
1634 }
1635 
ExecTcpServerSetExtraOptions(TcpServerSetExtraOptionsContext * context)1636 bool ExecTcpServerSetExtraOptions(TcpServerSetExtraOptionsContext *context)
1637 {
1638     if (!CommonUtils::HasInternetPermission()) {
1639         context->SetPermissionDenied(true);
1640         return false;
1641     }
1642 
1643     if (!SetBaseOptions(context->GetSocketFd(), &context->options_)) {
1644         context->SetError(errno, strerror(errno));
1645         return false;
1646     }
1647 
1648     if (context->options_.IsKeepAlive()) {
1649         int keepalive = 1;
1650         if (setsockopt(context->GetSocketFd(), SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)) < 0) {
1651             context->SetError(errno, strerror(errno));
1652             return false;
1653         }
1654     }
1655 
1656     if (context->options_.IsOOBInline()) {
1657         int oobInline = 1;
1658         if (setsockopt(context->GetSocketFd(), SOL_SOCKET, SO_OOBINLINE, &oobInline, sizeof(oobInline)) < 0) {
1659             context->SetError(errno, strerror(errno));
1660             return false;
1661         }
1662     }
1663 
1664     if (context->options_.IsTCPNoDelay()) {
1665         int tcpNoDelay = 1;
1666         if (setsockopt(context->GetSocketFd(), IPPROTO_TCP, TCP_NODELAY, &tcpNoDelay, sizeof(tcpNoDelay)) < 0) {
1667             context->SetError(errno, strerror(errno));
1668             return false;
1669         }
1670     }
1671 
1672     linger soLinger = {0};
1673     soLinger.l_onoff = context->options_.socketLinger.IsOn();
1674     soLinger.l_linger = (int)context->options_.socketLinger.GetLinger();
1675     if (setsockopt(context->GetSocketFd(), SOL_SOCKET, SO_LINGER, &soLinger, sizeof(soLinger)) < 0) {
1676         context->SetError(errno, strerror(errno));
1677         return false;
1678     }
1679 
1680     return true;
1681 }
1682 
SetIsConnected(TcpServerGetStateContext * context)1683 static void SetIsConnected(TcpServerGetStateContext *context)
1684 {
1685     std::lock_guard<std::mutex> lock(g_mutex);
1686     if (g_clientFDs.empty()) {
1687         context->state_.SetIsConnected(false);
1688     } else {
1689         context->state_.SetIsConnected(true);
1690     }
1691 }
1692 
SetIsBound(sa_family_t family,TcpServerGetStateContext * context,const sockaddr_in * addr4,const sockaddr_in6 * addr6)1693 static void SetIsBound(sa_family_t family, TcpServerGetStateContext *context, const sockaddr_in *addr4,
1694                        const sockaddr_in6 *addr6)
1695 {
1696     if (family == AF_INET) {
1697         context->state_.SetIsBound(ntohs(addr4->sin_port) != 0);
1698     } else if (family == AF_INET6) {
1699         context->state_.SetIsBound(ntohs(addr6->sin6_port) != 0);
1700     }
1701 }
1702 
ExecTcpServerGetState(TcpServerGetStateContext * context)1703 bool ExecTcpServerGetState(TcpServerGetStateContext *context)
1704 {
1705     if (!CommonUtils::HasInternetPermission()) {
1706         context->SetPermissionDenied(true);
1707         return false;
1708     }
1709 
1710     int opt;
1711     socklen_t optLen = sizeof(int);
1712     if (getsockopt(context->GetSocketFd(), SOL_SOCKET, SO_TYPE, &opt, &optLen) < 0) {
1713         context->state_.SetIsClose(true);
1714         return true;
1715     }
1716 
1717     sockaddr sockAddr = {0};
1718     socklen_t len = sizeof(sockaddr);
1719     if (getsockname(context->GetSocketFd(), &sockAddr, &len) < 0) {
1720         context->SetError(errno, strerror(errno));
1721         return false;
1722     }
1723 
1724     sockaddr_in addr4 = {0};
1725     sockaddr_in6 addr6 = {0};
1726     sockaddr *addr = nullptr;
1727     socklen_t addrLen;
1728     if (sockAddr.sa_family == AF_INET) {
1729         addr = reinterpret_cast<sockaddr *>(&addr4);
1730         addrLen = sizeof(addr4);
1731     } else if (sockAddr.sa_family == AF_INET6) {
1732         addr = reinterpret_cast<sockaddr *>(&addr6);
1733         addrLen = sizeof(addr6);
1734     }
1735 
1736     if (addr == nullptr) {
1737         NETSTACK_LOGE("addr family error, address invalid");
1738         context->SetErrorCode(ADDRESS_INVALID);
1739         return false;
1740     }
1741 
1742     if (memset_s(addr, addrLen, 0, addrLen) != EOK) {
1743         NETSTACK_LOGE("memset_s failed!");
1744         return false;
1745     }
1746     len = addrLen;
1747     if (getsockname(context->GetSocketFd(), addr, &len) < 0) {
1748         context->SetError(errno, strerror(errno));
1749         return false;
1750     }
1751 
1752     SetIsBound(sockAddr.sa_family, context, &addr4, &addr6);
1753 
1754     if (opt != SOCK_STREAM) {
1755         return true;
1756     }
1757     SetIsConnected(context);
1758     return true;
1759 }
1760 
BindCallback(BindContext * context)1761 napi_value BindCallback(BindContext *context)
1762 {
1763     context->Emit(EVENT_LISTENING, std::make_pair(NapiUtils::GetUndefined(context->GetEnv()),
1764                                                   NapiUtils::GetUndefined(context->GetEnv())));
1765     return NapiUtils::GetUndefined(context->GetEnv());
1766 }
1767 
UdpSendCallback(UdpSendContext * context)1768 napi_value UdpSendCallback(UdpSendContext *context)
1769 {
1770     return NapiUtils::GetUndefined(context->GetEnv());
1771 }
1772 
ConnectCallback(ConnectContext * context)1773 napi_value ConnectCallback(ConnectContext *context)
1774 {
1775     context->Emit(EVENT_CONNECT, std::make_pair(NapiUtils::GetUndefined(context->GetEnv()),
1776                                                 NapiUtils::GetUndefined(context->GetEnv())));
1777     return NapiUtils::GetUndefined(context->GetEnv());
1778 }
1779 
TcpSendCallback(TcpSendContext * context)1780 napi_value TcpSendCallback(TcpSendContext *context)
1781 {
1782     return NapiUtils::GetUndefined(context->GetEnv());
1783 }
1784 
CloseCallback(CloseContext * context)1785 napi_value CloseCallback(CloseContext *context)
1786 {
1787     context->Emit(EVENT_CLOSE, std::make_pair(NapiUtils::GetUndefined(context->GetEnv()),
1788                                               NapiUtils::GetUndefined(context->GetEnv())));
1789     return NapiUtils::GetUndefined(context->GetEnv());
1790 }
1791 
GetStateCallback(GetStateContext * context)1792 napi_value GetStateCallback(GetStateContext *context)
1793 {
1794     napi_value obj = NapiUtils::CreateObject(context->GetEnv());
1795     if (NapiUtils::GetValueType(context->GetEnv(), obj) != napi_object) {
1796         return NapiUtils::GetUndefined(context->GetEnv());
1797     }
1798 
1799     NapiUtils::SetBooleanProperty(context->GetEnv(), obj, KEY_IS_BOUND, context->state_.IsBound());
1800     NapiUtils::SetBooleanProperty(context->GetEnv(), obj, KEY_IS_CLOSE, context->state_.IsClose());
1801     NapiUtils::SetBooleanProperty(context->GetEnv(), obj, KEY_IS_CONNECTED, context->state_.IsConnected());
1802 
1803     return obj;
1804 }
1805 
GetRemoteAddressCallback(GetRemoteAddressContext * context)1806 napi_value GetRemoteAddressCallback(GetRemoteAddressContext *context)
1807 {
1808     napi_value obj = NapiUtils::CreateObject(context->GetEnv());
1809     if (NapiUtils::GetValueType(context->GetEnv(), obj) != napi_object) {
1810         return NapiUtils::GetUndefined(context->GetEnv());
1811     }
1812 
1813     NapiUtils::SetStringPropertyUtf8(context->GetEnv(), obj, KEY_ADDRESS, context->address_.GetAddress());
1814     NapiUtils::SetUint32Property(context->GetEnv(), obj, KEY_FAMILY, context->address_.GetJsValueFamily());
1815     NapiUtils::SetUint32Property(context->GetEnv(), obj, KEY_PORT, context->address_.GetPort());
1816 
1817     return obj;
1818 }
1819 
TcpSetExtraOptionsCallback(TcpSetExtraOptionsContext * context)1820 napi_value TcpSetExtraOptionsCallback(TcpSetExtraOptionsContext *context)
1821 {
1822     return NapiUtils::GetUndefined(context->GetEnv());
1823 }
1824 
UdpSetExtraOptionsCallback(UdpSetExtraOptionsContext * context)1825 napi_value UdpSetExtraOptionsCallback(UdpSetExtraOptionsContext *context)
1826 {
1827     return NapiUtils::GetUndefined(context->GetEnv());
1828 }
1829 
TcpGetSocketFdCallback(GetSocketFdContext * context)1830 napi_value TcpGetSocketFdCallback(GetSocketFdContext *context)
1831 {
1832     int sockFd = context->GetSocketFd();
1833     if (sockFd == -1) {
1834         return NapiUtils::GetUndefined(context->GetEnv());
1835     }
1836     return NapiUtils::CreateUint32(context->GetEnv(), sockFd);
1837 }
1838 
UdpGetSocketFdCallback(GetSocketFdContext * context)1839 napi_value UdpGetSocketFdCallback(GetSocketFdContext *context)
1840 {
1841     int sockFd = context->GetSocketFd();
1842     if (sockFd == -1) {
1843         return NapiUtils::GetUndefined(context->GetEnv());
1844     }
1845     return NapiUtils::CreateUint32(context->GetEnv(), sockFd);
1846 }
1847 
TcpConnectionSendCallback(TcpServerSendContext * context)1848 napi_value TcpConnectionSendCallback(TcpServerSendContext *context)
1849 {
1850     return NapiUtils::GetUndefined(context->GetEnv());
1851 }
1852 
TcpConnectionCloseCallback(TcpServerCloseContext * context)1853 napi_value TcpConnectionCloseCallback(TcpServerCloseContext *context)
1854 {
1855     int32_t clientFd = -1;
1856 
1857     {
1858         std::lock_guard<std::mutex> lock(g_mutex);
1859         auto iter = g_clientFDs.find(context->clientId_);
1860         if (iter != g_clientFDs.end()) {
1861             clientFd = iter->second;
1862         } else {
1863             NETSTACK_LOGE("not find clientId");
1864         }
1865     }
1866 
1867     if (shutdown(clientFd, SHUT_RDWR) != 0) {
1868         NETSTACK_LOGE("socket shutdown failed, socket is %{public}d, errno is %{public}d", clientFd, errno);
1869     }
1870     int ret = close(clientFd);
1871     if (ret < 0) {
1872         NETSTACK_LOGE("sock closed failed, socket is %{public}d, errno is %{public}d", clientFd, errno);
1873     } else {
1874         NETSTACK_LOGI("sock %{public}d closed success", clientFd);
1875         RemoveClientConnection(context->clientId_);
1876         context->Emit(EVENT_CLOSE, std::make_pair(NapiUtils::GetUndefined(context->GetEnv()),
1877                                                   NapiUtils::GetUndefined(context->GetEnv())));
1878     }
1879 
1880     return NapiUtils::GetUndefined(context->GetEnv());
1881 }
1882 
TcpConnectionGetRemoteAddressCallback(TcpServerGetRemoteAddressContext * context)1883 napi_value TcpConnectionGetRemoteAddressCallback(TcpServerGetRemoteAddressContext *context)
1884 {
1885     napi_value obj = NapiUtils::CreateObject(context->GetEnv());
1886     if (NapiUtils::GetValueType(context->GetEnv(), obj) != napi_object) {
1887         return NapiUtils::GetUndefined(context->GetEnv());
1888     }
1889 
1890     NapiUtils::SetStringPropertyUtf8(context->GetEnv(), obj, KEY_ADDRESS, context->address_.GetAddress());
1891     NapiUtils::SetUint32Property(context->GetEnv(), obj, KEY_FAMILY, context->address_.GetJsValueFamily());
1892     NapiUtils::SetUint32Property(context->GetEnv(), obj, KEY_PORT, context->address_.GetPort());
1893 
1894     return obj;
1895 }
1896 
ListenCallback(TcpServerListenContext * context)1897 napi_value ListenCallback(TcpServerListenContext *context)
1898 {
1899     return NapiUtils::GetUndefined(context->GetEnv());
1900 }
1901 
TcpServerSetExtraOptionsCallback(TcpServerSetExtraOptionsContext * context)1902 napi_value TcpServerSetExtraOptionsCallback(TcpServerSetExtraOptionsContext *context)
1903 {
1904     return NapiUtils::GetUndefined(context->GetEnv());
1905 }
1906 
TcpServerGetStateCallback(TcpServerGetStateContext * context)1907 napi_value TcpServerGetStateCallback(TcpServerGetStateContext *context)
1908 {
1909     napi_value obj = NapiUtils::CreateObject(context->GetEnv());
1910     if (NapiUtils::GetValueType(context->GetEnv(), obj) != napi_object) {
1911         return NapiUtils::GetUndefined(context->GetEnv());
1912     }
1913 
1914     NapiUtils::SetBooleanProperty(context->GetEnv(), obj, KEY_IS_BOUND, context->state_.IsBound());
1915     NapiUtils::SetBooleanProperty(context->GetEnv(), obj, KEY_IS_CLOSE, context->state_.IsClose());
1916     NapiUtils::SetBooleanProperty(context->GetEnv(), obj, KEY_IS_CONNECTED, context->state_.IsConnected());
1917 
1918     return obj;
1919 }
1920 } // namespace OHOS::NetStack::Socket::SocketExec
1921