8ba71895fe3f88de1ef8b12cf27cc3f6e4815f24
[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 #include "oic_string.h"
52
53 #ifdef __WITH_TLS__
54 #include "ca_adapter_net_ssl.h"
55 #endif
56
57 /**
58  * Logging tag for module name.
59  */
60 //#define TAG "OIC_CA_TCP_SERVER"
61 #define TAG TCP_SERVER_TAG
62
63 /**
64  * Maximum CoAP over TCP header length
65  * to know the total data length.
66  */
67 #define COAP_MAX_HEADER_SIZE  6
68
69 /**
70  * TLS header size
71  */
72 #define TLS_HEADER_SIZE 5
73
74 /**
75  * Max Connection Counts.
76  */
77 #define MAX_CONNECTION_COUNTS   500
78
79 #define COAP_TCP_MAX_BUFFER_CHUNK_SIZE 65530 //64kb - 6 (coap+tcp max header size)
80
81 #define MILLISECONDS_PER_SECOND   (1000)
82
83 /**
84  * Thread pool.
85  */
86 static ca_thread_pool_t g_threadPool = NULL;
87
88 /**
89  * Mutex to synchronize device object list.
90  */
91 static oc_mutex g_mutexObjectList = NULL;
92
93 /**
94  * Conditional mutex to synchronize.
95  */
96 static oc_cond g_condObjectList = NULL;
97
98 /**
99  * Mutex to synchronize send.
100  */
101 static oc_mutex g_mutexSend = NULL;
102
103 /**
104  * Conditional mutex to synchronize send.
105  */
106 static oc_cond g_condSend = NULL;
107
108 /**
109  * Maintains the callback to be notified when data received from remote device.
110  */
111 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
112
113 /**
114  * Error callback to update error in TCP.
115  */
116 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
117
118 /**
119  * Connected Callback to pass the connection information to RI.
120  */
121 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
122
123 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
124 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
125 static void CAFindReadyMessage();
126 static void CASelectReturned(fd_set *readFds);
127 static void CAReceiveMessage(int fd);
128 static void CAReceiveHandler(void *data);
129 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
130 static void CATCPInitializeSocket();
131 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index);
132
133 #if defined(__TIZEN__)
134 static char g_cloudproxyUri[CA_MAX_URI_LENGTH];
135
136 CAResult_t CASetCloudAddressForProxy(const char *uri)
137 {
138     if (uri == NULL)
139         memset(g_cloudproxyUri, '\0', sizeof (g_cloudproxyUri));
140     else
141         OICStrcpy(g_cloudproxyUri, sizeof (g_cloudproxyUri), uri);
142     return CA_STATUS_OK;
143 }
144
145 const char *CAGetCloudAddressForProxy()
146 {
147     if (g_cloudproxyUri[0] == '\0')
148         return NULL;
149     return g_cloudproxyUri;
150 }
151 #endif
152
153 #define CHECKFD(FD) \
154     if (FD > caglobals.tcp.maxfd) \
155         caglobals.tcp.maxfd = FD;
156
157 #define CLOSE_SOCKET(TYPE) \
158     if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
159     { \
160         close(caglobals.tcp.TYPE.fd); \
161         caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
162     }
163
164 #define CA_FD_SET(TYPE, FDS) \
165     if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
166     { \
167         FD_SET(caglobals.tcp.TYPE.fd, FDS); \
168     }
169
170 void CATCPDestroyMutex()
171 {
172     if (g_mutexObjectList)
173     {
174         oc_mutex_free(g_mutexObjectList);
175         g_mutexObjectList = NULL;
176     }
177 }
178
179 CAResult_t CATCPCreateMutex()
180 {
181     if (!g_mutexObjectList)
182     {
183         g_mutexObjectList = oc_mutex_new();
184         if (!g_mutexObjectList)
185         {
186             OIC_LOG(ERROR, TAG, "Failed to create mutex!");
187             return CA_STATUS_FAILED;
188         }
189     }
190
191     return CA_STATUS_OK;
192 }
193
194 void CATCPDestroyCond()
195 {
196     if (g_condObjectList)
197     {
198         oc_cond_free(g_condObjectList);
199         g_condObjectList = NULL;
200     }
201 }
202
203 CAResult_t CATCPCreateCond()
204 {
205     if (!g_condObjectList)
206     {
207         g_condObjectList = oc_cond_new();
208         if (!g_condObjectList)
209         {
210             OIC_LOG(ERROR, TAG, "Failed to create cond!");
211             return CA_STATUS_FAILED;
212         }
213     }
214     return CA_STATUS_OK;
215 }
216
217 void CATCPDestroySendMutex()
218 {
219     if (g_mutexSend)
220     {
221         oc_mutex_free(g_mutexSend);
222         g_mutexSend = NULL;
223     }
224 }
225
226 CAResult_t CATCPCreateSendMutex()
227 {
228     if (!g_mutexSend)
229     {
230         g_mutexSend = oc_mutex_new();
231         if (!g_mutexSend)
232         {
233             OIC_LOG(ERROR, TAG, "Failed to create send mutex!");
234             return CA_STATUS_FAILED;
235         }
236     }
237
238     return CA_STATUS_OK;
239 }
240
241 void CATCPDestroySendCond()
242 {
243     if (g_condSend)
244     {
245         oc_cond_free(g_condSend);
246         g_condSend = NULL;
247     }
248 }
249
250 CAResult_t CATCPCreateSendCond()
251 {
252     if (!g_condSend)
253     {
254         g_condSend = oc_cond_new();
255         if (!g_condSend)
256         {
257             OIC_LOG(ERROR, TAG, "Failed to create send cond!");
258             return CA_STATUS_FAILED;
259         }
260     }
261     return CA_STATUS_OK;
262 }
263
264 static void CAReceiveHandler(void *data)
265 {
266     (void)data;
267     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
268
269     while (true)
270     {
271         oc_mutex_lock(g_mutexObjectList);
272         if (caglobals.tcp.terminate)
273         {
274             oc_mutex_unlock(g_mutexObjectList);
275             break;
276         }
277         oc_mutex_unlock(g_mutexObjectList);
278         CAFindReadyMessage();
279     }
280
281     oc_mutex_lock(g_mutexObjectList);
282     oc_cond_signal(g_condObjectList);
283     oc_mutex_unlock(g_mutexObjectList);
284
285     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
286 }
287
288 static void CAFindReadyMessage()
289 {
290     fd_set readFds;
291     struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
292
293     FD_ZERO(&readFds);
294     CA_FD_SET(ipv4, &readFds);
295     CA_FD_SET(ipv4s, &readFds);
296     CA_FD_SET(ipv6, &readFds);
297     CA_FD_SET(ipv6s, &readFds);
298 #ifndef __TIZENRT__
299     if (OC_INVALID_SOCKET != caglobals.tcp.shutdownFds[0])
300     {
301         FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
302     }
303 #endif
304     if (OC_INVALID_SOCKET != caglobals.tcp.connectionFds[0])
305     {
306         FD_SET(caglobals.tcp.connectionFds[0], &readFds);
307     }
308
309     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
310     for (size_t i = 0; i < length; i++)
311     {
312         CATCPSessionInfo_t *svritem =
313                 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
314         if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
315         {
316             FD_SET(svritem->fd, &readFds);
317         }
318     }
319
320     int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
321
322     oc_mutex_lock(g_mutexObjectList);
323     if (caglobals.tcp.terminate)
324     {
325         oc_mutex_unlock(g_mutexObjectList);
326         OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
327         return;
328     }
329     oc_mutex_unlock(g_mutexObjectList);
330     if (0 >= ret)
331     {
332         if (0 > ret)
333         {
334             OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
335         }
336         return;
337     }
338
339     CASelectReturned(&readFds);
340 }
341
342 static void CASelectReturned(fd_set *readFds)
343 {
344     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
345
346     if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
347     {
348         CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
349         return;
350     }
351     else if (caglobals.tcp.ipv4s.fd != -1 && FD_ISSET(caglobals.tcp.ipv4s.fd, readFds))
352     {
353         CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
354         return;
355     }
356     else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
357     {
358         CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
359         return;
360     }
361     else if (caglobals.tcp.ipv6s.fd != -1 && FD_ISSET(caglobals.tcp.ipv6s.fd, readFds))
362     {
363         CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
364         return;
365     }
366     else if (-1 != caglobals.tcp.connectionFds[0] &&
367             FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
368     {
369         // new connection was created from remote device.
370         // exit the function to update read file descriptor.
371         char buf[MAX_ADDR_STR_SIZE_CA] = {0};
372         ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
373         if (-1 == len)
374         {
375             return;
376         }
377         OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
378         return;
379     }
380     else
381     {
382         int *readFDList = NULL;
383         size_t readFDListSize = 0;
384
385         oc_mutex_lock(g_mutexObjectList);
386         uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
387
388         readFDList = (int*) OICCalloc(length, sizeof(int));
389         if (NULL == readFDList)
390         {
391             OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
392             oc_mutex_unlock(g_mutexObjectList);
393             return;
394         }
395
396         for (size_t i = 0; i < length; i++)
397         {
398             CATCPSessionInfo_t *svritem =
399                     (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
400             if (svritem && svritem->fd >= 0)
401             {
402                 if (FD_ISSET(svritem->fd, readFds))
403                 {
404                     readFDList[readFDListSize++] = svritem->fd;
405                 }
406             }
407         }
408         oc_mutex_unlock(g_mutexObjectList);
409
410         // Read incomming messages from fds
411         for (size_t i = 0; i < readFDListSize; i++)
412         {
413             CAReceiveMessage(readFDList[i]);
414         }
415
416         OICFree(readFDList);
417     }
418 }
419
420 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
421 {
422     OIC_LOG_V(INFO, TAG, "In %s", __func__);
423     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
424
425     if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
426     {
427         OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
428         close(sock->fd);
429         sock->fd = OC_INVALID_SOCKET;
430         return;
431     }
432
433     struct sockaddr_storage clientaddr;
434     socklen_t clientlen = sizeof (struct sockaddr_in);
435     if (flag & CA_IPV6)
436     {
437         clientlen = sizeof(struct sockaddr_in6);
438     }
439
440     CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
441     if (OC_INVALID_SOCKET != sockfd)
442     {
443         CATCPSessionInfo_t *svritem =
444                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
445         if (!svritem)
446         {
447             OIC_LOG(ERROR, TAG, "Out of memory");
448             close(sockfd);
449             return;
450         }
451
452         svritem->fd = sockfd;
453         svritem->sep.endpoint.flags = flag;
454         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
455         svritem->state = CONNECTED;
456         svritem->isClient = false;
457         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
458                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
459
460         // Allocate message buffer
461         svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
462         if (!svritem->tlsdata)
463         {
464             OIC_LOG(ERROR, TAG, "Out of memory");
465             close(sockfd);
466             OICFree(svritem);
467             return;
468         }
469
470         oc_mutex_lock(g_mutexObjectList);
471         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
472         if (!result)
473         {
474             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
475             close(sockfd);
476             OICFree(svritem->tlsdata);
477             OICFree(svritem);
478             oc_mutex_unlock(g_mutexObjectList);
479             return;
480         }
481         oc_mutex_unlock(g_mutexObjectList);
482
483         CHECKFD(sockfd);
484
485         // pass the connection information to CA Common Layer.
486         if (g_connectionCallback)
487         {
488             g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
489         }
490     }
491     OIC_LOG_V(INFO, TAG, "Out %s", __func__);
492 }
493
494 /**
495  * Clean socket state data
496  *
497  * @param[in/out] item - socket state data
498  */
499 void CACleanData(CATCPSessionInfo_t *svritem)
500 {
501     if (svritem)
502     {
503         OICFree(svritem->data);
504         svritem->data = NULL;
505         svritem->len = 0;
506 #ifdef __WITH_TLS__
507         svritem->tlsLen = 0;
508 #endif
509         svritem->totalLen = 0;
510         svritem->bufLen = 0;
511         svritem->protocol = UNKNOWN;
512     }
513 }
514
515 /**
516  * Construct CoAP header and payload from buffer
517  *
518  * @param[in] svritem - used socket, buffer, current received message length and protocol
519  * @param[in/out]  data  - data buffer, this value is updated as data is copied to svritem
520  * @param[in/out]  dataLength  - length of data, this value decreased as data is copied to svritem
521  * @return             - CA_STATUS_OK or appropriate error code
522  */
523 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
524                           size_t *dataLength)
525 {
526     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
527
528     if (NULL == svritem || NULL == data || NULL == dataLength)
529     {
530         OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
531         return CA_STATUS_INVALID_PARAM;
532     }
533
534     unsigned char *inBuffer = *data;
535     size_t inLen = *dataLength;
536     OIC_LOG_V(DEBUG, TAG, "before-datalength : %zd", *dataLength);
537
538     if (NULL == svritem->data && inLen > 0)
539     {
540         // allocate memory for message header (CoAP header size because it is bigger)
541         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
542         if (NULL == svritem->data)
543         {
544             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
545             return CA_MEMORY_ALLOC_FAILED;
546         }
547
548         // copy 1 byte to parse coap header length
549         memcpy(svritem->data, inBuffer, 1);
550         svritem->len = 1;
551         svritem->bufLen = COAP_MAX_HEADER_SIZE;
552         inBuffer++;
553         inLen--;
554     }
555
556     //if not enough data received - read them on next CAFillHeader() call
557     if (0 == inLen)
558     {
559         return CA_STATUS_OK;
560     }
561
562     //if enough data received - parse header
563     svritem->protocol = COAP;
564
565     //seems CoAP data received. read full coap header.
566     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
567     size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
568     size_t copyLen = 0;
569
570     // HEADER
571     if (svritem->len < headerLen)
572     {
573         copyLen = headerLen - svritem->len;
574         if (inLen < copyLen)
575         {
576             copyLen = inLen;
577         }
578
579         //read required bytes to have full CoAP header
580         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
581         svritem->len += copyLen;
582         inBuffer += copyLen;
583         inLen -= copyLen;
584
585         //if not enough data received - read them on next CAFillHeader() call
586         if (svritem->len < headerLen)
587         {
588             *data = inBuffer;
589             *dataLength = inLen;
590             OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
591             return CA_STATUS_OK;
592         }
593
594         //calculate CoAP message length
595         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
596     }
597
598     // PAYLOAD
599     if (inLen > 0)
600     {
601         // Calculate length of data to be copied.
602         copyLen = svritem->totalLen - svritem->len;
603         if (inLen < copyLen)
604         {
605             copyLen = inLen;
606         }
607
608         // Is buffer not big enough for remaining data ?
609         if (svritem->len + copyLen > svritem->bufLen)
610         {
611             // Resize buffer to accommodate enough space
612             size_t extLen = svritem->totalLen - svritem->bufLen;
613             if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
614             {
615                 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
616             }
617
618             // Allocate required memory
619             unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
620             if (NULL == buffer)
621             {
622                 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
623                 return CA_MEMORY_ALLOC_FAILED;
624             }
625
626             svritem->data = buffer;
627             svritem->bufLen += extLen;
628         }
629
630         // Read required bytes to have full CoAP payload
631         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
632         svritem->len += copyLen;
633         inBuffer += copyLen;
634         inLen -= copyLen;
635     }
636
637     *data = inBuffer;
638     *dataLength = inLen;
639
640     OIC_LOG_V(DEBUG, TAG, "after-datalength : %zd", *dataLength);
641     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
642     return CA_STATUS_OK;
643 }
644
645 static void CAReceiveMessage(int fd)
646 {
647     CAResult_t res = CA_STATUS_OK;
648
649     oc_mutex_lock(g_mutexObjectList);
650
651     //get remote device information from file descriptor.
652     size_t index = 0;
653     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
654     if (!svritem)
655     {
656         OIC_LOG(ERROR, TAG, "there is no connection information in list");
657         oc_mutex_unlock(g_mutexObjectList);
658         return;
659     }
660
661     CASecureEndpoint_t peerEP = svritem->sep;
662     int len = 0;
663     if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection
664     {
665         svritem->protocol = TLS;
666
667 #ifdef __WITH_TLS__
668         size_t nbRead = 0;
669         size_t tlsLength = 0;
670
671         if (TLS_HEADER_SIZE > svritem->tlsLen)
672         {
673             nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
674         }
675         else
676         {
677             //[3][4] bytes in tls header are tls payload length
678             tlsLength = TLS_HEADER_SIZE +
679                             (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
680             OIC_LOG_V(DEBUG, TAG, "total tls length = %zd", tlsLength);
681             if (tlsLength > TLS_DATA_MAX_SIZE)
682             {
683                 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
684                                     TLS_DATA_MAX_SIZE);
685                 oc_mutex_unlock(g_mutexObjectList);
686                 CATCPDisconnectSession(&peerEP.endpoint);
687                 return;
688             }
689             nbRead = tlsLength - svritem->tlsLen;
690         }
691
692         len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
693         if (len < 0)
694         {
695             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
696             res = CA_RECEIVE_FAILED;
697         }
698         else if (0 == len)
699         {
700             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
701             svritem->state = DISCONNECTED;
702             res = CA_DESTINATION_DISCONNECTED;
703         }
704         else
705         {
706             svritem->tlsLen += len;
707             OIC_LOG_V(DEBUG, TAG, "nb_read : %zd bytes , recv() : %d bytes, svritem->tlsLen : %zd bytes",
708                                 nbRead, len, svritem->tlsLen);
709             if (tlsLength > 0 && tlsLength == svritem->tlsLen)
710             {
711                 // When successfully read data - pass them to callback.
712                 // Dont invoke callback locking mutex
713                 unsigned char *mesBuf = svritem->tlsdata;
714                 size_t mesBufLen = svritem->tlsLen;
715                 svritem->tlsdata = NULL;
716                 oc_mutex_unlock(g_mutexObjectList);
717
718                 res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen);
719                 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
720
721                 // Check for the svritem and reset buffer
722                 oc_mutex_lock(g_mutexObjectList);
723                 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
724                 if (svritem)
725                 {
726                     svritem->tlsdata = mesBuf;
727                     svritem->tlsLen = 0;
728                 }
729                 else
730                 {
731                     // svritem does not exist, thus free the message buffer
732                     OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
733                     OICFree(mesBuf);
734                 }
735             }
736         }
737 #endif
738     }
739     else // Non-Secure connection
740     {
741         svritem->protocol = COAP;
742
743         // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
744         len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0);
745         if (len < 0)
746         {
747             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
748             res = CA_RECEIVE_FAILED;
749         }
750         else if (0 == len)
751         {
752             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
753             res = CA_DESTINATION_DISCONNECTED;
754         }
755         else
756         {
757             //when successfully read data - pass them to callback.
758             OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
759             if (g_packetReceivedCallback)
760             {
761                 // Dont invoke callback locking mutex
762                 unsigned char *mesBuf = svritem->tlsdata;
763                 svritem->tlsdata = NULL;
764                 oc_mutex_unlock(g_mutexObjectList);
765
766                 res = g_packetReceivedCallback(&peerEP, mesBuf, len);
767
768                 // Check for the svritem and reset buffer
769                 oc_mutex_lock(g_mutexObjectList);
770                 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
771                 if (svritem)
772                 {
773                     svritem->tlsdata = mesBuf;
774                     svritem->tlsLen = 0;
775                 }
776                 else
777                 {
778                     // svritem does not exist, thus free the message buffer
779                     OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
780                     OICFree(mesBuf);
781                 }
782             }
783         }
784     }
785
786     oc_mutex_unlock(g_mutexObjectList);
787
788     if (res != CA_STATUS_OK)
789     {
790         CATCPDisconnectSession(&peerEP.endpoint);
791     }
792 }
793
794 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
795 {
796     if (caglobals.tcp.connectionFds[1] != -1)
797     {
798         ssize_t len = 0;
799         do
800         {
801             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
802         } while ((len == -1) && (errno == EINTR));
803
804         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
805         {
806             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
807         }
808         return len;
809     }
810     return -1;
811 }
812
813 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
814                                          struct sockaddr_storage *sockaddr)
815 {
816     struct addrinfo *addrs = NULL;
817     struct addrinfo hints = { .ai_family = family,
818                               .ai_protocol   = IPPROTO_TCP,
819                               .ai_socktype = SOCK_STREAM,
820                               .ai_flags = AI_NUMERICHOST };
821
822     int r = getaddrinfo(host, NULL, &hints, &addrs);
823     if (r)
824     {
825         if (EAI_SYSTEM == r)
826         {
827             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
828         }
829         else
830         {
831             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
832         }
833         freeaddrinfo(addrs);
834         return CA_STATUS_FAILED;
835     }
836     // assumption: in this case, getaddrinfo will only return one addrinfo
837     // or first is the one we want.
838     if (addrs[0].ai_family == AF_INET6)
839     {
840         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
841         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
842     }
843     else
844     {
845         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
846         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
847     }
848     freeaddrinfo(addrs);
849     return CA_STATUS_OK;
850 }
851
852 #if defined(__TIZEN__)
853 static int CAGetHTTPStatusCode(char * response) {
854     char *resp, *code_plus, *ptrSave;
855     int ret = -1;
856
857     resp = strdup(response);
858     strtok_r(resp, " ", &ptrSave);  /* skip HTTP version */
859     code_plus = strtok_r(NULL, " ", &ptrSave);
860
861     ret = code_plus ? atoi(code_plus) : -1;
862     free(resp);
863     return ret;
864 }
865 #endif
866
867 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
868 {
869     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
870
871     OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
872               svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
873
874     // #1. create tcp socket.
875     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
876     if (-1 == fd)
877     {
878         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
879         return CA_SOCKET_OPERATION_FAILED;
880     }
881     svritem->fd = fd;
882
883     // #2. convert address from string to binary.
884     struct sockaddr_storage sa = { .ss_family = family };
885     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
886                                             svritem->sep.endpoint.port, &sa);
887     if (CA_STATUS_OK != res)
888     {
889         OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
890         return CA_SOCKET_OPERATION_FAILED;
891     }
892
893     // #3. set socket length.
894     socklen_t socklen = 0;
895     if (sa.ss_family == AF_INET6)
896     {
897         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
898         if (!sock6->sin6_scope_id)
899         {
900             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
901         }
902         socklen = sizeof(struct sockaddr_in6);
903     }
904     else
905     {
906         socklen = sizeof(struct sockaddr_in);
907     }
908
909     // #4. connect to remote server device.
910     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
911     {
912         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
913         CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
914                            svritem->sep.endpoint.port, 0, false, strerror(errno));
915         return CA_SOCKET_OPERATION_FAILED;
916     }
917
918     OIC_LOG(INFO, TAG, "connect socket success");
919     svritem->state = CONNECTED;
920     CHECKFD(svritem->fd);
921     ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
922     if (-1 == len)
923     {
924         OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
925         return CA_SOCKET_OPERATION_FAILED;
926     }
927
928 #if defined(__TIZEN__)
929     // #5. Send HTTP CONNECT to proxy if proxy
930
931     const char *cloud_address = CAGetCloudAddressForProxy();
932     OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)");
933
934     if(cloud_address && *cloud_address)
935     {
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         ssize_t l = send(fd, message, len, 0);
943         if(l != len)
944         {
945             OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %zd)", len, l);
946             close(fd);
947             svritem->fd = -1;
948             return CA_SOCKET_OPERATION_FAILED;
949         }
950
951         // maybe this should be called in other thread, it causes bottleneck.
952         OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message);
953
954         *message = '\0';
955         OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy...");
956
957         l = recv(fd, message, 4096, 0);
958
959         OIC_LOG_V(INFO, TAG, "Received data : '%s'", message);
960         OIC_LOG_V(INFO, TAG, "Received len = %zd", l);
961
962         int status_code = CAGetHTTPStatusCode(message);
963
964         OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code);
965         if(status_code < 200 || status_code > 299)
966         {
967             OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %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 }