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