[IOT-1671] Fixed base layer terminate logic
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / ip_adapter / tizen / caipnwmonitor.c
1 /******************************************************************
2 *
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
4 *
5 *
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
21 #include <sys/types.h>
22 #include <ifaddrs.h>
23 #include <net/if.h>
24 #include <sys/socket.h>
25 #include <netdb.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <sys/ioctl.h>
30 #include <linux/netlink.h>
31 #include <linux/rtnetlink.h>
32 #include <arpa/inet.h>
33 #include <netinet/in.h>
34 #include <wifi.h>
35 #include <net_connection.h>
36
37 #include "caipinterface.h"
38 #include "caipnwmonitor.h"
39 #include "caadapterutils.h"
40 #include "logger.h"
41 #include "oic_malloc.h"
42 #include "oic_string.h"
43 #include <coap/utlist.h>
44
45 #define TAG "OIC_CA_IP_MONITOR"
46
47 #define NETLINK_MESSAGE_LENGTH  (4096)
48 #define IFC_LABEL_LOOP          "lo"
49 #define IFC_ADDR_LOOP_IPV4      "127.0.0.1"
50 #define IFC_ADDR_LOOP_IPV6      "::1"
51
52 /**
53  * Used to storing a connection handle for managing data connections.
54  */
55 static connection_h connection = NULL;
56
57 /**
58  * Used to storing adapter changes callback interface.
59  */
60 static struct CAIPCBData_t *g_adapterCallbackList = NULL;
61
62 /**
63  * Create new interface item.
64  */
65 static CAInterface_t *CANewInterfaceItem(int index, char *name, int family,
66                                          const char *addr, int flags);
67
68 /**
69  * Add new network interface in list.
70  */
71 static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
72                                      char *name, int family, const char *addr, int flags);
73
74 /**
75  * Pass the changed network status through the stored callback.
76  */
77 static void CAIPPassNetworkChangesToAdapter(CANetworkStatus_t status);
78
79 /**
80  * Callback function to received connection state changes.
81  */
82 static void CAIPConnectionStateChangedCb(connection_type_e type, void* userData);
83
84 int CAGetPollingInterval(int interval)
85 {
86     return interval;
87 }
88
89 static void CAIPPassNetworkChangesToAdapter(CANetworkStatus_t status)
90 {
91     CAIPCBData_t *cbitem = NULL;
92     LL_FOREACH(g_adapterCallbackList, cbitem)
93     {
94         if (cbitem && cbitem->adapter)
95         {
96             cbitem->callback(cbitem->adapter, status);
97         }
98     }
99 }
100
101 CAResult_t CAIPSetNetworkMonitorCallback(CAIPAdapterStateChangeCallback callback,
102                                          CATransportAdapter_t adapter)
103 {
104     if (!callback)
105     {
106         OIC_LOG(ERROR, TAG, "callback is null");
107         return CA_STATUS_INVALID_PARAM;
108     }
109
110     CAIPCBData_t *cbitem = NULL;
111     LL_FOREACH(g_adapterCallbackList, cbitem)
112     {
113         if (cbitem && adapter == cbitem->adapter && callback == cbitem->callback)
114         {
115             OIC_LOG(DEBUG, TAG, "this callback is already added");
116             return CA_STATUS_OK;
117         }
118     }
119
120     cbitem = (CAIPCBData_t *)OICCalloc(1, sizeof(*cbitem));
121     if (!cbitem)
122     {
123         OIC_LOG(ERROR, TAG, "Malloc failed");
124         return CA_STATUS_FAILED;
125     }
126
127     cbitem->adapter = adapter;
128     cbitem->callback = callback;
129     LL_APPEND(g_adapterCallbackList, cbitem);
130
131     return CA_STATUS_OK;
132 }
133
134 CAResult_t CAIPUnSetNetworkMonitorCallback(CATransportAdapter_t adapter)
135 {
136     CAIPCBData_t *cbitem = NULL;
137     CAIPCBData_t *tmpCbitem = NULL;
138     LL_FOREACH_SAFE(g_adapterCallbackList, cbitem, tmpCbitem)
139     {
140         if (cbitem && adapter == cbitem->adapter)
141         {
142             OIC_LOG(DEBUG, TAG, "remove specific callback");
143             LL_DELETE(g_adapterCallbackList, cbitem);
144             OICFree(cbitem);
145             return CA_STATUS_OK;
146         }
147     }
148     return CA_STATUS_OK;
149 }
150
151 u_arraylist_t *CAFindInterfaceChange()
152 {
153     u_arraylist_t *iflist = NULL;
154     char buf[NETLINK_MESSAGE_LENGTH] = { 0 };
155     struct sockaddr_nl sa = { 0 };
156     struct iovec iov = { .iov_base = buf,
157                          .iov_len = sizeof (buf) };
158     struct msghdr msg = { .msg_name = (void *)&sa,
159                           .msg_namelen = sizeof (sa),
160                           .msg_iov = &iov,
161                           .msg_iovlen = 1 };
162
163     ssize_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0);
164
165     for (struct nlmsghdr *nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len))
166     {
167         if (nh != NULL && nh->nlmsg_type != RTM_NEWLINK)
168         {
169             continue;
170         }
171         struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh);
172
173         if ((!ifi || (ifi->ifi_flags & IFF_LOOPBACK) || !(ifi->ifi_flags & IFF_RUNNING)))
174         {
175             continue;
176         }
177
178         int ifiIndex = ifi->ifi_index;
179
180         iflist = CAIPGetInterfaceInformation(ifiIndex);
181
182         if (!iflist)
183         {
184             OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
185             return NULL;
186         }
187     }
188     return iflist;
189 }
190
191 CAResult_t CAIPStartNetworkMonitor(CAIPAdapterStateChangeCallback callback,
192                                    CATransportAdapter_t adapter)
193 {
194     if (!g_adapterCallbackList)
195     {
196         // Initialize Wifi service.
197         if (WIFI_ERROR_NONE != wifi_initialize())
198         {
199             OIC_LOG(ERROR, TAG, "wifi_initialize failed");
200         }
201
202         // Initialize Connections.
203         connection_error_e ret = connection_create(&connection);
204         if (CONNECTION_ERROR_NONE != ret)
205         {
206             OIC_LOG(ERROR, TAG, "connection_create failed");
207             return CA_STATUS_FAILED;
208         }
209
210         // Set callback for receiving state changes.
211         ret = connection_set_type_changed_cb(connection, CAIPConnectionStateChangedCb, NULL);
212         if (CONNECTION_ERROR_NONE != ret)
213         {
214             OIC_LOG(ERROR, TAG, "connection_set_type_changed_cb failed");
215             return CA_STATUS_FAILED;
216         }
217     }
218
219     OIC_LOG(DEBUG, TAG, "Initialize network monitoring successfully");
220     return CAIPSetNetworkMonitorCallback(callback, adapter);
221 }
222
223 CAResult_t CAIPStopNetworkMonitor(CATransportAdapter_t adapter)
224 {
225     OIC_LOG(DEBUG, TAG, "IN");
226
227     CAIPUnSetNetworkMonitorCallback(adapter);
228     if (!g_adapterCallbackList)
229     {
230         // Deinitialize Wifi service.
231         if (WIFI_ERROR_NONE != wifi_deinitialize())
232         {
233             OIC_LOG(ERROR, TAG, "wifi_deinitialize failed");
234         }
235
236         // Reset callback for receiving state changes.
237         if (connection)
238         {
239             connection_error_e ret = connection_unset_type_changed_cb(connection);
240             if (CONNECTION_ERROR_NONE != ret)
241             {
242                 OIC_LOG(ERROR, TAG, "connection_unset_type_changed_cb failed");
243             }
244
245             // Deinitialize Wifi service.
246             ret = connection_destroy(connection);
247             if (CONNECTION_ERROR_NONE != ret)
248             {
249                 OIC_LOG(ERROR, TAG, "connection_destroy failed");
250             }
251             connection = NULL;
252         }
253     }
254
255     OIC_LOG(DEBUG, TAG, "Network monitoring terminated successfully");
256     return CA_STATUS_OK;
257 }
258
259 /**
260  * Used to send netlink query to kernel and recv response from kernel.
261  *
262  * @param[in]   idx       desired network interface index, 0 means all interfaces.
263  * @param[out]  iflist    linked list.
264  *
265  */
266 static bool CAIPGetAddrInfo(int idx, u_arraylist_t *iflist)
267 {
268     if ((idx < 0) || (iflist == NULL))
269     {
270         return false;
271     }
272
273     struct ifaddrs *ifp = NULL;
274     if (-1 == getifaddrs(&ifp))
275     {
276         OIC_LOG_V(ERROR, TAG, "Failed to get ifaddrs: %s", strerror(errno));
277         return false;
278     }
279
280     struct ifaddrs *ifa = NULL;
281     for (ifa = ifp; ifa; ifa = ifa->ifa_next)
282     {
283         if (!ifa->ifa_addr)
284         {
285             continue;
286         }
287
288         int family = ifa->ifa_addr->sa_family;
289         if ((ifa->ifa_flags & IFF_LOOPBACK) || (AF_INET != family && AF_INET6 != family))
290         {
291             continue;
292         }
293
294         int ifindex = if_nametoindex(ifa->ifa_name);
295         if (idx && (ifindex != idx))
296         {
297             continue;
298         }
299
300         char ipaddr[MAX_ADDR_STR_SIZE_CA] = {0};
301         if (family == AF_INET6)
302         {
303             struct sockaddr_in6 *in6 = (struct sockaddr_in6*) ifa->ifa_addr;
304             inet_ntop(family, (void *)&(in6->sin6_addr), ipaddr, sizeof(ipaddr));
305         }
306         else if (family == AF_INET)
307         {
308             struct sockaddr_in *in = (struct sockaddr_in*) ifa->ifa_addr;
309             inet_ntop(family, (void *)&(in->sin_addr), ipaddr, sizeof(ipaddr));
310         }
311
312         if ((strcmp(ipaddr, IFC_ADDR_LOOP_IPV4) == 0) ||
313             (strcmp(ipaddr, IFC_ADDR_LOOP_IPV6) == 0) ||
314             (strcmp(ifa->ifa_name, IFC_LABEL_LOOP) == 0))
315         {
316             OIC_LOG(DEBUG, TAG, "LOOPBACK continue!!!");
317             continue;
318         }
319
320         CAResult_t result = CAAddInterfaceItem(iflist, ifindex,
321                                                ifa->ifa_name, family,
322                                                ipaddr, ifa->ifa_flags);
323         if (CA_STATUS_OK != result)
324         {
325             OIC_LOG(ERROR, TAG, "CAAddInterfaceItem fail");
326             goto exit;
327         }
328     }
329     freeifaddrs(ifp);
330     return true;
331
332 exit:
333     freeifaddrs(ifp);
334     return false;
335 }
336
337 u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
338 {
339     u_arraylist_t *iflist = u_arraylist_create();
340     if (!iflist)
341     {
342         OIC_LOG_V(ERROR, TAG, "Failed to create iflist: %s", strerror(errno));
343         return NULL;
344     }
345
346     if (!CAIPGetAddrInfo(desiredIndex, iflist))
347     {
348         goto exit;
349     }
350
351     return iflist;
352
353 exit:
354     u_arraylist_destroy(iflist);
355     return NULL;
356 }
357
358 static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
359                                      char *name, int family, const char *addr, int flags)
360 {
361     CAInterface_t *ifitem = CANewInterfaceItem(index, name, family, addr, flags);
362     if (!ifitem)
363     {
364         return CA_STATUS_FAILED;
365     }
366     bool result = u_arraylist_add(iflist, ifitem);
367     if (!result)
368     {
369         OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
370         OICFree(ifitem);
371         return CA_STATUS_FAILED;
372     }
373
374     return CA_STATUS_OK;
375 }
376
377 static CAInterface_t *CANewInterfaceItem(int index, char *name, int family,
378                                          const char *addr, int flags)
379 {
380     CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof (CAInterface_t));
381     if (!ifitem)
382     {
383         OIC_LOG(ERROR, TAG, "Malloc failed");
384         return NULL;
385     }
386
387     OICStrcpy(ifitem->name, INTERFACE_NAME_MAX, name);
388     ifitem->index = index;
389     ifitem->family = family;
390     OICStrcpy(ifitem->addr, sizeof(ifitem->addr), addr);
391     ifitem->flags = flags;
392
393     return ifitem;
394 }
395
396 void CAIPConnectionStateChangedCb(connection_type_e type, void* userData)
397 {
398     switch (type)
399     {
400         case CONNECTION_TYPE_DISCONNECTED:
401             OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_DISCONNECTED");
402             CAIPPassNetworkChangesToAdapter(CA_INTERFACE_DOWN);
403             break;
404         case CONNECTION_TYPE_ETHERNET:
405             OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_ETHERNET");
406             CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
407             break;
408         case CONNECTION_TYPE_WIFI:
409             OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_WIFI");
410             CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
411             break;
412         case CONNECTION_TYPE_CELLULAR:
413             OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_CELLULAR");
414             CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
415             break;
416         default:
417             break;
418     }
419 }