added network monitoring logic in CAUtil
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / cainterfacecontroller.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 <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <inttypes.h>
25
26 #include "logger.h"
27 #include "oic_malloc.h"
28 #include "caadapterutils.h"
29 #include "canetworkconfigurator.h"
30 #include "cainterfacecontroller.h"
31 #include "caedradapter.h"
32 #include "caleadapter.h"
33 #include "canfcadapter.h"
34 #include "caremotehandler.h"
35 #include "cathreadpool.h"
36 #include "caipadapter.h"
37 #include "cainterface.h"
38
39 #ifdef RA_ADAPTER
40 #include "caraadapter.h"
41 #endif
42
43 #ifdef TCP_ADAPTER
44 #include "catcpadapter.h"
45 #endif
46
47 #define TAG "OIC_CA_INF_CTR"
48
49 #define CA_MEMORY_ALLOC_CHECK(arg) {if (arg == NULL) \
50     {OIC_LOG(ERROR, TAG, "memory error");goto memory_error_exit;} }
51
52 static CAConnectivityHandler_t *g_adapterHandler = NULL;
53
54 static uint32_t g_numberOfAdapters = 0;
55
56 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
57
58 static CAAdapterChangeCallback g_adapterChangeCallback = NULL;
59
60 static CAConnectionChangeCallback g_connChangeCallback = NULL;
61
62 static CAErrorHandleCallback g_errorHandleCallback = NULL;
63
64 static int CAGetAdapterIndex(CATransportAdapter_t cType)
65 {
66     for (uint32_t index=0 ; index < g_numberOfAdapters ; index++)
67     {
68         if (cType == g_adapterHandler[index].cType )
69          {
70              return index;
71          }
72     }
73     return -1;
74 }
75
76 static void CARegisterCallback(CAConnectivityHandler_t handler)
77 {
78     if(handler.startAdapter == NULL ||
79         handler.startListenServer == NULL ||
80         handler.stopListenServer == NULL ||
81         handler.startDiscoveryServer == NULL ||
82         handler.sendData == NULL ||
83         handler.sendDataToAll == NULL ||
84         handler.GetnetInfo == NULL ||
85         handler.readData == NULL ||
86         handler.stopAdapter == NULL ||
87         handler.terminate == NULL)
88     {
89         OIC_LOG(ERROR, TAG, "connectivity handler is not enough to be used!");
90         return;
91     }
92     uint32_t numberofAdapters = g_numberOfAdapters + 1;
93     CAConnectivityHandler_t *adapterHandler = OICRealloc(g_adapterHandler,
94                                    (numberofAdapters) * sizeof(*adapterHandler));
95     if (NULL == adapterHandler)
96     {
97         OIC_LOG(ERROR, TAG, "Memory allocation failed during registration");
98         return;
99     }
100     g_adapterHandler = adapterHandler;
101     g_numberOfAdapters = numberofAdapters;
102     g_adapterHandler[g_numberOfAdapters-1] = handler;
103
104     OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", handler.cType);
105 }
106
107 #ifdef RA_ADAPTER
108 CAResult_t CASetAdapterRAInfo(const CARAInfo_t *caraInfo)
109 {
110     return CASetRAInfo(caraInfo);
111 }
112 #endif
113
114 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
115                                      const void *data, uint32_t dataLen)
116 {
117     if (g_networkPacketReceivedCallback != NULL)
118     {
119         g_networkPacketReceivedCallback(sep, data, dataLen);
120     }
121     else
122     {
123         OIC_LOG(ERROR, TAG, "network packet received callback is NULL!");
124     }
125 }
126
127 static void CAAdapterChangedCallback(CATransportAdapter_t adapter, CANetworkStatus_t status)
128 {
129     // Call the callback.
130     if (g_adapterChangeCallback != NULL)
131     {
132         g_adapterChangeCallback(adapter, status);
133     }
134     OIC_LOG_V(DEBUG, TAG, "[%d]adapter status is changed to [%d]", adapter, status);
135 }
136
137 static void CAConnectionChangedCallback(const CAEndpoint_t *info, bool isConnected)
138 {
139     // Call the callback.
140     if (g_connChangeCallback != NULL)
141     {
142         g_connChangeCallback(info, isConnected);
143     }
144     OIC_LOG_V(DEBUG, TAG, "[%s] connection status is changed to [%d]", info->addr, isConnected);
145 }
146
147 static void CAAdapterErrorHandleCallback(const CAEndpoint_t *endpoint,
148                                          const void *data, uint32_t dataLen,
149                                          CAResult_t result)
150 {
151     OIC_LOG(DEBUG, TAG, "received error from adapter in interfacecontroller");
152
153     // Call the callback.
154     if (g_errorHandleCallback != NULL)
155     {
156         g_errorHandleCallback(endpoint, data, dataLen, result);
157     }
158 }
159
160 void CAInitializeAdapters(ca_thread_pool_t handle)
161 {
162     OIC_LOG(DEBUG, TAG, "initialize adapters..");
163
164     // Initialize adapters and register callback.
165 #ifdef IP_ADAPTER
166     CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
167                    CAAdapterErrorHandleCallback, handle);
168 #endif /* IP_ADAPTER */
169
170 #ifdef EDR_ADAPTER
171     CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
172                     CAConnectionChangedCallback, CAAdapterErrorHandleCallback, handle);
173 #endif /* EDR_ADAPTER */
174
175 #ifdef LE_ADAPTER
176     CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
177                    CAConnectionChangedCallback, CAAdapterErrorHandleCallback, handle);
178 #endif /* LE_ADAPTER */
179
180 #ifdef RA_ADAPTER
181     CAInitializeRA(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
182                    handle);
183 #endif /* RA_ADAPTER */
184
185 #ifdef TCP_ADAPTER
186     CAInitializeTCP(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
187                     CAConnectionChangedCallback, CAAdapterErrorHandleCallback, handle);
188 #endif /* TCP_ADAPTER */
189
190 #ifdef NFC_ADAPTER
191     CAInitializeNFC(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
192                     CAAdapterErrorHandleCallback, handle);
193 #endif /* NFC_ADAPTER */
194 }
195
196 void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback)
197 {
198     OIC_LOG(DEBUG, TAG, "Set Receiver handle callback");
199
200     g_networkPacketReceivedCallback = callback;
201 }
202
203 void CASetNetworkMonitorCallbacks(CAAdapterChangeCallback adapterCB,
204                                   CAConnectionChangeCallback connCB)
205 {
206     OIC_LOG(DEBUG, TAG, "Set network monitoring callback");
207
208     g_adapterChangeCallback = adapterCB;
209     g_connChangeCallback = connCB;
210 }
211
212 void CASetErrorHandleCallback(CAErrorHandleCallback errorCallback)
213 {
214     OIC_LOG(DEBUG, TAG, "Set error handle callback");
215     g_errorHandleCallback = errorCallback;
216 }
217
218 CAResult_t CAStartAdapter(CATransportAdapter_t transportType)
219 {
220     OIC_LOG_V(DEBUG, TAG, "Start the adapter of CAConnectivityType[%d]", transportType);
221
222     int index = CAGetAdapterIndex(transportType);
223     if (0 > index)
224     {
225         OIC_LOG(ERROR, TAG, "unknown connectivity type!");
226         return CA_STATUS_FAILED;
227     }
228
229     CAResult_t res = CA_STATUS_FAILED;
230     if (g_adapterHandler[index].startAdapter != NULL)
231     {
232         res = g_adapterHandler[index].startAdapter();
233     }
234
235     return res;
236 }
237
238 void CAStopAdapter(CATransportAdapter_t transportType)
239 {
240     OIC_LOG_V(DEBUG, TAG, "Stop the adapter of CATransportType[%d]", transportType);
241
242     int index = CAGetAdapterIndex(transportType);
243     if (0 > index)
244     {
245         OIC_LOG(ERROR, TAG, "unknown transport type!");
246         return;
247     }
248
249     if (g_adapterHandler[index].stopAdapter != NULL)
250     {
251         g_adapterHandler[index].stopAdapter();
252     }
253 }
254
255 CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size)
256 {
257     if (info == NULL || size == NULL)
258     {
259         return CA_STATUS_INVALID_PARAM;
260     }
261
262     CAEndpoint_t **tempInfo = (CAEndpoint_t**) OICCalloc(g_numberOfAdapters, sizeof(*tempInfo));
263     if (!tempInfo)
264     {
265         OIC_LOG(ERROR, TAG, "Out of memory!");
266         return CA_MEMORY_ALLOC_FAILED;
267     }
268     uint32_t *tempSize =(uint32_t*) OICCalloc(g_numberOfAdapters, sizeof(*tempSize));
269     if (!tempSize)
270     {
271         OIC_LOG(ERROR, TAG, "Out of memory!");
272         OICFree(tempInfo);
273         return CA_MEMORY_ALLOC_FAILED;
274     }
275
276     CAResult_t res = CA_STATUS_FAILED;
277     size_t resSize = 0;
278     for (uint32_t index = 0; index < g_numberOfAdapters; index++)
279     {
280         if (g_adapterHandler[index].GetnetInfo != NULL)
281         {
282             // #1. get information for each adapter
283             res = g_adapterHandler[index].GetnetInfo(&tempInfo[index],
284                                                      &tempSize[index]);
285
286             // #2. total size
287             if (res == CA_STATUS_OK)
288             {
289                 resSize += tempSize[index];
290             }
291
292             OIC_LOG_V(DEBUG,
293                       TAG,
294                       "%zu adapter network info size is %" PRIu32 " res:%d",
295                       index,
296                       tempSize[index],
297                       res);
298         }
299     }
300
301     OIC_LOG_V(DEBUG, TAG, "network info total size is %zu!", resSize);
302
303     if (resSize == 0)
304     {
305         OICFree(tempInfo);
306         OICFree(tempSize);
307         if (res == CA_ADAPTER_NOT_ENABLED || res == CA_NOT_SUPPORTED)
308         {
309             return res;
310         }
311         return CA_STATUS_FAILED;
312     }
313
314     // #3. add data into result
315     // memory allocation
316     CAEndpoint_t *resInfo = (CAEndpoint_t *) OICCalloc(resSize, sizeof (*resInfo));
317     CA_MEMORY_ALLOC_CHECK(resInfo);
318
319     // #4. save data
320     *info = resInfo;
321     *size = resSize;
322
323     for (uint32_t index = 0; index < g_numberOfAdapters; index++)
324     {
325         // check information
326         if (tempSize[index] == 0)
327         {
328             continue;
329         }
330
331         memcpy(resInfo,
332                tempInfo[index],
333                sizeof(*resInfo) * tempSize[index]);
334
335         resInfo += tempSize[index];
336
337         // free adapter data
338         OICFree(tempInfo[index]);
339         tempInfo[index] = NULL;
340     }
341     OICFree(tempInfo);
342     OICFree(tempSize);
343
344     OIC_LOG(DEBUG, TAG, "each network info save success!");
345     return CA_STATUS_OK;
346
347     // memory error label.
348 memory_error_exit:
349
350     for (uint32_t index = 0; index < g_numberOfAdapters; index++)
351     {
352         OICFree(tempInfo[index]);
353         tempInfo[index] = NULL;
354     }
355     OICFree(tempInfo);
356     OICFree(tempSize);
357
358     return CA_MEMORY_ALLOC_FAILED;
359 }
360
361 CAResult_t CASendUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
362 {
363     if (endpoint == NULL)
364     {
365         OIC_LOG(DEBUG, TAG, "Invalid endpoint");
366         return CA_STATUS_INVALID_PARAM;
367     }
368
369
370     u_arraylist_t *list = CAGetSelectedNetworkList();
371     if (!list)
372     {
373         OIC_LOG(ERROR, TAG, "No selected network");
374         return CA_SEND_FAILED;
375     }
376     CATransportAdapter_t requestedAdapter = endpoint->adapter ? endpoint->adapter : CA_ALL_ADAPTERS;
377
378     for (uint32_t i = 0; i < u_arraylist_length(list); i++)
379     {
380         void* ptrType = u_arraylist_get(list, i);
381
382         if (NULL == ptrType)
383         {
384             continue;
385         }
386
387         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
388         if (0 == (connType & requestedAdapter))
389         {
390             continue;
391         }
392
393         int index = CAGetAdapterIndex(connType);
394
395         if (-1 == index)
396         {
397             OIC_LOG(ERROR, TAG, "unknown transport type!");
398             return CA_STATUS_INVALID_PARAM;
399         }
400
401         int32_t sentDataLen = 0;
402
403         if (NULL != g_adapterHandler[index].sendData)
404         {
405             OIC_LOG(DEBUG, TAG, "unicast message to adapter");
406             sentDataLen = g_adapterHandler[index].sendData(endpoint, data, length);
407         }
408
409         if (sentDataLen != (int32_t)length)
410         {
411             OIC_LOG(ERROR, TAG, "error in sending data. Error will be reported in adapter");
412 #ifdef SINGLE_THREAD
413             //in case of single thread, no error handler. Report error immediately
414             return CA_SEND_FAILED;
415 #endif
416         }
417
418     }
419
420     return CA_STATUS_OK;
421 }
422
423 CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
424 {
425     u_arraylist_t *list = CAGetSelectedNetworkList();
426     if (!list)
427     {
428         OIC_LOG(DEBUG, TAG, "No selected network");
429         return CA_SEND_FAILED;
430     }
431
432     CATransportAdapter_t requestedAdapter = endpoint->adapter ? endpoint->adapter : CA_ALL_ADAPTERS;
433     size_t selectedLength = u_arraylist_length(list);
434     for (size_t i = 0; i < selectedLength; i++)
435     {
436         void* ptrType = u_arraylist_get(list, i);
437
438         if(NULL == ptrType)
439         {
440             continue;
441         }
442
443         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
444         if (0 == (connType & requestedAdapter))
445         {
446             continue;
447         }
448
449         int index = CAGetAdapterIndex(connType);
450         if (0 > index)
451         if (-1 == index)
452         {
453             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
454             continue;
455         }
456
457         uint32_t sentDataLen = 0;
458
459         if (NULL != g_adapterHandler[index].sendDataToAll)
460         {
461             void *payload = (void *) OICMalloc(length);
462             if (!payload)
463             {
464                 OIC_LOG(ERROR, TAG, "Out of memory!");
465                 return CA_MEMORY_ALLOC_FAILED;
466             }
467             memcpy(payload, data, length);
468             sentDataLen = g_adapterHandler[index].sendDataToAll(endpoint, payload, length);
469             OICFree(payload);
470         }
471
472         if (sentDataLen != length)
473         {
474             OIC_LOG(ERROR, TAG, "sendDataToAll failed! Error will be reported from adapter");
475 #ifdef SINGLE_THREAD
476             //in case of single thread, no error handler. Report error immediately
477             return CA_SEND_FAILED;
478 #endif
479         }
480     }
481
482     return CA_STATUS_OK;
483 }
484
485 CAResult_t CAStartListeningServerAdapters()
486 {
487     CAResult_t result = CA_STATUS_FAILED;
488
489     u_arraylist_t *list = CAGetSelectedNetworkList();
490     if (!list)
491     {
492         OIC_LOG(ERROR, TAG, "No selected network");
493         return result;
494     }
495
496     size_t length = u_arraylist_length(list);
497     for (size_t i = 0; i < length; i++)
498     {
499         void* ptrType = u_arraylist_get(list, i);
500
501         if(ptrType == NULL)
502         {
503             continue;
504         }
505
506         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
507
508         int index = CAGetAdapterIndex(connType);
509         if (0 > index)
510         {
511             OIC_LOG(ERROR, TAG, "unknown connectivity type!");
512             continue;
513         }
514
515         if (g_adapterHandler[index].startListenServer != NULL)
516         {
517             const CAResult_t tmp =
518                 g_adapterHandler[index].startListenServer();
519
520             // Successful listen if at least one adapter started.
521             if (CA_STATUS_OK == tmp)
522             {
523                 result = tmp;
524             }
525         }
526     }
527
528     return result;
529 }
530
531 CAResult_t CAStopListeningServerAdapters()
532 {
533     u_arraylist_t *list = CAGetSelectedNetworkList();
534     if (!list)
535     {
536         OIC_LOG(ERROR, TAG, "No selected network");
537         return CA_STATUS_FAILED;
538     }
539
540     size_t length = u_arraylist_length(list);
541     for (size_t i = 0; i < length; i++)
542     {
543         void* ptrType = u_arraylist_get(list, i);
544         if(ptrType == NULL)
545         {
546             continue;
547         }
548
549         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
550
551         int index = CAGetAdapterIndex(connType);
552         if (0 > index)
553         {
554             OIC_LOG(ERROR, TAG, "unknown connectivity type!");
555             continue;
556         }
557
558         if (g_adapterHandler[index].stopListenServer != NULL)
559         {
560             g_adapterHandler[index].stopListenServer();
561         }
562     }
563
564     return CA_STATUS_OK;
565 }
566
567 CAResult_t CAStartDiscoveryServerAdapters()
568 {
569     CAResult_t result = CA_STATUS_FAILED;
570
571     u_arraylist_t *list = CAGetSelectedNetworkList();
572
573     if (!list)
574     {
575         OIC_LOG(ERROR, TAG, "No selected network");
576         return result;
577     }
578
579     size_t length = u_arraylist_length(list);
580     for (size_t i = 0; i < length; i++)
581     {
582         void* ptrType = u_arraylist_get(list, i);
583
584         if(ptrType == NULL)
585         {
586             continue;
587         }
588
589         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
590
591         int index = CAGetAdapterIndex(connType);
592         if (0 > index)
593         {
594             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
595             continue;
596         }
597
598         if (g_adapterHandler[index].startDiscoveryServer != NULL)
599         {
600             const CAResult_t tmp =
601                 g_adapterHandler[index].startDiscoveryServer();
602
603             // Successful discovery if at least one adapter started.
604             if (CA_STATUS_OK == tmp)
605             {
606                 result = tmp;
607             }
608         }
609     }
610
611     return result;
612 }
613
614 void CATerminateAdapters()
615 {
616     for (uint32_t index = 0; index < g_numberOfAdapters; index++)
617     {
618         if (g_adapterHandler[index].terminate != NULL)
619         {
620             g_adapterHandler[index].terminate();
621         }
622     }
623
624     OICFree(g_adapterHandler);
625     g_adapterHandler = NULL;
626     g_numberOfAdapters = 0;
627 }
628
629 #ifdef SINGLE_THREAD
630 CAResult_t CAReadData()
631 {
632     u_arraylist_t *list = CAGetSelectedNetworkList();
633
634     if (!list)
635     {
636         return CA_STATUS_FAILED;
637     }
638
639     uint8_t i = 0;
640     for (i = 0; i < u_arraylist_length(list); i++)
641     {
642         void *ptrType = u_arraylist_get(list, i);
643         if (NULL == ptrType)
644         {
645             OIC_LOG(ERROR, TAG, "get list fail");
646             return CA_STATUS_FAILED;
647         }
648
649         CATransportAdapter_t connType = *(CATransportAdapter_t *) ptrType;
650
651         int index = CAGetAdapterIndex(connType);
652         if (0 > index)
653         {
654             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
655             continue;
656         }
657
658         if (g_adapterHandler[index].readData != NULL)
659         {
660             g_adapterHandler[index].readData();
661         }
662     }
663
664     return CA_STATUS_OK;
665 }
666 #endif
667