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