[Tizen]change flag which used for detect ip changed
[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_DELADDR && nh->nlmsg_type != RTM_NEWADDR))
168         {
169             continue;
170         }
171         struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh);
172         if (!ifi)
173         {
174             continue;
175         }
176
177         int ifiIndex = ifi->ifi_index;
178
179         iflist = CAIPGetInterfaceInformation(ifiIndex);
180         if (!iflist)
181         {
182             OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
183             return NULL;
184         }
185     }
186     return iflist;
187 }
188
189 CAResult_t CAIPStartNetworkMonitor(CAIPAdapterStateChangeCallback callback,
190                                    CATransportAdapter_t adapter)
191 {
192     if (!g_adapterCallbackList)
193     {
194         // Initialize Wifi service.
195         if (WIFI_ERROR_NONE != wifi_initialize())
196         {
197             OIC_LOG(ERROR, TAG, "wifi_initialize failed");
198         }
199
200         // Initialize Connections.
201         connection_error_e ret = connection_create(&connection);
202         if (CONNECTION_ERROR_NONE != ret)
203         {
204             OIC_LOG(ERROR, TAG, "connection_create failed");
205             return CA_STATUS_FAILED;
206         }
207
208         // Set callback for receiving state changes.
209         ret = connection_set_type_changed_cb(connection, CAIPConnectionStateChangedCb, NULL);
210         if (CONNECTION_ERROR_NONE != ret)
211         {
212             OIC_LOG(ERROR, TAG, "connection_set_type_changed_cb failed");
213             return CA_STATUS_FAILED;
214         }
215     }
216
217     OIC_LOG(DEBUG, TAG, "Initialize network monitoring successfully");
218     return CAIPSetNetworkMonitorCallback(callback, adapter);
219 }
220
221 CAResult_t CAIPStopNetworkMonitor(CATransportAdapter_t adapter)
222 {
223     OIC_LOG(DEBUG, TAG, "IN");
224
225     CAIPUnSetNetworkMonitorCallback(adapter);
226     if (!g_adapterCallbackList)
227     {
228         // Deinitialize Wifi service.
229         if (WIFI_ERROR_NONE != wifi_deinitialize())
230         {
231             OIC_LOG(ERROR, TAG, "wifi_deinitialize failed");
232         }
233
234         // Reset callback for receiving state changes.
235         if (connection)
236         {
237             connection_error_e ret = connection_unset_type_changed_cb(connection);
238             if (CONNECTION_ERROR_NONE != ret)
239             {
240                 OIC_LOG(ERROR, TAG, "connection_unset_type_changed_cb failed");
241             }
242
243             // Deinitialize Wifi service.
244             ret = connection_destroy(connection);
245             if (CONNECTION_ERROR_NONE != ret)
246             {
247                 OIC_LOG(ERROR, TAG, "connection_destroy failed");
248             }
249             connection = NULL;
250         }
251     }
252
253     OIC_LOG(DEBUG, TAG, "Network monitoring terminated successfully");
254     return CA_STATUS_OK;
255 }
256
257 /**
258  * Used to send netlink query to kernel and recv response from kernel.
259  *
260  * @param[in]   idx       desired network interface index, 0 means all interfaces.
261  * @param[out]  iflist    linked list.
262  *
263  */
264 static bool CAIPGetAddrInfo(int idx, u_arraylist_t *iflist)
265 {
266     if ((idx < 0) || (iflist == NULL))
267     {
268         return false;
269     }
270
271     struct ifaddrs *ifp = NULL;
272     if (-1 == getifaddrs(&ifp))
273     {
274         OIC_LOG_V(ERROR, TAG, "Failed to get ifaddrs: %s", strerror(errno));
275         return false;
276     }
277
278     struct ifaddrs *ifa = NULL;
279     for (ifa = ifp; ifa; ifa = ifa->ifa_next)
280     {
281         if (!ifa->ifa_addr)
282         {
283             continue;
284         }
285
286         int family = ifa->ifa_addr->sa_family;
287         if ((ifa->ifa_flags & IFF_LOOPBACK) || (AF_INET != family && AF_INET6 != family))
288         {
289             continue;
290         }
291
292         int ifindex = if_nametoindex(ifa->ifa_name);
293         if (idx && (ifindex != idx))
294         {
295             continue;
296         }
297
298         char ipaddr[MAX_ADDR_STR_SIZE_CA] = {0};
299         if (family == AF_INET6)
300         {
301             struct sockaddr_in6 *in6 = (struct sockaddr_in6*) ifa->ifa_addr;
302             inet_ntop(family, (void *)&(in6->sin6_addr), ipaddr, sizeof(ipaddr));
303         }
304         else if (family == AF_INET)
305         {
306             struct sockaddr_in *in = (struct sockaddr_in*) ifa->ifa_addr;
307             inet_ntop(family, (void *)&(in->sin_addr), ipaddr, sizeof(ipaddr));
308         }
309
310         if ((strcmp(ipaddr, IFC_ADDR_LOOP_IPV4) == 0) ||
311             (strcmp(ipaddr, IFC_ADDR_LOOP_IPV6) == 0) ||
312             (strcmp(ifa->ifa_name, IFC_LABEL_LOOP) == 0))
313         {
314             OIC_LOG(DEBUG, TAG, "LOOPBACK continue!!!");
315             continue;
316         }
317
318         CAResult_t result = CAAddInterfaceItem(iflist, ifindex,
319                                                ifa->ifa_name, family,
320                                                ipaddr, ifa->ifa_flags);
321         if (CA_STATUS_OK != result)
322         {
323             OIC_LOG(ERROR, TAG, "CAAddInterfaceItem fail");
324             goto exit;
325         }
326     }
327     freeifaddrs(ifp);
328     return true;
329
330 exit:
331     freeifaddrs(ifp);
332     return false;
333 }
334
335 u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
336 {
337     u_arraylist_t *iflist = u_arraylist_create();
338     if (!iflist)
339     {
340         OIC_LOG_V(ERROR, TAG, "Failed to create iflist: %s", strerror(errno));
341         return NULL;
342     }
343
344     if (!CAIPGetAddrInfo(desiredIndex, iflist))
345     {
346         goto exit;
347     }
348
349     return iflist;
350
351 exit:
352     u_arraylist_destroy(iflist);
353     return NULL;
354 }
355
356 static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
357                                      char *name, int family, const char *addr, int flags)
358 {
359     CAInterface_t *ifitem = CANewInterfaceItem(index, name, family, addr, flags);
360     if (!ifitem)
361     {
362         return CA_STATUS_FAILED;
363     }
364     bool result = u_arraylist_add(iflist, ifitem);
365     if (!result)
366     {
367         OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
368         OICFree(ifitem);
369         return CA_STATUS_FAILED;
370     }
371
372     return CA_STATUS_OK;
373 }
374
375 static CAInterface_t *CANewInterfaceItem(int index, char *name, int family,
376                                          const char *addr, int flags)
377 {
378     CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof (CAInterface_t));
379     if (!ifitem)
380     {
381         OIC_LOG(ERROR, TAG, "Malloc failed");
382         return NULL;
383     }
384
385     OICStrcpy(ifitem->name, INTERFACE_NAME_MAX, name);
386     ifitem->index = index;
387     ifitem->family = family;
388     OICStrcpy(ifitem->addr, sizeof(ifitem->addr), addr);
389     ifitem->flags = flags;
390
391     return ifitem;
392 }
393
394 void CAIPConnectionStateChangedCb(connection_type_e type, void* userData)
395 {
396     switch (type)
397     {
398         case CONNECTION_TYPE_DISCONNECTED:
399             OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_DISCONNECTED");
400             CAIPPassNetworkChangesToAdapter(CA_INTERFACE_DOWN);
401             break;
402         case CONNECTION_TYPE_ETHERNET:
403             OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_ETHERNET");
404             CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
405             break;
406         case CONNECTION_TYPE_WIFI:
407             OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_WIFI");
408             CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
409             break;
410         case CONNECTION_TYPE_CELLULAR:
411             OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_CELLULAR");
412             CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
413             break;
414         default:
415             break;
416     }
417 }