b1f84ca0f1fd3e02878b2599bc5543b57d97dcab
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / ip_adapter / android / 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 <sys/types.h>
24 #include <sys/socket.h>
25 #include <netdb.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <unistd.h>
29
30 #include <arpa/inet.h>
31 #include <linux/if.h>
32 #include <coap/utlist.h>
33
34 #include "caadapterutils.h"
35 #include "caipnwmonitor.h"
36 #include "logger.h"
37 #include "oic_malloc.h"
38 #include "oic_string.h"
39 #include "org_iotivity_ca_CaIpInterface.h"
40
41 #define TAG "OIC_CA_IP_MONITOR"
42 #define NETLINK_MESSAGE_LENGTH  (4096)
43
44 /**
45  * Used to storing adapter changes callback interface.
46  */
47 static struct CAIPCBData_t *g_adapterCallbackList = NULL;
48
49 /**
50  * Create new interface item to add in activated interface list.
51  * @param[in]  index    Network interface index number.
52  * @param[in]  name     Network interface name.
53  * @param[in]  family   Network interface family type.
54  * @param[in]  addr     New interface address.
55  * @param[in]  flags    The active flag word of a device.
56  * @return  CAInterface_t objects.
57  */
58 static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family,
59                                          const char *addr, int flags);
60
61 /**
62  * Add created new interface item activated interface list.
63  * @param[in]  iflist   Network interface array list.
64  * @param[in]  index    Network interface index number.
65  * @param[in]  name     Network interface name.
66  * @param[in]  family   Network interface family type.
67  * @param[in]  addr     New interface address.
68  * @param[in]  flags    The active flag word of a device.
69  * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
70  */
71 static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
72                                      const char *name, int family, const char *addr, int flags);
73
74 /**
75  * Initialize JNI interface.
76  * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
77  */
78 CAResult_t CAIPJniInit();
79
80 /**
81  * Destroy JNI interface.
82  * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
83  */
84 static CAResult_t CAIPDestroyJniInterface();
85
86 #define MAX_INTERFACE_INFO_LENGTH 1024 // allows 32 interfaces from SIOCGIFCONF
87
88 CAResult_t CAIPStartNetworkMonitor(CAIPAdapterStateChangeCallback callback,
89                                    CATransportAdapter_t adapter)
90 {
91     CAResult_t res = CAIPJniInit();
92     if (CA_STATUS_OK != res)
93     {
94         OIC_LOG(ERROR, TAG, "failed to initialize ip jni interface");
95         return res;
96     }
97
98     return CAIPSetNetworkMonitorCallback(callback, adapter);
99 }
100
101 CAResult_t CAIPStopNetworkMonitor(CATransportAdapter_t adapter)
102 {
103     CAIPUnSetNetworkMonitorCallback(adapter);
104
105     // if there is no callback to pass the changed status, stop monitoring.
106     if (!g_adapterCallbackList)
107     {
108         return CAIPDestroyJniInterface();
109     }
110
111     return CA_STATUS_OK;
112 }
113
114 int CAGetPollingInterval(int interval)
115 {
116     return interval;
117 }
118
119 static void CAIPPassNetworkChangesToAdapter(CANetworkStatus_t status)
120 {
121     CAIPCBData_t *cbitem = NULL;
122     LL_FOREACH(g_adapterCallbackList, cbitem)
123     {
124         if (cbitem && cbitem->adapter)
125         {
126             cbitem->callback(cbitem->adapter, status);
127         }
128     }
129 }
130
131 CAResult_t CAIPSetNetworkMonitorCallback(CAIPAdapterStateChangeCallback callback,
132                                          CATransportAdapter_t adapter)
133 {
134     if (!callback)
135     {
136         OIC_LOG(ERROR, TAG, "callback is null");
137         return CA_STATUS_INVALID_PARAM;
138     }
139
140     CAIPCBData_t *cbitem = NULL;
141     LL_FOREACH(g_adapterCallbackList, cbitem)
142     {
143         if (cbitem && adapter == cbitem->adapter && callback == cbitem->callback)
144         {
145             OIC_LOG(DEBUG, TAG, "this callback is already added");
146             return CA_STATUS_OK;
147         }
148     }
149
150     cbitem = (CAIPCBData_t *)OICCalloc(1, sizeof(*cbitem));
151     if (!cbitem)
152     {
153         OIC_LOG(ERROR, TAG, "Malloc failed");
154         return CA_STATUS_FAILED;
155     }
156
157     cbitem->adapter = adapter;
158     cbitem->callback = callback;
159     LL_APPEND(g_adapterCallbackList, cbitem);
160
161     return CA_STATUS_OK;
162 }
163
164 CAResult_t CAIPUnSetNetworkMonitorCallback(CATransportAdapter_t adapter)
165 {
166     CAIPCBData_t *cbitem = NULL;
167     CAIPCBData_t *tmpCbitem = NULL;
168     LL_FOREACH_SAFE(g_adapterCallbackList, cbitem, tmpCbitem)
169     {
170         if (cbitem && adapter == cbitem->adapter)
171         {
172             OIC_LOG(DEBUG, TAG, "remove specific callback");
173             LL_DELETE(g_adapterCallbackList, cbitem);
174             OICFree(cbitem);
175             return CA_STATUS_OK;
176         }
177     }
178     return CA_STATUS_OK;
179 }
180
181 CAInterface_t *CAFindInterfaceChange()
182 {
183     // release netlink event
184     char *bufPtr = (char *)OICCalloc(NETLINK_MESSAGE_LENGTH, sizeof (char));
185     if (!bufPtr)
186     {
187         OIC_LOG(ERROR, TAG, "Malloc failed");
188         return NULL;
189     }
190     recv(caglobals.ip.netlinkFd, bufPtr, NETLINK_MESSAGE_LENGTH, 0);
191     OICFree(bufPtr);
192     bufPtr = NULL;
193
194     char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 };
195     struct ifconf ifc  = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf };
196
197     int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd;
198     if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
199     {
200         OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno));
201         return NULL;
202     }
203
204     CAInterface_t *foundNewInterface = NULL;
205
206     struct ifreq* ifr = ifc.ifc_req;
207     size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]);
208     size_t ifreqsize = ifc.ifc_len;
209
210     CAIfItem_t *previous = (CAIfItem_t *)OICMalloc(ifreqsize);
211     if (!previous)
212     {
213         OIC_LOG(ERROR, TAG, "OICMalloc failed");
214         return NULL;
215     }
216
217     memcpy(previous, caglobals.ip.nm.ifItems, ifreqsize);
218     size_t numprevious = caglobals.ip.nm.numIfItems;
219
220     if (ifreqsize > caglobals.ip.nm.sizeIfItems)
221     {
222
223         CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize);
224         if (!items)
225         {
226             OIC_LOG(ERROR, TAG, "OICRealloc failed");
227             OICFree(previous);
228             return NULL;
229         }
230         caglobals.ip.nm.ifItems = items;
231         caglobals.ip.nm.sizeIfItems = ifreqsize;
232     }
233
234     caglobals.ip.nm.numIfItems = 0;
235     for (size_t i = 0; i < interfaces; i++)
236     {
237         struct ifreq* item = &ifr[i];
238         char *name = item->ifr_name;
239
240         if (ioctl(s, SIOCGIFFLAGS, item) < 0)
241         {
242             OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno));
243             continue;
244         }
245         int16_t flags = item->ifr_flags;
246         if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING))
247         {
248             continue;
249         }
250         if (ioctl(s, SIOCGIFINDEX, item) < 0)
251         {
252             OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno));
253             continue;
254         }
255
256         int ifIndex = item->ifr_ifindex;
257         caglobals.ip.nm.ifItems[i].ifIndex = ifIndex;  // refill interface list
258         caglobals.ip.nm.numIfItems++;
259
260         if (foundNewInterface)
261         {
262             continue;   // continue updating interface list
263         }
264
265         // see if this interface didn't previously exist
266         bool found = false;
267         for (size_t j = 0; j < numprevious; j++)
268         {
269             if (ifIndex == previous[j].ifIndex)
270             {
271                 found = true;
272                 break;
273             }
274         }
275         if (found)
276         {
277             OIC_LOG_V(INFO, TAG, "Interface found: %s", name);
278             continue;
279         }
280
281         // Get address of network interface.
282         char addr[MAX_ADDR_STR_SIZE_CA] = { 0 };
283         struct sockaddr_in *sa = (struct sockaddr_in *)&item->ifr_addr;
284         inet_ntop(AF_INET, (void *)&(sa->sin_addr), addr, sizeof(addr));
285
286         foundNewInterface = CANewInterfaceItem(ifIndex, name, AF_INET, addr, flags);
287     }
288
289     OICFree(previous);
290     return foundNewInterface;
291 }
292
293 u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
294 {
295     u_arraylist_t *iflist = u_arraylist_create();
296     if (!iflist)
297     {
298         OIC_LOG_V(ERROR, TAG, "Failed to create iflist: %s", strerror(errno));
299         return NULL;
300     }
301
302     char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 };
303     struct ifconf ifc = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf };
304
305     int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd;
306     if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
307     {
308         OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno));
309         u_arraylist_destroy(iflist);
310         return NULL;
311     }
312
313     struct ifreq* ifr = ifc.ifc_req;
314     size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]);
315     size_t ifreqsize = ifc.ifc_len;
316
317     if (ifreqsize > caglobals.ip.nm.sizeIfItems)
318     {
319         CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize);
320         if (!items)
321         {
322             OIC_LOG(ERROR, TAG, "OICRealloc failed");
323             goto exit;
324         }
325         caglobals.ip.nm.ifItems = items;
326         caglobals.ip.nm.sizeIfItems = ifreqsize;
327     }
328
329     caglobals.ip.nm.numIfItems = 0;
330     for (size_t i = 0; i < interfaces; i++)
331     {
332         struct ifreq* item = &ifr[i];
333         char *name = item->ifr_name;
334
335         if (ioctl(s, SIOCGIFFLAGS, item) < 0)
336         {
337             OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno));
338             continue;
339         }
340         int16_t flags = item->ifr_flags;
341         if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING))
342         {
343             continue;
344         }
345         if (ioctl(s, SIOCGIFINDEX, item) < 0)
346         {
347             OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno));
348             continue;
349         }
350
351         int ifindex = item->ifr_ifindex;
352         caglobals.ip.nm.ifItems[i].ifIndex = ifindex;
353         caglobals.ip.nm.numIfItems++;
354
355         if (desiredIndex && (ifindex != desiredIndex))
356         {
357             continue;
358         }
359
360         // Get address of network interface.
361         char addr[MAX_ADDR_STR_SIZE_CA] = { 0 };
362         struct sockaddr_in *sa = (struct sockaddr_in *)&item->ifr_addr;
363         inet_ntop(AF_INET, (void *)&(sa->sin_addr), addr, sizeof(addr));
364
365         // Add IPv4 interface
366         CAResult_t result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, addr, flags);
367         if (CA_STATUS_OK != result)
368         {
369             goto exit;
370         }
371
372         // Add IPv6 interface
373         result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET6, addr, flags);
374         if (CA_STATUS_OK != result)
375         {
376             goto exit;
377         }
378     }
379     return iflist;
380
381 exit:
382     u_arraylist_destroy(iflist);
383     return NULL;
384 }
385
386 static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
387                                      const char *name, int family, const char *addr, int flags)
388 {
389     CAInterface_t *ifitem = CANewInterfaceItem(index, name, family, addr, flags);
390     if (!ifitem)
391     {
392         return CA_STATUS_FAILED;
393     }
394     bool result = u_arraylist_add(iflist, ifitem);
395     if (!result)
396     {
397         OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
398         OICFree(ifitem);
399         return CA_STATUS_FAILED;
400     }
401
402     return CA_STATUS_OK;
403 }
404
405 static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family,
406                                          const char *addr, int flags)
407 {
408     CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof (CAInterface_t));
409     if (!ifitem)
410     {
411         OIC_LOG(ERROR, TAG, "Malloc failed");
412         return NULL;
413     }
414
415     OICStrcpy(ifitem->name, sizeof (ifitem->name), name);
416     ifitem->index = index;
417     ifitem->family = family;
418     OICStrcpy(ifitem->addr, sizeof (ifitem->addr), addr);
419     ifitem->flags = flags;
420
421     return ifitem;
422 }
423
424 CAResult_t CAIPJniInit()
425 {
426     OIC_LOG(DEBUG, TAG, "CAIPJniInit_IN");
427
428     JavaVM *jvm = CANativeJNIGetJavaVM();
429     if (!jvm)
430     {
431         OIC_LOG(ERROR, TAG, "Could not get JavaVM pointer");
432         return CA_STATUS_FAILED;
433     }
434
435     jobject context = CANativeJNIGetContext();
436     if (!context)
437     {
438         OIC_LOG(ERROR, TAG, "unable to get application context");
439         return CA_STATUS_FAILED;
440     }
441
442     JNIEnv* env = NULL;
443     if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
444     {
445         OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
446         return CA_STATUS_FAILED;
447     }
448
449     jmethodID mid_getApplicationContext = CAGetJNIMethodID(env, "android/content/Context",
450                                                            "getApplicationContext",
451                                                            "()Landroid/content/Context;");
452
453     if (!mid_getApplicationContext)
454     {
455         OIC_LOG(ERROR, TAG, "Could not get getApplicationContext method");
456         return CA_STATUS_FAILED;
457     }
458
459     jobject jApplicationContext = (*env)->CallObjectMethod(env, context,
460                                                            mid_getApplicationContext);
461     if (!jApplicationContext)
462     {
463         OIC_LOG(ERROR, TAG, "Could not get application context");
464         return CA_STATUS_FAILED;
465     }
466
467     jclass cls_CaIpInterface = (*env)->FindClass(env, "org/iotivity/ca/CaIpInterface");
468     if (!cls_CaIpInterface)
469     {
470         OIC_LOG(ERROR, TAG, "Could not get CaIpInterface class");
471         return CA_STATUS_FAILED;
472     }
473
474     jmethodID mid_CaIpInterface_ctor = (*env)->GetMethodID(env, cls_CaIpInterface, "<init>",
475                                                                    "(Landroid/content/Context;)V");
476     if (!mid_CaIpInterface_ctor)
477     {
478         OIC_LOG(ERROR, TAG, "Could not get CaIpInterface constructor method");
479         return CA_STATUS_FAILED;
480     }
481
482     (*env)->NewObject(env, cls_CaIpInterface, mid_CaIpInterface_ctor, jApplicationContext);
483     OIC_LOG(DEBUG, TAG, "Create CaIpInterface instance, success");
484
485     OIC_LOG(DEBUG, TAG, "CAIPJniInit_OUT");
486     return CA_STATUS_OK;
487 }
488
489 static CAResult_t CAIPDestroyJniInterface()
490 {
491     OIC_LOG(DEBUG, TAG, "CAIPDestroyJniInterface");
492
493     JavaVM *jvm = CANativeJNIGetJavaVM();
494     if (!jvm)
495     {
496         OIC_LOG(ERROR, TAG, "Could not get JavaVM pointer");
497         return CA_STATUS_FAILED;
498     }
499
500     bool isAttached = false;
501     JNIEnv* env = NULL;
502     jint res = (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6);
503     if (JNI_OK != res)
504     {
505         OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
506         res = (*jvm)->AttachCurrentThread(jvm, &env, NULL);
507
508         if (JNI_OK != res)
509         {
510             OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
511             return CA_STATUS_FAILED;
512         }
513         isAttached = true;
514     }
515
516     jclass jni_IpInterface = (*env)->FindClass(env, "org/iotivity/ca/CaIpInterface");
517     if (!jni_IpInterface)
518     {
519         OIC_LOG(ERROR, TAG, "Could not get CaIpInterface class");
520         goto error_exit;
521     }
522
523     jmethodID jni_InterfaceDestroyMethod = (*env)->GetStaticMethodID(env, jni_IpInterface,
524                                                                      "destroyIpInterface",
525                                                                      "()V");
526     if (!jni_InterfaceDestroyMethod)
527     {
528         OIC_LOG(ERROR, TAG, "Could not get CaIpInterface destroy method");
529         goto error_exit;
530     }
531
532     (*env)->CallStaticVoidMethod(env, jni_IpInterface, jni_InterfaceDestroyMethod);
533
534     if ((*env)->ExceptionCheck(env))
535     {
536         OIC_LOG(ERROR, TAG, "destroyIpInterface has failed");
537         (*env)->ExceptionDescribe(env);
538         (*env)->ExceptionClear(env);
539         goto error_exit;
540     }
541
542     OIC_LOG(DEBUG, TAG, "Destroy instance for CaIpInterface");
543
544     if (isAttached)
545     {
546         (*jvm)->DetachCurrentThread(jvm);
547     }
548
549     return CA_STATUS_OK;
550
551 error_exit:
552
553     if (isAttached)
554     {
555         (*jvm)->DetachCurrentThread(jvm);
556     }
557
558     return CA_STATUS_FAILED;
559 }
560
561 JNIEXPORT void JNICALL
562 Java_org_iotivity_ca_CaIpInterface_caIpStateEnabled(JNIEnv *env, jclass class)
563 {
564     (void)env;
565     (void)class;
566
567     OIC_LOG(DEBUG, TAG, "Wifi is in Activated State");
568     CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
569 }
570
571 JNIEXPORT void JNICALL
572 Java_org_iotivity_ca_CaIpInterface_caIpStateDisabled(JNIEnv *env, jclass class)
573 {
574     (void)env;
575     (void)class;
576
577     OIC_LOG(DEBUG, TAG, "Wifi is in Deactivated State");
578     CAIPPassNetworkChangesToAdapter(CA_INTERFACE_DOWN);
579 }