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