Merge branch 'master' into cloud-interface
[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         {
455             OIC_LOG(ERROR, TAG, "unknown connectivity type!");
456             continue;
457         }
458
459         uint32_t sentDataLen = 0;
460
461         if (NULL != g_adapterHandler[index].sendDataToAll)
462         {
463             void *payload = (void *) OICMalloc(length);
464             if (!payload)
465             {
466                 OIC_LOG(ERROR, TAG, "Out of memory!");
467                 return CA_MEMORY_ALLOC_FAILED;
468             }
469             memcpy(payload, data, length);
470             sentDataLen = g_adapterHandler[index].sendDataToAll(endpoint, payload, length);
471             OICFree(payload);
472         }
473
474         if (sentDataLen != length)
475         {
476             OIC_LOG(ERROR, TAG, "sendDataToAll failed! Error will be reported from adapter");
477 #ifdef SINGLE_THREAD
478             //in case of single thread, no error handler. Report error immediately
479             return CA_SEND_FAILED;
480 #endif
481         }
482     }
483
484     return CA_STATUS_OK;
485 }
486
487 CAResult_t CAStartListeningServerAdapters()
488 {
489     CAResult_t result = CA_STATUS_FAILED;
490
491     u_arraylist_t *list = CAGetSelectedNetworkList();
492     if (!list)
493     {
494         OIC_LOG(ERROR, TAG, "No selected network");
495         return result;
496     }
497
498     size_t length = u_arraylist_length(list);
499     for (size_t i = 0; i < length; i++)
500     {
501         void* ptrType = u_arraylist_get(list, i);
502
503         if(ptrType == NULL)
504         {
505             continue;
506         }
507
508         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
509
510         int index = CAGetAdapterIndex(connType);
511         if (0 > index)
512         {
513             OIC_LOG(ERROR, TAG, "unknown connectivity type!");
514             continue;
515         }
516
517         if (g_adapterHandler[index].startListenServer != NULL)
518         {
519             const CAResult_t tmp =
520                 g_adapterHandler[index].startListenServer();
521
522             // Successful listen if at least one adapter started.
523             if (CA_STATUS_OK == tmp)
524             {
525                 result = tmp;
526             }
527         }
528     }
529
530     return result;
531 }
532
533 CAResult_t CAStopListeningServerAdapters()
534 {
535     u_arraylist_t *list = CAGetSelectedNetworkList();
536     if (!list)
537     {
538         OIC_LOG(ERROR, TAG, "No selected network");
539         return CA_STATUS_FAILED;
540     }
541
542     size_t length = u_arraylist_length(list);
543     for (size_t i = 0; i < length; i++)
544     {
545         void* ptrType = u_arraylist_get(list, i);
546         if(ptrType == NULL)
547         {
548             continue;
549         }
550
551         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
552
553         int index = CAGetAdapterIndex(connType);
554         if (0 > index)
555         {
556             OIC_LOG(ERROR, TAG, "unknown connectivity type!");
557             continue;
558         }
559
560         if (g_adapterHandler[index].stopListenServer != NULL)
561         {
562             g_adapterHandler[index].stopListenServer();
563         }
564     }
565
566     return CA_STATUS_OK;
567 }
568
569 CAResult_t CAStartDiscoveryServerAdapters()
570 {
571     CAResult_t result = CA_STATUS_FAILED;
572
573     u_arraylist_t *list = CAGetSelectedNetworkList();
574
575     if (!list)
576     {
577         OIC_LOG(ERROR, TAG, "No selected network");
578         return result;
579     }
580
581     size_t length = u_arraylist_length(list);
582     for (size_t i = 0; i < length; i++)
583     {
584         void* ptrType = u_arraylist_get(list, i);
585
586         if(ptrType == NULL)
587         {
588             continue;
589         }
590
591         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
592
593         int index = CAGetAdapterIndex(connType);
594         if (0 > index)
595         {
596             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
597             continue;
598         }
599
600         if (g_adapterHandler[index].startDiscoveryServer != NULL)
601         {
602             const CAResult_t tmp =
603                 g_adapterHandler[index].startDiscoveryServer();
604
605             // Successful discovery if at least one adapter started.
606             if (CA_STATUS_OK == tmp)
607             {
608                 result = tmp;
609             }
610         }
611     }
612
613     return result;
614 }
615
616 void CATerminateAdapters()
617 {
618     for (uint32_t index = 0; index < g_numberOfAdapters; index++)
619     {
620         if (g_adapterHandler[index].terminate != NULL)
621         {
622             g_adapterHandler[index].terminate();
623         }
624     }
625
626     OICFree(g_adapterHandler);
627     g_adapterHandler = NULL;
628     g_numberOfAdapters = 0;
629 }
630
631 #ifdef SINGLE_THREAD
632 CAResult_t CAReadData()
633 {
634     u_arraylist_t *list = CAGetSelectedNetworkList();
635
636     if (!list)
637     {
638         return CA_STATUS_FAILED;
639     }
640
641     uint8_t i = 0;
642     for (i = 0; i < u_arraylist_length(list); i++)
643     {
644         void *ptrType = u_arraylist_get(list, i);
645         if (NULL == ptrType)
646         {
647             OIC_LOG(ERROR, TAG, "get list fail");
648             return CA_STATUS_FAILED;
649         }
650
651         CATransportAdapter_t connType = *(CATransportAdapter_t *) ptrType;
652
653         int index = CAGetAdapterIndex(connType);
654         if (0 > index)
655         {
656             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
657             continue;
658         }
659
660         if (g_adapterHandler[index].readData != NULL)
661         {
662             g_adapterHandler[index].readData();
663         }
664     }
665
666     return CA_STATUS_OK;
667 }
668 #endif
669