1 /*
2 * Copyright (c) 2022 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 "netsys_sock_client.h"
17
18 #include <atomic>
19 #include <sys/socket.h>
20 #include <sys/un.h>
21 #include <unistd.h>
22
23 #include "fwmark_client.h"
24 #include "net_manager_constants.h"
25 #include "netnative_log_wrapper.h"
26
27 namespace {
28 std::atomic_int g_netIdForApp(0);
29 std::atomic<const SocketDispatchType*> g_dispatch(nullptr);
30 std::atomic_bool g_hookFlag(false);
GetDispatch()31 const SocketDispatchType* GetDispatch()
32 {
33 return g_dispatch.load(std::memory_order_relaxed);
34 }
35 } // namespace
36
HookSocket(int (* fn)(int,int,int),int domain,int type,int protocol)37 int HookSocket(int (*fn)(int, int, int), int domain, int type, int protocol)
38 {
39 int fd = -1;
40 if (fn) {
41 fd = fn(domain, type, protocol);
42 }
43
44 if (fd < 0) {
45 NETNATIVE_LOGE("musl create socket failed");
46 return fd;
47 }
48
49 if (g_netIdForApp > 0) {
50 if (OHOS::nmd::FwmarkClient().BindSocket(fd, g_netIdForApp) != OHOS::NetManagerStandard::NETMANAGER_SUCCESS) {
51 NETNATIVE_LOGE("BindSocket [%{public}d] to netid [%{public}d] failed",
52 fd, g_netIdForApp.load(std::memory_order_relaxed));
53 return -1;
54 }
55 }
56
57 return fd;
58 }
59
ohos_socket_hook_initialize(const SocketDispatchType * disptch,bool *,const char *)60 bool ohos_socket_hook_initialize(const SocketDispatchType* disptch, bool*, const char*)
61 {
62 g_dispatch.store(disptch);
63 g_hookFlag = true;
64 return true;
65 }
66
ohos_socket_hook_finalize(void)67 void ohos_socket_hook_finalize(void)
68 {
69 g_hookFlag = false;
70 }
71
ohos_socket_hook_socket(int domain,int type,int protocol)72 int ohos_socket_hook_socket(int domain, int type, int protocol)
73 {
74 g_hookFlag = false;
75 int ret = HookSocket(GetDispatch()->socket, domain, type, protocol);
76 g_hookFlag = true;
77 return ret;
78 }
79
ohos_socket_hook_get_hook_flag(void)80 bool ohos_socket_hook_get_hook_flag(void)
81 {
82 return g_hookFlag;
83 }
84
ohos_socket_hook_set_hook_flag(bool flag)85 bool ohos_socket_hook_set_hook_flag(bool flag)
86 {
87 g_hookFlag = flag;
88 return true;
89 }
90
SetNetForApp(int netId)91 void SetNetForApp(int netId)
92 {
93 g_netIdForApp = netId;
94 }
95
GetNetForApp()96 int GetNetForApp()
97 {
98 return g_netIdForApp;
99 }
100