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