• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "connection_module.h"
17 
18 #include "bindsocket_context.h"
19 #include "connection_async_work.h"
20 #include "connection_exec.h"
21 #include "constant.h"
22 #include "getaddressbyname_context.h"
23 #include "getappnet_context.h"
24 #include "getdefaultnet_context.h"
25 #include "getglobalhttpproxy_context.h"
26 #include "napi_constant.h"
27 #include "net_all_capabilities.h"
28 #include "netconnection.h"
29 #include "netmanager_base_log.h"
30 #include "none_params_context.h"
31 #include "module_template.h"
32 #include "parse_nethandle_context.h"
33 #include "register_context.h"
34 #include "setappnet_context.h"
35 #include "setglobalhttpproxy_context.h"
36 
37 static constexpr const char *CONNECTION_MODULE_NAME = "net.connection";
38 
39 #define DECLARE_NET_CAP(cap) \
40     DECLARE_NAPI_STATIC_PROPERTY(#cap, NapiUtils::CreateUint32(env, static_cast<uint32_t>(NetCap::cap)))
41 
42 #define DECLARE_NET_BEAR_TYPE(type) \
43     DECLARE_NAPI_STATIC_PROPERTY(#type, NapiUtils::CreateUint32(env, static_cast<uint32_t>(NetBearType::type)))
44 
45 namespace OHOS::NetManagerStandard {
46 
ParseTypesArray(napi_env env,napi_value obj,std::set<T> & typeArray)47 template <typename T> static bool ParseTypesArray(napi_env env, napi_value obj, std::set<T> &typeArray)
48 {
49     if (!NapiUtils::IsArray(env, obj)) {
50         return false;
51     }
52     uint32_t arrayLenght =
53         NapiUtils::GetArrayLength(env, obj) > MAX_ARRAY_LENGTH ? MAX_ARRAY_LENGTH : NapiUtils::GetArrayLength(env, obj);
54     for (uint32_t i = 0; i < arrayLenght; ++i) {
55         napi_value val = NapiUtils::GetArrayElement(env, obj, i);
56         if (NapiUtils::GetValueType(env, val) == napi_number) {
57             typeArray.insert(static_cast<T>(NapiUtils::GetUint32FromValue(env, val)));
58         } else {
59             NETMANAGER_BASE_LOGE("Invalid parameter type of array element!");
60             return false;
61         }
62     }
63     return true;
64 }
65 
ParseCapabilities(napi_env env,napi_value obj,NetAllCapabilities & capabilities)66 static bool ParseCapabilities(napi_env env, napi_value obj, NetAllCapabilities &capabilities)
67 {
68     if (NapiUtils::GetValueType(env, obj) != napi_object) {
69         return false;
70     }
71 
72     capabilities.linkUpBandwidthKbps_ = NapiUtils::GetUint32Property(env, obj, KEY_LINK_UP_BAND_WIDTH_KPS);
73     capabilities.linkDownBandwidthKbps_ = NapiUtils::GetUint32Property(env, obj, KEY_LINK_DOWN_BAND_WIDTH_KPS);
74 
75     napi_value networkCap = NapiUtils::GetNamedProperty(env, obj, KEY_NETWORK_CAP);
76     (void)ParseTypesArray<NetCap>(env, networkCap, capabilities.netCaps_);
77 
78     napi_value bearerTypes = NapiUtils::GetNamedProperty(env, obj, KEY_BEARER_TYPE);
79     if (!ParseTypesArray<NetBearType>(env, bearerTypes, capabilities.bearerTypes_)) {
80         return false;
81     }
82 
83     return true;
84 }
85 
ParseNetSpecifier(napi_env env,napi_value obj,NetSpecifier & specifier)86 static bool ParseNetSpecifier(napi_env env, napi_value obj, NetSpecifier &specifier)
87 {
88     napi_value capabilitiesObj = NapiUtils::GetNamedProperty(env, obj, KEY_NET_CAPABILITIES);
89     if (!ParseCapabilities(env, capabilitiesObj, specifier.netCapabilities_)) {
90         return false;
91     }
92     specifier.ident_ = NapiUtils::GetStringPropertyUtf8(env, obj, KEY_BEARER_PRIVATE_IDENTIFIER);
93     return true;
94 }
95 
ParseNetConnectionParams(napi_env env,size_t argc,napi_value * argv,EventManager * manager)96 static void *ParseNetConnectionParams(napi_env env, size_t argc, napi_value *argv, EventManager *manager)
97 {
98     std::unique_ptr<NetConnection, decltype(&NetConnection::DeleteNetConnection)> netConnection(
99         NetConnection::MakeNetConnection(manager), NetConnection::DeleteNetConnection);
100 
101     if (argc == ARG_NUM_0) {
102         NETMANAGER_BASE_LOGI("ParseNetConnectionParams no params");
103         return netConnection.release();
104     }
105 
106     if (argc == ARG_NUM_1 && NapiUtils::GetValueType(env, argv[ARG_INDEX_0]) == napi_object) {
107         if (!ParseNetSpecifier(env, argv[ARG_INDEX_0], netConnection->netSpecifier_)) {
108             NETMANAGER_BASE_LOGE("ParseNetSpecifier failed");
109             return nullptr;
110         }
111         netConnection->hasNetSpecifier_ = true;
112         return netConnection.release();
113     }
114 
115     if (argc == ARG_NUM_2 && NapiUtils::GetValueType(env, argv[ARG_INDEX_0]) == napi_object &&
116         NapiUtils::GetValueType(env, argv[ARG_INDEX_1]) == napi_number) {
117         if (!ParseNetSpecifier(env, argv[ARG_INDEX_0], netConnection->netSpecifier_)) {
118             NETMANAGER_BASE_LOGE("ParseNetSpecifier failed, do not use params");
119             return nullptr;
120         }
121         netConnection->hasNetSpecifier_ = true;
122         netConnection->hasTimeout_ = true;
123         netConnection->timeout_ = NapiUtils::GetUint32FromValue(env, argv[ARG_INDEX_1]);
124         return netConnection.release();
125     }
126 
127     NETMANAGER_BASE_LOGE("constructor params invalid, should be none or specifier or specifier+timeout_");
128     return nullptr;
129 }
130 
InitConnectionModule(napi_env env,napi_value exports)131 napi_value ConnectionModule::InitConnectionModule(napi_env env, napi_value exports)
132 {
133     std::initializer_list<napi_property_descriptor> functions = {
134         DECLARE_NAPI_FUNCTION(FUNCTION_GET_DEFAULT_NET, GetDefaultNet),
135         DECLARE_NAPI_FUNCTION(FUNCTION_GET_DEFAULT_NET_SYNC, GetDefaultNetSync),
136         DECLARE_NAPI_FUNCTION(FUNCTION_CREATE_NET_CONNECTION, CreateNetConnection),
137         DECLARE_NAPI_FUNCTION(FUNCTION_GET_ADDRESSES_BY_NAME, GetAddressesByName),
138         DECLARE_NAPI_FUNCTION(FUNCTION_HAS_DEFAULT_NET, HasDefaultNet),
139         DECLARE_NAPI_FUNCTION(FUNCTION_IS_DEFAULT_NET_METERED, IsDefaultNetMetered),
140         DECLARE_NAPI_FUNCTION(FUNCTION_GET_NET_CAPABILITIES, GetNetCapabilities),
141         DECLARE_NAPI_FUNCTION(FUNCTION_GET_CONNECTION_PROPERTIES, GetConnectionProperties),
142         DECLARE_NAPI_FUNCTION(FUNCTION_GET_ALL_NETS, GetAllNets),
143         DECLARE_NAPI_FUNCTION(FUNCTION_ENABLE_AIRPLANE_MODE, EnableAirplaneMode),
144         DECLARE_NAPI_FUNCTION(FUNCTION_DISABLE_AIRPLANE_MODE, DisableAirplaneMode),
145         DECLARE_NAPI_FUNCTION(FUNCTION_REPORT_NET_CONNECTED, ReportNetConnected),
146         DECLARE_NAPI_FUNCTION(FUNCTION_REPORT_NET_DISCONNECTED, ReportNetDisconnected),
147         DECLARE_NAPI_FUNCTION(FUNCTION_GET_GLOBAL_HTTP_PROXY, GetGlobalHttpProxy),
148         DECLARE_NAPI_FUNCTION(FUNCTION_SET_GLOBAL_HTTP_PROXY, SetGlobalHttpProxy),
149         DECLARE_NAPI_FUNCTION(FUNCTION_GET_APP_NET, GetAppNet),
150         DECLARE_NAPI_FUNCTION(FUNCTION_SET_APP_NET, SetAppNet),
151     };
152     NapiUtils::DefineProperties(env, exports, functions);
153 
154     std::initializer_list<napi_property_descriptor> netConnectionFunctions = {
155         DECLARE_NAPI_FUNCTION(NetConnectionInterface::FUNCTION_ON, NetConnectionInterface::On),
156         DECLARE_NAPI_FUNCTION(NetConnectionInterface::FUNCTION_REGISTER, NetConnectionInterface::Register),
157         DECLARE_NAPI_FUNCTION(NetConnectionInterface::FUNCTION_UNREGISTER, NetConnectionInterface::Unregister),
158     };
159     ModuleTemplate::DefineClass(env, exports, netConnectionFunctions, INTERFACE_NET_CONNECTION);
160 
161     InitProperties(env, exports);
162     return exports;
163 }
164 
InitProperties(napi_env env,napi_value exports)165 void ConnectionModule::InitProperties(napi_env env, napi_value exports)
166 {
167     std::initializer_list<napi_property_descriptor> netCaps = {
168         DECLARE_NET_CAP(NET_CAPABILITY_MMS),
169         DECLARE_NET_CAP(NET_CAPABILITY_NOT_METERED),
170         DECLARE_NET_CAP(NET_CAPABILITY_INTERNET),
171         DECLARE_NET_CAP(NET_CAPABILITY_NOT_VPN),
172         DECLARE_NET_CAP(NET_CAPABILITY_VALIDATED),
173         DECLARE_NET_CAP(NET_CAPABILITY_CAPTIVE_PORTAL),
174         DECLARE_NET_CAP(NET_CAPABILITY_INTERNAL_DEFAULT),
175     };
176     napi_value caps = NapiUtils::CreateObject(env);
177     NapiUtils::DefineProperties(env, caps, netCaps);
178     NapiUtils::SetNamedProperty(env, exports, INTERFACE_NET_CAP, caps);
179 
180     std::initializer_list<napi_property_descriptor> netBearTypes = {
181         DECLARE_NET_BEAR_TYPE(BEARER_CELLULAR),  DECLARE_NET_BEAR_TYPE(BEARER_WIFI),
182         DECLARE_NET_BEAR_TYPE(BEARER_BLUETOOTH), DECLARE_NET_BEAR_TYPE(BEARER_ETHERNET),
183         DECLARE_NET_BEAR_TYPE(BEARER_VPN),       DECLARE_NET_BEAR_TYPE(BEARER_WIFI_AWARE),
184         DECLARE_NET_BEAR_TYPE(BEARER_DEFAULT),
185     };
186     napi_value types = NapiUtils::CreateObject(env);
187     NapiUtils::DefineProperties(env, types, netBearTypes);
188     NapiUtils::SetNamedProperty(env, exports, INTERFACE_NET_BEAR_TYPE, types);
189 }
190 
GetAddressesByName(napi_env env,napi_callback_info info)191 napi_value ConnectionModule::GetAddressesByName(napi_env env, napi_callback_info info)
192 {
193     return ModuleTemplate::Interface<GetAddressByNameContext>(env, info, FUNCTION_GET_ADDRESSES_BY_NAME, nullptr,
194                                                               ConnectionAsyncWork::ExecGetAddressesByName,
195                                                               ConnectionAsyncWork::GetAddressesByNameCallback);
196 }
197 
HasDefaultNet(napi_env env,napi_callback_info info)198 napi_value ConnectionModule::HasDefaultNet(napi_env env, napi_callback_info info)
199 {
200     return ModuleTemplate::Interface<HasDefaultNetContext>(env, info, FUNCTION_HAS_DEFAULT_NET, nullptr,
201                                                            ConnectionAsyncWork::ExecHasDefaultNet,
202                                                            ConnectionAsyncWork::HasDefaultNetCallback);
203 }
204 
IsDefaultNetMetered(napi_env env,napi_callback_info info)205 napi_value ConnectionModule::IsDefaultNetMetered(napi_env env, napi_callback_info info)
206 {
207     return ModuleTemplate::Interface<IsDefaultNetMeteredContext>(env, info, FUNCTION_IS_DEFAULT_NET_METERED, nullptr,
208                                                                  ConnectionAsyncWork::ExecIsDefaultNetMetered,
209                                                                  ConnectionAsyncWork::IsDefaultNetMeteredCallback);
210 }
211 
GetNetCapabilities(napi_env env,napi_callback_info info)212 napi_value ConnectionModule::GetNetCapabilities(napi_env env, napi_callback_info info)
213 {
214     return ModuleTemplate::Interface<GetNetCapabilitiesContext>(env, info, FUNCTION_GET_NET_CAPABILITIES, nullptr,
215                                                                 ConnectionAsyncWork::ExecGetNetCapabilities,
216                                                                 ConnectionAsyncWork::GetNetCapabilitiesCallback);
217 }
218 
GetConnectionProperties(napi_env env,napi_callback_info info)219 napi_value ConnectionModule::GetConnectionProperties(napi_env env, napi_callback_info info)
220 {
221     return ModuleTemplate::Interface<GetConnectionPropertiesContext>(
222         env, info, FUNCTION_GET_CONNECTION_PROPERTIES, nullptr, ConnectionAsyncWork::ExecGetConnectionProperties,
223         ConnectionAsyncWork::GetConnectionPropertiesCallback);
224 }
225 
CreateNetConnection(napi_env env,napi_callback_info info)226 napi_value ConnectionModule::CreateNetConnection(napi_env env, napi_callback_info info)
227 {
228     return ModuleTemplate::NewInstance(env, info, INTERFACE_NET_CONNECTION, ParseNetConnectionParams,
229                                        [](napi_env, void *data, void *) {
230                                            NETMANAGER_BASE_LOGI("finalize netConnection");
231                                            auto manager = static_cast<EventManager *>(data);
232                                            auto netConnection = static_cast<NetConnection *>(manager->GetData());
233                                            delete manager;
234                                            NetConnection::DeleteNetConnection(netConnection);
235                                        });
236 }
237 
GetDefaultNet(napi_env env,napi_callback_info info)238 napi_value ConnectionModule::GetDefaultNet(napi_env env, napi_callback_info info)
239 {
240     return ModuleTemplate::Interface<GetDefaultNetContext>(env, info, FUNCTION_GET_DEFAULT_NET, nullptr,
241                                                            ConnectionAsyncWork::ExecGetDefaultNet,
242                                                            ConnectionAsyncWork::GetDefaultNetCallback);
243 }
244 
GetDefaultNetSync(napi_env env,napi_callback_info info)245 napi_value ConnectionModule::GetDefaultNetSync(napi_env env, napi_callback_info info)
246 {
247     GetDefaultNetContext context(env, nullptr);
248     if (ConnectionExec::ExecGetDefaultNet(&context)) {
249         return ConnectionExec::GetDefaultNetCallback(&context);
250     }
251     return NapiUtils::CreateErrorMessage(env, context.GetErrorCode(), context.GetErrorMessage());
252 }
253 
GetAllNets(napi_env env,napi_callback_info info)254 napi_value ConnectionModule::GetAllNets(napi_env env, napi_callback_info info)
255 {
256     return ModuleTemplate::Interface<GetAllNetsContext>(env, info, FUNCTION_GET_ALL_NETS, nullptr,
257                                                         ConnectionAsyncWork::ExecGetAllNets,
258                                                         ConnectionAsyncWork::GetAllNetsCallback);
259 }
260 
EnableAirplaneMode(napi_env env,napi_callback_info info)261 napi_value ConnectionModule::EnableAirplaneMode(napi_env env, napi_callback_info info)
262 {
263     return ModuleTemplate::Interface<EnableAirplaneModeContext>(env, info, FUNCTION_ENABLE_AIRPLANE_MODE, nullptr,
264                                                                 ConnectionAsyncWork::ExecEnableAirplaneMode,
265                                                                 ConnectionAsyncWork::EnableAirplaneModeCallback);
266 }
267 
DisableAirplaneMode(napi_env env,napi_callback_info info)268 napi_value ConnectionModule::DisableAirplaneMode(napi_env env, napi_callback_info info)
269 {
270     return ModuleTemplate::Interface<DisableAirplaneModeContext>(env, info, FUNCTION_DISABLE_AIRPLANE_MODE, nullptr,
271                                                                  ConnectionAsyncWork::ExecDisableAirplaneMode,
272                                                                  ConnectionAsyncWork::DisableAirplaneModeCallback);
273 }
274 
ReportNetConnected(napi_env env,napi_callback_info info)275 napi_value ConnectionModule::ReportNetConnected(napi_env env, napi_callback_info info)
276 {
277     return ModuleTemplate::Interface<ReportNetConnectedContext>(env, info, FUNCTION_REPORT_NET_CONNECTED, nullptr,
278                                                                 ConnectionAsyncWork::ExecReportNetConnected,
279                                                                 ConnectionAsyncWork::ReportNetConnectedCallback);
280 }
281 
ReportNetDisconnected(napi_env env,napi_callback_info info)282 napi_value ConnectionModule::ReportNetDisconnected(napi_env env, napi_callback_info info)
283 {
284     return ModuleTemplate::Interface<ReportNetDisconnectedContext>(env, info, FUNCTION_REPORT_NET_DISCONNECTED, nullptr,
285                                                                    ConnectionAsyncWork::ExecReportNetDisconnected,
286                                                                    ConnectionAsyncWork::ReportNetDisconnectedCallback);
287 }
288 
GetGlobalHttpProxy(napi_env env,napi_callback_info info)289 napi_value ConnectionModule::GetGlobalHttpProxy(napi_env env, napi_callback_info info)
290 {
291     return ModuleTemplate::Interface<GetGlobalHttpProxyContext>(env, info, FUNCTION_GET_GLOBAL_HTTP_PROXY, nullptr,
292                                                              ConnectionAsyncWork::ExecGetGlobalHttpProxy,
293                                                              ConnectionAsyncWork::GetGlobalHttpProxyCallback);
294 }
295 
SetGlobalHttpProxy(napi_env env,napi_callback_info info)296 napi_value ConnectionModule::SetGlobalHttpProxy(napi_env env, napi_callback_info info)
297 {
298     return ModuleTemplate::Interface<SetGlobalHttpProxyContext>(env, info, FUNCTION_SET_GLOBAL_HTTP_PROXY, nullptr,
299                                                              ConnectionAsyncWork::ExecSetGlobalHttpProxy,
300                                                              ConnectionAsyncWork::SetGlobalHttpProxyCallback);
301 }
302 
GetAppNet(napi_env env,napi_callback_info info)303 napi_value ConnectionModule::GetAppNet(napi_env env, napi_callback_info info)
304 {
305     return ModuleTemplate::Interface<GetAppNetContext>(env, info, FUNCTION_GET_APP_NET, nullptr,
306                                                     ConnectionAsyncWork::ExecGetAppNet,
307                                                     ConnectionAsyncWork::GetAppNetCallback);
308 }
309 
SetAppNet(napi_env env,napi_callback_info info)310 napi_value ConnectionModule::SetAppNet(napi_env env, napi_callback_info info)
311 {
312     return ModuleTemplate::Interface<SetAppNetContext>(env, info, FUNCTION_SET_APP_NET, nullptr,
313                                                     ConnectionAsyncWork::ExecSetAppNet,
314                                                     ConnectionAsyncWork::SetAppNetCallback);
315 }
316 
GetAddressesByName(napi_env env,napi_callback_info info)317 napi_value ConnectionModule::NetHandleInterface::GetAddressesByName(napi_env env, napi_callback_info info)
318 {
319     return ModuleTemplate::Interface<GetAddressByNameContext>(
320         env, info, FUNCTION_GET_ADDRESSES_BY_NAME, nullptr,
321         ConnectionAsyncWork::NetHandleAsyncWork::ExecGetAddressesByName,
322         ConnectionAsyncWork::NetHandleAsyncWork::GetAddressesByNameCallback);
323 }
324 
GetAddressByName(napi_env env,napi_callback_info info)325 napi_value ConnectionModule::NetHandleInterface::GetAddressByName(napi_env env, napi_callback_info info)
326 {
327     return ModuleTemplate::Interface<GetAddressByNameContext>(
328         env, info, FUNCTION_GET_ADDRESSES_BY_NAME, nullptr,
329         ConnectionAsyncWork::NetHandleAsyncWork::ExecGetAddressByName,
330         ConnectionAsyncWork::NetHandleAsyncWork::GetAddressByNameCallback);
331 }
332 
BindSocket(napi_env env,napi_callback_info info)333 napi_value ConnectionModule::NetHandleInterface::BindSocket(napi_env env, napi_callback_info info)
334 {
335     return ModuleTemplate::Interface<BindSocketContext>(
336         env, info, FUNCTION_BIND_SOCKET,
337         [](napi_env theEnv, napi_value thisVal, BindSocketContext *context) -> bool {
338             context->netId_ = NapiUtils::GetInt32Property(theEnv, thisVal, PROPERTY_NET_ID);
339             return true;
340         },
341         ConnectionAsyncWork::NetHandleAsyncWork::ExecBindSocket,
342         ConnectionAsyncWork::NetHandleAsyncWork::BindSocketCallback);
343 }
344 
On(napi_env env,napi_callback_info info)345 napi_value ConnectionModule::NetConnectionInterface::On(napi_env env, napi_callback_info info)
346 {
347     std::initializer_list<std::string> events = {EVENT_NET_AVAILABLE,
348                                                  EVENT_NET_BLOCK_STATUS_CHANGE,
349                                                  EVENT_NET_CAPABILITIES_CHANGE,
350                                                  EVENT_NET_CONNECTION_PROPERTIES_CHANGE,
351                                                  EVENT_NET_LOST,
352                                                  EVENT_NET_UNAVAILABLE};
353     return ModuleTemplate::On(env, info, events, false);
354 }
355 
Register(napi_env env,napi_callback_info info)356 napi_value ConnectionModule::NetConnectionInterface::Register(napi_env env, napi_callback_info info)
357 {
358     return ModuleTemplate::Interface<RegisterContext>(env, info, FUNCTION_REGISTER, nullptr,
359                                                       ConnectionAsyncWork::NetConnectionAsyncWork::ExecRegister,
360                                                       ConnectionAsyncWork::NetConnectionAsyncWork::RegisterCallback);
361 }
362 
Unregister(napi_env env,napi_callback_info info)363 napi_value ConnectionModule::NetConnectionInterface::Unregister(napi_env env, napi_callback_info info)
364 {
365     return ModuleTemplate::Interface<UnregisterContext>(
366         env, info, FUNCTION_UNREGISTER,
367         [](napi_env theEnv, napi_value thisVal, UnregisterContext *context) -> bool {
368             if (context && context->GetManager()) {
369                 context->GetManager()->DeleteAllListener();
370             }
371             return true;
372         }, ConnectionAsyncWork::NetConnectionAsyncWork::ExecUnregister,
373         ConnectionAsyncWork::NetConnectionAsyncWork::UnregisterCallback);
374 }
375 
376 static napi_module g_connectionModule = {
377     .nm_version = 1,
378     .nm_flags = 0,
379     .nm_filename = nullptr,
380     .nm_register_func = ConnectionModule::InitConnectionModule,
381     .nm_modname = CONNECTION_MODULE_NAME,
382     .nm_priv = nullptr,
383     .reserved = {nullptr},
384 };
385 
RegisterConnectionModule(void)386 extern "C" __attribute__((constructor)) void RegisterConnectionModule(void)
387 {
388     napi_module_register(&g_connectionModule);
389 }
390 } // namespace OHOS::NetManagerStandard
391