[IOT-1346] Enable network status monitoring for tcp network
[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 "caipnwmonitor.h"
33 #include "catcpadapter.h"
34 #include "catcpinterface.h"
35 #include "caqueueingthread.h"
36 #include "caadapterutils.h"
37 #include "camutex.h"
38 #include "uarraylist.h"
39 #include "caremotehandler.h"
40 #include "logger.h"
41 #include "oic_malloc.h"
42 #ifdef __WITH_TLS__
43 #include "ca_adapter_net_ssl.h"
44 #endif
45
46 /**
47  * Logging tag for module name.
48  */
49 #define TAG "OIC_CA_TCP_ADAP"
50
51 /**
52  * Holds internal thread TCP data information.
53  */
54 typedef struct
55 {
56     CAEndpoint_t *remoteEndpoint;
57     void *data;
58     size_t dataLen;
59     bool isMulticast;
60 } CATCPData;
61
62 #define CA_TCP_LISTEN_BACKLOG  3
63
64 #define CA_TCP_SELECT_TIMEOUT 10
65
66 /**
67  * Queue handle for Send Data.
68  */
69 static CAQueueingThread_t *g_sendQueueHandle = NULL;
70
71 /**
72  * Network Packet Received Callback to CA.
73  */
74 static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
75
76 /**
77  * Adapter Changed Callback to CA.
78  */
79 static CAAdapterChangeCallback g_networkChangeCallback = NULL;
80
81 /**
82  * Connection Changed Callback to CA.
83  */
84 static CAConnectionChangeCallback g_connectionChangeCallback = NULL;
85
86 /**
87  * error Callback to CA adapter.
88  */
89 static CAErrorHandleCallback g_errorCallback = NULL;
90
91 static void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep,
92                                   const void *data, uint32_t dataLength);
93
94 /**
95  * KeepAlive Connected or Disconnected Callback to CA adapter.
96  */
97 static CAKeepAliveConnectionCallback g_connKeepAliveCallback = NULL;
98
99 static CAResult_t CATCPInitializeQueueHandles();
100
101 static void CATCPDeinitializeQueueHandles();
102
103 static void CATCPSendDataThread(void *threadData);
104
105 static CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint,
106                                   const void *data, size_t dataLength,
107                                   bool isMulticast);
108 void CAFreeTCPData(CATCPData *ipData);
109
110 static void CADataDestroyer(void *data, uint32_t size);
111
112 CAResult_t CATCPInitializeQueueHandles()
113 {
114     // Check if the message queue is already initialized
115     if (g_sendQueueHandle)
116     {
117         OIC_LOG(DEBUG, TAG, "send queue handle is already initialized!");
118         return CA_STATUS_OK;
119     }
120
121     // Create send message queue
122     g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
123     if (!g_sendQueueHandle)
124     {
125         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
126         return CA_MEMORY_ALLOC_FAILED;
127     }
128
129     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle,
130                                 (const ca_thread_pool_t)caglobals.tcp.threadpool,
131                                 CATCPSendDataThread, CADataDestroyer))
132     {
133         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
134         OICFree(g_sendQueueHandle);
135         g_sendQueueHandle = NULL;
136         return CA_STATUS_FAILED;
137     }
138
139     return CA_STATUS_OK;
140 }
141
142 void CATCPDeinitializeQueueHandles()
143 {
144     CAQueueingThreadDestroy(g_sendQueueHandle);
145     OICFree(g_sendQueueHandle);
146     g_sendQueueHandle = NULL;
147 }
148
149 void CATCPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
150 {
151     (void)ipAddress;
152     (void)status;
153 }
154
155 void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
156                            uint32_t dataLength)
157 {
158     VERIFY_NON_NULL_VOID(sep, TAG, "sep is NULL");
159     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
160
161     OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
162
163     if (g_networkPacketCallback)
164     {
165         g_networkPacketCallback(sep, data, dataLength);
166     }
167 }
168
169 #ifdef __WITH_TLS__
170 static void CATCPPacketSendCB(CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
171 {
172     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
173     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
174     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
175
176     OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", endpoint->addr, endpoint->port);
177     OIC_LOG_BUFFER(DEBUG, TAG, data, dataLength);
178
179     CATCPSendData(endpoint, data, dataLength, false);
180     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
181 }
182 #endif
183
184 void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
185                        uint32_t dataLength, CAResult_t result)
186 {
187     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
188     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
189
190     if (g_errorCallback)
191     {
192         g_errorCallback(endpoint, data, dataLength, result);
193     }
194 }
195
196 static void CATCPConnectionHandler(const CAEndpoint_t *endpoint, bool isConnected)
197 {
198     // Pass the changed connection status to RI Layer for keepalive.
199     if (g_connKeepAliveCallback)
200     {
201         g_connKeepAliveCallback(endpoint, isConnected);
202     }
203
204     // Pass the changed connection status to CAUtil.
205     if (g_connectionChangeCallback)
206     {
207         g_connectionChangeCallback(endpoint, isConnected);
208     }
209 }
210
211 void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectionCallback ConnHandler)
212 {
213     g_connKeepAliveCallback = ConnHandler;
214 }
215
216 void CATCPAdapterHandler(CATransportAdapter_t adapter, CANetworkStatus_t status)
217 {
218     if (g_networkChangeCallback)
219     {
220         g_networkChangeCallback(adapter, status);
221     }
222
223     if (CA_INTERFACE_DOWN == status)
224     {
225         OIC_LOG(DEBUG, TAG, "Network status is down, close all session");
226         CATCPStopServer();
227     }
228     else if (CA_INTERFACE_UP == status)
229     {
230         OIC_LOG(DEBUG, TAG, "Network status is up, create new socket for listening");
231
232         CAResult_t ret = CA_STATUS_FAILED;
233 #ifndef SINGLE_THREAD
234         ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
235 #else
236         ret = CATCPStartServer();
237 #endif
238         if (CA_STATUS_OK != ret)
239         {
240             OIC_LOG_V(DEBUG, TAG, "CATCPStartServer failed[%d]", ret);
241         }
242     }
243 }
244
245 static void CAInitializeTCPGlobals()
246 {
247     caglobals.tcp.ipv4.fd = -1;
248     caglobals.tcp.ipv6.fd = -1;
249     caglobals.tcp.selectTimeout = CA_TCP_SELECT_TIMEOUT;
250     caglobals.tcp.listenBacklog = CA_TCP_LISTEN_BACKLOG;
251     caglobals.tcp.svrlist = NULL;
252
253     CATransportFlags_t flags = 0;
254     if (caglobals.client)
255     {
256         flags |= caglobals.clientFlags;
257     }
258     if (caglobals.server)
259     {
260         flags |= caglobals.serverFlags;
261     }
262
263     caglobals.tcp.ipv4tcpenabled = flags & CA_IPV4;
264     caglobals.tcp.ipv6tcpenabled = flags & CA_IPV6;
265 }
266
267 CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
268                            CANetworkPacketReceivedCallback networkPacketCallback,
269                            CAAdapterChangeCallback netCallback,
270                            CAConnectionChangeCallback connCallback,
271                            CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
272 {
273     OIC_LOG(DEBUG, TAG, "IN");
274     VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
275     VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback");
276     VERIFY_NON_NULL(netCallback, TAG, "netCallback");
277 #ifndef SINGLE_THREAD
278     VERIFY_NON_NULL(handle, TAG, "thread pool handle");
279 #endif
280
281     g_networkChangeCallback = netCallback;
282     g_connectionChangeCallback = connCallback;
283     g_networkPacketCallback = networkPacketCallback;
284     g_errorCallback = errorCallback;
285
286     CAInitializeTCPGlobals();
287 #ifndef SINGLE_THREAD
288     caglobals.tcp.threadpool = handle;
289 #endif
290
291     CATCPSetConnectionChangedCallback(CATCPConnectionHandler);
292     CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB);
293     CATCPSetErrorHandler(CATCPErrorHandler);
294
295 #ifdef __WITH_TLS__
296     if (CA_STATUS_OK != CAinitSslAdapter())
297     {
298         OIC_LOG(ERROR, TAG, "Failed to init SSL adapter");
299     }
300     else
301     {
302         CAsetSslAdapterCallbacks(CATCPPacketReceivedCB, CATCPPacketSendCB, CA_ADAPTER_TCP);
303     }
304 #endif
305
306     CAConnectivityHandler_t tcpHandler = {
307         .startAdapter = CAStartTCP,
308         .startListenServer = CAStartTCPListeningServer,
309         .stopListenServer = CAStopTCPListeningServer,
310         .startDiscoveryServer = CAStartTCPDiscoveryServer,
311         .sendData = CASendTCPUnicastData,
312         .sendDataToAll = CASendTCPMulticastData,
313         .GetnetInfo = CAGetTCPInterfaceInformation,
314         .readData = CAReadTCPData,
315         .stopAdapter = CAStopTCP,
316         .terminate = CATerminateTCP,
317         .cType = CA_ADAPTER_TCP};
318
319     registerCallback(tcpHandler);
320
321     OIC_LOG(INFO, TAG, "OUT IntializeTCP is Success");
322     return CA_STATUS_OK;
323 }
324
325 CAResult_t CAStartTCP()
326 {
327     OIC_LOG(DEBUG, TAG, "IN");
328
329     // Start network monitoring to receive adapter status changes.
330     CAIPStartNetworkMonitor(CATCPAdapterHandler, CA_ADAPTER_TCP);
331
332     // Set the port number received from application.
333     caglobals.tcp.ipv4.port = caglobals.ports.tcp.u4;
334     caglobals.tcp.ipv6.port = caglobals.ports.tcp.u6;
335
336 #ifndef SINGLE_THREAD
337     if (CA_STATUS_OK != CATCPInitializeQueueHandles())
338     {
339         OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
340         CATerminateTCP();
341         return CA_STATUS_FAILED;
342     }
343
344     // Start send queue thread
345     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
346     {
347         OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
348         return CA_STATUS_FAILED;
349     }
350 #else
351     CAResult_t ret = CATCPStartServer();
352     if (CA_STATUS_OK != ret)
353     {
354         OIC_LOG_V(DEBUG, TAG, "CATCPStartServer failed[%d]", ret);
355         return ret;
356     }
357 #endif
358
359     return CA_STATUS_OK;
360 }
361
362 CAResult_t CAStartTCPListeningServer()
363 {
364 #ifndef SINGLE_THREAD
365     if (!caglobals.server)
366     {
367         caglobals.server = true;    // only needed to run CA tests
368     }
369
370     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
371     if (CA_STATUS_OK != ret)
372     {
373         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
374         return ret;
375     }
376 #endif
377
378     return CA_STATUS_OK;
379 }
380
381 CAResult_t CAStopTCPListeningServer()
382 {
383     return CA_STATUS_OK;
384 }
385
386 CAResult_t CAStartTCPDiscoveryServer()
387 {
388     if (!caglobals.client)
389     {
390         caglobals.client = true;    // only needed to run CA tests
391     }
392
393     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
394     if (CA_STATUS_OK != ret)
395     {
396         OIC_LOG_V(ERROR, TAG, "Failed to start discovery server![%d]", ret);
397         return ret;
398     }
399
400     return CA_STATUS_OK;
401 }
402
403 static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
404                              const void *data, size_t dataLength)
405 {
406     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", -1);
407     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
408
409     if (0 == dataLength)
410     {
411         OIC_LOG(ERROR, TAG, "Invalid Data Length");
412         return -1;
413     }
414
415     VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
416
417     // Create TCPData to add to queue
418     CATCPData *tcpData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
419     if (!tcpData)
420     {
421         OIC_LOG(ERROR, TAG, "Failed to create ipData!");
422         return -1;
423     }
424     // Add message to send queue
425     CAQueueingThreadAddData(g_sendQueueHandle, tcpData, sizeof(CATCPData));
426
427     return dataLength;
428 }
429
430 int32_t CASendTCPUnicastData(const CAEndpoint_t *endpoint,
431                              const void *data, uint32_t dataLength,
432                              CADataType_t dataType)
433 {
434     OIC_LOG(DEBUG, TAG, "IN");
435     (void)dataType;
436 #ifndef SINGLE_THREAD
437     return CAQueueTCPData(false, endpoint, data, dataLength);
438 #else
439     CATCPSendData(endpoint, data, dataLength, false);
440     return dataLength;
441 #endif
442 }
443
444 int32_t CASendTCPMulticastData(const CAEndpoint_t *endpoint,
445                                const void *data, uint32_t dataLength,
446                                CADataType_t dataType)
447 {
448     (void)dataType;
449     return CAQueueTCPData(true, endpoint, data, dataLength);
450 }
451
452 CAResult_t CAReadTCPData()
453 {
454     OIC_LOG(DEBUG, TAG, "IN");
455 #ifdef SINGLE_THREAD
456     CATCPPullData();
457 #endif
458     return CA_STATUS_OK;
459 }
460
461 CAResult_t CAStopTCP()
462 {
463     CAIPStopNetworkMonitor(CA_ADAPTER_TCP);
464
465 #ifndef SINGLE_THREAD
466     if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
467     {
468         CAQueueingThreadStop(g_sendQueueHandle);
469     }
470     CATCPDeinitializeQueueHandles();
471 #endif
472
473     CATCPStopServer();
474
475     //Re-initializing the Globals to start them again
476     CAInitializeTCPGlobals();
477
478 #ifdef __WITH_TLS__
479     CAdeinitSslAdapter();
480 #endif
481
482     return CA_STATUS_OK;
483 }
484
485 void CATerminateTCP()
486 {
487     CAStopTCP();
488     CATCPSetPacketReceiveCallback(NULL);
489 }
490
491 void CATCPSendDataThread(void *threadData)
492 {
493     CATCPData *tcpData = (CATCPData *) threadData;
494     if (!tcpData)
495     {
496         OIC_LOG(DEBUG, TAG, "Invalid TCP data!");
497         return;
498     }
499
500     if (tcpData->isMulticast)
501     {
502         //Processing for sending multicast
503         OIC_LOG(DEBUG, TAG, "Send Multicast Data is called, not supported");
504         return;
505     }
506     else
507     {
508 #ifdef __WITH_TLS__
509          if (tcpData->remoteEndpoint && tcpData->remoteEndpoint->flags & CA_SECURE)
510          {
511              CAResult_t result = CA_STATUS_OK;
512              OIC_LOG(DEBUG, TAG, "CAencryptSsl called!");
513              result = CAencryptSsl(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
514
515              if (CA_STATUS_OK != result)
516              {
517                  OIC_LOG(ERROR, TAG, "CAAdapterNetDtlsEncrypt failed!");
518              }
519              OIC_LOG_V(DEBUG, TAG,
520                        "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
521             return;
522          }
523 #endif
524         //Processing for sending unicast
525         CATCPSendData(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen, false);
526     }
527 }
528
529 CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint, const void *data,
530                            size_t dataLength, bool isMulticast)
531 {
532     VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint is NULL", NULL);
533     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", NULL);
534
535     CATCPData *tcpData = (CATCPData *) OICCalloc(1, sizeof(*tcpData));
536     if (!tcpData)
537     {
538         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
539         return NULL;
540     }
541
542     tcpData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
543     tcpData->data = (void *) OICMalloc(dataLength);
544     if (!tcpData->data)
545     {
546         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
547         CAFreeTCPData(tcpData);
548         return NULL;
549     }
550
551     memcpy(tcpData->data, data, dataLength);
552     tcpData->dataLen = dataLength;
553
554     tcpData->isMulticast = isMulticast;
555
556     return tcpData;
557 }
558
559 void CAFreeTCPData(CATCPData *tcpData)
560 {
561     VERIFY_NON_NULL_VOID(tcpData, TAG, "tcpData is NULL");
562
563     CAFreeEndpoint(tcpData->remoteEndpoint);
564     OICFree(tcpData->data);
565     OICFree(tcpData);
566 }
567
568 void CADataDestroyer(void *data, uint32_t size)
569 {
570     if (size < sizeof(CATCPData))
571     {
572         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
573     }
574     CATCPData *TCPData = (CATCPData *) data;
575
576     CAFreeTCPData(TCPData);
577 }
578
579 #ifdef SINGLE_THREAD
580 size_t CAGetTotalLengthFromPacketHeader(const unsigned char *recvBuffer, size_t size)
581 {
582     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
583
584     if (NULL == recvBuffer || !size)
585     {
586         OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
587         return 0;
588     }
589
590     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
591             ((unsigned char *)recvBuffer)[0] >> 4);
592     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
593                                                         transport);
594     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
595
596     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
597     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
598     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
599
600     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
601     return headerLen + optPaylaodLen;
602 }
603
604 void CAGetTCPHeaderDetails(unsigned char* recvBuffer, coap_transport_t *transport,
605                            size_t *headerlen)
606 {
607     if (NULL == recvBuffer)
608     {
609         OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
610         return;
611     }
612
613     if (NULL == transport)
614     {
615         OIC_LOG(ERROR, TAG, "transport is NULL");
616         return;
617     }
618
619     if (NULL == headerlen)
620     {
621         OIC_LOG(ERROR, TAG, "headerlen is NULL");
622         return;
623     }
624
625     *transport = coap_get_tcp_header_type_from_initbyte(
626         ((unsigned char *)recvBuffer)[0] >> 4);
627     *headerlen = coap_get_tcp_header_length_for_transport(*transport);
628 }
629 #endif