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