Merge remote-tracking branch 'origin/master' into notification-service
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / tcp_adapter / catcpadapter.c
1 /* ****************************************************************
2  *
3  * Copyright 2015 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 <stdint.h>
25
26 #ifndef __STDC_FORMAT_MACROS
27 #define __STDC_FORMAT_MACROS
28 #endif
29 #include <inttypes.h>
30
31 #include "cainterface.h"
32 #include "catcpadapter.h"
33 #include "catcpinterface.h"
34 #include "caqueueingthread.h"
35 #include "caadapterutils.h"
36 #include "camutex.h"
37 #include "uarraylist.h"
38 #include "caremotehandler.h"
39 #include "logger.h"
40 #include "oic_malloc.h"
41 #ifdef __WITH_TLS__
42 #include "ca_adapter_net_tls.h"
43 #endif
44
45 /**
46  * Logging tag for module name.
47  */
48 #define TAG "OIC_CA_TCP_ADAP"
49
50 /**
51  * Holds internal thread TCP data information.
52  */
53 typedef struct
54 {
55     CAEndpoint_t *remoteEndpoint;
56     void *data;
57     size_t dataLen;
58     bool isMulticast;
59 } CATCPData;
60
61 #define CA_TCP_LISTEN_BACKLOG  3
62
63 #define CA_TCP_SELECT_TIMEOUT 10
64
65 /**
66  * Queue handle for Send Data.
67  */
68 static CAQueueingThread_t *g_sendQueueHandle = NULL;
69
70 /**
71  * Network Packet Received Callback to CA.
72  */
73 static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
74
75 /**
76  * Adapter Changed Callback to CA.
77  */
78 static CAAdapterChangeCallback g_networkChangeCallback = NULL;
79
80 /**
81  * Connection Changed Callback to CA.
82  */
83 static CAConnectionChangeCallback g_connectionChangeCallback = NULL;
84
85 /**
86  * error Callback to CA adapter.
87  */
88 static CAErrorHandleCallback g_errorCallback = NULL;
89
90 static void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep,
91                                   const void *data, uint32_t dataLength);
92
93 /**
94  * KeepAlive Connected or Disconnected Callback to CA adapter.
95  */
96 static CAKeepAliveConnectionCallback g_connKeepAliveCallback = NULL;
97
98 static CAResult_t CATCPInitializeQueueHandles();
99
100 static void CATCPDeinitializeQueueHandles();
101
102 static void CATCPSendDataThread(void *threadData);
103
104 static CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint,
105                                   const void *data, size_t dataLength,
106                                   bool isMulticast);
107 void CAFreeTCPData(CATCPData *ipData);
108
109 static void CADataDestroyer(void *data, uint32_t size);
110
111 CAResult_t CATCPInitializeQueueHandles()
112 {
113     // Check if the message queue is already initialized
114     if (g_sendQueueHandle)
115     {
116         OIC_LOG(DEBUG, TAG, "send queue handle is already initialized!");
117         return CA_STATUS_OK;
118     }
119
120     // Create send message queue
121     g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
122     if (!g_sendQueueHandle)
123     {
124         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
125         return CA_MEMORY_ALLOC_FAILED;
126     }
127
128     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle,
129                                 (const ca_thread_pool_t)caglobals.tcp.threadpool,
130                                 CATCPSendDataThread, CADataDestroyer))
131     {
132         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
133         OICFree(g_sendQueueHandle);
134         g_sendQueueHandle = NULL;
135         return CA_STATUS_FAILED;
136     }
137
138     return CA_STATUS_OK;
139 }
140
141 void CATCPDeinitializeQueueHandles()
142 {
143     CAQueueingThreadDestroy(g_sendQueueHandle);
144     OICFree(g_sendQueueHandle);
145     g_sendQueueHandle = NULL;
146 }
147
148 void CATCPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
149 {
150     (void)ipAddress;
151     (void)status;
152 }
153
154 void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
155                            uint32_t dataLength)
156 {
157     VERIFY_NON_NULL_VOID(sep, TAG, "sep is NULL");
158     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
159
160     OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
161
162     if (g_networkPacketCallback)
163     {
164         g_networkPacketCallback(sep, data, dataLength);
165     }
166 }
167
168 #ifdef __WITH_TLS__
169 static void CATCPPacketSendCB(CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
170 {
171     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
172     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
173     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
174
175     OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", endpoint->addr, endpoint->port);
176     OIC_LOG_BUFFER(DEBUG, TAG, data, dataLength);
177
178     CATCPSendData(endpoint, data, dataLength, false);
179     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
180 }
181 #endif
182
183 void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
184                        uint32_t dataLength, CAResult_t result)
185 {
186     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
187     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
188
189     if (g_errorCallback)
190     {
191         g_errorCallback(endpoint, data, dataLength, result);
192     }
193 }
194
195 static void CATCPConnectionHandler(const CAEndpoint_t *endpoint, bool isConnected)
196 {
197     // Pass the changed connection status to RI Layer for keepalive.
198     if (g_connKeepAliveCallback)
199     {
200         g_connKeepAliveCallback(endpoint, isConnected);
201     }
202
203     // Pass the changed connection status to CAUtil.
204     if (g_connectionChangeCallback)
205     {
206         g_connectionChangeCallback(endpoint, isConnected);
207     }
208 }
209
210 void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectionCallback ConnHandler)
211 {
212     g_connKeepAliveCallback = ConnHandler;
213 }
214
215 static void CAInitializeTCPGlobals()
216 {
217     caglobals.tcp.ipv4.fd = -1;
218     caglobals.tcp.ipv6.fd = -1;
219     caglobals.tcp.selectTimeout = CA_TCP_SELECT_TIMEOUT;
220     caglobals.tcp.listenBacklog = CA_TCP_LISTEN_BACKLOG;
221     caglobals.tcp.svrlist = NULL;
222
223     CATransportFlags_t flags = 0;
224     if (caglobals.client)
225     {
226         flags |= caglobals.clientFlags;
227     }
228     if (caglobals.server)
229     {
230         flags |= caglobals.serverFlags;
231     }
232
233     caglobals.tcp.ipv4tcpenabled = flags & CA_IPV4;
234     caglobals.tcp.ipv6tcpenabled = flags & CA_IPV6;
235 }
236
237 CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
238                            CANetworkPacketReceivedCallback networkPacketCallback,
239                            CAAdapterChangeCallback netCallback,
240                            CAConnectionChangeCallback connCallback,
241                            CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
242 {
243     OIC_LOG(DEBUG, TAG, "IN");
244     VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
245     VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback");
246     VERIFY_NON_NULL(netCallback, TAG, "netCallback");
247 #ifndef SINGLE_THREAD
248     VERIFY_NON_NULL(handle, TAG, "thread pool handle");
249 #endif
250
251     g_networkChangeCallback = netCallback;
252     g_connectionChangeCallback = connCallback;
253     g_networkPacketCallback = networkPacketCallback;
254     g_errorCallback = errorCallback;
255
256     CAInitializeTCPGlobals();
257 #ifndef SINGLE_THREAD
258     caglobals.tcp.threadpool = handle;
259 #endif
260
261     CATCPSetConnectionChangedCallback(CATCPConnectionHandler);
262     CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB);
263     CATCPSetErrorHandler(CATCPErrorHandler);
264
265 #ifdef __WITH_TLS__
266     CAinitTlsAdapter();
267     CAsetTlsAdapterCallbacks(CATCPPacketReceivedCB, CATCPPacketSendCB, 0);
268 #endif
269
270     CAConnectivityHandler_t tcpHandler = {
271         .startAdapter = CAStartTCP,
272         .startListenServer = CAStartTCPListeningServer,
273         .stopListenServer = CAStopTCPListeningServer,
274         .startDiscoveryServer = CAStartTCPDiscoveryServer,
275         .sendData = CASendTCPUnicastData,
276         .sendDataToAll = CASendTCPMulticastData,
277         .GetnetInfo = CAGetTCPInterfaceInformation,
278         .readData = CAReadTCPData,
279         .stopAdapter = CAStopTCP,
280         .terminate = CATerminateTCP,
281         .cType = CA_ADAPTER_TCP};
282
283     registerCallback(tcpHandler);
284
285     OIC_LOG(INFO, TAG, "OUT IntializeTCP is Success");
286     return CA_STATUS_OK;
287 }
288
289 CAResult_t CAStartTCP()
290 {
291     OIC_LOG(DEBUG, TAG, "IN");
292
293     // Specific the port number received from application.
294     caglobals.tcp.ipv4.port = caglobals.ports.tcp.u4;
295     caglobals.tcp.ipv6.port = caglobals.ports.tcp.u6;
296
297 #ifndef SINGLE_THREAD
298     if (CA_STATUS_OK != CATCPInitializeQueueHandles())
299     {
300         OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
301         CATerminateTCP();
302         return CA_STATUS_FAILED;
303     }
304
305     // Start send queue thread
306     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
307     {
308         OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
309         return CA_STATUS_FAILED;
310     }
311
312 #else
313     CAResult_t ret = CATCPStartServer();
314     if (CA_STATUS_OK != ret)
315     {
316         OIC_LOG_V(DEBUG, TAG, "CATCPStartServer failed[%d]", ret);
317         return ret;
318     }
319 #endif
320
321     return CA_STATUS_OK;
322 }
323
324 CAResult_t CAStartTCPListeningServer()
325 {
326 #ifndef SINGLE_THREAD
327     if (!caglobals.server)
328     {
329         caglobals.server = true;    // only needed to run CA tests
330     }
331
332     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
333     if (CA_STATUS_OK != ret)
334     {
335         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
336         return ret;
337     }
338 #endif
339
340     return CA_STATUS_OK;
341 }
342
343 CAResult_t CAStopTCPListeningServer()
344 {
345     return CA_STATUS_OK;
346 }
347
348 CAResult_t CAStartTCPDiscoveryServer()
349 {
350     if (!caglobals.client)
351     {
352         caglobals.client = true;    // only needed to run CA tests
353     }
354
355     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
356     if (CA_STATUS_OK != ret)
357     {
358         OIC_LOG_V(ERROR, TAG, "Failed to start discovery server![%d]", ret);
359         return ret;
360     }
361
362     return CA_STATUS_OK;
363 }
364
365 static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
366                              const void *data, size_t dataLength)
367 {
368     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", -1);
369     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
370
371     if (0 == dataLength)
372     {
373         OIC_LOG(ERROR, TAG, "Invalid Data Length");
374         return -1;
375     }
376
377     VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
378
379     // Create TCPData to add to queue
380     CATCPData *tcpData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
381     if (!tcpData)
382     {
383         OIC_LOG(ERROR, TAG, "Failed to create ipData!");
384         return -1;
385     }
386     // Add message to send queue
387     CAQueueingThreadAddData(g_sendQueueHandle, tcpData, sizeof(CATCPData));
388
389     return dataLength;
390 }
391
392 int32_t CASendTCPUnicastData(const CAEndpoint_t *endpoint,
393                              const void *data, uint32_t dataLength,
394                              CADataType_t dataType)
395 {
396     OIC_LOG(DEBUG, TAG, "IN");
397     (void)dataType;
398 #ifndef SINGLE_THREAD
399     return CAQueueTCPData(false, endpoint, data, dataLength);
400 #else
401     CATCPSendData(endpoint, data, dataLength, false);
402     return dataLength;
403 #endif
404 }
405
406 int32_t CASendTCPMulticastData(const CAEndpoint_t *endpoint,
407                                const void *data, uint32_t dataLength,
408                                CADataType_t dataType)
409 {
410     (void)dataType;
411     return CAQueueTCPData(true, endpoint, data, dataLength);
412 }
413
414 CAResult_t CAReadTCPData()
415 {
416     OIC_LOG(DEBUG, TAG, "IN");
417 #ifdef SINGLE_THREAD
418     CATCPPullData();
419 #endif
420     return CA_STATUS_OK;
421 }
422
423 CAResult_t CAStopTCP()
424 {
425 #ifndef SINGLE_THREAD
426     if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
427     {
428         CAQueueingThreadStop(g_sendQueueHandle);
429     }
430 #endif
431
432     CATCPStopServer();
433
434     //Re-initializing the Globals to start them again
435     CAInitializeTCPGlobals();
436
437 #ifdef __WITH_TLS__
438     CAdeinitTlsAdapter();
439 #endif
440
441     return CA_STATUS_OK;
442 }
443
444 void CATerminateTCP()
445 {
446     CATCPSetPacketReceiveCallback(NULL);
447
448 #ifndef SINGLE_THREAD
449     CATCPDeinitializeQueueHandles();
450 #endif
451 }
452
453 void CATCPSendDataThread(void *threadData)
454 {
455     CATCPData *tcpData = (CATCPData *) threadData;
456     if (!tcpData)
457     {
458         OIC_LOG(DEBUG, TAG, "Invalid TCP data!");
459         return;
460     }
461
462     if (tcpData->isMulticast)
463     {
464         //Processing for sending multicast
465         OIC_LOG(DEBUG, TAG, "Send Multicast Data is called, not supported");
466         return;
467     }
468     else
469     {
470 #ifdef __WITH_TLS__
471          if (tcpData->remoteEndpoint && tcpData->remoteEndpoint->flags & CA_SECURE)
472          {
473              CAResult_t result = CA_STATUS_OK;
474              OIC_LOG(DEBUG, TAG, "CAencryptTls called!");
475              result = CAencryptTls(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
476
477              if (CA_STATUS_OK != result)
478              {
479                  OIC_LOG(ERROR, TAG, "CAAdapterNetDtlsEncrypt failed!");
480              }
481              OIC_LOG_V(DEBUG, TAG,
482                        "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
483             return;
484          }
485 #endif
486         //Processing for sending unicast
487         CATCPSendData(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen, false);
488     }
489 }
490
491 CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint, const void *data,
492                            size_t dataLength, bool isMulticast)
493 {
494     VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint is NULL", NULL);
495     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", NULL);
496
497     CATCPData *tcpData = (CATCPData *) OICCalloc(1, sizeof(*tcpData));
498     if (!tcpData)
499     {
500         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
501         return NULL;
502     }
503
504     tcpData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
505     tcpData->data = (void *) OICMalloc(dataLength);
506     if (!tcpData->data)
507     {
508         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
509         CAFreeTCPData(tcpData);
510         return NULL;
511     }
512
513     memcpy(tcpData->data, data, dataLength);
514     tcpData->dataLen = dataLength;
515
516     tcpData->isMulticast = isMulticast;
517
518     return tcpData;
519 }
520
521 void CAFreeTCPData(CATCPData *tcpData)
522 {
523     VERIFY_NON_NULL_VOID(tcpData, TAG, "tcpData is NULL");
524
525     CAFreeEndpoint(tcpData->remoteEndpoint);
526     OICFree(tcpData->data);
527     OICFree(tcpData);
528 }
529
530 void CADataDestroyer(void *data, uint32_t size)
531 {
532     if (size < sizeof(CATCPData))
533     {
534         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
535     }
536     CATCPData *TCPData = (CATCPData *) data;
537
538     CAFreeTCPData(TCPData);
539 }
540
541 #ifdef SINGLE_THREAD
542 size_t CAGetTotalLengthFromPacketHeader(const unsigned char *recvBuffer, size_t size)
543 {
544     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
545
546     if (NULL == recvBuffer || !size)
547     {
548         OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
549         return 0;
550     }
551
552     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
553             ((unsigned char *)recvBuffer)[0] >> 4);
554     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
555                                                         transport);
556     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
557
558     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
559     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
560     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
561
562     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
563     return headerLen + optPaylaodLen;
564 }
565
566 void CAGetTCPHeaderDetails(unsigned char* recvBuffer, coap_transport_type *transport,
567                            size_t *headerlen)
568 {
569     if (NULL == recvBuffer)
570     {
571         OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
572         return;
573     }
574
575     if (NULL == transport)
576     {
577         OIC_LOG(ERROR, TAG, "transport is NULL");
578         return;
579     }
580
581     if (NULL == headerlen)
582     {
583         OIC_LOG(ERROR, TAG, "headerlen is NULL");
584         return;
585     }
586
587     *transport = coap_get_tcp_header_type_from_initbyte(
588         ((unsigned char *)recvBuffer)[0] >> 4);
589     *headerlen = coap_get_tcp_header_length_for_transport(*transport);
590 }
591 #endif