RDK Documentation (Open Sourced RDK Components)
netSrvMgrMain.cpp
1 /*
2  * If not stated otherwise in this file or this component's Licenses.txt file the
3  * following copyright and licenses apply:
4  *
5  * Copyright 2016 RDK Management
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18 */
19 
20 #ifdef INCLUDE_BREAKPAD
21 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
22 #include <client/linux/handler/exception_handler.h>
23 #else
24 #include "breakpadwrap.h"
25 #endif
26 #endif
27 
28 #include "NetworkMgrMain.h"
29 #include "wifiSrvMgr.h"
30 #include "netsrvmgrUtiles.h"
31 #include "netsrvmgrIarm.h"
32 #include <string>
33 #include <vector>
34 #include <fstream>
35 #include <sstream>
36 #include <algorithm>
37 #include <sys/stat.h>
38 #include <unistd.h>
39 #include <arpa/inet.h>
40 #include <pthread.h>
41 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
42 #include "connectivity.h"
43 #endif
44 
45 #ifdef ENABLE_STUN_CLIENT
46 #include "StunClient.h"
47 #endif
48 
49 #ifdef ENABLE_ROUTE_SUPPORT
50 #include "routeSrvMgr.h"
51 #endif
52 
53 #ifdef USE_RDK_MOCA_HAL
54 #include "mocaSrvMgr.h"
55 #endif
56 
57 #ifdef ENABLE_NLMONITOR
58 #include "netlinkifc.h"
59 #endif
60 
61 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
62 #include "rfcapi.h" // for RFC queries
63 #endif
64 
65 #ifdef SAFEC_RDKV
66 #include "safec_lib.h"
67 #else
68 #define STRCPY_S(dest,size,source) \
69  strcpy(dest, source);
70 #endif
71 char configProp_FilePath[100] = {'\0'};;
72 netMgrConfigProps confProp;
73 
74 #ifdef ENABLE_STUN_CLIENT
75 #define STUN_DEFAULT_BIND_TIMEOUT 30 //seconds
76 #define STUN_DEFAULT_CACHE_TIMEOUT 0 //seconds (0 for disable)
77 stun::client stunClient;
78 #endif
79 #define NETSRVMGR_DHCP_SERVERIP_PATH "/tmp/netsrvmgr.dhcp.server.ip"
80 
81 /*Telemetry Configuration Parameter List*/
82 #ifdef USE_RDK_WIFI_HAL
83 telemetryParams wifiParams_Tele_Period1;
84 telemetryParams wifiParams_Tele_Period2;
85 #endif // USE_RDK_WIFI_HAL
86 static bool parse_telemetry_logging_configuration( char *);
87 static void teleParamList_free (gpointer val);
88 
89 static void netSrvMgr_start();
90 static void netSrvMgr_Loop();
91 
92 #ifdef RDK_LOGGER_ENABLED
93 int b_rdk_logger_enabled = 0;
94 
95 void logCallback(const char *buff)
96 {
97  DEBUG_LOG("%s",buff);
98 }
99 #endif
100 
101 static void NetworkMgr_SignalHandler (int sigNum);
102 static bool read_ConfigProps();
103 void Read_Telemetery_Param_File();
104 static bool update_telemetryParams_list(gchar *, telemetryParams *, gchar *, gchar *);
105 
106 #ifdef ENABLE_IARM
107 static void _eventHandler(const char *owner, IARM_EventId_t eventId, void *data, size_t len);
108 static IARM_Result_t getActiveInterface(void *arg);
109 static IARM_Result_t getNetworkInterfaces(void *arg);
110 #ifdef ENABLE_NLMONITOR
111 static IARM_Result_t getInterfaceList(void *arg);
112 static IARM_Result_t getDefaultInterface(void *arg);
113 #endif // ifdef ENABLE_NLMONITOR
114 static IARM_Result_t setDefaultInterface(void *arg);
115 static IARM_Result_t isInterfaceEnabled(void *arg);
116 static IARM_Result_t setInterfaceEnabled(void *arg);
117 static IARM_Result_t getSTBip(void *arg);
118 static IARM_Result_t setIPSettings(void *arg);
119 static IARM_Result_t getIPSettings(void *arg);
120 static bool getDNSip(const unsigned int family, char *primaryDNS, char *secondaryDNS);
121 static IARM_Result_t getSTBip_family(void *arg);
122 static IARM_Result_t isConnectedToInternet(void *arg);
123 static IARM_Result_t setConnectivityTestEndpoints(void *arg);
124 static IARM_Result_t isAvailable(void *arg);
125 #ifdef ENABLE_STUN_CLIENT
126 static IARM_Result_t getPublicIP(void* arg);
127 #endif
128 #endif // ifdef ENABLE_IARM
129 
130 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
131 static bool isFeatureEnabled(const char* feature);
132 static bool validate_interface_can_be_disabled (const char* interface);
133 #ifdef ENABLE_NLMONITOR
134 static bool getDefaultInterface(std::string &interface, std::string &gateway);
135 #endif // ifdef ENABLE_NLMONITOR
136 static bool setDefaultInterface(const char* interface, bool persist);
137 static bool setInterfaceEnabled(const char* interface, bool enabled, bool persist);
138 static bool setInterfaceState(std::string interface_name, bool enabled);
139 static bool setIPSettings(IARM_BUS_NetSrvMgr_Iface_Settings_t *param);
140 static bool getIPSettings(IARM_BUS_NetSrvMgr_Iface_Settings_t *param);
141 #ifdef ENABLE_STUN_CLIENT
142 static bool getPublicIP(IARM_BUS_NetSrvMgr_Iface_StunRequest_t *param);
143 #endif
144 #endif // if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
145 
146 std::string gDhcpServerIP;
147 static bool getDhcpServerIP();
148 
149 void NetworkMgr_SignalHandler (int sigNum)
150 {
151  LOG_ERR("Received signal %d", sigNum);
152  signal(sigNum, SIG_DFL );
153 #ifdef USE_RDK_WIFI_HAL
154  /* Telemetry Parameter list*/
155  if (wifiParams_Tele_Period1.paramlist != NULL) {
156  g_list_free_full(wifiParams_Tele_Period1.paramlist, (GDestroyNotify)&teleParamList_free);
157  }
158 
159  if (wifiParams_Tele_Period2.paramlist != NULL)
160  {
161  g_list_free_full(wifiParams_Tele_Period2.paramlist, (GDestroyNotify)&teleParamList_free);
162  }
163 #endif // USE_RDK_WIFI_HAL
164  kill(getpid(), sigNum );
165  exit(0);
166 }
167 
168 #ifdef INCLUDE_BREAKPAD
169 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
170 static bool breakpadDumpCallback(const google_breakpad::MinidumpDescriptor& descriptor,
171  void* context,
172  bool succeeded)
173 {
174  LOG_INFO("breakpadDumpCallback: Netsrvmgr crashed ---- Dump path: %s", descriptor.path());
175  return true;
176 }
177 #endif
178 #endif
179 
180 // TODO: move this into the utility file?
181 /**
182  * Returns:
183  * the specified environment variable's value if it is not NULL.
184  * the specified default value otherwise.
185  */
186 const char* getenvOrDefault (const char* name, const char* defaultValue)
187 {
188  char* value = getenv (name);
189  return value ? value : defaultValue;
190 }
191 
192 static bool split (const std::string &str, char delimiter, std::vector<std::string> &tokens, int min_expected_tokens = 0)
193 {
194  std::stringstream stream (str);
195  std::string token;
196  tokens.clear();
197  while (getline (stream, token, delimiter))
198  tokens.push_back (token);
199  if (min_expected_tokens > 0 && tokens.size () < min_expected_tokens)
200  {
201  LOG_ERR("Unexpected number of tokens. Arguments received = %s", str.c_str ());
202  return false;
203  }
204  return true;
205 }
206 
207 #ifdef ENABLE_IARM
208 
209 static void eventInterfaceEnabledStatusChanged(const std::string& interface, bool enabled)
210 {
211  LOG_INFO("interface=%s, enabled=%d", interface.c_str(), enabled);
212 
214  snprintf(e.interface, sizeof(e.interface), "%s", interface.c_str());
215  e.status = enabled;
216 
217  if (IARM_RESULT_SUCCESS != IARM_Bus_BroadcastEvent (IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETWORK_MANAGER_EVENT_INTERFACE_ENABLED_STATUS, &e, sizeof(e)))
218  {
219  LOG_ERR("IARM Bus Error!");
220  }
221 }
222 
223 static void eventInterfaceConnectionStatusChanged(const std::string& interface, bool connected)
224 {
225  LOG_INFO("interface=%s, connected=%d", interface.c_str(), connected);
226 
228  snprintf(e.interface, sizeof(e.interface), "%s", interface.c_str());
229  e.status = connected;
230 
231  if (IARM_RESULT_SUCCESS != IARM_Bus_BroadcastEvent (IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETWORK_MANAGER_EVENT_INTERFACE_CONNECTION_STATUS, &e, sizeof(e)))
232  {
233  LOG_ERR("IARM Bus Error!");
234  }
235 }
236 
237 static void eventInterfaceIPAddressStatusChanged (const std::string& interface, const std::string& ip_address, bool is_ipv6, bool acquired)
238 {
239  LOG_INFO("interface=%s, ip_address=%s, is_ipv6=%d, acquired=%d", interface.c_str(), ip_address.c_str(), is_ipv6, acquired);
240 
242  snprintf(e.interface, sizeof(e.interface), "%s", interface.c_str());
243  snprintf(e.ip_address, sizeof(e.ip_address), "%s", ip_address.c_str());
244  e.is_ipv6 = is_ipv6;
245  e.acquired = acquired;
246 
247  if (IARM_RESULT_SUCCESS != IARM_Bus_BroadcastEvent (IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETWORK_MANAGER_EVENT_INTERFACE_IPADDRESS, &e, sizeof(e)))
248  {
249  LOG_ERR("IARM Bus Error!");
250  }
251 
252  if (!is_ipv6)
253  {
254  if (getDhcpServerIP())
255  {
256  LOG_INFO("Updated the DHCP Server IP Address: [%s]", gDhcpServerIP.c_str());
257  }
258  }
259 }
260 
261 static void eventDefaultInterfaceChanged(const std::string& oldInterface, const std::string& newInterface)
262 {
263  LOG_INFO("oldInterface=%s, newInterface=%s", oldInterface.c_str(), newInterface.c_str());
264 
266  snprintf(e.oldInterface, sizeof(e.oldInterface), "%s", oldInterface.c_str());
267  snprintf(e.newInterface, sizeof(e.newInterface), "%s", newInterface.c_str());
268 
269  if (IARM_RESULT_SUCCESS != IARM_Bus_BroadcastEvent (IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETWORK_MANAGER_EVENT_DEFAULT_INTERFACE, &e, sizeof(e)))
270  {
271  LOG_ERR("IARM Bus Error!");
272  }
273 }
274 
275 #endif // ifdef ENABLE_IARM
276 
277 #ifdef ENABLE_NLMONITOR
278 
279 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
280 
281 class DefaultGatewayMACLogger
282 {
283 public:
284  static DefaultGatewayMACLogger& getInstance()
285  {
286  static DefaultGatewayMACLogger instance;
287  return instance;
288  }
289 
290  DefaultGatewayMACLogger(const DefaultGatewayMACLogger&) = delete;
291  void operator=(const DefaultGatewayMACLogger&) = delete;
292 
293  void signal()
294  {
295  LOG_ENTRY_EXIT;
296  pthread_mutex_lock(&mutex);
297  signaled = true;
298  pthread_cond_signal(&cond);
299  pthread_mutex_unlock(&mutex);
300  }
301 
302 private:
303  static void* default_gateway_mac_logger(void* arg)
304  {
305  LOG_ENTRY_EXIT;
306  ((DefaultGatewayMACLogger*) arg)->default_gateway_mac_logger();
307  return NULL;
308  }
309 
310  void default_gateway_mac_logger()
311  {
312  LOG_ENTRY_EXIT;
313  struct timespec timeout;
314  bool timedout = true;
315  std::string default_gateway_mac, last_logged_default_gateway_mac;
316 
317  while (true)
318  {
319  if (timedout)
320  {
321  clock_gettime(CLOCK_MONOTONIC, &timeout);
322  timeout.tv_sec += DEFAULT_GATEWAY_MAC_LOGGING_INTERVAL_SECONDS;
323  }
324  pthread_mutex_lock(&mutex);
325  timedout = false;
326  while (!signaled && !timedout)
327  if (ETIMEDOUT == pthread_cond_timedwait (&cond, &mutex, &timeout))
328  timedout = true;
329  LOG_INFO("Triggered by %s", timedout ? "timeout" : "signal");
330  signaled = false;
331  pthread_mutex_unlock(&mutex);
332 
333  if (get_default_gateway_mac(default_gateway_mac) && (default_gateway_mac != last_logged_default_gateway_mac || timedout))
334  {
335  LOG_INFO("Default gateway MAC = %s", default_gateway_mac.c_str());
336 #ifdef USE_TELEMETRY_2_0
337  telemetry_event_s("gw_mac_split", (char*) default_gateway_mac.c_str());
338 #endif // #ifdef USE_TELEMETRY_2_0
339  last_logged_default_gateway_mac = default_gateway_mac;
340  timedout = true;
341  }
342  }
343  }
344 
345  bool get_default_gateway_mac(std::string& default_gateway_mac)
346  {
347  LOG_ENTRY_EXIT;
348 
349  std::string default_interface, default_gateway_ip;
350  bool is_ipv6;
351  if (NetLinkIfc::get_instance()->getDefaultRoute(true, default_interface, default_gateway_ip))
352  {
353  LOG_DBG("ipv6 default route exists");
354  is_ipv6 = true;
355  }
356  else if (NetLinkIfc::get_instance()->getDefaultRoute(false, default_interface, default_gateway_ip))
357  {
358  LOG_DBG("ipv4 default route exists");
359  is_ipv6 = false;
360  }
361  else
362  {
363  LOG_ERR("no default route exists");
364  return false;
365  }
366 
367  iface_info default_interface_info;
368  if (NetLinkIfc::get_instance()->getInterface(default_interface, default_interface_info) == false)
369  {
370  LOG_ERR("interface %s does not exist", default_interface.c_str());
371  return false;
372  }
373  if (default_interface_info.m_if_flags & IFF_RUNNING == 0)
374  {
375  LOG_ERR("interface %s is disconnected", default_interface.c_str());
376  return false;
377  }
378 
379  NetLinkIfc::get_instance()->get_neigh_mac_addr(default_interface, default_gateway_ip, is_ipv6, default_gateway_mac);
380  if (default_gateway_mac.empty())
381  {
382  LOG_ERR("default_gateway_mac is empty");
383  return false;
384  }
385  return true;
386  }
387 
388  DefaultGatewayMACLogger() : signaled(false)
389  {
390  LOG_ENTRY_EXIT;
391  int rc;
392 
393  pthread_mutex_init(&mutex, NULL);
394 
395  pthread_condattr_t condattr;
396  pthread_condattr_init(&condattr);
397  if (0 != (rc = pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)))
398  LOG_ERR("pthread_condattr_setclock returned %d", rc);
399  if (0 != (rc = pthread_cond_init(&cond, &condattr)))
400  LOG_ERR("pthread_cond_init returned %d", rc);
401 
402  pthread_attr_t attr;
403  pthread_attr_init(&attr);
404  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
405  pthread_t default_gateway_mac_logger_thread;
406  if (0 != (rc = pthread_create(&default_gateway_mac_logger_thread, &attr, &default_gateway_mac_logger, this)))
407  LOG_ERR("pthread_create returned %d", rc);
408  }
409 
410  ~DefaultGatewayMACLogger()
411  {
412  LOG_ENTRY_EXIT;
413  pthread_cond_destroy(&cond);
414  pthread_mutex_destroy(&mutex);
415  }
416 
417  static const int DEFAULT_GATEWAY_MAC_LOGGING_INTERVAL_SECONDS = 600;
418  bool signaled;
419  pthread_mutex_t mutex;
420  pthread_cond_t cond;
421 };
422 
423 #endif // ifndef ENABLE_XCAM_SUPPORT and XHB1 and XHC3
424 
425 static void detectDefaultInterfaceChange()
426 {
427  LOG_ENTRY_EXIT;
428  static std::string default_interface ("");
429  std::string old_default_interface = default_interface;
430  std::string gateway;
431  getDefaultInterface (default_interface, gateway);
432  if (old_default_interface != default_interface)
433  eventDefaultInterfaceChanged (old_default_interface, default_interface);
434 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
435  DefaultGatewayMACLogger::getInstance().signal();
436 #endif
437 }
438 
439 static void linkCallback(std::string args)
440 {
441  // Message Format: interface up/down/add/delete
442  LOG_INFO("Arguments received = %s", args.c_str());
443  std::vector<std::string> tokens;
444  if (split(args, ' ', tokens, 2) == false)
445  return;
446 
447  if (tokens[1] == "up")
448  eventInterfaceEnabledStatusChanged(tokens[0], true);
449  else if (tokens[1] == "down")
450  {
451  eventInterfaceEnabledStatusChanged(tokens[0], false);
452  detectDefaultInterfaceChange(); // needed as netlink events are not sent for ipv4 route deletes that occur implicitly when a physical interface goes down
453  }
454  else if (tokens[1] == "add")
455  eventInterfaceConnectionStatusChanged(tokens[0], true);
456  else if (tokens[1] == "delete")
457  eventInterfaceConnectionStatusChanged(tokens[0], false);
458 }
459 
460 static void addressCallback(std::string args)
461 {
462  // Message Format: add/delete ipv4/ipv6 interface address global/local
463  LOG_INFO("Arguments received = %s", args.c_str());
464  std::vector<std::string> tokens;
465  if (split(args, ' ', tokens, 5) == false)
466  return;
467 
468  if (tokens[4] != "global")
469  return; // we are only interested in global addresses
470 
471  // do not event any IPv4 addresses reserved for documentation
472  if (!(tokens[1] == "ipv4" && netSrvMgrUtiles::isIPv4AddressScopeDocumentation(tokens[3])))
473  eventInterfaceIPAddressStatusChanged(tokens[2], tokens[3], tokens[1] == "ipv6", tokens[0] == "add");
474 
475  if ((tokens[2].find(':') != std::string::npos) && (tokens[0] == "delete")) // virtual interface deleted
476  detectDefaultInterfaceChange(); // needed as netlink events are not sent for ipv4 route deletes that occur implicitly when a virtual interface goes down
477 }
478 
479 const int DEFAULT_PRIORITY = 1024;
480 const int MAX_DEFAULT_ROUTES_PER_INTERFACE = 20;
481 
482 static void defaultRouteCallback(std::string args)
483 {
484  // Message Format: family interface destinationip gatewayip preferred_src metric add/delete
485  LOG_INFO(" Arguments received = %s", args.c_str());
486  std::vector<std::string> tokens;
487  if (split(args, ' ', tokens, 7) == false)
488  return;
489 
490  detectDefaultInterfaceChange();
491 }
492 
493 #endif // ifdef ENABLE_NLMONITOR
494 
495 int main(int argc, char *argv[])
496 {
497  const char* debugConfigFile = NULL;
498  const char* configFilePath = NULL;
499  int itr=0;
500 #ifdef ENABLE_IARM
501  IARM_Result_t err = IARM_RESULT_IPCCORE_FAIL;
502 #endif
503  /* Signal handler */
504  signal (SIGHUP, NetworkMgr_SignalHandler);
505  signal (SIGINT, NetworkMgr_SignalHandler);
506  signal (SIGQUIT, NetworkMgr_SignalHandler);
507  signal (SIGTERM, NetworkMgr_SignalHandler);
508 
509  signal (SIGPIPE, SIG_IGN);
510 
511 
512  while (itr < argc)
513  {
514  if(strcmp(argv[itr],"--debugconfig")==0)
515  {
516  itr++;
517  if (itr < argc)
518  {
519  debugConfigFile = argv[itr];
520  }
521  else
522  {
523  break;
524  }
525  }
526 
527  if(strcmp(argv[itr],"--configFilePath")==0)
528  {
529  itr++;
530  if (itr < argc)
531  {
532  configFilePath = argv[itr];
533  memset(&configProp_FilePath,0,sizeof(configProp_FilePath));
534  strncpy(configProp_FilePath, configFilePath, sizeof(configProp_FilePath));
535  }
536  else
537  {
538  break;
539  }
540  }
541  itr++;
542  }
543 #ifdef ENABLE_IARM
544  err = IARM_Bus_Init(IARM_BUS_NM_SRV_MGR_NAME);
545  if(IARM_RESULT_SUCCESS != err)
546  {
547  //LOG("Error initializing IARM.. error code : %d\n",err);
548  return err;
549  }
550  err = IARM_Bus_Connect();
551  if(IARM_RESULT_SUCCESS != err)
552  {
553  //LOG("Error connecting to IARM.. error code : %d\n",err);
554  return err;
555  }
556 #endif
557 
558 #ifdef RDK_LOGGER_ENABLED
559  if(rdk_logger_init(debugConfigFile) == 0) b_rdk_logger_enabled = 1;
560  if(configFilePath) {
561  memset(&configProp_FilePath,0,sizeof(configProp_FilePath));
562  strncpy(configProp_FilePath, configFilePath, sizeof(configProp_FilePath));
563  }
564 #ifdef ENABLE_IARM
565  IARM_Bus_RegisterForLog(logCallback);
566 #endif
567 
568 #else
569  rdk_logger_init(debugConfigFile);
570 #endif
571 
572 
573 #ifdef INCLUDE_BREAKPAD
574 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
575  std::string minidump_path;
576  RFC_ParamData_t secValue = {0};
577  WDMP_STATUS status = getRFCParameter("SecureCoreFile", "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.SecDump.Enable", &secValue);
578  if (( WDMP_SUCCESS == status ) && ( 0 == strncmp(secValue.value, "false", 5)))
579  {
580  minidump_path = "/opt/minidumps";
581  }
582  else
583  {
584  minidump_path = "/opt/secure/minidumps";
585  }
586  google_breakpad::MinidumpDescriptor descriptor(minidump_path.c_str());
587  google_breakpad::ExceptionHandler eh(descriptor, NULL, breakpadDumpCallback, NULL, true, -1);
588 #else
589  sleep(1);
590  BreakPadWrapExceptionHandler eh;
591  eh = newBreakPadWrapExceptionHandler();
592 #endif
593 #endif
594 
595  if(false == read_ConfigProps()) {
596  confProp.wifiProps.max_timeout = MAX_TIME_OUT_PERIOD;
597 #ifdef ENABLE_LOST_FOUND
598  confProp.wifiProps.bEnableLostFound = false;
599  confProp.wifiProps.lnfRetryInSecs = MAX_TIME_OUT_PERIOD;
600  confProp.wifiProps.lnfStartInSecs = MAX_TIME_OUT_PERIOD;
601  STRCPY_S(confProp.wifiProps.authServerURL, sizeof(confProp.wifiProps.authServerURL), "http://localhost:50050/authService/getDeviceId");
602 #endif
603  }
604 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3) && !defined(XHV1)
605  Read_Telemetery_Param_File();
606 #endif
607 #ifdef ENABLE_IARM
608  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_getActiveInterface, getActiveInterface);
609  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_getNetworkInterfaces, getNetworkInterfaces);
610 #ifdef ENABLE_NLMONITOR
611  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_getInterfaceList, getInterfaceList);
612  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_getDefaultInterface, getDefaultInterface);
613 #endif // ifdef ENABLE_NLMONITOR
614  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_setDefaultInterface, setDefaultInterface);
615  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_isInterfaceEnabled, isInterfaceEnabled);
616  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_setInterfaceEnabled, setInterfaceEnabled);
617  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_getSTBip, getSTBip);
618  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_setIPSettings, setIPSettings);
619  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_getIPSettings, getIPSettings);
620  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_getSTBip_family, getSTBip_family);
621  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_isConnectedToInternet, isConnectedToInternet);
622  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_setConnectivityTestEndpoints, setConnectivityTestEndpoints);
623  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_isAvailable, isAvailable);
624 #ifdef ENABLE_STUN_CLIENT
625  IARM_Bus_RegisterCall(IARM_BUS_NETSRVMGR_API_getPublicIP, getPublicIP);
626 #endif
627  IARM_Bus_RegisterEventHandler(IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETWORK_MANAGER_EVENT_WIFI_INTERFACE_STATE, _eventHandler);
628 #endif
629 #ifdef ENABLE_SD_NOTIFY
630  sd_notifyf(0, "READY=1\n"
631  "STATUS=netsrvmgr is Successfully Initialized\n"
632  "MAINPID=%lu",
633  (unsigned long) getpid());
634 #endif
635  netSrvMgr_start();
636  netSrvMgr_Loop();
637 
638 }
639 
640 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
641 
642 bool isFeatureEnabled(const char* feature)
643 {
644  RFC_ParamData_t param = {0};
645  if (WDMP_SUCCESS != getRFCParameter("netsrvmgr", feature, &param))
646  {
647  LOG_ERR("getRFCParameter for %s failed.", feature);
648  return false;
649  }
650  LOG_INFO( "name = %s, type = %d, value = %s", param.name, param.type, param.value);
651  return (strcmp(param.value, "true") == 0);
652 }
653 
654 bool validate_interface_can_be_disabled (const char* interface)
655 {
656  if (isFeatureEnabled("Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.Network.AllowDisableDefaultNetwork.Enable"))
657  return true;
658 
659  char activeInterface[INTERFACE_SIZE];
660  if (!netSrvMgrUtiles::getRouteInterfaceType (activeInterface))
661  {
662  LOG_ERR("Cannot determine the active interface");
663  return false;
664  }
665  if (strcmp (interface, activeInterface) == 0)
666  {
667  LOG_ERR("Cannot disable the active interface '%s'", activeInterface);
668  return false;
669  }
670  return true;
671 }
672 
673 #ifdef USE_RDK_WIFI_HAL
674 
675 // pni_controller.service determines, enables and configures the interface to make active (wifi/ethernet)
676 static void launch_pni_controller ()
677 {
678  LOG_INFO( "systemctl restart pni_controller.service");
679  system("systemctl restart pni_controller.service");
680 }
681 
682 #endif // USE_RDK_WIFI_HAL
683 
684 #endif // ifndef ENABLE_XCAM_SUPPORT and XHB1 and XHC3
685 
686 void netSrvMgr_start()
687 {
688  LOG_ENTRY_EXIT;
689 
690 #ifdef ENABLE_NLMONITOR
691  NetLinkIfc* netifc = NetLinkIfc::get_instance();
692  netifc->addSubscriber(new FunctionSubscriber(NlType::link, linkCallback));
693  netifc->addSubscriber(new FunctionSubscriber(NlType::address, addressCallback));
694  netifc->addSubscriber(new FunctionSubscriber(NlType::dfltroute, defaultRouteCallback));
695  netifc->initialize();
696  netifc->run(false);
697 #endif
698 
699 #ifdef ENABLE_ROUTE_SUPPORT
700  RouteNetworkMgr::getInstance()->Start();
701 #endif
702 
703 #ifdef USE_RDK_WIFI_HAL
704  WiFiNetworkMgr::getInstance()->Init();
705 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
706  launch_pni_controller();
707 #else
708  WiFiNetworkMgr::getInstance()->setWifiEnabled (true); // enable WiFi by default for XCAMs
709 #endif // ifndef ENABLE_XCAM_SUPPORT and XHB1 and XHC3
710 #endif // USE_RDK_WIFI_HAL
711 
712 #ifdef USE_RDK_MOCA_HAL
713  MocaNetworkMgr::getInstance()->Start();
714 #endif
715 }
716 
717 void netSrvMgr_Loop()
718 {
719  time_t curr = 0;
720  while(1)
721  {
722  time(&curr);
723 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
724  printf("I-ARM NET-SRV-MGR: HeartBeat at %s\r\n", ctime(&curr));
725 #endif
726  sleep(60);
727  }
728 }
729 
730 
731 
732 #if 0
733 NetworkMedium* createNetworkMedium(NetworkMedium::NetworkType _type)
734 {
735  NetworkMedium* mMedium=NULL;
736 
737  if(_type==NetworkMedium::WIFI)
738  {
739  mMedium = new WiFiNetworkMgr(_type);
740  }
741 }
742 #endif
743 
744 
745 static bool read_ConfigProps()
746 {
747  LOG_ENTRY_EXIT;
748  bool status = false;
749  GKeyFile *key_file = NULL;
750  GError *error = NULL;
751  gsize length = 0;
752  gdouble double_value = 0;
753  guint group = 0, key = 0;
754  static char *ethIfName=NULL;
755 
756  if(configProp_FilePath[0] == '\0')
757  {
758  LOG_ERR("Failed to read NETSRVMGR Configuration file");
759  return false;
760  }
761 
762  key_file = g_key_file_new();
763 
764  if(!key_file) {
765  LOG_ERR("Failed to g_key_file_new()");
766  return false;
767  }
768 
769  if(!g_key_file_load_from_file(key_file, configProp_FilePath, G_KEY_FILE_KEEP_COMMENTS, &error))
770  {
771  LOG_ERR("Failed with \"%s\"", error->message);
772  return false;
773  }
774  else
775  {
776  gsize groups_id, num_keys;
777  gchar **groups = NULL, **keys = NULL, *value = NULL;
778  ethIfName=getenv("ETHERNET_INTERFACE");
779 
780  groups = g_key_file_get_groups(key_file, &groups_id);
781 
782  for(group = 0; group < groups_id; group++)
783  {
784  LOG_DBG("Group %u/%u: \t%s", group, groups_id - 1, groups[group]);
785  if(0 == strncasecmp(WIFI_CONFIG, groups[group], strlen(groups[group])))
786  {
787  keys = g_key_file_get_keys(key_file, groups[group], &num_keys, &error);
788  for(key = 0; key < num_keys; key++)
789  {
790  value = g_key_file_get_value(key_file, groups[group], keys[key], &error);
791  LOG_DBG("[ \t\tkey %u/%u: \t%s => %s]", key, num_keys - 1, keys[key], value);
792  if(0 == strncasecmp(MAX_TIMEOUT_ON_DISCONNECT, keys[key], strlen(keys[key])))
793  {
794  confProp.wifiProps.max_timeout = atoi(value);
795  }
796 #ifdef ENABLE_LOST_FOUND
797  if((0 == strncasecmp(ENABLE_LOST_FOUND_RUN, keys[key], strlen(keys[key]))) && (!netSrvMgrUtiles::checkInterfaceActive(ethIfName)))
798  {
799  confProp.wifiProps.bEnableLostFound = (atoi(value) == 0) ? false : true;
800  }
801  if(0 == strncasecmp(LAF_CONNECT_RETRY_INTERVAL, keys[key], strlen(keys[key])))
802  {
803  confProp.wifiProps.lnfRetryInSecs = atoi(value);
804  }
805  if(0 == strncasecmp(LAF_CONNECT_START_INTERVAL, keys[key], strlen(keys[key])))
806  {
807  confProp.wifiProps.lnfStartInSecs = atoi(value);
808  }
809  if(0 == strncasecmp(GET_AUTHTOKEN_URL, keys[key], strlen(keys[key]) ) )
810  {
811  STRCPY_S(confProp.wifiProps.getAuthTokenUrl, sizeof(confProp.wifiProps.getAuthTokenUrl), value);
812  }
813  if(0 == strncasecmp(GET_LFAT_URL, keys[key], strlen(keys[key]) ) )
814  {
815  STRCPY_S(confProp.wifiProps.getLfatUrl, sizeof(confProp.wifiProps.getLfatUrl), value);
816  }
817  if(0 == strncasecmp(SET_LFAT_URL, keys[key], strlen(keys[key]) ) )
818  {
819  STRCPY_S(confProp.wifiProps.setLfatUrl, sizeof(confProp.wifiProps.setLfatUrl), value);
820  }
821  if(0 == strncasecmp(LFAT_VERSION, keys[key], strlen(keys[key]) ) )
822  {
823  STRCPY_S(confProp.wifiProps.lfatVersion, sizeof(confProp.wifiProps.lfatVersion), value);
824  }
825  if(0 == strncasecmp(LFAT_TTL, keys[key], strlen(keys[key]) ) )
826  {
827  confProp.wifiProps.lfatTTL = atoi(value);
828  }
829  if(0 == strncasecmp(LAF_CONNECTION_RETRY, keys[key], strlen(keys[key]) ) )
830  {
831  confProp.wifiProps.lnfRetryCount = atoi(value);
832  }
833 #endif
834  if(0 == strncasecmp(AUTHSERVER_URL, keys[key], strlen(keys[key])))
835  {
836  STRCPY_S(confProp.wifiProps.authServerURL, sizeof(confProp.wifiProps.authServerURL), value);
837  }
838  if(0 == strncasecmp(DISABLE_WPS_XRE, keys[key], strlen(keys[key])))
839  {
840  confProp.wifiProps.disableWpsXRE = (atoi(value) == 0) ? false : true;
841  }
842  if(value) g_free(value);
843  }
844  if(keys) g_strfreev(keys);
845  }
846 #ifdef ENABLE_STUN_CLIENT
847  else if(0 == strncasecmp(STUN_CONFIG, groups[group], strlen(groups[group])))
848  {
849  keys = g_key_file_get_keys(key_file, groups[group], &num_keys, &error);
850  for(key = 0; key < num_keys; key++)
851  {
852  value = g_key_file_get_value(key_file, groups[group], keys[key], &error);
853 
854  LOG_DBG("[ \t\tkey %u/%u: \t%s => %s]", key, num_keys - 1, keys[key], value);
855 
856  if(0 == strncasecmp(STUN_SERVER, keys[key], strlen(keys[key])))
857  {
858  STRCPY_S(confProp.stunProps.server, sizeof(confProp.stunProps.server), value);
859  }
860  else if(0 == strncasecmp(STUN_PORT, keys[key], strlen(keys[key])))
861  {
862  confProp.stunProps.port = atoi(value);
863  }
864  else if(0 == strncasecmp(STUN_INTERFACE, keys[key], strlen(keys[key])))
865  {
866  STRCPY_S(confProp.stunProps.interface, sizeof(confProp.stunProps.interface), value);
867  }
868  else if(0 == strncasecmp(STUN_IPV6, keys[key], strlen(keys[key])))
869  {
870  confProp.stunProps.ipv6 = (atoi(value) == 0) ? false : true;
871  }
872  else if(0 == strncasecmp(STUN_BIND_TIMEOUT, keys[key], strlen(keys[key])))
873  {
874  confProp.stunProps.bind_timeout = atoi(value);
875  }
876  else if(0 == strncasecmp(STUN_CACHE_TIMEOUT, keys[key], strlen(keys[key])))
877  {
878  confProp.stunProps.cache_timeout = atoi(value);
879  }
880  if(value) g_free(value);
881  }
882  if(keys) g_strfreev(keys);
883 
884  if(!confProp.stunProps.bind_timeout)
885  confProp.stunProps.bind_timeout = STUN_DEFAULT_BIND_TIMEOUT;
886 
887  if(!confProp.stunProps.cache_timeout)
888  confProp.stunProps.cache_timeout = STUN_DEFAULT_CACHE_TIMEOUT;
889 
890  LOG_WARN("stun config: server=%s port=%u iface=%s ipv6=%u bind_timeout=%u cache_timeout=%u",
891  confProp.stunProps.server,
892  confProp.stunProps.port,
893  confProp.stunProps.interface,
894  confProp.stunProps.ipv6,
895  confProp.stunProps.bind_timeout,
896  confProp.stunProps.cache_timeout);
897  }
898 #endif
899  }
900  if(groups) g_strfreev(groups);
901  }
902  if(key_file) g_key_file_free(key_file);
903 
904  return true;
905 }
906 
907 /*Read Telemetry Parameter configurations*/
908 void Read_Telemetery_Param_File()
909 {
910  LOG_ENTRY_EXIT;
911  gchar *contents = NULL;
912  gsize length = 0;
913  GError *error = NULL;
914 
915  gboolean fstatus = g_file_get_contents ((const gchar *) TELEMETRY_LOGGING_PARAM_FILE, &contents, &length, &error);
916 
917  if(!fstatus) {
918  LOG_ERR("Failed to read \"%s\" file using g_file_get_contents() due to %s(%d)",
919  TELEMETRY_LOGGING_PARAM_FILE, error->message, error->code);
920  return;
921  }
922  else {
923  LOG_DBG("Successfully read \"%s\". The file Contents are \"%s\" with length (%d).", TELEMETRY_LOGGING_PARAM_FILE, contents, (int)length);
924  }
925 
926  if(contents) {
927  parse_telemetry_logging_configuration(contents);
928  g_free(contents);
929  }
930 }
931 
932 /*Print parameters in list*/
933 static void printf_list_info(GList *list)
934 {
935  if(!list) {
936  printf("Since list is NULL, Failed to print info.");
937  return;
938  }
939 
940  GList *iter = g_list_first(list);
941  while(iter)
942  {
943  LOG_INFO("Parameter Name : \"%s\"", (char *)iter->data);
944  iter = g_list_next(iter);
945  }
946 }
947 
948 
949 bool parse_telemetry_logging_configuration(gchar *string)
950 {
951  LOG_ENTRY_EXIT;
952 
953  if(NULL == string)
954  {
955  LOG_ERR("Failed due to NULL request buffer");
956  return false;
957  }
958 
959 #ifdef USE_RDK_WIFI_HAL
960  wifiParams_Tele_Period1.timePeriod = 0;
961  wifiParams_Tele_Period1.paramlist = NULL;
962 
963  update_telemetryParams_list(string, &wifiParams_Tele_Period1, (gchar *)T_PERIOD_1_INTERVAL, (gchar *)T_PERIOD_1_PARAMETER_LIST);
964 
965  wifiParams_Tele_Period2.timePeriod = 0;
966  wifiParams_Tele_Period2.paramlist = NULL;
967 
968  update_telemetryParams_list(string, &wifiParams_Tele_Period2, (gchar *)T_PERIOD_2_INTERVAL, (gchar *)T_PERIOD_2_PARAMETER_LIST);
969 
970 #endif // USE_RDK_WIFI_HAL
971 
972  return true;
973 }
974 
975 bool update_telemetryParams_list(gchar *input_buffer, telemetryParams *telemery_params, gchar *time_period_string, gchar *param_name_string)
976 {
977  cJSON *request_msg = NULL;
978 
979  LOG_ENTRY_EXIT;
980 
981  request_msg = cJSON_Parse(input_buffer);
982 
983  if (!request_msg)
984  {
985  LOG_ERR("Failed to parse json buffer with \"%s\"", cJSON_GetErrorPtr());
986  return false;
987  }
988  else
989  {
990  int item, arrSize = 0;
991  cJSON* param_item = NULL, *param_list_obj = NULL;
992 
993  telemery_params->timePeriod = cJSON_GetObjectItem(request_msg, time_period_string)->valueint;
994  param_list_obj = cJSON_GetObjectItem(request_msg, param_name_string);
995 
996  arrSize = cJSON_GetArraySize(param_list_obj);
997 
998  for ( item = 0; item < arrSize; item++) {
999  param_item = cJSON_GetArrayItem(param_list_obj, item);
1000  if(!param_item) {
1001  LOG_ERR("Failed in cJSON_GetArrayItem()");
1002  }
1003  else {
1004  telemery_params->paramlist = g_list_prepend(telemery_params->paramlist, g_strdup(param_item->valuestring));
1005  }
1006  }
1007  if(telemery_params->paramlist)
1008  telemery_params->paramlist = g_list_reverse(telemery_params->paramlist);
1009 
1010  cJSON_Delete(request_msg);
1011  }
1012 
1013  return true;
1014 }
1015 
1016 void teleParamList_free (gpointer val)
1017 {
1018  LOG_ENTRY_EXIT;
1019  if(val) {
1020  LOG_DBG("\"%s\"", (gchar *)val);
1021  g_free (val);
1022  }
1023 }
1024 
1025 #ifdef ENABLE_IARM
1026 
1027 IARM_Result_t getActiveInterface(void *arg)
1028 {
1029  LOG_ENTRY_EXIT;
1030  IARM_Result_t ret = IARM_RESULT_SUCCESS;
1031  char devName[INTERFACE_SIZE]={0};
1033  param->activeIface[0]='\0';
1035  {
1036  STRCPY_S(param->activeIface, sizeof(param->activeIface), devName);
1037  }
1038  else
1039  {
1040  LOG_ERR("No Route Found");
1042  {
1043  if(!netSrvMgrUtiles::readDevFile(devName))
1044  {
1045  LOG_ERR("Get Active interface type failed for %s", devName);
1046  }
1047  else
1048  {
1049  STRCPY_S(param->activeIface, sizeof(param->activeIface), devName);
1050  }
1051  }
1052  else
1053  {
1054  LOG_ERR(" No Active Interface.");
1055  }
1056  }
1057  LOG_INFO("Current Active Interface : [%s].", param->activeIface);
1058  LOG_INFO("TELEMETRY_NETWORK_MANAGER_ACTIVE_INTERFACE:%s", param->activeIface);
1059  return ret;
1060 }
1061 
1062 IARM_Result_t getNetworkInterfaces(void *arg)
1063 {
1064  LOG_ENTRY_EXIT;
1065  IARM_Result_t ret = IARM_RESULT_SUCCESS;
1066  char devName[INTERFACE_LIST]={0};
1068  param->allNetworkInterfaces[0]='\0';
1069  char count = netSrvMgrUtiles::getAllNetworkInterface(devName);
1070  if(count)
1071  g_stpcpy(param->allNetworkInterfaces,devName);
1072  else
1073  LOG_ERR("list of Network Interface is empty");
1074  param->interfaceCount=count;
1075  LOG_INFO("list of Network Interface : [%s]", param->allNetworkInterfaces);
1076  return ret;
1077 }
1078 
1079 void _eventHandler (const char *owner, IARM_EventId_t eventId, void *data, size_t len)
1080 {
1081  LOG_ENTRY_EXIT;
1082 
1083  if (strcmp (owner, IARM_BUS_NM_SRV_MGR_NAME) != 0)
1084  return;
1085 
1087 
1088  switch (eventId)
1089  {
1090 #ifdef USE_RDK_WIFI_HAL
1091  case IARM_BUS_NETWORK_MANAGER_EVENT_WIFI_INTERFACE_STATE:
1092  {
1093  WiFiNetworkMgr::getInstance()->setWifiEnabled (param->isInterfaceEnabled);
1094  break;
1095  }
1096 #endif // USE_RDK_WIFI_HAL
1097  default:
1098  break;
1099  }
1100 }
1101 
1102 #ifdef ENABLE_NLMONITOR
1103 
1104 IARM_Result_t getInterfaceList(void *arg)
1105 {
1106  LOG_ENTRY_EXIT;
1108  std::vector<iface_info> interfaces;
1109  NetLinkIfc::get_instance()->getInterfaces(interfaces);
1110  list->size = interfaces.size();
1111  if (list->size > (sizeof(list->interfaces)/sizeof(list->interfaces[0])))
1112  {
1113  LOG_INFO(" Size of list is larger than allocated size. Size returned = %d", list->size);
1114  return IARM_RESULT_IPCCORE_FAIL;
1115  }
1116  for (int i = 0; i < list->size; i++)
1117  {
1118  LOG_INFO("Before Copying name=%s, mac=%s, flags=0x%08x",
1119  interfaces[i].m_if_name.c_str(), interfaces[i].m_if_macaddr.c_str(), interfaces[i].m_if_flags);
1120  snprintf(list->interfaces[i].name, sizeof(list->interfaces[i].name), "%s", interfaces[i].m_if_name.c_str());
1121  snprintf(list->interfaces[i].mac, sizeof(list->interfaces[i].mac), "%s", interfaces[i].m_if_macaddr.c_str());
1122  list->interfaces[i].flags = interfaces[i].m_if_flags;
1123  LOG_INFO("name=%s, mac=%s, flags=0x%08x",
1124  list->interfaces[i].name, list->interfaces[i].mac, list->interfaces[i].flags);
1125  }
1126  return IARM_RESULT_SUCCESS;
1127 }
1128 
1129 IARM_Result_t getDefaultInterface(void *arg)
1130 {
1131  LOG_ENTRY_EXIT;
1133  std::string interface;
1134  std::string gateway;
1135  if (getDefaultInterface(interface, gateway))
1136  {
1137  snprintf(default_route->interface, sizeof(default_route->interface), "%s", interface.c_str());
1138  snprintf(default_route->gateway, sizeof(default_route->gateway), "%s", gateway.c_str());
1139  }
1140  else
1141  {
1142  memset(default_route, 0, sizeof(IARM_BUS_NetSrvMgr_DefaultRoute_t)); // default_route->interface[0] = '\0';
1143  }
1144  return IARM_RESULT_SUCCESS;
1145 }
1146 
1147 #endif // ifdef ENABLE_NLMONITOR
1148 
1149 IARM_Result_t setDefaultInterface(void *arg)
1150 {
1151  LOG_ENTRY_EXIT;
1153  return setDefaultInterface (param->setInterface, param->persist) ? IARM_RESULT_SUCCESS : IARM_RESULT_IPCCORE_FAIL;
1154 }
1155 
1156 IARM_Result_t isInterfaceEnabled(void *arg)
1157 {
1158  LOG_ENTRY_EXIT;
1160  return isInterfaceEnabled(param->setInterface, param->isInterfaceEnabled) ? IARM_RESULT_SUCCESS : IARM_RESULT_IPCCORE_FAIL;
1161 }
1162 
1163 // TODO - Fix HomeNetworkingService references to
1164 // - IARM_BUS_NETWORK_MANAGER_EVENT_SET_INTERFACE_ENABLED
1165 // - IARM_BUS_NETWORK_MANAGER_EVENT_SET_INTERFACE_CONTROL_PERSISTENCE
1166 IARM_Result_t setInterfaceEnabled(void *arg)
1167 {
1168  LOG_ENTRY_EXIT;
1170  return setInterfaceEnabled (param->setInterface, param->isInterfaceEnabled, param->persist) ? IARM_RESULT_SUCCESS : IARM_RESULT_IPCCORE_FAIL;
1171 }
1172 
1173 IARM_Result_t setIPSettings(void *arg)
1174 {
1175  LOG_ENTRY_EXIT;
1177  return setIPSettings (param) ? IARM_RESULT_SUCCESS : IARM_RESULT_IPCCORE_FAIL;
1178 }
1179 
1180 IARM_Result_t getIPSettings(void *arg)
1181 {
1182  LOG_ENTRY_EXIT;
1184  return getIPSettings (param) ? IARM_RESULT_SUCCESS : IARM_RESULT_IPCCORE_FAIL;
1185 }
1186 
1187 IARM_Result_t getSTBip(void *arg)
1188 {
1189  LOG_ENTRY_EXIT;
1190  IARM_Result_t ret = IARM_RESULT_SUCCESS;
1191  char stbip[MAX_IP_ADDRESS_LEN];
1192  bool isIpv6=false;
1194 
1195  if(netSrvMgrUtiles::getSTBip(stbip,&isIpv6))
1196  {
1197  STRCPY_S(param->activeIfaceIpaddr, sizeof(param->activeIfaceIpaddr), stbip);
1198  LOG_INFO("stb ipaddress : [%s]", stbip);
1199  }
1200  else
1201  LOG_ERR("stb ipaddress not found");
1202  return ret;
1203 }
1204 
1205 IARM_Result_t getSTBip_family(void *arg)
1206 {
1207  LOG_ENTRY_EXIT;
1208  IARM_Result_t ret = IARM_RESULT_SUCCESS;
1209  char stbip[MAX_IP_ADDRESS_LEN];
1211 
1212 
1213  if (netSrvMgrUtiles::getSTBip_family(stbip,param->ipfamily))
1214  {
1215  STRCPY_S(param->activeIfaceIpaddr, sizeof(param->activeIfaceIpaddr), stbip);
1216  LOG_INFO("stb ipaddress : [%s]", stbip);
1217  }
1218  else
1219  LOG_ERR("stb ipaddress not found");
1220  return ret;
1221 }
1222 
1223 IARM_Result_t isConnectedToInternet(void *arg)
1224 {
1225  LOG_ENTRY_EXIT;
1226  long timeout_ms = 2000; // using timeout = 2s ( < default IARM call timeout of 5s)
1227  LOG_INFO("test_connectivity: : BEGIN timeout = %ldms", timeout_ms);
1228  bool connectivity = test_connectivity(timeout_ms);
1229  LOG_INFO("test_connectivity: : %s", connectivity ? "PASS" : "FAIL");
1230  *((bool*) arg) = connectivity;
1231  return IARM_RESULT_SUCCESS;
1232 }
1233 
1234 IARM_Result_t setConnectivityTestEndpoints(void *arg)
1235 {
1236  LOG_ENTRY_EXIT;
1238  std::vector<std::string> endpoints(param->endpoints, param->endpoints + param->size);
1239  return set_connectivity_test_endpoints(endpoints) ? IARM_RESULT_SUCCESS : IARM_RESULT_IPCCORE_FAIL;
1240 }
1241 
1242 IARM_Result_t isAvailable(void *arg)
1243 {
1244  LOG_ENTRY_EXIT;
1245  LOG_INFO("[%s] IARM_BUS_NETSRVMGR_API_isAvailable is called", MODULE_NAME);
1246  return IARM_RESULT_SUCCESS;
1247 }
1248 #ifdef ENABLE_STUN_CLIENT
1249 IARM_Result_t getPublicIP(void *arg)
1250 {
1251  LOG_ENTRY_EXIT;
1253  return getPublicIP (param) ? IARM_RESULT_SUCCESS : IARM_RESULT_IPCCORE_FAIL;
1254 }
1255 #endif
1256 #endif // ENABLE_IARM
1257 
1258 
1259 #if !defined(ENABLE_XCAM_SUPPORT) && !defined(XHB1) && !defined(XHC3)
1260 
1261 /*
1262  * touches /tmp/<filename>
1263  * touches /opt/persistent/<filename> also if persist = true
1264  */
1265 static void mark(const char* filename, bool persist)
1266 {
1267  char fqn[64];
1268  snprintf (fqn, sizeof(fqn), "/tmp/%s", filename);
1269  FILE *fp = fopen(fqn, "w"); // TODO: not expecting errors but handle failure
1270  fclose(fp);
1271  if (persist)
1272  {
1273  snprintf (fqn, sizeof(fqn), "/opt/persistent/%s", filename);
1274  FILE *fp = fopen(fqn, "w"); // TODO: not expecting errors but handle failure
1275  fclose(fp);
1276  }
1277 }
1278 
1279 /*
1280  * removes /tmp/<filename>
1281  * removes /opt/persistent/<filename> also if persist = true
1282  */
1283 static void unmark(const char* filename, bool persist)
1284 {
1285  char fqn[64];
1286  snprintf (fqn, sizeof(fqn), "/tmp/%s", filename);
1287  remove (fqn);
1288  if (persist)
1289  {
1290  snprintf (fqn, sizeof(fqn), "/opt/persistent/%s", filename);
1291  remove (fqn);
1292  }
1293 }
1294 
1295 #ifdef ENABLE_NLMONITOR
1296 bool getDefaultInterface(std::string &interface, std::string &gateway)
1297 {
1298  LOG_ENTRY_EXIT;
1299 
1300  if (NetLinkIfc::get_instance()->getDefaultRoute(true, interface, gateway) || // ipv6 default route exists
1301  NetLinkIfc::get_instance()->getDefaultRoute(false, interface, gateway)) // ipv4 default route exists
1302  {
1303  LOG_INFO("default route interface = %s gateway = %s", interface.c_str(), gateway.c_str());
1304  return true;
1305  }
1306  else
1307  {
1308  LOG_INFO("no default route");
1309  interface.clear();
1310  gateway.clear();
1311  return false;
1312  }
1313 }
1314 #endif // ifdef ENABLE_NLMONITOR
1315 
1316 bool setDefaultInterface (const char* interface, bool persist)
1317 {
1318  LOG_ENTRY_EXIT;
1319  LOG_INFO("interface = [%s], persist = [%d]", interface, persist);
1320 
1321 #ifdef USE_RDK_WIFI_HAL
1322  if (strcmp (interface, "ETHERNET") == 0)
1323  {
1324  unmark("pni_wifi", persist); // remove marker file (if present) that says "WIFI is the preferred network interface"
1325  launch_pni_controller();
1326  return true;
1327  }
1328  else if (strcmp (interface, "WIFI") == 0)
1329  {
1330 #ifndef DISABLE_PNI
1331  const char* RFC_PNI_ENABLE = "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.PreferredNetworkInterface.Enable";
1332  if (isFeatureEnabled(RFC_PNI_ENABLE) == false)
1333  {
1334  LOG_ERR("failed. RFC %s is not set.", RFC_PNI_ENABLE);
1335  return false;
1336  }
1337  bool enabled;
1338  if (isInterfaceEnabled(interface, enabled) && !enabled) // even if this check is not done here, pni_controller will not use wifi if "/tmp/wifi_disallowed" exists
1339  {
1340  LOG_ERR("failed. interface [%s] is disabled", interface);
1341  return false;
1342  }
1343  mark("pni_wifi", persist); // touch marker file that says "WIFI is the preferred network interface"
1344  launch_pni_controller();
1345  return true;
1346 #else
1347  LOG_ERR("failed. Build configuration DISABLE_PNI is set");
1348  return false;
1349 #endif // DISABLE_PNI
1350  }
1351 #else
1352  if (strcmp (interface, "ETHERNET") == 0)
1353  {
1354  LOG_INFO("nothing to do. interface [%s] is always the default interface.", interface);
1355  return true;
1356  }
1357 #endif // #ifdef USE_RDK_WIFI_HAL
1358  else
1359  {
1360  LOG_ERR("failed. interface [%s] is invalid", interface);
1361  return false;
1362  }
1363 }
1364 
1365 bool isInterfaceEnabled(const char* interface, bool& enabled)
1366 {
1367  LOG_ENTRY_EXIT;
1368  LOG_INFO("interface = [%s]", interface);
1369 
1370  std::string interface_name;
1371  if (strcmp (interface, "ETHERNET") == 0)
1372  {
1373  interface_name = getenvOrDefault("ETHERNET_INTERFACE", "");
1374  }
1375 #ifdef USE_RDK_WIFI_HAL
1376  else if (strcmp (interface, "WIFI") == 0)
1377  {
1378  interface_name = getenvOrDefault("WIFI_INTERFACE", "");
1379  }
1380 #endif // USE_RDK_WIFI_HAL
1381  else
1382  {
1383  LOG_ERR("interface [%s] is invalid", interface);
1384  return false;
1385  }
1386 #ifdef ENABLE_NLMONITOR
1387  std::vector<iface_info> interfaces;
1388  NetLinkIfc::get_instance()->getInterfaces(interfaces);
1389  for (const auto& i : interfaces)
1390  {
1391  if (i.m_if_name == interface_name)
1392  {
1393  enabled = ((i.m_if_flags & IFF_UP) != 0);
1394  LOG_INFO("interface = [%s] enabled = [%d]", interface, enabled);
1395  return true;
1396  }
1397  }
1398 #endif // ifdef ENABLE_NLMONITOR
1399  LOG_ERR("interface = [%s] enabled = [NA]", interface);
1400  return false;
1401 }
1402 
1403 bool setInterfaceEnabled (const char* interface, bool enabled, bool persist)
1404 {
1405  LOG_ENTRY_EXIT;
1406  LOG_INFO("interface = [%s] enable = [%d] persist = [%d]", interface, enabled, persist);
1407 
1408 #ifndef USE_RDK_WIFI_HAL
1409  if (strcmp (interface, "ETHERNET") == 0)
1410  {
1411  if (enabled)
1412  {
1413  LOG_INFO("nothing to do. interface [%s] is always enabled", interface);
1414  return true;
1415  }
1416  else
1417  {
1418  LOG_ERR("failed. interface [%s] cannot be disabled", interface);
1419  return false;
1420  }
1421  }
1422 #else
1423  if (strcmp (interface, "ETHERNET") == 0)
1424  {
1425  if (enabled)
1426  {
1427  unmark("ethernet_disallowed", persist); // remove marker file (if present) that says "ETHERNET is disallowed"
1428  setInterfaceState (getenvOrDefault("ETHERNET_INTERFACE", ""), true);
1429  launch_pni_controller();
1430  return true;
1431  }
1432  else // if (validate_interface_can_be_disabled(interface)) not needed for ETHERNET as per clarification in ticket
1433  {
1434  mark("ethernet_disallowed", persist); // touch marker file that says "ETHERNET is disallowed"
1435  setInterfaceState (getenvOrDefault("ETHERNET_INTERFACE", ""), false);
1436  launch_pni_controller();
1437  return true;
1438  }
1439  }
1440  else if (strcmp (interface, "WIFI") == 0)
1441  {
1442  if (enabled)
1443  {
1444  unmark("wifi_disallowed", persist); // remove marker file (if present) that says "WIFI is disallowed"
1445  setInterfaceState (getenvOrDefault("WIFI_INTERFACE", ""), true);
1446  WiFiNetworkMgr::getInstance()->setWifiEnabled(true);
1447  launch_pni_controller();
1448  return true;
1449  }
1450  else if (validate_interface_can_be_disabled(interface))
1451  {
1452  mark("wifi_disallowed", persist); // touch marker file that says "WIFI is disallowed"
1453  setInterfaceState (getenvOrDefault("WIFI_INTERFACE", ""), false);
1454  WiFiNetworkMgr::getInstance()->setWifiEnabled(false);
1455  launch_pni_controller();
1456  return true;
1457  }
1458  else
1459  {
1460  LOG_ERR("failed. interface [%s] cannot be disabled.", interface);
1461  return false;
1462  }
1463  }
1464 #endif // ifndef USE_RDK_WIFI_HAL
1465  else
1466  {
1467  LOG_ERR("failed. interface [%s] is invalid.", interface);
1468  return false;
1469  }
1470 }
1471 
1472 bool getDNSip (const unsigned int family, char *primaryDNS, char *secondaryDNS)
1473 {
1474  LOG_ENTRY_EXIT;
1475  char* dns[2] = {primaryDNS, secondaryDNS};
1476  std::string line, keyword, value;
1477  unsigned char s[sizeof(struct in6_addr)];
1478  std::ifstream f("/etc/resolv.dnsmasq");
1479  if (!f.is_open())
1480  {
1481  LOG_ERR("DNS file is not present");
1482  return false;
1483  }
1484  for (int i = 0; i < 2 && std::getline (f, line); )
1485  {
1486  std::istringstream ss(line);
1487  ss >> keyword;
1488  if (keyword == "nameserver")
1489  {
1490  ss >> std::ws >> value;
1491  if (1 == inet_pton(family, value.c_str(), s))
1492  {
1493  STRCPY_S(dns[i++], INET6_ADDRSTRLEN, value.c_str());
1494  }
1495  }
1496  }
1497  f.close();
1498  return true;
1499 }
1500 
1501 static bool getDhcpServerIP()
1502 {
1503  std::string line;;
1504  std::ifstream f(NETSRVMGR_DHCP_SERVERIP_PATH);
1505  if (!f.is_open())
1506  {
1507  LOG_INFO("DHCP SERVER IP file is not present");
1508  return false;
1509  }
1510 
1511  std::getline (f, line);
1512  struct in_addr ipv4address;
1513  if (inet_pton(AF_INET, line.c_str(), &ipv4address) <= 0)
1514  {
1515  LOG_ERR("invalid ipaddress [%s]", line.c_str());
1516  f.close();
1517  return false;
1518  }
1519 
1520  gDhcpServerIP = line;
1521  f.close();
1522 
1523  return true;
1524 }
1525 
1526 // returns true if IP settings are the same, false otherwise
1527 bool ip_settings_compare(const IARM_BUS_NetSrvMgr_Iface_Settings_t& ip_settings1, const IARM_BUS_NetSrvMgr_Iface_Settings_t& ip_settings2)
1528 {
1529  LOG_ENTRY_EXIT;
1530  return 0 == strcmp(ip_settings1.ipaddress, ip_settings2.ipaddress) &&
1531  0 == strcmp(ip_settings1.netmask, ip_settings2.netmask) &&
1532  0 == strcmp(ip_settings1.gateway, ip_settings2.gateway) &&
1533  0 == strcmp(ip_settings1.primarydns, ip_settings2.primarydns) &&
1534  0 == strcmp(ip_settings1.secondarydns, ip_settings2.secondarydns);
1535 }
1536 
1537 bool ip_settings_file_read(const char* ip_settings_filename, IARM_BUS_NetSrvMgr_Iface_Settings_t& ip_settings)
1538 {
1539  LOG_ENTRY_EXIT;
1540  FILE *fp = fopen(ip_settings_filename, "r");
1541  if (fp == NULL)
1542  return false;
1543  char name_value_entry[512];
1544  while (NULL != fgets(name_value_entry, sizeof(name_value_entry), fp))
1545  {
1546  char* key = strtok (name_value_entry, "=\n");
1547  char* value = strtok (NULL, "=\n");
1548  if (0 == strcmp (key, "ipaddress"))
1549  snprintf(ip_settings.ipaddress, sizeof(ip_settings.ipaddress), "%s", value);
1550  else if (0 == strcmp (key, "netmask"))
1551  snprintf(ip_settings.netmask, sizeof(ip_settings.netmask), "%s", value);
1552  else if (0 == strcmp (key, "gateway"))
1553  snprintf(ip_settings.gateway, sizeof(ip_settings.gateway), "%s", value);
1554  else if (0 == strcmp (key, "primarydns"))
1555  snprintf(ip_settings.primarydns, sizeof(ip_settings.primarydns), "%s", value);
1556  else if (0 == strcmp (key, "secondarydns"))
1557  snprintf(ip_settings.secondarydns, sizeof(ip_settings.secondarydns), "%s", value);
1558  }
1559  fclose(fp);
1560  return true;
1561 }
1562 
1563 bool ip_settings_file_write(const char* ip_settings_filename, const IARM_BUS_NetSrvMgr_Iface_Settings_t& ip_settings)
1564 {
1565  LOG_ENTRY_EXIT;
1566  FILE *fp = fopen(ip_settings_filename, "w");
1567  if (fp == NULL)
1568  return false;
1569  fprintf(fp, "ipaddress=%s\nnetmask=%s\ngateway=%s\nprimarydns=%s\nsecondarydns=%s\n",
1570  ip_settings.ipaddress, ip_settings.netmask, ip_settings.gateway, ip_settings.primarydns, ip_settings.secondarydns);
1571  fclose(fp);
1572  return true;
1573 }
1574 
1575 // triggers reconfigure of given interface if it is the active interface, otherwise does nothing.
1576 void ipv4_reconfigure_interface (const char* interface)
1577 {
1578  LOG_ENTRY_EXIT;
1579  std::string default_interface;
1580  std::string default_gateway;
1581  if ( getDefaultInterface(default_interface, default_gateway) && (0 != strcmp(interface, default_interface.c_str())) )
1582  return;
1583  char command[128];
1584  snprintf (command, sizeof(command), "/lib/rdk/pni_controller.sh ipv4_reconfigure_interface %s", interface);
1585  LOG_INFO("Executing command [%s]", command);
1586  int status = system(command);
1587  LOG_INFO("Exit code [%d] from command [%s]", status, command);
1588 }
1589 
1590 bool valid_ipv4_netmask (uint32_t mask)
1591 {
1592  LOG_ENTRY_EXIT;
1593  if (mask == 0) // = 00000000 00000000 00000000 00000000 (invalid)
1594  return false;
1595  // example mask = 11111111 11111111 11111111 00000000 (255.255.255.0 valid IPv4 netmask = 1-bit string followed by 0-bit string, totaling 32 bits)
1596  uint32_t x = ~mask; // = 00000000 00000000 00000000 11111111 (bitwise NOT of valid IPv4 netmask = 0-bit string followed by 1-bit string, totaling 32 bits)
1597  uint32_t y = x + 1; // = 00000000 00000000 00000001 00000000 (add 1)
1598  return (x & y) == 0; // = 00000000 00000000 00000000 00000000 (bitwise AND of last 2 sequences = 0 for a valid IPv4 netmask)
1599 }
1600 
1601 bool setIPSettings(IARM_BUS_NetSrvMgr_Iface_Settings_t *param)
1602 {
1603  LOG_ENTRY_EXIT;
1604  LOG_INFO("interface [%s], ipversion [%s], autoconfig [%d], ipaddress [%s], netmask [%s], gateway [%s], primarydns [%s], secondarydns [%s]",
1605  param->interface, param->ipversion, param->autoconfig, param->ipaddress, param->netmask, param->gateway, param->primarydns, param->secondarydns);
1606 
1607  std:string secondarydns = param->secondarydns;
1608  const char* RFC_MANUALIP_ENABLE = "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.Network.ManualIPSettings.Enable";
1609 
1610  bool ethernet = true;
1611  if (0 == strcasecmp(param->interface, "WIFI"))
1612  {
1613  ethernet = false;
1614  }
1615  else if (0 != strcasecmp(param->interface, "ETHERNET"))
1616  {
1617  LOG_ERR("unsupported interface [%s]", param->interface);
1618  return false;
1619  }
1620 
1621  const char *interface = ethernet ? getenv("ETHERNET_INTERFACE") : getenv("WIFI_INTERFACE");
1622  if (interface == NULL)
1623  {
1624  LOG_ERR("failed to identify interface");
1625  return false;
1626  }
1627 
1628  const char* ip_settings_file = ethernet ? "/opt/persistent/ip.eth0.0" : "/opt/persistent/ip.wifi.0";
1629  bool autoconfig = ( access(ip_settings_file, F_OK) != 0 );
1630 
1631  LOG_INFO("interface: [%s], autoconfig: current [%d] requested [%d]", interface, autoconfig, param->autoconfig);
1632 
1633  if (param->autoconfig)
1634  {
1635  param->isSupported = true;
1636  if (autoconfig)
1637  {
1638  LOG_INFO("already in autoconfig mode.");
1639  return true;
1640  }
1641  else if (0 != remove(ip_settings_file))
1642  {
1643  LOG_ERR("remove(%s) returned errno %d (%s)", ip_settings_file, errno, strerror(errno));
1644  return false;
1645  }
1646  ipv4_reconfigure_interface (interface);
1647  return true;
1648  }
1649  else
1650  {
1651  if (isFeatureEnabled(RFC_MANUALIP_ENABLE) == false)
1652  {
1653  LOG_ERR("RFC for manual IP settings is not enabled");
1654  param->isSupported = false;
1655  return false;
1656  }
1657 
1658  if (0 != strcasecmp(param->ipversion, "ipv4"))
1659  {
1660  LOG_ERR("unsupported ipversion [%s]", param->ipversion);
1661  param->isSupported = false;
1662  return false;
1663  }
1664 
1665  struct in_addr ipv4address;
1666  if (!inet_pton(AF_INET, param->ipaddress, &ipv4address))
1667  {
1668  LOG_ERR("invalid ipaddress [%s]", param->ipaddress);
1669  return false;
1670  }
1671  if (!inet_pton(AF_INET, param->netmask, &ipv4address) || !valid_ipv4_netmask(ntohl(ipv4address.s_addr)))
1672  {
1673  LOG_ERR("invalid netmask [%s]", param->netmask);
1674  return false;
1675  }
1676  if (!inet_pton(AF_INET, param->gateway, &ipv4address))
1677  {
1678  LOG_ERR("invalid gateway [%s]", param->gateway);
1679  return false;
1680  }
1681  if (!inet_pton(AF_INET, param->primarydns, &ipv4address))
1682  {
1683  LOG_ERR("invalid primarydns [%s]", param->primarydns);
1684  return false;
1685  }
1686  if (!secondarydns.empty())
1687  {
1688  if (!inet_pton(AF_INET, param->secondarydns, &ipv4address))
1689  {
1690  LOG_ERR("invalid secondarydns [%s]", param->secondarydns);
1691  return false;
1692  }
1693  }
1694  IARM_BUS_NetSrvMgr_Iface_Settings_t current_ip_settings = {};
1695  if (!autoconfig && ip_settings_file_read(ip_settings_file, current_ip_settings) && ip_settings_compare(current_ip_settings, *param))
1696  {
1697  LOG_INFO("provided config is same as the current config");
1698  return true;
1699  }
1700  if (!ip_settings_file_write(ip_settings_file, *param))
1701  {
1702  LOG_ERR("failed to save the new config. enabling dhcp");
1703  remove(ip_settings_file);
1704  ipv4_reconfigure_interface (interface);
1705  return false;
1706  }
1707  ipv4_reconfigure_interface (interface);
1708  return true;
1709  }
1710 }
1711 
1712 bool getIPSettings(IARM_BUS_NetSrvMgr_Iface_Settings_t *param)
1713 {
1714  LOG_ENTRY_EXIT;
1715  bool is_ipv6=true;
1716  char interface[16] = {0};
1717  std::string inter;
1718  std::string gateway;
1719  char primaryDNSaddr[INET6_ADDRSTRLEN]={0};
1720  char secondaryDNSaddr[INET6_ADDRSTRLEN]={0};
1721 
1722  const char* RFC_MANUALIP_ENABLE = "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.Network.ManualIPSettings.Enable";
1723  if (isFeatureEnabled(RFC_MANUALIP_ENABLE) == false)
1724  {
1725  LOG_INFO("Manual IP settings RFC is disabled");
1726  }
1727  param->errCode = NETWORK_IPADDRESS_ACQUIRED;
1728  if (0 == strcasecmp (param->interface, "WIFI") )
1729  {
1730  char* c = getenv("WIFI_INTERFACE");
1731  snprintf (interface, sizeof(interface), "%s", c ? c : "");
1732  struct stat stat_buf;
1733  param->autoconfig = (access( "/opt/persistent/ip.wifi.0", F_OK ) != 0 ) ? true :(stat("/opt/persistent/ip.wifi.0", &stat_buf) == 0 ? stat_buf.st_size == 0 :false);
1734  }
1735  else if (0 == strcasecmp(param->interface, "ETHERNET"))
1736  {
1737  char* c = getenv("ETHERNET_INTERFACE");
1738  snprintf (interface, sizeof(interface), "%s", c ? c : "");
1739  struct stat stat_buf;
1740  param->autoconfig = (access( "/opt/persistent/ip.eth0.0", F_OK ) != 0 ) ? true :(stat("/opt/persistent/ip.eth0.0", &stat_buf) == 0 ? stat_buf.st_size == 0 :false);
1741  }
1742  //If interface param is not provided, use currently active interface
1743  else if (!netSrvMgrUtiles::currentActiveInterface(interface))
1744  {
1745  LOG_ERR("No routable interface found.");
1746  param->errCode = NETWORK_NO_ROUTE_INTERFACE;
1747  return false;
1748  }
1749  else if (0 == strcasecmp(interface, getenv("ETHERNET_INTERFACE")))
1750  {
1751  STRCPY_S(param->interface, sizeof(param->interface), "ETHERNET");
1752  struct stat stat_buf;
1753  param->autoconfig = (access( "/opt/persistent/ip.eth0.0", F_OK ) != 0 ) ? true :(stat("/opt/persistent/ip.eth0.0", &stat_buf) == 0 ? stat_buf.st_size == 0 :false);
1754 
1755  }
1756  else if (0 == strcasecmp(interface, getenv("WIFI_INTERFACE")))
1757  {
1758  STRCPY_S(param->interface, sizeof(param->interface), "WIFI");
1759  struct stat stat_buf;
1760  param->autoconfig = (access( "/opt/persistent/ip.wifi.0", F_OK ) != 0 ) ? true :(stat("/opt/persistent/ip.wifi.0", &stat_buf) == 0 ? stat_buf.st_size == 0 :false);
1761  }
1762  LOG_INFO("interface [%s]", interface);
1763 
1764  /*To get ipaddress based on interface and family input paramter*/
1765  if (strcasecmp (param->ipversion, "IPV6") == 0)
1766  {
1767  if(!netSrvMgrUtiles::getInterfaceConfig(interface, AF_INET6, param->ipaddress, param->netmask))
1768  {
1769  LOG_ERR("stb ipv6 ipaddress not found");
1770  param->errCode = NETWORK_IPADDRESS_NOTFOUND;
1771  return true;
1772  }
1773  }
1774  else if (strcasecmp (param->ipversion, "IPV4") == 0)
1775  {
1776  is_ipv6=false;
1777  if(!netSrvMgrUtiles::getInterfaceConfig(interface, AF_INET, param->ipaddress, param->netmask))
1778  {
1779  LOG_ERR("stb ipv4 ipaddress not found.");
1780  param->errCode = NETWORK_IPADDRESS_NOTFOUND;
1781  return true;
1782  }
1783  }
1784  else if (netSrvMgrUtiles::getInterfaceConfig(interface, AF_INET6, param->ipaddress, param->netmask))
1785  {
1786  STRCPY_S(param->ipversion, sizeof(param->ipversion), "IPV6");
1787  }
1788  else if (netSrvMgrUtiles::getInterfaceConfig(interface, AF_INET, param->ipaddress, param->netmask))
1789  {
1790  STRCPY_S(param->ipversion, sizeof(param->ipversion), "IPV4");
1791  is_ipv6=false;
1792  }
1793  else
1794  {
1795  LOG_ERR("stb ipaddress not found");
1796  param->errCode = NETWORK_IPADDRESS_NOTFOUND;
1797  return true;
1798  }
1799 
1800  /* ipv4/ ipv6 default route depends on is_ipv6 flag */
1801  if(NetLinkIfc::get_instance()->getDefaultRoute(is_ipv6, inter, gateway))
1802  {
1803  snprintf(param->gateway, sizeof(param->gateway), "%s", gateway.c_str());
1804  LOG_INFO("Default Gateway [%s]", param->gateway);
1805  }
1806  else
1807  {
1808  LOG_INFO("Default Gateway not present ");
1809  param->errCode = NETWORK_NO_DEFAULT_ROUTE;
1810  }
1811 
1812  /* To DHCP Server IP */
1813  if ((param->autoconfig) && (!is_ipv6))
1814  {
1815  snprintf(param->dhcp_server, sizeof(param->dhcp_server), "%s", gDhcpServerIP.c_str());
1816  }
1817  else
1818  {
1819  snprintf(param->dhcp_server, sizeof(param->dhcp_server), "");
1820  }
1821  LOG_INFO("DHCP Server IP Address [%s]", param->dhcp_server);
1822 
1823  /* To get Primary and Secondary DNS */
1824  if (getDNSip(is_ipv6 ? AF_INET6 : AF_INET,primaryDNSaddr, secondaryDNSaddr))
1825  {
1826  STRCPY_S(param->primarydns, sizeof(param->primarydns), primaryDNSaddr);
1827  STRCPY_S(param->secondarydns, sizeof(param->secondarydns), secondaryDNSaddr);
1828  LOG_INFO("Primary DNS %s", param->primarydns);
1829  LOG_INFO("Secondary DNS %s", param->secondarydns);
1830  }
1831  else
1832  {
1833  LOG_INFO("No DNS ip is confiured");
1834  param->errCode = NETWORK_DNS_NOT_CONFIGURED; //DNS file is not present
1835  }
1836  return true;
1837 }
1838 
1839 bool setInterfaceState (std::string interface_name, bool enabled)
1840 {
1841  if (interface_name.empty())
1842  {
1843  LOG_ERR("no interface name");
1844  return false;
1845  }
1846  char command[64];
1847  snprintf (command, sizeof(command), "ip link set dev %s %s", interface_name.c_str(), enabled ? "up" : "down");
1848  LOG_INFO("%s", command);
1849  system (command);
1850  return true;
1851 }
1852 
1853 #ifdef ENABLE_STUN_CLIENT
1854 bool getPublicIP (IARM_BUS_NetSrvMgr_Iface_StunRequest_t* param)
1855 {
1856  std::string host (param->server[0] ? param->server : confProp.stunProps.server);
1857  uint16_t port (param->port ? param->port : confProp.stunProps.port);
1858  stun::protocol proto (param->ipv6 ? stun::protocol::af_inet6 : stun::protocol::af_inet);
1859  uint16_t bindtm (param->bind_timeout ? param->bind_timeout : confProp.stunProps.bind_timeout);
1860  uint16_t cachetm (param->cache_timeout ? param->cache_timeout : confProp.stunProps.cache_timeout);
1861  std:string interface = param->interface;
1862  char activeInterface[INTERFACE_SIZE];
1863 
1864  long timeout_ms = 2000; // using timeout = 2s ( < default IARM call timeout of 5s)
1865  LOG_DBG("BEGIN timeout = %ldms", timeout_ms);
1866  bool connectivity = (test_connectivity(timeout_ms) > 0);
1867  if (!connectivity)
1868  {
1869  LOG_ERR("testConnectivity failed: internet not available");
1870  return false;
1871  }
1872 
1873  if (0 == strcasecmp(param->interface, "WIFI"))
1874  {
1875  interface = getenvOrDefault("WIFI_INTERFACE", "");
1876  }
1877  else if (0 == strcasecmp(param->interface, "ETHERNET"))
1878  {
1879  interface = getenvOrDefault("ETHERNET_INTERFACE", "");
1880  }
1881  else if (0 == strcasecmp(param->interface, "MOCA"))
1882  {
1883  interface = getenvOrDefault("MOCA_INTERFACE", "");
1884  }
1885  else if (interface.empty())
1886  {
1887  if(!netSrvMgrUtiles::getRouteInterface(activeInterface))
1888  {
1889  if(!netSrvMgrUtiles::currentActiveInterface(activeInterface))
1890  {
1891  LOG_ERR("No routable interface found");
1892  return false;
1893  }
1894  }
1895  interface = activeInterface;
1896  }
1897  else
1898  {
1899  LOG_ERR("failed to identify interface");
1900  return false;
1901  }
1902 
1903  LOG_INFO("interface value: %s", interface.c_str());
1904  std::string iface (param->interface[0] ? interface : confProp.stunProps.interface);
1905 
1906  stun::bind_result result;
1907  if(stunClient.bind(host, port, iface, proto, bindtm, cachetm, result))
1908  {
1909  strncpy(param->public_ip, result.public_ip.c_str(), MAX_IP_ADDRESS_LEN);
1910  return true;
1911  }
1912  else
1913  {
1914  return false;
1915  }
1916 }
1917 #endif
1918 
1919 #endif // ifndef ENABLE_XCAM_SUPPORT and XHB1 and XHC3
getDNSip
bool getDNSip(const unsigned int family, char *primaryDNS, char *secondaryDNS)
This function is used to get Interface IP address and on which interface.
Definition: netSrvMgrMain.cpp:1472
IARM_BUS_NetSrvMgr_Iface_TestEndpoints_t
Definition: netsrvmgrIarm.h:164
netsrvmgrIarm.h
The header file provides components netSrvMgrIarm information APIs.
getenvOrDefault
char * getenvOrDefault(const char *name, char *defaultValue)
Definition: hostIf_utils.cpp:404
netSrvMgrUtiles::checkInterfaceActive
bool checkInterfaceActive(char *interfaceName)
This function returns the Ethernet active status of the interface, if finds the status from interface...
Definition: netsrvmgrUtiles.cpp:409
WiFiNetworkMgr
Definition: wifiSrvMgr.h:29
IARM_BUS_NetSrvMgr_Iface_EventDefaultInterface_t
Definition: netsrvmgrIarm.h:159
IARM_BUS_NetSrvMgr_Iface_EventInterfaceIPAddress_t
Definition: netsrvmgrIarm.h:152
netSrvMgrUtiles::getSTBip
bool getSTBip(char *stbip, bool *isIpv6)
This function is used to get STB IP address and its IP version.
Definition: netsrvmgrUtiles.cpp:535
_netMgrConfigProps
Definition: NetworkMgrMain.h:141
netSrvMgrUtiles::getAllNetworkInterface
char getAllNetworkInterface(char *devAllInterface)
This function parse all the device interface details and gives all the network interface device name ...
Definition: netsrvmgrUtiles.cpp:349
netSrvMgrUtiles::getInterfaceConfig
bool getInterfaceConfig(const char *ifName, const unsigned int family, char *interfaceIp, char *netMask)
This function is used to get Interface IP address and on which interface.
Definition: netsrvmgrUtiles.cpp:481
IARM_BUS_NetSrvMgr_InterfaceList_t
Definition: netsrvmgrIarm.h:134
IARM_Bus_RegisterEventHandler
IARM_Result_t IARM_Bus_RegisterEventHandler(const char *ownerName, IARM_EventId_t eventId, IARM_EventHandler_t handler)
This API register to listen to event and provide the callback function for event notification....
Definition: iarmMgrMocks.cpp:43
stun::client
Definition: StunClient.h:145
readDevFile
gboolean readDevFile(const char *deviceFile)
This function is used to get partner ID.
Definition: xcal-device-library.c:385
IARM_Bus_RegisterCall
IARM_Result_t IARM_Bus_RegisterCall(const char *methodName, IARM_BusCall_t handler)
This API is used to register an RPC method that can be invoked by other applications.
netsrvmgrUtiles.h
The header file provides components netSrvMgrUtiles information APIs.
stun::bind_result
Definition: StunClient.h:138
netSrvMgrUtiles::getRouteInterfaceType
bool getRouteInterfaceType(char *devname)
This function gets the active interface device type(Ethernet/MOCA/WIFI).
Definition: netsrvmgrUtiles.cpp:272
IARM_Bus_BroadcastEvent
IARM_Result_t IARM_Bus_BroadcastEvent(const char *ownerName, IARM_EventId_t eventId, void *data, size_t len)
This API is used to publish an Asynchronous event to all IARM client registered for this perticular e...
netSrvMgrUtiles::isIPv4AddressScopeDocumentation
bool isIPv4AddressScopeDocumentation(const std::string &ipv4_address)
This function checks if the input ipv4 address is a unicast address reserved for documentation.
Definition: netsrvmgrUtiles.cpp:803
NetworkMedium
Definition: NetworkMedium.h:24
netSrvMgrUtiles::currentActiveInterface
bool currentActiveInterface(char *currentInterface)
This function is used to get the current active interface(WIFI/MOCA).
Definition: netsrvmgrUtiles.cpp:656
IARM_BUS_NetSrvMgr_Iface_Settings_t
Definition: netsrvmgrIarm.h:114
IARM_BUS_NetSrvMgr_Iface_EventInterfaceStatus_t
Definition: netsrvmgrIarm.h:144
LOG_INFO
#define LOG_INFO(AAMP_JS_OBJECT, FORMAT,...)
Definition: jsutils.h:39
IARM_BUS_NetSrvMgr_DefaultRoute_t
Definition: netsrvmgrIarm.h:139
IARM_Bus_Connect
IARM_Result_t IARM_Bus_Connect(void)
This API is used to connect application to the IARM bus daemon. After connected, the application can ...
Definition: iarmMgrMocks.cpp:33
_IARM_BUS_NetSrvMgr_Iface_EventData_t
IARM Bus struct contains active streaming interface, origional definition present in homenetworkingse...
Definition: priv_aamp.cpp:193
IARM_BUS_NetSrvMgr_Iface_StunRequest_t
Definition: netsrvmgrIarm.h:170
netSrvMgrUtiles::getRouteInterface
bool getRouteInterface(char *devname)
This function retrieves information about the active routing interface.
Definition: netsrvmgrUtiles.cpp:263
telemetryParams
Definition: NetworkMgrMain.h:98
rdk_logger_init
rdk_Error rdk_logger_init(const char *debugConfigFile)
Initialize the logger. Sets up the environment variable storage by parsing debug configuration file t...
Definition: rdk_logger_init.c:57
IARM_Bus_Init
IARM_Result_t IARM_Bus_Init(const char *name)
This API is used to initialize the IARM-Bus library.
Definition: iarmMgrMocks.cpp:38