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