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