Merge branch 'master' into windows-port
[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         else
312         {
313             return CA_STATUS_FAILED;
314         }
315     }
316
317     // #3. add data into result
318     // memory allocation
319     CAEndpoint_t *resInfo = (CAEndpoint_t *) OICCalloc(resSize, sizeof (*resInfo));
320     CA_MEMORY_ALLOC_CHECK(resInfo);
321
322     // #4. save data
323     *info = resInfo;
324     *size = resSize;
325
326     for (uint32_t index = 0; index < g_numberOfAdapters; index++)
327     {
328         // check information
329         if (tempSize[index] == 0)
330         {
331             continue;
332         }
333
334         memcpy(resInfo,
335                tempInfo[index],
336                sizeof(*resInfo) * tempSize[index]);
337
338         resInfo += tempSize[index];
339
340         // free adapter data
341         OICFree(tempInfo[index]);
342         tempInfo[index] = NULL;
343     }
344     OICFree(tempInfo);
345     OICFree(tempSize);
346
347     OIC_LOG(DEBUG, TAG, "each network info save success!");
348     return CA_STATUS_OK;
349
350     // memory error label.
351 memory_error_exit:
352
353     for (uint32_t index = 0; index < g_numberOfAdapters; index++)
354     {
355         OICFree(tempInfo[index]);
356         tempInfo[index] = NULL;
357     }
358     OICFree(tempInfo);
359     OICFree(tempSize);
360
361     return CA_MEMORY_ALLOC_FAILED;
362 }
363
364 CAResult_t CASendUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
365 {
366     if (endpoint == NULL)
367     {
368         OIC_LOG(DEBUG, TAG, "Invalid endpoint");
369         return CA_STATUS_INVALID_PARAM;
370     }
371
372
373     u_arraylist_t *list = CAGetSelectedNetworkList();
374     if (!list)
375     {
376         OIC_LOG(ERROR, TAG, "No selected network");
377         return CA_SEND_FAILED;
378     }
379     CATransportAdapter_t requestedAdapter = endpoint->adapter ? endpoint->adapter : CA_ALL_ADAPTERS;
380
381     for (uint32_t i = 0; i < u_arraylist_length(list); i++)
382     {
383         void* ptrType = u_arraylist_get(list, i);
384
385         if (NULL == ptrType)
386         {
387             continue;
388         }
389
390         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
391         if (0 == (connType & requestedAdapter))
392         {
393             continue;
394         }
395
396         int index = CAGetAdapterIndex(connType);
397
398         if (-1 == index)
399         {
400             OIC_LOG(ERROR, TAG, "unknown transport type!");
401             return CA_STATUS_INVALID_PARAM;
402         }
403
404         int32_t sentDataLen = 0;
405
406         if (NULL != g_adapterHandler[index].sendData)
407         {
408             OIC_LOG(DEBUG, TAG, "unicast message to adapter");
409             sentDataLen = g_adapterHandler[index].sendData(endpoint, data, length);
410         }
411
412         if (sentDataLen != (int32_t)length)
413         {
414             OIC_LOG(ERROR, TAG, "error in sending data. Error will be reported in adapter");
415 #ifdef SINGLE_THREAD
416             //in case of single thread, no error handler. Report error immediately
417             return CA_SEND_FAILED;
418 #endif
419         }
420
421     }
422
423     return CA_STATUS_OK;
424 }
425
426 CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
427 {
428     u_arraylist_t *list = CAGetSelectedNetworkList();
429     if (!list)
430     {
431         OIC_LOG(DEBUG, TAG, "No selected network");
432         return CA_SEND_FAILED;
433     }
434
435     CATransportAdapter_t requestedAdapter = endpoint->adapter ? endpoint->adapter : CA_ALL_ADAPTERS;
436     size_t selectedLength = u_arraylist_length(list);
437     for (size_t i = 0; i < selectedLength; i++)
438     {
439         void* ptrType = u_arraylist_get(list, i);
440
441         if(NULL == ptrType)
442         {
443             continue;
444         }
445
446         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
447         if (0 == (connType & requestedAdapter))
448         {
449             continue;
450         }
451
452         int index = CAGetAdapterIndex(connType);
453         if (0 > index)
454         if (-1 == index)
455         {
456             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
457             continue;
458         }
459
460         uint32_t sentDataLen = 0;
461
462         if (NULL != g_adapterHandler[index].sendDataToAll)
463         {
464             void *payload = (void *) OICMalloc(length);
465             if (!payload)
466             {
467                 OIC_LOG(ERROR, TAG, "Out of memory!");
468                 return CA_MEMORY_ALLOC_FAILED;
469             }
470             memcpy(payload, data, length);
471             sentDataLen = g_adapterHandler[index].sendDataToAll(endpoint, payload, length);
472             OICFree(payload);
473         }
474
475         if (sentDataLen != length)
476         {
477             OIC_LOG(ERROR, TAG, "sendDataToAll failed! Error will be reported from adapter");
478 #ifdef SINGLE_THREAD
479             //in case of single thread, no error handler. Report error immediately
480             return CA_SEND_FAILED;
481 #endif
482         }
483     }
484
485     return CA_STATUS_OK;
486 }
487
488 CAResult_t CAStartListeningServerAdapters()
489 {
490     CAResult_t result = CA_STATUS_FAILED;
491
492     u_arraylist_t *list = CAGetSelectedNetworkList();
493     if (!list)
494     {
495         OIC_LOG(ERROR, TAG, "No selected network");
496         return result;
497     }
498
499     size_t length = u_arraylist_length(list);
500     for (size_t i = 0; i < length; i++)
501     {
502         void* ptrType = u_arraylist_get(list, i);
503
504         if(ptrType == NULL)
505         {
506             continue;
507         }
508
509         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
510
511         int index = CAGetAdapterIndex(connType);
512         if (0 > index)
513         {
514             OIC_LOG(ERROR, TAG, "unknown connectivity type!");
515             continue;
516         }
517
518         if (g_adapterHandler[index].startListenServer != NULL)
519         {
520             const CAResult_t tmp =
521                 g_adapterHandler[index].startListenServer();
522
523             // Successful listen if at least one adapter started.
524             if (CA_STATUS_OK == tmp)
525             {
526                 result = tmp;
527             }
528         }
529     }
530
531     return result;
532 }
533
534 CAResult_t CAStopListeningServerAdapters()
535 {
536     u_arraylist_t *list = CAGetSelectedNetworkList();
537     if (!list)
538     {
539         OIC_LOG(ERROR, TAG, "No selected network");
540         return CA_STATUS_FAILED;
541     }
542
543     size_t length = u_arraylist_length(list);
544     for (size_t i = 0; i < length; i++)
545     {
546         void* ptrType = u_arraylist_get(list, i);
547         if(ptrType == NULL)
548         {
549             continue;
550         }
551
552         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
553
554         int index = CAGetAdapterIndex(connType);
555         if (0 > index)
556         {
557             OIC_LOG(ERROR, TAG, "unknown connectivity type!");
558             continue;
559         }
560
561         if (g_adapterHandler[index].stopListenServer != NULL)
562         {
563             g_adapterHandler[index].stopListenServer();
564         }
565     }
566
567     return CA_STATUS_OK;
568 }
569
570 CAResult_t CAStartDiscoveryServerAdapters()
571 {
572     CAResult_t result = CA_STATUS_FAILED;
573
574     u_arraylist_t *list = CAGetSelectedNetworkList();
575
576     if (!list)
577     {
578         OIC_LOG(ERROR, TAG, "No selected network");
579         return result;
580     }
581
582     size_t length = u_arraylist_length(list);
583     for (size_t i = 0; i < length; i++)
584     {
585         void* ptrType = u_arraylist_get(list, i);
586
587         if(ptrType == NULL)
588         {
589             continue;
590         }
591
592         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
593
594         int index = CAGetAdapterIndex(connType);
595         if (0 > index)
596         {
597             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
598             continue;
599         }
600
601         if (g_adapterHandler[index].startDiscoveryServer != NULL)
602         {
603             const CAResult_t tmp =
604                 g_adapterHandler[index].startDiscoveryServer();
605
606             // Successful discovery if at least one adapter started.
607             if (CA_STATUS_OK == tmp)
608             {
609                 result = tmp;
610             }
611         }
612     }
613
614     return result;
615 }
616
617 void CATerminateAdapters()
618 {
619     for (uint32_t index = 0; index < g_numberOfAdapters; index++)
620     {
621         if (g_adapterHandler[index].terminate != NULL)
622         {
623             g_adapterHandler[index].terminate();
624         }
625     }
626
627     OICFree(g_adapterHandler);
628     g_adapterHandler = NULL;
629     g_numberOfAdapters = 0;
630 }
631
632 #ifdef SINGLE_THREAD
633 CAResult_t CAReadData()
634 {
635     u_arraylist_t *list = CAGetSelectedNetworkList();
636
637     if (!list)
638     {
639         return CA_STATUS_FAILED;
640     }
641
642     uint8_t i = 0;
643     for (i = 0; i < u_arraylist_length(list); i++)
644     {
645         void *ptrType = u_arraylist_get(list, i);
646         if (NULL == ptrType)
647         {
648             OIC_LOG(ERROR, TAG, "get list fail");
649             return CA_STATUS_FAILED;
650         }
651
652         CATransportAdapter_t connType = *(CATransportAdapter_t *) ptrType;
653
654         int index = CAGetAdapterIndex(connType);
655         if (0 > index)
656         {
657             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
658             continue;
659         }
660
661         if (g_adapterHandler[index].readData != NULL)
662         {
663             g_adapterHandler[index].readData();
664         }
665     }
666
667     return CA_STATUS_OK;
668 }
669 #endif
670