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"
42 #include "ca_adapter_net_tls.h"
46 * Logging tag for module name.
48 #define TAG "OIC_CA_TCP_ADAP"
51 * Holds internal thread TCP data information.
55 CAEndpoint_t *remoteEndpoint;
61 #define CA_TCP_LISTEN_BACKLOG 3
63 #define CA_TCP_SELECT_TIMEOUT 10
66 * Queue handle for Send Data.
68 static CAQueueingThread_t *g_sendQueueHandle = NULL;
71 * Network Packet Received Callback to CA.
73 static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
76 * Adapter Changed Callback to CA.
78 static CAAdapterChangeCallback g_networkChangeCallback = NULL;
81 * Connection Changed Callback to CA.
83 static CAConnectionChangeCallback g_connectionChangeCallback = NULL;
86 * error Callback to CA adapter.
88 static CAErrorHandleCallback g_errorCallback = NULL;
90 static void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep,
91 const void *data, uint32_t dataLength);
94 * KeepAlive Connected or Disconnected Callback to CA adapter.
96 static CAKeepAliveConnectionCallback g_connKeepAliveCallback = NULL;
98 static CAResult_t CATCPInitializeQueueHandles();
100 static void CATCPDeinitializeQueueHandles();
102 static void CATCPSendDataThread(void *threadData);
104 static CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint,
105 const void *data, size_t dataLength,
107 void CAFreeTCPData(CATCPData *ipData);
109 static void CADataDestroyer(void *data, uint32_t size);
111 CAResult_t CATCPInitializeQueueHandles()
113 // Check if the message queue is already initialized
114 if (g_sendQueueHandle)
116 OIC_LOG(DEBUG, TAG, "send queue handle is already initialized!");
120 // Create send message queue
121 g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
122 if (!g_sendQueueHandle)
124 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
125 return CA_MEMORY_ALLOC_FAILED;
128 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle,
129 (const ca_thread_pool_t)caglobals.tcp.threadpool,
130 CATCPSendDataThread, CADataDestroyer))
132 OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
133 OICFree(g_sendQueueHandle);
134 g_sendQueueHandle = NULL;
135 return CA_STATUS_FAILED;
141 void CATCPDeinitializeQueueHandles()
143 CAQueueingThreadDestroy(g_sendQueueHandle);
144 OICFree(g_sendQueueHandle);
145 g_sendQueueHandle = NULL;
148 void CATCPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
154 void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
157 VERIFY_NON_NULL_VOID(sep, TAG, "sep is NULL");
158 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
160 OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
162 if (g_networkPacketCallback)
164 g_networkPacketCallback(sep, data, dataLength);
169 static void CATCPPacketSendCB(CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
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");
175 OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", endpoint->addr, endpoint->port);
176 OIC_LOG_BUFFER(DEBUG, TAG, data, dataLength);
178 CATCPSendData(endpoint, data, dataLength, false);
179 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
183 void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
184 uint32_t dataLength, CAResult_t result)
186 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
187 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
191 g_errorCallback(endpoint, data, dataLength, result);
195 static void CATCPConnectionHandler(const CAEndpoint_t *endpoint, bool isConnected)
197 // Pass the changed connection status to RI Layer for keepalive.
198 if (g_connKeepAliveCallback)
200 g_connKeepAliveCallback(endpoint, isConnected);
203 // Pass the changed connection status to CAUtil.
204 if (g_connectionChangeCallback)
206 g_connectionChangeCallback(endpoint, isConnected);
210 void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectionCallback ConnHandler)
212 g_connKeepAliveCallback = ConnHandler;
215 static void CAInitializeTCPGlobals()
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;
223 CATransportFlags_t flags = 0;
224 if (caglobals.client)
226 flags |= caglobals.clientFlags;
228 if (caglobals.server)
230 flags |= caglobals.serverFlags;
233 caglobals.tcp.ipv4tcpenabled = flags & CA_IPV4;
234 caglobals.tcp.ipv6tcpenabled = flags & CA_IPV6;
237 CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
238 CANetworkPacketReceivedCallback networkPacketCallback,
239 CAAdapterChangeCallback netCallback,
240 CAConnectionChangeCallback connCallback,
241 CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
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");
251 g_networkChangeCallback = netCallback;
252 g_connectionChangeCallback = connCallback;
253 g_networkPacketCallback = networkPacketCallback;
254 g_errorCallback = errorCallback;
256 CAInitializeTCPGlobals();
257 #ifndef SINGLE_THREAD
258 caglobals.tcp.threadpool = handle;
261 CATCPSetConnectionChangedCallback(CATCPConnectionHandler);
262 CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB);
263 CATCPSetErrorHandler(CATCPErrorHandler);
267 CAsetTlsAdapterCallbacks(CATCPPacketReceivedCB, CATCPPacketSendCB, 0);
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};
283 registerCallback(tcpHandler);
285 OIC_LOG(INFO, TAG, "OUT IntializeTCP is Success");
289 CAResult_t CAStartTCP()
291 OIC_LOG(DEBUG, TAG, "IN");
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;
297 #ifndef SINGLE_THREAD
298 if (CA_STATUS_OK != CATCPInitializeQueueHandles())
300 OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
302 return CA_STATUS_FAILED;
305 // Start send queue thread
306 if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
308 OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
309 return CA_STATUS_FAILED;
313 CAResult_t ret = CATCPStartServer();
314 if (CA_STATUS_OK != ret)
316 OIC_LOG_V(DEBUG, TAG, "CATCPStartServer failed[%d]", ret);
324 CAResult_t CAStartTCPListeningServer()
326 #ifndef SINGLE_THREAD
327 if (!caglobals.server)
329 caglobals.server = true; // only needed to run CA tests
332 CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
333 if (CA_STATUS_OK != ret)
335 OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
343 CAResult_t CAStopTCPListeningServer()
348 CAResult_t CAStartTCPDiscoveryServer()
350 if (!caglobals.client)
352 caglobals.client = true; // only needed to run CA tests
355 CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
356 if (CA_STATUS_OK != ret)
358 OIC_LOG_V(ERROR, TAG, "Failed to start discovery server![%d]", ret);
365 static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
366 const void *data, size_t dataLength)
368 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", -1);
369 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
373 OIC_LOG(ERROR, TAG, "Invalid Data Length");
377 VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
379 // Create TCPData to add to queue
380 CATCPData *tcpData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
383 OIC_LOG(ERROR, TAG, "Failed to create ipData!");
386 // Add message to send queue
387 CAQueueingThreadAddData(g_sendQueueHandle, tcpData, sizeof(CATCPData));
392 int32_t CASendTCPUnicastData(const CAEndpoint_t *endpoint,
393 const void *data, uint32_t dataLength,
394 CADataType_t dataType)
396 OIC_LOG(DEBUG, TAG, "IN");
398 #ifndef SINGLE_THREAD
399 return CAQueueTCPData(false, endpoint, data, dataLength);
401 CATCPSendData(endpoint, data, dataLength, false);
406 int32_t CASendTCPMulticastData(const CAEndpoint_t *endpoint,
407 const void *data, uint32_t dataLength,
408 CADataType_t dataType)
411 return CAQueueTCPData(true, endpoint, data, dataLength);
414 CAResult_t CAReadTCPData()
416 OIC_LOG(DEBUG, TAG, "IN");
423 CAResult_t CAStopTCP()
425 #ifndef SINGLE_THREAD
426 if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
428 CAQueueingThreadStop(g_sendQueueHandle);
434 //Re-initializing the Globals to start them again
435 CAInitializeTCPGlobals();
438 CAdeinitTlsAdapter();
444 void CATerminateTCP()
446 CATCPSetPacketReceiveCallback(NULL);
448 #ifndef SINGLE_THREAD
449 CATCPDeinitializeQueueHandles();
453 void CATCPSendDataThread(void *threadData)
455 CATCPData *tcpData = (CATCPData *) threadData;
458 OIC_LOG(DEBUG, TAG, "Invalid TCP data!");
462 if (tcpData->isMulticast)
464 //Processing for sending multicast
465 OIC_LOG(DEBUG, TAG, "Send Multicast Data is called, not supported");
471 if (tcpData->remoteEndpoint && tcpData->remoteEndpoint->flags & CA_SECURE)
473 CAResult_t result = CA_STATUS_OK;
474 OIC_LOG(DEBUG, TAG, "CAencryptTls called!");
475 result = CAencryptTls(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
477 if (CA_STATUS_OK != result)
479 OIC_LOG(ERROR, TAG, "CAAdapterNetDtlsEncrypt failed!");
481 OIC_LOG_V(DEBUG, TAG,
482 "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
486 //Processing for sending unicast
487 CATCPSendData(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen, false);
491 CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint, const void *data,
492 size_t dataLength, bool isMulticast)
494 VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint is NULL", NULL);
495 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", NULL);
497 CATCPData *tcpData = (CATCPData *) OICCalloc(1, sizeof(*tcpData));
500 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
504 tcpData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
505 tcpData->data = (void *) OICMalloc(dataLength);
508 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
509 CAFreeTCPData(tcpData);
513 memcpy(tcpData->data, data, dataLength);
514 tcpData->dataLen = dataLength;
516 tcpData->isMulticast = isMulticast;
521 void CAFreeTCPData(CATCPData *tcpData)
523 VERIFY_NON_NULL_VOID(tcpData, TAG, "tcpData is NULL");
525 CAFreeEndpoint(tcpData->remoteEndpoint);
526 OICFree(tcpData->data);
530 void CADataDestroyer(void *data, uint32_t size)
532 if (size < sizeof(CATCPData))
534 OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
536 CATCPData *TCPData = (CATCPData *) data;
538 CAFreeTCPData(TCPData);
542 size_t CAGetTotalLengthFromPacketHeader(const unsigned char *recvBuffer, size_t size)
544 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
546 if (NULL == recvBuffer || !size)
548 OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
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,
556 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
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);
562 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
563 return headerLen + optPaylaodLen;
566 void CAGetTCPHeaderDetails(unsigned char* recvBuffer, coap_transport_type *transport,
569 if (NULL == recvBuffer)
571 OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
575 if (NULL == transport)
577 OIC_LOG(ERROR, TAG, "transport is NULL");
581 if (NULL == headerlen)
583 OIC_LOG(ERROR, TAG, "headerlen is NULL");
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);