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