1 /* ****************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
26 #ifndef __STDC_FORMAT_MACROS
27 #define __STDC_FORMAT_MACROS
31 #include "cainterface.h"
32 #include "catcpadapter.h"
33 #include "catcpinterface.h"
34 #include "caqueueingthread.h"
35 #include "caadapterutils.h"
37 #include "uarraylist.h"
38 #include "caremotehandler.h"
40 #include "oic_malloc.h"
41 #include "oic_string.h"
44 * Logging tag for module name.
46 #define TAG "OIC_CA_TCP_ADAP"
49 * Holds internal thread TCP data information.
53 CAEndpoint_t *remoteEndpoint;
59 #define CA_TCP_LISTEN_BACKLOG 3
61 #define CA_TCP_SELECT_TIMEOUT 10
64 * Queue handle for Send Data.
66 static CAQueueingThread_t *g_sendQueueHandle = NULL;
69 * Network Packet Received Callback to CA.
71 static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
74 * Adapter Changed Callback to CA.
76 static CAAdapterChangeCallback g_networkChangeCallback = NULL;
79 * Connection Changed Callback to CA.
81 static CAConnectionChangeCallback g_connectionChangeCallback = NULL;
84 * error Callback to CA adapter.
86 static CAErrorHandleCallback g_errorCallback = NULL;
88 static void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep,
89 const void *data, uint32_t dataLength);
92 * KeepAlive Connected or Disconnected Callback to CA adapter.
94 static CAKeepAliveConnectionCallback g_connKeepAliveCallback = NULL;
96 static CAResult_t CATCPInitializeQueueHandles();
98 static void CATCPDeinitializeQueueHandles();
100 static void CATCPSendDataThread(void *threadData);
102 static CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint,
103 const void *data, size_t dataLength,
105 void CAFreeTCPData(CATCPData *ipData);
107 static void CADataDestroyer(void *data, uint32_t size);
109 CAResult_t CATCPInitializeQueueHandles()
111 // Check if the message queue is already initialized
112 if (g_sendQueueHandle)
114 OIC_LOG(DEBUG, TAG, "send queue handle is already initialized!");
118 // Create send message queue
119 g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
120 if (!g_sendQueueHandle)
122 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
123 return CA_MEMORY_ALLOC_FAILED;
126 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle,
127 (const ca_thread_pool_t)caglobals.tcp.threadpool,
128 CATCPSendDataThread, CADataDestroyer))
130 OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
131 OICFree(g_sendQueueHandle);
132 g_sendQueueHandle = NULL;
133 return CA_STATUS_FAILED;
139 void CATCPDeinitializeQueueHandles()
141 CAQueueingThreadDestroy(g_sendQueueHandle);
142 OICFree(g_sendQueueHandle);
143 g_sendQueueHandle = NULL;
146 void CATCPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
152 void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
155 VERIFY_NON_NULL_VOID(sep, TAG, "sep is NULL");
156 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
158 OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
160 if (g_networkPacketCallback)
162 g_networkPacketCallback(sep, data, dataLength);
166 void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
167 uint32_t dataLength, CAResult_t result)
169 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
170 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
174 g_errorCallback(endpoint, data, dataLength, result);
178 static void CATCPConnectionHandler(const char *addr, uint16_t port, bool isConnected)
180 CAEndpoint_t endpoint = { .adapter = CA_ADAPTER_TCP,
182 OICStrcpy(endpoint.addr, sizeof(endpoint.addr), addr);
184 // Pass the changed connection status to RI Layer for keepalive.
185 if (g_connKeepAliveCallback)
187 g_connKeepAliveCallback(&endpoint, isConnected);
190 // Pass the changed connection status to CAUtil.
191 if (g_connectionChangeCallback)
193 g_connectionChangeCallback(&endpoint, isConnected);
197 void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectionCallback ConnHandler)
199 g_connKeepAliveCallback = ConnHandler;
202 static void CAInitializeTCPGlobals()
204 caglobals.tcp.ipv4.fd = -1;
205 caglobals.tcp.ipv6.fd = -1;
206 caglobals.tcp.selectTimeout = CA_TCP_SELECT_TIMEOUT;
207 caglobals.tcp.listenBacklog = CA_TCP_LISTEN_BACKLOG;
208 caglobals.tcp.svrlist = NULL;
210 CATransportFlags_t flags = 0;
211 if (caglobals.client)
213 flags |= caglobals.clientFlags;
215 if (caglobals.server)
217 flags |= caglobals.serverFlags;
220 caglobals.tcp.ipv4tcpenabled = flags & CA_IPV4;
221 caglobals.tcp.ipv6tcpenabled = flags & CA_IPV6;
224 CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
225 CANetworkPacketReceivedCallback networkPacketCallback,
226 CAAdapterChangeCallback netCallback,
227 CAConnectionChangeCallback connCallback,
228 CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
230 OIC_LOG(DEBUG, TAG, "IN");
231 VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
232 VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback");
233 VERIFY_NON_NULL(netCallback, TAG, "netCallback");
234 #ifndef SINGLE_THREAD
235 VERIFY_NON_NULL(handle, TAG, "thread pool handle");
238 g_networkChangeCallback = netCallback;
239 g_connectionChangeCallback = connCallback;
240 g_networkPacketCallback = networkPacketCallback;
241 g_errorCallback = errorCallback;
243 CAInitializeTCPGlobals();
244 #ifndef SINGLE_THREAD
245 caglobals.tcp.threadpool = handle;
248 CATCPSetConnectionChangedCallback(CATCPConnectionHandler);
249 CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB);
250 CATCPSetErrorHandler(CATCPErrorHandler);
252 CAConnectivityHandler_t tcpHandler = {
253 .startAdapter = CAStartTCP,
254 .startListenServer = CAStartTCPListeningServer,
255 .stopListenServer = CAStopTCPListeningServer,
256 .startDiscoveryServer = CAStartTCPDiscoveryServer,
257 .sendData = CASendTCPUnicastData,
258 .sendDataToAll = CASendTCPMulticastData,
259 .GetnetInfo = CAGetTCPInterfaceInformation,
260 .readData = CAReadTCPData,
261 .stopAdapter = CAStopTCP,
262 .terminate = CATerminateTCP,
263 .cType = CA_ADAPTER_TCP};
265 registerCallback(tcpHandler);
267 OIC_LOG(INFO, TAG, "OUT IntializeTCP is Success");
271 CAResult_t CAStartTCP()
273 OIC_LOG(DEBUG, TAG, "IN");
275 // Specific the port number received from application.
276 caglobals.tcp.ipv4.port = caglobals.ports.tcp.u4;
277 caglobals.tcp.ipv6.port = caglobals.ports.tcp.u6;
279 #ifndef SINGLE_THREAD
280 if (CA_STATUS_OK != CATCPInitializeQueueHandles())
282 OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
284 return CA_STATUS_FAILED;
287 // Start send queue thread
288 if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
290 OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
291 return CA_STATUS_FAILED;
295 CAResult_t ret = CATCPStartServer();
296 if (CA_STATUS_OK != ret)
298 OIC_LOG_V(DEBUG, TAG, "CATCPStartServer failed[%d]", ret);
306 CAResult_t CAStartTCPListeningServer()
308 #ifndef SINGLE_THREAD
309 if (!caglobals.server)
311 caglobals.server = true; // only needed to run CA tests
314 CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
315 if (CA_STATUS_OK != ret)
317 OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
325 CAResult_t CAStopTCPListeningServer()
330 CAResult_t CAStartTCPDiscoveryServer()
332 if (!caglobals.client)
334 caglobals.client = true; // only needed to run CA tests
337 CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
338 if (CA_STATUS_OK != ret)
340 OIC_LOG_V(ERROR, TAG, "Failed to start discovery server![%d]", ret);
347 static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
348 const void *data, size_t dataLength)
350 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", -1);
351 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
355 OIC_LOG(ERROR, TAG, "Invalid Data Length");
359 VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
361 // Create TCPData to add to queue
362 CATCPData *tcpData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
365 OIC_LOG(ERROR, TAG, "Failed to create ipData!");
368 // Add message to send queue
369 CAQueueingThreadAddData(g_sendQueueHandle, tcpData, sizeof(CATCPData));
374 int32_t CASendTCPUnicastData(const CAEndpoint_t *endpoint,
375 const void *data, uint32_t dataLength)
377 OIC_LOG(DEBUG, TAG, "IN");
378 #ifndef SINGLE_THREAD
379 return CAQueueTCPData(false, endpoint, data, dataLength);
381 CATCPSendData(endpoint, data, dataLength, false);
386 int32_t CASendTCPMulticastData(const CAEndpoint_t *endpoint,
387 const void *data, uint32_t dataLength)
389 return CAQueueTCPData(true, endpoint, data, dataLength);
392 CAResult_t CAReadTCPData()
394 OIC_LOG(DEBUG, TAG, "IN");
401 CAResult_t CAStopTCP()
403 #ifndef SINGLE_THREAD
404 if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
406 CAQueueingThreadStop(g_sendQueueHandle);
412 //Re-initializing the Globals to start them again
413 CAInitializeTCPGlobals();
418 void CATerminateTCP()
420 CATCPSetPacketReceiveCallback(NULL);
422 #ifndef SINGLE_THREAD
423 CATCPDeinitializeQueueHandles();
427 void CATCPSendDataThread(void *threadData)
429 CATCPData *tcpData = (CATCPData *) threadData;
432 OIC_LOG(DEBUG, TAG, "Invalid TCP data!");
436 if (tcpData->isMulticast)
438 //Processing for sending multicast
439 OIC_LOG(DEBUG, TAG, "Send Multicast Data is called, not supported");
444 //Processing for sending unicast
445 CATCPSendData(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen, false);
449 CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint, const void *data,
450 size_t dataLength, bool isMulticast)
452 VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint is NULL", NULL);
453 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", NULL);
455 CATCPData *tcpData = (CATCPData *) OICCalloc(1, sizeof(*tcpData));
458 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
462 tcpData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
463 tcpData->data = (void *) OICMalloc(dataLength);
466 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
467 CAFreeTCPData(tcpData);
471 memcpy(tcpData->data, data, dataLength);
472 tcpData->dataLen = dataLength;
474 tcpData->isMulticast = isMulticast;
479 void CAFreeTCPData(CATCPData *tcpData)
481 VERIFY_NON_NULL_VOID(tcpData, TAG, "tcpData is NULL");
483 CAFreeEndpoint(tcpData->remoteEndpoint);
484 OICFree(tcpData->data);
488 void CADataDestroyer(void *data, uint32_t size)
490 if (size < sizeof(CATCPData))
492 OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
494 CATCPData *TCPData = (CATCPData *) data;
496 CAFreeTCPData(TCPData);
500 size_t CAGetTotalLengthFromPacketHeader(const unsigned char *recvBuffer, size_t size)
502 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
504 if (NULL == recvBuffer || !size)
506 OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
510 coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
511 ((unsigned char *)recvBuffer)[0] >> 4);
512 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
514 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
516 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
517 OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
518 OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
520 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
521 return headerLen + optPaylaodLen;
524 void CAGetTCPHeaderDetails(unsigned char* recvBuffer, coap_transport_type *transport,
527 if (NULL == recvBuffer)
529 OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
533 if (NULL == transport)
535 OIC_LOG(ERROR, TAG, "transport is NULL");
539 if (NULL == headerlen)
541 OIC_LOG(ERROR, TAG, "headerlen is NULL");
545 *transport = coap_get_tcp_header_type_from_initbyte(
546 ((unsigned char *)recvBuffer)[0] >> 4);
547 *headerlen = coap_get_tcp_header_length_for_transport(*transport);