Imported Upstream version 1.1.0
[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  * Network Changed Callback to CA.
75  */
76 static CANetworkChangeCallback g_networkChangeCallback = NULL;
77
78 /**
79  * error Callback to CA adapter.
80  */
81 static CAErrorHandleCallback g_errorCallback = NULL;
82
83 static void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep,
84                                   const void *data, uint32_t dataLength);
85
86 /**
87  * KeepAlive Connected Callback to CA adapter.
88  */
89 static CAKeepAliveConnectedCallback g_connCallback = NULL;
90
91 /**
92  * KeepAlive Disconnected Callback to CA adapter.
93  */
94 static CAKeepAliveDisconnectedCallback g_disconnCallback = 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 CATCPKeepAliveHandler(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     if (isConnected)
185     {
186         g_connCallback(&endpoint);
187     }
188     else
189     {
190         g_disconnCallback(&endpoint);
191     }
192 }
193
194 void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectedCallback ConnHandler,
195                                 CAKeepAliveDisconnectedCallback DisconnHandler)
196 {
197     g_connCallback = ConnHandler;
198     g_disconnCallback = DisconnHandler;
199
200     CATCPSetKeepAliveCallback(CATCPKeepAliveHandler);
201 }
202
203 static void CAInitializeTCPGlobals()
204 {
205     caglobals.tcp.selectTimeout = CA_TCP_SELECT_TIMEOUT;
206     caglobals.tcp.listenBacklog = CA_TCP_LISTEN_BACKLOG;
207     caglobals.tcp.svrlist = NULL;
208
209     CATransportFlags_t flags = 0;
210     if (caglobals.client)
211     {
212         flags |= caglobals.clientFlags;
213     }
214     if (caglobals.server)
215     {
216         flags |= caglobals.serverFlags;
217     }
218
219     caglobals.tcp.ipv4tcpenabled = flags & CA_IPV4;
220 }
221
222 CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
223                            CANetworkPacketReceivedCallback networkPacketCallback,
224                            CANetworkChangeCallback netCallback,
225                            CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
226 {
227     OIC_LOG(DEBUG, TAG, "IN");
228     VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
229     VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback");
230     VERIFY_NON_NULL(netCallback, TAG, "netCallback");
231     VERIFY_NON_NULL(handle, TAG, "thread pool handle");
232
233     g_networkChangeCallback = netCallback;
234     g_networkPacketCallback = networkPacketCallback;
235     g_errorCallback = errorCallback;
236
237     CAInitializeTCPGlobals();
238     caglobals.tcp.threadpool = handle;
239
240     CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB);
241     CATCPSetErrorHandler(CATCPErrorHandler);
242
243     CAConnectivityHandler_t tcpHandler = {
244         .startAdapter = CAStartTCP,
245         .startListenServer = CAStartTCPListeningServer,
246         .stopListenServer = CAStopTCPListeningServer,
247         .startDiscoveryServer = CAStartTCPDiscoveryServer,
248         .sendData = CASendTCPUnicastData,
249         .sendDataToAll = CASendTCPMulticastData,
250         .GetnetInfo = CAGetTCPInterfaceInformation,
251         .readData = CAReadTCPData,
252         .stopAdapter = CAStopTCP,
253         .terminate = CATerminateTCP,
254         .cType = CA_ADAPTER_TCP};
255
256     registerCallback(tcpHandler);
257
258     OIC_LOG(INFO, TAG, "OUT IntializeTCP is Success");
259     return CA_STATUS_OK;
260 }
261
262 CAResult_t CAStartTCP()
263 {
264     if (CA_STATUS_OK != CATCPInitializeQueueHandles())
265     {
266         OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
267         CATerminateTCP();
268         return CA_STATUS_FAILED;
269     }
270
271     // Start send queue thread
272     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
273     {
274         OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
275         return CA_STATUS_FAILED;
276     }
277
278     return CA_STATUS_OK;
279 }
280
281 CAResult_t CAStartTCPListeningServer()
282 {
283     if (!caglobals.server)
284     {
285         caglobals.server = true;    // only needed to run CA tests
286     }
287
288     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
289     if (CA_STATUS_OK != ret)
290     {
291         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
292         return ret;
293     }
294
295     return CA_STATUS_OK;
296 }
297
298 CAResult_t CAStopTCPListeningServer()
299 {
300     return CA_STATUS_OK;
301 }
302
303 CAResult_t CAStartTCPDiscoveryServer()
304 {
305     if (!caglobals.client)
306     {
307         caglobals.client = 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 discovery server![%d]", ret);
314         return ret;
315     }
316
317     return CA_STATUS_OK;
318 }
319
320 static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
321                              const void *data, size_t dataLength)
322 {
323     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", -1);
324     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
325
326     if (0 == dataLength)
327     {
328         OIC_LOG(ERROR, TAG, "Invalid Data Length");
329         return -1;
330     }
331
332     VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
333
334     // Create TCPData to add to queue
335     CATCPData *tcpData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
336     if (!tcpData)
337     {
338         OIC_LOG(ERROR, TAG, "Failed to create ipData!");
339         return -1;
340     }
341     // Add message to send queue
342     CAQueueingThreadAddData(g_sendQueueHandle, tcpData, sizeof(CATCPData));
343
344     return dataLength;
345 }
346
347 int32_t CASendTCPUnicastData(const CAEndpoint_t *endpoint,
348                              const void *data, uint32_t dataLength)
349 {
350     return CAQueueTCPData(false, endpoint, data, dataLength);
351 }
352
353 int32_t CASendTCPMulticastData(const CAEndpoint_t *endpoint,
354                                const void *data, uint32_t dataLength)
355 {
356     return CAQueueTCPData(true, endpoint, data, dataLength);
357 }
358
359 CAResult_t CAReadTCPData()
360 {
361     return CA_STATUS_OK;
362 }
363
364 CAResult_t CAStopTCP()
365 {
366     if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
367     {
368         CAQueueingThreadStop(g_sendQueueHandle);
369     }
370
371     CATCPStopServer();
372
373     //Re-initializing the Globals to start them again
374     CAInitializeTCPGlobals();
375
376     return CA_STATUS_OK;
377 }
378
379 void CATerminateTCP()
380 {
381     CATCPSetPacketReceiveCallback(NULL);
382
383     CATCPDeinitializeQueueHandles();
384 }
385
386 void CATCPSendDataThread(void *threadData)
387 {
388     CATCPData *tcpData = (CATCPData *) threadData;
389     if (!tcpData)
390     {
391         OIC_LOG(DEBUG, TAG, "Invalid TCP data!");
392         return;
393     }
394
395     if (tcpData->isMulticast)
396     {
397         //Processing for sending multicast
398         OIC_LOG(DEBUG, TAG, "Send Multicast Data is called, not supported");
399         return;
400     }
401     else
402     {
403         //Processing for sending unicast
404         CATCPSendData(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen, false);
405     }
406 }
407
408 CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint, const void *data,
409                            size_t dataLength, bool isMulticast)
410 {
411     VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint is NULL", NULL);
412     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", NULL);
413
414     CATCPData *tcpData = (CATCPData *) OICCalloc(1, sizeof(*tcpData));
415     if (!tcpData)
416     {
417         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
418         return NULL;
419     }
420
421     tcpData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
422     tcpData->data = (void *) OICMalloc(dataLength);
423     if (!tcpData->data)
424     {
425         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
426         CAFreeTCPData(tcpData);
427         return NULL;
428     }
429
430     memcpy(tcpData->data, data, dataLength);
431     tcpData->dataLen = dataLength;
432
433     tcpData->isMulticast = isMulticast;
434
435     return tcpData;
436 }
437
438 void CAFreeTCPData(CATCPData *tcpData)
439 {
440     VERIFY_NON_NULL_VOID(tcpData, TAG, "tcpData is NULL");
441
442     CAFreeEndpoint(tcpData->remoteEndpoint);
443     OICFree(tcpData->data);
444     OICFree(tcpData);
445 }
446
447 void CADataDestroyer(void *data, uint32_t size)
448 {
449     if (size < sizeof(CATCPData))
450     {
451         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
452     }
453     CATCPData *TCPData = (CATCPData *) data;
454
455     CAFreeTCPData(TCPData);
456 }