From ec07ee7ff1eccb0c06aa51bc585364f04e529bf9 Mon Sep 17 00:00:00 2001 From: Hongjin Li Date: Tue, 8 Feb 2022 17:39:57 +0800 Subject: [PATCH] =?UTF-8?q?fear:=20=E5=90=8C=E6=AD=A5netmanager=5Fbase=5F0?= =?UTF-8?q?128=20=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Hongjin Li Change-Id: I31b40a2b9874530952fbde202102da9c5be0ae80 --- bundle.json | 7 +- frameworks/js/napi/common/base_context.h | 1 - frameworks/js/napi/common/event_context.h | 8 - .../netconn/include/event_listener_context.h | 5 +- .../js/napi/netconn/include/napi_net_conn.h | 6 - .../netconn/include/napi_net_connection.h | 6 +- .../netconn/src/event_listener_context.cpp | 101 +- .../js/napi/netconn/src/napi_net_conn.cpp | 78 +- .../netconn/src/napi_net_conn_observer.cpp | 14 +- .../napi/netconn/src/napi_net_connection.cpp | 18 +- frameworks/js/napi/netpolicy/BUILD.gn | 3 +- .../napi/netpolicy/include/napi_net_policy.h | 24 +- .../include/napi_net_policy_observer.h | 22 +- .../net_policy_event_listener_context.h} | 33 +- .../net_policy_event_listener_handler.h | 48 - .../net_policy_event_listener_manager.h | 50 - .../js/napi/netpolicy/src/napi_net_policy.cpp | 175 ++- .../src/napi_net_policy_observer.cpp | 40 +- ... => net_policy_event_listener_context.cpp} | 62 +- .../src/net_policy_event_listener_handler.cpp | 106 -- frameworks/js/napi/netstats/BUILD.gn | 1 - .../net_stats_event_listener_manager.h | 22 +- .../js/napi/netstats/src/napi_net_stats.cpp | 242 ++-- .../napi/netstats/src/net_stats_callback.cpp | 32 +- .../src/net_stats_event_listener_handler.cpp | 82 -- .../src/net_stats_event_listener_manager.cpp | 46 +- .../src/net_policy_cellular_policy.cpp | 4 +- .../netpolicyclient/src/net_policy_client.cpp | 8 +- .../src/net_policy_quota_policy.cpp | 6 +- .../src/proxy/net_policy_callback_stub.cpp | 8 +- .../src/proxy/net_policy_service_proxy.cpp | 8 +- .../innerkits/dnsresolverclient/BUILD.gn | 7 +- interfaces/innerkits/netconnclient/BUILD.gn | 7 +- interfaces/innerkits/netpolicyclient/BUILD.gn | 7 +- .../include/net_policy_cellular_policy.h | 8 +- .../include/net_policy_client.h | 8 +- .../include/net_policy_quota_policy.h | 4 +- .../include/proxy/i_net_policy_callback.h | 2 +- .../include/proxy/i_net_policy_service.h | 4 +- .../include/proxy/net_policy_callback_stub.h | 2 +- .../include/proxy/net_policy_service_proxy.h | 4 +- interfaces/innerkits/netstatsclient/BUILD.gn | 7 +- .../include/net_stats_constants.h | 4 +- interfaces/kits/js/@ohos.net.connection.d.ts | 510 ++++++++ interfaces/kits/js/@ohos.net.policy.d.ts | 204 ++++ interfaces/kits/js/@ohos.net.statistics.d.ts | 158 +++ interfaces/kits/js/basic.d.ts | 15 + netmanager_base_config.gni | 18 +- ohos.build | 75 -- .../include/common/include/blocking_queue.h | 150 +-- .../netd/include/common/include/job.h | 76 +- .../netd/include/common/include/net_utils.h | 1078 ++++++++--------- .../include/common/include/server_socket.h | 72 +- .../include/common/include/server_template.h | 106 +- .../netd/include/common/include/socket_base.h | 152 +-- .../netd/include/common/include/thread_pool.h | 112 +- .../include/common/include/warning_disable.h | 90 +- .../net_mgr_native/include/dnsresolv.h | 434 +++---- .../include/dnsresolv_controller.h | 92 +- .../include/dnsresolv_service.h | 158 +-- .../net_mgr_native/include/event_reporter.h | 94 +- .../net_mgr_native/include/fwmark_server.h | 104 +- .../include/interface_controller.h | 134 +- .../include/net_manager_native.h | 256 ++-- .../net_mgr_native/include/netlink_event.h | 148 +-- .../net_mgr_native/include/netlink_handler.h | 116 +- .../net_mgr_native/include/netlink_listener.h | 86 +- .../net_mgr_native/include/netlink_manager.h | 142 +-- .../net_mgr_native/include/netlink_socket.h | 156 +-- .../include/network_controller.h | 126 +- .../net_mgr_native/include/nmd_network.h | 146 +-- .../net_mgr_native/include/route_controller.h | 122 +- .../include/traffic_controller.h | 176 +-- services/common/BUILD.gn | 2 +- services/common/include/route_utils.h | 2 +- services/dnsresolvermanager/BUILD.gn | 2 +- services/netconnmanager/BUILD.gn | 2 +- .../netconnmanager/include/net_conn_service.h | 2 + .../netconnmanager/include/net_conn_types.h | 23 +- services/netconnmanager/include/net_monitor.h | 2 +- services/netconnmanager/include/net_score.h | 9 +- .../netconnmanager/include/net_supplier.h | 2 +- services/netconnmanager/src/http_request.cpp | 4 +- .../netconnmanager/src/net_conn_service.cpp | 29 +- services/netconnmanager/src/net_monitor.cpp | 20 +- services/netconnmanager/src/net_supplier.cpp | 2 +- services/netdcontroller/BUILD.gn | 3 +- .../netdcontroller/src/netd_controller.cpp | 4 +- services/netmanagernative/BUILD.gn | 3 +- .../src/netd_native_service_stub.cpp | 2 +- services/netpolicymanager/BUILD.gn | 2 +- .../include/net_policy_callback.h | 2 +- .../include/net_policy_define.h | 11 +- .../include/net_policy_file.h | 5 +- .../include/net_policy_service.h | 4 +- .../include/net_policy_traffic.h | 4 +- .../include/stub/net_policy_callback_proxy.h | 2 +- .../src/net_policy_callback.cpp | 18 +- .../netpolicymanager/src/net_policy_file.cpp | 41 +- .../src/net_policy_service.cpp | 26 +- .../src/net_policy_traffic.cpp | 8 +- .../src/stub/net_policy_callback_proxy.cpp | 4 +- .../src/stub/net_policy_service_stub.cpp | 6 +- services/netstatsmanager/BUILD.gn | 2 +- .../netstatsmanager/include/net_stats_csv.h | 2 +- .../src/net_stats_callback.cpp | 9 +- .../netstatsmanager/src/net_stats_csv.cpp | 8 +- .../netstatsmanager/src/net_stats_service.cpp | 14 +- .../src/stub/net_stats_service_stub.cpp | 20 +- test/netmanagernative/BUILD.gn | 1 - test/netmanagernative/unittest/BUILD.gn | 1 - .../net_policy_callback_test.cpp | 6 +- .../net_policy_callback_test.h | 2 +- .../net_policy_manager_test.cpp | 10 +- 114 files changed, 3846 insertions(+), 3111 deletions(-) rename frameworks/js/napi/{netstats/include/net_stats_event_listener_handler.h => netpolicy/include/net_policy_event_listener_context.h} (44%) delete mode 100644 frameworks/js/napi/netpolicy/include/net_policy_event_listener_handler.h delete mode 100644 frameworks/js/napi/netpolicy/include/net_policy_event_listener_manager.h rename frameworks/js/napi/netpolicy/src/{net_policy_event_listener_manager.cpp => net_policy_event_listener_context.cpp} (45%) delete mode 100644 frameworks/js/napi/netpolicy/src/net_policy_event_listener_handler.cpp delete mode 100644 frameworks/js/napi/netstats/src/net_stats_event_listener_handler.cpp create mode 100644 interfaces/kits/js/@ohos.net.connection.d.ts create mode 100644 interfaces/kits/js/@ohos.net.policy.d.ts create mode 100644 interfaces/kits/js/@ohos.net.statistics.d.ts create mode 100644 interfaces/kits/js/basic.d.ts delete mode 100644 ohos.build diff --git a/bundle.json b/bundle.json index 85a4da5ac..59ee4e1fd 100644 --- a/bundle.json +++ b/bundle.json @@ -26,12 +26,13 @@ "adapted_system_type": [ "standard" ], - "rom": "", - "ram": "", + "rom": "4.5MB", + "ram": "5MB", "deps": { "components": [ "ability_runtime", - "appexecfwk_standard", + "bundle_framework", + "eventhandler", "ces_standard", "ipc", "safwk", diff --git a/frameworks/js/napi/common/base_context.h b/frameworks/js/napi/common/base_context.h index 24d3483a7..7c51da5fb 100644 --- a/frameworks/js/napi/common/base_context.h +++ b/frameworks/js/napi/common/base_context.h @@ -35,7 +35,6 @@ struct BooleanValueContext : BaseContext { }; struct RestoreFactoryDataContext : BaseContext { - int32_t resolved = 0; int32_t errorCode = 0; }; diff --git a/frameworks/js/napi/common/event_context.h b/frameworks/js/napi/common/event_context.h index 7d4483142..832e83a72 100644 --- a/frameworks/js/napi/common/event_context.h +++ b/frameworks/js/napi/common/event_context.h @@ -59,14 +59,6 @@ struct EventListener { napi_env env = nullptr; napi_ref callbackRef = nullptr; }; - -struct NetStatusListenser : public EventListener { - NetStatusListenser() {} - std::string identifier; - int32_t netType = 0; - int32_t netCapabilities = 0; - int32_t netId = 0; -}; } // namespace NetManagerStandard } // namespace OHOS #endif // EVENT_CONTEXT_H diff --git a/frameworks/js/napi/netconn/include/event_listener_context.h b/frameworks/js/napi/netconn/include/event_listener_context.h index 082280a45..cabca8453 100644 --- a/frameworks/js/napi/netconn/include/event_listener_context.h +++ b/frameworks/js/napi/netconn/include/event_listener_context.h @@ -35,9 +35,12 @@ public: static int32_t Unregister(NapiNetConnection *conn); static int32_t Display(); static int32_t FindListener(NapiNetConnObserver *observer, EventListener &listen); + static int32_t RemoveCallback(NapiNetConnObserver *observer); private: + static int32_t RemoveIndexListense(intptr_t index); static std::map> listenses; // Netconnection obj to a group refences - static std::map> callbacks; // Netconnection obj to callback obj + static std::map> callbacks; // Netconnection obj to napi callback obj + static std::mutex mtx; }; } // namespace NetManagerStandard } // namespace OHOS diff --git a/frameworks/js/napi/netconn/include/napi_net_conn.h b/frameworks/js/napi/netconn/include/napi_net_conn.h index 7d8702309..ae174ff78 100644 --- a/frameworks/js/napi/netconn/include/napi_net_conn.h +++ b/frameworks/js/napi/netconn/include/napi_net_conn.h @@ -72,8 +72,6 @@ public: static void DeclareNetConnDestructor(napi_env env, void *nativeObject, void *hint); static napi_value CreateNetHandle(napi_env env, sptr &net); - static void ExecAddNetStatusCallback(napi_env env, void *data); - static void ExecRemoveNetStatusCallback(napi_env env, void *data); static void ExecNetDetection(napi_env env, void *data); static void ExecBindSocket(napi_env env, void *data); static void ExecGetAddressesByName(napi_env env, void *data); @@ -84,8 +82,6 @@ public: static void ExecGetNetCapabilities(napi_env env, void *data); static void ExecHasDefaultNet(napi_env env, void *data); static void NativeRestoreFactoryData(napi_env env, void *data); - static void CompleteAddNetStatusCallback(napi_env env, napi_status status, void *data); - static void CompleteRemoveNetStatusCallback(napi_env env, napi_status status, void *data); static void CompleteNetDetection(napi_env env, napi_status status, void *data); static void CompleteBindSocket(napi_env env, napi_status status, void *data); static void CompleteGetAddressesByName(napi_env env, napi_status status, void *data); @@ -110,8 +106,6 @@ public: static napi_value EnableAirplaneMode(napi_env env, napi_callback_info info); static napi_value DisableAirplaneMode(napi_env env, napi_callback_info info); static napi_value RestoreFactoryData(napi_env env, napi_callback_info info); - static napi_value AddNetStatusCallback(napi_env env, napi_callback_info info); - static napi_value RemoveNetStatusCallback(napi_env env, napi_callback_info info); }; } // namespace NetManagerStandard } // namespace OHOS diff --git a/frameworks/js/napi/netconn/include/napi_net_connection.h b/frameworks/js/napi/netconn/include/napi_net_connection.h index b709e78cc..8b16a87dd 100644 --- a/frameworks/js/napi/netconn/include/napi_net_connection.h +++ b/frameworks/js/napi/netconn/include/napi_net_connection.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef NAPI_NETCONN_INCLUDE_NAPI_NET_CONNECTION -#define NAPI_NETCONN_INCLUDE_NAPI_NET_CONNECTION +#ifndef NAPI_NETCONN_INCLUDE_NAPI_NET_CONNECTION_H +#define NAPI_NETCONN_INCLUDE_NAPI_NET_CONNECTION_H #include "napi/native_api.h" #include "napi/native_node_api.h" @@ -30,7 +30,7 @@ struct NapiNetConnection { bool hasSpecifier = false; bool hasTimeout = false; NetSpecifier netSpecifier_; - uint32_t timeout_; + uint32_t timeout_ = 0; }; } // namespace NetManagerStandard } // namespace OHOS diff --git a/frameworks/js/napi/netconn/src/event_listener_context.cpp b/frameworks/js/napi/netconn/src/event_listener_context.cpp index db1d06597..60e396069 100644 --- a/frameworks/js/napi/netconn/src/event_listener_context.cpp +++ b/frameworks/js/napi/netconn/src/event_listener_context.cpp @@ -27,18 +27,21 @@ namespace OHOS { namespace NetManagerStandard { std::map> EventListenerContext::listenses; std::map> EventListenerContext::callbacks; +std::mutex EventListenerContext::mtx; + EventListenerContext &EventListenerContext::GetInstance() { - NETMGR_LOG_D("EventListenerContext::GetInstance"); + NETMGR_LOG_I("EventListenerContext::GetInstance"); static EventListenerContext instance; return instance; } int32_t EventListenerContext::AddListense(NapiNetConnection *conn, EventListener &listen) { - NETMGR_LOG_D("EventListenerContext::AddListense"); + NETMGR_LOG_I("EventListenerContext::AddListense"); + std::lock_guard lck(mtx); intptr_t index = intptr_t(static_cast(conn)); - NETMGR_LOG_D("NetConnection *conn = [%{public}" PRIdPTR "]", index); + NETMGR_LOG_I("NetConnection *conn = [%{public}" PRIdPTR "]", index); listenses[index].insert(std::pair(listen.eventId, listen)); Display(); return 0; @@ -46,9 +49,10 @@ int32_t EventListenerContext::AddListense(NapiNetConnection *conn, EventListener int32_t EventListenerContext::RemoveListense(NapiNetConnection *conn, EventListener &listen) { - NETMGR_LOG_D("EventListenerContext::RemoveListense"); + NETMGR_LOG_I("EventListenerContext::RemoveListense"); + std::lock_guard lck(mtx); intptr_t index = intptr_t(static_cast(conn)); - NETMGR_LOG_D("NetConnection *conn = [%{public}" PRIdPTR "]", index); + NETMGR_LOG_I("NetConnection *conn = [%{public}" PRIdPTR "]", index); listenses[index].erase(listen.eventId); Display(); return 0; @@ -56,11 +60,15 @@ int32_t EventListenerContext::RemoveListense(NapiNetConnection *conn, EventListe int32_t EventListenerContext::Register(NapiNetConnection *conn) { - NETMGR_LOG_D("EventListenerContext::Register"); + NETMGR_LOG_I("EventListenerContext::Register"); int32_t ret = 0; intptr_t index = intptr_t(static_cast(conn)); - NETMGR_LOG_D("NetConnection *conn = [%{public}" PRIdPTR "]", index); + NETMGR_LOG_I("NetConnection *conn = [%{public}" PRIdPTR "]", index); sptr callback = (std::make_unique()).release(); + { + std::lock_guard lck(mtx); + callbacks[index] = callback; + } if ((conn->hasSpecifier) && (conn->hasTimeout)) { sptr specifier = (std::make_unique(conn->netSpecifier_)).release(); ret = DelayedSingleton::GetInstance()->RegisterNetConnCallback( @@ -69,38 +77,87 @@ int32_t EventListenerContext::Register(NapiNetConnection *conn) ret = DelayedSingleton::GetInstance()->RegisterNetConnCallback(callback); } if (ret == 0) { - callbacks[index] = callback; + NETMGR_LOG_I("Register successful"); + } else { + NETMGR_LOG_I("Register fail"); + std::lock_guard lck(mtx); + RemoveIndexListense(index); + callbacks.erase(index); } - NETMGR_LOG_D("Register ret = [%{public}d]", ret); + NETMGR_LOG_I("Register ret = [%{public}d]", ret); return ret; } int32_t EventListenerContext::Unregister(NapiNetConnection *conn) { - NETMGR_LOG_D("EventListenerContext::Unregister"); + NETMGR_LOG_I("EventListenerContext::Unregister"); int32_t ret = 0; intptr_t index = intptr_t(static_cast(conn)); - NETMGR_LOG_D("NetConnection *conn = [%{public}" PRIdPTR "]", index); - sptr callback = callbacks[index]; + NETMGR_LOG_I("NetConnection *conn = [%{public}" PRIdPTR "]", index); + sptr callback; + { + std::lock_guard lck(mtx); + std::map>::iterator iter = callbacks.find(index); + if (iter != callbacks.end()) { + callback = iter->second; + } + } if (callback != nullptr) { - NETMGR_LOG_D("Hava callback"); + NETMGR_LOG_I("Hava callback"); ret = DelayedSingleton::GetInstance()->UnregisterNetConnCallback(callback); - NETMGR_LOG_D("Unregister ret = [%{public}d]", ret); - if (ret == 0) { - listenses.erase(index); + if (ret != 0) { + NETMGR_LOG_I("Unregister fail = [%{public}d]", ret); + return ret; + } else { + NETMGR_LOG_I("Unregister successful = [%{public}d]", ret); + std::lock_guard lck(mtx); + RemoveIndexListense(index); + callbacks.erase(index); } } else { - NETMGR_LOG_D("Hava not callback"); + NETMGR_LOG_I("Hava not callback"); } return ret; } +int32_t EventListenerContext::RemoveCallback(NapiNetConnObserver *observer) +{ + std::lock_guard lck(mtx); + intptr_t index = 0; + for (std::map>::iterator it = callbacks.begin(); it != callbacks.end(); ++it) { + if (observer == it->second) { + NETMGR_LOG_I("RemoveCallback, [%{public}p] == [%{public}p]", observer, it->second->AsObject().GetRefPtr()); + index = it->first; + RemoveIndexListense(index); + callbacks.erase(index); + break; + } + } + NETMGR_LOG_I("RemoveCallback index = [%{public}" PRIdPTR "]", index); + return index; +} + +int32_t EventListenerContext::RemoveIndexListense(intptr_t index) +{ + std::map>::iterator it = listenses.find(index); + if (it == listenses.end()) { + return 0; + } + for (std::map::iterator itt = it->second.begin(); itt != it->second.end(); ++itt) { + NETMGR_LOG_I("Remove EventListener[%{public}" PRIdPTR "][%{public}d] = [%{public}d]", it->first, + itt->first, itt->second.eventId); + napi_delete_reference(itt->second.env, itt->second.callbackRef); + } + listenses.erase(index); + return 0; +} + int32_t EventListenerContext::Display() { for (std::map>::iterator it = listenses.begin(); it != listenses.end(); ++it) { for (std::map::iterator itt = it->second.begin(); itt != it->second.end(); ++itt) { - NETMGR_LOG_D("listenses[%{public}" PRIdPTR "][%{public}d] = [%{public}d]", it->first, itt->first, + NETMGR_LOG_I("listenses[%{public}" PRIdPTR "][%{public}d] = [%{public}d]", it->first, itt->first, itt->second.eventId); } } @@ -109,13 +166,17 @@ int32_t EventListenerContext::Display() int32_t EventListenerContext::FindListener(NapiNetConnObserver *observer, EventListener &listen) { + std::lock_guard lck(mtx); int32_t eventId = EVENT_NET_UNKNOW_CHANGE; - int32_t index = 0; - for (std::map>::iterator it = callbacks.begin(); it!=callbacks.end(); ++it) { + intptr_t index = 0; + NETMGR_LOG_I("FindListener, callbacks.size = [%{public}zd]", callbacks.size()); + for (std::map>::iterator it = callbacks.begin(); it != callbacks.end(); ++it) { if (observer == it->second) { + NETMGR_LOG_I("FindListener, [%{public}p] == [%{public}p]", observer, it->second->AsObject().GetRefPtr()); index = it->first; eventId = listen.eventId; listen = listenses[index][eventId]; + break; } } return eventId; diff --git a/frameworks/js/napi/netconn/src/napi_net_conn.cpp b/frameworks/js/napi/netconn/src/napi_net_conn.cpp index bcf517b5d..c65e47715 100644 --- a/frameworks/js/napi/netconn/src/napi_net_conn.cpp +++ b/frameworks/js/napi/netconn/src/napi_net_conn.cpp @@ -27,6 +27,35 @@ namespace OHOS { namespace NetManagerStandard { namespace { napi_value netConnectionObject; +template +napi_value ParseTypesArray(napi_env env, napi_value obj, std::set &typeArray) +{ + bool result = false; + napi_status status = napi_is_array(env, obj, &result); + if (status != napi_ok || !result) { + NETMGR_LOG_E("Invalid input parameter type!"); + return nullptr; + } + + napi_value elementValue = nullptr; + int32_t element = ERROR_DEFAULT; + uint32_t arrayLength = 0; + NAPI_CALL(env, napi_get_array_length(env, obj, &arrayLength)); + for (uint32_t i = 0; i < arrayLength; ++i) { + NAPI_CALL(env, napi_get_element(env, obj, i, &elementValue)); + napi_valuetype valueType = napi_undefined; + napi_typeof(env, elementValue, &valueType); + if (valueType == napi_number) { + NAPI_CALL(env, napi_get_value_int32(env, elementValue, &element)); + typeArray.insert(static_cast(element)); + } else { + NETMGR_LOG_E("Invalid parameter type of array element!"); + return nullptr; + } + } + return NapiCommon::CreateUndefined(env); +} + napi_value ParseCapabilities(napi_env env, napi_value obj, NetAllCapabilities &capabilities) { capabilities.linkUpBandwidthKbps_ = NapiCommon::GetNapiInt32Value(env, obj, "linkUpBandwidthKbps"); @@ -34,30 +63,18 @@ napi_value ParseCapabilities(napi_env env, napi_value obj, NetAllCapabilities &c napi_value networkCap = NapiCommon::GetNamedProperty(env, obj, "networkCap"); if (networkCap) { - napi_value elementValue = nullptr; - int32_t element = ERROR_DEFAULT; - uint32_t arrayLength = 0; - NAPI_CALL(env, napi_get_array_length(env, networkCap, &arrayLength)); - for (uint32_t i = 0; i < arrayLength; ++i) { - NAPI_CALL(env, napi_get_element(env, networkCap, i, &elementValue)); - NAPI_CALL(env, napi_get_value_int32(env, elementValue, &element)); - capabilities.netCaps_.insert(static_cast(element)); + if (ParseTypesArray(env, networkCap, capabilities.netCaps_) == nullptr) { + return nullptr; } } napi_value bearerTypes = NapiCommon::GetNamedProperty(env, obj, "bearerTypes"); if (bearerTypes) { - napi_value elementValue = nullptr; - int32_t element = ERROR_DEFAULT; - uint32_t arrayLength = 0; - NAPI_CALL(env, napi_get_array_length(env, bearerTypes, &arrayLength)); - for (uint32_t i = 0; i < arrayLength; ++i) { - NAPI_CALL(env, napi_get_element(env, bearerTypes, i, &elementValue)); - NAPI_CALL(env, napi_get_value_int32(env, elementValue, &element)); - capabilities.bearerTypes_.insert(static_cast(element)); + if (ParseTypesArray(env, bearerTypes, capabilities.bearerTypes_) == nullptr) { + return nullptr; } } - return obj; + return NapiCommon::CreateUndefined(env); } napi_status ParseNetSpecifier(napi_env env, napi_value obj, NetSpecifier &specifier) @@ -75,6 +92,7 @@ napi_status ParseNetSpecifier(napi_env env, napi_value obj, NetSpecifier &specif napi_value JS_Constructor(napi_env env, napi_callback_info cbinfo) { + NETMGR_LOG_I("netConnection JS_Constructor"); size_t argc = 2; napi_value argv[] = {nullptr, nullptr}; napi_value thisVar = nullptr; @@ -85,19 +103,25 @@ napi_value JS_Constructor(napi_env env, napi_callback_info cbinfo) napi_valuetype valueType = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_0], &valueType)); if (valueType == napi_object) { - NAPI_CALL(env, ParseNetSpecifier(env, argv[ARGV_INDEX_0], netConnection->netSpecifier_)); - netConnection->hasSpecifier = true; + if (ParseNetSpecifier(env, argv[ARGV_INDEX_0], netConnection->netSpecifier_) == napi_ok) { + netConnection->timeout_ = 0; + netConnection->hasSpecifier = true; + netConnection->hasTimeout = true; + } + NETMGR_LOG_I("netConnection hasSpecifier:%{public}d, hasTimeout:%{public}d", + netConnection->hasSpecifier, netConnection->hasTimeout); } else if (valueType == napi_number) { - NETMGR_LOG_I("JS_Constructor valueType napi_number"); - NAPI_CALL(env, napi_get_value_uint32(env, argv[ARGV_INDEX_0], &netConnection->timeout_)); - netConnection->hasTimeout = true; + std::string msg("The parameter 'timeout' is only valid when the parameter 'netSpecifier' is input!"); + NETMGR_LOG_E("%{public}s", msg.c_str()); + napi_throw_error(env, "1", msg.c_str()); + return nullptr; } else { NETMGR_LOG_E("invalid data type!"); return nullptr; } } else if (argc == ARGV_INDEX_2) { NAPI_CALL(env, ParseNetSpecifier(env, argv[ARGV_INDEX_0], netConnection->netSpecifier_)); - NAPI_CALL(env, napi_get_value_uint32(env, argv[ARGV_INDEX_0], &netConnection->timeout_)); + NAPI_CALL(env, napi_get_value_uint32(env, argv[ARGV_INDEX_1], &netConnection->timeout_)); netConnection->hasSpecifier = true; netConnection->hasTimeout = true; } else { @@ -134,6 +158,7 @@ napi_value RegisternetConnectionObject(napi_env env, napi_value exports) napi_value CreateNetConnection(napi_env env, napi_callback_info info) { + NETMGR_LOG_I("netConnection CreateNetConnection"); std::size_t argc = 2; napi_value argv[] = {nullptr, nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); @@ -174,7 +199,6 @@ napi_value NapiNetConn::DeclareNetConnNew(napi_env env, napi_callback_info info) napi_value thisVar = nullptr; void *data = nullptr; int32_t netId = 0; - napi_ref wrapper = nullptr; napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); if (argc == ARGV_NUM_1) { napi_get_value_int32(env, argv[ARGV_INDEX_0], &netId); @@ -188,7 +212,7 @@ napi_value NapiNetConn::DeclareNetConnNew(napi_env env, napi_callback_info info) NapiCommon::SetPropertyInt32(env, thisVar, "netId", netId); sptr *handlerPtr = new sptr(std::make_unique(netId).release()); napi_status status = napi_wrap(env, thisVar, reinterpret_cast(handlerPtr), - NapiNetConn::DeclareNetConnDestructor, nullptr, &wrapper); + NapiNetConn::DeclareNetConnDestructor, nullptr, nullptr); if (status != napi_ok) { NETMGR_LOG_E("Failed to wrap DeclareNetConnNew."); delete handlerPtr; @@ -1316,8 +1340,8 @@ napi_value NapiNetConn::RestoreFactoryData(napi_env env, napi_callback_info info napi_value arg = nullptr; void *data = nullptr; napi_get_cb_info(env, info, ¶msCount, params, &arg, &data); - NAPI_ASSERT( - env, MatchRestoreFactoryDataParam(env, params, paramsCount), "RestoreFactoryData input param type mismatch"); + NAPI_ASSERT(env, MatchRestoreFactoryDataParam(env, params, paramsCount), + "RestoreFactoryData input param type mismatch"); auto context = std::make_unique().release(); if (paramsCount == 1) { NAPI_CALL(env, napi_create_reference(env, params[0], 1, &context->callbackRef)); diff --git a/frameworks/js/napi/netconn/src/napi_net_conn_observer.cpp b/frameworks/js/napi/netconn/src/napi_net_conn_observer.cpp index 759cb42fe..bc0ceaa35 100644 --- a/frameworks/js/napi/netconn/src/napi_net_conn_observer.cpp +++ b/frameworks/js/napi/netconn/src/napi_net_conn_observer.cpp @@ -97,7 +97,7 @@ static void OnNetUnavailableEvent(EventListener &listen) napi_value recv = nullptr; napi_value result = nullptr; napi_value callbackFunc = nullptr; - napi_create_int32(listen.env, listen.eventId, &info); + info = NapiCommon::CreateUndefined(listen.env); napi_get_undefined(listen.env, &recv); napi_get_reference_value(listen.env, listen.callbackRef, &callbackFunc); callbackValues[CALLBACK_ARGV_INDEX_1] = info; @@ -126,7 +126,7 @@ static void OnNetBlockStatusChangeEvent( int32_t NapiNetConnObserver::NetAvailable(sptr &netHandle) { - NETMGR_LOG_D("NetAvailable netId [%{public}d]", netHandle->GetNetId()); + NETMGR_LOG_I("NetAvailable netId [%{public}d]", netHandle->GetNetId()); EventListener listen; listen.eventId = EVENT_NET_AVAILABLE_CHANGE; if (EventListenerContext::GetInstance().FindListener(this, listen) != EVENT_NET_UNKNOW_CHANGE) { @@ -138,7 +138,7 @@ int32_t NapiNetConnObserver::NetAvailable(sptr &netHandle) int32_t NapiNetConnObserver::NetCapabilitiesChange( sptr &netHandle, const sptr &netAllCap) { - NETMGR_LOG_D("NetCapabilitiesChange netId [%{public}d]", netHandle->GetNetId()); + NETMGR_LOG_I("NetCapabilitiesChange netId [%{public}d]", netHandle->GetNetId()); EventListener listen; listen.eventId = EVENT_NET_CAPABILITIES_CHANGE; if (EventListenerContext::GetInstance().FindListener(this, listen) != EVENT_NET_UNKNOW_CHANGE) { @@ -150,7 +150,7 @@ int32_t NapiNetConnObserver::NetCapabilitiesChange( int32_t NapiNetConnObserver::NetConnectionPropertiesChange(sptr &netHandle, const sptr &info) { - NETMGR_LOG_D("NetConnectionPropertiesChange netId [%{public}d], info is [%{public}s]", + NETMGR_LOG_I("NetConnectionPropertiesChange netId [%{public}d], info is [%{public}s]", netHandle->GetNetId(), info == nullptr ? "nullptr" : "not nullptr"); EventListener listen; listen.eventId = EVENT_NET_CONNECTION_CHANGE; @@ -162,7 +162,7 @@ int32_t NapiNetConnObserver::NetConnectionPropertiesChange(sptr &netH int32_t NapiNetConnObserver::NetLost(sptr &netHandle) { - NETMGR_LOG_D("NetLost netId [%{public}d]", netHandle->GetNetId()); + NETMGR_LOG_I("NetLost netId [%{public}d]", netHandle->GetNetId()); std::unique_ptr id = std::make_unique(netHandle->GetNetId()); EventListener listen; listen.eventId = EVENT_NET_LOST_CHANGE; @@ -174,17 +174,19 @@ int32_t NapiNetConnObserver::NetLost(sptr &netHandle) int32_t NapiNetConnObserver::NetUnavailable() { + NETMGR_LOG_I("NetUnavailable"); EventListener listen; listen.eventId = EVENT_NET_UNAVAILABLE_CHANGE; if (EventListenerContext::GetInstance().FindListener(this, listen) != EVENT_NET_UNKNOW_CHANGE) { OnNetUnavailableEvent(listen); + EventListenerContext::GetInstance().RemoveCallback(this); } return 0; } int32_t NapiNetConnObserver::NetBlockStatusChange(sptr &netHandle, bool blocked) { - NETMGR_LOG_D("NapiNetConnObserver NetBlockStatusChange netId [%{public}d]", netHandle->GetNetId()); + NETMGR_LOG_I("NapiNetConnObserver NetBlockStatusChange netId [%{public}d]", netHandle->GetNetId()); EventListener listen; listen.eventId = EVENT_NET_BLOCK_STATUS_CHANGE; if (EventListenerContext::GetInstance().FindListener(this, listen) != EVENT_NET_UNKNOW_CHANGE) { diff --git a/frameworks/js/napi/netconn/src/napi_net_connection.cpp b/frameworks/js/napi/netconn/src/napi_net_connection.cpp index 9c0cf52db..d22dcec42 100644 --- a/frameworks/js/napi/netconn/src/napi_net_connection.cpp +++ b/frameworks/js/napi/netconn/src/napi_net_connection.cpp @@ -30,7 +30,7 @@ struct ObserverContext : public BaseContext { void OnExecute(napi_env env, void *data) { if (data == nullptr) { - NETMGR_LOG_E("OnExecute data is nullptr"); + NETMGR_LOG_E("onExecute data is nullptr"); return; } ObserverContext *asyncContext = static_cast(data); @@ -45,12 +45,12 @@ void OnExecute(napi_env env, void *data) void OnComplete(napi_env env, napi_status status, void *data) { if (data == nullptr) { - NETMGR_LOG_E("OnComplete data is nullptr"); + NETMGR_LOG_E("onComplete data is nullptr"); return; } std::unique_ptr asyncContext(static_cast(data)); if (!asyncContext->resolved) { - NETMGR_LOG_E("OnComplete error by add observer failed"); + NETMGR_LOG_E("onComplete error by add observer failed"); } napi_delete_async_work(env, asyncContext->work); } @@ -58,7 +58,7 @@ void OnComplete(napi_env env, napi_status status, void *data) void RegisterExecute(napi_env env, void *data) { if (data == nullptr) { - NETMGR_LOG_E("RegisterExecute data is nullptr"); + NETMGR_LOG_E("registerExecute data is nullptr"); return; } ObserverContext *asyncContext = static_cast(data); @@ -69,14 +69,14 @@ void RegisterExecute(napi_env env, void *data) void RegisterComplete(napi_env env, napi_status status, void *data) { if (data == nullptr) { - NETMGR_LOG_E("RegisterComplete data is nullptr"); + NETMGR_LOG_E("registerComplete data is nullptr"); return; } std::unique_ptr asyncContext(static_cast(data)); napi_value callbackValue = nullptr; if (!asyncContext->resolved) { callbackValue = NapiCommon::CreateErrorMessage( - env, "RegisterComplete error by add observer failed", asyncContext->errorCode); + env, "registerComplete error by add observer failed", asyncContext->errorCode); } else { callbackValue = NapiCommon::CreateUndefined(env); } @@ -103,8 +103,7 @@ void UnregisterComplete(napi_env env, napi_status status, void *data) std::unique_ptr asyncContext(static_cast(data)); napi_value callbackValue = nullptr; if (!asyncContext->resolved) { - callbackValue = NapiCommon::CreateErrorMessage( - env, "RegisterComplete error by add observer failed", asyncContext->errorCode); + callbackValue = NapiCommon::CreateErrorMessage(env, "unregister failed", asyncContext->errorCode); } else { callbackValue = NapiCommon::CreateUndefined(env); } @@ -114,7 +113,6 @@ void UnregisterComplete(napi_env env, napi_status status, void *data) napi_value NapiNetConnection::On(napi_env env, napi_callback_info info) { - NETMGR_LOG_I("NapiNetConnection::On"); size_t argc = 2; napi_value argv[] = {nullptr, nullptr}; napi_value thisVar = nullptr; @@ -153,7 +151,6 @@ napi_value NapiNetConnection::On(napi_env env, napi_callback_info info) napi_value NapiNetConnection::Register(napi_env env, napi_callback_info info) { - NETMGR_LOG_I("NapiNetConnection::Register"); size_t argc = 1; napi_value argv[] = {nullptr}; napi_value thisVar = nullptr; @@ -183,7 +180,6 @@ napi_value NapiNetConnection::Register(napi_env env, napi_callback_info info) napi_value NapiNetConnection::Unregister(napi_env env, napi_callback_info info) { - NETMGR_LOG_I("NapiNetConnection::Unregister"); size_t argc = 1; napi_value argv[] = {nullptr}; napi_value thisVar = nullptr; diff --git a/frameworks/js/napi/netpolicy/BUILD.gn b/frameworks/js/napi/netpolicy/BUILD.gn index 5c3dff364..0aaf53d2e 100644 --- a/frameworks/js/napi/netpolicy/BUILD.gn +++ b/frameworks/js/napi/netpolicy/BUILD.gn @@ -31,8 +31,7 @@ ohos_shared_library("policy") { "$NETMANAGER_NAPI_ROOT/common/napi_common.cpp", "$NETMANAGER_NAPI_ROOT/netpolicy/src/napi_net_policy.cpp", "$NETMANAGER_NAPI_ROOT/netpolicy/src/napi_net_policy_observer.cpp", - "$NETMANAGER_NAPI_ROOT/netpolicy/src/net_policy_event_listener_handler.cpp", - "$NETMANAGER_NAPI_ROOT/netpolicy/src/net_policy_event_listener_manager.cpp", + "$NETMANAGER_NAPI_ROOT/netpolicy/src/net_policy_event_listener_context.cpp", ] defines = [ "NETMGR_DEBUG" ] diff --git a/frameworks/js/napi/netpolicy/include/napi_net_policy.h b/frameworks/js/napi/netpolicy/include/napi_net_policy.h index 563abcae7..e43bf5fe7 100644 --- a/frameworks/js/napi/netpolicy/include/napi_net_policy.h +++ b/frameworks/js/napi/netpolicy/include/napi_net_policy.h @@ -60,15 +60,30 @@ struct NetPolicyAsyncContext { bool isTrustList = false; std::vector uids; int8_t netType = 0; - int32_t slotId = 0; + int32_t simId = 0; + bool allow = false; }; struct GetNetPolicyContext : BaseContext { std::vector result; }; +enum MeteringMode { + /* non metering */ + UN_METERED = 0, + /* metering */ + METERED, +}; + +enum ApplicationType { + /* common application */ + COMMON = 0, + /* system application */ + SYSTEM, +}; + struct SetFactoryPolicyContext : BaseContext { - int32_t slotId; + int32_t simId; }; struct GetBackgroundPolicyContext : BaseContext { @@ -89,6 +104,8 @@ public: static napi_value DeclareNapiNetPolicyResultData(napi_env env, napi_value exports); static napi_value DeclareNetBearTypeData(napi_env env, napi_value exports); static napi_value DeclareBackgroundPolicyData(napi_env env, napi_value exports); + static napi_value DeclareEnumMeteringMode(napi_env env, napi_value exports); + static napi_value DeclareEnumApplicationType(napi_env env, napi_value exports); static void ExecSetPolicyByUid(napi_env env, void *data); static void ExecGetUidsByPolicy(napi_env env, void *data); @@ -96,6 +113,7 @@ public: static void ExecSetNetQuotaPolicies(napi_env env, void *data); static void ExecSetSnoozePolicy(napi_env env, void *data); static void ExecSetFactoryPolicy(napi_env env, void *data); + static void ExecSetBackgroundPolicy(napi_env env, void *data); static void ExecGetBackgroundPolicy(napi_env env, void *data); static void ExecOn(napi_env env, void *data); static void ExecOff(napi_env env, void *data); @@ -106,6 +124,7 @@ public: static void CompleteSetSnoozePolicy(napi_env env, napi_status status, void *data); static void CompleteNetPolicyResultCode(napi_env env, napi_status status, void *data); static void CompleteSetFactoryPolicy(napi_env env, napi_status status, void *data); + static void CompleteSetBackgroundPolicy(napi_env env, napi_status status, void *data); static void CompleteGetBackgroundPolicy(napi_env env, napi_status status, void *data); static void CompleteOn(napi_env env, napi_status status, void *data); static void CompleteOff(napi_env env, napi_status status, void *data); @@ -119,6 +138,7 @@ public: static napi_value GetNetQuotaPolicies(napi_env env, napi_callback_info info); static napi_value SetSnoozePolicy(napi_env env, napi_callback_info info); static napi_value SetFactoryPolicy(napi_env env, napi_callback_info info); + static napi_value SetBackgroundPolicy(napi_env env, napi_callback_info info); static napi_value GetBackgroundPolicy(napi_env env, napi_callback_info info); static napi_value On(napi_env env, napi_callback_info info); static napi_value Off(napi_env env, napi_callback_info info); diff --git a/frameworks/js/napi/netpolicy/include/napi_net_policy_observer.h b/frameworks/js/napi/netpolicy/include/napi_net_policy_observer.h index bcc641107..a436cb8c3 100644 --- a/frameworks/js/napi/netpolicy/include/napi_net_policy_observer.h +++ b/frameworks/js/napi/netpolicy/include/napi_net_policy_observer.h @@ -23,31 +23,11 @@ namespace OHOS { namespace NetManagerStandard { -struct UidPolicyEvent { - UidPolicyEvent(int32_t uid, NetUidPolicy policy) - : uid(uid), policy(policy) {} - int32_t uid; - NetUidPolicy policy; -}; - -struct CellularPolicyEvent { - CellularPolicyEvent (const std::vector &cellularPolicys) - : cellularPolicys(cellularPolicys) {} - std::vector cellularPolicys; -}; - -struct StrategySwitchEvent { - StrategySwitchEvent(int32_t slotId, bool enable) - : slotId(slotId), enable(enable) {} - int32_t slotId; - bool enable; -}; - class NapiNetPolicyObserver : public NetPolicyCallbackStub { public: int32_t NetUidPolicyChanged(uint32_t uid, NetUidPolicy policy) override; int32_t NetCellularPolicyChanged(const std::vector &cellularPolicys) override; - int32_t NetStrategySwitch(int32_t slotId, bool enable) override; + int32_t NetStrategySwitch(const std::string &simId, bool enable) override; int32_t NetBackgroundPolicyChanged(bool isBackgroundPolicyAllow) override; }; } // namespace NetManagerStandard diff --git a/frameworks/js/napi/netstats/include/net_stats_event_listener_handler.h b/frameworks/js/napi/netpolicy/include/net_policy_event_listener_context.h similarity index 44% rename from frameworks/js/napi/netstats/include/net_stats_event_listener_handler.h rename to frameworks/js/napi/netpolicy/include/net_policy_event_listener_context.h index b553dfa67..ae7f9a0d8 100644 --- a/frameworks/js/napi/netstats/include/net_stats_event_listener_handler.h +++ b/frameworks/js/napi/netpolicy/include/net_policy_event_listener_context.h @@ -13,36 +13,25 @@ * limitations under the License. */ -#ifndef NET_STATS_EVENT_LISTENER_HANDLER_H -#define NET_STATS_EVENT_LISTENER_HANDLER_H +#ifndef NET_POLICY_EVENT_LISTENER_CONTEXT_H +#define NET_POLICY_EVENT_LISTENER_CONTEXT_H -#include -#include // support libuv #include - -#include "event_handler.h" -#include "event_runner.h" - +#include +#include "net_mgr_log_wrapper.h" #include "napi_common.h" -#include "napi_net_stats.h" -#include "net_stats_callback.h" namespace OHOS { namespace NetManagerStandard { -class NetStatsEventListenerHandler : public AppExecFwk::EventHandler { +class NetPolicyEventListenerContext { public: - NetStatsEventListenerHandler(const std::shared_ptr &runner); - ~NetStatsEventListenerHandler() = default; - int32_t AddEventListener(EventListener &eventListener); - int32_t RemoveEventListener(EventListener &eventListener); - - void NetIfaceStatsUpdated(EventListener &eventListener, std::unique_ptr &event) ; - void NetUidStatsUpdated(EventListener &eventListener, std::unique_ptr &event) ; -private: - void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; + static NetPolicyEventListenerContext& GetInstance(); + static int32_t AddEventListener(EventListener &eventListener); + static int32_t RemoveEventListener(EventListener &eventListener); + static int32_t FindEventListense(EventListener &eventListener); private: - std::list listenerList; + static std::map listenses; }; } // namespace NetManagerStandard } // namespace OHOS -#endif // NET_STATS_EVENT_LISTENER_HANDLER_H \ No newline at end of file +#endif // NET_POLICY_EVENT_LISTENER_CONTEXT_H diff --git a/frameworks/js/napi/netpolicy/include/net_policy_event_listener_handler.h b/frameworks/js/napi/netpolicy/include/net_policy_event_listener_handler.h deleted file mode 100644 index 8800573d0..000000000 --- a/frameworks/js/napi/netpolicy/include/net_policy_event_listener_handler.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NET_POLICY_EVENT_LISTENER_HANDLER_H -#define NET_POLICY_EVENT_LISTENER_HANDLER_H - -#include -#include // support libuv -#include - -#include "event_handler.h" -#include "event_runner.h" - -#include "napi_common.h" -#include "napi_net_policy.h" -#include "napi_net_policy_observer.h" - -namespace OHOS { -namespace NetManagerStandard { -class NetPolicyEventListenerHandler : public AppExecFwk::EventHandler { -public: - NetPolicyEventListenerHandler(const std::shared_ptr &runner); - ~NetPolicyEventListenerHandler() = default; - int32_t AddEventListener(EventListener &eventListener); - int32_t RemoveEventListener(EventListener &eventListener); - void NetUidPolicyUpdated(EventListener &eventListener, std::unique_ptr &event) ; - void NetCellularPolicyUpdated(EventListener &eventListener, std::unique_ptr &event); - void NetStrategySwitchUpdated(EventListener &eventListener, std::unique_ptr &event); -private: - void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; -private: - std::list listenerList; -}; -} // namespace NetManagerStandard -} // namespace OHOS -#endif // NET_POLICY_EVENT_LISTENER_HANDLER_H \ No newline at end of file diff --git a/frameworks/js/napi/netpolicy/include/net_policy_event_listener_manager.h b/frameworks/js/napi/netpolicy/include/net_policy_event_listener_manager.h deleted file mode 100644 index 7c246b48a..000000000 --- a/frameworks/js/napi/netpolicy/include/net_policy_event_listener_manager.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NET_POLICY_EVENT_LISTENER_MANAGER_H -#define NET_POLICY_EVENT_LISTENER_MANAGER_H - -#include -#include "net_mgr_log_wrapper.h" -#include "net_policy_event_listener_handler.h" - -namespace OHOS { -namespace NetManagerStandard { -enum EventHandleRun { STATE_NOT_START, STATE_RUNNING }; - -class NetPolicyEventListenerManager { -public: - static NetPolicyEventListenerManager& GetInstance(); - template - inline bool SendEvent(uint32_t innerEventId, std::unique_ptr &object, int64_t delayTime = 0) - { - if (eventListenerHandler != nullptr) { - return eventListenerHandler->SendEvent(innerEventId, object, delayTime); - } else { - NETMGR_LOG_D("eventListenerHandler fail...."); - return false; - } - } - int32_t AddEventListener(EventListener &eventListener); - int32_t RemoveEventListener(EventListener &eventListener); -private: - NetPolicyEventListenerManager(); - std::shared_ptr eventListenerHandler = nullptr; - std::shared_ptr eventLoop = nullptr; - EventHandleRun eventStateRun_ = STATE_NOT_START; -}; -} // namespace NetManagerStandard -} // namespace OHOS -#endif // NET_POLICY_EVENT_LISTENER_MANAGER_H \ No newline at end of file diff --git a/frameworks/js/napi/netpolicy/src/napi_net_policy.cpp b/frameworks/js/napi/netpolicy/src/napi_net_policy.cpp index 42b8bdaaf..2058a4d8a 100644 --- a/frameworks/js/napi/netpolicy/src/napi_net_policy.cpp +++ b/frameworks/js/napi/netpolicy/src/napi_net_policy.cpp @@ -16,6 +16,7 @@ #include "napi_net_policy.h" #include #include +#include #include "system_ability_definition.h" #include "iservice_registry.h" #include "net_mgr_log_wrapper.h" @@ -23,12 +24,13 @@ #include "net_policy_client.h" #include "napi_common.h" #include "base_context.h" -#include "net_policy_event_listener_manager.h" +#include "net_policy_event_listener_context.h" #include "net_all_capabilities.h" namespace OHOS { namespace NetManagerStandard { const int32_t DEFAULT_REF_COUNT = 1; +const int32_t DECIMAL = 10; void NapiNetPolicy::ExecSetPolicyByUid(napi_env env, void *data) { NetPolicyAsyncContext *context = static_cast(data); @@ -87,8 +89,8 @@ void NapiNetPolicy::ExecSetSnoozePolicy(napi_env env, void *data) NETMGR_LOG_E("context == nullptr"); return; } - context->resultCode = - DelayedSingleton::GetInstance()->SetSnoozePolicy(context->netType, context->slotId); + context->resultCode = DelayedSingleton::GetInstance()->SetSnoozePolicy(context->netType, + std::to_string(context->simId)); } void NapiNetPolicy::ExecOn(napi_env env, void *data) @@ -103,7 +105,7 @@ void NapiNetPolicy::ExecOn(napi_env env, void *data) listen.callbackRef = context->callbackRef; listen.env = env; listen.eventId = context->eventPolicyId; - context->result = NetPolicyEventListenerManager::GetInstance().AddEventListener(listen); + context->policyResult = NetPolicyEventListenerContext::GetInstance().AddEventListener(listen); } void NapiNetPolicy::ExecOff(napi_env env, void *data) @@ -118,7 +120,7 @@ void NapiNetPolicy::ExecOff(napi_env env, void *data) listen.callbackRef = context->callbackRef; listen.env = env; listen.eventId = context->eventPolicyId; - context->result = NetPolicyEventListenerManager::GetInstance().RemoveEventListener(listen); + context->policyResult = NetPolicyEventListenerContext::GetInstance().RemoveEventListener(listen); } void NapiNetPolicy::CompleteSetPolicyByUid(napi_env env, napi_status status, void *data) @@ -279,8 +281,20 @@ void NapiNetPolicy::CompleteOn(napi_env env, napi_status status, void *data) NETMGR_LOG_E("context == nullptr"); return; } - if (context->result != 0) { - NETMGR_LOG_E("CompleteOn context->result = [%{public}d]", context->result); + napi_value info = nullptr; + if (context->callbackRef != nullptr) { + if (context->policyResult != 0) { + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + napi_create_int32(env, context->policyResult, &info); + callbackValues[CALLBACK_ARGV_INDEX_0] = info; + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } } napi_delete_async_work(env, context->work); delete context; @@ -295,8 +309,20 @@ void NapiNetPolicy::CompleteOff(napi_env env, napi_status status, void *data) NETMGR_LOG_E("context == nullptr"); return; } - if (context->result != 0) { - NETMGR_LOG_E("CompleteOff context->result = [%{public}d]", context->result); + napi_value info = nullptr; + if (context->callbackRef != nullptr) { + if (context->policyResult != 0) { + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + napi_create_int32(env, context->policyResult, &info); + callbackValues[CALLBACK_ARGV_INDEX_0] = info; + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } } napi_delete_async_work(env, context->work); delete context; @@ -307,14 +333,13 @@ NetPolicyQuotaPolicy NapiNetPolicy::ReadQuotaPolicy(napi_env env, napi_value val { NetPolicyQuotaPolicy data; data.netType_ = static_cast(NapiCommon::GetNapiInt32Value(env, value, "netType")); - data.slotId_ = NapiCommon::GetNapiInt32Value(env, value, "slotId"); - data.periodStartTime_ = NapiCommon::GetNapiInt32Value(env, value, "periodStartTime"); + data.simId_ = std::to_string(NapiCommon::GetNapiInt64Value(env, value, "simId")); + data.periodStartTime_ = NapiCommon::GetNapiInt64Value(env, value, "periodStartTime"); data.periodDuration_ = NapiCommon::GetNapiStringValue(env, value, "periodDuration"); data.warningBytes_ = NapiCommon::GetNapiInt64Value(env, value, "warningBytes"); data.limitBytes_ = NapiCommon::GetNapiInt64Value(env, value, "limitBytes"); - data.lastLimitSnooze_ = NapiCommon::GetNapiInt32Value(env, value, "lastLimitSnooze"); + data.lastLimitSnooze_ = NapiCommon::GetNapiInt64Value(env, value, "lastLimitSnooze"); data.metered_ = static_cast(NapiCommon::GetNapiInt32Value(env, value, "metered")); - data.source_ = static_cast(NapiCommon::GetNapiInt32Value(env, value, "source")); return data; } @@ -356,14 +381,15 @@ void GetNetQuotaPoliciesCallback(napi_env env, napi_status status, void *data) napi_create_object(env, &elementObject); NetPolicyQuotaPolicy item = context->result[i]; NapiCommon::SetPropertyInt32(env, elementObject, "netType", item.netType_); - NapiCommon::SetPropertyInt32(env, elementObject, "slotId", item.slotId_); + int64_t simIdValue = 0; + std::from_chars(&(*item.simId_.begin()), &(*item.simId_.end()), simIdValue, DECIMAL); + NapiCommon::SetPropertyInt64(env, elementObject, "simId", simIdValue); NapiCommon::SetPropertyInt64(env, elementObject, "periodStartTime", item.periodStartTime_); NapiCommon::SetPropertyString(env, elementObject, "periodDuration", item.periodDuration_); NapiCommon::SetPropertyInt64(env, elementObject, "warningBytes", item.warningBytes_); NapiCommon::SetPropertyInt64(env, elementObject, "limitBytes", item.limitBytes_); NapiCommon::SetPropertyInt64(env, elementObject, "lastLimitSnooze", item.lastLimitSnooze_); NapiCommon::SetPropertyInt32(env, elementObject, "metered", static_cast(item.metered_)); - NapiCommon::SetPropertyInt32(env, elementObject, "source", static_cast(item.source_)); napi_set_element(env, callbackValue, i, elementObject); } } else { @@ -456,6 +482,30 @@ napi_value NapiNetPolicy::DeclareNetBearTypeData(napi_env env, napi_value export return exports; } +napi_value NapiNetPolicy::DeclareEnumMeteringMode(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("UN_METERED", + NapiCommon::NapiValueByInt32(env, static_cast(MeteringMode::UN_METERED))), + DECLARE_NAPI_STATIC_PROPERTY("METERED", + NapiCommon::NapiValueByInt32(env, static_cast(MeteringMode::METERED))), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +napi_value NapiNetPolicy::DeclareEnumApplicationType(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("COMMON", + NapiCommon::NapiValueByInt32(env, static_cast(ApplicationType::COMMON))), + DECLARE_NAPI_STATIC_PROPERTY("SYSTEM", + NapiCommon::NapiValueByInt32(env, static_cast(ApplicationType::SYSTEM))), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + napi_value NapiNetPolicy::DeclareBackgroundPolicyData(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { @@ -490,7 +540,7 @@ bool MatchSetFactoryPolicyParameters(napi_env env, napi_value argv[], size_t arg void NapiNetPolicy::ExecSetFactoryPolicy(napi_env env, void *data) { auto context = static_cast(data); - DelayedSingleton::GetInstance()->SetFactoryPolicy(std::to_string(context->slotId)); + DelayedSingleton::GetInstance()->SetFactoryPolicy(std::to_string(context->simId)); context->resolved = true; } @@ -515,14 +565,14 @@ void NapiNetPolicy::CompleteSetFactoryPolicy(napi_env env, napi_status status, v napi_value NapiNetPolicy::SetFactoryPolicy(napi_env env, napi_callback_info info) { size_t argc = ARGV_NUM_2; - napi_value argv[] = {nullptr, nullptr, nullptr}; + napi_value argv[] = {nullptr, nullptr}; napi_value thisVar = nullptr; void *data = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); NAPI_ASSERT(env, MatchSetFactoryPolicyParameters(env, argv, argc), "type mismatch"); auto context = std::make_unique().release(); NETMGR_LOG_I("napi_policy SetFactoryPolicy start."); - napi_get_value_int32(env, argv[0], &context->slotId); + napi_get_value_int32(env, argv[0], &context->simId); if (argc == ARGV_NUM_2) { napi_create_reference(env, argv[1], CALLBACK_REF_CNT, &context->callbackRef); } @@ -543,6 +593,17 @@ bool MatchGetBackgroundPolicyParameters(napi_env env, napi_value argv[], size_t } } +void NapiNetPolicy::ExecSetBackgroundPolicy(napi_env env, void *data) +{ + NetPolicyAsyncContext *context = static_cast(data); + if (context == nullptr) { + NETMGR_LOG_E("context == nullptr"); + return; + } + context->resultCode = + DelayedSingleton::GetInstance()->SetBackgroundPolicy(context->allow); +} + void NapiNetPolicy::ExecGetBackgroundPolicy(napi_env env, void *data) { auto context = static_cast(data); @@ -550,6 +611,45 @@ void NapiNetPolicy::ExecGetBackgroundPolicy(napi_env env, void *data) context->resolved = true; } +void NapiNetPolicy::CompleteSetBackgroundPolicy(napi_env env, napi_status status, void *data) +{ + NetPolicyAsyncContext *context = static_cast(data); + if (context == nullptr) { + NETMGR_LOG_E("context == nullptr"); + return; + } + napi_value info = nullptr; + if (context->resultCode != NetPolicyResultCode::ERR_NONE) { + info = NapiCommon::CreateCodeMessage(env, "fail", static_cast(context->resultCode)); + } else { + info = NapiCommon::CreateUndefined(env); + } + if (!context->callbackRef) { // promiss return + if (context->resultCode != NetPolicyResultCode::ERR_NONE) { + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, context->deferred, info)); + } else { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + } + } else { // call back + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + if (context->resultCode != NetPolicyResultCode::ERR_NONE) { + callbackValues[CALLBACK_ARGV_INDEX_0] = info; + } else { + callbackValues[CALLBACK_ARGV_INDEX_1] = info; + } + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + void NapiNetPolicy::CompleteGetBackgroundPolicy(napi_env env, napi_status status, void *data) { NETMGR_LOG_I("CompleteSetBackgroundPolicy start"); @@ -568,6 +668,40 @@ void NapiNetPolicy::CompleteGetBackgroundPolicy(napi_env env, napi_status status NapiCommon::Handle2ValueCallback(env, context, callbackValue); } +napi_value NapiNetPolicy::SetBackgroundPolicy(napi_env env, napi_callback_info info) +{ + size_t argc = ARGV_NUM_2; + napi_value argv[] = {nullptr, nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NetPolicyAsyncContext *context = std::make_unique().release(); + NAPI_CALL(env, napi_get_value_bool(env, argv[ARGV_INDEX_0], &context->allow)); + NETMGR_LOG_I( + "JS agvc count = [%{public}d], argv[ARGV_INDEX_0] = [%{public}d], ", + static_cast(argc), static_cast(context->allow)); + napi_value result = nullptr; + if (argc == ARGV_NUM_1) { + if (context->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if (argc == ARGV_NUM_2) { + NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_1], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOG_E("SetBackgroundPolicy exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "SetBackgroundPolicy", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, + napi_create_async_work(env, resource, resourceName, ExecSetBackgroundPolicy, CompleteSetBackgroundPolicy, + (void *)context, &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + napi_value NapiNetPolicy::GetBackgroundPolicy(napi_env env, napi_callback_info info) { size_t argc = ARGV_NUM_1; @@ -595,6 +729,7 @@ napi_value NapiNetPolicy::DeclareNapiNetPolicyInterface(napi_env env, napi_value DECLARE_NAPI_FUNCTION("getNetQuotaPolicies", GetNetQuotaPolicies), DECLARE_NAPI_FUNCTION("setFactoryPolicy", SetFactoryPolicy), DECLARE_NAPI_FUNCTION("setSnoozePolicy", SetSnoozePolicy), + DECLARE_NAPI_FUNCTION("setBackgroundPolicy", SetBackgroundPolicy), DECLARE_NAPI_FUNCTION("getBackgroundPolicy", GetBackgroundPolicy), DECLARE_NAPI_FUNCTION("on", On), DECLARE_NAPI_FUNCTION("off", Off), @@ -764,7 +899,7 @@ napi_value NapiNetPolicy::SetSnoozePolicy(napi_env env, napi_callback_info info) int32_t netType = 0; NAPI_CALL(env, napi_get_value_int32(env, argv[ARGV_INDEX_0], &netType)); context->netType = static_cast(netType); - NAPI_CALL(env, napi_get_value_int32(env, argv[ARGV_INDEX_1], &context->slotId)); + NAPI_CALL(env, napi_get_value_int32(env, argv[ARGV_INDEX_1], &context->simId)); napi_value result = nullptr; if (argc == ARGV_NUM_2) { // promise call if (!context->callbackRef) { @@ -867,6 +1002,8 @@ napi_value NapiNetPolicy::RegisterNetPolicyInterface(napi_env env, napi_value ex DeclareNapiNetPolicyResultData(env, exports); DeclareNetBearTypeData(env, exports); DeclareBackgroundPolicyData(env, exports); + DeclareEnumMeteringMode(env, exports); + DeclareEnumApplicationType(env, exports); return exports; } diff --git a/frameworks/js/napi/netpolicy/src/napi_net_policy_observer.cpp b/frameworks/js/napi/netpolicy/src/napi_net_policy_observer.cpp index f9e758ec0..db1d90b81 100644 --- a/frameworks/js/napi/netpolicy/src/napi_net_policy_observer.cpp +++ b/frameworks/js/napi/netpolicy/src/napi_net_policy_observer.cpp @@ -15,16 +15,40 @@ #include "napi_net_policy_observer.h" #include "net_mgr_log_wrapper.h" -#include "net_policy_event_listener_manager.h" +#include "net_policy_event_listener_context.h" #include "napi_common.h" namespace OHOS { namespace NetManagerStandard { +static void OnNetUidPolicyEvent(EventListener &eventListener, + uint32_t uid, NetUidPolicy policy) +{ + napi_value info = nullptr; + napi_create_object(eventListener.env, &info); + NapiCommon::SetPropertyUint32(eventListener.env, info, "uid", uid); + NapiCommon::SetPropertyInt32(eventListener.env, info, "policy", static_cast(policy)); + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + if ((eventListener.env == nullptr) || (eventListener.callbackRef == nullptr)) { + NETMGR_LOG_E("eventListener.env = nullptr || eventListener.callbackRef =nullptr"); + return; + } + napi_get_undefined(eventListener.env, &recv); + napi_get_reference_value(eventListener.env, eventListener.callbackRef, &callbackFunc); + callbackValues[ARGV_INDEX_1] = info; + napi_call_function(eventListener.env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); +} + int32_t NapiNetPolicyObserver::NetUidPolicyChanged(uint32_t uid, NetUidPolicy policy) { NETMGR_LOG_I("NapiNetPolicyObserver NetUidPolicyChanged(), uid = [%{public}d], policy = [%{public}u]", uid, policy); - std::unique_ptr event = std::make_unique(uid, policy); - NetPolicyEventListenerManager::GetInstance().SendEvent(EVENT_NET_UID_POLICY_CHANGE, event); + EventListener eventListener; + eventListener.eventId = EVENT_NET_UID_POLICY_CHANGE; + if (NetPolicyEventListenerContext::FindEventListense(eventListener) != EVENT_NET_UNKNOW_CHANGE) { + OnNetUidPolicyEvent(eventListener, uid, policy); + } return 0; } @@ -38,17 +62,13 @@ int32_t NapiNetPolicyObserver::NetCellularPolicyChanged( { NETMGR_LOG_I("NapiNetPolicyObserver NetCellularPolicyChanged(), cellularPolicys.size = [%{public}zd]", cellularPolicys.size()); - std::unique_ptr event = std::make_unique(cellularPolicys); - NetPolicyEventListenerManager::GetInstance().SendEvent(EVENT_NET_CELLULAR_POLICY_CHANGE, event); return 0; } -int32_t NapiNetPolicyObserver::NetStrategySwitch(int32_t slotId, bool enable) +int32_t NapiNetPolicyObserver::NetStrategySwitch(const std::string &simId, bool enable) { - NETMGR_LOG_I("NapiNetPolicyObserver NetStrategySwitch(), subscriberId = [%{public}d], enable = [%{public}d]", - slotId, enable); - std::unique_ptr event = std::make_unique(slotId, enable); - NetPolicyEventListenerManager::GetInstance().SendEvent(EVENT_NET_STRATEGY_SWITCH_CHANGE, event); + NETMGR_LOG_I("NapiNetPolicyObserver NetStrategySwitch(), simId = [%{public}s], enable = [%{public}d]", + simId.c_str(), enable); return 0; } } // namespace NetManagerStandard diff --git a/frameworks/js/napi/netpolicy/src/net_policy_event_listener_manager.cpp b/frameworks/js/napi/netpolicy/src/net_policy_event_listener_context.cpp similarity index 45% rename from frameworks/js/napi/netpolicy/src/net_policy_event_listener_manager.cpp rename to frameworks/js/napi/netpolicy/src/net_policy_event_listener_context.cpp index fe90d19b3..9a6ebeb5f 100644 --- a/frameworks/js/napi/netpolicy/src/net_policy_event_listener_manager.cpp +++ b/frameworks/js/napi/netpolicy/src/net_policy_event_listener_context.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "net_policy_event_listener_manager.h" +#include "net_policy_event_listener_context.h" #include "iservice_registry.h" #include "system_ability_definition.h" #include "net_policy_client.h" @@ -22,49 +22,51 @@ namespace OHOS { namespace NetManagerStandard { +std::map NetPolicyEventListenerContext::listenses; static sptr callback = (std::make_unique()).release(); -NetPolicyEventListenerManager& NetPolicyEventListenerManager::GetInstance() +NetPolicyEventListenerContext& NetPolicyEventListenerContext::GetInstance() { - NETMGR_LOG_D("NetPolicyEventListenerManager::GetInstance"); - static NetPolicyEventListenerManager instance; + NETMGR_LOG_D("NetPolicyEventListenerContext::GetInstance"); + static NetPolicyEventListenerContext instance; return instance; } -NetPolicyEventListenerManager::NetPolicyEventListenerManager() +int32_t NetPolicyEventListenerContext::AddEventListener(EventListener &eventListener) { - NETMGR_LOG_D("NetPolicyEventListenerManager"); - if (eventStateRun_ == STATE_RUNNING) { - NETMGR_LOG_D("eventListenerHandler is running"); - return; - } - eventLoop = AppExecFwk::EventRunner::Create("EventListenerHandler"); - if (eventLoop.get() == nullptr) { - NETMGR_LOG_E("failed to create EventRunner"); - return; - } - eventListenerHandler = std::make_shared(eventLoop); - if (eventListenerHandler == nullptr) { - NETMGR_LOG_E("failed to create new eventListenerHandler"); - return; + int32_t ret = 0; + NETMGR_LOG_D("eventListener.eventId = [%{public}d]", eventListener.eventId); + ret = DelayedSingleton::GetInstance()->RegisterNetPolicyCallback(callback); + if (ret == 0) { + listenses.insert(std::pair(eventListener.eventId, eventListener)); } - eventLoop->Run(); - NETMGR_LOG_D("eventLoop is running"); - eventStateRun_ = STATE_RUNNING; + return ret; } -int32_t NetPolicyEventListenerManager::AddEventListener(EventListener &eventListener) +int32_t NetPolicyEventListenerContext::RemoveEventListener(EventListener &eventListener) { - NETMGR_LOG_D("eventListener.eventId = [%{public}d]", eventListener.eventId); - eventListenerHandler->AddEventListener(eventListener); - return DelayedSingleton::GetInstance()->RegisterNetPolicyCallback(callback); + int32_t ret = 0; + NETMGR_LOG_D("RemoveEventListener"); + ret = DelayedSingleton::GetInstance()->UnregisterNetPolicyCallback(callback); + if (ret == 0) { + std::map::iterator it = listenses.find(eventListener.eventId); + if (it !=listenses.end()) { + napi_delete_reference(it->second.env, it->second.callbackRef); + listenses.erase(eventListener.eventId); + } + } + return ret; } -int32_t NetPolicyEventListenerManager::RemoveEventListener(EventListener &eventListener) +int32_t NetPolicyEventListenerContext::FindEventListense(EventListener &eventListener) { - NETMGR_LOG_D("RemoveEventListener"); - eventListenerHandler->RemoveEventListener(eventListener); - return DelayedSingleton::GetInstance()->UnregisterNetPolicyCallback(callback); + int32_t eventId = EVENT_NET_UNKNOW_CHANGE; + std::map::iterator it = listenses.find(eventListener.eventId); + if (it != listenses.end()) { + eventListener = it->second; + eventId = it->first; + } + return eventId; } } // namespace NetManagerStandard } // namespace OHOS diff --git a/frameworks/js/napi/netpolicy/src/net_policy_event_listener_handler.cpp b/frameworks/js/napi/netpolicy/src/net_policy_event_listener_handler.cpp deleted file mode 100644 index 39d916fa0..000000000 --- a/frameworks/js/napi/netpolicy/src/net_policy_event_listener_handler.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "net_policy_event_listener_handler.h" -#include "inner_event.h" -#include "net_mgr_log_wrapper.h" - -namespace OHOS { -namespace NetManagerStandard { -NetPolicyEventListenerHandler::NetPolicyEventListenerHandler( - const std::shared_ptr &runner) - : AppExecFwk::EventHandler(runner) -{ - NETMGR_LOG_D("NetPolicyEventListenerHandler"); -} - -int32_t NetPolicyEventListenerHandler::AddEventListener(EventListener &eventListener) -{ - listenerList.push_back(eventListener); - for (std::list::iterator it = listenerList.begin(); it != listenerList.end(); it++) { - NETMGR_LOG_D("eventId = [%{public}d]", it->eventId); - } - NETMGR_LOG_D("listenerList.size = [%{public}zd]", listenerList.size()); - return 0; -} - -int32_t NetPolicyEventListenerHandler::RemoveEventListener(EventListener &eventListener) -{ - for (std::list::iterator it = listenerList.begin(); it != listenerList.end(); it++) { - if (it->env != nullptr && it->callbackRef != nullptr) { - napi_delete_reference(it->env, it->callbackRef); - } - } - listenerList.erase(listenerList.begin(), listenerList.end()); - NETMGR_LOG_D("listenerList.size = [%{puvlic}zd]", listenerList.size()); - return 0; -} - -void NetPolicyEventListenerHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) -{ - int32_t eventId = event->GetInnerEventId(); - NETMGR_LOG_D("eventId = %{public}d", eventId); - std::unique_ptr uidPolicyEvent = nullptr; - if (eventId == EVENT_NET_UID_POLICY_CHANGE) { - uidPolicyEvent = event->GetUniqueObject(); - } else { - NETMGR_LOG_E("UNKONOW_EVENT"); - } - for (auto it = listenerList.begin(); it != listenerList.end(); ++it) { - if (it->eventId == EVENT_NET_UID_POLICY_CHANGE) { - NetUidPolicyUpdated(*it, uidPolicyEvent); - } else { - NETMGR_LOG_E("listener.eventId = [%{public}d] unknown", eventId); - } - } -} - -void NetPolicyEventListenerHandler::NetUidPolicyUpdated(EventListener &eventListener, - std::unique_ptr &event) -{ - NETMGR_LOG_I("NetUidPolicyUpdated, event->uid = [%{public}d], event->policy = [%{public}u]", event->uid, - event->policy); - napi_value info = nullptr; - napi_create_object(eventListener.env, &info); - NapiCommon::SetPropertyInt32(eventListener.env, info, "uid", event->uid); - NapiCommon::SetPropertyInt32(eventListener.env, info, "policy", static_cast(event->policy)); - napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; - napi_value recv = nullptr; - napi_value result = nullptr; - napi_value callbackFunc = nullptr; - if ((eventListener.env == nullptr) || (eventListener.callbackRef == nullptr)) { - NETMGR_LOG_E("eventListener.env = nullptr || eventListener.callbackRef =nullptr"); - return; - } - napi_get_undefined(eventListener.env, &recv); - napi_get_reference_value(eventListener.env, eventListener.callbackRef, &callbackFunc); - callbackValues[ARGV_INDEX_1] = info; - napi_call_function(eventListener.env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); -} - -void NetPolicyEventListenerHandler::NetCellularPolicyUpdated(EventListener &eventListener, - std::unique_ptr &event) -{ - NETMGR_LOG_I("NetCellularPolicyUpdated cellularPolicys.size= [%{public}zd]", event->cellularPolicys.size()); -} - -void NetPolicyEventListenerHandler::NetStrategySwitchUpdated(EventListener &eventListener, - std::unique_ptr &event) -{ - NETMGR_LOG_I("NetStrategySwitchUpdated, event->slotId = [%{public}d], event->enable = [%{public}d]", - event->slotId, event->enable); -} -} // namespace NetManagerStandard -} // namespace OHOS diff --git a/frameworks/js/napi/netstats/BUILD.gn b/frameworks/js/napi/netstats/BUILD.gn index 5f28e1977..83e9c4cb0 100644 --- a/frameworks/js/napi/netstats/BUILD.gn +++ b/frameworks/js/napi/netstats/BUILD.gn @@ -31,7 +31,6 @@ ohos_shared_library("statistics") { "$NETMANAGER_NAPI_ROOT/common/napi_common.cpp", "$NETMANAGER_NAPI_ROOT/netstats/src/napi_net_stats.cpp", "$NETMANAGER_NAPI_ROOT/netstats/src/net_stats_callback.cpp", - "$NETMANAGER_NAPI_ROOT/netstats/src/net_stats_event_listener_handler.cpp", "$NETMANAGER_NAPI_ROOT/netstats/src/net_stats_event_listener_manager.cpp", ] diff --git a/frameworks/js/napi/netstats/include/net_stats_event_listener_manager.h b/frameworks/js/napi/netstats/include/net_stats_event_listener_manager.h index 373a7e118..9aa49b234 100644 --- a/frameworks/js/napi/netstats/include/net_stats_event_listener_manager.h +++ b/frameworks/js/napi/netstats/include/net_stats_event_listener_manager.h @@ -16,8 +16,9 @@ #ifndef NETMANAGER_BASE_NET_STATS_EVENT_LISTENER_MANAGER_H #define NETMANAGER_BASE_NET_STATS_EVENT_LISTENER_MANAGER_H #include -#include "net_stats_event_listener_handler.h" +#include #include "net_mgr_log_wrapper.h" +#include "napi_common.h" namespace OHOS { namespace NetManagerStandard { @@ -25,27 +26,14 @@ enum EventHandleRun { STATE_NOT_START, STATE_RUNNING }; class NetStatsEventListenerManager { public: - static NetStatsEventListenerManager& GetInstance(); - - template - inline bool SendEvent(uint32_t innerEventId, std::unique_ptr &object, int64_t delayTime = 0) - { - if (eventListenerHandler != nullptr) { - return eventListenerHandler->SendEvent(innerEventId, object, delayTime); - } else { - NETMGR_LOG_I("eventListenerHandler fail...."); - return false; - } - return false; - } + static NetStatsEventListenerManager &GetInstance(); int32_t AddEventListener(EventListener &eventListener); int32_t RemoveEventListener(EventListener &eventListener); + int32_t FindListener(EventListener &listen); private: NetStatsEventListenerManager(); - std::shared_ptr eventListenerHandler = nullptr; - std::shared_ptr eventLoop = nullptr; - EventHandleRun eventStateRun_ = STATE_NOT_START; + std::list listenerList; }; } // namespace NetManagerStandard } // namespace OHOS diff --git a/frameworks/js/napi/netstats/src/napi_net_stats.cpp b/frameworks/js/napi/netstats/src/napi_net_stats.cpp index ba09339e1..108fd2f4d 100644 --- a/frameworks/js/napi/netstats/src/napi_net_stats.cpp +++ b/frameworks/js/napi/netstats/src/napi_net_stats.cpp @@ -99,7 +99,7 @@ void NapiNetStats::CompleteGetBytes(napi_env env, napi_status status, void *data return; } napi_value info = NapiCommon::CreateCodeMessage(env, "successful", context->bytes64); - if (context->callbackRef == nullptr) { // promiss return + if (context->callbackRef == nullptr) { NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); } else { // call back napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; @@ -120,77 +120,47 @@ void NapiNetStats::CompleteGetBytes(napi_env env, napi_status status, void *data void NapiNetStats::CompleteGetIfaceStatsDetail(napi_env env, napi_status status, void *data) { NETMGR_LOG_I("CompleteGetIfaceStatsDetail"); - NetStatsAsyncContext *context = static_cast(data); - if (context == nullptr) { - NETMGR_LOG_E("context == nullptr"); - return; - } - napi_value info = nullptr; - napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; - if (context->callbackRef == nullptr) { - if (context->result != static_cast(NetStatsResultCode::ERR_NONE)) { - napi_create_int32(env, context->result, &info); - callbackValues[0] = info; - NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, context->deferred, info)); + auto context = static_cast(data); + napi_value callbackValue = nullptr; + if (status == napi_ok) { + if (context->resolved) { + napi_create_object(env, &callbackValue); + NapiCommon::SetPropertyInt64(env, callbackValue, "rxBytes", context->statsInfo.rxBytes_); + NapiCommon::SetPropertyInt64(env, callbackValue, "txBytes", context->statsInfo.txBytes_); + NapiCommon::SetPropertyInt64(env, callbackValue, "rxPackets", context->statsInfo.rxPackets_); + NapiCommon::SetPropertyInt64(env, callbackValue, "txPackets", context->statsInfo.txPackets_); } else { - napi_create_object(env, &info); - NapiCommon::SetPropertyInt64(env, info, "rxBytes", context->statsInfo.rxBytes_); - NapiCommon::SetPropertyInt64(env, info, "txBytes", context->statsInfo.txBytes_); - NapiCommon::SetPropertyInt64(env, info, "rxPackets", context->statsInfo.rxPackets_); - NapiCommon::SetPropertyInt64(env, info, "txPackets", context->statsInfo.txPackets_); - callbackValues[1] = info; - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + callbackValue = + NapiCommon::CreateErrorMessage(env, "get iface stats detail error by ipc", context->result); } } else { - napi_value recv = nullptr; - napi_value result = nullptr; - napi_value callbackFunc = nullptr; - napi_get_undefined(env, &recv); - napi_get_reference_value(env, context->callbackRef, &callbackFunc); - napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); - napi_delete_reference(env, context->callbackRef); + callbackValue = NapiCommon::CreateErrorMessage( + env, "get iface stats detail error,napi_status = " + std ::to_string(status)); } - napi_delete_async_work(env, context->work); - delete context; - context = nullptr; + NapiCommon::Handle2ValueCallback(env, context, callbackValue); } void NapiNetStats::CompleteGetUidStatsDetail(napi_env env, napi_status status, void *data) { NETMGR_LOG_I("CompleteGetUidStatsDetail"); - NetStatsAsyncContext *context = static_cast(data); - if (context == nullptr) { - NETMGR_LOG_E("context == nullptr"); - return; - } - napi_value info = nullptr; - napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; - if (context->callbackRef == nullptr) { - if (context->result != static_cast(NetStatsResultCode::ERR_NONE)) { - napi_create_int32(env, context->result, &info); - callbackValues[0] = info; - NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, context->deferred, info)); + auto context = static_cast(data); + napi_value callbackValue = nullptr; + if (status == napi_ok) { + if (context->resolved) { + napi_create_object(env, &callbackValue); + NapiCommon::SetPropertyInt64(env, callbackValue, "rxBytes", context->statsInfo.rxBytes_); + NapiCommon::SetPropertyInt64(env, callbackValue, "txBytes", context->statsInfo.txBytes_); + NapiCommon::SetPropertyInt64(env, callbackValue, "rxPackets", context->statsInfo.rxPackets_); + NapiCommon::SetPropertyInt64(env, callbackValue, "txPackets", context->statsInfo.txPackets_); } else { - napi_create_object(env, &info); - NapiCommon::SetPropertyInt64(env, info, "rxBytes", context->statsInfo.rxBytes_); - NapiCommon::SetPropertyInt64(env, info, "txBytes", context->statsInfo.txBytes_); - NapiCommon::SetPropertyInt64(env, info, "rxPackets", context->statsInfo.rxPackets_); - NapiCommon::SetPropertyInt64(env, info, "txPackets", context->statsInfo.txPackets_); - callbackValues[1] = info; - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + callbackValue = + NapiCommon::CreateErrorMessage(env, "get iface uid detail error by ipc", context->result); } } else { - napi_value recv = nullptr; - napi_value result = nullptr; - napi_value callbackFunc = nullptr; - napi_get_undefined(env, &recv); - napi_get_reference_value(env, context->callbackRef, &callbackFunc); - napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); - napi_delete_reference(env, context->callbackRef); + callbackValue = NapiCommon::CreateErrorMessage( + env, "get uid stats detail error,napi_status = " + std ::to_string(status)); } - napi_delete_async_work(env, context->work); - delete context; - context = nullptr; + NapiCommon::Handle2ValueCallback(env, context, callbackValue); } void NapiNetStats::CompleteUpdateIfacesStats(napi_env env, napi_status status, void *data) @@ -367,6 +337,7 @@ void NapiNetStats::ExecGetIfaceStatsDetail(napi_env env, void *data) } context->result = static_cast(DelayedSingleton::GetInstance()->GetIfaceStatsDetail( context->interfaceName, context->start, context->end, context->statsInfo)); + context->resolved = context->result == static_cast(NetStatsResultCode::ERR_NONE); } void NapiNetStats::ExecGetUidStatsDetail(napi_env env, void *data) @@ -379,6 +350,7 @@ void NapiNetStats::ExecGetUidStatsDetail(napi_env env, void *data) } context->result = static_cast(DelayedSingleton::GetInstance()->GetUidStatsDetail( context->interfaceName, context->uid, context->start, context->end, context->statsInfo)); + context->resolved = context->result == static_cast(NetStatsResultCode::ERR_NONE); } void NapiNetStats::ExecUpdateIfacesStats(napi_env env, void *data) @@ -415,19 +387,16 @@ napi_value NapiNetStats::GetCellularRxBytes(napi_env env, napi_callback_info inf NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); NetStatsAsyncContext *context = std::make_unique().release(); napi_value result = nullptr; - if (argc == ARGV_INDEX_0) { // promise call + if (argc == ARGV_INDEX_0) { if (context->callbackRef == nullptr) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_INDEX_1) { // callback + } else if (argc == ARGV_INDEX_1) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_0], CALLBACK_REF_CNT, &context->callbackRef)); } else { - // exception } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -446,19 +415,16 @@ napi_value NapiNetStats::GetCellularTxBytes(napi_env env, napi_callback_info inf NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); NetStatsAsyncContext *context = std::make_unique().release(); napi_value result = nullptr; - if (argc == ARGV_INDEX_0) { // promise call + if (argc == ARGV_INDEX_0) { if (context->callbackRef == nullptr) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_INDEX_1) { // callback + } else if (argc == ARGV_INDEX_1) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_0], CALLBACK_REF_CNT, &context->callbackRef)); } else { - // exception } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -477,19 +443,16 @@ napi_value NapiNetStats::GetAllRxBytes(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); NetStatsAsyncContext *context = std::make_unique().release(); napi_value result = nullptr; - if (argc == ARGV_INDEX_0) { // promise call + if (argc == ARGV_INDEX_0) { if (context->callbackRef == nullptr) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_INDEX_1) { // callback + } else if (argc == ARGV_INDEX_1) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_0], CALLBACK_REF_CNT, &context->callbackRef)); } else { - // exception } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -507,19 +470,16 @@ napi_value NapiNetStats::GetAllTxBytes(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); NetStatsAsyncContext *context = std::make_unique().release(); napi_value result = nullptr; - if (argc == ARGV_INDEX_0) { // promise call + if (argc == ARGV_INDEX_0) { if (context->callbackRef == nullptr) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_INDEX_1) { // callback + } else if (argc == ARGV_INDEX_1) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_0], CALLBACK_REF_CNT, &context->callbackRef)); } else { - // exception } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -541,20 +501,18 @@ napi_value NapiNetStats::GetUidRxBytes(napi_env env, napi_callback_info info) NETMGR_LOG_I("js argc = [%{public}zu], argv[0](uid) = [%{public}d]", argc, context->uid); napi_value result = nullptr; - if (argc == ARGV_NUM_1) { // promise call + if (argc == ARGV_NUM_1) { if (!context->callbackRef) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_NUM_2) { // callback + } else if (argc == ARGV_NUM_2) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_NUM_1], CALLBACK_REF_CNT, &context->callbackRef)); } else { NETMGR_LOG_E("Unexpected parameters."); } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -576,20 +534,18 @@ napi_value NapiNetStats::GetUidTxBytes(napi_env env, napi_callback_info info) NETMGR_LOG_I("js argc = [%{public}zu], argv[0](uid) = [%{public}d]", argc, context->uid); napi_value result = nullptr; - if (argc == ARGV_NUM_1) { // promise call + if (argc == ARGV_NUM_1) { if (!context->callbackRef) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_NUM_2) { // callback + } else if (argc == ARGV_NUM_2) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_NUM_1], CALLBACK_REF_CNT, &context->callbackRef)); } else { NETMGR_LOG_E("Unexpected parameters."); } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -614,20 +570,18 @@ napi_value NapiNetStats::GetIfaceRxBytes(napi_env env, napi_callback_info info) NETMGR_LOG_E("interfaceName = [%{public}s].\n", context->interfaceName.c_str()); napi_value result = nullptr; - if (argc == ARGV_NUM_1) { // promise call + if (argc == ARGV_NUM_1) { if (!context->callbackRef) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_NUM_2) { // callback + } else if (argc == ARGV_NUM_2) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_NUM_1], CALLBACK_REF_CNT, &context->callbackRef)); } else { NETMGR_LOG_E("Unexpected parameters."); } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -652,20 +606,18 @@ napi_value NapiNetStats::GetIfaceTxBytes(napi_env env, napi_callback_info info) NETMGR_LOG_E("interfaceName = [%{public}s].\n", context->interfaceName.c_str()); napi_value result = nullptr; - if (argc == ARGV_NUM_1) { // promise call + if (argc == ARGV_NUM_1) { if (!context->callbackRef) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_NUM_2) { // callback + } else if (argc == ARGV_NUM_2) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_NUM_1], CALLBACK_REF_CNT, &context->callbackRef)); } else { NETMGR_LOG_E("Unexpected parameters."); } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -695,8 +647,8 @@ bool MatchGetIfaceStatsDetail(napi_env env, const napi_value parameters[], size_ return false; } bool hasIface = NapiCommon::HasNamedTypeProperty(env, parameters[0], napi_string, "iface"); - bool hasStart = NapiCommon::HasNamedTypeProperty(env, parameters[0], napi_number, "start"); - bool hasEnd = NapiCommon::HasNamedTypeProperty(env, parameters[0], napi_number, "end"); + bool hasStart = NapiCommon::HasNamedTypeProperty(env, parameters[0], napi_number, "startTime"); + bool hasEnd = NapiCommon::HasNamedTypeProperty(env, parameters[0], napi_number, "endTime"); return hasIface && hasStart && hasEnd; } @@ -709,23 +661,21 @@ napi_value NapiNetStats::GetIfaceStatsDetail(napi_env env, napi_callback_info in NAPI_ASSERT(env, MatchGetIfaceStatsDetail(env, argv, argc), "type mismatch"); NetStatsAsyncContext *context = std::make_unique().release(); context->interfaceName = NapiCommon::GetNapiStringValue(env, argv[ARGV_INDEX_0], "iface"); - context->start = NapiCommon::GetNapiInt32Value(env, argv[ARGV_INDEX_0], "start"); - context->end = NapiCommon::GetNapiInt32Value(env, argv[ARGV_INDEX_0], "end"); + context->start = NapiCommon::GetNapiInt32Value(env, argv[ARGV_INDEX_0], "startTime"); + context->end = NapiCommon::GetNapiInt32Value(env, argv[ARGV_INDEX_0], "endTime"); napi_value result = nullptr; - if (argc == ARGV_NUM_1) { // promise call + if (argc == ARGV_NUM_1) { if (!context->callbackRef) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_NUM_2) { // callback + } else if (argc == ARGV_NUM_2) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_1], CALLBACK_REF_CNT, &context->callbackRef)); } else { NETMGR_LOG_E("Unexpected parameters."); } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -757,8 +707,8 @@ bool MatchGetUidStatsDetail(napi_env env, const napi_value parameters[], size_t napi_value ifaceInfo = NapiCommon::GetNamedProperty(env, parameters[ARGV_INDEX_0], "ifaceInfo"); bool hasUid = NapiCommon::HasNamedTypeProperty(env, parameters[ARGV_INDEX_0], napi_number, "uid"); bool hasIface = NapiCommon::HasNamedTypeProperty(env, ifaceInfo, napi_string, "iface"); - bool hasStart = NapiCommon::HasNamedTypeProperty(env, ifaceInfo, napi_number, "start"); - bool hasEnd = NapiCommon::HasNamedTypeProperty(env, ifaceInfo, napi_number, "end"); + bool hasStart = NapiCommon::HasNamedTypeProperty(env, ifaceInfo, napi_number, "startTime"); + bool hasEnd = NapiCommon::HasNamedTypeProperty(env, ifaceInfo, napi_number, "endTime"); return hasUid && hasIface && hasStart && hasEnd; } @@ -773,23 +723,21 @@ napi_value NapiNetStats::GetUidStatsDetail(napi_env env, napi_callback_info info context->uid = NapiCommon::GetNapiInt32Value(env, argv[ARGV_INDEX_0], "uid"); napi_value ifaceInfoValue = NapiCommon::GetNamedProperty(env, argv[ARGV_INDEX_0], "ifaceInfo"); context->interfaceName = NapiCommon::GetNapiStringValue(env, ifaceInfoValue, "iface"); - context->start = NapiCommon::GetNapiInt32Value(env, ifaceInfoValue, "start"); - context->end = NapiCommon::GetNapiInt32Value(env, ifaceInfoValue, "end"); + context->start = NapiCommon::GetNapiInt32Value(env, ifaceInfoValue, "startTime"); + context->end = NapiCommon::GetNapiInt32Value(env, ifaceInfoValue, "endTime"); napi_value result = nullptr; - if (argc == ARGV_NUM_1) { // promise call + if (argc == ARGV_NUM_1) { if (!context->callbackRef) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_NUM_2) { // callback + } else if (argc == ARGV_NUM_2) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_1], CALLBACK_REF_CNT, &context->callbackRef)); } else { NETMGR_LOG_E("Unexpected parameters."); } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -814,26 +762,23 @@ napi_value NapiNetStats::UpdateIfacesStats(napi_env env, napi_callback_info info NETMGR_LOG_E("interfaceName = [%{public}s].\n", context->interfaceName.c_str()); napi_get_value_uint32(env, argv[ARGV_INDEX_1], &context->start); napi_get_value_uint32(env, argv[ARGV_INDEX_2], &context->end); - // parse object NapiCommon::GetPropertyInt64(env, argv[ARGV_INDEX_3], "rxBytes", context->statsInfo.rxBytes_); NapiCommon::GetPropertyInt64(env, argv[ARGV_INDEX_3], "txBytes", context->statsInfo.txBytes_); NapiCommon::GetPropertyInt64(env, argv[ARGV_INDEX_3], "rxPackets", context->statsInfo.rxPackets_); NapiCommon::GetPropertyInt64(env, argv[ARGV_INDEX_3], "txPackets", context->statsInfo.txPackets_); napi_value result = nullptr; - if (argc == ARGV_NUM_4) { // promise call + if (argc == ARGV_NUM_4) { if (!context->callbackRef) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_NUM_5) { // callback + } else if (argc == ARGV_NUM_5) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_4], CALLBACK_REF_CNT, &context->callbackRef)); } else { NETMGR_LOG_E("Unexpected parameters."); } - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -852,20 +797,17 @@ napi_value NapiNetStats::UpdateStatsData(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); NetStatsAsyncContext *context = std::make_unique().release(); napi_value result = nullptr; - if (argc == ARGV_NUM_0) { // promise call + if (argc == ARGV_NUM_0) { if (!context->callbackRef) { - NAPI_CALL( - env, napi_create_promise(env, &context->deferred, &result)); // promise call, other callref call + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); } else { NAPI_CALL(env, napi_get_undefined(env, &result)); } - } else if (argc == ARGV_NUM_1) { // callback + } else if (argc == ARGV_NUM_1) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_0], CALLBACK_REF_CNT, &context->callbackRef)); } else { NETMGR_LOG_E("Unexpected parameters."); } - - // creat async work napi_value resource = nullptr; napi_value resourceName = nullptr; NAPI_CALL(env, napi_get_undefined(env, &resource)); @@ -900,8 +842,11 @@ void NapiNetStats::ExecOn(napi_env env, void *data) NETMGR_LOG_E("context == nullptr"); return; } + NETMGR_LOG_I("NetStatsCallback callbackRef = %{public}d", context->callbackRef != nullptr); EventListener listen; + listen.env = env; listen.callbackRef = context->callbackRef; + NETMGR_LOG_I("callbackRef 1 =%{public}p", (int32_t *)listen.callbackRef); listen.eventId = context->eventStatsId; NetStatsEventListenerManager::GetInstance().AddEventListener(listen); context->result = true; @@ -911,18 +856,9 @@ void NapiNetStats::CompleteOn(napi_env env, napi_status status, void *data) { NETMGR_LOG_I("CompleteOn start"); auto context = static_cast(data); - napi_value callbackValue = nullptr; - if (status == napi_ok) { - if (context->result) { - napi_get_undefined(env, &callbackValue); - } else { - callbackValue = NapiCommon::CreateErrorMessage(env, "register net stats error"); - } - } else { - callbackValue = NapiCommon::CreateErrorMessage( - env, "register net stats error cause napi_status = " + std::to_string(status)); - } - NapiCommon::Handle1ValueCallback(env, context, callbackValue); + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; } napi_value NapiNetStats::On(napi_env env, napi_callback_info info) @@ -942,6 +878,7 @@ napi_value NapiNetStats::On(napi_env env, napi_callback_info info) if (argc == ARGV_NUM_2) { if (NapiCommon::IsValidEvent(content, context->eventStatsId)) { NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_1], CALLBACK_REF_CNT, &context->callbackRef)); + NETMGR_LOG_I("NetStatsCallback callbackRef = %{public}d", context->callbackRef != nullptr); } else { NETMGR_LOG_E("NapiNetConn::On exception[event]"); return nullptr; @@ -971,18 +908,9 @@ void NapiNetStats::CompleteOff(napi_env env, napi_status status, void *data) { NETMGR_LOG_I("CompleteOff start"); auto context = static_cast(data); - napi_value callbackValue = nullptr; - if (status == napi_ok) { - if (context->result) { - napi_get_undefined(env, &callbackValue); - } else { - callbackValue = NapiCommon::CreateErrorMessage(env, "unregister net stats error"); - } - } else { - callbackValue = NapiCommon::CreateErrorMessage( - env, "unregister net stats error cause napi_status = " + std::to_string(status)); - } - NapiCommon::Handle1ValueCallback(env, context, callbackValue); + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; } napi_value NapiNetStats::Off(napi_env env, napi_callback_info info) diff --git a/frameworks/js/napi/netstats/src/net_stats_callback.cpp b/frameworks/js/napi/netstats/src/net_stats_callback.cpp index bdded20fd..d46719c1d 100644 --- a/frameworks/js/napi/netstats/src/net_stats_callback.cpp +++ b/frameworks/js/napi/netstats/src/net_stats_callback.cpp @@ -19,19 +19,43 @@ namespace OHOS { namespace NetManagerStandard { +void OnNetStatsChangeEvent(napi_env env, napi_ref callbackRef, napi_value callbackValue) +{ + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, callbackRef, &callbackFunc); + napi_value callbackValues[] = {callbackValue}; + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); +} + int32_t NetStatsCallback::NetIfaceStatsChanged(const std::string &iface) { NETMGR_LOG_I("NetStatsCallback NetIfaceStatsChanged iface = %{public}s", iface.c_str()); - std::unique_ptr event = std::make_unique(iface); - NetStatsEventListenerManager::GetInstance().SendEvent(NET_STATS_IFACE_CHANGED, event); + EventListener listen; + listen.eventId = EVENT_NET_STATS_CHANGE; + if (NetStatsEventListenerManager::GetInstance().FindListener(listen) != EVENT_NET_UNKNOW_CHANGE) { + napi_value callbackValue = nullptr; + napi_create_object(listen.env, &callbackValue); + NapiCommon::SetPropertyString(listen.env, callbackValue, "iface", iface); + OnNetStatsChangeEvent(listen.env, listen.callbackRef, callbackValue); + } return 0; }; int32_t NetStatsCallback::NetUidStatsChanged(const std::string &iface, uint32_t uid) { NETMGR_LOG_I("NetStatsCallback NetUidStatsChanged iface = %{public}s, uid = %{public}d", iface.c_str(), uid); - std::unique_ptr event = std::make_unique(iface, uid); - NetStatsEventListenerManager::GetInstance().SendEvent(NET_STATS_UID_CHANGED, event); + EventListener listen; + listen.eventId = EVENT_NET_STATS_CHANGE; + if (NetStatsEventListenerManager::GetInstance().FindListener(listen) != EVENT_NET_UNKNOW_CHANGE) { + napi_value callbackValue = nullptr; + napi_create_object(listen.env, &callbackValue); + NapiCommon::SetPropertyString(listen.env, callbackValue, "iface", iface); + NapiCommon::SetPropertyInt32(listen.env, callbackValue, "uid", static_cast(uid)); + OnNetStatsChangeEvent(listen.env, listen.callbackRef, callbackValue); + } return 0; } } // namespace NetManagerStandard diff --git a/frameworks/js/napi/netstats/src/net_stats_event_listener_handler.cpp b/frameworks/js/napi/netstats/src/net_stats_event_listener_handler.cpp deleted file mode 100644 index cb30fe4a4..000000000 --- a/frameworks/js/napi/netstats/src/net_stats_event_listener_handler.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "net_stats_event_listener_handler.h" -#include "inner_event.h" -#include "net_mgr_log_wrapper.h" -#include "i_net_stats_callback.h" - -namespace OHOS { -namespace NetManagerStandard { -NetStatsEventListenerHandler::NetStatsEventListenerHandler(const std::shared_ptr &runner) - : AppExecFwk::EventHandler(runner) -{ - NETMGR_LOG_I("NetStatsEventListenerHandler"); -} - -void NetStatsEventListenerHandler::NetIfaceStatsUpdated( - EventListener &eventListener, std::unique_ptr &event) -{ - NETMGR_LOG_I("event->iface = [%{public}s], ", event->iface.c_str()); -} - -void NetStatsEventListenerHandler::NetUidStatsUpdated( - EventListener &eventListener, std::unique_ptr &event) -{ - NETMGR_LOG_I("event->iface = [%{public}s], event->uid = [%{public}d]", event->iface.c_str(), event->uid); -} - -int32_t NetStatsEventListenerHandler::AddEventListener(EventListener &eventListener) -{ - listenerList.push_back(eventListener); - for (std::list::iterator it = listenerList.begin(); it != listenerList.end(); it++) { - NETMGR_LOG_I("eventId = [%{public}d]", it->eventId); - } - NETMGR_LOG_I("listenerList.size = [%{public}zu]", listenerList.size()); - return 0; -} - -int32_t NetStatsEventListenerHandler::RemoveEventListener(EventListener &eventListener) -{ - for (std::list::iterator it = listenerList.begin(); it != listenerList.end(); it++) { - if (it->env != nullptr && it->callbackRef != nullptr) { - napi_delete_reference(it->env, it->callbackRef); - } - } - listenerList.erase(listenerList.begin(), listenerList.end()); - NETMGR_LOG_I("listenerList.size = [%{puvlic}zu]", listenerList.size()); - return 0; -} - -void NetStatsEventListenerHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) -{ - int32_t eventId = event->GetInnerEventId(); - NETMGR_LOG_I("eventId = %{public}d", eventId); - std::unique_ptr ifaceStatsEvent = nullptr; - if (eventId == INetStatsCallback::NET_STATS_IFACE_CHANGED) { - ifaceStatsEvent = event->GetUniqueObject(); - } else { - NETMGR_LOG_E("UNKONOW_EVENT"); - } - for (auto it = listenerList.begin(); it != listenerList.end(); ++it) { - if (it->eventId == INetStatsCallback::NET_STATS_IFACE_CHANGED) { - NetIfaceStatsUpdated(*it, ifaceStatsEvent); - } else { - NETMGR_LOG_E("listener.eventId = [%{public}d] unknown", eventId); - } - } -} -} // namespace NetManagerStandard -} // namespace OHOS diff --git a/frameworks/js/napi/netstats/src/net_stats_event_listener_manager.cpp b/frameworks/js/napi/netstats/src/net_stats_event_listener_manager.cpp index d317aad78..25e4d0bd2 100644 --- a/frameworks/js/napi/netstats/src/net_stats_event_listener_manager.cpp +++ b/frameworks/js/napi/netstats/src/net_stats_event_listener_manager.cpp @@ -16,46 +16,52 @@ #include "net_stats_event_listener_manager.h" #include "iservice_registry.h" #include "net_stats_callback.h" -#include "net_stats_event_listener_handler.h" #include "net_stats_client.h" namespace OHOS { namespace NetManagerStandard { static sptr callback = (std::make_unique()).release(); -NetStatsEventListenerManager& NetStatsEventListenerManager::GetInstance() +NetStatsEventListenerManager &NetStatsEventListenerManager::GetInstance() { static NetStatsEventListenerManager instance; return instance; } -NetStatsEventListenerManager::NetStatsEventListenerManager() -{ - if (eventStateRun_ == STATE_RUNNING) { - return; - } - eventLoop = AppExecFwk::EventRunner::Create("EventListenerHandler"); - if (eventLoop.get() == nullptr) { - return; - } - eventListenerHandler = std::make_shared(eventLoop); - if (eventListenerHandler == nullptr) { - return; - } - eventLoop->Run(); - eventStateRun_ = STATE_RUNNING; -} +NetStatsEventListenerManager::NetStatsEventListenerManager() {} int32_t NetStatsEventListenerManager::AddEventListener(EventListener &eventListener) { - eventListenerHandler->AddEventListener(eventListener); + listenerList.push_back(eventListener); return DelayedSingleton::GetInstance()->RegisterNetStatsCallback(callback); } int32_t NetStatsEventListenerManager::RemoveEventListener(EventListener &eventListener) { - eventListenerHandler->RemoveEventListener(eventListener); + for (std::list::iterator it = listenerList.begin(); it != listenerList.end(); it++) { + if (it->env != nullptr && it->callbackRef != nullptr) { + napi_delete_reference(it->env, it->callbackRef); + } + } + listenerList.erase(listenerList.begin(), listenerList.end()); + return DelayedSingleton::GetInstance()->UnregisterNetStatsCallback(callback); } + +int32_t NetStatsEventListenerManager::FindListener(EventListener &listen) +{ + int32_t eventId = EVENT_NET_UNKNOW_CHANGE; + for (auto it = listenerList.begin(); it != listenerList.end(); ++it) { + NETMGR_LOG_I("NetStatsCallback it->eventId = %{public}d, callbackRef = %{public}d", it->eventId, + it->callbackRef != nullptr); + if (it->eventId == listen.eventId) { + eventId = listen.eventId; + listen.eventId = it->eventId; + listen.env = it->env; + listen.callbackRef = it->callbackRef; + } + } + return eventId; +} } // namespace NetManagerStandard } // namespace OHOS diff --git a/frameworks/native/netpolicyclient/src/net_policy_cellular_policy.cpp b/frameworks/native/netpolicyclient/src/net_policy_cellular_policy.cpp index 90d9e4d4c..fd1c44e9d 100644 --- a/frameworks/native/netpolicyclient/src/net_policy_cellular_policy.cpp +++ b/frameworks/native/netpolicyclient/src/net_policy_cellular_policy.cpp @@ -18,7 +18,7 @@ namespace OHOS { namespace NetManagerStandard { bool NetPolicyCellularPolicy::Marshalling(Parcel &parcel) const { - if (!parcel.WriteInt32(slotId_)) { + if (!parcel.WriteString(simId_)) { return false; } if (!parcel.WriteInt64(periodStartTime_)) { @@ -75,7 +75,7 @@ bool NetPolicyCellularPolicy::Unmarshalling(Parcel &parcel, std::vectorGetCellularPolicies(cellularPolicies); } -NetPolicyResultCode NetPolicyClient::SetFactoryPolicy(const std::string &slotId) +NetPolicyResultCode NetPolicyClient::SetFactoryPolicy(const std::string &simId) { sptr proxy = GetProxy(); if (proxy == nullptr) { @@ -227,7 +227,7 @@ NetPolicyResultCode NetPolicyClient::SetFactoryPolicy(const std::string &slotId) return NetPolicyResultCode::ERR_INTERNAL_ERROR; } - return proxy->SetFactoryPolicy(slotId); + return proxy->SetFactoryPolicy(simId); } NetPolicyResultCode NetPolicyClient::SetBackgroundPolicy(bool isBackgroundPolicyAllow) @@ -274,7 +274,7 @@ NetBackgroundPolicy NetPolicyClient::GetCurrentBackgroundPolicy() return proxy->GetCurrentBackgroundPolicy(); } -NetPolicyResultCode NetPolicyClient::SetSnoozePolicy(int8_t netType, int32_t slotId) +NetPolicyResultCode NetPolicyClient::SetSnoozePolicy(int8_t netType, const std::string &simId) { sptr proxy = GetProxy(); if (proxy == nullptr) { @@ -282,7 +282,7 @@ NetPolicyResultCode NetPolicyClient::SetSnoozePolicy(int8_t netType, int32_t slo return NetPolicyResultCode::ERR_INTERNAL_ERROR; } - return proxy->SetSnoozePolicy(netType, slotId); + return proxy->SetSnoozePolicy(netType, simId); } NetPolicyResultCode NetPolicyClient::SetIdleTrustlist(uint32_t uid, bool isTrustlist) diff --git a/frameworks/native/netpolicyclient/src/net_policy_quota_policy.cpp b/frameworks/native/netpolicyclient/src/net_policy_quota_policy.cpp index 8cf04a371..a65598c16 100644 --- a/frameworks/native/netpolicyclient/src/net_policy_quota_policy.cpp +++ b/frameworks/native/netpolicyclient/src/net_policy_quota_policy.cpp @@ -22,7 +22,7 @@ bool NetPolicyQuotaPolicy::Marshalling(Parcel &parcel) const if (!parcel.WriteInt8(netType_)) { return false; } - if (!parcel.WriteInt32(slotId_)) { + if (!parcel.WriteString(simId_)) { return false; } if (!parcel.WriteInt64(periodStartTime_)) { @@ -75,7 +75,7 @@ bool NetPolicyQuotaPolicy::Unmarshalling(Parcel &parcel, NetPolicyQuotaPolicy &q if (!parcel.ReadInt8(quotaPolicy.netType_)) { return false; } - if (!parcel.ReadInt32(quotaPolicy.slotId_)) { + if (!parcel.ReadString(quotaPolicy.simId_)) { return false; } if (!parcel.ReadInt64(quotaPolicy.periodStartTime_)) { @@ -115,7 +115,7 @@ bool NetPolicyQuotaPolicy::Unmarshalling(Parcel &parcel, std::vector(reply.ReadInt32()); } -NetPolicyResultCode NetPolicyServiceProxy::SetFactoryPolicy(const std::string &slotId) +NetPolicyResultCode NetPolicyServiceProxy::SetFactoryPolicy(const std::string &simId) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -384,7 +384,7 @@ NetPolicyResultCode NetPolicyServiceProxy::SetFactoryPolicy(const std::string &s return NetPolicyResultCode::ERR_INTERNAL_ERROR; } - if (!data.WriteString(slotId)) { + if (!data.WriteString(simId)) { return NetPolicyResultCode::ERR_INTERNAL_ERROR; } @@ -513,7 +513,7 @@ NetBackgroundPolicy NetPolicyServiceProxy::GetCurrentBackgroundPolicy() return static_cast(reply.ReadInt32()); } -NetPolicyResultCode NetPolicyServiceProxy::SetSnoozePolicy(int8_t netType, int32_t slotId) +NetPolicyResultCode NetPolicyServiceProxy::SetSnoozePolicy(int8_t netType, const std::string &simId) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -531,7 +531,7 @@ NetPolicyResultCode NetPolicyServiceProxy::SetSnoozePolicy(int8_t netType, int32 return NetPolicyResultCode::ERR_INTERNAL_ERROR; } - if (!data.WriteInt32(slotId)) { + if (!data.WriteString(simId)) { return NetPolicyResultCode::ERR_INTERNAL_ERROR; } diff --git a/interfaces/innerkits/dnsresolverclient/BUILD.gn b/interfaces/innerkits/dnsresolverclient/BUILD.gn index e65a82ecc..a6c306fc6 100644 --- a/interfaces/innerkits/dnsresolverclient/BUILD.gn +++ b/interfaces/innerkits/dnsresolverclient/BUILD.gn @@ -48,9 +48,12 @@ ohos_source_set("dns_resolver_parcel") { "$INNERKITS_ROOT/dnsresolverclient/include", ] - deps = [ "$NETMANAGER_BASE_ROOT/utils:net_manager_common" ] + deps = [ + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "//utils/native/base:utils", + ] - external_deps = [ "utils_base:utils" ] + external_deps = [] if (is_standard_system) { external_deps += [ "hiviewdfx_hilog_native:libhilog" ] } else { diff --git a/interfaces/innerkits/netconnclient/BUILD.gn b/interfaces/innerkits/netconnclient/BUILD.gn index 7d7aadf96..98bbe9b1b 100644 --- a/interfaces/innerkits/netconnclient/BUILD.gn +++ b/interfaces/innerkits/netconnclient/BUILD.gn @@ -52,9 +52,12 @@ ohos_source_set("net_conn_parcel") { "$INNERKITS_ROOT/netconnclient/include", ] - deps = [ "$NETMANAGER_BASE_ROOT/utils:net_manager_common" ] + deps = [ + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "//utils/native/base:utils", + ] - external_deps = [ "utils_base:utils" ] + external_deps = [] if (is_standard_system) { external_deps += [ "hiviewdfx_hilog_native:libhilog" ] } else { diff --git a/interfaces/innerkits/netpolicyclient/BUILD.gn b/interfaces/innerkits/netpolicyclient/BUILD.gn index 1e0839918..3f5a38a6e 100644 --- a/interfaces/innerkits/netpolicyclient/BUILD.gn +++ b/interfaces/innerkits/netpolicyclient/BUILD.gn @@ -44,9 +44,12 @@ ohos_source_set("net_policy_parcel") { include_dirs = [ "$INNERKITS_ROOT/netpolicyclient/include" ] - deps = [ "$NETMANAGER_BASE_ROOT/utils:net_manager_common" ] + deps = [ + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "//utils/native/base:utils", + ] - external_deps = [ "utils_base:utils" ] + external_deps = [] if (is_standard_system) { external_deps += [ "hiviewdfx_hilog_native:libhilog" ] } else { diff --git a/interfaces/innerkits/netpolicyclient/include/net_policy_cellular_policy.h b/interfaces/innerkits/netpolicyclient/include/net_policy_cellular_policy.h index 933a56fd8..b8b473d41 100644 --- a/interfaces/innerkits/netpolicyclient/include/net_policy_cellular_policy.h +++ b/interfaces/innerkits/netpolicyclient/include/net_policy_cellular_policy.h @@ -24,13 +24,13 @@ namespace OHOS { namespace NetManagerStandard { struct NetPolicyCellularPolicy : public Parcelable { /* slot ID, get from telephone module */ - int32_t slotId_ = 0; + std::string simId_; /* Time rubbing, for example:1636598990 */ int64_t periodStartTime_ = -1; /* Unit: Month for example:M1 (The 1st of each month) */ std::string periodDuration_ = "M1"; - std::string title_ = ""; - std::string summary_ = ""; + std::string title_; + std::string summary_; /* Limit threshold */ int64_t limitBytes_ = -1; /* Limit action; 1 : prohibit; 2 : charging; 3 : Speed limit */ @@ -39,7 +39,7 @@ struct NetPolicyCellularPolicy : public Parcelable { int64_t usedBytes_ = -1; int64_t usedTimeDuration_ = -1; /* possessor */ - std::string possessor_ = ""; + std::string possessor_; virtual bool Marshalling(Parcel &parcel) const override; static bool Marshalling(Parcel &parcel, const std::vector &cellularPolicies); diff --git a/interfaces/innerkits/netpolicyclient/include/net_policy_client.h b/interfaces/innerkits/netpolicyclient/include/net_policy_client.h index ea3a73f97..263364ba9 100644 --- a/interfaces/innerkits/netpolicyclient/include/net_policy_client.h +++ b/interfaces/innerkits/netpolicyclient/include/net_policy_client.h @@ -107,12 +107,12 @@ public: */ NetPolicyResultCode GetCellularPolicies(std::vector &cellularPolicies); /** - * @brief SetFactoryPolicy reset policys for slotId + * @brief SetFactoryPolicy reset policys for simId * - * @param slotId subscriber ID, get from telephone module + * @param simId ID, get from telephone module * @return Returns 0, successfully */ - NetPolicyResultCode SetFactoryPolicy(const std::string &slotId); + NetPolicyResultCode SetFactoryPolicy(const std::string &simId); /** * @brief SetBackgroundPolicy reset backgroundpolicy for all app * @@ -144,7 +144,7 @@ public: * * @return Returns 0, successfully */ - NetPolicyResultCode SetSnoozePolicy(int8_t netType, int32_t slotId); + NetPolicyResultCode SetSnoozePolicy(int8_t netType, const std::string &simId); /** * @brief SetIdleTrustlist for add trust list for Idle status * diff --git a/interfaces/innerkits/netpolicyclient/include/net_policy_quota_policy.h b/interfaces/innerkits/netpolicyclient/include/net_policy_quota_policy.h index 5fc32d37e..c68ed8ffc 100644 --- a/interfaces/innerkits/netpolicyclient/include/net_policy_quota_policy.h +++ b/interfaces/innerkits/netpolicyclient/include/net_policy_quota_policy.h @@ -25,8 +25,8 @@ namespace NetManagerStandard { struct NetPolicyQuotaPolicy : public Parcelable { /* netType value in NetBearType */ int8_t netType_ = -1; - /* slot ID, get from telephone module */ - int32_t slotId_ = 0; + /* IccId, get from telephone module */ + std::string simId_; /* Time rubbing, for example:1636598990 */ int64_t periodStartTime_ = -1; /* Unit: Month for example:M1 (The 1st of each month) */ diff --git a/interfaces/innerkits/netpolicyclient/include/proxy/i_net_policy_callback.h b/interfaces/innerkits/netpolicyclient/include/proxy/i_net_policy_callback.h index 7ed83fe93..8f0ce8f57 100644 --- a/interfaces/innerkits/netpolicyclient/include/proxy/i_net_policy_callback.h +++ b/interfaces/innerkits/netpolicyclient/include/proxy/i_net_policy_callback.h @@ -39,7 +39,7 @@ public: public: virtual int32_t NetUidPolicyChanged(uint32_t uid, NetUidPolicy policy) = 0; virtual int32_t NetCellularPolicyChanged(const std::vector &cellularPolicies) = 0; - virtual int32_t NetStrategySwitch(int32_t slotId, bool enable) = 0; + virtual int32_t NetStrategySwitch(const std::string &simId, bool enable) = 0; virtual int32_t NetBackgroundPolicyChanged(bool isBackgroundPolicyAllow) = 0; }; } // namespace NetManagerStandard diff --git a/interfaces/innerkits/netpolicyclient/include/proxy/i_net_policy_service.h b/interfaces/innerkits/netpolicyclient/include/proxy/i_net_policy_service.h index 8d9386ba6..70fdc8a7f 100644 --- a/interfaces/innerkits/netpolicyclient/include/proxy/i_net_policy_service.h +++ b/interfaces/innerkits/netpolicyclient/include/proxy/i_net_policy_service.h @@ -64,12 +64,12 @@ public: virtual NetPolicyResultCode GetNetQuotaPolicies(std::vector "aPolicies) = 0; virtual NetPolicyResultCode SetCellularPolicies(const std::vector &cellularPolicies) = 0; virtual NetPolicyResultCode GetCellularPolicies(std::vector &cellularPolicies) = 0; - virtual NetPolicyResultCode SetFactoryPolicy(const std::string &slotId) = 0; + virtual NetPolicyResultCode SetFactoryPolicy(const std::string &simId) = 0; virtual NetPolicyResultCode SetBackgroundPolicy(bool backgroundPolicy) = 0; virtual bool GetBackgroundPolicy() = 0; virtual bool GetBackgroundPolicyByUid(uint32_t uid) = 0; virtual NetBackgroundPolicy GetCurrentBackgroundPolicy() = 0; - virtual NetPolicyResultCode SetSnoozePolicy(int8_t netType, int32_t slotId) = 0; + virtual NetPolicyResultCode SetSnoozePolicy(int8_t netType, const std::string &simId) = 0; virtual NetPolicyResultCode SetIdleTrustlist(uint32_t uid, bool isTrustlist) = 0; virtual NetPolicyResultCode GetIdleTrustlist(std::vector &uids) = 0; }; diff --git a/interfaces/innerkits/netpolicyclient/include/proxy/net_policy_callback_stub.h b/interfaces/innerkits/netpolicyclient/include/proxy/net_policy_callback_stub.h index 531564237..942cf0754 100644 --- a/interfaces/innerkits/netpolicyclient/include/proxy/net_policy_callback_stub.h +++ b/interfaces/innerkits/netpolicyclient/include/proxy/net_policy_callback_stub.h @@ -34,7 +34,7 @@ public: public: int32_t NetUidPolicyChanged(uint32_t uid, NetUidPolicy policy) override; int32_t NetCellularPolicyChanged(const std::vector &cellularPolicies) override; - int32_t NetStrategySwitch(int32_t slotId, bool enable) override; + int32_t NetStrategySwitch(const std::string &simId, bool enable) override; int32_t NetBackgroundPolicyChanged(bool isBackgroundPolicyAllow) override; private: diff --git a/interfaces/innerkits/netpolicyclient/include/proxy/net_policy_service_proxy.h b/interfaces/innerkits/netpolicyclient/include/proxy/net_policy_service_proxy.h index 7a6b565bd..b23dc54c5 100644 --- a/interfaces/innerkits/netpolicyclient/include/proxy/net_policy_service_proxy.h +++ b/interfaces/innerkits/netpolicyclient/include/proxy/net_policy_service_proxy.h @@ -40,12 +40,12 @@ public: NetPolicyResultCode GetNetQuotaPolicies(std::vector "aPolicies) override; NetPolicyResultCode SetCellularPolicies(const std::vector &cellularPolicies) override; NetPolicyResultCode GetCellularPolicies(std::vector &cellularPolicies) override; - NetPolicyResultCode SetFactoryPolicy(const std::string &slotId) override; + NetPolicyResultCode SetFactoryPolicy(const std::string &simId) override; NetPolicyResultCode SetBackgroundPolicy(bool backgroundPolicy) override; bool GetBackgroundPolicy() override; bool GetBackgroundPolicyByUid(uint32_t uid) override; NetBackgroundPolicy GetCurrentBackgroundPolicy() override; - NetPolicyResultCode SetSnoozePolicy(int8_t netType, int32_t slotId) override; + NetPolicyResultCode SetSnoozePolicy(int8_t netType, const std::string &simId) override; NetPolicyResultCode SetIdleTrustlist(uint32_t uid, bool isTrustlist) override; NetPolicyResultCode GetIdleTrustlist(std::vector &uids) override; diff --git a/interfaces/innerkits/netstatsclient/BUILD.gn b/interfaces/innerkits/netstatsclient/BUILD.gn index 5559eaba0..dbeff8b8a 100644 --- a/interfaces/innerkits/netstatsclient/BUILD.gn +++ b/interfaces/innerkits/netstatsclient/BUILD.gn @@ -41,9 +41,12 @@ ohos_source_set("net_stats_parcel") { include_dirs = [ "$INNERKITS_ROOT/netstatsclient/include" ] - deps = [ "$NETMANAGER_BASE_ROOT/utils:net_manager_common" ] + deps = [ + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "//utils/native/base:utils", + ] - external_deps = [ "utils_base:utils" ] + external_deps = [] if (is_standard_system) { external_deps += [ "hiviewdfx_hilog_native:libhilog" ] } else { diff --git a/interfaces/innerkits/netstatsclient/include/net_stats_constants.h b/interfaces/innerkits/netstatsclient/include/net_stats_constants.h index 68673239b..841c88f7d 100644 --- a/interfaces/innerkits/netstatsclient/include/net_stats_constants.h +++ b/interfaces/innerkits/netstatsclient/include/net_stats_constants.h @@ -18,10 +18,12 @@ namespace OHOS { namespace NetManagerStandard { +constexpr int16_t LIMIT_STATS_CALLBACK_NUM = 200; enum class NetStatsResultCode { ERR_NONE = 0, ERR_INTERNAL_ERROR = (-1), - ERR_INVALID_PARAMETER = (-2) + ERR_INVALID_PARAMETER = (-2), + ERR_INVALID_TIME_PERIOD = (-3), }; } // namespace NetManagerStandard } // namespace OHOS diff --git a/interfaces/kits/js/@ohos.net.connection.d.ts b/interfaces/kits/js/@ohos.net.connection.d.ts new file mode 100644 index 000000000..1762a3e7b --- /dev/null +++ b/interfaces/kits/js/@ohos.net.connection.d.ts @@ -0,0 +1,510 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {AsyncCallback, Callback} from "./basic"; +import http from "./@ohos.net.http"; +import socket from "./@ohos.net.socket"; + +/** + * Provides interfaces to manage and use data networks. + * + * @since 8 + * @sysCap SystemCapability.Communication.NetManager + * @devices phone, tablet, tv, wearable, car + */ +declare namespace connection { + type HttpRequest = http.HttpRequest; + type TCPSocket = socket.TCPSocket; + type UDPSocket = socket.UDPSocket; + + /** + * Create a network connection with optional netSpefifier and timeout. + * + * @param netSpecifier Indicates the network specifier. See {@link NetSpecifier}. + * @param timeout The time in milliseconds to attempt looking for a suitable network before + * {@link NetConnection#netUnavailable} is called. + */ + function createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; + + /** + * Obtains the data network that is activated by default. + * + *

To call this method, you must have the {@code ohos.permission.GET_NETWORK_INFO} permission. + * + * @param callback Returns the {@link NetHandle} object; + * returns {@code null} if the default network is not activated. + * @permission ohos.permission.GET_NETWORK_INFO + */ + function getDefaultNet(callback: AsyncCallback): void; + function getDefaultNet(): Promise; + + /** + * Obtains the list of data networks that are activated. + * + *

To invoke this method, you must have the {@code ohos.permission.GET_NETWORK_INFO} permission. + * + * @param callback Returns the {@link NetHandle} object; returns {@code null} if no network is activated. + * @permission ohos.permission.GET_NETWORK_INFO + */ + function getAllNets(callback: AsyncCallback>): void; + function getAllNets(): Promise>; + + /** + * Queries the connection properties of a network. + * + *

This method requires the {@code ohos.permission.GET_NETWORK_INFO} permission. + * + * @param netHandle Indicates the network to be queried. + * @param callback Returns the {@link ConnectionProperties} object. + * @permission ohos.permission.GET_NETWORK_INFO + */ + function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback): void; + function getConnectionProperties(netHandle: NetHandle): Promise; + + /** + * Obtains {@link NetCapabilities} of a {@link NetHandle} object. + * + *

To invoke this method, you must have the {@code ohos.permission.GET_NETWORK_INFO} permission. + * + * @param netHandle Indicates the handle. See {@link NetHandle}. + * @param callback Returns {@link NetCapabilities}; returns {@code null} if {@code handle} is invalid. + * @permission ohos.permission.GET_NETWORK_INFO + */ + function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback): void; + function getNetCapabilities(netHandle: NetHandle): Promise; + + /** + * Checks whether the default data network is activated. + * + * @param callback Returns {@code true} if the default data network is activated; returns {@code false} otherwise. + */ + function hasDefaultNet(callback: AsyncCallback): void; + function hasDefaultNet(): Promise; + + /** + * Enables the airplane mode for a device. + * + * @systemapi Hide this for inner system use. Only used for system app. + */ + function enableAirplaneMode(callback: AsyncCallback): void; + function enableAirplaneMode(): Promise; + + /** + * Disables the airplane mode for a device. + * + * @systemapi Hide this for inner system use. Only used for system app. + */ + function disableAirplaneMode(callback: AsyncCallback): void; + function disableAirplaneMode(): Promise; + + /** + * Reports the network state is connected. + * + * @param netHandle Indicates the network whose state is to be reported. + * @permission ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET + */ + function reportNetConnected(netHandle: NetHandle, callback: AsyncCallback): void; + function reportNetConnected(netHandle: NetHandle): Promise; + + /** + * Reports the network state is disconnected. + * + * @param netHandle Indicates the network whose state is to be reported. + * @permission ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET + */ + function reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback): void; + function reportNetDisconnected(netHandle: NetHandle): Promise; + + /** + * Resolves the host name to obtain all IP addresses based on the default data network. + * + * @param host Indicates the host name or the domain. + * @param callback Returns the NetAddress list. + * @permission ohos.permission.GET_NETWORK_INFO + */ + function getAddressesByName(host: string, callback: AsyncCallback>): void; + function getAddressesByName(host: string): Promise>; + + export interface NetConnection { + on(type: 'netAvailable', callback: Callback): void; + + on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; + + on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void; + + on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; + + on(type: 'netLost', callback: Callback): void; + + on(type: 'netUnavailable', callback: Callback): void; + + /** + * Receives status change notifications of a specified network. + * + * @permission ohos.permission.GET_NETWORK_INFO + */ + register(callback: AsyncCallback): void; + + /** + * Cancels listening for network status changes. + */ + unregister(callback: AsyncCallback): void; + } + + export interface NetSpecifier { + netCapabilities: NetCapabilities; + bearerPrivateIdentifier?: string; + } + + export interface NetHandle { + netId: number; + + /** + * Binds a TCPSocket or UDPSocket to the current network. All data flows from + * the socket will use this network, without being subject to {@link setAppNet}. + * Before using this method, ensure that the socket is disconnected. + * + * @param socketParam Indicates the TCPSocket or UDPSocket object. + */ + bindSocket(socketParam: TCPSocket | UDPSocket, callback: AsyncCallback): void; + bindSocket(socketParam: TCPSocket | UDPSocket): Promise; + + /** + * Accesses a specified URL. + * + * @param url Indicates a URL connection. + * @param callback Returns a {@code URLConnection} object matching the given {@code url}. + */ + openConnection(url: string, callback: AsyncCallback): void; + openConnection(url: string, proxy: NetProxy, callback: AsyncCallback): void; + openConnection(url: string, proxy?: NetProxy): Promise; + + /** + * Resolves a host name to obtain all IP addresses based on the specified NetHandle. + * + * @param host Indicates the host name or the domain. + * @param callback Returns the NetAddress list. + */ + getAddressesByName(host: string, callback: AsyncCallback>): void; + getAddressesByName(host: string): Promise>; + + /** + * Resolves a host name to obtain the first IP address based on the specified NetHandle. + * + * @param host Indicates the host name or the domain. + * @return Returns the first NetAddress. + */ + getAddressByName(host: string, callback: AsyncCallback): void; + getAddressByName(host: string): Promise; + } + + export interface NetCapabilities { + linkUpBandwidthKbps?: number; + linkDownBandwidthKbps?: number; + networkCap?: Array; + bearerTypes: Array; + } + + export enum NetCap { + /** + * Indicates that the network can access the carrier's MMSC to send and receive multimedia messages. + */ + NET_CAPABILITY_MMS = 0, + + /** + * Indicates that the network can access the carrier's SUPL server. + */ + NET_CAPABILITY_SUPL = 1, + + /** + * Indicates that the network can access the carrier's DUN or Tethering gateway. + */ + NET_CAPABILITY_DUN = 2, + + /** + * Indicates that the network can access the FOTA server for remote device upgrade. + */ + NET_CAPABILITY_FOTA = 3, + + /** + * Indicates that the network can access the IMS server. + */ + NET_CAPABILITY_IMS = 4, + + /** + * Indicates that the network can access the carrier's CBS server. + */ + NET_CAPABILITY_CBS = 5, + + /** + * Indicates that the network can be used for Wi-Fi Direct. + */ + NET_CAPABILITY_WIFI_P2P = 6, + + /** + * Indicates that the network can access the carrier's Initial Attach server. + */ + NET_CAPABILITY_IA = 7, + + /** + * Indicates that the network can access the carrier's RCS server. + */ + NET_CAPABILITY_RCS = 8, + + /** + * Indicates that the network can access the carrier's XCAP server. + */ + NET_CAPABILITY_XCAP = 9, + + /** + * Indicates that the network can access the carrier's IMS emergency call server. + */ + NET_CAPABILITY_EIMS = 10, + + /** + * Indicates that the network traffic is not metered. + */ + NET_CAPABILITY_NOT_METERED = 11, + + /** + * Indicates that the network can access the Internet. + */ + NET_CAPABILITY_INTERNET = 12, + + /** + * Indicates that the network is not restricted. + */ + NET_CAPABILITY_NOT_RESTRICTED = 13, + + /** + * Indicates that the network is trusted. + */ + NET_CAPABILITY_TRUSTED = 14, + + /** + * Indicates that the network does not use a VPN. + */ + NET_CAPABILITY_NOT_VPN = 15, + + /** + * Indicates that the network is available. + */ + NET_CAPABILITY_VALIDATED = 16, + + /** + * Indicates that this network was found to have a captive portal in place last time it was + * probed. + */ + NET_CAPABILITY_CAPTIVE_PORTAL = 17, + + /** + * Indicates that the network is unavailable during roaming. + */ + NET_CAPABILITY_NOT_ROAMING = 18, + + /** + * Indicates that the network is available only for foreground applications. + */ + NET_CAPABILITY_FOREGROUND = 19, + + /** + * Indicates that the network is not congested. + */ + NET_CAPABILITY_NOT_CONGESTED = 20, + + /** + * Indicates that the network is not suspended. + */ + NET_CAPABILITY_NOT_SUSPENDED = 21, + + /** + * Indicates that traffic that goes through this network is paid by oem. For example, + * this network can be used by system apps to upload telemetry data. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_OEM_PAID = 22, + + /** + * Indicates that the network can access the Mission Critical server of the carrier. + */ + NET_CAPABILITY_MCX = 23, + + /** + * Indicates that the network was tested to only provide partial connectivity. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_PARTIAL_CONNECTIVITY = 24, + + /** + * Indicates that the network extends cap + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_HW_BASE = NET_CAPABILITY_PARTIAL_CONNECTIVITY, + + /** + * Indicates that the network can access the BIP0 server. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_BIP0 = NET_CAPABILITY_HW_BASE + 1, + + /** + * Indicates that the network can access the BIP1 server. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_BIP1 = NET_CAPABILITY_HW_BASE + 2, + + /** + * Indicates that the network can access the BIP2 server. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_BIP2 = NET_CAPABILITY_HW_BASE + 3, + + /** + * Indicates that the network can access the BIP3 server. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_BIP3 = NET_CAPABILITY_HW_BASE + 4, + + /** + * Indicates that the network can access the BIP4 server. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_BIP4 = NET_CAPABILITY_HW_BASE + 5, + + /** + * Indicates that the network can access the BIP5 server. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_BIP5 = NET_CAPABILITY_HW_BASE + 6, + + /** + * Indicates that the network can access the BIP6 server. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_BIP6 = NET_CAPABILITY_HW_BASE + 7, + + /** + * Indicates that the network can access internal default servers. + * + * @systemapi Hide this for inner system use. + */ + NET_CAPABILITY_INTERNAL_DEFAULT + } + + export enum NetBearType { + /** + * Indicates that the network is based on a cellular network. + */ + BEARER_CELLULAR = 0, + + /** + * Indicates that the network is based on a Wi-Fi network. + */ + BEARER_WIFI = 1, + + /** + * Indicates that the network is based on a Bluetooth network. + */ + BEARER_BLUETOOTH = 2, + + /** + * Indicates that the network is an Ethernet network. + */ + BEARER_ETHERNET = 3, + + /** + * Indicates that the network is a VPN. + */ + BEARER_VPN = 4, + + /** + * Indicates that the network is a Wi-Fi Aware network. + */ + BEARER_WIFI_AWARE = 5, + + /** + * Indicates that the network is a LoWPAN network. + */ + BEARER_LOWPAN = 6 + } + + export interface ConnectionProperties { + interfaceName: string; + isUsePrivateDns: boolean; + privateDnsServerName: string; + domains: string; + httpProxy: HttpProxy; + linkAddresses: Array; + dnses: Array; + routes: Array; + mtu: number; + } + + export interface HttpProxy { + host: string; + port: number; + parsedExclusionList: Array; + } + + export interface RouteInfo { + interface: string; + destination: LinkAddress; + gateway: NetAddress; + hasGateway: boolean; + isDefaultRoute: boolean; + } + + export interface LinkAddress { + address: NetAddress; + prefixLength: number; + } + + /** + * @since 7 + */ + export interface NetAddress { + address: string; + family?: number; // IPv4 = 1; IPv6 = 2, default is IPv4 + port?: number; // [0, 65535] + } + + export interface NetProxy { + type: ProxyType; + address: NetAddress; + } + + export enum ProxyType { + /** + * Represents proxy for high level protocols such as HTTP or FTP. + */ + HTTP, + /** + * Represents a SOCKS (V4 or V5) proxy. + */ + SOCKS + } +} + +export default connection; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.net.policy.d.ts b/interfaces/kits/js/@ohos.net.policy.d.ts new file mode 100644 index 000000000..393e675d0 --- /dev/null +++ b/interfaces/kits/js/@ohos.net.policy.d.ts @@ -0,0 +1,204 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {AsyncCallback, Callback} from "./basic"; +import connection from "./@ohos.net.connection"; + +/** + * Provides interfaces to manage network policy rules. + * + * @since 8 + * @sysCap SystemCapability.Communication.NetManager + * @devices phone, tablet, tv, wearable, car + */ +declare namespace policy { + type NetBearType = connection.NetBearType; + + /** + * Set the background policy. + * + * @param allow Indicates whether the background appications are allowed to access network. + * @permission ohos.permission.SET_NETWORK_POLICY + * @systemapi Hide this for inner system use. + */ + function setBackgroundPolicy(allow: boolean, callback: AsyncCallback): void ; + function setBackgroundPolicy(allow: boolean): Promise; + + /** + * Query the background policy. + * + * @param callback Returns the background policy. + * For details, see {@link BackgroundPolicy#BACKGROUND_POLICY_DISABLE}. + * @permission ohos.permission.GET_NETWORK_POLICY + * @systemapi Hide this for inner system use. + */ + function getBackgroundPolicy(callback: AsyncCallback): void; + function getBackgroundPolicy(): Promise; + + /** + * Set policy for the specified UID. + * + * @param uid the specified UID of application. + * @param policy the policy of the current UID of application. + * For details, see {@link NetUidPolicy}. + * @permission ohos.permission.SET_NETWORK_POLICY + * @systemapi Hide this for inner system use. + */ + function setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback): void; + function setPolicyByUid(uid: number, policy: NetUidPolicy): Promise; + + /** + * Query the policy of the specified UID. + * + * @param uid the specified UID of application. + * @param callback Returns the policy of the current UID of application. + * For details, see {@link NetUidPolicy}. + * @permission ohos.permission.GET_NETWORK_POLICY + * @systemapi Hide this for inner system use. + */ + function getPolicyByUid(uid: number, callback: AsyncCallback): void; + function getPolicyByUid(uid: number): Promise; + + /** + * Query the application UIDs of the specified policy. + * + * @param policy the policy of the current UID of application. + * For details, see {@link NetUidPolicy}. + * @param callback Returns the UIDs of the specified policy. + * @permission ohos.permission.GET_NETWORK_POLICY + * @systemapi Hide this for inner system use. + */ + function getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback>): void; + function getUidsByPolicy(policy: NetUidPolicy): Promise>; + + /** + * Register and unregister network policy listener. + * + * @permission ohos.permission.CONNECTIVITY_INTERNAL + * @systemapi Hide this for inner system use. + */ + function on(type: 'netUidPolicyChange', callback: Callback<{ uid: number, policy: NetUidPolicy }>): void; + + /** + * @systemapi Hide this for inner system use. + */ + function off(type: 'netUidPolicyChange', callback?: Callback<{ uid: number, policy: NetUidPolicy }>): void; + + /** + * Get network policies. + * + * @return See {@link NetPolicyQuotaPolicy}. + * @permission ohos.permission.GET_NETWORK_POLICY + * @systemapi Hide this for inner system use. + */ + function getNetQuotaPolicies(callback: AsyncCallback>): void; + function getNetQuotaPolicies(): Promise>; + + /** + * Set network policies. + * + * @param quotaPolicies Indicates {@link NetPolicyQuotaPolicy}. + * @permission ohos.permission.SET_NETWORK_POLICY + * @systemapi Hide this for inner system use. + */ + function setNetQuotaPolicies(quotaPolicies: Array, callback: AsyncCallback): void; + function setNetQuotaPolicies(quotaPolicies: Array): Promise; + + /** + * Temporarily deactivate the specified network management policy. + * + * @param simId Indicates the specified sim that is valid when netType is cellular. + * @param netType Indicates the {@link NetBearType}. + * @permission ohos.permission.SET_NETWORK_POLICY + * @systemapi Hide this for inner system use. + */ + function setSnoozePolicy(simId: number, netType: NetBearType, callback: AsyncCallback): void; + function setSnoozePolicy(simId: number, netType: NetBearType): Promise; + + /** + * Reset the specified network management policy. + * + * @param simId Indicates the specified sim that is valid when netType is cellular. + * @permission ohos.permission.SET_NETWORK_POLICY + * @systemapi Hide this for inner system use. + */ + function setFactoryPolicy(simId: number, callback: AsyncCallback): void; + function setFactoryPolicy(simId: number): Promise; + + export enum BackgroundPolicy { + /** + * Indicates that applications can use metered networks. + */ + BACKGROUND_POLICY_DISABLE = 1, + + /** + * Indicates that only applications in the allowlist can use metered networks. + */ + BACKGROUND_POLICY_ALLOWLISTED = 2, + + /** + * Indicates that applications cannot use metered networks. + */ + BACKGROUND_POLICY_ENABLED = 3 + } + + /** + * @systemapi Hide this for inner system use. + */ + export interface NetPolicyQuotaPolicy { + /* netType value range in NetBearType */ + netType: NetBearType; + /* The ID of the target card, valid when netType is BEARER_CELLULAR. */ + simId: number; + /* Time rubbing, for example:1636598990 */ + periodStartTime: number; + /* Unit: The cycle starts on one day of month, for example: M1 Indicates the 1st of each month. */ + periodDuration: string; + /* Alarm threshold */ + warningBytes: number; + /* Limit threshold */ + limitBytes: number; + /* Time rubbing, for example:1636598990, -1 Indicates the policy need not snooze */ + lastLimitSnooze?: number; + /* @see{MeteringMode} */ + metered?: MeteringMode; + } + + /** + * @systemapi Hide this for inner system use. + */ + export enum NetUidPolicy { + NET_POLICY_NONE = 0, + NET_POLICY_ALLOW_METERED_BACKGROUND = 1 << 0, + NET_POLICY_TEMPORARY_ALLOW_METERED = 1 << 1, + NET_POLICY_REJECT_METERED_BACKGROUND = 1 << 2, + NET_POLICY_ALLOW_METERED = 1 << 3, + NET_POLICY_REJECT_METERED = 1 << 4, + NET_POLICY_ALLOW_ALL = 1 << 5, + NET_POLICY_REJECT_ALL = 1 << 6 + } + + /** + * @systemapi Hide this for inner system use. + */ + export enum MeteringMode { + /* non metering */ + UN_METERED = 0, + /* metering */ + METERED = 1 + } +} + +export default policy; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.net.statistics.d.ts b/interfaces/kits/js/@ohos.net.statistics.d.ts new file mode 100644 index 000000000..18b596feb --- /dev/null +++ b/interfaces/kits/js/@ohos.net.statistics.d.ts @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {AsyncCallback} from "./basic"; + +/** + * Obtains traffic statistics. + * + * @since 8 + * @sysCap SystemCapability.Communication.NetManager + * @devices phone, tablet, tv, wearable, car + */ +declare namespace statistics { + /** + * Queries the data traffic (including all TCP and UDP data packets) received through a specified NIC. + * + * @param nic Indicates the NIC name. + * @param callback Returns the data traffic received through the specified NIC. + */ + function getIfaceRxBytes(nic: string, callback: AsyncCallback): void; + function getIfaceRxBytes(nic: string): Promise; + + /** + * Queries the data traffic (including all TCP and UDP data packets) sent through a specified NIC. + * + * @param nic Indicates the NIC name. + * @param callback Returns the data traffic sent through the specified NIC. + */ + function getIfaceTxBytes(nic: string, callback: AsyncCallback): void; + function getIfaceTxBytes(nic: string): Promise; + + /** + * Queries the data traffic (including all TCP and UDP data packets) received through the cellular network. + * + * @param callback Returns the data traffic received through the cellular network. + */ + function getCellularRxBytes(callback: AsyncCallback): void; + function getCellularRxBytes(): Promise; + + /** + * Queries the data traffic (including all TCP and UDP data packets) sent through the cellular network. + * + * @param callback Returns the data traffic sent through the cellular network. + */ + function getCellularTxBytes(callback: AsyncCallback): void; + function getCellularTxBytes(): Promise; + + /** + * Queries the data traffic (including all TCP and UDP data packets) sent through all NICs. + * + * @param callback Returns the data traffic sent through all NICs. + */ + function getAllTxBytes(callback: AsyncCallback): void; + function getAllTxBytes(): Promise; + + /** + * Queries the data traffic (including all TCP and UDP data packets) received through all NICs. + * + * @param callback Returns the data traffic received through all NICs. + */ + function getAllRxBytes(callback: AsyncCallback): void; + function getAllRxBytes(): Promise; + + /** + * Queries the data traffic (including all TCP and UDP data packets) received by a specified application. + * This method applies only to system applications and your own applications. + * + * @param uid Indicates the process ID of the application. + * @param callback Returns the data traffic received by the specified application. + */ + function getUidRxBytes(uid: number, callback: AsyncCallback): void; + function getUidRxBytes(uid: number): Promise; + + /** + * Queries the data traffic (including all TCP and UDP data packets) sent by a specified application. + * This method applies only to system applications and your own applications. + * + * @param uid Indicates the process ID of the application. + * @param callback Returns the data traffic sent by the specified application. + */ + function getUidTxBytes(uid: number, callback: AsyncCallback): void; + function getUidTxBytes(uid: number): Promise; + + /** + * Register notifications of network traffic updates, restrictions, and warnings. + * + * @permission ohos.permission.GET_NETSTATS_SUMMARY + * @systemapi Hide this for inner system use. + */ + function on(type: 'netStatsChange', callback: Callback<{ iface: string, uid?: number }>): void; + + /** + * @systemapi Hide this for inner system use. + */ + function off(type: 'netStatsChange', callback?: Callback<{ iface: string, uid?: number }>): void; + + /** + * Get the traffic usage details of the network interface in the specified time period. + * + * @param IfaceInfo Indicates the handle. See {@link IfaceInfo}. + * @permission ohos.permission.GET_NETSTATS_SUMMARY + * @systemapi Hide this for inner system use. + */ + function getIfaceStatsDetail(ifaceInfo: IfaceInfo, callback: AsyncCallback): void; + function getIfaceStatsDetail(ifaceInfo: IfaceInfo): Promise; + + /** + * Get the traffic usage details of the specified time period of the application. + * + * @param UidStatsInfo Indicates the handle. See {@link UidStatsInfo}. + * @permission ohos.permission.GET_NETSTATS_SUMMARY + * @systemapi Hide this for inner system use. + */ + function getUidStatsDetail(uidStatsInfo: UidStatsInfo, callback: AsyncCallback): void; + function getUidStatsDetail(uidStatsInfo: UidStatsInfo): Promise; + + /** + * @systemapi Hide this for inner system use. + */ + export interface IfaceInfo { + iface: string; + startTime: number; + endTime: number; + } + + /** + * @systemapi Hide this for inner system use. + */ + export interface UidStatsInfo { + /*See {@link IfaceInfo}*/ + ifaceInfo: IfaceInfo; + uid: number; + } + + /** + * @systemapi Hide this for inner system use. + */ + export interface NetStatsInfo { + rxBytes: number; + txBytes: number; + rxPackets: number; + txPackets: number; + } +} + +export default statistics; \ No newline at end of file diff --git a/interfaces/kits/js/basic.d.ts b/interfaces/kits/js/basic.d.ts new file mode 100644 index 000000000..d30529a62 --- /dev/null +++ b/interfaces/kits/js/basic.d.ts @@ -0,0 +1,15 @@ +export interface Callback { + (data: T): void; +} + +export interface ErrorCallback { + (err: T): void; +} + +export interface AsyncCallback { + (err: BusinessError, data: T): void; +} + +export interface BusinessError extends Error { + code: number; +} diff --git a/netmanager_base_config.gni b/netmanager_base_config.gni index 07f2ade95..a2709334a 100644 --- a/netmanager_base_config.gni +++ b/netmanager_base_config.gni @@ -15,16 +15,22 @@ SUBSYSTEM_DIR = "//foundation/communication" NETMANAGER_BASE_ROOT = "$SUBSYSTEM_DIR/netmanager_base" NETMANAGERNATIVE_ROOT = "$NETMANAGER_BASE_ROOT/services/netmanagernative" INNERKITS_ROOT = "$NETMANAGER_BASE_ROOT/interfaces/innerkits" -NETCONNMANAGER_INNERKITS_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/frameworks/native/netconnclient" -NETPOLICYMANAGER_INNERKITS_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/frameworks/native/netpolicyclient" -DNSRESOLVERMANAGER_INNERKITS_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/frameworks/native/dnsresolverclient" -NETSTATSMANAGER_INNERKITS_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/frameworks/native/netstatsclient" +NETCONNMANAGER_INNERKITS_SOURCE_DIR = + "$NETMANAGER_BASE_ROOT/frameworks/native/netconnclient" +NETPOLICYMANAGER_INNERKITS_SOURCE_DIR = + "$NETMANAGER_BASE_ROOT/frameworks/native/netpolicyclient" +DNSRESOLVERMANAGER_INNERKITS_SOURCE_DIR = + "$NETMANAGER_BASE_ROOT/frameworks/native/dnsresolverclient" +NETSTATSMANAGER_INNERKITS_SOURCE_DIR = + "$NETMANAGER_BASE_ROOT/frameworks/native/netstatsclient" NETCONNMANAGER_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/netconnmanager" NETPOLICYMANAGER_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/netpolicymanager" NETSTATSMANAGER_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/netstatsmanager" NETCONNMANAGER_COMMON_DIR = "$NETMANAGER_BASE_ROOT/services/common" -DNSRESOLVERMANAGER_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/dnsresolvermanager" -NETDNATIVE_INNERKITS_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/frameworks/native/netmanagernative" +DNSRESOLVERMANAGER_SOURCE_DIR = + "$NETMANAGER_BASE_ROOT/services/dnsresolvermanager" +NETDNATIVE_INNERKITS_SOURCE_DIR = + "$NETMANAGER_BASE_ROOT/frameworks/native/netmanagernative" NETDNATIVE_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/netmanagernative" NETMANAGER_PREBUILTS_DIR = "$NETMANAGER_BASE_ROOT/prebuilts" NETDCONTROLLER_ROOT_DIR = "$NETMANAGER_BASE_ROOT/services/netdcontroller" diff --git a/ohos.build b/ohos.build deleted file mode 100644 index 7e9b630c9..000000000 --- a/ohos.build +++ /dev/null @@ -1,75 +0,0 @@ -{ - "subsystem": "communication", - "parts": { - "netmanager_base": { - "variants": [ - "phone", - "wearable", - "ivi" - ], - "module_list": [ - "//foundation/communication/netmanager_base/services/netmanagernative:netd_native_manager", - "//foundation/communication/netmanager_base/prebuilts/librarys/netd:libnet_manager_native", - "//foundation/communication/netmanager_base/services/netdcontroller:netd_controller", - "//foundation/communication/netmanager_base/services/netconnmanager:net_conn_manager", - "//foundation/communication/netmanager_base/services/dnsresolvermanager:dns_resolver_manager", - "//foundation/communication/netmanager_base/services/netpolicymanager:net_policy_manager", - "//foundation/communication/netmanager_base/services/netstatsmanager:net_stats_manager", - "//foundation/communication/netmanager_base/interfaces/innerkits/netconnclient:net_conn_manager_if", - "//foundation/communication/netmanager_base/interfaces/innerkits/dnsresolverclient:dns_resolver_manager_if", - "//foundation/communication/netmanager_base/interfaces/innerkits/netpolicyclient:net_policy_manager_if", - "//foundation/communication/netmanager_base/interfaces/innerkits/netstatsclient:net_stats_manager_if", - "//foundation/communication/netmanager_base/utils:net_manager_common", - "//foundation/communication/netmanager_base/services/etc/init:netmanager_base.rc", - "//foundation/communication/netmanager_base/services/etc/init:netdnative.rc", - "//foundation/communication/netmanager_base/sa_profile:net_manager_profile", - "//foundation/communication/netmanager_base/frameworks/js/napi/netpolicy:policy", - "//foundation/communication/netmanager_base/frameworks/js/napi/netstats:statistics", - "//foundation/communication/netmanager_base/frameworks/js/napi/netconn:connection" - ], - "inner_kits": [ - { - "type": "so", - "name": "//foundation/communication/netmanager_base/interfaces/innerkits/netconnclient:net_conn_manager_if", - "header": { - "header_files": [ - "net_conn_client.h", - "net_link_info.h", - "net_supplier_info.h", - "net_specifier.h", - "route.h" - ], - "header_base": "//foundation/communication/netmanager_base/interfaces/innerkits/netconnclient/include" - } - }, - { - "type": "so", - "name": "//foundation/communication/netmanager_base/interfaces/innerkits/netpolicyclient:net_policy_manager_if", - "header": { - "header_files": [ - "net_policy_client.h" - ], - "header_base": "//foundation/communication/netmanager_base/interfaces/innerkits/netpolicyclient/include" - } - }, - { - "type": "so", - "name": "//foundation/communication/netmanager_base/interfaces/innerkits/netstatsclient:net_stats_manager_if", - "header": { - "header_files": [ - "net_stats_info.h", - "net_stats_client.h" - ], - "header_base": "//foundation/communication/netmanager_base/interfaces/innerkits/netstatsclient/include" - } - } - ], - "test_list": [ - "//foundation/communication/netmanager_base/test/dnsresolvermanager:unittest", - "//foundation/communication/netmanager_base/test/netconnmanager:unittest", - "//foundation/communication/netmanager_base/test/netpolicymanager:unittest", - "//foundation/communication/netmanager_base/test/netstatsmanager:unittest" - ] - } - } -} diff --git a/prebuilts/librarys/netd/include/common/include/blocking_queue.h b/prebuilts/librarys/netd/include/common/include/blocking_queue.h index 8f8d6b133..85c9cc1c1 100755 --- a/prebuilts/librarys/netd/include/common/include/blocking_queue.h +++ b/prebuilts/librarys/netd/include/common/include/blocking_queue.h @@ -1,76 +1,76 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_BLOCKING_QUEUE_H__ -#define INCLUDE_BLOCKING_QUEUE_H__ - -#include -#include -#include -namespace OHOS { -namespace nmd { -template -class blocking_queue { -public: - explicit blocking_queue(unsigned int capacity) : start_(0), end_(0), capacity_(capacity), vt_(capacity + 1) {}; - ~blocking_queue() {}; - - bool isEmpty() - { - return this->end_ == this->start_; - } - - bool isFull() - { - return (this->start_ + this->capacity_ - this->end_) % (this->capacity_ + 1) == 0; - } - - void push(const T &e) - { - std::unique_lock lock(this->mutex_); - while (this->isFull()) { - this->notFull_.wait(lock); - } - - this->vt_[this->end_++] = e; - this->end_ %= (this->capacity_ + 1); - this->notEmpty_.notify_one(); - } - - T pop() - { - std::unique_lock lock(this->mutex_); - while (this->isEmpty()) { - this->notEmpty_.wait(lock); - } - - auto res = this->vt_[this->start_++]; - this->start_ %= (this->capacity_ + 1); - this->notFull_.notify_one(); - return res; - } - -private: - std::mutex mutex_; - std::condition_variable notFull_; - std::condition_variable notEmpty_; - unsigned int start_; - unsigned int end_; - unsigned int capacity_; - std::vector vt_; -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_BLOCKING_QUEUE_H__ +#define INCLUDE_BLOCKING_QUEUE_H__ + +#include +#include +#include +namespace OHOS { +namespace nmd { +template +class blocking_queue { +public: + explicit blocking_queue(unsigned int capacity) : start_(0), end_(0), capacity_(capacity), vt_(capacity + 1) {}; + ~blocking_queue() {}; + + bool isEmpty() + { + return this->end_ == this->start_; + } + + bool isFull() + { + return (this->start_ + this->capacity_ - this->end_) % (this->capacity_ + 1) == 0; + } + + void push(const T &e) + { + std::unique_lock lock(this->mutex_); + while (this->isFull()) { + this->notFull_.wait(lock); + } + + this->vt_[this->end_++] = e; + this->end_ %= (this->capacity_ + 1); + this->notEmpty_.notify_one(); + } + + T pop() + { + std::unique_lock lock(this->mutex_); + while (this->isEmpty()) { + this->notEmpty_.wait(lock); + } + + auto res = this->vt_[this->start_++]; + this->start_ %= (this->capacity_ + 1); + this->notFull_.notify_one(); + return res; + } + +private: + std::mutex mutex_; + std::condition_variable notFull_; + std::condition_variable notEmpty_; + unsigned int start_; + unsigned int end_; + unsigned int capacity_; + std::vector vt_; +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_BLOCKING_QUEUE_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/job.h b/prebuilts/librarys/netd/include/common/include/job.h index e7123d5c0..58e93cede 100755 --- a/prebuilts/librarys/netd/include/common/include/job.h +++ b/prebuilts/librarys/netd/include/common/include/job.h @@ -1,39 +1,39 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_JOB_H__ -#define INCLUDE_JOB_H__ - -#include -#include "server_socket.h" -namespace OHOS { -namespace nmd { -class job { -public: - job(const int fd, const uint8_t *msg, const size_t msgLen, - const std::shared_ptr serverSocket) - : fd_(fd), msg_(msg, msg + msgLen), serverSocket_(serverSocket) - {} - virtual ~job() = default; - virtual void run() = 0; - -protected: - int fd_; - std::vector msg_; - std::shared_ptr serverSocket_; -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_JOB_H__ +#define INCLUDE_JOB_H__ + +#include +#include "server_socket.h" +namespace OHOS { +namespace nmd { +class job { +public: + job(const int fd, const uint8_t *msg, const size_t msgLen, + const std::shared_ptr serverSocket) + : fd_(fd), msg_(msg, msg + msgLen), serverSocket_(serverSocket) + {} + virtual ~job() = default; + virtual void run() = 0; + +protected: + int fd_; + std::vector msg_; + std::shared_ptr serverSocket_; +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_JOB_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/net_utils.h b/prebuilts/librarys/netd/include/common/include/net_utils.h index 4de8fa830..91f8e6099 100755 --- a/prebuilts/librarys/netd/include/common/include/net_utils.h +++ b/prebuilts/librarys/netd/include/common/include/net_utils.h @@ -1,539 +1,539 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_NET_UTILS_H__ -#define INCLUDE_NET_UTILS_H__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "warning_disable.h" -namespace OHOS { -namespace nmd { -namespace common { -namespace net_utils { -enum protocol : uint8_t { - PROTO_UNKNOWN = 0, - PROTO_TCP = 6, - PROTO_UDP = 17, -}; -// See also NetworkConstants.java in frameworks/base. -constexpr int IPV4_ADDR_LEN = 4; -constexpr int IPV4_ADDR_BITS = 32; -constexpr int IPV6_ADDR_LEN = 16; -constexpr int IPV6_ADDR_BITS = 128; - -// Referred from SHA256_DIGEST_LENGTH in boringssl -constexpr size_t SHA256_SIZE = 32; - -struct compact_ipdata { - uint8_t family {AF_UNSPEC}; - uint8_t cidrlen {0U}; // written and read in host-byte order - in_port_t port {0U}; // written and read in host-byte order - uint32_t scope_id {0U}; - - DISABLE_WARNING_PUSH - DISABLE_WARNING_C99_EXTENSIONS - union { - in_addr v4; - in6_addr v6; - } ip {.v6 = IN6ADDR_ANY_INIT}; // written and read in network-byte order - - DISABLE_WARNING_POP - // Classes that use compact_ipdata and this method should be sure to clear - // (i.e. zero or make uniform) any fields not relevant to the class. - friend bool operator==(const compact_ipdata &a, const compact_ipdata &b) - { - if ((a.family != b.family) || (a.cidrlen != b.cidrlen) || (a.port != b.port) || (a.scope_id != b.scope_id)) { - return false; - } - switch (a.family) { - case AF_UNSPEC: - // After the above checks, two AF_UNSPEC objects can be - // considered equal, for convenience. - return true; - case AF_INET: { - const in_addr v4a = a.ip.v4; - const in_addr v4b = b.ip.v4; - return (v4a.s_addr == v4b.s_addr); - } - case AF_INET6: { - const in6_addr v6a = a.ip.v6; - const in6_addr v6b = b.ip.v6; - return IN6_ARE_ADDR_EQUAL(&v6a, &v6b); - } - default: - break; - } - return false; - } - - // Classes that use compact_ipdata and this method should be sure to clear - // (i.e. zero or make uniform) any fields not relevant to the class. - friend bool operator!=(const compact_ipdata &a, const compact_ipdata &b) - { - return !(a == b); - } - - // Classes that use compact_ipdata and this method should be sure to clear - // (i.e. zero or make uniform) any fields not relevant to the class. - friend bool operator<(const compact_ipdata &a, const compact_ipdata &b) - { - if (a.family != b.family) - return (a.family < b.family); - switch (a.family) { - case AF_INET: { - const in_addr v4a = a.ip.v4; - const in_addr v4b = b.ip.v4; - if (v4a.s_addr != v4b.s_addr) - return (ntohl(v4a.s_addr) < ntohl(v4b.s_addr)); - break; - } - case AF_INET6: { - const in6_addr v6a = a.ip.v6; - const in6_addr v6b = b.ip.v6; - const int cmp = std::memcmp(v6a.s6_addr, v6b.s6_addr, IPV6_ADDR_LEN); - if (cmp != 0) - return cmp < 0; - break; - } - default: - break; - } - if (a.cidrlen != b.cidrlen) - return (a.cidrlen < b.cidrlen); - if (a.port != b.port) - return (a.port < b.port); - return (a.scope_id < b.scope_id); - } -}; - -static_assert(AF_UNSPEC <= std::numeric_limits::max(), "AF_UNSPEC value too large"); -static_assert(AF_INET <= std::numeric_limits::max(), "AF_INET value too large"); -static_assert(AF_INET6 <= std::numeric_limits::max(), "AF_INET6 value too large"); -static_assert(sizeof(compact_ipdata) == 24U, "compact_ipdata unexpectedly large"); - -struct addrinfo_deleter { - void operator()(struct addrinfo *p) const - { - if (p != nullptr) { - freeaddrinfo(p); - } - } -}; - -typedef std::unique_ptr ScopedAddrinfo; - -inline bool usesScopedIds(const in6_addr &ipv6) -{ - return (IN6_IS_ADDR_LINKLOCAL(&ipv6) || IN6_IS_ADDR_MC_LINKLOCAL(&ipv6)); -} - -class ip_prefix; -class ip_sock_addr; - -class ip_address { -public: - static bool forString(const std::string &repr, ip_address *ip); - static ip_address forString(const std::string &repr) - { - ip_address ip; - if (!forString(repr, &ip)) - return ip_address(); - return ip; - } - - ip_address() = default; - ip_address(const ip_address &) = default; - ip_address(ip_address &&) = default; - - DISABLE_WARNING_PUSH - DISABLE_WARNING_C99_EXTENSIONS - - explicit ip_address(const in_addr &ipv4); - explicit ip_address(const in6_addr &ipv6); - ip_address(const in6_addr &ipv6, uint32_t scope_id); - - DISABLE_WARNING_POP - - ip_address(const ip_address &ip, uint32_t scope_id) : ip_address(ip) - { - mData.scope_id = (family() == AF_INET6 && usesScopedIds(mData.ip.v6)) ? scope_id : 0U; - } - - ip_address &operator=(const ip_address &) = default; - ip_address &operator=(ip_address &&) = default; - - constexpr sa_family_t family() const noexcept - { - return mData.family; - } - constexpr uint32_t scope_id() const noexcept - { - return mData.scope_id; - } - - std::string toString() const noexcept; - - friend std::ostream &operator<<(std::ostream &os, const ip_address &ip) - { - os << ip.toString(); - return os; - } - friend bool operator==(const ip_address &a, const ip_address &b) - { - return (a.mData == b.mData); - } - friend bool operator!=(const ip_address &a, const ip_address &b) - { - return (a.mData != b.mData); - } - friend bool operator<(const ip_address &a, const ip_address &b) - { - return (a.mData < b.mData); - } - friend bool operator>(const ip_address &a, const ip_address &b) - { - return (b.mData < a.mData); - } - friend bool operator<=(const ip_address &a, const ip_address &b) - { - return (a < b) || (a == b); - } - friend bool operator>=(const ip_address &a, const ip_address &b) - { - return (b < a) || (a == b); - } - -private: - friend class ip_prefix; - friend class ip_sock_addr; - - explicit ip_address(const compact_ipdata &ipdata) : mData(ipdata) - { - mData.port = 0U; - switch (mData.family) { - case AF_INET: - mData.cidrlen = IPV4_ADDR_BITS; - mData.scope_id = 0U; - break; - case AF_INET6: - mData.cidrlen = IPV6_ADDR_BITS; - if (usesScopedIds(ipdata.ip.v6)) - mData.scope_id = ipdata.scope_id; - break; - default: - mData.cidrlen = 0U; - mData.scope_id = 0U; - break; - } - } - - compact_ipdata mData {}; -}; - -class ip_prefix { -public: - static bool forString(const std::string &repr, ip_prefix *prefix); - static ip_prefix forString(const std::string &repr) - { - ip_prefix prefix; - if (!forString(repr, &prefix)) - return ip_prefix(); - return prefix; - } - - ip_prefix() = default; - ip_prefix(const ip_prefix &) = default; - ip_prefix(ip_prefix &&) = default; - - explicit ip_prefix(const ip_address &ip) : mData(ip.mData) {} - - // Truncate the IP address |ip| at length |length|. Lengths greater than - // the address-family-relevant maximum, along with negative values, are - // interpreted as if the address-family-relevant maximum had been given. - ip_prefix(const ip_address &ip, size_t length); - - ip_prefix &operator=(const ip_prefix &) = default; - ip_prefix &operator=(ip_prefix &&) = default; - - constexpr sa_family_t family() const noexcept - { - return mData.family; - } - ip_address ip() const noexcept - { - return ip_address(mData); - } - in_addr addr4() const noexcept - { - return mData.ip.v4; - } - in6_addr addr6() const noexcept - { - return mData.ip.v6; - } - constexpr int length() const noexcept - { - return mData.cidrlen; - } - - bool isUninitialized() const noexcept; - std::string toString() const noexcept; - - friend std::ostream &operator<<(std::ostream &os, const ip_prefix &prefix) - { - os << prefix.toString(); - return os; - } - friend bool operator==(const ip_prefix &a, const ip_prefix &b) - { - return (a.mData == b.mData); - } - friend bool operator!=(const ip_prefix &a, const ip_prefix &b) - { - return (a.mData != b.mData); - } - friend bool operator<(const ip_prefix &a, const ip_prefix &b) - { - return (a.mData < b.mData); - } - friend bool operator>(const ip_prefix &a, const ip_prefix &b) - { - return (b.mData < a.mData); - } - friend bool operator<=(const ip_prefix &a, const ip_prefix &b) - { - return (a < b) || (a == b); - } - friend bool operator>=(const ip_prefix &a, const ip_prefix &b) - { - return (b < a) || (a == b); - } - -private: - compact_ipdata mData {}; -}; - -// An Internet socket address. -// -// Cannot represent other types of socket addresses (e.g. UNIX socket address, et cetera). -class ip_sock_addr { -public: - static ip_sock_addr toIPSockAddr(const std::string &repr, in_port_t port) - { - return ip_sock_addr(ip_address::forString(repr), port); - } - static ip_sock_addr toIPSockAddr(const sockaddr &sa) - { - switch (sa.sa_family) { - case AF_INET: - return ip_sock_addr(*reinterpret_cast(&sa)); - case AF_INET6: - return ip_sock_addr(*reinterpret_cast(&sa)); - default: - return ip_sock_addr(); - } - } - static ip_sock_addr toIPSockAddr(const sockaddr_storage &ss) - { - return toIPSockAddr(*reinterpret_cast(&ss)); - } - - ip_sock_addr() = default; - ip_sock_addr(const ip_sock_addr &) = default; - ip_sock_addr(ip_sock_addr &&) = default; - - explicit ip_sock_addr(const ip_address &ip) : mData(ip.mData) {} - ip_sock_addr(const ip_address &ip, in_port_t port) : mData(ip.mData) - { - mData.port = port; - } - explicit ip_sock_addr(const sockaddr_in &ipv4sa) - : ip_sock_addr(ip_address(ipv4sa.sin_addr), ntohs(ipv4sa.sin_port)) - {} - explicit ip_sock_addr(const sockaddr_in6 &ipv6sa) - : ip_sock_addr(ip_address(ipv6sa.sin6_addr, ipv6sa.sin6_scope_id), ntohs(ipv6sa.sin6_port)) - {} - - ip_sock_addr &operator=(const ip_sock_addr &) = default; - ip_sock_addr &operator=(ip_sock_addr &&) = default; - - constexpr sa_family_t family() const noexcept - { - return mData.family; - } - ip_address ip() const noexcept - { - return ip_address(mData); - } - constexpr in_port_t port() const noexcept - { - return mData.port; - } - - // Implicit conversion to sockaddr_storage. - operator sockaddr_storage() const noexcept - { - sockaddr_storage ss; - ss.ss_family = mData.family; - switch (mData.family) { - case AF_INET: - reinterpret_cast(&ss)->sin_addr = mData.ip.v4; - reinterpret_cast(&ss)->sin_port = htons(mData.port); - break; - case AF_INET6: - reinterpret_cast(&ss)->sin6_addr = mData.ip.v6; - reinterpret_cast(&ss)->sin6_port = htons(mData.port); - reinterpret_cast(&ss)->sin6_scope_id = mData.scope_id; - break; - default: - break; - } - return ss; - } - - std::string toString() const noexcept; - - friend std::ostream &operator<<(std::ostream &os, const ip_sock_addr &prefix) - { - os << prefix.toString(); - return os; - } - friend bool operator==(const ip_sock_addr &a, const ip_sock_addr &b) - { - return (a.mData == b.mData); - } - friend bool operator!=(const ip_sock_addr &a, const ip_sock_addr &b) - { - return (a.mData != b.mData); - } - friend bool operator<(const ip_sock_addr &a, const ip_sock_addr &b) - { - return (a.mData < b.mData); - } - friend bool operator>(const ip_sock_addr &a, const ip_sock_addr &b) - { - return (b.mData < a.mData); - } - friend bool operator<=(const ip_sock_addr &a, const ip_sock_addr &b) - { - return (a < b) || (a == b); - } - friend bool operator>=(const ip_sock_addr &a, const ip_sock_addr &b) - { - return (b < a) || (a == b); - } - -private: - compact_ipdata mData {}; -}; - -class sock_addr_utils final { -public: - static socklen_t sockaddrSize(const sockaddr *sa) - { - if (sa == nullptr) { - return 0; - } - - switch (sa->sa_family) { - case AF_INET: - return sizeof(sockaddr_in); - case AF_INET6: - return sizeof(sockaddr_in6); - default: - return 0; - } - } - -public: - sock_addr_utils() = default; /* args */ - ~sock_addr_utils() = default; -}; - -class fd_wrapper final { -public: - fd_wrapper() = default; - explicit fd_wrapper(const int fd) - { - reset(fd); - }; - fd_wrapper(const fd_wrapper &) = delete; - void operator=(const fd_wrapper &) = delete; - ~fd_wrapper() - { - reset(); - } - - int getFd() const - { - return fd_; - } - - operator int() const - { - return getFd(); - } - bool operator>=(int rhs) const - { - return getFd() >= rhs; - } - bool operator<(int rhs) const - { - return getFd() < rhs; - } - bool operator==(int rhs) const - { - return getFd() == rhs; - } - bool operator!=(int rhs) const - { - return getFd() != rhs; - } - bool operator==(const fd_wrapper &rhs) const - { - return getFd() == rhs.getFd(); - } - bool operator!=(const fd_wrapper &rhs) const - { - return getFd() != rhs.getFd(); - } - -public: - void reset(int newFd = -1) - { - if (fd_ != -1) { - close(fd_); - } - fd_ = newFd; - } - -private: - int fd_ = -1; -}; -using socket_fd = fd_wrapper; -} // namespace net_utils -} // namespace common -} // namespace nmd -} // namespace OHOS -#endif // !INCLUDE_NET_UTILS_H__ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NET_UTILS_H__ +#define INCLUDE_NET_UTILS_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "warning_disable.h" +namespace OHOS { +namespace nmd { +namespace common { +namespace net_utils { +enum protocol : uint8_t { + PROTO_UNKNOWN = 0, + PROTO_TCP = 6, + PROTO_UDP = 17, +}; +// See also NetworkConstants.java in frameworks/base. +constexpr int IPV4_ADDR_LEN = 4; +constexpr int IPV4_ADDR_BITS = 32; +constexpr int IPV6_ADDR_LEN = 16; +constexpr int IPV6_ADDR_BITS = 128; + +// Referred from SHA256_DIGEST_LENGTH in boringssl +constexpr size_t SHA256_SIZE = 32; + +struct compact_ipdata { + uint8_t family {AF_UNSPEC}; + uint8_t cidrlen {0U}; // written and read in host-byte order + in_port_t port {0U}; // written and read in host-byte order + uint32_t scope_id {0U}; + + DISABLE_WARNING_PUSH + DISABLE_WARNING_C99_EXTENSIONS + union { + in_addr v4; + in6_addr v6; + } ip {.v6 = IN6ADDR_ANY_INIT}; // written and read in network-byte order + + DISABLE_WARNING_POP + // Classes that use compact_ipdata and this method should be sure to clear + // (i.e. zero or make uniform) any fields not relevant to the class. + friend bool operator==(const compact_ipdata &a, const compact_ipdata &b) + { + if ((a.family != b.family) || (a.cidrlen != b.cidrlen) || (a.port != b.port) || (a.scope_id != b.scope_id)) { + return false; + } + switch (a.family) { + case AF_UNSPEC: + // After the above checks, two AF_UNSPEC objects can be + // considered equal, for convenience. + return true; + case AF_INET: { + const in_addr v4a = a.ip.v4; + const in_addr v4b = b.ip.v4; + return (v4a.s_addr == v4b.s_addr); + } + case AF_INET6: { + const in6_addr v6a = a.ip.v6; + const in6_addr v6b = b.ip.v6; + return IN6_ARE_ADDR_EQUAL(&v6a, &v6b); + } + default: + break; + } + return false; + } + + // Classes that use compact_ipdata and this method should be sure to clear + // (i.e. zero or make uniform) any fields not relevant to the class. + friend bool operator!=(const compact_ipdata &a, const compact_ipdata &b) + { + return !(a == b); + } + + // Classes that use compact_ipdata and this method should be sure to clear + // (i.e. zero or make uniform) any fields not relevant to the class. + friend bool operator<(const compact_ipdata &a, const compact_ipdata &b) + { + if (a.family != b.family) + return (a.family < b.family); + switch (a.family) { + case AF_INET: { + const in_addr v4a = a.ip.v4; + const in_addr v4b = b.ip.v4; + if (v4a.s_addr != v4b.s_addr) + return (ntohl(v4a.s_addr) < ntohl(v4b.s_addr)); + break; + } + case AF_INET6: { + const in6_addr v6a = a.ip.v6; + const in6_addr v6b = b.ip.v6; + const int cmp = std::memcmp(v6a.s6_addr, v6b.s6_addr, IPV6_ADDR_LEN); + if (cmp != 0) + return cmp < 0; + break; + } + default: + break; + } + if (a.cidrlen != b.cidrlen) + return (a.cidrlen < b.cidrlen); + if (a.port != b.port) + return (a.port < b.port); + return (a.scope_id < b.scope_id); + } +}; + +static_assert(AF_UNSPEC <= std::numeric_limits::max(), "AF_UNSPEC value too large"); +static_assert(AF_INET <= std::numeric_limits::max(), "AF_INET value too large"); +static_assert(AF_INET6 <= std::numeric_limits::max(), "AF_INET6 value too large"); +static_assert(sizeof(compact_ipdata) == 24U, "compact_ipdata unexpectedly large"); + +struct addrinfo_deleter { + void operator()(struct addrinfo *p) const + { + if (p != nullptr) { + freeaddrinfo(p); + } + } +}; + +typedef std::unique_ptr ScopedAddrinfo; + +inline bool usesScopedIds(const in6_addr &ipv6) +{ + return (IN6_IS_ADDR_LINKLOCAL(&ipv6) || IN6_IS_ADDR_MC_LINKLOCAL(&ipv6)); +} + +class ip_prefix; +class ip_sock_addr; + +class ip_address { +public: + static bool forString(const std::string &repr, ip_address *ip); + static ip_address forString(const std::string &repr) + { + ip_address ip; + if (!forString(repr, &ip)) + return ip_address(); + return ip; + } + + ip_address() = default; + ip_address(const ip_address &) = default; + ip_address(ip_address &&) = default; + + DISABLE_WARNING_PUSH + DISABLE_WARNING_C99_EXTENSIONS + + explicit ip_address(const in_addr &ipv4); + explicit ip_address(const in6_addr &ipv6); + ip_address(const in6_addr &ipv6, uint32_t scope_id); + + DISABLE_WARNING_POP + + ip_address(const ip_address &ip, uint32_t scope_id) : ip_address(ip) + { + mData.scope_id = (family() == AF_INET6 && usesScopedIds(mData.ip.v6)) ? scope_id : 0U; + } + + ip_address &operator=(const ip_address &) = default; + ip_address &operator=(ip_address &&) = default; + + constexpr sa_family_t family() const noexcept + { + return mData.family; + } + constexpr uint32_t scope_id() const noexcept + { + return mData.scope_id; + } + + std::string toString() const noexcept; + + friend std::ostream &operator<<(std::ostream &os, const ip_address &ip) + { + os << ip.toString(); + return os; + } + friend bool operator==(const ip_address &a, const ip_address &b) + { + return (a.mData == b.mData); + } + friend bool operator!=(const ip_address &a, const ip_address &b) + { + return (a.mData != b.mData); + } + friend bool operator<(const ip_address &a, const ip_address &b) + { + return (a.mData < b.mData); + } + friend bool operator>(const ip_address &a, const ip_address &b) + { + return (b.mData < a.mData); + } + friend bool operator<=(const ip_address &a, const ip_address &b) + { + return (a < b) || (a == b); + } + friend bool operator>=(const ip_address &a, const ip_address &b) + { + return (b < a) || (a == b); + } + +private: + friend class ip_prefix; + friend class ip_sock_addr; + + explicit ip_address(const compact_ipdata &ipdata) : mData(ipdata) + { + mData.port = 0U; + switch (mData.family) { + case AF_INET: + mData.cidrlen = IPV4_ADDR_BITS; + mData.scope_id = 0U; + break; + case AF_INET6: + mData.cidrlen = IPV6_ADDR_BITS; + if (usesScopedIds(ipdata.ip.v6)) + mData.scope_id = ipdata.scope_id; + break; + default: + mData.cidrlen = 0U; + mData.scope_id = 0U; + break; + } + } + + compact_ipdata mData {}; +}; + +class ip_prefix { +public: + static bool forString(const std::string &repr, ip_prefix *prefix); + static ip_prefix forString(const std::string &repr) + { + ip_prefix prefix; + if (!forString(repr, &prefix)) + return ip_prefix(); + return prefix; + } + + ip_prefix() = default; + ip_prefix(const ip_prefix &) = default; + ip_prefix(ip_prefix &&) = default; + + explicit ip_prefix(const ip_address &ip) : mData(ip.mData) {} + + // Truncate the IP address |ip| at length |length|. Lengths greater than + // the address-family-relevant maximum, along with negative values, are + // interpreted as if the address-family-relevant maximum had been given. + ip_prefix(const ip_address &ip, size_t length); + + ip_prefix &operator=(const ip_prefix &) = default; + ip_prefix &operator=(ip_prefix &&) = default; + + constexpr sa_family_t family() const noexcept + { + return mData.family; + } + ip_address ip() const noexcept + { + return ip_address(mData); + } + in_addr addr4() const noexcept + { + return mData.ip.v4; + } + in6_addr addr6() const noexcept + { + return mData.ip.v6; + } + constexpr int length() const noexcept + { + return mData.cidrlen; + } + + bool isUninitialized() const noexcept; + std::string toString() const noexcept; + + friend std::ostream &operator<<(std::ostream &os, const ip_prefix &prefix) + { + os << prefix.toString(); + return os; + } + friend bool operator==(const ip_prefix &a, const ip_prefix &b) + { + return (a.mData == b.mData); + } + friend bool operator!=(const ip_prefix &a, const ip_prefix &b) + { + return (a.mData != b.mData); + } + friend bool operator<(const ip_prefix &a, const ip_prefix &b) + { + return (a.mData < b.mData); + } + friend bool operator>(const ip_prefix &a, const ip_prefix &b) + { + return (b.mData < a.mData); + } + friend bool operator<=(const ip_prefix &a, const ip_prefix &b) + { + return (a < b) || (a == b); + } + friend bool operator>=(const ip_prefix &a, const ip_prefix &b) + { + return (b < a) || (a == b); + } + +private: + compact_ipdata mData {}; +}; + +// An Internet socket address. +// +// Cannot represent other types of socket addresses (e.g. UNIX socket address, et cetera). +class ip_sock_addr { +public: + static ip_sock_addr toIPSockAddr(const std::string &repr, in_port_t port) + { + return ip_sock_addr(ip_address::forString(repr), port); + } + static ip_sock_addr toIPSockAddr(const sockaddr &sa) + { + switch (sa.sa_family) { + case AF_INET: + return ip_sock_addr(*reinterpret_cast(&sa)); + case AF_INET6: + return ip_sock_addr(*reinterpret_cast(&sa)); + default: + return ip_sock_addr(); + } + } + static ip_sock_addr toIPSockAddr(const sockaddr_storage &ss) + { + return toIPSockAddr(*reinterpret_cast(&ss)); + } + + ip_sock_addr() = default; + ip_sock_addr(const ip_sock_addr &) = default; + ip_sock_addr(ip_sock_addr &&) = default; + + explicit ip_sock_addr(const ip_address &ip) : mData(ip.mData) {} + ip_sock_addr(const ip_address &ip, in_port_t port) : mData(ip.mData) + { + mData.port = port; + } + explicit ip_sock_addr(const sockaddr_in &ipv4sa) + : ip_sock_addr(ip_address(ipv4sa.sin_addr), ntohs(ipv4sa.sin_port)) + {} + explicit ip_sock_addr(const sockaddr_in6 &ipv6sa) + : ip_sock_addr(ip_address(ipv6sa.sin6_addr, ipv6sa.sin6_scope_id), ntohs(ipv6sa.sin6_port)) + {} + + ip_sock_addr &operator=(const ip_sock_addr &) = default; + ip_sock_addr &operator=(ip_sock_addr &&) = default; + + constexpr sa_family_t family() const noexcept + { + return mData.family; + } + ip_address ip() const noexcept + { + return ip_address(mData); + } + constexpr in_port_t port() const noexcept + { + return mData.port; + } + + // Implicit conversion to sockaddr_storage. + operator sockaddr_storage() const noexcept + { + sockaddr_storage ss; + ss.ss_family = mData.family; + switch (mData.family) { + case AF_INET: + reinterpret_cast(&ss)->sin_addr = mData.ip.v4; + reinterpret_cast(&ss)->sin_port = htons(mData.port); + break; + case AF_INET6: + reinterpret_cast(&ss)->sin6_addr = mData.ip.v6; + reinterpret_cast(&ss)->sin6_port = htons(mData.port); + reinterpret_cast(&ss)->sin6_scope_id = mData.scope_id; + break; + default: + break; + } + return ss; + } + + std::string toString() const noexcept; + + friend std::ostream &operator<<(std::ostream &os, const ip_sock_addr &prefix) + { + os << prefix.toString(); + return os; + } + friend bool operator==(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (a.mData == b.mData); + } + friend bool operator!=(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (a.mData != b.mData); + } + friend bool operator<(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (a.mData < b.mData); + } + friend bool operator>(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (b.mData < a.mData); + } + friend bool operator<=(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (a < b) || (a == b); + } + friend bool operator>=(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (b < a) || (a == b); + } + +private: + compact_ipdata mData {}; +}; + +class sock_addr_utils final { +public: + static socklen_t sockaddrSize(const sockaddr *sa) + { + if (sa == nullptr) { + return 0; + } + + switch (sa->sa_family) { + case AF_INET: + return sizeof(sockaddr_in); + case AF_INET6: + return sizeof(sockaddr_in6); + default: + return 0; + } + } + +public: + sock_addr_utils() = default; /* args */ + ~sock_addr_utils() = default; +}; + +class fd_wrapper final { +public: + fd_wrapper() = default; + explicit fd_wrapper(const int fd) + { + reset(fd); + }; + fd_wrapper(const fd_wrapper &) = delete; + void operator=(const fd_wrapper &) = delete; + ~fd_wrapper() + { + reset(); + } + + int getFd() const + { + return fd_; + } + + operator int() const + { + return getFd(); + } + bool operator>=(int rhs) const + { + return getFd() >= rhs; + } + bool operator<(int rhs) const + { + return getFd() < rhs; + } + bool operator==(int rhs) const + { + return getFd() == rhs; + } + bool operator!=(int rhs) const + { + return getFd() != rhs; + } + bool operator==(const fd_wrapper &rhs) const + { + return getFd() == rhs.getFd(); + } + bool operator!=(const fd_wrapper &rhs) const + { + return getFd() != rhs.getFd(); + } + +public: + void reset(int newFd = -1) + { + if (fd_ != -1) { + close(fd_); + } + fd_ = newFd; + } + +private: + int fd_ = -1; +}; +using socket_fd = fd_wrapper; +} // namespace net_utils +} // namespace common +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NET_UTILS_H__ diff --git a/prebuilts/librarys/netd/include/common/include/server_socket.h b/prebuilts/librarys/netd/include/common/include/server_socket.h index 2643a3bac..046bd0efb 100755 --- a/prebuilts/librarys/netd/include/common/include/server_socket.h +++ b/prebuilts/librarys/netd/include/common/include/server_socket.h @@ -1,37 +1,37 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NETD_COMMON_SERVER_SOCKET_H__ -#define NETD_COMMON_SERVER_SOCKET_H__ - -#include "socket_base.h" -namespace OHOS { -namespace nmd { -namespace common { -class server_socket : public socket_base { -public: - server_socket(); - ~server_socket(); - - int bindPort(uint16_t port); - int bindFile(const char *filePath, const char *name); - -private: - struct sockaddr addr_ {}; -}; -} // namespace common -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETD_COMMON_SERVER_SOCKET_H__ +#define NETD_COMMON_SERVER_SOCKET_H__ + +#include "socket_base.h" +namespace OHOS { +namespace nmd { +namespace common { +class server_socket : public socket_base { +public: + server_socket(); + ~server_socket(); + + int bindPort(uint16_t port); + int bindFile(const char *filePath, const char *name); + +private: + struct sockaddr addr_ {}; +}; +} // namespace common +} // namespace nmd +} // namespace OHOS #endif // !NETD_COMMON_SERVER_SOCKET_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/server_template.h b/prebuilts/librarys/netd/include/common/include/server_template.h index c29ba9d2c..7a5054da9 100755 --- a/prebuilts/librarys/netd/include/common/include/server_template.h +++ b/prebuilts/librarys/netd/include/common/include/server_template.h @@ -1,54 +1,54 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_SERVER_TEMPLATE_H__ -#define INCLUDE_SERVER_TEMPLATE_H__ -#include -#include -#include "server_socket.h" -#include "thread_pool.h" -namespace OHOS { -namespace nmd { -namespace common { -class server_template { - const char *const SOCKET_FILE_PATH = "/dev/socket"; - -public: - void start(); - void stop(); - void handler(int socketFd, const uint8_t *msg, const size_t msgLen); - -public: - explicit server_template(const char *socketName, const char *serverName) - : socketName_(socketName), serverName_(serverName), server_(std::make_shared()), - pool_(std::make_shared(16, 256)), job_(nullptr) - {} - virtual ~server_template() = default; - -protected: - virtual void initJob(const int socketFd, const uint8_t *msg, const size_t msgLen) = 0; - -protected: - std::string socketName_; - std::string serverName_; - std::shared_ptr server_; - std::shared_ptr pool_; - nmd::job *job_; - bool mRunning = false; -}; -} // namespace common -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_SERVER_TEMPLATE_H__ +#define INCLUDE_SERVER_TEMPLATE_H__ +#include +#include +#include "server_socket.h" +#include "thread_pool.h" +namespace OHOS { +namespace nmd { +namespace common { +class server_template { + const char *const SOCKET_FILE_PATH = "/dev/socket"; + +public: + void start(); + void stop(); + void handler(int socketFd, const uint8_t *msg, const size_t msgLen); + +public: + explicit server_template(const char *socketName, const char *serverName) + : socketName_(socketName), serverName_(serverName), server_(std::make_shared()), + pool_(std::make_shared(16, 256)), job_(nullptr) + {} + virtual ~server_template() = default; + +protected: + virtual void initJob(const int socketFd, const uint8_t *msg, const size_t msgLen) = 0; + +protected: + std::string socketName_; + std::string serverName_; + std::shared_ptr server_; + std::shared_ptr pool_; + nmd::job *job_; + bool mRunning = false; +}; +} // namespace common +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_SERVER_TEMPLATE_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/socket_base.h b/prebuilts/librarys/netd/include/common/include/socket_base.h index 6ee257911..a0fce0e8c 100755 --- a/prebuilts/librarys/netd/include/common/include/socket_base.h +++ b/prebuilts/librarys/netd/include/common/include/socket_base.h @@ -1,76 +1,76 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NETD_SOCKET_BASE_H__ -#define NETD_SOCKET_BASE_H__ - -#include -#include -#include -#include -#include "netnative_log_wrapper.h" - -namespace OHOS { -namespace nmd { -namespace common { -typedef struct end_point { - int port; -} end_point; -class socket_base { -public: - socket_base(); - virtual ~socket_base(); - - int createInet(); - int createUnix(); - int listenSocket(); - int acceptSocket(); - int connectSocket(struct sockaddr_in serverAddr); - ssize_t sendSocket(int socketFd, const char *buffer); - ssize_t sendSocket(const char *buffer); - virtual ssize_t sendMsg(const int socketFd, const msghdr &msg); - char *receiveSocket(char *buffer); - - template - void setRecevedHandler(R (*)(Params...)) - {} - - template - void setRecevedHandler(R (C::*func)(Params...), C *instance) - { - this->handler_ = - std::bind(func, instance, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); - } - - int getSocketFileDescriptor() - { - return this->socketFd_; - } - -protected: - int socketFd_; - int epollFd_ = 0; - int eventCnt_ = 0; - struct epoll_event *epollEvents_; - struct epoll_event event_ {}; - std::function handler_; - -private: - int create(int domain, int protocol); -}; -} // namespace common -} // namespace nmd -} // namespace OHOS -#endif // !NETD_SOCKET_BASE_H__ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETD_SOCKET_BASE_H__ +#define NETD_SOCKET_BASE_H__ + +#include +#include +#include +#include +#include "netnative_log_wrapper.h" + +namespace OHOS { +namespace nmd { +namespace common { +typedef struct end_point { + int port; +} end_point; +class socket_base { +public: + socket_base(); + virtual ~socket_base(); + + int createInet(); + int createUnix(); + int listenSocket(); + int acceptSocket(); + int connectSocket(struct sockaddr_in serverAddr); + ssize_t sendSocket(int socketFd, const char *buffer); + ssize_t sendSocket(const char *buffer); + virtual ssize_t sendMsg(const int socketFd, const msghdr &msg); + char *receiveSocket(char *buffer); + + template + void setRecevedHandler(R (*)(Params...)) + {} + + template + void setRecevedHandler(R (C::*func)(Params...), C *instance) + { + this->handler_ = + std::bind(func, instance, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); + } + + int getSocketFileDescriptor() + { + return this->socketFd_; + } + +protected: + int socketFd_; + int epollFd_ = 0; + int eventCnt_ = 0; + struct epoll_event *epollEvents_; + struct epoll_event event_ {}; + std::function handler_; + +private: + int create(int domain, int protocol); +}; +} // namespace common +} // namespace nmd +} // namespace OHOS +#endif // !NETD_SOCKET_BASE_H__ diff --git a/prebuilts/librarys/netd/include/common/include/thread_pool.h b/prebuilts/librarys/netd/include/common/include/thread_pool.h index aed9c9b3a..db6e12e33 100755 --- a/prebuilts/librarys/netd/include/common/include/thread_pool.h +++ b/prebuilts/librarys/netd/include/common/include/thread_pool.h @@ -1,57 +1,57 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_THREAD_POOL_H__ -#define INCLUDE_THREAD_POOL_H__ - -#include -#include -#include -#include -#include -#include -#include -#include "blocking_queue.h" -#include "job.h" - -namespace OHOS { -namespace nmd { -class thread_pool { -public: - thread_pool(unsigned int threadNums, unsigned int queueSize); - - void execute(nmd::job *job); - - ~thread_pool(); - -private: - unsigned int threadNums_; - unsigned int queueSize_; - - bool running_ = false; - - std::vector workers_; - nmd::blocking_queue *workQueue_; - - std::mutex mutex_; - std::condition_variable cond_; - - void threadLoop(); - - nmd::job *takeJobFromQueue(); -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_THREAD_POOL_H__ +#define INCLUDE_THREAD_POOL_H__ + +#include +#include +#include +#include +#include +#include +#include +#include "blocking_queue.h" +#include "job.h" + +namespace OHOS { +namespace nmd { +class thread_pool { +public: + thread_pool(unsigned int threadNums, unsigned int queueSize); + + void execute(nmd::job *job); + + ~thread_pool(); + +private: + unsigned int threadNums_; + unsigned int queueSize_; + + bool running_ = false; + + std::vector workers_; + nmd::blocking_queue *workQueue_; + + std::mutex mutex_; + std::condition_variable cond_; + + void threadLoop(); + + nmd::job *takeJobFromQueue(); +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_THREAD_POOL_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/warning_disable.h b/prebuilts/librarys/netd/include/common/include/warning_disable.h index 1ae027e26..32c77246f 100755 --- a/prebuilts/librarys/netd/include/common/include/warning_disable.h +++ b/prebuilts/librarys/netd/include/common/include/warning_disable.h @@ -1,46 +1,46 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_WARNING_DISABLE_H__ -#define INCLUDE_WARNING_DISABLE_H__ - -#if defined(__GNUC__) || defined(__clang__) -#define DO_PRAGMA(X) _Pragma(#X) -#define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) -#define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) -#define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored warningName) - -#define DISABLE_WARNING_OLD_STYLE_CAST DISABLE_WARNING("-Wold-style-cast") -#define DISABLE_WARNING_MISSING_FIELD_INITIALIZERS DISABLE_WARNING("-Wmissing-field-initializers") -#define DISABLE_WARNING_SIGN_CONVERSION DISABLE_WARNING("-Wsign-conversion") -#define DISABLE_WARNING_IMPLICIT_INT_CONVERSION DISABLE_WARNING("-Wimplicit-int-conversion") -#define DISABLE_WARNING_SIGN_COMPARE DISABLE_WARNING("-Wsign-compare") -#define DISABLE_WARNING_SHORTEN_64_TO_32 DISABLE_WARNING("-Wshorten-64-to-32") -#define DISABLE_WARNING_CAST_ALIGN DISABLE_WARNING("-Wcast-align") -#define DISABLE_WARNING_UNUSED_PARAMETER DISABLE_WARNING("-Wunused-parameter") -#define DISABLE_WARNING_UNUSED_VARIABLE DISABLE_WARNING("-Wunused-variable") -#define DISABLE_WARNING_C99_EXTENSIONS DISABLE_WARNING("-Wc99-extensions") -// other warnings you want to deactivate... - -#else -#define DISABLE_WARNING_PUSH -#define DISABLE_WARNING_POP -#define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER -#define DISABLE_WARNING_UNREFERENCED_FUNCTION -// other warnings you want to deactivate... - -#endif - +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_WARNING_DISABLE_H__ +#define INCLUDE_WARNING_DISABLE_H__ + +#if defined(__GNUC__) || defined(__clang__) +#define DO_PRAGMA(X) _Pragma(#X) +#define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) +#define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) +#define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored warningName) + +#define DISABLE_WARNING_OLD_STYLE_CAST DISABLE_WARNING("-Wold-style-cast") +#define DISABLE_WARNING_MISSING_FIELD_INITIALIZERS DISABLE_WARNING("-Wmissing-field-initializers") +#define DISABLE_WARNING_SIGN_CONVERSION DISABLE_WARNING("-Wsign-conversion") +#define DISABLE_WARNING_IMPLICIT_INT_CONVERSION DISABLE_WARNING("-Wimplicit-int-conversion") +#define DISABLE_WARNING_SIGN_COMPARE DISABLE_WARNING("-Wsign-compare") +#define DISABLE_WARNING_SHORTEN_64_TO_32 DISABLE_WARNING("-Wshorten-64-to-32") +#define DISABLE_WARNING_CAST_ALIGN DISABLE_WARNING("-Wcast-align") +#define DISABLE_WARNING_UNUSED_PARAMETER DISABLE_WARNING("-Wunused-parameter") +#define DISABLE_WARNING_UNUSED_VARIABLE DISABLE_WARNING("-Wunused-variable") +#define DISABLE_WARNING_C99_EXTENSIONS DISABLE_WARNING("-Wc99-extensions") +// other warnings you want to deactivate... + +#else +#define DISABLE_WARNING_PUSH +#define DISABLE_WARNING_POP +#define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER +#define DISABLE_WARNING_UNREFERENCED_FUNCTION +// other warnings you want to deactivate... + +#endif + #endif // !INCLUDE_WARNING_DISABLE_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv.h b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv.h index a3eb1c221..2a60c3097 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv.h @@ -1,218 +1,218 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_DNSRESOLV_H__ -#define INCLUDE_DNSRESOLV_H__ -#include -#include -#include -#include "net_utils.h" -#include "warning_disable.h" - -#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST | AI_NUMERICSERV | AI_ADDRCONFIG) - -namespace OHOS { -namespace nmd { -DISABLE_WARNING_PUSH -DISABLE_WARNING_OLD_STYLE_CAST -const uid_t NET_CONTEXT_INVALID_UID = ((uid_t)-1); -DISABLE_WARNING_POP - -const uint8_t RES_DEFAULT_TIMEOUT = 5; // default dns request timeout - -const int32_t ANY_SOCK_TYPE = 0; - -const pid_t NET_CONTEXT_INVALID_PID = -1; - -const uint8_t PTON_MAX = 16; -constexpr int MAX_PACKET = 8 * 1024; - -const uint8_t RCODE_TIMEOUT = 255; -const uint8_t RCODE_INTERNAL_ERROR = 254; - -const uint8_t MAXNS = 4; // max # name servers we'll track - -const long BILLION = 1000000000; - -const uint16_t DNS_REQ_PORT = 53; -const char *const DNS_REQ_PORT_STR = "53"; - -const uint8_t ANYSIZE_ARRAY = 1; - -// MARK_UNSET represents the default (i.e. unset) value for a socket mark. -const uint32_t NETID_UNSET = 0u; -const uint32_t MARK_UNSET = 0u; - -const uint32_t MAX_NAME_LEN = 64; -const uint32_t MAX_NAME_LIST_LEN = 1024; - -struct netd_net_context { - uint16_t appNetId; - uint32_t appMark; - uint16_t dnsNetId; - uint32_t dnsMark; - uid_t uid = NET_CONTEXT_INVALID_UID; - uint32_t flags; - pid_t pid = NET_CONTEXT_INVALID_PID; -}; - -union sockaddr_union { - struct sockaddr sa; - struct sockaddr_in sin; - struct sockaddr_in6 sin6; -}; - -struct res_target { - struct res_target *next; - const char *name; // domain name - int qclass; - int qtype; // class and type of query - std::vector answer = std::vector(MAX_PACKET, 0); // buffer to put answer - size_t n = 0; // result length -}; - -struct dns_res_state { - void init(const netd_net_context *netcontext) - { - if (netcontext == nullptr) { - return; - } - netid = netcontext->dnsNetId; - ndots = 1; - mark = netcontext->dnsMark; - - for (auto &sock : nssocks) { - sock.reset(); - } - } - - void closeSockets() - { - tcpNsSock.reset(); - isTcp = false; - - for (auto &sock : nssocks) { - sock.reset(); - } - } - - size_t nameserverCount() - { - return nsaddrs.size(); - } - - uint16_t netid; // NetId: cache key and socket mark - uid_t uid; // uid of the app that sent the DNS lookup - pid_t pid; // pid of the app that sent the DNS lookup - uint16_t id; // current message id - std::vector searchDomains {}; // domains to search - std::vector nsaddrs; - nmd::common::net_utils::socket_fd nssocks[MAXNS]; // UDP sockets to nameservers - unsigned ndots : 4; // threshold for initial abs. query - unsigned mark; // If non-0 SET_MARK to mark on all request sockets - nmd::common::net_utils::socket_fd tcpNsSock; // TCP socket - bool isTcp = false; -}; - -// Per-netid configuration parameters passed from netd to the resolver -struct dns_res_params { - uint16_t baseTimeoutMsec; // base query retry timeout (if 0, use RES_TIMEOUT) - uint8_t retryCount = 1; // number of retries - void operator=(const dns_res_params ¶m) - { - baseTimeoutMsec = param.baseTimeoutMsec; - retryCount = param.retryCount; - } -}; - -enum dns_request_send_flag : uint32_t { - // Send a single request to a single resolver and fail on timeout or network errors - NETD_DNS_RESOLV_NO_RETRY = 1 << 0, - - // Don't lookup this request in the cache, and don't cache the result of the lookup. - NETD_DNS_RESOLV_NO_CACHE_STORE = 1 << 1, - - // Don't lookup the request in cache. - NETD_DNS_RESOLV_NO_CACHE_LOOKUP = 1 << 2, -}; - -struct dnsresolver_params { - uint16_t netId = 0; - uint16_t baseTimeoutMsec = 0; - uint8_t retryCount = 0; - std::vector servers; - std::vector domains; -}; - -typedef struct alignas(8) dnsresolver_request_cmd { - enum cmd_id { - CREATE_NETWORK_CACHE, - SET_RESOLVER_CONFIG, - DESOTRY_NETWORK_CACHE, - GET_ADDR_INFO, - GET_ADDR_INFO_PROXY, - } cmdID; - uint16_t netid; - union { - struct dnsresolv_req_param { - addrinfo hints; - uid_t uid; - char hostName[MAX_NAME_LEN]; - char serverName[MAX_NAME_LEN]; - } reqParam; - - struct dnsresolv_cfg_param { - uint16_t baseTimeoutMsec; - uint8_t retryCount; - uint8_t serverCount; - uint8_t domainCount; - char servers[MAX_NAME_LIST_LEN]; - char domains[MAX_NAME_LIST_LEN]; - } cfgParam; - } u; -} dnsresolver_request_cmd_t; - -#define cmd_hints u.reqParam.hints -#define cmd_uid u.reqParam.uid -#define cmd_hostName u.reqParam.hostName -#define cmd_serverName u.reqParam.serverName - -#define cmd_baseTimeoutMsec u.cfgParam.baseTimeoutMsec -#define cmd_retryCount u.cfgParam.retryCount -#define cmd_serverCount u.cfgParam.serverCount -#define cmd_domainCount u.cfgParam.domainCount -#define cmd_servers u.cfgParam.servers -#define cmd_domains u.cfgParam.domains - -typedef struct alignas(8) dnsresolver_response_cmd { - enum cmd_id { - QUERY_STATE_OK, - QUERY_STATE_FAIL, - QUERY_SUCCESS_WITH_RESULT, - QUERY_STATE_BUTT - } cmdID = QUERY_STATE_BUTT; - int result = 0; - size_t resSize = 0; - uint8_t resData[ANYSIZE_ARRAY]; -} dnsresolver_response_cmd_t, *p_dnsresolver_response_cmd; - -typedef void (*get_network_context_callback)(uint16_t netid, uid_t uid, netd_net_context &netcontext); -struct dnsresolv_callbacks { - dnsresolv_callbacks() : getNetworkContext(nullptr) {} - get_network_context_callback getNetworkContext; -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_DNSRESOLV_H__ +#define INCLUDE_DNSRESOLV_H__ +#include +#include +#include +#include "net_utils.h" +#include "warning_disable.h" + +#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST | AI_NUMERICSERV | AI_ADDRCONFIG) + +namespace OHOS { +namespace nmd { +DISABLE_WARNING_PUSH +DISABLE_WARNING_OLD_STYLE_CAST +const uid_t NET_CONTEXT_INVALID_UID = ((uid_t)-1); +DISABLE_WARNING_POP + +const uint8_t RES_DEFAULT_TIMEOUT = 5; // default dns request timeout + +const int32_t ANY_SOCK_TYPE = 0; + +const pid_t NET_CONTEXT_INVALID_PID = -1; + +const uint8_t PTON_MAX = 16; +constexpr int MAX_PACKET = 8 * 1024; + +const uint8_t RCODE_TIMEOUT = 255; +const uint8_t RCODE_INTERNAL_ERROR = 254; + +const uint8_t MAXNS = 4; // max # name servers we'll track + +const long BILLION = 1000000000; + +const uint16_t DNS_REQ_PORT = 53; +const char *const DNS_REQ_PORT_STR = "53"; + +const uint8_t ANYSIZE_ARRAY = 1; + +// MARK_UNSET represents the default (i.e. unset) value for a socket mark. +const uint32_t NETID_UNSET = 0u; +const uint32_t MARK_UNSET = 0u; + +const uint32_t MAX_NAME_LEN = 64; +const uint32_t MAX_NAME_LIST_LEN = 1024; + +struct netd_net_context { + uint16_t appNetId; + uint32_t appMark; + uint16_t dnsNetId; + uint32_t dnsMark; + uid_t uid = NET_CONTEXT_INVALID_UID; + uint32_t flags; + pid_t pid = NET_CONTEXT_INVALID_PID; +}; + +union sockaddr_union { + struct sockaddr sa; + struct sockaddr_in sin; + struct sockaddr_in6 sin6; +}; + +struct res_target { + struct res_target *next; + const char *name; // domain name + int qclass; + int qtype; // class and type of query + std::vector answer = std::vector(MAX_PACKET, 0); // buffer to put answer + size_t n = 0; // result length +}; + +struct dns_res_state { + void init(const netd_net_context *netcontext) + { + if (netcontext == nullptr) { + return; + } + netid = netcontext->dnsNetId; + ndots = 1; + mark = netcontext->dnsMark; + + for (auto &sock : nssocks) { + sock.reset(); + } + } + + void closeSockets() + { + tcpNsSock.reset(); + isTcp = false; + + for (auto &sock : nssocks) { + sock.reset(); + } + } + + size_t nameserverCount() + { + return nsaddrs.size(); + } + + uint16_t netid; // NetId: cache key and socket mark + uid_t uid; // uid of the app that sent the DNS lookup + pid_t pid; // pid of the app that sent the DNS lookup + uint16_t id; // current message id + std::vector searchDomains {}; // domains to search + std::vector nsaddrs; + nmd::common::net_utils::socket_fd nssocks[MAXNS]; // UDP sockets to nameservers + unsigned ndots : 4; // threshold for initial abs. query + unsigned mark; // If non-0 SET_MARK to mark on all request sockets + nmd::common::net_utils::socket_fd tcpNsSock; // TCP socket + bool isTcp = false; +}; + +// Per-netid configuration parameters passed from netd to the resolver +struct dns_res_params { + uint16_t baseTimeoutMsec; // base query retry timeout (if 0, use RES_TIMEOUT) + uint8_t retryCount = 1; // number of retries + void operator=(const dns_res_params ¶m) + { + baseTimeoutMsec = param.baseTimeoutMsec; + retryCount = param.retryCount; + } +}; + +enum dns_request_send_flag : uint32_t { + // Send a single request to a single resolver and fail on timeout or network errors + NETD_DNS_RESOLV_NO_RETRY = 1 << 0, + + // Don't lookup this request in the cache, and don't cache the result of the lookup. + NETD_DNS_RESOLV_NO_CACHE_STORE = 1 << 1, + + // Don't lookup the request in cache. + NETD_DNS_RESOLV_NO_CACHE_LOOKUP = 1 << 2, +}; + +struct dnsresolver_params { + uint16_t netId = 0; + uint16_t baseTimeoutMsec = 0; + uint8_t retryCount = 0; + std::vector servers; + std::vector domains; +}; + +typedef struct alignas(8) dnsresolver_request_cmd { + enum cmd_id { + CREATE_NETWORK_CACHE, + SET_RESOLVER_CONFIG, + DESOTRY_NETWORK_CACHE, + GET_ADDR_INFO, + GET_ADDR_INFO_PROXY, + } cmdID; + uint16_t netid; + union { + struct dnsresolv_req_param { + addrinfo hints; + uid_t uid; + char hostName[MAX_NAME_LEN]; + char serverName[MAX_NAME_LEN]; + } reqParam; + + struct dnsresolv_cfg_param { + uint16_t baseTimeoutMsec; + uint8_t retryCount; + uint8_t serverCount; + uint8_t domainCount; + char servers[MAX_NAME_LIST_LEN]; + char domains[MAX_NAME_LIST_LEN]; + } cfgParam; + } u; +} dnsresolver_request_cmd_t; + +#define cmd_hints u.reqParam.hints +#define cmd_uid u.reqParam.uid +#define cmd_hostName u.reqParam.hostName +#define cmd_serverName u.reqParam.serverName + +#define cmd_baseTimeoutMsec u.cfgParam.baseTimeoutMsec +#define cmd_retryCount u.cfgParam.retryCount +#define cmd_serverCount u.cfgParam.serverCount +#define cmd_domainCount u.cfgParam.domainCount +#define cmd_servers u.cfgParam.servers +#define cmd_domains u.cfgParam.domains + +typedef struct alignas(8) dnsresolver_response_cmd { + enum cmd_id { + QUERY_STATE_OK, + QUERY_STATE_FAIL, + QUERY_SUCCESS_WITH_RESULT, + QUERY_STATE_BUTT + } cmdID = QUERY_STATE_BUTT; + int result = 0; + size_t resSize = 0; + uint8_t resData[ANYSIZE_ARRAY]; +} dnsresolver_response_cmd_t, *p_dnsresolver_response_cmd; + +typedef void (*get_network_context_callback)(uint16_t netid, uid_t uid, netd_net_context &netcontext); +struct dnsresolv_callbacks { + dnsresolv_callbacks() : getNetworkContext(nullptr) {} + get_network_context_callback getNetworkContext; +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_DNSRESOLV_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_controller.h index 627fbe37b..c4839f74c 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_controller.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_controller.h @@ -1,46 +1,46 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_DNSRESOLV_CONTROLLER_H__ -#define INCLUDE_DNSRESOLV_CONTROLLER_H__ - -#include -#include -#include -#include -namespace OHOS { -namespace nmd { -struct dnsresolver_params; -struct netd_net_context; -class dnsresolv_controller { -public: - int getResolverInfo(const uint16_t netid, std::vector &servers, std::vector &domains, - struct dns_res_params ¶m); - int setResolverConfig(const dnsresolver_params &resolvParams); - int createNetworkCache(const uint16_t netid); - int destoryNetworkCache(const uint16_t netid); - int flushNetworkCache(const uint16_t netid); - -public: - static int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, - struct addrinfo **res, const uint16_t netid); - static int getaddrinfoForNet(const char *hostname, const char *servname, const struct addrinfo *hints, - uint16_t netid, unsigned mark, struct addrinfo **res); - static int getaddrinfoFornetContext(const char *hostname, const char *servname, const addrinfo *hints, - const netd_net_context &netcontext, addrinfo **res); -}; -} // namespace nmd -} // namespace OHOS -#endif // !INCLUDE_DNSRESOLV_CONTROLLER_H__ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_DNSRESOLV_CONTROLLER_H__ +#define INCLUDE_DNSRESOLV_CONTROLLER_H__ + +#include +#include +#include +#include +namespace OHOS { +namespace nmd { +struct dnsresolver_params; +struct netd_net_context; +class dnsresolv_controller { +public: + int getResolverInfo(const uint16_t netid, std::vector &servers, std::vector &domains, + struct dns_res_params ¶m); + int setResolverConfig(const dnsresolver_params &resolvParams); + int createNetworkCache(const uint16_t netid); + int destoryNetworkCache(const uint16_t netid); + int flushNetworkCache(const uint16_t netid); + +public: + static int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, + struct addrinfo **res, const uint16_t netid); + static int getaddrinfoForNet(const char *hostname, const char *servname, const struct addrinfo *hints, + uint16_t netid, unsigned mark, struct addrinfo **res); + static int getaddrinfoFornetContext(const char *hostname, const char *servname, const addrinfo *hints, + const netd_net_context &netcontext, addrinfo **res); +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_DNSRESOLV_CONTROLLER_H__ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_service.h b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_service.h index defc48ead..66edb710a 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_service.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_service.h @@ -1,79 +1,79 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_DNSRESOLV_SERVICE_H__ -#define INCLUDE_DNSRESOLV_SERVICE_H__ -#include -#include -#include -#include "dnsresolv.h" -#include "dnsresolv_controller.h" -#include "job.h" -#include "server_template.h" -namespace OHOS { -namespace nmd { -const char *const DNS_RESOLV_SERVICE_SOCK_NAME = "dnsresolvproxy.sock"; -const char *const DNS_RESOLV_SERVICE_NAME = "DNSResolverService"; -class dnsresolv_job : public job { -public: - dnsresolv_job(const int fd, const uint8_t *msg, const size_t msgLen, - const std::shared_ptr serverSocket) - : job(fd, msg, msgLen, serverSocket) - {} - ~dnsresolv_job() = default; - virtual void run() override; - void setupCallbacks(const dnsresolv_callbacks &callbacks) - { - dnsresolvCallbacks_ = callbacks; - } -private: - void doCreateNetworkCache(const dnsresolver_request_cmd *command); - void doSetResolverConfig(const dnsresolver_request_cmd *command); - void doDestroyNetworkCache(const dnsresolver_request_cmd *command); - void doGetAddrInfo(const dnsresolver_request_cmd *command); - void doGetAddrInfoProxy(const dnsresolver_request_cmd *command); - void responseOk(); - void responseOk(const struct addrinfo *res); - void responseFailed(const int ret); - size_t getNameList(const char *buffer, const size_t bufferSize, std::vector &namelist); - ssize_t sendResponseResult(dnsresolver_response_cmd &cmd); -private: - dnsresolv_callbacks dnsresolvCallbacks_; - dnsresolv_controller dnsresolvCtrl_; -}; - -class dnsresolv_service : public common::server_template { -public: - int getResolverInfo(const uint16_t netid, std::vector &servers, std::vector &domains, - dns_res_params ¶m); - int setResolverConfig(const dnsresolver_params &resolvParams); - int createNetworkCache(const uint16_t netid); - int flushNetworkCache(const uint16_t netid); - int destoryNetworkCache(const uint16_t netid); - int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, - struct addrinfo **res, const uint16_t netid); -public: - dnsresolv_service() : common::server_template(DNS_RESOLV_SERVICE_SOCK_NAME, DNS_RESOLV_SERVICE_NAME) {} - ~dnsresolv_service() = default; - bool init(const dnsresolv_callbacks &callbacks); -private: - virtual void initJob(const int socketFd, const uint8_t *msg, const size_t msgLen) override; -private: - dnsresolv_controller dnsresolvCtrl_; - dnsresolv_callbacks dnsresolvCallbacks_; -}; -} // namespace nmd -} // namespace OHOS -#endif // !INCLUDE_DNSRESOLV_SERVICE_H_ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_DNSRESOLV_SERVICE_H__ +#define INCLUDE_DNSRESOLV_SERVICE_H__ +#include +#include +#include +#include "dnsresolv.h" +#include "dnsresolv_controller.h" +#include "job.h" +#include "server_template.h" +namespace OHOS { +namespace nmd { +const char *const DNS_RESOLV_SERVICE_SOCK_NAME = "dnsresolvproxy.sock"; +const char *const DNS_RESOLV_SERVICE_NAME = "DNSResolverService"; +class dnsresolv_job : public job { +public: + dnsresolv_job(const int fd, const uint8_t *msg, const size_t msgLen, + const std::shared_ptr serverSocket) + : job(fd, msg, msgLen, serverSocket) + {} + ~dnsresolv_job() = default; + virtual void run() override; + void setupCallbacks(const dnsresolv_callbacks &callbacks) + { + dnsresolvCallbacks_ = callbacks; + } +private: + void doCreateNetworkCache(const dnsresolver_request_cmd *command); + void doSetResolverConfig(const dnsresolver_request_cmd *command); + void doDestroyNetworkCache(const dnsresolver_request_cmd *command); + void doGetAddrInfo(const dnsresolver_request_cmd *command); + void doGetAddrInfoProxy(const dnsresolver_request_cmd *command); + void responseOk(); + void responseOk(const struct addrinfo *res); + void responseFailed(const int ret); + size_t getNameList(const char *buffer, const size_t bufferSize, std::vector &namelist); + ssize_t sendResponseResult(dnsresolver_response_cmd &cmd); +private: + dnsresolv_callbacks dnsresolvCallbacks_; + dnsresolv_controller dnsresolvCtrl_; +}; + +class dnsresolv_service : public common::server_template { +public: + int getResolverInfo(const uint16_t netid, std::vector &servers, std::vector &domains, + dns_res_params ¶m); + int setResolverConfig(const dnsresolver_params &resolvParams); + int createNetworkCache(const uint16_t netid); + int flushNetworkCache(const uint16_t netid); + int destoryNetworkCache(const uint16_t netid); + int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, + struct addrinfo **res, const uint16_t netid); +public: + dnsresolv_service() : common::server_template(DNS_RESOLV_SERVICE_SOCK_NAME, DNS_RESOLV_SERVICE_NAME) {} + ~dnsresolv_service() = default; + bool init(const dnsresolv_callbacks &callbacks); +private: + virtual void initJob(const int socketFd, const uint8_t *msg, const size_t msgLen) override; +private: + dnsresolv_controller dnsresolvCtrl_; + dnsresolv_callbacks dnsresolvCallbacks_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_DNSRESOLV_SERVICE_H_ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/event_reporter.h b/prebuilts/librarys/netd/include/net_mgr_native/include/event_reporter.h index 90dc732cd..672e7aaf6 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/event_reporter.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/event_reporter.h @@ -1,48 +1,48 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_EVENT_REPORTER_H__ -#define INCLUDE_EVENT_REPORTER_H__ -#include - -namespace OHOS { -namespace nmd { -typedef struct inetd_unsolicited_event_listener { - void (*onInterfaceAddressUpdated)(const std::string &addr, const std::string &ifName, int flags, int scope); - void (*onInterfaceAddressRemoved)(const std::string &addr, const std::string &ifName, int flags, int scope); - void (*onInterfaceAdded)(const std::string &ifName); - void (*onInterfaceRemoved)(const std::string &ifName); - void (*onInterfaceChanged)(const std::string &ifName, bool up); - void (*onInterfaceLinkStateChanged)(const std::string &ifName, bool up); - void (*onRouteChanged)( - bool updated, const std::string &route, const std::string &gateway, const std::string &ifName); -} inetd_unsolicited_event_listener; - -class event_reporter { -public: - event_reporter() = default; - void registerEventListener(inetd_unsolicited_event_listener &listener); - inetd_unsolicited_event_listener getListener() - { - return this->listener_; - } - ~event_reporter(); - -private: - inetd_unsolicited_event_listener listener_; -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_EVENT_REPORTER_H__ +#define INCLUDE_EVENT_REPORTER_H__ +#include + +namespace OHOS { +namespace nmd { +typedef struct inetd_unsolicited_event_listener { + void (*onInterfaceAddressUpdated)(const std::string &addr, const std::string &ifName, int flags, int scope); + void (*onInterfaceAddressRemoved)(const std::string &addr, const std::string &ifName, int flags, int scope); + void (*onInterfaceAdded)(const std::string &ifName); + void (*onInterfaceRemoved)(const std::string &ifName); + void (*onInterfaceChanged)(const std::string &ifName, bool up); + void (*onInterfaceLinkStateChanged)(const std::string &ifName, bool up); + void (*onRouteChanged)( + bool updated, const std::string &route, const std::string &gateway, const std::string &ifName); +} inetd_unsolicited_event_listener; + +class event_reporter { +public: + event_reporter() = default; + void registerEventListener(inetd_unsolicited_event_listener &listener); + inetd_unsolicited_event_listener getListener() + { + return this->listener_; + } + ~event_reporter(); + +private: + inetd_unsolicited_event_listener listener_; +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_EVENT_REPORTER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/fwmark_server.h b/prebuilts/librarys/netd/include/net_mgr_native/include/fwmark_server.h index 7b09044ea..fad6b6920 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/fwmark_server.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/fwmark_server.h @@ -1,53 +1,53 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __INCLUDE_FWMARK_SERVER_H__ -#define __INCLUDE_FWMARK_SERVER_H__ - -#include -#include "job.h" -#include "server_template.h" -namespace OHOS { -namespace nmd { -const char *const FWMARK_SERVER_SOCK_NAME = "fwmarkd.sock"; -const char *const FWMARK_SERVER_NAME = "FWMarkServer"; - -class fwmark_job : public job { -public: - fwmark_job(const int fd, const uint8_t *msg, const size_t msgLen, - const std::shared_ptr &serverSocket) - : job(fd, msg, msgLen, serverSocket) - {} - ~fwmark_job() = default; - - virtual void run() override; - -private: - void responseOk(); - void responseFailed(); -}; - -class fwmark_server : public common::server_template { -public: - fwmark_server() : common::server_template(FWMARK_SERVER_SOCK_NAME, FWMARK_SERVER_NAME) {} - - virtual ~fwmark_server() = default; - -private: - virtual void initJob(const int socketFd, const uint8_t *msg, const size_t msgLen) override; -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __INCLUDE_FWMARK_SERVER_H__ +#define __INCLUDE_FWMARK_SERVER_H__ + +#include +#include "job.h" +#include "server_template.h" +namespace OHOS { +namespace nmd { +const char *const FWMARK_SERVER_SOCK_NAME = "fwmarkd.sock"; +const char *const FWMARK_SERVER_NAME = "FWMarkServer"; + +class fwmark_job : public job { +public: + fwmark_job(const int fd, const uint8_t *msg, const size_t msgLen, + const std::shared_ptr &serverSocket) + : job(fd, msg, msgLen, serverSocket) + {} + ~fwmark_job() = default; + + virtual void run() override; + +private: + void responseOk(); + void responseFailed(); +}; + +class fwmark_server : public common::server_template { +public: + fwmark_server() : common::server_template(FWMARK_SERVER_SOCK_NAME, FWMARK_SERVER_NAME) {} + + virtual ~fwmark_server() = default; + +private: + virtual void initJob(const int socketFd, const uint8_t *msg, const size_t msgLen) override; +}; +} // namespace nmd +} // namespace OHOS #endif // !__INCLUDE_FWMARK_SERVER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/interface_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/interface_controller.h index 803f9597f..b37f1b328 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/interface_controller.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/interface_controller.h @@ -1,67 +1,67 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __INCLUDE_INTERFACE_CONTROLLER_H__ -#define __INCLUDE_INTERFACE_CONTROLLER_H__ -#include -#include -#include - -namespace OHOS { -namespace nmd { -typedef struct interface_configuration_parcel { - std::string ifName; - std::string hwAddr; - std::string ipv4Addr; - int prefixLength; - std::vector flags; - friend std::ostream &operator<<(std::ostream &os, const nmd::interface_configuration_parcel &parcel) - { - os << "ifName: " << parcel.ifName << "\n" - << "hwAddr: " << parcel.hwAddr << "\n" - << "ipv4Addr: " << parcel.ipv4Addr << "\n" - << "prefixLength: " << parcel.prefixLength << "\n" - << "flags: [" - << "\n"; - for (unsigned long i = 0; i < parcel.flags.size(); i++) { - os << " " << parcel.flags[i] << "\n"; - } - os << "] " - << "\n"; - return os; - } -} interface_configuration_parcel; - -class interface_controller { -public: - interface_controller(); - ~interface_controller(); - static int setMtu(const char *interfaceName, const char *mtuValue); - static int getMtu(const char *interfaceName); - static std::vector getInterfaceNames(); - static int clearAddrs(const std::string &ifName); - static int interfaceAddAddress(const std::string &ifName, const std::string &addr, const int prefixLen); - static int interfaceDelAddress(const std::string &ifName, const std::string &addr, const int prefixLen); - static int setParameter( - const char *family, const char *which, const char *ifName, const char *parameter, const char *value); - static int getParameter( - const char *family, const char *which, const char *ifName, const char *parameter, std::string *value); - static interface_configuration_parcel getConfig(const std::string &ifName); - static int setConfig(const nmd::interface_configuration_parcel &cfg); -}; -} // namespace nmd -} // namespace OHOS - -#endif // !__INCLUDE_INTERFACE_CONTROLLER_H__ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __INCLUDE_INTERFACE_CONTROLLER_H__ +#define __INCLUDE_INTERFACE_CONTROLLER_H__ +#include +#include +#include + +namespace OHOS { +namespace nmd { +typedef struct interface_configuration_parcel { + std::string ifName; + std::string hwAddr; + std::string ipv4Addr; + int prefixLength; + std::vector flags; + friend std::ostream &operator<<(std::ostream &os, const nmd::interface_configuration_parcel &parcel) + { + os << "ifName: " << parcel.ifName << "\n" + << "hwAddr: " << parcel.hwAddr << "\n" + << "ipv4Addr: " << parcel.ipv4Addr << "\n" + << "prefixLength: " << parcel.prefixLength << "\n" + << "flags: [" + << "\n"; + for (unsigned long i = 0; i < parcel.flags.size(); i++) { + os << " " << parcel.flags[i] << "\n"; + } + os << "] " + << "\n"; + return os; + } +} interface_configuration_parcel; + +class interface_controller { +public: + interface_controller(); + ~interface_controller(); + static int setMtu(const char *interfaceName, const char *mtuValue); + static int getMtu(const char *interfaceName); + static std::vector getInterfaceNames(); + static int clearAddrs(const std::string &ifName); + static int interfaceAddAddress(const std::string &ifName, const std::string &addr, const int prefixLen); + static int interfaceDelAddress(const std::string &ifName, const std::string &addr, const int prefixLen); + static int setParameter( + const char *family, const char *which, const char *ifName, const char *parameter, const char *value); + static int getParameter( + const char *family, const char *which, const char *ifName, const char *parameter, std::string *value); + static interface_configuration_parcel getConfig(const std::string &ifName); + static int setConfig(const nmd::interface_configuration_parcel &cfg); +}; +} // namespace nmd +} // namespace OHOS + +#endif // !__INCLUDE_INTERFACE_CONTROLLER_H__ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/net_manager_native.h b/prebuilts/librarys/netd/include/net_mgr_native/include/net_manager_native.h index 0403b38c7..d8b6d023d 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/net_manager_native.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/net_manager_native.h @@ -1,128 +1,128 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_NET_MANAGER_NATIVE_H__ -#define INCLUDE_NET_MANAGER_NATIVE_H__ - -#include -#include -#include -#include -#include -#include -#include -#include "event_reporter.h" - -namespace OHOS { -namespace nmd { -enum set_proc_sys_net { - IPV4 = 4, - IPV6 = 6, - CONF = 1, - NEIGH = 2, -}; -typedef struct route_info_parcel { - std::string destination; - std::string ifName; - std::string nextHop; - int mtu; -} route_info_parcel; - -typedef struct tether_offload_rule_parcel { - int inputInterfaceIndex; - int outputInterfaceIndex; - std::vector destination; - int prefixLength; - std::vector srcL2Address; - std::vector dstL2Address; - int pmtu = 1500; -} tether_offload_rule_parcel; - -typedef struct tether_config_parcel { - bool usingLegacyDnsProxy; - std::vector dhcpRanges; -} tether_config_parcel; - -typedef struct mark_mask_parcel { - int mark; - int mask; -} mark_mask_parcel; -class NetManagerNative { -public: - NetManagerNative(); - ~NetManagerNative(); - - static void getOriginInterfaceIdex(); - static std::vector getCurrentInterfaceIdex(); - static void updateInterfaceIdex(unsigned int infIdex); - - void initChildChains(); - void initUnixSocket(); - void initDnsConfFile(); - void init(); - - int networkCreatePhysical(int netId, int permission); - int networkDestroy(int netId); - int networkAddInterface(int netId, std::string iface); - int networkRemoveInterface(int netId, std::string iface); - void socketDestroy(std::string iface); - void socketDestroy(int netId); - mark_mask_parcel getFwmarkForNetwork(int netId); - int networkAddRoute(int netId, std::string ifName, std::string destination, std::string nextHop); - int networkRemoveRoute(int netId, std::string ifName, std::string destination, std::string nextHop); - int networkGetDefault(); - int networkSetDefault(int netId); - int networkClearDefault(); - int networkSetPermissionForNetwork(int netId, NetworkPermission permission); - std::vector interfaceGetList(); - - int setProcSysNet(int32_t ipversion, int32_t which, const std::string ifname, const std::string parameter, - const std::string value); - int getProcSysNet(int32_t ipversion, int32_t which, const std::string ifname, const std::string parameter, - std::string *value); - - nmd::interface_configuration_parcel interfaceGetConfig(std::string ifName); - void interfaceSetConfig(interface_configuration_parcel cfg); - void interfaceClearAddrs(const std::string ifName); - int interfaceGetMtu(std::string ifName); - int interfaceSetMtu(std::string ifName, int mtuValue); - int interfaceAddAddress(std::string ifName, std::string addrString, int prefixLength); - int interfaceDelAddress(std::string ifName, std::string addrString, int prefixLength); - - void registerUnsolicitedEventListener(inetd_unsolicited_event_listener listener); - int networkAddRouteParcel(int netId, route_info_parcel routeInfo); - int networkRemoveRouteParcel(int netId, route_info_parcel routeInfo); - - long getCellularRxBytes(); - long getCellularTxBytes(); - long getAllRxBytes(); - long getAllTxBytes(); - long getUidTxBytes(int uid); - long getUidRxBytes(int uid); - traffic_stats_parcel interfaceGetStats(std::string interfaceName); - long getIfaceRxBytes(std::string interfaceName); - long getIfaceTxBytes(std::string interfaceName); - long getTetherRxBytes(); - long getTetherTxBytes(); - -private: - std::shared_ptr networkController_; - std::shared_ptr routeController_; - std::shared_ptr interfaceController_; - static std::vector interfaceIdex_; -}; -} // namespace nmd -} // namespace OHOS -#endif // !INCLUDE_NET_MANAGER_NATIVE_H__ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NET_MANAGER_NATIVE_H__ +#define INCLUDE_NET_MANAGER_NATIVE_H__ + +#include +#include +#include +#include +#include +#include +#include +#include "event_reporter.h" + +namespace OHOS { +namespace nmd { +enum set_proc_sys_net { + IPV4 = 4, + IPV6 = 6, + CONF = 1, + NEIGH = 2, +}; +typedef struct route_info_parcel { + std::string destination; + std::string ifName; + std::string nextHop; + int mtu; +} route_info_parcel; + +typedef struct tether_offload_rule_parcel { + int inputInterfaceIndex; + int outputInterfaceIndex; + std::vector destination; + int prefixLength; + std::vector srcL2Address; + std::vector dstL2Address; + int pmtu = 1500; +} tether_offload_rule_parcel; + +typedef struct tether_config_parcel { + bool usingLegacyDnsProxy; + std::vector dhcpRanges; +} tether_config_parcel; + +typedef struct mark_mask_parcel { + int mark; + int mask; +} mark_mask_parcel; +class NetManagerNative { +public: + NetManagerNative(); + ~NetManagerNative(); + + static void getOriginInterfaceIdex(); + static std::vector getCurrentInterfaceIdex(); + static void updateInterfaceIdex(unsigned int infIdex); + + void initChildChains(); + void initUnixSocket(); + void initDnsConfFile(); + void init(); + + int networkCreatePhysical(int netId, int permission); + int networkDestroy(int netId); + int networkAddInterface(int netId, std::string iface); + int networkRemoveInterface(int netId, std::string iface); + void socketDestroy(std::string iface); + void socketDestroy(int netId); + mark_mask_parcel getFwmarkForNetwork(int netId); + int networkAddRoute(int netId, std::string ifName, std::string destination, std::string nextHop); + int networkRemoveRoute(int netId, std::string ifName, std::string destination, std::string nextHop); + int networkGetDefault(); + int networkSetDefault(int netId); + int networkClearDefault(); + int networkSetPermissionForNetwork(int netId, NetworkPermission permission); + std::vector interfaceGetList(); + + int setProcSysNet(int32_t ipversion, int32_t which, const std::string ifname, const std::string parameter, + const std::string value); + int getProcSysNet(int32_t ipversion, int32_t which, const std::string ifname, const std::string parameter, + std::string *value); + + nmd::interface_configuration_parcel interfaceGetConfig(std::string ifName); + void interfaceSetConfig(interface_configuration_parcel cfg); + void interfaceClearAddrs(const std::string ifName); + int interfaceGetMtu(std::string ifName); + int interfaceSetMtu(std::string ifName, int mtuValue); + int interfaceAddAddress(std::string ifName, std::string addrString, int prefixLength); + int interfaceDelAddress(std::string ifName, std::string addrString, int prefixLength); + + void registerUnsolicitedEventListener(inetd_unsolicited_event_listener listener); + int networkAddRouteParcel(int netId, route_info_parcel routeInfo); + int networkRemoveRouteParcel(int netId, route_info_parcel routeInfo); + + long getCellularRxBytes(); + long getCellularTxBytes(); + long getAllRxBytes(); + long getAllTxBytes(); + long getUidTxBytes(int uid); + long getUidRxBytes(int uid); + traffic_stats_parcel interfaceGetStats(std::string interfaceName); + long getIfaceRxBytes(std::string interfaceName); + long getIfaceTxBytes(std::string interfaceName); + long getTetherRxBytes(); + long getTetherTxBytes(); + +private: + std::shared_ptr networkController_; + std::shared_ptr routeController_; + std::shared_ptr interfaceController_; + static std::vector interfaceIdex_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NET_MANAGER_NATIVE_H__ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_event.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_event.h index c6d2c8822..34475045f 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_event.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_event.h @@ -1,75 +1,75 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_NETLINK_EVENT_H__ -#define INCLUDE_NETLINK_EVENT_H__ - -#include -#include -#include -#include -#include -#include -#include -namespace OHOS { -namespace nmd { -enum class Action { - Unknown = 0, - Add, - Remove, - Change, - LinkUp, - LinkDown, - AddressUpdated, - AddressRemoved, - RouteUpdated, - RouteRemoved, - NewRule, - DelRule, -}; -class netlink_event { -public: - netlink_event() = default; - bool parseInterfaceInfoInfoMessage(struct nlmsghdr *hdr); - bool parseInterafaceAddressMessage(struct nlmsghdr *hdr); - bool parseRouteMessage(struct nlmsghdr *hdr); - bool parseRuleMessage(struct nlmsghdr *hdr); - bool parseNetLinkMessage(char *buffer, ssize_t size); - - void setAction(Action action) - { - this->action_ = action; - } - Action getAction() - { - return this->action_; - } - - void addParam(std::string key, std::string value) - { - this->params_.insert(std::pair(key, value)); - } - const char *findParam(const char *key); - const char *rtMessageName(int type); - - ~netlink_event(); - -private: - Action action_; - std::map params_; -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_EVENT_H__ +#define INCLUDE_NETLINK_EVENT_H__ + +#include +#include +#include +#include +#include +#include +#include +namespace OHOS { +namespace nmd { +enum class Action { + Unknown = 0, + Add, + Remove, + Change, + LinkUp, + LinkDown, + AddressUpdated, + AddressRemoved, + RouteUpdated, + RouteRemoved, + NewRule, + DelRule, +}; +class netlink_event { +public: + netlink_event() = default; + bool parseInterfaceInfoInfoMessage(struct nlmsghdr *hdr); + bool parseInterafaceAddressMessage(struct nlmsghdr *hdr); + bool parseRouteMessage(struct nlmsghdr *hdr); + bool parseRuleMessage(struct nlmsghdr *hdr); + bool parseNetLinkMessage(char *buffer, ssize_t size); + + void setAction(Action action) + { + this->action_ = action; + } + Action getAction() + { + return this->action_; + } + + void addParam(std::string key, std::string value) + { + this->params_.insert(std::pair(key, value)); + } + const char *findParam(const char *key); + const char *rtMessageName(int type); + + ~netlink_event(); + +private: + Action action_; + std::map params_; +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_NETLINK_EVENT_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_handler.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_handler.h index 200a90a7f..bad7674be 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_handler.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_handler.h @@ -1,59 +1,59 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_NETLINK_HANDLER_H__ -#define INCLUDE_NETLINK_HANDLER_H__ -#include -#include "event_reporter.h" -#include "netlink_listener.h" -#include "netlink_event.h" - -namespace OHOS { -namespace nmd { -class netlink_handler : public netlink_listener { -public: - void onEvent(std::shared_ptr evt); - - void notifyInterfaceAdded(const std::string &ifName); - void notifyInterfaceRemoved(const std::string &ifName); - void notifyInterfaceChanged(const std::string &ifName, bool isUp); - void notifyInterfaceLinkChanged(const std::string &ifName, bool isUp); - void notifyAddressUpdated(const std::string &addr, const std::string &ifName, int flags, int scope); - void notifyAddressRemoved(const std::string &addr, const std::string &ifName, int flags, int scope); - void notifyRouteChange( - bool updated, const std::string &route, const std::string &gateway, const std::string &ifName); - - int start(); - void stop(); - - int getSock() - { - return this->socketFd_; - } - - void setEventListener(const std::shared_ptr &reporter) - { - this->reporter_ = reporter; - } - - netlink_handler(int protocol, int pid); - ~netlink_handler(); - -private: - std::shared_ptr reporter_; -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_HANDLER_H__ +#define INCLUDE_NETLINK_HANDLER_H__ +#include +#include "event_reporter.h" +#include "netlink_listener.h" +#include "netlink_event.h" + +namespace OHOS { +namespace nmd { +class netlink_handler : public netlink_listener { +public: + void onEvent(std::shared_ptr evt); + + void notifyInterfaceAdded(const std::string &ifName); + void notifyInterfaceRemoved(const std::string &ifName); + void notifyInterfaceChanged(const std::string &ifName, bool isUp); + void notifyInterfaceLinkChanged(const std::string &ifName, bool isUp); + void notifyAddressUpdated(const std::string &addr, const std::string &ifName, int flags, int scope); + void notifyAddressRemoved(const std::string &addr, const std::string &ifName, int flags, int scope); + void notifyRouteChange( + bool updated, const std::string &route, const std::string &gateway, const std::string &ifName); + + int start(); + void stop(); + + int getSock() + { + return this->socketFd_; + } + + void setEventListener(const std::shared_ptr &reporter) + { + this->reporter_ = reporter; + } + + netlink_handler(int protocol, int pid); + ~netlink_handler(); + +private: + std::shared_ptr reporter_; +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_NETLINK_HANDLER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_listener.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_listener.h index 1b6081693..7ae0bf4f1 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_listener.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_listener.h @@ -1,44 +1,44 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_NETLINK_LISTENER_H__ -#define INCLUDE_NETLINK_LISTENER_H__ - -#include -#include "netlink_socket.h" -#include "netlink_event.h" - -namespace OHOS { -namespace nmd { -class netlink_listener : public netlink_socket { -public: - netlink_listener(int protocol, int pid); - ~netlink_listener(); - - void setOnEventHandler(const std::function)> &handler); - int listen(); - - void stopListen(); - bool getNetlinkListenerState(); - -private: - bool running_ = false; - std::function)> onEventHandler_; - - void onDataAvaliable(int fd, char *buf, ssize_t size); -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_LISTENER_H__ +#define INCLUDE_NETLINK_LISTENER_H__ + +#include +#include "netlink_socket.h" +#include "netlink_event.h" + +namespace OHOS { +namespace nmd { +class netlink_listener : public netlink_socket { +public: + netlink_listener(int protocol, int pid); + ~netlink_listener(); + + void setOnEventHandler(const std::function)> &handler); + int listen(); + + void stopListen(); + bool getNetlinkListenerState(); + +private: + bool running_ = false; + std::function)> onEventHandler_; + + void onDataAvaliable(int fd, char *buf, ssize_t size); +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_NETLINK_LISTENER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_manager.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_manager.h index 97005a030..cf13e14b8 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_manager.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_manager.h @@ -1,72 +1,72 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_NETLINK_MANAGER_H__ -#define INCLUDE_NETLINK_MANAGER_H__ - -#include -#include "event_reporter.h" -#include "netlink_handler.h" -namespace OHOS { -namespace nmd { -namespace listeners { -void defaultOnInterfaceAddressUpdated(const std::string &, const std::string &, int, int); -void defaultOnInterfaceAddressRemoved(const std::string &, const std::string &, int, int); -void defaultOnInterfaceAdded(const std::string &); -void defaultOnInterfaceRemoved(const std::string &); -void defaultOnInterfaceChanged(const std::string &, bool); -void defaultOnInterfaceLinkStateChanged(const std::string &, bool); -void defaultOnRouteChanged(bool, const std::string &, const std::string &, const std::string &); -} // namespace listeners -class netlink_manager { -public: - void start(); - void stop(); - - int getRouteSock() - { - return this->routeHandler_->getSock(); - } - std::shared_ptr getRouteHandler() - { - return this->routeHandler_; - } - - static int getPid() - { - return pid_; - } - static void setPid(int pid) - { - pid_ = pid; - } - static std::shared_ptr getReporter() - { - return reporter_; - } - - explicit netlink_manager(int pid); - ~netlink_manager(); - -private: - static int pid_; - static std::shared_ptr reporter_; - - std::shared_ptr routeHandler_; - void startRouteHandler(); -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_MANAGER_H__ +#define INCLUDE_NETLINK_MANAGER_H__ + +#include +#include "event_reporter.h" +#include "netlink_handler.h" +namespace OHOS { +namespace nmd { +namespace listeners { +void defaultOnInterfaceAddressUpdated(const std::string &, const std::string &, int, int); +void defaultOnInterfaceAddressRemoved(const std::string &, const std::string &, int, int); +void defaultOnInterfaceAdded(const std::string &); +void defaultOnInterfaceRemoved(const std::string &); +void defaultOnInterfaceChanged(const std::string &, bool); +void defaultOnInterfaceLinkStateChanged(const std::string &, bool); +void defaultOnRouteChanged(bool, const std::string &, const std::string &, const std::string &); +} // namespace listeners +class netlink_manager { +public: + void start(); + void stop(); + + int getRouteSock() + { + return this->routeHandler_->getSock(); + } + std::shared_ptr getRouteHandler() + { + return this->routeHandler_; + } + + static int getPid() + { + return pid_; + } + static void setPid(int pid) + { + pid_ = pid; + } + static std::shared_ptr getReporter() + { + return reporter_; + } + + explicit netlink_manager(int pid); + ~netlink_manager(); + +private: + static int pid_; + static std::shared_ptr reporter_; + + std::shared_ptr routeHandler_; + void startRouteHandler(); +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_NETLINK_MANAGER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_socket.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_socket.h index 0ea193466..57cbc8d9d 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_socket.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_socket.h @@ -1,79 +1,79 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_NETLINK_SOCKET_H__ -#define INCLUDE_NETLINK_SOCKET_H__ - -#include -#include -#include -#include -#include -#include - -namespace OHOS { -namespace nmd { -class netlink_socket { -public: - int socketFd_; - int pid_ = 0; - - virtual ~netlink_socket(); - - void setSock(int sock) - { - this->socketFd_ = sock; - } - - int create(int protocol); - int create(int type, int protocol); - int binding(); - - int acceptAndListen(); - - int sendNetlinkMsgToKernel(struct nlmsghdr *msg); - - ssize_t receive(void *buf); - - int shutdown(); - - void setOnDataReceiveHandler(const std::function &handler); - - void setPid(int pid) - { - this->pid_ = pid; - } - -private: - std::function handler_; - struct sockaddr addr_ {}; - /** - * Link layer: RTM_NEWLINK, RTM_DELLINK, RTM_GETLINK, RTM_SETLINK - * Address settings: RTM_NEWADDR, RTM_DELADDR, RTM_GETADDR - * Routing tables: RTM_NEWROUTE, RTM_DELROUTE, RTM_GETROUTE - * Neighbor cache: RTM_NEWNEIGH, RTM_DELNEIGH, RTM_GETNEIGH - * Routing rules: RTM_NEWRULE, RTM_DELRULE, RTM_GETRULE - * Queuing discipline settings: RTM_NEWQDISC, RTM_DELQDISC, RTM_GETQDISC - * Traffic classes used with queues: RTM_NEWTCLASS, RTM_DELTCLASS, RTM_GETTCLASS - * Traffic filters: RTM_NEWTFILTER, RTM_DELTFILTER, RTM_GETTFILTER - * Others: RTM_NEWACTION, RTM_DELACTION, RTM_GETACTION, RTM_NEWPREFIX, RTM_GETPREFIX, RTM_GETMULTICAST, - * RTM_GETANYCAST, RTM_NEWNEIGHTBL, RTM_GETNEIGHTBL, RTM_SETNEIGHTBL - */ - int send(unsigned short action, char *buffer, size_t size, unsigned short rtaType, char *attrBuf, - size_t attrBufLen); -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_SOCKET_H__ +#define INCLUDE_NETLINK_SOCKET_H__ + +#include +#include +#include +#include +#include +#include + +namespace OHOS { +namespace nmd { +class netlink_socket { +public: + int socketFd_; + int pid_ = 0; + + virtual ~netlink_socket(); + + void setSock(int sock) + { + this->socketFd_ = sock; + } + + int create(int protocol); + int create(int type, int protocol); + int binding(); + + int acceptAndListen(); + + int sendNetlinkMsgToKernel(struct nlmsghdr *msg); + + ssize_t receive(void *buf); + + int shutdown(); + + void setOnDataReceiveHandler(const std::function &handler); + + void setPid(int pid) + { + this->pid_ = pid; + } + +private: + std::function handler_; + struct sockaddr addr_ {}; + /** + * Link layer: RTM_NEWLINK, RTM_DELLINK, RTM_GETLINK, RTM_SETLINK + * Address settings: RTM_NEWADDR, RTM_DELADDR, RTM_GETADDR + * Routing tables: RTM_NEWROUTE, RTM_DELROUTE, RTM_GETROUTE + * Neighbor cache: RTM_NEWNEIGH, RTM_DELNEIGH, RTM_GETNEIGH + * Routing rules: RTM_NEWRULE, RTM_DELRULE, RTM_GETRULE + * Queuing discipline settings: RTM_NEWQDISC, RTM_DELQDISC, RTM_GETQDISC + * Traffic classes used with queues: RTM_NEWTCLASS, RTM_DELTCLASS, RTM_GETTCLASS + * Traffic filters: RTM_NEWTFILTER, RTM_DELTFILTER, RTM_GETTFILTER + * Others: RTM_NEWACTION, RTM_DELACTION, RTM_GETACTION, RTM_NEWPREFIX, RTM_GETPREFIX, RTM_GETMULTICAST, + * RTM_GETANYCAST, RTM_NEWNEIGHTBL, RTM_GETNEIGHTBL, RTM_SETNEIGHTBL + */ + int send(unsigned short action, char *buffer, size_t size, unsigned short rtaType, char *attrBuf, + size_t attrBufLen); +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_NETLINK_SOCKET_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/network_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/network_controller.h index e9135a58c..0de0ccb39 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/network_controller.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/network_controller.h @@ -1,64 +1,64 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_NETWORK_CONTROLLER_H__ -#define INCLUDE_NETWORK_CONTROLLER_H__ -#include -#include -#include -#include -#include "nmd_network.h" -namespace OHOS { -namespace nmd { -class network_controller { -public: - network_controller() = default; - ~network_controller(); - - int createPhysicalNetwork(uint16_t netId, Permission permission); - - int destroyNetwork(int netId); - - int setDefaultNetwork(int netId); - - int clearDefaultNetwork(); - - int getDefaultNetwork(); - - int addInterfaceToNetwork(int netId, std::string &interafceName); - - int removeInterfaceFromNetwork(int netId, std::string &interafceName); - - int addRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); - - int removeRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); - - int getFwmarkForNetwork(int netId); - - int setPermissionForNetwork(int netId, Permission permission); - - std::vector getNetworks(); - - nmd::NmdNetwork *getNetwork(int netId); - -private: - int defaultNetId_; - std::map networks_; - std::tuple findNetworkById(int netId); - int getNetworkForInterface(std::string &interfaceName); -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETWORK_CONTROLLER_H__ +#define INCLUDE_NETWORK_CONTROLLER_H__ +#include +#include +#include +#include +#include "nmd_network.h" +namespace OHOS { +namespace nmd { +class network_controller { +public: + network_controller() = default; + ~network_controller(); + + int createPhysicalNetwork(uint16_t netId, Permission permission); + + int destroyNetwork(int netId); + + int setDefaultNetwork(int netId); + + int clearDefaultNetwork(); + + int getDefaultNetwork(); + + int addInterfaceToNetwork(int netId, std::string &interafceName); + + int removeInterfaceFromNetwork(int netId, std::string &interafceName); + + int addRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); + + int removeRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); + + int getFwmarkForNetwork(int netId); + + int setPermissionForNetwork(int netId, Permission permission); + + std::vector getNetworks(); + + nmd::NmdNetwork *getNetwork(int netId); + +private: + int defaultNetId_; + std::map networks_; + std::tuple findNetworkById(int netId); + int getNetworkForInterface(std::string &interfaceName); +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_NETWORK_CONTROLLER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/nmd_network.h b/prebuilts/librarys/netd/include/net_mgr_native/include/nmd_network.h index 81acdb26e..be83ce589 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/nmd_network.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/nmd_network.h @@ -1,73 +1,73 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_NMD_NETWORK_H__ -#define INCLUDE_NMD_NETWORK_H__ - -#include -#include -namespace OHOS { -namespace nmd { -typedef enum Permission { - PERMISSION_NONE = 0x0, - PERMISSION_NETWORK = 0x1, - PERMISSION_SYSTEM = 0x3, -} NetworkPermission; - -class NmdNetwork { -public: - NmdNetwork(uint16_t netId, NetworkPermission permission); - - void asDefault(); - void removeAsDefault(); - - int addInterface(std::string &interfaceName); - int removeInterface(std::string &interfaceName); - int clearInterfaces(); - - bool hasInterface(std::string &interfaceName); - std::set getAllInterface() - { - return this->interfaces_; - } - - uint16_t getNetId() - { - return this->netId_; - } - NetworkPermission getPermission() - { - return this->permission_; - } - - bool isDefault() - { - return this->isDefault_; - } - - virtual ~NmdNetwork(); - -private: - uint16_t netId_; - - bool isDefault_ = false; - - NetworkPermission permission_; - - std::set interfaces_; -}; -} // namespace nmd -} // namespace OHOS -#endif // !INCLUDE_NMD_NETWORK_H__ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NMD_NETWORK_H__ +#define INCLUDE_NMD_NETWORK_H__ + +#include +#include +namespace OHOS { +namespace nmd { +typedef enum Permission { + PERMISSION_NONE = 0x0, + PERMISSION_NETWORK = 0x1, + PERMISSION_SYSTEM = 0x3, +} NetworkPermission; + +class NmdNetwork { +public: + NmdNetwork(uint16_t netId, NetworkPermission permission); + + void asDefault(); + void removeAsDefault(); + + int addInterface(std::string &interfaceName); + int removeInterface(std::string &interfaceName); + int clearInterfaces(); + + bool hasInterface(std::string &interfaceName); + std::set getAllInterface() + { + return this->interfaces_; + } + + uint16_t getNetId() + { + return this->netId_; + } + NetworkPermission getPermission() + { + return this->permission_; + } + + bool isDefault() + { + return this->isDefault_; + } + + virtual ~NmdNetwork(); + +private: + uint16_t netId_; + + bool isDefault_ = false; + + NetworkPermission permission_; + + std::set interfaces_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NMD_NETWORK_H__ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/route_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/route_controller.h index 654a07525..22d3ddb7c 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/route_controller.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/route_controller.h @@ -1,62 +1,62 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_ROUTE_CONTROLLER_H__ -#define INCLUDE_ROUTE_CONTROLLER_H__ - -#include -#include -#include "nmd_network.h" - -namespace OHOS { -namespace nmd { -typedef struct _inet_addr { - int family; - int bitlen; - int prefixlen; - uint8_t data[sizeof(struct in6_addr)]; -} _inet_addr; - -class route_controller { -public: - route_controller(); - ~route_controller(); - - static int createChildChains(const char *table, const char *parentChain, const char *childChain); - static int addInterfaceToDefaultNetwork(const char *interface, NetworkPermission permission); - static int removeInterfaceFromDefaultNetwork(const char *interface, NetworkPermission permission); - static int addInterfaceToPhysicalNetwork(uint16_t netId, const char *interface, NetworkPermission permission); - - static int removeInterfaceFromPhysicalNetwork( - uint16_t netId, const char *interfaceName, NetworkPermission permission); - - static int addRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); - - static int removeRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); - - static int read_addr(const char *addr, _inet_addr *res); - static int read_addr_gw(const char *addr, _inet_addr *res); - -private: - static int executeIptablesRestore(std::string command); - static void updateTableNamesFile(); - static std::map interfaceToTable_; - static uint32_t getRouteTableForInterface(const char *interfaceName); - - void modifyIpRule(std::string interface, NetworkPermission permission); -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_ROUTE_CONTROLLER_H__ +#define INCLUDE_ROUTE_CONTROLLER_H__ + +#include +#include +#include "nmd_network.h" + +namespace OHOS { +namespace nmd { +typedef struct _inet_addr { + int family; + int bitlen; + int prefixlen; + uint8_t data[sizeof(struct in6_addr)]; +} _inet_addr; + +class route_controller { +public: + route_controller(); + ~route_controller(); + + static int createChildChains(const char *table, const char *parentChain, const char *childChain); + static int addInterfaceToDefaultNetwork(const char *interface, NetworkPermission permission); + static int removeInterfaceFromDefaultNetwork(const char *interface, NetworkPermission permission); + static int addInterfaceToPhysicalNetwork(uint16_t netId, const char *interface, NetworkPermission permission); + + static int removeInterfaceFromPhysicalNetwork( + uint16_t netId, const char *interfaceName, NetworkPermission permission); + + static int addRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); + + static int removeRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); + + static int read_addr(const char *addr, _inet_addr *res); + static int read_addr_gw(const char *addr, _inet_addr *res); + +private: + static int executeIptablesRestore(std::string command); + static void updateTableNamesFile(); + static std::map interfaceToTable_; + static uint32_t getRouteTableForInterface(const char *interfaceName); + + void modifyIpRule(std::string interface, NetworkPermission permission); +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_ROUTE_CONTROLLER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/traffic_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/traffic_controller.h index 121e428a1..fa7ab5f77 100755 --- a/prebuilts/librarys/netd/include/net_mgr_native/include/traffic_controller.h +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/traffic_controller.h @@ -1,89 +1,89 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef INCLUDE_TRAFFIC_CONTROLLER_H__ -#define INCLUDE_TRAFFIC_CONTROLLER_H__ -#include -#include -#include -namespace OHOS { -namespace nmd { -typedef struct arp_cache_information { - std::string ipAddr; - std::string macAddr; - std::string dev; - std::string state; - - friend std::ostream &operator<<(std::ostream &os, const arp_cache_information &information) - { - os << "ipAddr: " << information.ipAddr << " macAddr: " << information.macAddr - << " dev: " << information.dev << " state: " << information.state; - return os; - } -} arp_cache_information; - -typedef struct tether_traffic_account { - std::string bytes; - std::string sourceIp; - std::string destinationIp; - - friend std::ostream &operator<<(std::ostream &os, const tether_traffic_account &account) - { - os << "bytes: " << account.bytes << " sourceIp: " << account.sourceIp - << " destinationIp: " << account.destinationIp; - return os; - } -} tether_traffic_account; - -typedef struct tether_stats_parcel { - std::string iface; - unsigned int ifIndex = 0; - long rxBytes; - long rxPackets; - long txBytes; - long txPackets; - - friend std::ostream &operator<<(std::ostream &os, const tether_stats_parcel &parcel) - { - os << "iface: " << parcel.iface << "ifIndex: " << parcel.ifIndex << "rxBytes: " << parcel.rxBytes - << "rxPackets: " << parcel.rxPackets << "txBytes: " << parcel.txBytes - << "txPackets: " << parcel.txPackets; - return os; - } -} tether_stats_parcel; - -typedef tether_stats_parcel traffic_stats_parcel; - -class traffic_controller { -public: - traffic_controller(); - ~traffic_controller(); - bool isTetherEnable(); - static nmd::traffic_stats_parcel getInterfaceTraffic(const std::string &ifName); - static long getAllRxTraffic(); - static long getAllTxTraffic(); - static std::vector getTetherClientInfo(); - static void startTrafficTether(); - static long getTxTetherTraffic(); - static long getRxTetherTraffic(); - static long getRxUidTraffic(int uid); - static long getTxUidTraffic(int uid); - static long getCellularRxTraffic(); - static long getCellularTxTraffic(); - static void traffic_controller_log(); - static void execIptablesRuleMethod(std::string &cmd); -}; -} // namespace nmd -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef INCLUDE_TRAFFIC_CONTROLLER_H__ +#define INCLUDE_TRAFFIC_CONTROLLER_H__ +#include +#include +#include +namespace OHOS { +namespace nmd { +typedef struct arp_cache_information { + std::string ipAddr; + std::string macAddr; + std::string dev; + std::string state; + + friend std::ostream &operator<<(std::ostream &os, const arp_cache_information &information) + { + os << "ipAddr: " << information.ipAddr << " macAddr: " << information.macAddr + << " dev: " << information.dev << " state: " << information.state; + return os; + } +} arp_cache_information; + +typedef struct tether_traffic_account { + std::string bytes; + std::string sourceIp; + std::string destinationIp; + + friend std::ostream &operator<<(std::ostream &os, const tether_traffic_account &account) + { + os << "bytes: " << account.bytes << " sourceIp: " << account.sourceIp + << " destinationIp: " << account.destinationIp; + return os; + } +} tether_traffic_account; + +typedef struct tether_stats_parcel { + std::string iface; + unsigned int ifIndex = 0; + long rxBytes; + long rxPackets; + long txBytes; + long txPackets; + + friend std::ostream &operator<<(std::ostream &os, const tether_stats_parcel &parcel) + { + os << "iface: " << parcel.iface << "ifIndex: " << parcel.ifIndex << "rxBytes: " << parcel.rxBytes + << "rxPackets: " << parcel.rxPackets << "txBytes: " << parcel.txBytes + << "txPackets: " << parcel.txPackets; + return os; + } +} tether_stats_parcel; + +typedef tether_stats_parcel traffic_stats_parcel; + +class traffic_controller { +public: + traffic_controller(); + ~traffic_controller(); + bool isTetherEnable(); + static nmd::traffic_stats_parcel getInterfaceTraffic(const std::string &ifName); + static long getAllRxTraffic(); + static long getAllTxTraffic(); + static std::vector getTetherClientInfo(); + static void startTrafficTether(); + static long getTxTetherTraffic(); + static long getRxTetherTraffic(); + static long getRxUidTraffic(int uid); + static long getTxUidTraffic(int uid); + static long getCellularRxTraffic(); + static long getCellularTxTraffic(); + static void traffic_controller_log(); + static void execIptablesRuleMethod(std::string &cmd); +}; +} // namespace nmd +} // namespace OHOS #endif // !INCLUDE_TRAFFIC_CONTROLLER_H__ \ No newline at end of file diff --git a/services/common/BUILD.gn b/services/common/BUILD.gn index 9ff9a5f16..410593489 100644 --- a/services/common/BUILD.gn +++ b/services/common/BUILD.gn @@ -35,13 +35,13 @@ ohos_shared_library("net_service_common") { "$INNERKITS_ROOT/netconnclient:net_conn_parcel", "$NETDCONTROLLER_ROOT_DIR:netd_controller", "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "//utils/native/base:utils", ] external_deps = [ "ability_runtime:want", "ces_standard:cesfwk_innerkits", "ipc:ipc_core", - "utils_base:utils", ] defines = [ diff --git a/services/common/include/route_utils.h b/services/common/include/route_utils.h index 25e787fbf..194cf0766 100644 --- a/services/common/include/route_utils.h +++ b/services/common/include/route_utils.h @@ -84,7 +84,7 @@ public: * * @param netId * @param newnl route info will add or update to route table - * @oldnl oldnl route info will remove from route table + * @param oldnl route info will remove from route table * * @return 1, route changed between oldnl and newnl */ diff --git a/services/dnsresolvermanager/BUILD.gn b/services/dnsresolvermanager/BUILD.gn index 9bd9a64f7..f7a1f2d8d 100644 --- a/services/dnsresolvermanager/BUILD.gn +++ b/services/dnsresolvermanager/BUILD.gn @@ -38,6 +38,7 @@ ohos_shared_library("dns_resolver_manager") { "$NETCONNMANAGER_COMMON_DIR:net_service_common", "$NETDCONTROLLER_ROOT_DIR:netd_controller", "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "//utils/native/base:utils", ] external_deps = [ @@ -46,7 +47,6 @@ ohos_shared_library("dns_resolver_manager") { "ipc:ipc_core", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", - "utils_base:utils", ] defines = [ diff --git a/services/netconnmanager/BUILD.gn b/services/netconnmanager/BUILD.gn index c81c0523f..2c49c768f 100644 --- a/services/netconnmanager/BUILD.gn +++ b/services/netconnmanager/BUILD.gn @@ -49,6 +49,7 @@ ohos_shared_library("net_conn_manager") { "$NETDCONTROLLER_ROOT_DIR:netd_controller", "$NETMANAGER_BASE_ROOT/utils:net_manager_common", "//third_party/curl:curl", + "//utils/native/base:utils", ] external_deps = [ @@ -58,7 +59,6 @@ ohos_shared_library("net_conn_manager") { "ipc:ipc_core", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", - "utils_base:utils", ] defines = [ diff --git a/services/netconnmanager/include/net_conn_service.h b/services/netconnmanager/include/net_conn_service.h index 9f80c6176..943c2f688 100644 --- a/services/netconnmanager/include/net_conn_service.h +++ b/services/netconnmanager/include/net_conn_service.h @@ -34,6 +34,7 @@ namespace OHOS { namespace NetManagerStandard { +constexpr uint32_t MAX_REQUEST_NUM = 200; class NetConnService : public SystemAbility, public NetConnServiceStub, public std::enable_shared_from_this { @@ -218,6 +219,7 @@ private: void CreateDefaultRequest(); int32_t RegUnRegNetDetectionCallback(int32_t netId, const sptr &callback, bool isReg); int32_t GenerateNetId(); + bool FindSameCallback(const sptr &callback, uint32_t &reqId); private: enum ServiceRunningState { diff --git a/services/netconnmanager/include/net_conn_types.h b/services/netconnmanager/include/net_conn_types.h index edba809f0..b4f29c1c9 100755 --- a/services/netconnmanager/include/net_conn_types.h +++ b/services/netconnmanager/include/net_conn_types.h @@ -42,16 +42,19 @@ enum ResultCode { ERR_NET_TYPE_NOT_FOUND = (-18), ERR_NO_ANY_NET_TYPE = (-19), ERR_NO_REGISTERED = (-20), - ERR_NET_HOST_EMPTY = (-21), - ERR_SERVICE_NO_REQUEST = (-22), - ERR_NO_ADDRESS = (-23), - ERR_NET_FIND_BESTNETWORK_FOR_REQUEST = (-24), - ERR_NET_NOT_FIND_BESTNETWORK_FOR_REQUEST = (-25), - ERR_NET_NOT_FIND_REQUEST_ID = (-26), - ERR_NET_NOT_FIND_NETID = (-27), - ERR_VPN = (-28), - ERR_NET_DEFAULTNET_NOT_EXIST = (-29), - ERR_NET_NO_RESTRICT_BACKGROUND = (-30) + ERR_NET_HOST_EMPTY = (-21), + ERR_SERVICE_NO_REQUEST = (-22), + ERR_NO_ADDRESS = (-23), + ERR_NET_FIND_BESTNETWORK_FOR_REQUEST = (-24), + ERR_NET_NOT_FIND_BESTNETWORK_FOR_REQUEST = (-25), + ERR_NET_NOT_FIND_REQUEST_ID = (-26), + ERR_NET_NOT_FIND_NETID = (-27), + ERR_VPN = (-28), + ERR_NET_DEFAULTNET_NOT_EXIST = (-29), + ERR_NET_NO_RESTRICT_BACKGROUND = (-30), + ERR_NET_OVER_MAX_REQUEST_NUM = (-31), + ERR_REGISTER_THE_SAME_CALLBACK = (-32), + ERR_UNREGISTER_CALLBACK_NOT_FOUND = (-33) }; enum NetMonitorResponseCode { diff --git a/services/netconnmanager/include/net_monitor.h b/services/netconnmanager/include/net_monitor.h index 789dcafaa..b083e8197 100755 --- a/services/netconnmanager/include/net_monitor.h +++ b/services/netconnmanager/include/net_monitor.h @@ -96,7 +96,7 @@ private: std::condition_variable conditionTimeout_; bool isStopNetMonitor_; bool isExitNetMonitorThread_; - std::thread *netMonitorThread_; + std::unique_ptr netMonitorThread_; NetDetectionStateHandler netDetectionStatus_; NetDetectionStatus lastDetectionState_; std::string ifaceName_; diff --git a/services/netconnmanager/include/net_score.h b/services/netconnmanager/include/net_score.h index 6d73670ff..a96c2e4f8 100644 --- a/services/netconnmanager/include/net_score.h +++ b/services/netconnmanager/include/net_score.h @@ -32,7 +32,8 @@ enum class NetTypeScoreValue : int32_t { CELLULAR_VALUE = 6 * NET_TYPE_SCORE_INTERVAL, WIFI_VALUE = 7 * NET_TYPE_SCORE_INTERVAL, ETHERNET_VALUE = 8 * NET_TYPE_SCORE_INTERVAL, - VPN_VALUE = 9 * NET_TYPE_SCORE_INTERVAL + VPN_VALUE = 9 * NET_TYPE_SCORE_INTERVAL, + WIFI_AWARE_VALUE = 10 * NET_TYPE_SCORE_INTERVAL }; class NetScore { @@ -47,7 +48,11 @@ private: private: NetTypeScore netTypeScore_ = { {BEARER_CELLULAR, static_cast(NetTypeScoreValue::CELLULAR_VALUE)}, - {BEARER_ETHERNET, static_cast(NetTypeScoreValue::ETHERNET_VALUE)}}; + {BEARER_WIFI, static_cast(NetTypeScoreValue::WIFI_VALUE)}, + {BEARER_BLUETOOTH, static_cast(NetTypeScoreValue::BLUETOOTH_VALUE)}, + {BEARER_ETHERNET, static_cast(NetTypeScoreValue::ETHERNET_VALUE)}, + {BEARER_VPN, static_cast(NetTypeScoreValue::VPN_VALUE)}, + {BEARER_WIFI_AWARE, static_cast(NetTypeScoreValue::WIFI_AWARE_VALUE)}}; }; } // namespace NetManagerStandard } // namespace OHOS diff --git a/services/netconnmanager/include/net_supplier.h b/services/netconnmanager/include/net_supplier.h index 285d53898..0fc03d401 100644 --- a/services/netconnmanager/include/net_supplier.h +++ b/services/netconnmanager/include/net_supplier.h @@ -90,7 +90,7 @@ public: void AddRequsetIdToList(uint32_t requestId); int32_t SelectAsBestNetwork(uint32_t reqId); void ReceiveBestScore(uint32_t reqId, int32_t bestScore); - int32_t CancleRequest(uint32_t reqId); + int32_t CancelRequest(uint32_t reqId); void RemoveBestRequest(uint32_t reqId); std::set& GetBestRequestList(); void SetDefault(); diff --git a/services/netconnmanager/src/http_request.cpp b/services/netconnmanager/src/http_request.cpp index c16d57776..37ebd2bf0 100755 --- a/services/netconnmanager/src/http_request.cpp +++ b/services/netconnmanager/src/http_request.cpp @@ -49,7 +49,6 @@ void HttpRequest::SetIfaceName(const std::string &ifaceName) int32_t HttpRequest::HttpGetHeader(const std::string &strUrl, std::string &strHeader) { - NETMGR_LOG_I("Enter HttpGetHeader"); return HttpRequestHeaderExec(strUrl, strHeader); } @@ -116,7 +115,7 @@ int32_t HttpRequest::HttpRequestExec( int32_t HttpRequest::HttpRequestHeaderExec(const std::string &strUrl, std::string &strHeader) { - NETMGR_LOG_D("Enter HttpRequestHeaderExec, ifaceName:[%{public}s]", ifaceName_.c_str()); + NETMGR_LOG_D("ifaceName:[%{public}s]", ifaceName_.c_str()); /* Check whether the URL is valid. */ if (strUrl.empty() || strUrl.length() > URL_SIZE) { NETMGR_LOG_E("URL error!"); @@ -234,7 +233,6 @@ int32_t HttpRequest::SetCurlOptCommon(const std::unique_ptr &cu CURLcode errCode = CURLE_OK; if (!ifaceName_.empty()) { - NETMGR_LOG_D("CURLOPT_INTERFACE:[%{public}s]!", ifaceName_.c_str()); errCode = curl_easy_setopt(curl.get(), CURLOPT_INTERFACE, ifaceName_.c_str()); if (errCode != CURLE_OK) { NETMGR_LOG_E("CURLOPT_INTERFACE failed:%d!", errCode); diff --git a/services/netconnmanager/src/net_conn_service.cpp b/services/netconnmanager/src/net_conn_service.cpp index 463216031..ec4d8613f 100755 --- a/services/netconnmanager/src/net_conn_service.cpp +++ b/services/netconnmanager/src/net_conn_service.cpp @@ -228,10 +228,18 @@ int32_t NetConnService::RegisterNetConnCallback(const sptr &ca int32_t NetConnService::RegisterNetConnCallback( const sptr &netSpecifier, const sptr &callback, const uint32_t &timeoutMS) { + if (netActivates_.size() >= MAX_REQUEST_NUM) { + NETMGR_LOG_E("Over the max request number"); + return ERR_NET_OVER_MAX_REQUEST_NUM; + } if (netSpecifier == nullptr || callback == nullptr) { NETMGR_LOG_E("The parameter of netSpecifier or callback is null"); return ERR_SERVICE_NULL_PTR; } + uint32_t reqId = 0; + if (FindSameCallback(callback, reqId)) { + return ERR_REGISTER_THE_SAME_CALLBACK; + } return ActivateNetwork(netSpecifier, callback, timeoutMS); } @@ -242,6 +250,16 @@ int32_t NetConnService::UnregisterNetConnCallback(const sptr & NETMGR_LOG_E("callback is null"); return ERR_SERVICE_NULL_PTR; } + uint32_t reqId = 0; + if (!FindSameCallback(callback, reqId)) { + return ERR_UNREGISTER_CALLBACK_NOT_FOUND; + } + deleteNetActivates_.clear(); + return DeactivateNetwork(reqId); +} + +bool NetConnService::FindSameCallback(const sptr &callback, uint32_t &reqId) +{ NET_ACTIVATE_MAP::iterator iterActive; for (iterActive = netActivates_.begin(); iterActive != netActivates_.end(); ++iterActive) { if (!iterActive->second) { @@ -252,12 +270,11 @@ int32_t NetConnService::UnregisterNetConnCallback(const sptr & continue; } if (callback->AsObject().GetRefPtr() == saveCallback->AsObject().GetRefPtr()) { - DeactivateNetwork(iterActive->first); - return ERR_NONE; + reqId = iterActive->first; + return true; } } - deleteNetActivates_.clear(); - return ERR_NET_TYPE_NOT_FOUND; + return false; } int32_t NetConnService::UpdateNetStateForTest(const sptr &netSpecifier, int32_t netState) @@ -470,13 +487,13 @@ int32_t NetConnService::DeactivateNetwork(uint32_t reqId) if (pNetActivate) { sptr pNetService = pNetActivate->GetServiceSupply(); if (pNetService) { - pNetService->CancleRequest(reqId); + pNetService->CancelRequest(reqId); } } NET_SUPPLIER_MAP::iterator iterSupplier; for (iterSupplier = netSuppliers_.begin(); iterSupplier != netSuppliers_.end(); ++iterSupplier) { - iterSupplier->second->CancleRequest(reqId); + iterSupplier->second->CancelRequest(reqId); } deleteNetActivates_.insert(std::pair>(reqId, pNetActivate)); netActivates_.erase(reqId); diff --git a/services/netconnmanager/src/net_monitor.cpp b/services/netconnmanager/src/net_monitor.cpp index cdaef1e83..d2df37b57 100755 --- a/services/netconnmanager/src/net_monitor.cpp +++ b/services/netconnmanager/src/net_monitor.cpp @@ -20,7 +20,6 @@ namespace OHOS { namespace NetManagerStandard { NetMonitor::NetMonitor(NetDetectionStateHandler handle) { - netMonitorThread_ = nullptr; isExitNetMonitorThread_ = false; isStopNetMonitor_ = true; isExitNetMonitorThread_ = false; @@ -43,7 +42,6 @@ bool NetMonitor::HttpDetection() int32_t ret = httpRequest.HttpGetHeader(httpMsg, httpHeader); std::string urlRedirect; if (ret != 0 || httpHeader.empty()) { - NETMGR_LOG_E("The network is abnormal or Response code returned by httpRequest is empty!"); netDetectionStatus_(NetDetectionStatus::INVALID_DETECTION_STATE, urlRedirect); lastDetectionState_ = INVALID_DETECTION_STATE; return true; @@ -58,10 +56,8 @@ bool NetMonitor::HttpDetection() netDetectionStatus_(NetDetectionStatus::CAPTIVE_PORTAL_STATE, urlRedirect); } lastDetectionState_ = CAPTIVE_PORTAL_STATE; - NETMGR_LOG_D("This network is portal AP, need certification!"); isNotPortal = false; } else if (statusCode == NO_CONTENT) { - NETMGR_LOG_D("This network is normal!"); netDetectionStatus_(NetDetectionStatus::VERIFICATION_STATE, urlRedirect); lastDetectionState_ = VERIFICATION_STATE; isNotPortal = true; @@ -70,10 +66,8 @@ bool NetMonitor::HttpDetection() netDetectionStatus_(NetDetectionStatus::CAPTIVE_PORTAL_STATE, urlRedirect); } lastDetectionState_ = CAPTIVE_PORTAL_STATE; - NETMGR_LOG_D("This network is portal AP, need certification!"); isNotPortal = false; } else { - NETMGR_LOG_D("This network can't online!"); netDetectionStatus_(NetDetectionStatus::INVALID_DETECTION_STATE, urlRedirect); lastDetectionState_ = INVALID_DETECTION_STATE; isNotPortal = true; @@ -99,20 +93,15 @@ void NetMonitor::RunNetMonitorThreadFunc() } HttpDetection(); if (!isExitNetMonitorThread_) { - NETMGR_LOG_D("conditionTimeout_ wait_for."); std::unique_lock lock(mutex_); - if (conditionTimeout_.wait_for(lock, std::chrono::milliseconds(timeoutMs)) == std::cv_status::timeout) { - NETMGR_LOG_D("conditionTimeout_ timeout."); - } else { - NETMGR_LOG_D("for SignalNetMonitor, wakeup!"); - } + conditionTimeout_.wait_for(lock, std::chrono::milliseconds(timeoutMs)); } } } ResultCode NetMonitor::InitNetMonitorThread() { - netMonitorThread_ = new (std::nothrow) std::thread(&NetMonitor::RunNetMonitorThreadFunc, this); + netMonitorThread_ = std::make_unique(&NetMonitor::RunNetMonitorThreadFunc, this); if (netMonitorThread_ == nullptr) { NETMGR_LOG_E("Start NetMonitor thread failed!"); return ResultCode::ERR_NET_MONITOR_OPT_FAILED; @@ -141,7 +130,7 @@ void NetMonitor::SignalNetMonitorThread(const std::string &ifaceName) void NetMonitor::ExitNetMonitorThread() { - NETMGR_LOG_D("Enter NetMonitor::ExitNetMonitorThread"); + NETMGR_LOG_D("Enter ExitNetMonitorThread"); { std::unique_lock lock(mutex_); isStopNetMonitor_ = false; @@ -152,8 +141,7 @@ void NetMonitor::ExitNetMonitorThread() if (netMonitorThread_ != nullptr) { netMonitorThread_->join(); - delete netMonitorThread_; - netMonitorThread_ = nullptr; + NETMGR_LOG_D("ExitNetMonitorThread OK"); } } diff --git a/services/netconnmanager/src/net_supplier.cpp b/services/netconnmanager/src/net_supplier.cpp index 6c3e6858f..2d8461b11 100644 --- a/services/netconnmanager/src/net_supplier.cpp +++ b/services/netconnmanager/src/net_supplier.cpp @@ -351,7 +351,7 @@ void NetSupplier::ReceiveBestScore(uint32_t reqId, int32_t bestScore) return; } -int32_t NetSupplier::CancleRequest(uint32_t reqId) +int32_t NetSupplier::CancelRequest(uint32_t reqId) { std::set::iterator iter = requestList_.find(reqId); if (iter == requestList_.end()) { diff --git a/services/netdcontroller/BUILD.gn b/services/netdcontroller/BUILD.gn index b87858909..b4eaba304 100644 --- a/services/netdcontroller/BUILD.gn +++ b/services/netdcontroller/BUILD.gn @@ -37,17 +37,16 @@ ohos_shared_library("netd_controller") { deps = [ "$NETMANAGER_BASE_ROOT/services/netmanagernative:netd_native_manager", "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "//utils/native/base:utils", ] external_deps = [ - "ability_runtime:app_manager", "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ipc:ipc_core", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", - "utils_base:utils", ] defines = [ diff --git a/services/netdcontroller/src/netd_controller.cpp b/services/netdcontroller/src/netd_controller.cpp index efa21482e..42ccec1ae 100755 --- a/services/netdcontroller/src/netd_controller.cpp +++ b/services/netdcontroller/src/netd_controller.cpp @@ -380,7 +380,7 @@ int64_t NetdController::GetIfaceRxPackets(const std::string &interfaceName) NETMGR_LOG_E("netdService_ is null"); return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; } - return 0; + return netdService_->GetIfaceRxPackets(interfaceName); } int64_t NetdController::GetIfaceTxPackets(const std::string &interfaceName) @@ -390,7 +390,7 @@ int64_t NetdController::GetIfaceTxPackets(const std::string &interfaceName) NETMGR_LOG_E("netdService_ is null"); return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; } - return 0; + return netdService_->GetIfaceTxPackets(interfaceName); } int32_t NetdController::SetDefaultNetWork(int32_t netId) diff --git a/services/netmanagernative/BUILD.gn b/services/netmanagernative/BUILD.gn index 1fa9cc2a4..dcdc61ea6 100644 --- a/services/netmanagernative/BUILD.gn +++ b/services/netmanagernative/BUILD.gn @@ -35,11 +35,13 @@ ohos_shared_library("netd_native_manager") { "$NETMANAGER_PREBUILTS_DIR/librarys/netd/include/common/include", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + "utils/native/base/include", ] deps = [ "$NETMANAGER_PREBUILTS_DIR/librarys/netd:libnet_manager_native", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", + "//utils/native/base:utils", ] external_deps = [ @@ -49,7 +51,6 @@ ohos_shared_library("netd_native_manager") { "ipc:ipc_core", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", - "utils_base:utils", ] defines = [ diff --git a/services/netmanagernative/src/netd_native_service_stub.cpp b/services/netmanagernative/src/netd_native_service_stub.cpp index 617c49e1d..036336f9d 100644 --- a/services/netmanagernative/src/netd_native_service_stub.cpp +++ b/services/netmanagernative/src/netd_native_service_stub.cpp @@ -14,7 +14,7 @@ */ #include -#include +#include #include "netnative_log_wrapper.h" #include "netd_native_service_stub.h" diff --git a/services/netpolicymanager/BUILD.gn b/services/netpolicymanager/BUILD.gn index 3c11616ac..a21f20883 100644 --- a/services/netpolicymanager/BUILD.gn +++ b/services/netpolicymanager/BUILD.gn @@ -40,6 +40,7 @@ ohos_shared_library("net_policy_manager") { "$NETCONNMANAGER_COMMON_DIR:net_service_common", "$NETMANAGER_BASE_ROOT/utils:net_manager_common", "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", ] external_deps = [ @@ -49,7 +50,6 @@ ohos_shared_library("net_policy_manager") { "netmanager_base:net_stats_manager_if", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", - "utils_base:utils", ] defines = [ diff --git a/services/netpolicymanager/include/net_policy_callback.h b/services/netpolicymanager/include/net_policy_callback.h index 838c76e58..040d40032 100755 --- a/services/netpolicymanager/include/net_policy_callback.h +++ b/services/netpolicymanager/include/net_policy_callback.h @@ -30,7 +30,7 @@ public: void UnregisterNetPolicyCallback(const sptr &callback); int32_t NotifyNetUidPolicyChanged(uint32_t uid, NetUidPolicy policy); int32_t NotifyNetCellularPolicyChanged(const std::vector &cellularPolicies); - int32_t NotifyNetStrategySwitch(int32_t slotId, bool enable); + int32_t NotifyNetStrategySwitch(const std::string &simId, bool enable); int32_t NotifyNetBackgroundPolicyChanged(bool isBackgroundPolicyAllow); private: diff --git a/services/netpolicymanager/include/net_policy_define.h b/services/netpolicymanager/include/net_policy_define.h index fbfa6a32c..bbf4862a1 100755 --- a/services/netpolicymanager/include/net_policy_define.h +++ b/services/netpolicymanager/include/net_policy_define.h @@ -26,6 +26,7 @@ constexpr int16_t DAY_ONE = 1; constexpr int16_t DAY_THIRTY_ONE = 31; constexpr int16_t LIMIT_ACTION_ONE = 1; constexpr int16_t LIMIT_ACTION_THREE = 3; +constexpr int16_t LIMIT_CALLBACK_NUM = 200; const std::string POLICY_QUOTA_MONTH_U = "M"; const std::string POLICY_QUOTA_MONTH_L = "m"; const std::string POLICY_FILE_NAME = "/data/system/net_policy.json"; @@ -38,7 +39,7 @@ const std::string CONFIG_BACKGROUND_POLICY = "backgroundPolicy"; const std::string CONFIG_BACKGROUND_POLICY_STATUS = "status"; const std::string CONFIG_QUOTA_POLICY = "quotaPolicy"; const std::string CONFIG_QUOTA_POLICY_NETTYPE = "netType"; -const std::string CONFIG_QUOTA_POLICY_SUBSCRIBERID = "slotId"; +const std::string CONFIG_QUOTA_POLICY_SUBSCRIBERID = "simId"; const std::string CONFIG_QUOTA_POLICY_PERIODSTARTTIME = "periodStartTime"; const std::string CONFIG_QUOTA_POLICY_PERIODDURATION = "periodDuration"; const std::string CONFIG_QUOTA_POLICY_WARNINGBYTES = "warningBytes"; @@ -47,7 +48,7 @@ const std::string CONFIG_QUOTA_POLICY_LASTLIMITSNOOZE = "lastLimitSnooze"; const std::string CONFIG_QUOTA_POLICY_METERED = "metered"; const std::string CONFIG_QUOTA_POLICY_SOURCE = "source"; const std::string CONFIG_CELLULAR_POLICY = "cellularPolicy"; -const std::string CONFIG_CELLULAR_POLICY_SUBSCRIBERID = "slotId"; +const std::string CONFIG_CELLULAR_POLICY_SUBSCRIBERID = "simId"; const std::string CONFIG_CELLULAR_POLICY_PERIODSTARTTIME = "periodStartTime"; const std::string CONFIG_CELLULAR_POLICY_PERIODDURATION = "periodDuration"; const std::string CONFIG_CELLULAR_POLICY_TITLE = "title"; @@ -59,7 +60,7 @@ const std::string CONFIG_CELLULAR_POLICY_USEDTIMEDURATION = "usedTimeDuration"; const std::string CONFIG_CELLULAR_POLICY_POSSESSOR = "possessor"; const std::string BACKGROUND_POLICY_ALLOW = "allow"; const std::string BACKGROUND_POLICY_REJECT = "reject"; -const std::string IDENT_PREFIX = "slotId"; +const std::string IDENT_PREFIX = "usb0"; struct UidPolicy { std::string uid; @@ -68,7 +69,7 @@ struct UidPolicy { struct NetPolicyQuota { std::string netType; - std::string slotId; + std::string simId; std::string periodStartTime; std::string periodDuration; std::string warningBytes; @@ -79,7 +80,7 @@ struct NetPolicyQuota { }; struct NetPolicyCellular { - std::string slotId; + std::string simId; std::string periodStartTime; std::string periodDuration; std::string title; diff --git a/services/netpolicymanager/include/net_policy_file.h b/services/netpolicymanager/include/net_policy_file.h index 1a19b2db9..8fc08f3e2 100755 --- a/services/netpolicymanager/include/net_policy_file.h +++ b/services/netpolicymanager/include/net_policy_file.h @@ -58,9 +58,10 @@ public: NetUidPolicy GetPolicyByUid(uint32_t uid); bool GetUidsByPolicy(NetUidPolicy policy, std::vector &uids); NetPolicyResultCode GetNetQuotaPolicies(std::vector "aPolicies); - NetPolicyResultCode GetNetQuotaPolicy(int8_t netType, int32_t slotId, NetPolicyQuotaPolicy "aPolicy); + NetPolicyResultCode GetNetQuotaPolicy(int8_t netType, const std::string &simId, + NetPolicyQuotaPolicy "aPolicy); NetPolicyResultCode GetCellularPolicies(std::vector &cellularPolicies); - NetPolicyResultCode SetFactoryPolicy(const std::string &slotId); + NetPolicyResultCode SetFactoryPolicy(const std::string &simId); NetPolicyResultCode SetBackgroundPolicy(bool backgroundPolicy); bool GetBackgroundPolicy(); bool IsInterfaceMetered(const std::string &ifaceName); diff --git a/services/netpolicymanager/include/net_policy_service.h b/services/netpolicymanager/include/net_policy_service.h index 0a44ded86..00b2778b8 100755 --- a/services/netpolicymanager/include/net_policy_service.h +++ b/services/netpolicymanager/include/net_policy_service.h @@ -52,12 +52,12 @@ public: NetPolicyResultCode GetNetQuotaPolicies(std::vector "aPolicies) override; NetPolicyResultCode SetCellularPolicies(const std::vector &cellularPolicies) override; NetPolicyResultCode GetCellularPolicies(std::vector &cellularPolicies) override; - NetPolicyResultCode SetFactoryPolicy(const std::string &slotId) override; + NetPolicyResultCode SetFactoryPolicy(const std::string &simId) override; NetPolicyResultCode SetBackgroundPolicy(bool backgroundPolicy) override; bool GetBackgroundPolicy() override; bool GetBackgroundPolicyByUid(uint32_t uid) override; NetBackgroundPolicy GetCurrentBackgroundPolicy() override; - NetPolicyResultCode SetSnoozePolicy(int8_t netType, int32_t slotId) override; + NetPolicyResultCode SetSnoozePolicy(int8_t netType, const std::string &simId) override; NetPolicyResultCode SetIdleTrustlist(uint32_t uid, bool isTrustlist) override; NetPolicyResultCode GetIdleTrustlist(std::vector &uids) override; void CheckNetStatsOverLimit(const std::vector "aPolicies); diff --git a/services/netpolicymanager/include/net_policy_traffic.h b/services/netpolicymanager/include/net_policy_traffic.h index ffe752981..971a6add8 100755 --- a/services/netpolicymanager/include/net_policy_traffic.h +++ b/services/netpolicymanager/include/net_policy_traffic.h @@ -46,7 +46,7 @@ public: bool IsUidPolicyExist(uint32_t uid); NetPolicyResultCode SetNetQuotaPolicies(const std::vector "aPolicies); NetPolicyResultCode SetCellularPolicies(const std::vector &cellularPolicies); - NetPolicyResultCode SetSnoozePolicy(int8_t netType, int32_t slotId, + NetPolicyResultCode SetSnoozePolicy(int8_t netType, const std::string &simId, std::vector "aPolicies); NetPolicyResultCode SetIdleTrustlist(uint32_t uid, bool isTrustlist); NetPolicyResultCode GetIdleTrustlist(std::vector &uids); @@ -57,7 +57,7 @@ private: bool IsNetPolicyTypeValid(NetBearType netType); bool IsNetPolicyPeriodDurationValid(const std::string &periodDuration); void InitController(); - bool IsQuotaPolicyExist(int8_t netType, int32_t slotId); + bool IsQuotaPolicyExist(int8_t netType, const std::string &simId); private: sptr netPolicyFile_; diff --git a/services/netpolicymanager/include/stub/net_policy_callback_proxy.h b/services/netpolicymanager/include/stub/net_policy_callback_proxy.h index 581b07045..45e4c0c0d 100755 --- a/services/netpolicymanager/include/stub/net_policy_callback_proxy.h +++ b/services/netpolicymanager/include/stub/net_policy_callback_proxy.h @@ -32,7 +32,7 @@ public: public: int32_t NetUidPolicyChanged(uint32_t uid, NetUidPolicy policy) override; int32_t NetCellularPolicyChanged(const std::vector &cellularPolicies) override; - int32_t NetStrategySwitch(int32_t slotId, bool enable) override; + int32_t NetStrategySwitch(const std::string &simId, bool enable) override; int32_t NetBackgroundPolicyChanged(bool isBackgroundPolicyAllow) override; private: diff --git a/services/netpolicymanager/src/net_policy_callback.cpp b/services/netpolicymanager/src/net_policy_callback.cpp index 1db7ce3b3..9dd266f1c 100755 --- a/services/netpolicymanager/src/net_policy_callback.cpp +++ b/services/netpolicymanager/src/net_policy_callback.cpp @@ -14,6 +14,7 @@ */ #include "net_policy_callback.h" #include "net_policy_constants.h" +#include "net_policy_define.h" #include "net_mgr_log_wrapper.h" namespace OHOS { @@ -25,7 +26,14 @@ void NetPolicyCallback::RegisterNetPolicyCallback(const sptr return; } - for (uint32_t i = 0; i < netPolicyCallback_.size(); i++) { + uint32_t callBackNum = netPolicyCallback_.size(); + NETMGR_LOG_D("netPolicyCallback_ callback num [%{public}d]", callBackNum); + if (callBackNum >= LIMIT_CALLBACK_NUM) { + NETMGR_LOG_E("netPolicyCallback_ callback num cannot more than [%{public}d]", LIMIT_CALLBACK_NUM); + return; + } + + for (uint32_t i = 0; i < callBackNum; i++) { if (callback->AsObject().GetRefPtr() == netPolicyCallback_[i]->AsObject().GetRefPtr()) { NETMGR_LOG_I("netPolicyCallback_ had this callback"); return; @@ -95,14 +103,14 @@ int32_t NetPolicyCallback::NotifyNetCellularPolicyChanged(const std::vector(NetPolicyResultCode::ERR_NONE); } -int32_t NetPolicyCallback::NotifyNetStrategySwitch(int32_t slotId, bool enable) +int32_t NetPolicyCallback::NotifyNetStrategySwitch(const std::string &simId, bool enable) { - NETMGR_LOG_I("NotifyNetStrategySwitch slotId[%{public}d] enable[%{public}d]", - slotId, static_cast(enable)); + NETMGR_LOG_I("NotifyNetStrategySwitch simId[%{public}s] enable[%{public}d]", + simId.c_str(), static_cast(enable)); for (const auto &callback : netPolicyCallback_) { if (callback != nullptr) { - callback->NetStrategySwitch(slotId, enable); + callback->NetStrategySwitch(simId, enable); } } diff --git a/services/netpolicymanager/src/net_policy_file.cpp b/services/netpolicymanager/src/net_policy_file.cpp index 75f7a86eb..183dda85a 100755 --- a/services/netpolicymanager/src/net_policy_file.cpp +++ b/services/netpolicymanager/src/net_policy_file.cpp @@ -75,7 +75,7 @@ void NetPolicyFile::ParseQuotaPolicy(const Json::Value &root, NetPolicy &netPoli NetPolicyQuota quotaPolicy; for (uint32_t i = 0; i < size; i++) { quotaPolicy.netType = arrayQuotaPolicy[i][CONFIG_QUOTA_POLICY_NETTYPE].asString(); - quotaPolicy.slotId = arrayQuotaPolicy[i][CONFIG_QUOTA_POLICY_SUBSCRIBERID].asString(); + quotaPolicy.simId = arrayQuotaPolicy[i][CONFIG_QUOTA_POLICY_SUBSCRIBERID].asString(); quotaPolicy.periodStartTime = arrayQuotaPolicy[i][CONFIG_QUOTA_POLICY_PERIODSTARTTIME].asString(); quotaPolicy.periodDuration = arrayQuotaPolicy[i][CONFIG_QUOTA_POLICY_PERIODDURATION].asString(); quotaPolicy.warningBytes = arrayQuotaPolicy[i][CONFIG_QUOTA_POLICY_WARNINGBYTES].asString(); @@ -93,7 +93,7 @@ void NetPolicyFile::ParseCellularPolicy(const Json::Value &root, NetPolicy &netP uint32_t size = arrayCellularPolicy.size(); NetPolicyCellular cellularPolicy; for (uint32_t i = 0; i < size; i++) { - cellularPolicy.slotId = arrayCellularPolicy[i][CONFIG_CELLULAR_POLICY_SUBSCRIBERID].asString(); + cellularPolicy.simId = arrayCellularPolicy[i][CONFIG_CELLULAR_POLICY_SUBSCRIBERID].asString(); cellularPolicy.periodStartTime = arrayCellularPolicy[i][CONFIG_CELLULAR_POLICY_PERIODSTARTTIME].asString(); cellularPolicy.periodDuration = arrayCellularPolicy[i][CONFIG_CELLULAR_POLICY_PERIODDURATION].asString(); cellularPolicy.title = arrayCellularPolicy[i][CONFIG_CELLULAR_POLICY_TITLE].asString(); @@ -170,7 +170,7 @@ void NetPolicyFile::AppendQuotaPolicy(Json::Value &root) for (uint32_t i = 0; i < size; i++) { Json::Value quotaPolicy; quotaPolicy[CONFIG_QUOTA_POLICY_NETTYPE] = netPolicy_.netQuotaPolicys[i].netType; - quotaPolicy[CONFIG_QUOTA_POLICY_SUBSCRIBERID] = netPolicy_.netQuotaPolicys[i].slotId; + quotaPolicy[CONFIG_QUOTA_POLICY_SUBSCRIBERID] = netPolicy_.netQuotaPolicys[i].simId; quotaPolicy[CONFIG_QUOTA_POLICY_PERIODSTARTTIME] = netPolicy_.netQuotaPolicys[i].periodStartTime; quotaPolicy[CONFIG_QUOTA_POLICY_PERIODDURATION] = netPolicy_.netQuotaPolicys[i].periodDuration; quotaPolicy[CONFIG_QUOTA_POLICY_WARNINGBYTES] = netPolicy_.netQuotaPolicys[i].warningBytes; @@ -187,7 +187,7 @@ void NetPolicyFile::AppendCellularPolicy(Json::Value &root) uint32_t size = netPolicy_.netCellularPolicys.size(); for (uint32_t i = 0; i < size; i++) { Json::Value cellularPolicy; - cellularPolicy[CONFIG_CELLULAR_POLICY_SUBSCRIBERID] = netPolicy_.netCellularPolicys[i].slotId; + cellularPolicy[CONFIG_CELLULAR_POLICY_SUBSCRIBERID] = netPolicy_.netCellularPolicys[i].simId; cellularPolicy[CONFIG_CELLULAR_POLICY_PERIODSTARTTIME] = netPolicy_.netCellularPolicys[i].periodStartTime; cellularPolicy[CONFIG_CELLULAR_POLICY_PERIODDURATION] = netPolicy_.netCellularPolicys[i].periodDuration; @@ -306,7 +306,7 @@ bool NetPolicyFile::UpdateQuotaPolicyExist(const NetPolicyQuotaPolicy "aPoli } for (uint32_t i = 0; i < netPolicy_.netQuotaPolicys.size(); ++i) { - if (std::to_string(quotaPolicy.slotId_) == netPolicy_.netQuotaPolicys[i].slotId && + if (quotaPolicy.simId_ == netPolicy_.netQuotaPolicys[i].simId && netPolicy_.netQuotaPolicys[i].netType == std::to_string(quotaPolicy.netType_)) { netPolicy_.netQuotaPolicys[i].lastLimitSnooze = std::to_string(quotaPolicy.lastLimitSnooze_); netPolicy_.netQuotaPolicys[i].limitBytes = std::to_string(quotaPolicy.limitBytes_); @@ -315,7 +315,7 @@ bool NetPolicyFile::UpdateQuotaPolicyExist(const NetPolicyQuotaPolicy "aPoli netPolicy_.netQuotaPolicys[i].periodDuration = quotaPolicy.periodDuration_; netPolicy_.netQuotaPolicys[i].periodStartTime = std::to_string(quotaPolicy.periodStartTime_); netPolicy_.netQuotaPolicys[i].source = std::to_string(quotaPolicy.source_); - netPolicy_.netQuotaPolicys[i].slotId = std::to_string(quotaPolicy.slotId_); + netPolicy_.netQuotaPolicys[i].simId = quotaPolicy.simId_; netPolicy_.netQuotaPolicys[i].warningBytes = std::to_string(quotaPolicy.warningBytes_); return true; } @@ -339,7 +339,7 @@ bool NetPolicyFile::WriteFile(const std::vector "aPoli quotaPolicy.periodDuration = quotaPolicies[i].periodDuration_; quotaPolicy.periodStartTime = std::to_string(quotaPolicies[i].periodStartTime_); quotaPolicy.source = std::to_string(quotaPolicies[i].source_); - quotaPolicy.slotId = std::to_string(quotaPolicies[i].slotId_); + quotaPolicy.simId = quotaPolicies[i].simId_; quotaPolicy.warningBytes = std::to_string(quotaPolicies[i].warningBytes_); netPolicy_.netQuotaPolicys.push_back(quotaPolicy); } @@ -360,8 +360,8 @@ bool NetPolicyFile::UpdateCellularPolicyExist(const NetPolicyCellularPolicy &cel } for (uint32_t i = 0; i < netPolicy_.netCellularPolicys.size(); ++i) { - if (std::to_string(cellularPolicy.slotId_) == netPolicy_.netCellularPolicys[i].slotId) { - netPolicy_.netCellularPolicys[i].slotId = std::to_string(cellularPolicy.slotId_); + if (cellularPolicy.simId_ == netPolicy_.netCellularPolicys[i].simId) { + netPolicy_.netCellularPolicys[i].simId = cellularPolicy.simId_; netPolicy_.netCellularPolicys[i].periodStartTime = std::to_string(cellularPolicy.periodStartTime_); netPolicy_.netCellularPolicys[i].periodDuration = cellularPolicy.periodDuration_; netPolicy_.netCellularPolicys[i].title = cellularPolicy.title_; @@ -386,7 +386,7 @@ bool NetPolicyFile::WriteFile(const std::vector &cellul if (UpdateCellularPolicyExist(cellularPolicies[i])) { continue; } - cellularPolicy.slotId = std::to_string(cellularPolicies[i].slotId_); + cellularPolicy.simId = cellularPolicies[i].simId_; cellularPolicy.periodStartTime = std::to_string(cellularPolicies[i].periodStartTime_); cellularPolicy.periodDuration = cellularPolicies[i].periodDuration_; cellularPolicy.title = cellularPolicies[i].title_; @@ -453,7 +453,7 @@ NetPolicyResultCode NetPolicyFile::GetNetQuotaPolicies(std::vector(std::stoll(quotaPolicy.periodStartTime)); quotaPolicyTmp.source_ = static_cast(std::stol(quotaPolicy.source)); - quotaPolicyTmp.slotId_ = static_cast(std::stol(quotaPolicy.slotId)); + quotaPolicyTmp.simId_ = quotaPolicy.simId; quotaPolicyTmp.warningBytes_ = static_cast(std::stoll(quotaPolicy.warningBytes)); quotaPolicies.push_back(quotaPolicyTmp); } @@ -461,11 +461,12 @@ NetPolicyResultCode NetPolicyFile::GetNetQuotaPolicies(std::vector(std::stol(quotaPolicyTemp.netType)) && - slotId == static_cast(std::stol(quotaPolicyTemp.slotId))) { + simId == quotaPolicyTemp.simId) { quotaPolicy.lastLimitSnooze_ = static_cast(std::stoll(quotaPolicyTemp.lastLimitSnooze)); quotaPolicy.limitBytes_ = static_cast(std::stoll(quotaPolicyTemp.limitBytes)); quotaPolicy.metered_ = static_cast(std::stol(quotaPolicyTemp.metered)); @@ -473,7 +474,7 @@ NetPolicyResultCode NetPolicyFile::GetNetQuotaPolicy(int8_t netType, int32_t slo quotaPolicy.periodDuration_ = quotaPolicyTemp.periodDuration; quotaPolicy.periodStartTime_ = static_cast(std::stoll(quotaPolicyTemp.periodStartTime)); quotaPolicy.source_ = static_cast(std::stol(quotaPolicyTemp.source)); - quotaPolicy.slotId_ = static_cast(std::stol(quotaPolicyTemp.slotId)); + quotaPolicy.simId_ = quotaPolicyTemp.simId; quotaPolicy.warningBytes_ = static_cast(std::stoll(quotaPolicyTemp.warningBytes)); return NetPolicyResultCode::ERR_NONE; } @@ -489,7 +490,7 @@ bool NetPolicyFile::IsInterfaceMetered(const std::string &ifaceName) NetBearType bearerType = static_cast(netType); std::string policyIfaceName; int32_t ret = NetManagerCenter::GetInstance().GetIfaceNameByType(bearerType, - IDENT_PREFIX + quotaPolicy.slotId, policyIfaceName); + IDENT_PREFIX, policyIfaceName); if (ret != 0 || policyIfaceName.empty()) { continue; } @@ -504,7 +505,7 @@ NetPolicyResultCode NetPolicyFile::GetCellularPolicies(std::vector(std::stol(cellularPolicy.slotId)); + cellularPolicyTmp.simId_ = cellularPolicy.simId; cellularPolicyTmp.periodStartTime_ = static_cast(std::stoll(cellularPolicy.periodStartTime)); cellularPolicyTmp.periodDuration_ = cellularPolicy.periodDuration; cellularPolicyTmp.title_ = cellularPolicy.title; @@ -520,24 +521,24 @@ NetPolicyResultCode NetPolicyFile::GetCellularPolicies(std::vectorslotId) { + if (simId == iter->simId) { netPolicy_.netQuotaPolicys.erase(iter); break; } } for (auto iter = netPolicy_.netCellularPolicys.begin(); iter != netPolicy_.netCellularPolicys.end(); ++iter) { - if (slotId == iter->slotId) { + if (simId == iter->simId) { netPolicy_.netCellularPolicys.erase(iter); break; } diff --git a/services/netpolicymanager/src/net_policy_service.cpp b/services/netpolicymanager/src/net_policy_service.cpp index 0357e79bf..b120ea7be 100755 --- a/services/netpolicymanager/src/net_policy_service.cpp +++ b/services/netpolicymanager/src/net_policy_service.cpp @@ -287,13 +287,12 @@ void NetPolicyService::CheckNetStatsOverLimit(const std::vectorNotifyNetStrategySwitch(cellularPolicies[i].slotId_, true); + netPolicyCallback_->NotifyNetStrategySwitch(cellularPolicies[i].simId_, true); } continue; } - std::string slotId = IDENT_PREFIX + std::to_string(cellularPolicies[i].slotId_); int32_t ret = NetManagerCenter::GetInstance().GetIfaceNameByType(BEARER_CELLULAR, - slotId, ifaceName); + IDENT_PREFIX, ifaceName); if (ret != 0 || ifaceName.empty()) { NETMGR_LOG_E("GetIfaceNameByType ret [%{public}d] ifaceName [%{public}s]", ret, ifaceName.c_str()); continue; @@ -310,11 +309,11 @@ void NetPolicyService::CheckNetStatsOverLimit(const std::vectorNotifyNetStrategySwitch(cellularPolicies[i].slotId_, true); + netPolicyCallback_->NotifyNetStrategySwitch(cellularPolicies[i].simId_, true); } } else { if (netPolicyCallback_ != nullptr) { - netPolicyCallback_->NotifyNetStrategySwitch(cellularPolicies[i].slotId_, false); + netPolicyCallback_->NotifyNetStrategySwitch(cellularPolicies[i].simId_, false); } } } @@ -341,9 +340,8 @@ void NetPolicyService::CheckNetStatsOverLimit(const std::vector(quotaPolicies[i].netType_); - std::string slotId = IDENT_PREFIX + std::to_string(quotaPolicies[i].slotId_); int32_t ret = NetManagerCenter::GetInstance().GetIfaceNameByType( - bearerType, slotId, ifaceName); + bearerType, IDENT_PREFIX, ifaceName); if (ret != 0 || ifaceName.empty()) { NETMGR_LOG_E("GetIfaceNameByType ret [%{public}d] ifaceName [%{public}s]", ret, ifaceName.c_str()); continue; @@ -363,11 +361,11 @@ void NetPolicyService::CheckNetStatsOverLimit(const std::vectorNotifyNetStrategySwitch(quotaPolicies[i].slotId_, true); + netPolicyCallback_->NotifyNetStrategySwitch(quotaPolicies[i].simId_, true); } } else { if (netPolicyCallback_ != nullptr) { - netPolicyCallback_->NotifyNetStrategySwitch(quotaPolicies[i].slotId_, false); + netPolicyCallback_->NotifyNetStrategySwitch(quotaPolicies[i].simId_, false); } } } @@ -425,12 +423,12 @@ NetPolicyResultCode NetPolicyService::GetCellularPolicies(std::vectorGetCellularPolicies(cellularPolicies); } -NetPolicyResultCode NetPolicyService::SetFactoryPolicy(const std::string &slotId) +NetPolicyResultCode NetPolicyService::SetFactoryPolicy(const std::string &simId) { std::unique_lock lock(mutex_); NETMGR_LOG_I("SetFactoryPolicy begin"); netPolicyTraffic_->ClearIdleTrustList(); - return netPolicyFile_->SetFactoryPolicy(slotId); + return netPolicyFile_->SetFactoryPolicy(simId); } NetPolicyResultCode NetPolicyService::SetBackgroundPolicy(bool backgroundPolicy) @@ -475,13 +473,13 @@ NetBackgroundPolicy NetPolicyService::GetCurrentBackgroundPolicy() return netPolicyFirewall_->GetCurrentBackgroundPolicy(); } -NetPolicyResultCode NetPolicyService::SetSnoozePolicy(int8_t netType, int32_t slotId) +NetPolicyResultCode NetPolicyService::SetSnoozePolicy(int8_t netType, const std::string &simId) { NETMGR_LOG_I("SetSnoozePolicy begin"); NetPolicyQuotaPolicy quotaPolicy; std::unique_lock lock(mutex_); - NetPolicyResultCode ret = netPolicyFile_->GetNetQuotaPolicy(netType, slotId, quotaPolicy); + NetPolicyResultCode ret = netPolicyFile_->GetNetQuotaPolicy(netType, simId, quotaPolicy); if (NetPolicyResultCode::ERR_NONE != ret) { NETMGR_LOG_E("SetSnoozePolicy GetQuotaPolicy failed"); return ret; @@ -489,7 +487,7 @@ NetPolicyResultCode NetPolicyService::SetSnoozePolicy(int8_t netType, int32_t sl /* Set the sleep time to the current time. */ quotaPolicy.lastLimitSnooze_ = GetCurrentTime(); std::vector quotaPolicies = {quotaPolicy}; - ret = netPolicyTraffic_->SetSnoozePolicy(netType, slotId, quotaPolicies); + ret = netPolicyTraffic_->SetSnoozePolicy(netType, simId, quotaPolicies); lock.unlock(); if (ret == NetPolicyResultCode::ERR_NONE) { /* Judge whether the flow exceeds the limit */ diff --git a/services/netpolicymanager/src/net_policy_traffic.cpp b/services/netpolicymanager/src/net_policy_traffic.cpp index 4f77c7893..dba31a727 100755 --- a/services/netpolicymanager/src/net_policy_traffic.cpp +++ b/services/netpolicymanager/src/net_policy_traffic.cpp @@ -213,7 +213,7 @@ NetPolicyResultCode NetPolicyTraffic::SetCellularPolicies(const std::vector quotaPolicies; if (netPolicyFile_->GetNetQuotaPolicies(quotaPolicies) != NetPolicyResultCode::ERR_NONE) { @@ -227,7 +227,7 @@ bool NetPolicyTraffic::IsQuotaPolicyExist(int8_t netType, int32_t slotId) } for (uint32_t i = 0; i < quotaPolicies.size(); i++) { - if (netType == quotaPolicies[i].netType_ && slotId == quotaPolicies[i].slotId_) { + if (netType == quotaPolicies[i].netType_ && simId == quotaPolicies[i].simId_) { NETMGR_LOG_D("netQuotaPolicy exist"); return true; } @@ -236,7 +236,7 @@ bool NetPolicyTraffic::IsQuotaPolicyExist(int8_t netType, int32_t slotId) return false; } -NetPolicyResultCode NetPolicyTraffic::SetSnoozePolicy(int8_t netType, int32_t slotId, +NetPolicyResultCode NetPolicyTraffic::SetSnoozePolicy(int8_t netType, const std::string &simId, std::vector "aPolicies) { if (!IsNetPolicyTypeValid(static_cast(netType))) { @@ -244,7 +244,7 @@ NetPolicyResultCode NetPolicyTraffic::SetSnoozePolicy(int8_t netType, int32_t sl return NetPolicyResultCode::ERR_INVALID_QUOTA_POLICY; } - if (!IsQuotaPolicyExist(netType, slotId)) { + if (!IsQuotaPolicyExist(netType, simId)) { NETMGR_LOG_E("quotaPolicy is not exist"); return NetPolicyResultCode::ERR_QUOTA_POLICY_NOT_EXIST; } diff --git a/services/netpolicymanager/src/stub/net_policy_callback_proxy.cpp b/services/netpolicymanager/src/stub/net_policy_callback_proxy.cpp index c24ead4b2..c7c83db92 100755 --- a/services/netpolicymanager/src/stub/net_policy_callback_proxy.cpp +++ b/services/netpolicymanager/src/stub/net_policy_callback_proxy.cpp @@ -116,7 +116,7 @@ int32_t NetPolicyCallbackProxy::NetCellularPolicyChanged(const std::vector(SetSnoozePolicy(netType, slotId)))) { + if (!reply.WriteInt32(static_cast(SetSnoozePolicy(netType, simId)))) { return ERR_FLATTEN_OBJECT; } diff --git a/services/netstatsmanager/BUILD.gn b/services/netstatsmanager/BUILD.gn index e1fb3140e..aedb4985e 100644 --- a/services/netstatsmanager/BUILD.gn +++ b/services/netstatsmanager/BUILD.gn @@ -42,6 +42,7 @@ ohos_shared_library("net_stats_manager") { "$NETDCONTROLLER_ROOT_DIR:netd_controller", "$NETMANAGER_BASE_ROOT/utils:net_manager_common", "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//utils/native/base:utils", ] external_deps = [ @@ -51,7 +52,6 @@ ohos_shared_library("net_stats_manager") { "ipc:ipc_core", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", - "utils_base:utils", ] defines = [ diff --git a/services/netstatsmanager/include/net_stats_csv.h b/services/netstatsmanager/include/net_stats_csv.h index 0597e68c3..5ee7497be 100755 --- a/services/netstatsmanager/include/net_stats_csv.h +++ b/services/netstatsmanager/include/net_stats_csv.h @@ -58,7 +58,7 @@ enum class UidStatCsvColumn { class CSVRow { public: - std::string const& operator[](uint32_t index) const + const std::string& operator[](uint32_t index) const { return data_[index]; } diff --git a/services/netstatsmanager/src/net_stats_callback.cpp b/services/netstatsmanager/src/net_stats_callback.cpp index 83db232bb..0ed91cba9 100755 --- a/services/netstatsmanager/src/net_stats_callback.cpp +++ b/services/netstatsmanager/src/net_stats_callback.cpp @@ -26,7 +26,14 @@ void NetStatsCallback::RegisterNetStatsCallback(const sptr &c return; } - for (uint32_t i = 0; i < netStatsCallback_.size(); i++) { + uint32_t callBackNum = netStatsCallback_.size(); + NETMGR_LOG_D("netStatsCallback_ callback num [%{public}d]", callBackNum); + if (callBackNum >= LIMIT_STATS_CALLBACK_NUM) { + NETMGR_LOG_E("netStatsCallback_ callback num cannot more than [%{public}d]", LIMIT_STATS_CALLBACK_NUM); + return; + } + + for (uint32_t i = 0; i < callBackNum; i++) { if (callback->AsObject().GetRefPtr() == netStatsCallback_[i]->AsObject().GetRefPtr()) { NETMGR_LOG_I("netStatsCallback_ had this callback"); return; diff --git a/services/netstatsmanager/src/net_stats_csv.cpp b/services/netstatsmanager/src/net_stats_csv.cpp index 9db84e291..8bf158f2e 100755 --- a/services/netstatsmanager/src/net_stats_csv.cpp +++ b/services/netstatsmanager/src/net_stats_csv.cpp @@ -457,8 +457,8 @@ NetStatsResultCode NetStatsCsv::GetIfaceBytes(const std::string &iface, uint32_t if (calStartTime == calEndTime) { statsInfo.rxBytes_ = 0; statsInfo.txBytes_ = 0; - NETMGR_LOG_E("start and end less equal Minimum time or greater equal Maximum time"); - return NetStatsResultCode::ERR_INTERNAL_ERROR; + NETMGR_LOG_E("there is no data in this time period, please enter a valid time period."); + return NetStatsResultCode::ERR_INVALID_TIME_PERIOD; } CSVRow row; @@ -484,8 +484,8 @@ NetStatsResultCode NetStatsCsv::GetUidBytes(const std::string &iface, uint32_t u if (calStartTime == calEndTime) { statsInfo.rxBytes_ = 0; statsInfo.txBytes_ = 0; - NETMGR_LOG_E("start and end less equal Minimum time or greater equal Maximum time"); - return NetStatsResultCode::ERR_INTERNAL_ERROR; + NETMGR_LOG_E("there is no data in this time period, please enter a valid time period."); + return NetStatsResultCode::ERR_INVALID_TIME_PERIOD; } std::ifstream uid_file(CSV_DIR + UID_STATS_CSV_FILE_NAME, std::fstream::in); diff --git a/services/netstatsmanager/src/net_stats_service.cpp b/services/netstatsmanager/src/net_stats_service.cpp index fb71999f5..3002ae01a 100644 --- a/services/netstatsmanager/src/net_stats_service.cpp +++ b/services/netstatsmanager/src/net_stats_service.cpp @@ -179,11 +179,10 @@ NetStatsResultCode NetStatsService::GetIfaceStatsDetail(const std::string &iface NetStatsResultCode result = netStatsCsv_->GetIfaceBytes(iface, start, end, statsInfo); NETMGR_LOG_I("GetIfaceStatsDetail iface[%{public}s], statsInfo.rxBytes[%{public}" PRId64 "]" "statsInfo.txBytes[%{public}" PRId64 "]", iface.c_str(), statsInfo.rxBytes_, statsInfo.txBytes_); - if (result == NetStatsResultCode::ERR_INTERNAL_ERROR) { - NETMGR_LOG_E("GetIfaceBytes data is error."); - return NetStatsResultCode::ERR_INTERNAL_ERROR; + if (result == NetStatsResultCode::ERR_INVALID_TIME_PERIOD) { + NETMGR_LOG_E("GetIfaceBytes is error."); } - return NetStatsResultCode::ERR_NONE; + return result; } NetStatsResultCode NetStatsService::GetUidStatsDetail(const std::string &iface, uint32_t uid, @@ -204,11 +203,10 @@ NetStatsResultCode NetStatsService::GetUidStatsDetail(const std::string &iface, NetStatsResultCode result = netStatsCsv_->GetUidBytes(iface, uid, start, end, statsInfo); NETMGR_LOG_I("GetUidStatsDetail iface[%{public}s], uid[%{public}d] statsInfo.rxBytes[%{public}" PRId64 "] " "statsInfo.txBytes[%{public}" PRId64 "]", iface.c_str(), uid, statsInfo.rxBytes_, statsInfo.txBytes_); - if (result == NetStatsResultCode::ERR_INTERNAL_ERROR) { - NETMGR_LOG_E("GetIfaceBytes data is error."); - return NetStatsResultCode::ERR_INTERNAL_ERROR; + if (result == NetStatsResultCode::ERR_INVALID_TIME_PERIOD) { + NETMGR_LOG_E("GetUidBytes is error."); } - return NetStatsResultCode::ERR_NONE; + return result; } NetStatsResultCode NetStatsService::UpdateIfacesStats(const std::string &iface, diff --git a/services/netstatsmanager/src/stub/net_stats_service_stub.cpp b/services/netstatsmanager/src/stub/net_stats_service_stub.cpp index 867e958d4..04e89fa78 100755 --- a/services/netstatsmanager/src/stub/net_stats_service_stub.cpp +++ b/services/netstatsmanager/src/stub/net_stats_service_stub.cpp @@ -103,15 +103,15 @@ int32_t NetStatsServiceStub::OnGetIfaceStatsDetail(MessageParcel &data, MessageP } NetStatsInfo stats; - if (GetIfaceStatsDetail(iface, start, end, stats) != NetStatsResultCode::ERR_NONE) { - NETMGR_LOG_E("GetIfaceStatsDetail failed."); - return ERR_FLATTEN_OBJECT; - } - + int32_t result = static_cast(GetIfaceStatsDetail(iface, start, end, stats)); if (!NetStatsInfo::Marshalling(reply, stats)) { NETMGR_LOG_E("proxy Marshalling failed"); return ERR_FLATTEN_OBJECT; } + NETMGR_LOG_I("NetStatsServiceStub::OnGetIfaceStatsDetail, result[%{public}d]", result); + if (!reply.WriteInt32(result)) { + return ERR_FLATTEN_OBJECT; + } return ERR_NONE; } @@ -138,13 +138,13 @@ int32_t NetStatsServiceStub::OnGetUidStatsDetail(MessageParcel &data, MessagePar } NetStatsInfo stats; - if (GetUidStatsDetail(iface, uid, start, end, stats) != NetStatsResultCode::ERR_NONE) { - NETMGR_LOG_E("GetUidStatsDetail failed."); + int32_t result = static_cast(GetUidStatsDetail(iface, uid, start, end, stats)); + if (!NetStatsInfo::Marshalling(reply, stats)) { + NETMGR_LOG_E("proxy Marshalling failed"); return ERR_FLATTEN_OBJECT; } - - if (!NetStatsInfo::Marshalling(reply, stats)) { - NETMGR_LOG_E("NetStatsInfo Marshalling failed"); + NETMGR_LOG_I("NetStatsServiceStub::OnGetUidStatsDetail, result[%{public}d]", result); + if (!reply.WriteInt32(result)) { return ERR_FLATTEN_OBJECT; } return ERR_NONE; diff --git a/test/netmanagernative/BUILD.gn b/test/netmanagernative/BUILD.gn index 809f0ad1a..e69df5f0e 100644 --- a/test/netmanagernative/BUILD.gn +++ b/test/netmanagernative/BUILD.gn @@ -36,7 +36,6 @@ ohos_unittest("netd_native_manager_test") { ] external_deps = [ - "ability_runtime:app_manager", "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", diff --git a/test/netmanagernative/unittest/BUILD.gn b/test/netmanagernative/unittest/BUILD.gn index 809f0ad1a..e69df5f0e 100644 --- a/test/netmanagernative/unittest/BUILD.gn +++ b/test/netmanagernative/unittest/BUILD.gn @@ -36,7 +36,6 @@ ohos_unittest("netd_native_manager_test") { ] external_deps = [ - "ability_runtime:app_manager", "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", diff --git a/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_callback_test.cpp b/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_callback_test.cpp index 7dd30a2bb..a021e92d8 100755 --- a/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_callback_test.cpp +++ b/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_callback_test.cpp @@ -66,10 +66,10 @@ int32_t NetPolicyCallbackTest::NetCellularPolicyChanged(const std::vector(enable)); + NETMGR_LOG_D("unittest NetStrategySwitch, simId:[%{public}s], enable:[%{public}d]", + simId.c_str(), static_cast(enable)); return 0; } diff --git a/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_callback_test.h b/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_callback_test.h index dd4a0e0e0..7abc6cda0 100755 --- a/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_callback_test.h +++ b/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_callback_test.h @@ -31,7 +31,7 @@ public: virtual ~NetPolicyCallbackTest() override; int32_t NetUidPolicyChanged(uint32_t uid, NetUidPolicy policy) override; int32_t NetCellularPolicyChanged(const std::vector &cellularPolicies) override; - int32_t NetStrategySwitch(int32_t slotId, bool enable) override; + int32_t NetStrategySwitch(const std::string &simId, bool enable) override; int32_t NetBackgroundPolicyChanged(bool isBackgroundPolicyAllow) override; void WaitFor(int32_t timeoutSecond); diff --git a/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_manager_test.cpp b/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_manager_test.cpp index 3b7d55329..80beaec65 100755 --- a/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_manager_test.cpp +++ b/test/netpolicymanager/unittest/net_policy_manager_test/net_policy_manager_test.cpp @@ -160,7 +160,7 @@ HWTEST_F(NetPolicyManagerTest, NetPolicyManager007, TestSize.Level1) NetPolicyQuotaPolicy quotaPolicy; quotaPolicy.netType_ = 0; - quotaPolicy.slotId_ = TRIGER_DELAY_US; + quotaPolicy.simId_ = std::to_string(TRIGER_DELAY_US); quotaPolicy.periodStartTime_ = TRIGER_DELAY_US; quotaPolicy.periodDuration_ = TEST_STRING_PERIODDURATION; quotaPolicy.warningBytes_ = TRIGER_DELAY_US; @@ -198,7 +198,7 @@ HWTEST_F(NetPolicyManagerTest, NetPolicyManager009, TestSize.Level1) NetPolicyCellularPolicy cellularPolicy; for (uint32_t i = 0; i < TEST_CONSTANT_NUM; ++i) { - cellularPolicy.slotId_ = i; + cellularPolicy.simId_ = std::to_string(i); cellularPolicy.periodStartTime_ = TRIGER_DELAY_US + i; cellularPolicy.periodDuration_ = TEST_STRING_PERIODDURATION; cellularPolicy.title_ = std::to_string(TRIGER_DELAY_US + i); @@ -238,9 +238,9 @@ HWTEST_F(NetPolicyManagerTest, NetPolicyManager010, TestSize.Level1) */ HWTEST_F(NetPolicyManagerTest, NetPolicyManager011, TestSize.Level1) { - std::string slotId = "0"; + std::string simId = "0"; - NetPolicyResultCode result = DelayedSingleton::GetInstance()->SetFactoryPolicy(slotId); + NetPolicyResultCode result = DelayedSingleton::GetInstance()->SetFactoryPolicy(simId); ASSERT_TRUE(result == NetPolicyResultCode::ERR_NONE); } @@ -252,7 +252,7 @@ HWTEST_F(NetPolicyManagerTest, NetPolicyManager011, TestSize.Level1) HWTEST_F(NetPolicyManagerTest, NetPolicyManager012, TestSize.Level1) { NetPolicyResultCode result = DelayedSingleton::GetInstance()->SetSnoozePolicy(0, - TRIGER_DELAY_US); + std::to_string(TRIGER_DELAY_US)); ASSERT_TRUE(result == NetPolicyResultCode::ERR_NONE); } -- Gitee