Merge branch '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 #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 CAEndpoint_t *endpoint, bool isConnected)
179 {
180     // Pass the changed connection status to RI Layer for keepalive.
181     if (g_connKeepAliveCallback)
182     {
183         g_connKeepAliveCallback(endpoint, isConnected);
184     }
185
186     // Pass the changed connection status to CAUtil.
187     if (g_connectionChangeCallback)
188     {
189         g_connectionChangeCallback(endpoint, isConnected);
190     }
191 }
192
193 void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectionCallback ConnHandler)
194 {
195     g_connKeepAliveCallback = ConnHandler;
196 }
197
198 static void CAInitializeTCPGlobals()
199 {
200     caglobals.tcp.ipv4.fd = -1;
201     caglobals.tcp.ipv6.fd = -1;
202     caglobals.tcp.selectTimeout = CA_TCP_SELECT_TIMEOUT;
203     caglobals.tcp.listenBacklog = CA_TCP_LISTEN_BACKLOG;
204     caglobals.tcp.svrlist = NULL;
205
206     CATransportFlags_t flags = 0;
207     if (caglobals.client)
208     {
209         flags |= caglobals.clientFlags;
210     }
211     if (caglobals.server)
212     {
213         flags |= caglobals.serverFlags;
214     }
215
216     caglobals.tcp.ipv4tcpenabled = flags & CA_IPV4;
217     caglobals.tcp.ipv6tcpenabled = flags & CA_IPV6;
218 }
219
220 CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
221                            CANetworkPacketReceivedCallback networkPacketCallback,
222                            CAAdapterChangeCallback netCallback,
223                            CAConnectionChangeCallback connCallback,
224                            CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
225 {
226     OIC_LOG(DEBUG, TAG, "IN");
227     VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
228     VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback");
229     VERIFY_NON_NULL(netCallback, TAG, "netCallback");
230 #ifndef SINGLE_THREAD
231     VERIFY_NON_NULL(handle, TAG, "thread pool handle");
232 #endif
233
234     g_networkChangeCallback = netCallback;
235     g_connectionChangeCallback = connCallback;
236     g_networkPacketCallback = networkPacketCallback;
237     g_errorCallback = errorCallback;
238
239     CAInitializeTCPGlobals();
240 #ifndef SINGLE_THREAD
241     caglobals.tcp.threadpool = handle;
242 #endif
243
244     CATCPSetConnectionChangedCallback(CATCPConnectionHandler);
245     CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB);
246     CATCPSetErrorHandler(CATCPErrorHandler);
247
248     CAConnectivityHandler_t tcpHandler = {
249         .startAdapter = CAStartTCP,
250         .startListenServer = CAStartTCPListeningServer,
251         .stopListenServer = CAStopTCPListeningServer,
252         .startDiscoveryServer = CAStartTCPDiscoveryServer,
253         .sendData = CASendTCPUnicastData,
254         .sendDataToAll = CASendTCPMulticastData,
255         .GetnetInfo = CAGetTCPInterfaceInformation,
256         .readData = CAReadTCPData,
257         .stopAdapter = CAStopTCP,
258         .terminate = CATerminateTCP,
259         .cType = CA_ADAPTER_TCP};
260
261     registerCallback(tcpHandler);
262
263     OIC_LOG(INFO, TAG, "OUT IntializeTCP is Success");
264     return CA_STATUS_OK;
265 }
266
267 CAResult_t CAStartTCP()
268 {
269     OIC_LOG(DEBUG, TAG, "IN");
270
271     // Specific the port number received from application.
272     caglobals.tcp.ipv4.port = caglobals.ports.tcp.u4;
273     caglobals.tcp.ipv6.port = caglobals.ports.tcp.u6;
274
275 #ifndef SINGLE_THREAD
276     if (CA_STATUS_OK != CATCPInitializeQueueHandles())
277     {
278         OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
279         CATerminateTCP();
280         return CA_STATUS_FAILED;
281     }
282
283     // Start send queue thread
284     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
285     {
286         OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
287         return CA_STATUS_FAILED;
288     }
289
290 #else
291     CAResult_t ret = CATCPStartServer();
292     if (CA_STATUS_OK != ret)
293     {
294         OIC_LOG_V(DEBUG, TAG, "CATCPStartServer failed[%d]", ret);
295         return ret;
296     }
297 #endif
298
299     return CA_STATUS_OK;
300 }
301
302 CAResult_t CAStartTCPListeningServer()
303 {
304 #ifndef SINGLE_THREAD
305     if (!caglobals.server)
306     {
307         caglobals.server = true;    // only needed to run CA tests
308     }
309
310     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
311     if (CA_STATUS_OK != ret)
312     {
313         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
314         return ret;
315     }
316 #endif
317
318     return CA_STATUS_OK;
319 }
320
321 CAResult_t CAStopTCPListeningServer()
322 {
323     return CA_STATUS_OK;
324 }
325
326 CAResult_t CAStartTCPDiscoveryServer()
327 {
328     if (!caglobals.client)
329     {
330         caglobals.client = true;    // only needed to run CA tests
331     }
332
333     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
334     if (CA_STATUS_OK != ret)
335     {
336         OIC_LOG_V(ERROR, TAG, "Failed to start discovery server![%d]", ret);
337         return ret;
338     }
339
340     return CA_STATUS_OK;
341 }
342
343 static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
344                              const void *data, size_t dataLength)
345 {
346     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", -1);
347     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
348
349     if (0 == dataLength)
350     {
351         OIC_LOG(ERROR, TAG, "Invalid Data Length");
352         return -1;
353     }
354
355     VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
356
357     // Create TCPData to add to queue
358     CATCPData *tcpData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
359     if (!tcpData)
360     {
361         OIC_LOG(ERROR, TAG, "Failed to create ipData!");
362         return -1;
363     }
364     // Add message to send queue
365     CAQueueingThreadAddData(g_sendQueueHandle, tcpData, sizeof(CATCPData));
366
367     return dataLength;
368 }
369
370 int32_t CASendTCPUnicastData(const CAEndpoint_t *endpoint,
371                              const void *data, uint32_t dataLength)
372 {
373     OIC_LOG(DEBUG, TAG, "IN");
374 #ifndef SINGLE_THREAD
375     return CAQueueTCPData(false, endpoint, data, dataLength);
376 #else
377     CATCPSendData(endpoint, data, dataLength, false);
378     return dataLength;
379 #endif
380 }
381
382 int32_t CASendTCPMulticastData(const CAEndpoint_t *endpoint,
383                                const void *data, uint32_t dataLength)
384 {
385     return CAQueueTCPData(true, endpoint, data, dataLength);
386 }
387
388 CAResult_t CAReadTCPData()
389 {
390     OIC_LOG(DEBUG, TAG, "IN");
391 #ifdef SINGLE_THREAD
392     CATCPPullData();
393 #endif
394     return CA_STATUS_OK;
395 }
396
397 CAResult_t CAStopTCP()
398 {
399 #ifndef SINGLE_THREAD
400     if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
401     {
402         CAQueueingThreadStop(g_sendQueueHandle);
403     }
404 #endif
405
406     CATCPStopServer();
407
408     //Re-initializing the Globals to start them again
409     CAInitializeTCPGlobals();
410
411     return CA_STATUS_OK;
412 }
413
414 void CATerminateTCP()
415 {
416     CATCPSetPacketReceiveCallback(NULL);
417
418 #ifndef SINGLE_THREAD
419     CATCPDeinitializeQueueHandles();
420 #endif
421 }
422
423 void CATCPSendDataThread(void *threadData)
424 {
425     CATCPData *tcpData = (CATCPData *) threadData;
426     if (!tcpData)
427     {
428         OIC_LOG(DEBUG, TAG, "Invalid TCP data!");
429         return;
430     }
431
432     if (tcpData->isMulticast)
433     {
434         //Processing for sending multicast
435         OIC_LOG(DEBUG, TAG, "Send Multicast Data is called, not supported");
436         return;
437     }
438     else
439     {
440         //Processing for sending unicast
441         CATCPSendData(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen, false);
442     }
443 }
444
445 CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint, const void *data,
446                            size_t dataLength, bool isMulticast)
447 {
448     VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint is NULL", NULL);
449     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", NULL);
450
451     CATCPData *tcpData = (CATCPData *) OICCalloc(1, sizeof(*tcpData));
452     if (!tcpData)
453     {
454         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
455         return NULL;
456     }
457
458     tcpData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
459     tcpData->data = (void *) OICMalloc(dataLength);
460     if (!tcpData->data)
461     {
462         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
463         CAFreeTCPData(tcpData);
464         return NULL;
465     }
466
467     memcpy(tcpData->data, data, dataLength);
468     tcpData->dataLen = dataLength;
469
470     tcpData->isMulticast = isMulticast;
471
472     return tcpData;
473 }
474
475 void CAFreeTCPData(CATCPData *tcpData)
476 {
477     VERIFY_NON_NULL_VOID(tcpData, TAG, "tcpData is NULL");
478
479     CAFreeEndpoint(tcpData->remoteEndpoint);
480     OICFree(tcpData->data);
481     OICFree(tcpData);
482 }
483
484 void CADataDestroyer(void *data, uint32_t size)
485 {
486     if (size < sizeof(CATCPData))
487     {
488         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
489     }
490     CATCPData *TCPData = (CATCPData *) data;
491
492     CAFreeTCPData(TCPData);
493 }
494
495 #ifdef SINGLE_THREAD
496 size_t CAGetTotalLengthFromPacketHeader(const unsigned char *recvBuffer, size_t size)
497 {
498     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
499
500     if (NULL == recvBuffer || !size)
501     {
502         OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
503         return 0;
504     }
505
506     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
507             ((unsigned char *)recvBuffer)[0] >> 4);
508     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
509                                                         transport);
510     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
511
512     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
513     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
514     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
515
516     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
517     return headerLen + optPaylaodLen;
518 }
519
520 void CAGetTCPHeaderDetails(unsigned char* recvBuffer, coap_transport_type *transport,
521                            size_t *headerlen)
522 {
523     if (NULL == recvBuffer)
524     {
525         OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
526         return;
527     }
528
529     if (NULL == transport)
530     {
531         OIC_LOG(ERROR, TAG, "transport is NULL");
532         return;
533     }
534
535     if (NULL == headerlen)
536     {
537         OIC_LOG(ERROR, TAG, "headerlen is NULL");
538         return;
539     }
540
541     *transport = coap_get_tcp_header_type_from_initbyte(
542         ((unsigned char *)recvBuffer)[0] >> 4);
543     *headerlen = coap_get_tcp_header_length_for_transport(*transport);
544 }
545 #endif