Merge branch 'master' into simulator
[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 #define __STDC_FORMAT_MACROS
27 #include <inttypes.h>
28
29 #include "catcpadapter.h"
30 #include "catcpinterface.h"
31 #include "caqueueingthread.h"
32 #include "caadapterutils.h"
33 #include "camutex.h"
34 #include "uarraylist.h"
35 #include "caremotehandler.h"
36 #include "logger.h"
37 #include "oic_malloc.h"
38 #include "oic_string.h"
39
40 /**
41  * Logging tag for module name.
42  */
43 #define TAG "TCP_ADAP"
44
45 /**
46  * Holds internal thread TCP data information.
47  */
48 typedef struct
49 {
50     CAEndpoint_t *remoteEndpoint;
51     void *data;
52     size_t dataLen;
53     bool isMulticast;
54 } CATCPData;
55
56 #define CA_TCP_TIMEOUT 1000
57
58 #define CA_TCP_LISTEN_BACKLOG  3
59
60 /**
61  * Queue handle for Send Data.
62  */
63 static CAQueueingThread_t *g_sendQueueHandle = NULL;
64
65 /**
66  * Network Packet Received Callback to CA.
67  */
68 static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
69
70 /**
71  * Network Changed Callback to CA.
72  */
73 static CANetworkChangeCallback g_networkChangeCallback = NULL;
74
75 /**
76  * error Callback to CA adapter.
77  */
78 static CAErrorHandleCallback g_errorCallback = NULL;
79
80 static void CATCPPacketReceivedCB(const CAEndpoint_t *endpoint,
81                                   const void *data, uint32_t dataLength);
82
83 static CAResult_t CATCPInitializeQueueHandles();
84
85 static void CATCPDeinitializeQueueHandles();
86
87 static void CATCPSendDataThread(void *threadData);
88
89 static CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint,
90                                   const void *data, size_t dataLength,
91                                   bool isMulticast);
92 void CAFreeTCPData(CATCPData *ipData);
93
94 static void CADataDestroyer(void *data, uint32_t size);
95
96 CAResult_t CATCPInitializeQueueHandles()
97 {
98     OIC_LOG(DEBUG, TAG, "IN");
99
100     // Check if the message queue is already initialized
101     if (g_sendQueueHandle)
102     {
103         OIC_LOG(DEBUG, TAG, "send queue handle is already initialized!");
104         return CA_STATUS_OK;
105     }
106
107     // Create send message queue
108     g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
109     if (!g_sendQueueHandle)
110     {
111         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
112         return CA_MEMORY_ALLOC_FAILED;
113     }
114
115     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle,
116                                 (const ca_thread_pool_t)caglobals.tcp.threadpool,
117                                 CATCPSendDataThread, CADataDestroyer))
118     {
119         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
120         OICFree(g_sendQueueHandle);
121         g_sendQueueHandle = NULL;
122         return CA_STATUS_FAILED;
123     }
124
125     OIC_LOG(DEBUG, TAG, "OUT");
126     return CA_STATUS_OK;
127 }
128
129 void CATCPDeinitializeQueueHandles()
130 {
131     OIC_LOG(DEBUG, TAG, "IN");
132
133     CAQueueingThreadDestroy(g_sendQueueHandle);
134     OICFree(g_sendQueueHandle);
135     g_sendQueueHandle = NULL;
136
137     OIC_LOG(DEBUG, TAG, "OUT");
138 }
139
140 void CATCPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
141 {
142     (void)ipAddress;
143     (void)status;
144     OIC_LOG(DEBUG, TAG, "IN");
145 }
146
147 void CATCPPacketReceivedCB(const CAEndpoint_t *endpoint, const void *data,
148                            uint32_t dataLength)
149 {
150     OIC_LOG(DEBUG, TAG, "IN");
151
152     VERIFY_NON_NULL_VOID(endpoint, TAG, "ipAddress is NULL");
153     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
154
155     OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", endpoint->addr, endpoint->port);
156
157     if (g_networkPacketCallback)
158     {
159         g_networkPacketCallback(endpoint, data, dataLength);
160     }
161     OIC_LOG(DEBUG, TAG, "OUT");
162 }
163
164 void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
165                        uint32_t dataLength, CAResult_t result)
166 {
167     OIC_LOG(DEBUG, TAG, "IN");
168
169     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
170
171     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
172
173     if (g_errorCallback)
174     {
175         g_errorCallback(endpoint, data, dataLength, result);
176     }
177
178     OIC_LOG(DEBUG, TAG, "OUT");
179 }
180
181 static void CAInitializeTCPGlobals()
182 {
183     caglobals.tcp.selectTimeout = CA_TCP_TIMEOUT;
184     caglobals.tcp.listenBacklog = CA_TCP_LISTEN_BACKLOG;
185     caglobals.tcp.svrlist = NULL;
186
187     CATransportFlags_t flags = 0;
188     if (caglobals.client)
189     {
190         flags |= caglobals.clientFlags;
191     }
192     if (caglobals.server)
193     {
194         flags |= caglobals.serverFlags;
195     }
196
197     caglobals.tcp.ipv4tcpenabled = flags & CA_IPV4;
198 }
199
200 CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
201                            CANetworkPacketReceivedCallback networkPacketCallback,
202                            CANetworkChangeCallback netCallback,
203                            CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
204 {
205     OIC_LOG(DEBUG, TAG, "IN");
206     VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
207     VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback");
208     VERIFY_NON_NULL(netCallback, TAG, "netCallback");
209     VERIFY_NON_NULL(handle, TAG, "thread pool handle");
210
211     g_networkChangeCallback = netCallback;
212     g_networkPacketCallback = networkPacketCallback;
213     g_errorCallback = errorCallback;
214
215     CAInitializeTCPGlobals();
216     caglobals.tcp.threadpool = handle;
217
218     CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB);
219     CATCPSetErrorHandler(CATCPErrorHandler);
220
221     CAConnectivityHandler_t TCPHandler = {
222         .startAdapter = CAStartTCP,
223         .startListenServer = CAStartTCPListeningServer,
224         .stopListenServer = CAStopTCPListeningServer,
225         .startDiscoveryServer = CAStartTCPDiscoveryServer,
226         .sendData = CASendTCPUnicastData,
227         .sendDataToAll = CASendTCPMulticastData,
228         .GetnetInfo = CAGetTCPInterfaceInformation,
229         .readData = CAReadTCPData,
230         .stopAdapter = CAStopTCP,
231         .terminate = CATerminateTCP };
232     registerCallback(TCPHandler, CA_ADAPTER_TCP);
233
234     OIC_LOG(INFO, TAG, "OUT IntializeTCP is Success");
235     return CA_STATUS_OK;
236 }
237
238 CAResult_t CAStartTCP()
239 {
240     OIC_LOG(DEBUG, TAG, "IN");
241
242     if (CA_STATUS_OK != CATCPInitializeQueueHandles())
243     {
244         OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
245         CATerminateTCP();
246         return CA_STATUS_FAILED;
247     }
248
249     // Start send queue thread
250     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
251     {
252         OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
253         return CA_STATUS_FAILED;
254     }
255
256     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
257     if (CA_STATUS_OK != ret)
258     {
259         OIC_LOG_V(ERROR, TAG, "Failed to start server![%d]", ret);
260         return ret;
261     }
262
263     OIC_LOG(DEBUG, TAG, "OUT");
264     return CA_STATUS_OK;
265 }
266
267 CAResult_t CAStartTCPListeningServer()
268 {
269     OIC_LOG(DEBUG, TAG, "IN");
270
271     OIC_LOG(DEBUG, TAG, "OUT");
272     return CA_STATUS_OK;
273 }
274
275 CAResult_t CAStopTCPListeningServer()
276 {
277     OIC_LOG(DEBUG, TAG, "IN");
278
279     OIC_LOG(DEBUG, TAG, "OUT");
280     return CA_STATUS_OK;
281 }
282
283 CAResult_t CAStartTCPDiscoveryServer()
284 {
285     OIC_LOG(DEBUG, TAG, "IN");
286
287     OIC_LOG(DEBUG, TAG, "OUT");
288     return CA_STATUS_OK;
289 }
290
291 static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
292                              const void *data, size_t dataLength)
293 {
294     OIC_LOG(DEBUG, TAG, "IN");
295
296     VERIFY_NON_NULL_RET(endpoint, TAG, "remoteEndpoint", -1);
297     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
298
299     if (0 == dataLength)
300     {
301         OIC_LOG(ERROR, TAG, "Invalid Data Length");
302         return -1;
303     }
304
305     VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
306
307     // Create TCPData to add to queue
308     CATCPData *TCPData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
309     if (!TCPData)
310     {
311         OIC_LOG(ERROR, TAG, "Failed to create ipData!");
312         return -1;
313     }
314     // Add message to send queue
315     CAQueueingThreadAddData(g_sendQueueHandle, TCPData, sizeof(CATCPData));
316
317     OIC_LOG(DEBUG, TAG, "OUT");
318     return dataLength;
319 }
320
321 int32_t CASendTCPUnicastData(const CAEndpoint_t *endpoint,
322                              const void *data, uint32_t dataLength)
323 {
324     OIC_LOG(DEBUG, TAG, "IN");
325     return CAQueueTCPData(false, endpoint, data, dataLength);
326 }
327
328 int32_t CASendTCPMulticastData(const CAEndpoint_t *endpoint,
329                                const void *data, uint32_t dataLength)
330 {
331     OIC_LOG(DEBUG, TAG, "IN");
332     return CAQueueTCPData(true, endpoint, data, dataLength);
333 }
334
335 CAResult_t CAReadTCPData()
336 {
337     OIC_LOG(DEBUG, TAG, "IN");
338     OIC_LOG(DEBUG, TAG, "OUT");
339     return CA_STATUS_OK;
340 }
341
342 CAResult_t CAStopTCP()
343 {
344     OIC_LOG(DEBUG, TAG, "IN");
345
346     if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
347     {
348         CAQueueingThreadStop(g_sendQueueHandle);
349     }
350
351     CATCPDeinitializeQueueHandles();
352
353     CATCPStopServer();
354
355     OIC_LOG(DEBUG, TAG, "OUT");
356     return CA_STATUS_OK;
357 }
358
359 void CATerminateTCP()
360 {
361     OIC_LOG(DEBUG, TAG, "IN");
362
363     CATCPSetPacketReceiveCallback(NULL);
364
365     CATCPDeinitializeQueueHandles();
366
367     OIC_LOG(DEBUG, TAG, "OUT");
368 }
369
370 void CATCPSendDataThread(void *threadData)
371 {
372     OIC_LOG(DEBUG, TAG, "IN");
373
374     CATCPData *TCPData = (CATCPData *) threadData;
375     if (!TCPData)
376     {
377         OIC_LOG(DEBUG, TAG, "Invalid TCP data!");
378         return;
379     }
380
381     if (TCPData->isMulticast)
382     {
383         //Processing for sending multicast
384         OIC_LOG(DEBUG, TAG, "Send Multicast Data is called, not supported");
385         return;
386     }
387     else
388     {
389         //Processing for sending unicast
390         CATCPSendData(TCPData->remoteEndpoint, TCPData->data, TCPData->dataLen, false);
391     }
392
393     OIC_LOG(DEBUG, TAG, "OUT");
394 }
395
396 CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint, const void *data,
397                            size_t dataLength, bool isMulticast)
398 {
399     VERIFY_NON_NULL_RET(data, TAG, "TCPData is NULL", NULL);
400
401     CATCPData *TCPData = (CATCPData *) OICMalloc(sizeof(CATCPData));
402     if (!TCPData)
403     {
404         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
405         return NULL;
406     }
407
408     TCPData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
409     TCPData->data = (void *) OICMalloc(dataLength);
410     if (!TCPData->data)
411     {
412         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
413         CAFreeTCPData(TCPData);
414         return NULL;
415     }
416
417     memcpy(TCPData->data, data, dataLength);
418     TCPData->dataLen = dataLength;
419
420     TCPData->isMulticast = isMulticast;
421
422     return TCPData;
423 }
424
425 void CAFreeTCPData(CATCPData *TCPData)
426 {
427     VERIFY_NON_NULL_VOID(TCPData, TAG, "TCPData is NULL");
428
429     CAFreeEndpoint(TCPData->remoteEndpoint);
430     OICFree(TCPData->data);
431     OICFree(TCPData);
432 }
433
434 void CADataDestroyer(void *data, uint32_t size)
435 {
436     if (size < sizeof(CATCPData))
437     {
438         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
439     }
440     CATCPData *TCPData = (CATCPData *) data;
441
442     CAFreeTCPData(TCPData);
443 }