Merge branch 'master' into simulator
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / ip_adapter / caipadapter.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 #include "caipadapter.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <stdint.h>
26
27 #include "caipinterface.h"
28 #include "caqueueingthread.h"
29 #include "caadapterutils.h"
30 #ifdef __WITH_DTLS__
31 #include "caadapternetdtls.h"
32 #endif
33 #include "camutex.h"
34 #include "uarraylist.h"
35 #include "caremotehandler.h"
36 #include "logger.h"
37 #include "oic_malloc.h"
38 #include "oic_string.h"
39
40 /**
41  * Logging tag for module name.
42  */
43 #define TAG "IP_ADAP"
44
45 #ifndef SINGLE_THREAD
46 /**
47  * Holds inter thread ip data information.
48  */
49 typedef struct
50 {
51     CAEndpoint_t *remoteEndpoint;
52     void *data;
53     uint32_t dataLen;
54     bool isMulticast;
55 } CAIPData;
56
57 /**
58  * Queue handle for Send Data.
59  */
60 static CAQueueingThread_t *g_sendQueueHandle = NULL;
61 #endif
62
63 /**
64  * Network Packet Received Callback to CA.
65  */
66 static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
67
68 /**
69  * Network Changed Callback to CA.
70  */
71 static CANetworkChangeCallback g_networkChangeCallback = NULL;
72
73 /**
74  * error Callback to CA adapter.
75  */
76 static CAErrorHandleCallback g_errorCallback = NULL;
77
78 static void CAIPPacketReceivedCB(const CASecureEndpoint_t *endpoint,
79                                  const void *data, uint32_t dataLength);
80 #ifdef __WITH_DTLS__
81 static void CAIPPacketSendCB(CAEndpoint_t *endpoint,
82                              const void *data, uint32_t dataLength);
83 #endif
84
85 #ifndef SINGLE_THREAD
86
87 static CAResult_t CAIPInitializeQueueHandles();
88
89 static void CAIPDeinitializeQueueHandles();
90
91 static void CAIPSendDataThread(void *threadData);
92
93 static CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint,
94                                 const void *data, uint32_t dataLength,
95                                 bool isMulticast);
96 void CAFreeIPData(CAIPData *ipData);
97
98 static void CADataDestroyer(void *data, uint32_t size);
99
100 CAResult_t CAIPInitializeQueueHandles()
101 {
102     OIC_LOG(DEBUG, TAG, "IN");
103
104     // Check if the message queue is already initialized
105     if (g_sendQueueHandle)
106     {
107         OIC_LOG(DEBUG, TAG, "send queue handle is already initialized!");
108         return CA_STATUS_OK;
109     }
110
111     // Create send message queue
112     g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
113     if (!g_sendQueueHandle)
114     {
115         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
116         return CA_MEMORY_ALLOC_FAILED;
117     }
118
119     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle,
120                                 (const ca_thread_pool_t)caglobals.ip.threadpool,
121                                 CAIPSendDataThread, CADataDestroyer))
122     {
123         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
124         OICFree(g_sendQueueHandle);
125         g_sendQueueHandle = NULL;
126         return CA_STATUS_FAILED;
127     }
128
129     OIC_LOG(DEBUG, TAG, "OUT");
130     return CA_STATUS_OK;
131 }
132
133 void CAIPDeinitializeQueueHandles()
134 {
135     OIC_LOG(DEBUG, TAG, "IN");
136
137     CAQueueingThreadDestroy(g_sendQueueHandle);
138     OICFree(g_sendQueueHandle);
139     g_sendQueueHandle = NULL;
140
141     OIC_LOG(DEBUG, TAG, "OUT");
142 }
143
144 #endif // SINGLE_THREAD
145
146 void CAIPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
147 {
148     (void)ipAddress;
149     (void)status;
150     OIC_LOG(DEBUG, TAG, "IN");
151 }
152
153 #ifdef __WITH_DTLS__
154 static void CAIPPacketSendCB(CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
155 {
156     OIC_LOG(DEBUG, TAG, "IN");
157
158     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
159     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
160
161     CAIPSendData(endpoint, data, dataLength, false);
162
163     OIC_LOG(DEBUG, TAG, "OUT");
164 }
165 #endif
166
167
168 void CAIPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
169                           uint32_t dataLength)
170 {
171     OIC_LOG(DEBUG, TAG, "IN");
172
173     VERIFY_NON_NULL_VOID(sep, TAG, "sep is NULL");
174     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
175
176     OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
177
178     if (g_networkPacketCallback)
179     {
180         g_networkPacketCallback(sep, data, dataLength);
181     }
182     OIC_LOG(DEBUG, TAG, "OUT");
183 }
184
185 void CAIPErrorHandler (const CAEndpoint_t *endpoint, const void *data,
186                        uint32_t dataLength, CAResult_t result)
187 {
188     OIC_LOG(DEBUG, TAG, "IN");
189
190     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
191
192     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
193
194     void *buf = (void*)OICMalloc(sizeof(char) * dataLength);
195     if (!buf)
196     {
197         OIC_LOG(ERROR, TAG, "Memory Allocation failed!");
198         return;
199     }
200     memcpy(buf, data, dataLength);
201     if (g_errorCallback)
202     {
203         g_errorCallback(endpoint, buf, dataLength, result);
204     }
205     else
206     {
207         OICFree(buf);
208     }
209
210     OIC_LOG(DEBUG, TAG, "OUT");
211 }
212
213 static void CAInitializeIPGlobals()
214 {
215     caglobals.ip.u6.fd  = -1;
216     caglobals.ip.u6s.fd = -1;
217     caglobals.ip.u4.fd  = -1;
218     caglobals.ip.u4s.fd = -1;
219     caglobals.ip.m6.fd  = -1;
220     caglobals.ip.m6s.fd = -1;
221     caglobals.ip.m4.fd  = -1;
222     caglobals.ip.m4s.fd = -1;
223     caglobals.ip.u6.port  = 0;
224     caglobals.ip.u6s.port = 0;
225     caglobals.ip.u4.port  = 0;
226     caglobals.ip.u4s.port = 0;
227     caglobals.ip.m6.port  = CA_COAP;
228     caglobals.ip.m6s.port = CA_SECURE_COAP;
229     caglobals.ip.m4.port  = CA_COAP;
230     caglobals.ip.m4s.port = CA_SECURE_COAP;
231
232     CATransportFlags_t flags = 0;
233     if (caglobals.client)
234     {
235         flags |= caglobals.clientFlags;
236     }
237     if (caglobals.server)
238     {
239         flags |= caglobals.serverFlags;
240     }
241     caglobals.ip.ipv6enabled = flags & CA_IPV6;
242     caglobals.ip.ipv4enabled = flags & CA_IPV4;
243     caglobals.ip.dualstack = caglobals.ip.ipv6enabled && caglobals.ip.ipv4enabled;
244 }
245
246 CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
247                           CANetworkPacketReceivedCallback networkPacketCallback,
248                           CANetworkChangeCallback netCallback,
249                           CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
250 {
251     OIC_LOG(DEBUG, TAG, "IN");
252     VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
253     VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback");
254     VERIFY_NON_NULL(netCallback, TAG, "netCallback");
255 #ifndef SINGLE_THREAD
256     VERIFY_NON_NULL(handle, TAG, "thread pool handle");
257 #endif
258
259     g_networkChangeCallback = netCallback;
260     g_networkPacketCallback = networkPacketCallback;
261     g_errorCallback = errorCallback;
262
263     CAInitializeIPGlobals();
264     caglobals.ip.threadpool = handle;
265
266     CAIPSetPacketReceiveCallback(CAIPPacketReceivedCB);
267 #ifdef __WITH_DTLS__
268     CAAdapterNetDtlsInit();
269
270     CADTLSSetAdapterCallbacks(CAIPPacketReceivedCB, CAIPPacketSendCB, 0);
271 #endif
272
273     CAConnectivityHandler_t ipHandler;
274     ipHandler.startAdapter = CAStartIP;
275     ipHandler.startListenServer = CAStartIPListeningServer;
276     ipHandler.stopListenServer = CAStopIPListeningServer;
277     ipHandler.startDiscoveryServer = CAStartIPDiscoveryServer;
278     ipHandler.sendData = CASendIPUnicastData;
279     ipHandler.sendDataToAll = CASendIPMulticastData;
280     ipHandler.GetnetInfo = CAGetIPInterfaceInformation;
281     ipHandler.readData = CAReadIPData;
282     ipHandler.stopAdapter = CAStopIP;
283     ipHandler.terminate = CATerminateIP;
284     registerCallback(ipHandler, CA_ADAPTER_IP);
285
286     OIC_LOG(INFO, TAG, "OUT IntializeIP is Success");
287     return CA_STATUS_OK;
288 }
289
290 CAResult_t CAStartIP()
291 {
292     OIC_LOG(DEBUG, TAG, "IN");
293
294     CAIPStartNetworkMonitor();
295 #ifdef SINGLE_THREAD
296     uint16_t unicastPort = 55555;
297     // Address is hardcoded as we are using Single Interface
298     CAResult_t ret = CAIPStartServer();
299     if (CA_STATUS_OK != ret)
300     {
301         OIC_LOG_V(DEBUG, TAG, "CAIPStartServer failed[%d]", ret);
302         return ret;
303     }
304 #else
305     if (CA_STATUS_OK != CAIPInitializeQueueHandles())
306     {
307         OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
308         CATerminateIP();
309         return CA_STATUS_FAILED;
310     }
311
312     // Start send queue thread
313     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
314     {
315         OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
316         return CA_STATUS_FAILED;
317     }
318
319     CAResult_t ret = CAIPStartServer((const ca_thread_pool_t)caglobals.ip.threadpool);
320     if (CA_STATUS_OK != ret)
321     {
322         OIC_LOG_V(ERROR, TAG, "Failed to start server![%d]", ret);
323         return ret;
324     }
325
326 #endif
327
328     OIC_LOG(DEBUG, TAG, "OUT");
329     return CA_STATUS_OK;
330 }
331
332 CAResult_t CAStartIPListeningServer()
333 {
334     OIC_LOG(DEBUG, TAG, "IN");
335     CAResult_t ret = CAIPStartListenServer();
336     if (CA_STATUS_OK != ret)
337     {
338         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
339         return ret;
340     }
341     OIC_LOG(DEBUG, TAG, "OUT");
342     return CA_STATUS_OK;
343 }
344
345 CAResult_t CAStopIPListeningServer()
346 {
347     OIC_LOG(DEBUG, TAG, "IN");
348     CAResult_t ret = CAIPStopListenServer();
349     if (CA_STATUS_OK != ret)
350     {
351         OIC_LOG_V(ERROR, TAG, "Failed to stop listening server![%d]", ret);
352         return ret;
353     }
354     OIC_LOG(DEBUG, TAG, "OUT");
355     return CA_STATUS_OK;
356 }
357
358 CAResult_t CAStartIPDiscoveryServer()
359 {
360     OIC_LOG(DEBUG, TAG, "IN");
361     return CAStartIPListeningServer();
362 }
363
364 static int32_t CAQueueIPData(bool isMulticast, const CAEndpoint_t *endpoint,
365                             const void *data, uint32_t dataLength)
366 {
367     OIC_LOG(DEBUG, TAG, "IN");
368
369     VERIFY_NON_NULL_RET(endpoint, TAG, "remoteEndpoint", -1);
370     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
371
372     if (0 == dataLength)
373     {
374         OIC_LOG(ERROR, TAG, "Invalid Data Length");
375         return -1;
376     }
377
378 #ifdef SINGLE_THREAD
379
380     CAIPSendData(endpoint, data, dataLength, isMulticast);
381     return dataLength;
382
383 #else
384
385     VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
386     // Create IPData to add to queue
387     CAIPData *ipData = CACreateIPData(endpoint, data, dataLength, isMulticast);
388     if (!ipData)
389     {
390         OIC_LOG(ERROR, TAG, "Failed to create ipData!");
391         return -1;
392     }
393     // Add message to send queue
394     CAQueueingThreadAddData(g_sendQueueHandle, ipData, sizeof(CAIPData));
395
396 #endif // SINGLE_THREAD
397
398     OIC_LOG(DEBUG, TAG, "OUT");
399     return dataLength;
400 }
401
402 int32_t CASendIPUnicastData(const CAEndpoint_t *endpoint,
403                             const void *data, uint32_t dataLength)
404 {
405     OIC_LOG(DEBUG, TAG, "IN");
406     return CAQueueIPData(false, endpoint, data, dataLength);
407 }
408
409 int32_t CASendIPMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
410 {
411     OIC_LOG(DEBUG, TAG, "IN");
412     return CAQueueIPData(true, endpoint, data, dataLength);
413 }
414
415 CAResult_t CAReadIPData()
416 {
417     OIC_LOG(DEBUG, TAG, "IN");
418     CAIPPullData();
419     OIC_LOG(DEBUG, TAG, "OUT");
420     return CA_STATUS_OK;
421 }
422
423 CAResult_t CAStopIP()
424 {
425     OIC_LOG(DEBUG, TAG, "IN");
426
427 #ifdef __WITH_DTLS__
428     CAAdapterNetDtlsDeInit();
429 #endif
430
431 #ifndef SINGLE_THREAD
432     if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
433     {
434         CAQueueingThreadStop(g_sendQueueHandle);
435     }
436
437     CAIPDeinitializeQueueHandles();
438 #endif
439
440     CAIPStopNetworkMonitor();
441     CAIPStopServer();
442     //Re-initializing the Globals to start them again
443     CAInitializeIPGlobals();
444
445     OIC_LOG(DEBUG, TAG, "OUT");
446     return CA_STATUS_OK;
447 }
448
449 void CATerminateIP()
450 {
451     OIC_LOG(DEBUG, TAG, "IN");
452
453 #ifdef __WITH_DTLS__
454     CADTLSSetAdapterCallbacks(NULL, NULL, 0);
455 #endif
456
457     CAIPSetPacketReceiveCallback(NULL);
458
459 #ifndef SINGLE_THREAD
460     CAIPDeinitializeQueueHandles();
461 #endif
462
463     OIC_LOG(DEBUG, TAG, "OUT");
464 }
465
466 #ifndef SINGLE_THREAD
467
468 void CAIPSendDataThread(void *threadData)
469 {
470     OIC_LOG(DEBUG, TAG, "IN");
471
472     CAIPData *ipData = (CAIPData *) threadData;
473     if (!ipData)
474     {
475         OIC_LOG(DEBUG, TAG, "Invalid ip data!");
476         return;
477     }
478
479     if (ipData->isMulticast)
480     {
481         //Processing for sending multicast
482         OIC_LOG(DEBUG, TAG, "Send Multicast Data is called");
483         CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, true);
484     }
485     else
486     {
487         //Processing for sending unicast
488 #ifdef __WITH_DTLS__
489         if (ipData->remoteEndpoint->flags & CA_SECURE)
490         {
491             OIC_LOG(DEBUG, TAG, "CAAdapterNetDtlsEncrypt called!");
492             CAResult_t result = CAAdapterNetDtlsEncrypt(ipData->remoteEndpoint,
493                                                ipData->data, ipData->dataLen);
494             if (CA_STATUS_OK != result)
495             {
496                 OIC_LOG(ERROR, TAG, "CAAdapterNetDtlsEncrypt failed!");
497             }
498             OIC_LOG_V(DEBUG, TAG,
499                       "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
500         }
501         else
502         {
503             OIC_LOG(DEBUG, TAG, "Send Unicast Data is called");
504             CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, false);
505         }
506 #else
507         CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, false);
508 #endif
509     }
510
511     OIC_LOG(DEBUG, TAG, "OUT");
512 }
513
514 #endif
515
516 #ifndef SINGLE_THREAD
517
518 CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint, const void *data,
519                                      uint32_t dataLength, bool isMulticast)
520 {
521     VERIFY_NON_NULL_RET(data, TAG, "IPData is NULL", NULL);
522
523     CAIPData *ipData = (CAIPData *) OICMalloc(sizeof(CAIPData));
524     if (!ipData)
525     {
526         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
527         return NULL;
528     }
529
530     ipData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
531     ipData->data = (void *) OICMalloc(dataLength);
532     if (!ipData->data)
533     {
534         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
535         CAFreeIPData(ipData);
536         return NULL;
537     }
538
539     memcpy(ipData->data, data, dataLength);
540     ipData->dataLen = dataLength;
541
542     ipData->isMulticast = isMulticast;
543
544     return ipData;
545 }
546
547 void CAFreeIPData(CAIPData *ipData)
548 {
549     VERIFY_NON_NULL_VOID(ipData, TAG, "ipData is NULL");
550
551     CAFreeEndpoint(ipData->remoteEndpoint);
552     OICFree(ipData->data);
553     OICFree(ipData);
554 }
555
556 void CADataDestroyer(void *data, uint32_t size)
557 {
558     if (size < sizeof(CAIPData))
559     {
560         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
561     }
562     CAIPData *etdata = (CAIPData *) data;
563
564     CAFreeIPData(etdata);
565 }
566
567 #endif // SINGLE_THREAD