replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / ip_adapter / linux / 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 "caipinterface.h"
22
23 #include <stdio.h>
24 #include <string.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/select.h>
28 #include <ifaddrs.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <arpa/inet.h>
32 #include <netinet/in.h>
33 #include <net/if.h>
34 #include <netdb.h>
35 #include <errno.h>
36
37 #ifdef __linux__
38 #include <linux/netlink.h>
39 #include <linux/rtnetlink.h>
40 #endif
41
42 #include "octhread.h"
43 #include "caipnwmonitor.h"
44 #include "caadapterutils.h"
45 #include "logger.h"
46 #include "oic_malloc.h"
47 #include "oic_string.h"
48 #include <coap/utlist.h>
49
50 #define TAG "OIC_CA_IP_MONITOR"
51
52 /**
53  * Mutex for synchronizing access to cached interface and IP address information.
54  */
55 static oc_mutex g_networkMonitorContextMutex = NULL;
56
57 /**
58  * Used to storing network interface.
59  */
60 static u_arraylist_t *g_netInterfaceList = NULL;
61
62 /**
63  * Used to storing adapter changes callback interface.
64  */
65 static struct CAIPCBData_t *g_adapterCallbackList = NULL;
66
67 /**
68  * Initialize the network interface monitoring list.
69  */
70 static CAResult_t CAIPInitializeNetworkMonitorList();
71
72 /**
73  * Destroy the network interface monitoring list.
74  */
75 static void CAIPDestroyNetworkMonitorList();
76
77 /**
78  * Compare the interface with the already added interface in list.
79  */
80 static bool CACmpNetworkList(uint32_t ifiindex);
81
82 /**
83  * Add new network interface in list.
84  */
85 static CAResult_t CAAddNetworkMonitorList(CAInterface_t *ifitem);
86
87 /**
88  * Remove network interace from list.
89  */
90 static void CARemoveNetworkMonitorList(int ifiindex);
91
92 /**
93  * Pass the changed network status through the stored callback.
94  */
95 static void CAIPPassNetworkChangesToAdapter(CANetworkStatus_t status);
96
97 /**
98  * Create new interface item.
99  */
100 static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family,
101                                          const char *addr, int flags);
102
103 static CAResult_t CAIPInitializeNetworkMonitorList()
104 {
105     if (!g_networkMonitorContextMutex)
106     {
107         g_networkMonitorContextMutex = oc_mutex_new();
108         if (!g_networkMonitorContextMutex)
109         {
110             OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
111             return CA_STATUS_FAILED;
112         }
113     }
114
115     if (!g_netInterfaceList)
116     {
117         g_netInterfaceList = u_arraylist_create();
118         if (!g_netInterfaceList)
119         {
120             OIC_LOG(ERROR, TAG, "u_arraylist_create has failed");
121             CAIPDestroyNetworkMonitorList();
122             return CA_STATUS_FAILED;
123         }
124     }
125     return CA_STATUS_OK;
126 }
127
128 static void CAIPDestroyNetworkMonitorList()
129 {
130     if (g_netInterfaceList)
131     {
132         u_arraylist_destroy(g_netInterfaceList);
133         g_netInterfaceList = NULL;
134     }
135
136     if (g_networkMonitorContextMutex)
137     {
138         oc_mutex_free(g_networkMonitorContextMutex);
139         g_networkMonitorContextMutex = NULL;
140     }
141 }
142
143 static bool CACmpNetworkList(uint32_t ifiindex)
144 {
145     if (!g_netInterfaceList)
146     {
147         OIC_LOG(ERROR, TAG, "g_netInterfaceList is NULL");
148         return false;
149     }
150
151     oc_mutex_lock(g_networkMonitorContextMutex);
152
153     uint32_t list_length = u_arraylist_length(g_netInterfaceList);
154     for (uint32_t list_index = 0; list_index < list_length; list_index++)
155     {
156         CAInterface_t *currItem = (CAInterface_t *) u_arraylist_get(g_netInterfaceList,
157                                                                     list_index);
158         if (currItem->index == ifiindex)
159         {
160             oc_mutex_unlock(g_networkMonitorContextMutex);
161             return true;
162         }
163     }
164     oc_mutex_unlock(g_networkMonitorContextMutex);
165     return false;
166 }
167
168 static CAResult_t CAAddNetworkMonitorList(CAInterface_t *ifitem)
169 {
170     VERIFY_NON_NULL(g_netInterfaceList, TAG, "g_netInterfaceList is NULL");
171     VERIFY_NON_NULL(ifitem, TAG, "ifitem is NULL");
172
173     oc_mutex_lock(g_networkMonitorContextMutex);
174     bool result = u_arraylist_add(g_netInterfaceList, (void *) ifitem);
175     if (!result)
176     {
177         OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
178         oc_mutex_unlock(g_networkMonitorContextMutex);
179         return CA_STATUS_FAILED;
180     }
181     oc_mutex_unlock(g_networkMonitorContextMutex);
182     return CA_STATUS_OK;
183 }
184
185 static void CARemoveNetworkMonitorList(int ifiindex)
186 {
187     VERIFY_NON_NULL_VOID(g_netInterfaceList, TAG, "g_netInterfaceList is NULL");
188
189     oc_mutex_lock(g_networkMonitorContextMutex);
190
191     uint32_t list_length = u_arraylist_length(g_netInterfaceList);
192     for (uint32_t list_index = 0; list_index < list_length; list_index++)
193     {
194         CAInterface_t *removedifitem = (CAInterface_t *) u_arraylist_get(
195                 g_netInterfaceList, list_index);
196         if (removedifitem && ((int)removedifitem->index) == ifiindex)
197         {
198             if (u_arraylist_remove(g_netInterfaceList, list_index))
199             {
200                 OICFree(removedifitem);
201                 oc_mutex_unlock(g_networkMonitorContextMutex);
202                 return;
203             }
204             continue;
205         }
206     }
207     oc_mutex_unlock(g_networkMonitorContextMutex);
208     return;
209 }
210
211 CAResult_t CAIPStartNetworkMonitor(CAIPAdapterStateChangeCallback callback,
212                                    CATransportAdapter_t adapter)
213 {
214     CAResult_t res = CAIPInitializeNetworkMonitorList();
215     if (CA_STATUS_OK == res)
216     {
217         return CAIPSetNetworkMonitorCallback(callback, adapter);
218     }
219     return res;
220 }
221
222 CAResult_t CAIPStopNetworkMonitor(CATransportAdapter_t adapter)
223 {
224     CAIPDestroyNetworkMonitorList();
225     return CAIPUnSetNetworkMonitorCallback(adapter);
226 }
227
228 int CAGetPollingInterval(int interval)
229 {
230     return interval;
231 }
232
233 static void CAIPPassNetworkChangesToAdapter(CANetworkStatus_t status)
234 {
235     CAIPCBData_t *cbitem = NULL;
236     LL_FOREACH(g_adapterCallbackList, cbitem)
237     {
238         if (cbitem && cbitem->adapter)
239         {
240             cbitem->callback(cbitem->adapter, status);
241             CALogAdapterStateInfo(cbitem->adapter, status);
242         }
243     }
244 }
245
246 CAResult_t CAIPSetNetworkMonitorCallback(CAIPAdapterStateChangeCallback callback,
247                                          CATransportAdapter_t adapter)
248 {
249     if (!callback)
250     {
251         OIC_LOG(ERROR, TAG, "callback is null");
252         return CA_STATUS_INVALID_PARAM;
253     }
254
255     CAIPCBData_t *cbitem = NULL;
256     LL_FOREACH(g_adapterCallbackList, cbitem)
257     {
258         if (cbitem && adapter == cbitem->adapter && callback == cbitem->callback)
259         {
260             OIC_LOG(DEBUG, TAG, "this callback is already added");
261             return CA_STATUS_OK;
262         }
263     }
264
265     cbitem = (CAIPCBData_t *)OICCalloc(1, sizeof(*cbitem));
266     if (!cbitem)
267     {
268         OIC_LOG(ERROR, TAG, "Malloc failed");
269         return CA_STATUS_FAILED;
270     }
271
272     cbitem->adapter = adapter;
273     cbitem->callback = callback;
274     LL_APPEND(g_adapterCallbackList, cbitem);
275
276     return CA_STATUS_OK;
277 }
278
279 CAResult_t CAIPUnSetNetworkMonitorCallback(CATransportAdapter_t adapter)
280 {
281     CAIPCBData_t *cbitem = NULL;
282     CAIPCBData_t *tmpCbitem = NULL;
283     LL_FOREACH_SAFE(g_adapterCallbackList, cbitem, tmpCbitem)
284     {
285         if (cbitem && adapter == cbitem->adapter)
286         {
287             OIC_LOG(DEBUG, TAG, "remove specific callback");
288             LL_DELETE(g_adapterCallbackList, cbitem);
289             OICFree(cbitem);
290             return CA_STATUS_OK;
291         }
292     }
293     return CA_STATUS_OK;
294 }
295
296 static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family,
297                                          const char *addr, int flags)
298 {
299     CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof (CAInterface_t));
300     if (!ifitem)
301     {
302         OIC_LOG(ERROR, TAG, "Malloc failed");
303         return NULL;
304     }
305
306     OICStrcpy(ifitem->name, sizeof (ifitem->name), name);
307     ifitem->index = index;
308     ifitem->family = family;
309     OICStrcpy(ifitem->addr, sizeof (ifitem->addr), addr);
310     ifitem->flags = flags;
311
312     return ifitem;
313 }
314
315 u_arraylist_t *CAFindInterfaceChange()
316 {
317     u_arraylist_t *iflist = NULL;
318 #ifdef __linux__
319     char buf[4096] = { 0 };
320     struct nlmsghdr *nh = NULL;
321     struct sockaddr_nl sa = { .nl_family = 0 };
322     struct iovec iov = { .iov_base = buf,
323                          .iov_len = sizeof (buf) };
324     struct msghdr msg = { .msg_name = (void *)&sa,
325                           .msg_namelen = sizeof (sa),
326                           .msg_iov = &iov,
327                           .msg_iovlen = 1 };
328
329     ssize_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0);
330
331     for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len))
332     {
333         if (nh != NULL && (nh->nlmsg_type != RTM_DELADDR && nh->nlmsg_type != RTM_NEWADDR))
334         {
335             continue;
336         }
337
338         if (RTM_DELADDR == nh->nlmsg_type)
339         {
340             struct ifaddrmsg *ifa = (struct ifaddrmsg *)NLMSG_DATA (nh);
341             int ifiIndex = ifa->ifa_index;
342             bool isFound = CACmpNetworkList(ifiIndex);
343             if (isFound)
344             {
345                 CARemoveNetworkMonitorList(ifiIndex);
346                 CAIPPassNetworkChangesToAdapter(CA_INTERFACE_DOWN);
347             }
348             continue;
349         }
350
351         // Netlink message type is RTM_NEWADDR.
352         struct ifaddrmsg *ifa = (struct ifaddrmsg *)NLMSG_DATA (nh);
353         int ifiIndex = ifa->ifa_index;
354
355         iflist = CAIPGetInterfaceInformation(ifiIndex);
356         if (!iflist)
357         {
358             OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
359             return NULL;
360         }
361     }
362 #endif
363     return iflist;
364 }
365
366 u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
367 {
368     if (desiredIndex < 0)
369     {
370         OIC_LOG_V(ERROR, TAG, "invalid index : %d", desiredIndex);
371         return NULL;
372     }
373
374     u_arraylist_t *iflist = u_arraylist_create();
375     if (!iflist)
376     {
377         OIC_LOG_V(ERROR, TAG, "Failed to create iflist: %s", strerror(errno));
378         return NULL;
379     }
380
381     struct ifaddrs *ifp = NULL;
382     if (-1 == getifaddrs(&ifp))
383     {
384         OIC_LOG_V(ERROR, TAG, "Failed to get ifaddrs: %s", strerror(errno));
385         u_arraylist_destroy(iflist);
386         return NULL;
387     }
388
389     struct ifaddrs *ifa = NULL;
390     for (ifa = ifp; ifa; ifa = ifa->ifa_next)
391     {
392         if (!ifa->ifa_addr)
393         {
394             continue;
395         }
396         int family = ifa->ifa_addr->sa_family;
397         if ((ifa->ifa_flags & IFF_LOOPBACK) || (AF_INET != family && AF_INET6 != family))
398         {
399             continue;
400         }
401
402         int ifindex = if_nametoindex(ifa->ifa_name);
403         if (desiredIndex && (ifindex != desiredIndex))
404         {
405             continue;
406         }
407
408         int length = u_arraylist_length(iflist);
409         int already = false;
410         for (int i = length-1; i >= 0; i--)
411         {
412             CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
413
414             if (ifitem
415                 && (int)ifitem->index == ifindex
416                 && ifitem->family == (uint16_t)family)
417             {
418                 already = true;
419                 break;
420             }
421         }
422         if (already)
423         {
424             continue;
425         }
426
427         CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof(CAInterface_t));
428         if (!ifitem)
429         {
430             OIC_LOG(ERROR, TAG, "Malloc failed");
431             goto exit;
432         }
433
434         OICStrcpy(ifitem->name, INTERFACE_NAME_MAX, ifa->ifa_name);
435         ifitem->index = ifindex;
436         ifitem->family = family;
437         ifitem->flags = ifa->ifa_flags;
438
439         if (ifitem->family == AF_INET6)
440         {
441             struct sockaddr_in6 *in6 = (struct sockaddr_in6*) ifa->ifa_addr;
442             inet_ntop(ifitem->family, (void *)&(in6->sin6_addr), ifitem->addr,
443                       sizeof(ifitem->addr));
444         }
445         else if (ifitem->family == AF_INET)
446         {
447             struct sockaddr_in *in = (struct sockaddr_in*) ifa->ifa_addr;
448             inet_ntop(ifitem->family, (void *)&(in->sin_addr), ifitem->addr,
449                       sizeof(ifitem->addr));
450         }
451
452         bool result = u_arraylist_add(iflist, ifitem);
453         if (!result)
454         {
455             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
456             goto exit;
457         }
458
459         bool isFound = CACmpNetworkList(ifitem->index);
460         if (!isFound)
461         {
462             CAInterface_t *newifitem = CANewInterfaceItem(ifitem->index, ifitem->name, ifitem->family,
463                                                           ifitem->addr, ifitem->flags);
464             CAResult_t ret = CAAddNetworkMonitorList(newifitem);
465             if (CA_STATUS_OK != ret)
466             {
467                 OICFree(newifitem);
468                 goto exit;
469             }
470             CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
471             OIC_LOG_V(DEBUG, TAG, "Added interface: %s (%d)", ifitem->name, ifitem->family);
472         }
473     }
474 #ifndef __TIZENRT__
475     freeifaddrs(ifp);
476 #endif
477     return iflist;
478
479 exit:
480 #ifndef __TIZENRT__
481     freeifaddrs(ifp);
482 #endif
483     u_arraylist_destroy(iflist);
484     return NULL;
485 }