Crash in select
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / tcp_adapter / catcpserver.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 <sys/types.h>
22 #include <sys/socket.h>
23 #include <sys/ioctl.h>
24 #ifdef __TIZENRT__
25 #include <tinyara/config.h>
26 #include <poll.h>
27 #else
28 #include <sys/poll.h>
29 #endif
30 #include <stdio.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <arpa/inet.h>
34 #include <netinet/in.h>
35 #include <net/if.h>
36 #include <errno.h>
37
38 #ifndef WITH_ARDUINO
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <netdb.h>
42 #endif
43
44 #include "catcpinterface.h"
45 #include "caipnwmonitor.h"
46 #include <coap/pdu.h>
47 #include "caadapterutils.h"
48 #include "octhread.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
51
52 #ifdef __WITH_TLS__
53 #include "ca_adapter_net_ssl.h"
54 #endif
55
56 /**
57  * Logging tag for module name.
58  */
59 //#define TAG "OIC_CA_TCP_SERVER"
60 #define TAG TCP_SERVER_TAG
61
62 /**
63  * Maximum CoAP over TCP header length
64  * to know the total data length.
65  */
66 #define COAP_MAX_HEADER_SIZE  6
67
68 /**
69  * TLS header size
70  */
71 #define TLS_HEADER_SIZE 5
72
73 /**
74  * Max Connection Counts.
75  */
76 #define MAX_CONNECTION_COUNTS   500
77
78 #define COAP_TCP_MAX_BUFFER_CHUNK_SIZE 65530 //64kb - 6 (coap+tcp max header size)
79
80 #define MILLISECONDS_PER_SECOND   (1000)
81
82 /**
83  * Thread pool.
84  */
85 static ca_thread_pool_t g_threadPool = NULL;
86
87 /**
88  * Thread task id.
89  */
90 static uint32_t g_taskId = 0;
91
92 /**
93  * Mutex to synchronize device object list.
94  */
95 static oc_mutex g_mutexObjectList = NULL;
96
97 /**
98  * Conditional mutex to synchronize.
99  */
100 static oc_cond g_condObjectList = NULL;
101
102 /**
103  * Mutex to synchronize send.
104  */
105 static oc_mutex g_mutexSend = NULL;
106
107 /**
108  * Conditional mutex to synchronize send.
109  */
110 static oc_cond g_condSend = NULL;
111
112 /**
113  * Maintains the callback to be notified when data received from remote device.
114  */
115 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
116
117 /**
118  * Error callback to update error in TCP.
119  */
120 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
121
122 /**
123  * Connected Callback to pass the connection information to RI.
124  */
125 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
126
127 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
128 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
129 static void CAFindReadyMessage();
130 static void CAPollReturned(struct pollfd *readFds, size_t size);
131 static void CAReceiveMessage(int fd);
132 static void CAReceiveHandler(void *data);
133 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
134 static void CATCPInitializeSocket();
135 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index);
136
137 #if defined(__TIZEN__)
138 static char g_cloudproxyUri[CA_MAX_URI_LENGTH];
139
140 CAResult_t CASetCloudAddressForProxy(const char *uri)
141 {
142     if (uri == NULL)
143         memset(g_cloudproxyUri, '\0', sizeof (g_cloudproxyUri));
144     else
145         OICStrcpy(g_cloudproxyUri, sizeof (g_cloudproxyUri), uri);
146     return CA_STATUS_OK;
147 }
148
149 const char *CAGetCloudAddressForProxy()
150 {
151     if (g_cloudproxyUri[0] == '\0')
152         return NULL;
153     return g_cloudproxyUri;
154 }
155 #endif
156
157 #define MAX_TCP_SOCK_COUNT 4
158
159 #define CLOSE_SOCKET(TYPE) \
160     if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
161     { \
162         close(caglobals.tcp.TYPE.fd); \
163         caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
164     }
165
166 #define CA_FD_SET(TYPE, FDS, COUNT) \
167         FDS[COUNT].fd = caglobals.tcp.TYPE.fd; \
168         FDS[COUNT].events = POLLIN;
169
170 void CATCPDestroyMutex()
171 {
172     if (g_mutexObjectList)
173     {
174         oc_mutex_free(g_mutexObjectList);
175         g_mutexObjectList = NULL;
176     }
177 }
178
179 CAResult_t CATCPCreateMutex()
180 {
181     if (!g_mutexObjectList)
182     {
183         g_mutexObjectList = oc_mutex_new();
184         if (!g_mutexObjectList)
185         {
186             OIC_LOG(ERROR, TAG, "Failed to create mutex!");
187             return CA_STATUS_FAILED;
188         }
189     }
190
191     return CA_STATUS_OK;
192 }
193
194 void CATCPDestroyCond()
195 {
196     if (g_condObjectList)
197     {
198         oc_cond_free(g_condObjectList);
199         g_condObjectList = NULL;
200     }
201 }
202
203 CAResult_t CATCPCreateCond()
204 {
205     if (!g_condObjectList)
206     {
207         g_condObjectList = oc_cond_new();
208         if (!g_condObjectList)
209         {
210             OIC_LOG(ERROR, TAG, "Failed to create cond!");
211             return CA_STATUS_FAILED;
212         }
213     }
214     return CA_STATUS_OK;
215 }
216
217 void CATCPDestroySendMutex()
218 {
219     if (g_mutexSend)
220     {
221         oc_mutex_free(g_mutexSend);
222         g_mutexSend = NULL;
223     }
224 }
225
226 CAResult_t CATCPCreateSendMutex()
227 {
228     if (!g_mutexSend)
229     {
230         g_mutexSend = oc_mutex_new();
231         if (!g_mutexSend)
232         {
233             OIC_LOG(ERROR, TAG, "Failed to create send mutex!");
234             return CA_STATUS_FAILED;
235         }
236     }
237
238     return CA_STATUS_OK;
239 }
240
241 void CATCPDestroySendCond()
242 {
243     if (g_condSend)
244     {
245         oc_cond_free(g_condSend);
246         g_condSend = NULL;
247     }
248 }
249
250 CAResult_t CATCPCreateSendCond()
251 {
252     if (!g_condSend)
253     {
254         g_condSend = oc_cond_new();
255         if (!g_condSend)
256         {
257             OIC_LOG(ERROR, TAG, "Failed to create send cond!");
258             return CA_STATUS_FAILED;
259         }
260     }
261     return CA_STATUS_OK;
262 }
263
264 static void CAReceiveHandler(void *data)
265 {
266     (void)data;
267     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
268
269     while (true)
270     {
271         oc_mutex_lock(g_mutexObjectList);
272         if (caglobals.tcp.terminate)
273         {
274             oc_mutex_unlock(g_mutexObjectList);
275             break;
276         }
277         oc_mutex_unlock(g_mutexObjectList);
278         CAFindReadyMessage();
279     }
280
281     oc_mutex_lock(g_mutexObjectList);
282     oc_cond_signal(g_condObjectList);
283     oc_mutex_unlock(g_mutexObjectList);
284
285     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
286 }
287
288 static void CAFindReadyMessage()
289 {
290     int timeout = (caglobals.tcp.selectTimeout * 1000);
291     size_t counter = 0;
292
293     oc_mutex_lock(g_mutexObjectList);
294     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
295
296     // Consider 4 tcp sockets(ipv4, ipv4s, ipv6, ipv6s) + 1 connection fd + all sockets in svrlist
297     struct pollfd *readFds = (struct pollfd *)OICCalloc(MAX_TCP_SOCK_COUNT + 1 + length, sizeof(struct pollfd));
298     if (NULL == readFds)
299     {
300         OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
301         oc_mutex_unlock(g_mutexObjectList);
302         return;
303     }
304
305     // 4 tcp sockets
306     CA_FD_SET(ipv4, readFds, counter);
307     counter++;
308     CA_FD_SET(ipv4s, readFds, counter);
309     counter++;
310     CA_FD_SET(ipv6, readFds, counter);
311     counter++;
312     CA_FD_SET(ipv6s, readFds, counter);
313     counter++;
314
315     // 1 connection fd
316     readFds[counter].fd = caglobals.tcp.connectionFds[0];
317     readFds[counter].events = POLLIN;
318     counter++;
319
320     // All sockets in svrlist
321     for (size_t i = 0; i < length; i++)
322     {
323         CATCPSessionInfo_t *svritem =
324                 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
325         if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
326         {
327             readFds[counter].fd = svritem->fd;
328             readFds[counter].events = POLLIN;
329             counter++;
330         }
331     }
332     oc_mutex_unlock(g_mutexObjectList);
333     int ret = poll(readFds, counter, timeout);
334
335     oc_mutex_lock(g_mutexObjectList);
336     if (caglobals.tcp.terminate)
337     {
338         OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
339         oc_mutex_unlock(g_mutexObjectList);
340         OICFree(readFds);
341         return;
342     }
343     oc_mutex_unlock(g_mutexObjectList);
344
345     if (ret > 0)
346     {
347         CAPollReturned(readFds, counter);
348     }
349     else if (ret == 0)
350     {
351         usleep(1000); /* some of the fields are not set by kernel on repeatedly calling
352                          poll.Applying a timeout will solve this*/
353     }
354     else if (ret < 0)
355     {
356         OIC_LOG_V(FATAL, TAG, "poll error %s", strerror(errno));
357     }
358
359     OICFree(readFds);
360 }
361
362 static void CAPollReturned(struct pollfd *readFds, size_t size)
363 {
364     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
365
366     if (caglobals.tcp.ipv4.fd != -1 && readFds[0].revents == POLLIN)
367     {
368         CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
369         return;
370     }
371     else if (caglobals.tcp.ipv4s.fd != -1 && readFds[1].revents == POLLIN)
372     {
373         CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
374         return;
375     }
376     else if (caglobals.tcp.ipv6.fd != -1 && readFds[2].revents == POLLIN)
377     {
378         CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
379         return;
380     }
381     else if (caglobals.tcp.ipv6s.fd != -1 && readFds[3].revents == POLLIN)
382     {
383         CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
384         return;
385     }
386     else if (-1 != caglobals.tcp.connectionFds[0] && readFds[4].revents != 0)
387     {
388             // new connection was created from remote device.
389             // exit the function to update read file descriptor.
390             char buf[MAX_ADDR_STR_SIZE_CA] = {0};
391             ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
392             if (-1 == len)
393             {
394                 return;
395             }
396             OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
397             return;
398     }
399     else
400     {
401         int *readFDList = NULL;
402         size_t readFDListSize = 0;
403
404         oc_mutex_lock(g_mutexObjectList);
405         uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
406
407         readFDList = (int*) OICCalloc(length, sizeof(int));
408         if (NULL == readFDList)
409         {
410             OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
411             oc_mutex_unlock(g_mutexObjectList);
412             return;
413         }
414
415         for (size_t i = 0; i < length; i++)
416         {
417             CATCPSessionInfo_t *svritem =
418                     (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
419             if (svritem && svritem->fd >= 0)
420             {
421                 size_t j = 0;
422                 while (j < size)
423                 {
424                     if (svritem->fd == readFds[j].fd)
425                     {
426                         break;
427                     }
428                     j++;
429                 }
430
431                 if (j < size  && readFds[j].revents != 0)
432                 {
433                     readFDList[readFDListSize++] = svritem->fd;
434                 }
435             }
436         }
437         oc_mutex_unlock(g_mutexObjectList);
438
439         // Read incomming messages from fds
440         for (size_t i = 0; i < readFDListSize; i++)
441         {
442             CAReceiveMessage(readFDList[i]);
443         }
444
445         OICFree(readFDList);
446     }
447 }
448
449 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
450 {
451     OIC_LOG_V(INFO, TAG, "In %s", __func__);
452     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
453
454     if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
455     {
456         OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
457         close(sock->fd);
458         sock->fd = OC_INVALID_SOCKET;
459         return;
460     }
461
462     struct sockaddr_storage clientaddr;
463     socklen_t clientlen = sizeof (struct sockaddr_in);
464     if (flag & CA_IPV6)
465     {
466         clientlen = sizeof(struct sockaddr_in6);
467     }
468
469     CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
470     if (OC_INVALID_SOCKET != sockfd)
471     {
472         CATCPSessionInfo_t *svritem =
473                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
474         if (!svritem)
475         {
476             OIC_LOG(ERROR, TAG, "Out of memory");
477             close(sockfd);
478             return;
479         }
480
481         svritem->fd = sockfd;
482         svritem->sep.endpoint.flags = flag;
483         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
484         svritem->state = CONNECTED;
485         svritem->isClient = false;
486         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
487                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
488
489         // Allocate message buffer
490         svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
491         if (!svritem->tlsdata)
492         {
493             OIC_LOG(ERROR, TAG, "Out of memory");
494             close(sockfd);
495             OICFree(svritem);
496             return;
497         }
498
499         oc_mutex_lock(g_mutexObjectList);
500         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
501         if (!result)
502         {
503             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
504             close(sockfd);
505             OICFree(svritem->tlsdata);
506             OICFree(svritem);
507             oc_mutex_unlock(g_mutexObjectList);
508             return;
509         }
510         oc_mutex_unlock(g_mutexObjectList);
511
512         // pass the connection information to CA Common Layer.
513         if (g_connectionCallback)
514         {
515             g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
516         }
517     }
518     OIC_LOG_V(INFO, TAG, "Out %s", __func__);
519 }
520
521 /**
522  * Clean socket state data
523  *
524  * @param[in/out] item - socket state data
525  */
526 void CACleanData(CATCPSessionInfo_t *svritem)
527 {
528     if (svritem)
529     {
530         OICFree(svritem->data);
531         svritem->data = NULL;
532         svritem->len = 0;
533 #ifdef __WITH_TLS__
534         svritem->tlsLen = 0;
535 #endif
536         svritem->totalLen = 0;
537         svritem->bufLen = 0;
538         svritem->protocol = UNKNOWN;
539     }
540 }
541
542 /**
543  * Construct CoAP header and payload from buffer
544  *
545  * @param[in] svritem - used socket, buffer, current received message length and protocol
546  * @param[in/out]  data  - data buffer, this value is updated as data is copied to svritem
547  * @param[in/out]  dataLength  - length of data, this value decreased as data is copied to svritem
548  * @return             - CA_STATUS_OK or appropriate error code
549  */
550 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
551                           size_t *dataLength)
552 {
553     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
554
555     if (NULL == svritem || NULL == data || NULL == dataLength)
556     {
557         OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
558         return CA_STATUS_INVALID_PARAM;
559     }
560
561     unsigned char *inBuffer = *data;
562     size_t inLen = *dataLength;
563     OIC_LOG_V(DEBUG, TAG, "before-datalength : %zd", *dataLength);
564
565     if (NULL == svritem->data && inLen > 0)
566     {
567         // allocate memory for message header (CoAP header size because it is bigger)
568         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
569         if (NULL == svritem->data)
570         {
571             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
572             return CA_MEMORY_ALLOC_FAILED;
573         }
574
575         // copy 1 byte to parse coap header length
576         memcpy(svritem->data, inBuffer, 1);
577         svritem->len = 1;
578         svritem->bufLen = COAP_MAX_HEADER_SIZE;
579         inBuffer++;
580         inLen--;
581     }
582
583     //if not enough data received - read them on next CAFillHeader() call
584     if (0 == inLen)
585     {
586         return CA_STATUS_OK;
587     }
588
589     //if enough data received - parse header
590     svritem->protocol = COAP;
591
592     //seems CoAP data received. read full coap header.
593     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
594     size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
595     size_t copyLen = 0;
596
597     // HEADER
598     if (svritem->len < headerLen)
599     {
600         copyLen = headerLen - svritem->len;
601         if (inLen < copyLen)
602         {
603             copyLen = inLen;
604         }
605
606         //read required bytes to have full CoAP header
607         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
608         svritem->len += copyLen;
609         inBuffer += copyLen;
610         inLen -= copyLen;
611
612         //if not enough data received - read them on next CAFillHeader() call
613         if (svritem->len < headerLen)
614         {
615             *data = inBuffer;
616             *dataLength = inLen;
617             OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
618             return CA_STATUS_OK;
619         }
620
621         //calculate CoAP message length
622         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
623     }
624
625     // PAYLOAD
626     if (inLen > 0)
627     {
628         // Calculate length of data to be copied.
629         copyLen = svritem->totalLen - svritem->len;
630         if (inLen < copyLen)
631         {
632             copyLen = inLen;
633         }
634
635         // Is buffer not big enough for remaining data ?
636         if (svritem->len + copyLen > svritem->bufLen)
637         {
638             // Resize buffer to accommodate enough space
639             size_t extLen = svritem->totalLen - svritem->bufLen;
640             if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
641             {
642                 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
643             }
644
645             // Allocate required memory
646             unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
647             if (NULL == buffer)
648             {
649                 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
650                 return CA_MEMORY_ALLOC_FAILED;
651             }
652
653             svritem->data = buffer;
654             svritem->bufLen += extLen;
655         }
656
657         // Read required bytes to have full CoAP payload
658         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
659         svritem->len += copyLen;
660         inBuffer += copyLen;
661         inLen -= copyLen;
662     }
663
664     *data = inBuffer;
665     *dataLength = inLen;
666
667     OIC_LOG_V(DEBUG, TAG, "after-datalength : %zd", *dataLength);
668     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
669     return CA_STATUS_OK;
670 }
671
672 static void CAReceiveMessage(int fd)
673 {
674     CAResult_t res = CA_STATUS_OK;
675
676     oc_mutex_lock(g_mutexObjectList);
677
678     //get remote device information from file descriptor.
679     size_t index = 0;
680     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
681     if (!svritem)
682     {
683         OIC_LOG(ERROR, TAG, "there is no connection information in list");
684         oc_mutex_unlock(g_mutexObjectList);
685         return;
686     }
687
688     CASecureEndpoint_t peerEP = svritem->sep;
689     int len = 0;
690     if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection
691     {
692         svritem->protocol = TLS;
693
694 #ifdef __WITH_TLS__
695         size_t nbRead = 0;
696         size_t tlsLength = 0;
697
698         if (TLS_HEADER_SIZE > svritem->tlsLen)
699         {
700             nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
701         }
702         else
703         {
704             //[3][4] bytes in tls header are tls payload length
705             tlsLength = TLS_HEADER_SIZE +
706                             (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
707             OIC_LOG_V(DEBUG, TAG, "total tls length = %zd", tlsLength);
708             if (tlsLength > TLS_DATA_MAX_SIZE)
709             {
710                 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
711                                     TLS_DATA_MAX_SIZE);
712                 oc_mutex_unlock(g_mutexObjectList);
713                 CATCPDisconnectSession(&peerEP.endpoint);
714                 return;
715             }
716             nbRead = tlsLength - svritem->tlsLen;
717         }
718
719         len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
720         if (len < 0)
721         {
722             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
723             res = CA_RECEIVE_FAILED;
724         }
725         else if (0 == len)
726         {
727             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
728             svritem->state = DISCONNECTED;
729             res = CA_DESTINATION_DISCONNECTED;
730         }
731         else
732         {
733             svritem->tlsLen += len;
734             OIC_LOG_V(DEBUG, TAG, "nb_read : %zd bytes , recv() : %d bytes, svritem->tlsLen : %zd bytes",
735                                 nbRead, len, svritem->tlsLen);
736             if (tlsLength > 0 && tlsLength == svritem->tlsLen)
737             {
738                 // When successfully read data - pass them to callback.
739                 // Dont invoke callback locking mutex
740                 unsigned char *mesBuf = svritem->tlsdata;
741                 size_t mesBufLen = svritem->tlsLen;
742                 svritem->tlsdata = NULL;
743                 oc_mutex_unlock(g_mutexObjectList);
744
745                 res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen);
746                 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
747
748                 // Check for the svritem and reset buffer
749                 oc_mutex_lock(g_mutexObjectList);
750                 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
751                 if (svritem)
752                 {
753                     svritem->tlsdata = mesBuf;
754                     svritem->tlsLen = 0;
755                 }
756                 else
757                 {
758                     // svritem does not exist, thus free the message buffer
759                     OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
760                     OICFree(mesBuf);
761                 }
762             }
763         }
764 #endif
765     }
766     else // Non-Secure connection
767     {
768         svritem->protocol = COAP;
769
770         // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
771         len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0);
772         if (len < 0)
773         {
774             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
775             res = CA_RECEIVE_FAILED;
776         }
777         else if (0 == len)
778         {
779             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
780             res = CA_DESTINATION_DISCONNECTED;
781         }
782         else
783         {
784             //when successfully read data - pass them to callback.
785             OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
786             if (g_packetReceivedCallback)
787             {
788                 // Dont invoke callback locking mutex
789                 unsigned char *mesBuf = svritem->tlsdata;
790                 svritem->tlsdata = NULL;
791                 oc_mutex_unlock(g_mutexObjectList);
792
793                 res = g_packetReceivedCallback(&peerEP, mesBuf, len);
794
795                 // Check for the svritem and reset buffer
796                 oc_mutex_lock(g_mutexObjectList);
797                 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
798                 if (svritem)
799                 {
800                     svritem->tlsdata = mesBuf;
801                     svritem->tlsLen = 0;
802                 }
803                 else
804                 {
805                     // svritem does not exist, thus free the message buffer
806                     OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
807                     OICFree(mesBuf);
808                 }
809             }
810         }
811     }
812
813     oc_mutex_unlock(g_mutexObjectList);
814
815     if (res != CA_STATUS_OK)
816     {
817         CATCPDisconnectSession(&peerEP.endpoint);
818     }
819 }
820
821 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
822 {
823     if (caglobals.tcp.connectionFds[1] != -1)
824     {
825         ssize_t len = 0;
826         do
827         {
828             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
829         } while ((len == -1) && (errno == EINTR));
830
831         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
832         {
833             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
834         }
835         return len;
836     }
837     return -1;
838 }
839
840 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
841                                          struct sockaddr_storage *sockaddr)
842 {
843     struct addrinfo *addrs = NULL;
844     struct addrinfo hints = { .ai_family = family,
845                               .ai_protocol   = IPPROTO_TCP,
846                               .ai_socktype = SOCK_STREAM,
847                               .ai_flags = AI_NUMERICHOST };
848
849     int r = getaddrinfo(host, NULL, &hints, &addrs);
850     if (r)
851     {
852         if (EAI_SYSTEM == r)
853         {
854             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
855         }
856         else
857         {
858             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
859         }
860         freeaddrinfo(addrs);
861         return CA_STATUS_FAILED;
862     }
863     // assumption: in this case, getaddrinfo will only return one addrinfo
864     // or first is the one we want.
865     if (addrs[0].ai_family == AF_INET6)
866     {
867         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
868         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
869     }
870     else
871     {
872         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
873         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
874     }
875     freeaddrinfo(addrs);
876     return CA_STATUS_OK;
877 }
878
879 #if defined(__TIZEN__)
880 static int CAGetHTTPStatusCode(char * response) {
881     char *resp, *code_plus, *ptrSave;
882     int ret = -1;
883
884     resp = strdup(response);
885     strtok_r(resp, " ", &ptrSave);  /* skip HTTP version */
886     code_plus = strtok_r(NULL, " ", &ptrSave);
887
888     ret = code_plus ? atoi(code_plus) : -1;
889     free(resp);
890     return ret;
891 }
892 #endif
893
894 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
895 {
896     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
897
898     OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
899               svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
900
901     // #1. create tcp socket.
902     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
903     if (-1 == fd)
904     {
905         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
906         return CA_SOCKET_OPERATION_FAILED;
907     }
908     svritem->fd = fd;
909
910     // #2. convert address from string to binary.
911     struct sockaddr_storage sa = { .ss_family = family };
912     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
913                                             svritem->sep.endpoint.port, &sa);
914     if (CA_STATUS_OK != res)
915     {
916         OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
917         return CA_SOCKET_OPERATION_FAILED;
918     }
919
920     // #3. set socket length.
921     socklen_t socklen = 0;
922     if (sa.ss_family == AF_INET6)
923     {
924         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
925         if (!sock6->sin6_scope_id)
926         {
927             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
928         }
929         socklen = sizeof(struct sockaddr_in6);
930     }
931     else
932     {
933         socklen = sizeof(struct sockaddr_in);
934     }
935
936     // #4. connect to remote server device.
937     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
938     {
939         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
940         CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
941                            svritem->sep.endpoint.port, 0, false, strerror(errno));
942         return CA_SOCKET_OPERATION_FAILED;
943     }
944
945     OIC_LOG(INFO, TAG, "connect socket success");
946     svritem->state = CONNECTED;
947     ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
948     if (-1 == len)
949     {
950         OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
951         return CA_SOCKET_OPERATION_FAILED;
952     }
953
954 #if defined(__TIZEN__)
955     // #5. Send HTTP CONNECT to proxy if proxy
956
957     const char *cloud_address = CAGetCloudAddressForProxy();
958     OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)");
959
960     if(cloud_address && *cloud_address)
961     {
962         char message[4096];
963         int len = sprintf(message,
964                 "CONNECT %s HTTP/1.1\r\n"
965                 "Host: %s\r\n\r\n", cloud_address, cloud_address
966         );
967
968         ssize_t l = send(fd, message, len, 0);
969         if(l != len)
970         {
971             OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %zd)", len, l);
972             close(fd);
973             svritem->fd = -1;
974             return CA_SOCKET_OPERATION_FAILED;
975         }
976
977         // maybe this should be called in other thread, it causes bottleneck.
978         OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message);
979
980         *message = '\0';
981         OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy...");
982
983         l = recv(fd, message, 4096, 0);
984
985         OIC_LOG_V(INFO, TAG, "Received data : '%s'", message);
986         OIC_LOG_V(INFO, TAG, "Received len = %zd", l);
987
988         int status_code = CAGetHTTPStatusCode(message);
989
990         OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code);
991         if(status_code < 200 || status_code > 299)
992         {
993             OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %d", status_code);
994             close(fd);
995             svritem->fd = -1;
996             return CA_SOCKET_OPERATION_FAILED;
997         }
998     }
999 #endif
1000
1001     return CA_STATUS_OK;
1002 }
1003
1004 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
1005 {
1006     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
1007
1008     if (OC_INVALID_SOCKET != sock->fd)
1009     {
1010         OIC_LOG(DEBUG, TAG, "accept socket created already");
1011         return sock->fd;
1012     }
1013
1014     socklen_t socklen = 0;
1015     struct sockaddr_storage server = { .ss_family = family };
1016
1017     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
1018     if (OC_INVALID_SOCKET == fd)
1019     {
1020         OIC_LOG(ERROR, TAG, "Failed to create socket");
1021         goto exit;
1022     }
1023
1024     if (family == AF_INET6)
1025     {
1026         // the socket is restricted to sending and receiving IPv6 packets only.
1027         int on = 1;
1028 //TODO: enable once IPv6 is supported
1029 #ifndef __TIZENRT__
1030         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
1031         {
1032             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
1033             goto exit;
1034         }
1035 #endif
1036         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
1037         socklen = sizeof (struct sockaddr_in6);
1038     }
1039     else
1040     {
1041         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
1042         socklen = sizeof (struct sockaddr_in);
1043     }
1044
1045     int reuse = 1;
1046     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
1047     {
1048         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
1049         goto exit;
1050     }
1051
1052     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
1053     {
1054         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1055         goto exit;
1056     }
1057
1058     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
1059     {
1060         OIC_LOG(ERROR, TAG, "listen() error");
1061         goto exit;
1062     }
1063
1064     if (sock->port) // use the given port
1065     {
1066         int on = 1;
1067         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
1068         {
1069             OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
1070             close(fd);
1071             return OC_INVALID_SOCKET;
1072         }
1073     }
1074     else  // return the assigned port
1075     {
1076         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
1077         {
1078             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
1079             goto exit;
1080         }
1081         sock->port = ntohs(family == AF_INET6 ?
1082                       ((struct sockaddr_in6 *)&server)->sin6_port :
1083                       ((struct sockaddr_in *)&server)->sin_port);
1084     }
1085
1086     return fd;
1087
1088 exit:
1089     if (fd >= 0)
1090     {
1091         close(fd);
1092     }
1093     return OC_INVALID_SOCKET;
1094 }
1095
1096 static void CAInitializePipe(int *fds)
1097 {
1098     int ret = pipe(fds);
1099 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
1100 /* Temporary workaround: By pass F_GETFD / F_SETFD */
1101 #ifdef __TIZENRT__
1102     if (-1 == ret)
1103     {
1104         close(fds[1]);
1105         close(fds[0]);
1106
1107         fds[0] = -1;
1108         fds[1] = -1;
1109
1110         OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1111     }
1112 #else
1113     if (-1 != ret)
1114     {
1115         ret = fcntl(fds[0], F_GETFD);
1116         if (-1 != ret)
1117         {
1118             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1119         }
1120         if (-1 != ret)
1121         {
1122             ret = fcntl(fds[1], F_GETFD);
1123         }
1124         if (-1 != ret)
1125         {
1126             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1127         }
1128         if (-1 == ret)
1129         {
1130             close(fds[1]);
1131             close(fds[0]);
1132
1133             fds[0] = -1;
1134             fds[1] = -1;
1135
1136             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1137         }
1138     }
1139 #endif
1140 }
1141
1142 #ifndef DISABLE_TCP_SERVER
1143 #define NEWSOCKET(FAMILY, NAME) \
1144     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1145     if (caglobals.tcp.NAME.fd == -1) \
1146     { \
1147         caglobals.tcp.NAME.port = 0; \
1148         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1149     } \
1150
1151 void CATCPInitializeSocket()
1152 {
1153 #ifndef __WITH_TLS__
1154         NEWSOCKET(AF_INET, ipv4);
1155 #else
1156         NEWSOCKET(AF_INET, ipv4s);
1157 #endif
1158
1159 //TODO Enable once TizenRT supports IPv6
1160 #ifndef __TIZENRT__
1161 #ifndef __WITH_TLS__
1162         NEWSOCKET(AF_INET6, ipv6);
1163 #else
1164         NEWSOCKET(AF_INET6, ipv6s);
1165 #endif
1166 #endif
1167 #ifndef __WITH_TLS__
1168         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1169                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1170         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1171                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1172 #else
1173         OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1174                   caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1175         OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1176                   caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1177 #endif
1178 }
1179 #endif // DISABLE_TCP_SERVER
1180
1181 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1182 {
1183     oc_mutex_lock(g_mutexObjectList);
1184     if (caglobals.tcp.started)
1185     {
1186         oc_mutex_unlock(g_mutexObjectList);
1187         OIC_LOG(INFO, TAG, "Adapter is started already");
1188         return CA_STATUS_OK;
1189     }
1190
1191     g_threadPool = threadPool;
1192
1193     if (!caglobals.tcp.ipv4tcpenabled)
1194     {
1195         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
1196     }
1197     if (!caglobals.tcp.ipv6tcpenabled)
1198     {
1199         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
1200     }
1201
1202     caglobals.tcp.terminate = false;
1203     if (!caglobals.tcp.svrlist)
1204     {
1205         caglobals.tcp.svrlist = u_arraylist_create();
1206     }
1207
1208 #ifndef DISABLE_TCP_SERVER
1209     if (caglobals.server)
1210     {
1211         CATCPInitializeSocket();
1212     }
1213 #endif
1214
1215 #ifndef __TIZENRT__
1216     // create pipe for fast shutdown
1217     CAInitializePipe(caglobals.tcp.shutdownFds);
1218 #endif
1219     // create pipe for connection event
1220     CAInitializePipe(caglobals.tcp.connectionFds);
1221
1222     CAResult_t res = CA_STATUS_OK;
1223 #ifndef __TIZENRT__
1224     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_taskId);
1225 #else
1226     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1227                                  "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1228 #endif
1229     if (CA_STATUS_OK != res)
1230     {
1231         oc_mutex_unlock(g_mutexObjectList);
1232         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1233         CATCPStopServer();
1234         return res;
1235     }
1236
1237     caglobals.tcp.started = true;
1238     oc_mutex_unlock(g_mutexObjectList);
1239
1240     OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1241     return CA_STATUS_OK;
1242 }
1243
1244 void CATCPStopServer()
1245 {
1246     oc_mutex_lock(g_mutexObjectList);
1247     if (caglobals.tcp.terminate)
1248     {
1249         oc_mutex_unlock(g_mutexObjectList);
1250         OIC_LOG(INFO, TAG, "Adapter is not enabled");
1251         return;
1252     }
1253
1254     // set terminate flag.
1255     caglobals.tcp.terminate = true;
1256
1257     oc_mutex_lock(g_mutexSend);
1258     oc_cond_signal(g_condSend);
1259     oc_mutex_unlock(g_mutexSend);
1260
1261 #ifdef __TIZENRT__
1262     if (caglobals.tcp.started)
1263     {
1264         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1265         caglobals.tcp.started = false;
1266     }
1267 #endif
1268
1269     // close accept socket.
1270 #ifndef __WITH_TLS__
1271     CLOSE_SOCKET(ipv4);
1272     CLOSE_SOCKET(ipv6);
1273 #else
1274     CLOSE_SOCKET(ipv4s);
1275     CLOSE_SOCKET(ipv6s);
1276 #endif
1277
1278     if (caglobals.tcp.connectionFds[1] != OC_INVALID_SOCKET)
1279     {
1280         close(caglobals.tcp.connectionFds[1]);
1281         caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1282     }
1283     if (caglobals.tcp.connectionFds[0] != OC_INVALID_SOCKET)
1284     {
1285         close(caglobals.tcp.connectionFds[0]);
1286         caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1287     }
1288 #ifndef __TIZENRT__
1289     if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1290     {
1291         close(caglobals.tcp.shutdownFds[1]);
1292         caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1293         // receive thread will stop immediately
1294     }
1295     if (caglobals.tcp.started)
1296     {
1297         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1298         caglobals.tcp.started = false;
1299     }
1300     if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1301     {
1302         close(caglobals.tcp.shutdownFds[0]);
1303         caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1304     }
1305 #endif
1306     oc_mutex_unlock(g_mutexObjectList);
1307
1308 #ifndef __TIZENRT__
1309     ca_thread_pool_remove_task(g_threadPool, g_taskId);
1310 #endif
1311
1312     CATCPDisconnectAll();
1313     sleep(1);
1314     OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1315 }
1316
1317 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1318 {
1319     g_packetReceivedCallback = callback;
1320 }
1321
1322 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1323 {
1324     g_connectionCallback = connHandler;
1325 }
1326
1327 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1328 {
1329     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1330
1331     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1332             ((unsigned char *)data)[0] >> 4);
1333
1334     coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1335     if (!pdu)
1336     {
1337         OIC_LOG(ERROR, TAG, "outpdu is null");
1338         OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1339         return 0;
1340     }
1341
1342     int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1343     if (0 >= ret)
1344     {
1345         OIC_LOG(ERROR, TAG, "pdu parse failed");
1346         coap_delete_pdu(pdu);
1347         return 0;
1348     }
1349
1350     size_t payloadLen = 0;
1351     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1352     OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1353               headerSize, pdu->length);
1354     if (pdu->length > headerSize)
1355     {
1356         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1357     }
1358
1359     OICFree(pdu);
1360
1361     return payloadLen;
1362 }
1363
1364 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1365                         size_t dlen, const char *fam)
1366 {
1367     OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1368
1369     // #1. find a session info from list.
1370     CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1371     if (OC_INVALID_SOCKET == sockFd)
1372     {
1373         // if there is no connection info, connect to remote device.
1374         sockFd = CAConnectTCPSession(endpoint);
1375         if (OC_INVALID_SOCKET == sockFd)
1376         {
1377             OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1378             return -1;
1379         }
1380     }
1381
1382     // #2. send data to remote device.
1383     ssize_t remainLen = dlen;
1384     unsigned int sendRetryTime = 1;
1385     do
1386     {
1387 #ifdef MSG_NOSIGNAL
1388         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1389 #else
1390         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1391 #endif
1392         if (-1 == len)
1393         {
1394             if (EWOULDBLOCK != errno && EAGAIN != errno)
1395             {
1396                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1397                 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1398                                    len, false, strerror(errno));
1399                 return len;
1400             }
1401
1402             // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds
1403             if (sendRetryTime > 32)
1404             {
1405                 return len;
1406             }
1407
1408             unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND;
1409             OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime);
1410
1411             oc_mutex_lock(g_mutexSend);
1412             oc_cond_wait_for(g_condSend, g_mutexSend, waitTime);
1413             oc_mutex_unlock(g_mutexSend);
1414
1415             oc_mutex_lock(g_mutexObjectList);
1416             if (caglobals.tcp.terminate)
1417             {
1418                 oc_mutex_unlock(g_mutexObjectList);
1419                 return len;
1420             }
1421             oc_mutex_unlock(g_mutexObjectList);
1422
1423             sendRetryTime = (sendRetryTime << 1);
1424
1425             continue;
1426         }
1427         sendRetryTime = 1;
1428         data += len;
1429         remainLen -= len;
1430     } while (remainLen > 0);
1431
1432 #ifndef TB_LOG
1433     (void)fam;
1434 #endif
1435     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1436     CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1437                        dlen, true, NULL);
1438     return dlen;
1439 }
1440
1441 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1442 {
1443     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1444     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1445
1446     if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1447     {
1448         return sendData(endpoint, data, datalen, "ipv6");
1449     }
1450     if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1451     {
1452         return sendData(endpoint, data, datalen, "ipv4");
1453     }
1454
1455     OIC_LOG(ERROR, TAG, "Not supported transport flags");
1456     return -1;
1457 }
1458
1459 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1460 {
1461     VERIFY_NON_NULL(info, TAG, "info is NULL");
1462     VERIFY_NON_NULL(size, TAG, "size is NULL");
1463
1464     return CA_NOT_SUPPORTED;
1465 }
1466
1467 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1468 {
1469     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1470
1471     // #1. create TCP server object
1472     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1473     if (!svritem)
1474     {
1475         OIC_LOG(ERROR, TAG, "Out of memory");
1476         return OC_INVALID_SOCKET;
1477     }
1478     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1479     svritem->sep.endpoint.adapter = endpoint->adapter;
1480     svritem->sep.endpoint.port = endpoint->port;
1481     svritem->sep.endpoint.flags = endpoint->flags;
1482     svritem->sep.endpoint.ifindex = endpoint->ifindex;
1483     svritem->state = CONNECTING;
1484     svritem->isClient = true;
1485
1486     // Allocate message buffer
1487     svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1488     if (!svritem->tlsdata)
1489     {
1490         OIC_LOG(ERROR, TAG, "Out of memory");
1491         OICFree(svritem);
1492         return OC_INVALID_SOCKET;
1493     }
1494
1495     // #2. add TCP connection info to list
1496     oc_mutex_lock(g_mutexObjectList);
1497     if (caglobals.tcp.svrlist)
1498     {
1499         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1500         if (!res)
1501         {
1502             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1503             close(svritem->fd);
1504             OICFree(svritem->tlsdata);
1505             OICFree(svritem);
1506             oc_mutex_unlock(g_mutexObjectList);
1507             return OC_INVALID_SOCKET;
1508         }
1509     }
1510     oc_mutex_unlock(g_mutexObjectList);
1511
1512     // #3. create the socket and connect to TCP server
1513     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1514     if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1515     {
1516         return OC_INVALID_SOCKET;
1517     }
1518
1519     // #4. pass the connection information to CA Common Layer.
1520     if (g_connectionCallback)
1521     {
1522         g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1523     }
1524
1525     return svritem->fd;
1526 }
1527
1528 CAResult_t CADisconnectTCPSession(size_t index)
1529 {
1530     CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1531     if (!removedData)
1532     {
1533         OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1534         return CA_STATUS_OK;
1535     }
1536
1537     // close the socket and remove session info in list.
1538     if (removedData->fd >= 0)
1539     {
1540         shutdown(removedData->fd, SHUT_RDWR);
1541         close(removedData->fd);
1542         removedData->fd = -1;
1543         removedData->state = (CONNECTED == removedData->state) ?
1544                                     DISCONNECTED : removedData->state;
1545
1546         // pass the connection information to CA Common Layer.
1547         if (g_connectionCallback && DISCONNECTED == removedData->state)
1548         {
1549             g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1550         }
1551     }
1552     OICFree(removedData->data);
1553     removedData->data = NULL;
1554
1555     OICFree(removedData->tlsdata);
1556     removedData->tlsdata = NULL;
1557
1558     OICFree(removedData);
1559     removedData = NULL;
1560
1561     OIC_LOG(DEBUG, TAG, "data is removed from session list");
1562
1563 #ifndef DISABLE_TCP_SERVER
1564     if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1565     {
1566         CATCPInitializeSocket();
1567     }
1568 #endif
1569
1570     return CA_STATUS_OK;
1571 }
1572
1573 void CATCPDisconnectAll()
1574 {
1575     OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1576
1577     oc_mutex_lock(g_mutexObjectList);
1578
1579     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1580     for (ssize_t index = length; index > 0; index--)
1581     {
1582         // disconnect session from remote device.
1583         CADisconnectTCPSession(index - 1);
1584     }
1585
1586     u_arraylist_destroy(caglobals.tcp.svrlist);
1587     caglobals.tcp.svrlist = NULL;
1588
1589     oc_mutex_unlock(g_mutexObjectList);
1590
1591 #ifdef __WITH_TLS__
1592     CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1593 #endif
1594
1595     OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1596 }
1597
1598 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1599 {
1600     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1601     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1602
1603     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1604
1605     // get connection info from list
1606     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1607     for (size_t i = 0; i < length; i++)
1608     {
1609         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1610                 caglobals.tcp.svrlist, i);
1611         if (!svritem)
1612         {
1613             continue;
1614         }
1615
1616         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1617                      sizeof(svritem->sep.endpoint.addr))
1618                 && (svritem->sep.endpoint.port == endpoint->port)
1619                 && (svritem->sep.endpoint.flags & endpoint->flags))
1620         {
1621             OIC_LOG(DEBUG, TAG, "Found in session list");
1622             *index = i;
1623             return svritem;
1624         }
1625     }
1626
1627     OIC_LOG(DEBUG, TAG, "Session not found");
1628     return NULL;
1629 }
1630
1631 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1632 {
1633     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1634
1635     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1636
1637     // get connection info from list.
1638     oc_mutex_lock(g_mutexObjectList);
1639     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1640     for (size_t i = 0; i < length; i++)
1641     {
1642         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1643                 caglobals.tcp.svrlist, i);
1644         if (!svritem)
1645         {
1646             continue;
1647         }
1648
1649         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1650                      sizeof(svritem->sep.endpoint.addr))
1651                 && (svritem->sep.endpoint.port == endpoint->port)
1652                 && (svritem->sep.endpoint.flags & endpoint->flags))
1653         {
1654             oc_mutex_unlock(g_mutexObjectList);
1655             OIC_LOG(DEBUG, TAG, "Found in session list");
1656             return svritem->fd;
1657         }
1658     }
1659
1660     oc_mutex_unlock(g_mutexObjectList);
1661     OIC_LOG(DEBUG, TAG, "Session not found");
1662     return OC_INVALID_SOCKET;
1663 }
1664
1665 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1666 {
1667
1668     // check from the last item.
1669     CATCPSessionInfo_t *svritem = NULL;
1670     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1671     for (size_t i = 0; i < length; i++)
1672     {
1673         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1674
1675         if (svritem && svritem->fd == fd)
1676         {
1677             *index = i;
1678             oc_mutex_unlock(g_mutexObjectList);
1679             return svritem;
1680         }
1681     }
1682
1683
1684     return NULL;
1685 }
1686
1687 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1688 {
1689     CATCPSessionInfo_t *svritem = NULL;
1690     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1691     for (size_t i = 0; i < length; i++)
1692     {
1693         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1694
1695         if (svritem && svritem->fd == fd)
1696         {
1697             *index = i;
1698             return svritem;
1699         }
1700     }
1701
1702     return NULL;
1703 }
1704
1705 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1706 {
1707     oc_mutex_lock(g_mutexObjectList);
1708
1709     CAResult_t result = CA_STATUS_OK;
1710     size_t index = 0;
1711     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1712     if (svritem)
1713     {
1714         result = CADisconnectTCPSession(index);
1715         if (CA_STATUS_OK != result)
1716         {
1717             OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1718         }
1719     }
1720
1721     oc_mutex_unlock(g_mutexObjectList);
1722     return result;
1723 }
1724
1725 void CATCPCloseInProgressConnections()
1726 {
1727     OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1728
1729     oc_mutex_lock(g_mutexObjectList);
1730
1731     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1732     for (size_t index = 0; index < length; index++)
1733     {
1734         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1735                 caglobals.tcp.svrlist, index);
1736         if (!svritem)
1737         {
1738             continue;
1739         }
1740
1741         // Session which are connecting state
1742         if (svritem->fd >= 0 && svritem->state == CONNECTING)
1743         {
1744             shutdown(svritem->fd, SHUT_RDWR);
1745             close(svritem->fd);
1746             svritem->fd = -1;
1747             svritem->state = DISCONNECTED;
1748         }
1749     }
1750
1751     oc_mutex_unlock(g_mutexObjectList);
1752
1753     OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1754 }
1755
1756 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1757 {
1758     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1759
1760     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1761             ((unsigned char *)recvBuffer)[0] >> 4);
1762     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1763                                                         transport);
1764     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1765
1766     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1767     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1768     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1769
1770     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1771     return headerLen + optPaylaodLen;
1772 }
1773
1774 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1775 {
1776     g_tcpErrorHandler = errorHandleCallback;
1777 }