Fix the build error for tizen 5.5's dlog format
[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 #if defined(__TIZEN__)
852 static int CAGetHTTPStatusCode(char * response) {
853     char *resp, *code_plus, *ptrSave;
854     int ret = -1;
855
856     resp = strdup(response);
857     strtok_r(resp, " ", &ptrSave);  /* skip HTTP version */
858     code_plus = strtok_r(NULL, " ", &ptrSave);
859
860     ret = code_plus ? atoi(code_plus) : -1;
861     free(resp);
862     return ret;
863 }
864 #endif
865
866 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
867 {
868     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
869
870     OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
871               svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
872
873     // #1. create tcp socket.
874     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
875     if (-1 == fd)
876     {
877         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
878         return CA_SOCKET_OPERATION_FAILED;
879     }
880     svritem->fd = fd;
881
882     // #2. convert address from string to binary.
883     struct sockaddr_storage sa = { .ss_family = family };
884     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
885                                             svritem->sep.endpoint.port, &sa);
886     if (CA_STATUS_OK != res)
887     {
888         OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
889         return CA_SOCKET_OPERATION_FAILED;
890     }
891
892     // #3. set socket length.
893     socklen_t socklen = 0;
894     if (sa.ss_family == AF_INET6)
895     {
896         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
897         if (!sock6->sin6_scope_id)
898         {
899             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
900         }
901         socklen = sizeof(struct sockaddr_in6);
902     }
903     else
904     {
905         socklen = sizeof(struct sockaddr_in);
906     }
907
908     // #4. connect to remote server device.
909     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
910     {
911         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
912         CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
913                            svritem->sep.endpoint.port, 0, false, strerror(errno));
914         return CA_SOCKET_OPERATION_FAILED;
915     }
916
917     OIC_LOG(INFO, TAG, "connect socket success");
918     svritem->state = CONNECTED;
919     CHECKFD(svritem->fd);
920     ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
921     if (-1 == len)
922     {
923         OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
924         return CA_SOCKET_OPERATION_FAILED;
925     }
926
927 #if defined(__TIZEN__)
928     // #5. Send HTTP CONNECT to proxy if proxy
929
930     const char *cloud_address = CAGetCloudAddressForProxy();
931     OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)");
932
933     if(cloud_address && *cloud_address)
934     {
935         char message[4096];
936         int len = sprintf(message,
937                 "CONNECT %s HTTP/1.1\r\n"
938                 "Host: %s\r\n\r\n", cloud_address, cloud_address
939         );
940
941         ssize_t l = send(fd, message, len, 0);
942         if(l != len)
943         {
944             OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %d)", len, l);
945             close(fd);
946             svritem->fd = -1;
947             return CA_SOCKET_OPERATION_FAILED;
948         }
949
950         // maybe this should be called in other thread, it causes bottleneck.
951         OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message);
952
953         *message = '\0';
954         OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy...");
955
956         l = recv(fd, message, 4096, 0);
957
958         OIC_LOG_V(INFO, TAG, "Received data : '%s'", message);
959         OIC_LOG_V(INFO, TAG, "Received len = %d", l);
960
961         int status_code = CAGetHTTPStatusCode(message);
962
963         OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code);
964         if(status_code < 200 || status_code > 299)
965         {
966             OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %d", status_code);
967             close(fd);
968             svritem->fd = -1;
969             return CA_SOCKET_OPERATION_FAILED;
970         }
971     }
972 #endif
973
974     return CA_STATUS_OK;
975 }
976
977 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
978 {
979     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
980
981     if (OC_INVALID_SOCKET != sock->fd)
982     {
983         OIC_LOG(DEBUG, TAG, "accept socket created already");
984         return sock->fd;
985     }
986
987     socklen_t socklen = 0;
988     struct sockaddr_storage server = { .ss_family = family };
989
990     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
991     if (OC_INVALID_SOCKET == fd)
992     {
993         OIC_LOG(ERROR, TAG, "Failed to create socket");
994         goto exit;
995     }
996
997     if (family == AF_INET6)
998     {
999         // the socket is restricted to sending and receiving IPv6 packets only.
1000         int on = 1;
1001 //TODO: enable once IPv6 is supported
1002 #ifndef __TIZENRT__
1003         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
1004         {
1005             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
1006             goto exit;
1007         }
1008 #endif
1009         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
1010         socklen = sizeof (struct sockaddr_in6);
1011     }
1012     else
1013     {
1014         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
1015         socklen = sizeof (struct sockaddr_in);
1016     }
1017
1018     int reuse = 1;
1019     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
1020     {
1021         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
1022         goto exit;
1023     }
1024
1025     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
1026     {
1027         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1028         goto exit;
1029     }
1030
1031     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
1032     {
1033         OIC_LOG(ERROR, TAG, "listen() error");
1034         goto exit;
1035     }
1036
1037     if (sock->port) // use the given port
1038     {
1039         int on = 1;
1040         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
1041         {
1042             OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
1043             close(fd);
1044             return OC_INVALID_SOCKET;
1045         }
1046     }
1047     else  // return the assigned port
1048     {
1049         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
1050         {
1051             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
1052             goto exit;
1053         }
1054         sock->port = ntohs(family == AF_INET6 ?
1055                       ((struct sockaddr_in6 *)&server)->sin6_port :
1056                       ((struct sockaddr_in *)&server)->sin_port);
1057     }
1058
1059     return fd;
1060
1061 exit:
1062     if (fd >= 0)
1063     {
1064         close(fd);
1065     }
1066     return OC_INVALID_SOCKET;
1067 }
1068
1069 static void CAInitializePipe(int *fds)
1070 {
1071     int ret = pipe(fds);
1072 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
1073 /* Temporary workaround: By pass F_GETFD / F_SETFD */
1074 #ifdef __TIZENRT__
1075     if (-1 == ret)
1076     {
1077         close(fds[1]);
1078         close(fds[0]);
1079
1080         fds[0] = -1;
1081         fds[1] = -1;
1082
1083         OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1084     }
1085 #else
1086     if (-1 != ret)
1087     {
1088         ret = fcntl(fds[0], F_GETFD);
1089         if (-1 != ret)
1090         {
1091             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1092         }
1093         if (-1 != ret)
1094         {
1095             ret = fcntl(fds[1], F_GETFD);
1096         }
1097         if (-1 != ret)
1098         {
1099             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1100         }
1101         if (-1 == ret)
1102         {
1103             close(fds[1]);
1104             close(fds[0]);
1105
1106             fds[0] = -1;
1107             fds[1] = -1;
1108
1109             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1110         }
1111     }
1112 #endif
1113 }
1114
1115 #ifndef DISABLE_TCP_SERVER
1116 #define NEWSOCKET(FAMILY, NAME) \
1117     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1118     if (caglobals.tcp.NAME.fd == -1) \
1119     { \
1120         caglobals.tcp.NAME.port = 0; \
1121         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1122     } \
1123     CHECKFD(caglobals.tcp.NAME.fd);
1124
1125 void CATCPInitializeSocket()
1126 {
1127 #ifndef __WITH_TLS__
1128         NEWSOCKET(AF_INET, ipv4);
1129 #else
1130         NEWSOCKET(AF_INET, ipv4s);
1131 #endif
1132
1133 //TODO Enable once TizenRT supports IPv6
1134 #ifndef __TIZENRT__
1135 #ifndef __WITH_TLS__
1136         NEWSOCKET(AF_INET6, ipv6);
1137 #else
1138         NEWSOCKET(AF_INET6, ipv6s);
1139 #endif
1140 #endif
1141 #ifndef __WITH_TLS__
1142         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1143                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1144         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1145                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1146 #else
1147         OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1148                   caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1149         OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1150                   caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1151 #endif
1152 }
1153 #endif // DISABLE_TCP_SERVER
1154
1155 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1156 {
1157     oc_mutex_lock(g_mutexObjectList);
1158     if (caglobals.tcp.started)
1159     {
1160         oc_mutex_unlock(g_mutexObjectList);
1161         OIC_LOG(INFO, TAG, "Adapter is started already");
1162         return CA_STATUS_OK;
1163     }
1164
1165     g_threadPool = threadPool;
1166
1167     if (!caglobals.tcp.ipv4tcpenabled)
1168     {
1169         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
1170     }
1171     if (!caglobals.tcp.ipv6tcpenabled)
1172     {
1173         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
1174     }
1175
1176     caglobals.tcp.terminate = false;
1177     if (!caglobals.tcp.svrlist)
1178     {
1179         caglobals.tcp.svrlist = u_arraylist_create();
1180     }
1181
1182 #ifndef DISABLE_TCP_SERVER
1183     if (caglobals.server)
1184     {
1185         CATCPInitializeSocket();
1186     }
1187 #endif
1188
1189 #ifndef __TIZENRT__
1190     // create pipe for fast shutdown
1191     CAInitializePipe(caglobals.tcp.shutdownFds);
1192     CHECKFD(caglobals.tcp.shutdownFds[0]);
1193     CHECKFD(caglobals.tcp.shutdownFds[1]);
1194 #endif
1195     // create pipe for connection event
1196     CAInitializePipe(caglobals.tcp.connectionFds);
1197     CHECKFD(caglobals.tcp.connectionFds[0]);
1198     CHECKFD(caglobals.tcp.connectionFds[1]);
1199
1200     CAResult_t res = CA_STATUS_OK;
1201 #ifndef __TIZENRT__
1202     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL);
1203 #else
1204     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1205                                  "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1206 #endif
1207     if (CA_STATUS_OK != res)
1208     {
1209         oc_mutex_unlock(g_mutexObjectList);
1210         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1211         CATCPStopServer();
1212         return res;
1213     }
1214
1215     caglobals.tcp.started = true;
1216     oc_mutex_unlock(g_mutexObjectList);
1217
1218     OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1219     return CA_STATUS_OK;
1220 }
1221
1222 void CATCPStopServer()
1223 {
1224     oc_mutex_lock(g_mutexObjectList);
1225     if (caglobals.tcp.terminate)
1226     {
1227         oc_mutex_unlock(g_mutexObjectList);
1228         OIC_LOG(INFO, TAG, "Adapter is not enabled");
1229         return;
1230     }
1231
1232     // set terminate flag.
1233     caglobals.tcp.terminate = true;
1234
1235     oc_mutex_lock(g_mutexSend);
1236     oc_cond_signal(g_condSend);
1237     oc_mutex_unlock(g_mutexSend);
1238
1239 #ifdef __TIZENRT__
1240     if (caglobals.tcp.started)
1241     {
1242         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1243         caglobals.tcp.started = false;
1244     }
1245 #endif
1246
1247     // close accept socket.
1248 #ifndef __WITH_TLS__
1249     CLOSE_SOCKET(ipv4);
1250     CLOSE_SOCKET(ipv6);
1251 #else
1252     CLOSE_SOCKET(ipv4s);
1253     CLOSE_SOCKET(ipv6s);
1254 #endif
1255
1256     if (caglobals.tcp.connectionFds[1] != OC_INVALID_SOCKET)
1257     {
1258         close(caglobals.tcp.connectionFds[1]);
1259         caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1260     }
1261     if (caglobals.tcp.connectionFds[0] != OC_INVALID_SOCKET)
1262     {
1263         close(caglobals.tcp.connectionFds[0]);
1264         caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1265     }
1266 #ifndef __TIZENRT__
1267     if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1268     {
1269         close(caglobals.tcp.shutdownFds[1]);
1270         caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1271         // receive thread will stop immediately
1272     }
1273     if (caglobals.tcp.started)
1274     {
1275         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1276         caglobals.tcp.started = false;
1277     }
1278     if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1279     {
1280         close(caglobals.tcp.shutdownFds[0]);
1281         caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1282     }
1283 #endif
1284     oc_mutex_unlock(g_mutexObjectList);
1285
1286     CATCPDisconnectAll();
1287     sleep(1);
1288
1289     OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1290 }
1291
1292 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1293 {
1294     g_packetReceivedCallback = callback;
1295 }
1296
1297 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1298 {
1299     g_connectionCallback = connHandler;
1300 }
1301
1302 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1303 {
1304     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1305
1306     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1307             ((unsigned char *)data)[0] >> 4);
1308
1309     coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1310     if (!pdu)
1311     {
1312         OIC_LOG(ERROR, TAG, "outpdu is null");
1313         OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1314         return 0;
1315     }
1316
1317     int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1318     if (0 >= ret)
1319     {
1320         OIC_LOG(ERROR, TAG, "pdu parse failed");
1321         coap_delete_pdu(pdu);
1322         return 0;
1323     }
1324
1325     size_t payloadLen = 0;
1326     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1327     OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1328               headerSize, pdu->length);
1329     if (pdu->length > headerSize)
1330     {
1331         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1332     }
1333
1334     OICFree(pdu);
1335
1336     return payloadLen;
1337 }
1338
1339 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1340                         size_t dlen, const char *fam)
1341 {
1342     OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1343
1344     // #1. find a session info from list.
1345     CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1346     if (OC_INVALID_SOCKET == sockFd)
1347     {
1348         // if there is no connection info, connect to remote device.
1349         sockFd = CAConnectTCPSession(endpoint);
1350         if (OC_INVALID_SOCKET == sockFd)
1351         {
1352             OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1353             return -1;
1354         }
1355     }
1356
1357     // #2. send data to remote device.
1358     ssize_t remainLen = dlen;
1359     unsigned int sendRetryTime = 1;
1360     do
1361     {
1362 #ifdef MSG_NOSIGNAL
1363         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1364 #else
1365         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1366 #endif
1367         if (-1 == len)
1368         {
1369             if (EWOULDBLOCK != errno && EAGAIN != errno)
1370             {
1371                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1372                 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1373                                    len, false, strerror(errno));
1374                 return len;
1375             }
1376
1377             // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds
1378             if (sendRetryTime > 32)
1379             {
1380                 return len;
1381             }
1382
1383             unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND;
1384             OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime);
1385
1386             oc_mutex_lock(g_mutexSend);
1387             oc_cond_wait_for(g_condSend, g_mutexSend, waitTime);
1388             oc_mutex_unlock(g_mutexSend);
1389
1390             oc_mutex_lock(g_mutexObjectList);
1391             if (caglobals.tcp.terminate)
1392             {
1393                 oc_mutex_unlock(g_mutexObjectList);
1394                 return len;
1395             }
1396             oc_mutex_unlock(g_mutexObjectList);
1397
1398             sendRetryTime = (sendRetryTime << 1);
1399
1400             continue;
1401         }
1402         sendRetryTime = 1;
1403         data += len;
1404         remainLen -= len;
1405     } while (remainLen > 0);
1406
1407 #ifndef TB_LOG
1408     (void)fam;
1409 #endif
1410     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1411     CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1412                        dlen, true, NULL);
1413     return dlen;
1414 }
1415
1416 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1417 {
1418     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1419     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1420
1421     if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1422     {
1423         return sendData(endpoint, data, datalen, "ipv6");
1424     }
1425     if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1426     {
1427         return sendData(endpoint, data, datalen, "ipv4");
1428     }
1429
1430     OIC_LOG(ERROR, TAG, "Not supported transport flags");
1431     return -1;
1432 }
1433
1434 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1435 {
1436     VERIFY_NON_NULL(info, TAG, "info is NULL");
1437     VERIFY_NON_NULL(size, TAG, "size is NULL");
1438
1439     return CA_NOT_SUPPORTED;
1440 }
1441
1442 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1443 {
1444     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1445
1446     // #1. create TCP server object
1447     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1448     if (!svritem)
1449     {
1450         OIC_LOG(ERROR, TAG, "Out of memory");
1451         return OC_INVALID_SOCKET;
1452     }
1453     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1454     svritem->sep.endpoint.adapter = endpoint->adapter;
1455     svritem->sep.endpoint.port = endpoint->port;
1456     svritem->sep.endpoint.flags = endpoint->flags;
1457     svritem->sep.endpoint.ifindex = endpoint->ifindex;
1458     svritem->state = CONNECTING;
1459     svritem->isClient = true;
1460
1461     // Allocate message buffer
1462     svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1463     if (!svritem->tlsdata)
1464     {
1465         OIC_LOG(ERROR, TAG, "Out of memory");
1466         OICFree(svritem);
1467         return OC_INVALID_SOCKET;
1468     }
1469
1470     // #2. add TCP connection info to list
1471     oc_mutex_lock(g_mutexObjectList);
1472     if (caglobals.tcp.svrlist)
1473     {
1474         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1475         if (!res)
1476         {
1477             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1478             close(svritem->fd);
1479             OICFree(svritem->tlsdata);
1480             OICFree(svritem);
1481             oc_mutex_unlock(g_mutexObjectList);
1482             return OC_INVALID_SOCKET;
1483         }
1484     }
1485     oc_mutex_unlock(g_mutexObjectList);
1486
1487     // #3. create the socket and connect to TCP server
1488     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1489     if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1490     {
1491         return OC_INVALID_SOCKET;
1492     }
1493
1494     // #4. pass the connection information to CA Common Layer.
1495     if (g_connectionCallback)
1496     {
1497         g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1498     }
1499
1500     return svritem->fd;
1501 }
1502
1503 CAResult_t CADisconnectTCPSession(size_t index)
1504 {
1505     CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1506     if (!removedData)
1507     {
1508         OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1509         return CA_STATUS_OK;
1510     }
1511
1512     // close the socket and remove session info in list.
1513     if (removedData->fd >= 0)
1514     {
1515         shutdown(removedData->fd, SHUT_RDWR);
1516         close(removedData->fd);
1517         removedData->fd = -1;
1518         removedData->state = (CONNECTED == removedData->state) ?
1519                                     DISCONNECTED : removedData->state;
1520
1521         // pass the connection information to CA Common Layer.
1522         if (g_connectionCallback && DISCONNECTED == removedData->state)
1523         {
1524             g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1525         }
1526     }
1527     OICFree(removedData->data);
1528     removedData->data = NULL;
1529
1530     OICFree(removedData->tlsdata);
1531     removedData->tlsdata = NULL;
1532
1533     OICFree(removedData);
1534     removedData = NULL;
1535
1536     OIC_LOG(DEBUG, TAG, "data is removed from session list");
1537
1538 #ifndef DISABLE_TCP_SERVER
1539     if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1540     {
1541         CATCPInitializeSocket();
1542     }
1543 #endif
1544
1545     return CA_STATUS_OK;
1546 }
1547
1548 void CATCPDisconnectAll()
1549 {
1550     OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1551
1552     oc_mutex_lock(g_mutexObjectList);
1553
1554     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1555     for (ssize_t index = length; index > 0; index--)
1556     {
1557         // disconnect session from remote device.
1558         CADisconnectTCPSession(index - 1);
1559     }
1560
1561     u_arraylist_destroy(caglobals.tcp.svrlist);
1562     caglobals.tcp.svrlist = NULL;
1563
1564     oc_mutex_unlock(g_mutexObjectList);
1565
1566 #ifdef __WITH_TLS__
1567     CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1568 #endif
1569
1570     OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1571 }
1572
1573 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1574 {
1575     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1576     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1577
1578     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1579
1580     // get connection info from list
1581     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1582     for (size_t i = 0; i < length; i++)
1583     {
1584         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1585                 caglobals.tcp.svrlist, i);
1586         if (!svritem)
1587         {
1588             continue;
1589         }
1590
1591         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1592                      sizeof(svritem->sep.endpoint.addr))
1593                 && (svritem->sep.endpoint.port == endpoint->port)
1594                 && (svritem->sep.endpoint.flags & endpoint->flags))
1595         {
1596             OIC_LOG(DEBUG, TAG, "Found in session list");
1597             *index = i;
1598             return svritem;
1599         }
1600     }
1601
1602     OIC_LOG(DEBUG, TAG, "Session not found");
1603     return NULL;
1604 }
1605
1606 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1607 {
1608     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1609
1610     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1611
1612     // get connection info from list.
1613     oc_mutex_lock(g_mutexObjectList);
1614     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1615     for (size_t i = 0; i < length; i++)
1616     {
1617         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1618                 caglobals.tcp.svrlist, i);
1619         if (!svritem)
1620         {
1621             continue;
1622         }
1623
1624         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1625                      sizeof(svritem->sep.endpoint.addr))
1626                 && (svritem->sep.endpoint.port == endpoint->port)
1627                 && (svritem->sep.endpoint.flags & endpoint->flags))
1628         {
1629             oc_mutex_unlock(g_mutexObjectList);
1630             OIC_LOG(DEBUG, TAG, "Found in session list");
1631             return svritem->fd;
1632         }
1633     }
1634
1635     oc_mutex_unlock(g_mutexObjectList);
1636     OIC_LOG(DEBUG, TAG, "Session not found");
1637     return OC_INVALID_SOCKET;
1638 }
1639
1640 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1641 {
1642
1643     // check from the last item.
1644     CATCPSessionInfo_t *svritem = NULL;
1645     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1646     for (size_t i = 0; i < length; i++)
1647     {
1648         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1649
1650         if (svritem && svritem->fd == fd)
1651         {
1652             *index = i;
1653             oc_mutex_unlock(g_mutexObjectList);
1654             return svritem;
1655         }
1656     }
1657
1658
1659     return NULL;
1660 }
1661
1662 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1663 {
1664     CATCPSessionInfo_t *svritem = NULL;
1665     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1666     for (size_t i = 0; i < length; i++)
1667     {
1668         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1669
1670         if (svritem && svritem->fd == fd)
1671         {
1672             *index = i;
1673             return svritem;
1674         }
1675     }
1676
1677     return NULL;
1678 }
1679
1680 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1681 {
1682     oc_mutex_lock(g_mutexObjectList);
1683
1684     CAResult_t result = CA_STATUS_OK;
1685     size_t index = 0;
1686     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1687     if (svritem)
1688     {
1689         result = CADisconnectTCPSession(index);
1690         if (CA_STATUS_OK != result)
1691         {
1692             OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1693         }
1694     }
1695
1696     oc_mutex_unlock(g_mutexObjectList);
1697     return result;
1698 }
1699
1700 void CATCPCloseInProgressConnections()
1701 {
1702     OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1703
1704     oc_mutex_lock(g_mutexObjectList);
1705
1706     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1707     for (size_t index = 0; index < length; index++)
1708     {
1709         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1710                 caglobals.tcp.svrlist, index);
1711         if (!svritem)
1712         {
1713             continue;
1714         }
1715
1716         // Session which are connecting state
1717         if (svritem->fd >= 0 && svritem->state == CONNECTING)
1718         {
1719             shutdown(svritem->fd, SHUT_RDWR);
1720             close(svritem->fd);
1721             svritem->fd = -1;
1722             svritem->state = DISCONNECTED;
1723         }
1724     }
1725
1726     oc_mutex_unlock(g_mutexObjectList);
1727
1728     OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1729 }
1730
1731 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1732 {
1733     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1734
1735     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1736             ((unsigned char *)recvBuffer)[0] >> 4);
1737     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1738                                                         transport);
1739     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1740
1741     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1742     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1743     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1744
1745     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1746     return headerLen + optPaylaodLen;
1747 }
1748
1749 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1750 {
1751     g_tcpErrorHandler = errorHandleCallback;
1752 }