[IOT-1575] Initialize socket fd after closing session
[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 #include <sys/poll.h>
26 #include <stdio.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
31 #include <net/if.h>
32 #include <errno.h>
33
34 #ifndef WITH_ARDUINO
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <netdb.h>
38 #endif
39
40 #include "catcpinterface.h"
41 #include "caipnwmonitor.h"
42 #include <coap/pdu.h>
43 #include "caadapterutils.h"
44 #include "camutex.h"
45 #include "oic_malloc.h"
46
47 #ifdef __WITH_TLS__
48 #include "ca_adapter_net_ssl.h"
49 #endif
50
51 /**
52  * Logging tag for module name.
53  */
54 #define TAG "OIC_CA_TCP_SERVER"
55
56 /**
57  * Maximum CoAP over TCP header length
58  * to know the total data length.
59  */
60 #define COAP_MAX_HEADER_SIZE  6
61
62 /**
63  * TLS header size
64  */
65 #define TLS_HEADER_SIZE 5
66
67 /**
68  * Mutex to synchronize device object list.
69  */
70 static ca_mutex g_mutexObjectList = NULL;
71
72 /**
73  * Conditional mutex to synchronize.
74  */
75 static ca_cond g_condObjectList = NULL;
76
77 /**
78  * Maintains the callback to be notified when data received from remote device.
79  */
80 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
81
82 /**
83  * Error callback to update error in TCP.
84  */
85 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
86
87 /**
88  * Connected Callback to pass the connection information to RI.
89  */
90 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
91
92 static CAResult_t CATCPCreateMutex();
93 static void CATCPDestroyMutex();
94 static CAResult_t CATCPCreateCond();
95 static void CATCPDestroyCond();
96 static int CACreateAcceptSocket(int family, CASocket_t *sock);
97 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
98 static void CAFindReadyMessage();
99 static void CASelectReturned(fd_set *readFds);
100 static void CAReceiveMessage(int fd);
101 static void CAReceiveHandler(void *data);
102 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
103
104 #define CHECKFD(FD) \
105     if (FD > caglobals.tcp.maxfd) \
106         caglobals.tcp.maxfd = FD;
107
108 /**
109  * Read length amount of data from socket item->fd
110  * Can read less data length then requested
111  * Actual read length added to item->len variable
112  *
113  * @param[in/out] item - used socket, buffer and to update received message length
114  * @param[in]  length  - length of data required to read
115  * @param[in]  flags   - additional info about socket
116  * @return             - CA_STATUS_OK or appropriate error code
117  */
118 static CAResult_t CARecv(CATCPSessionInfo_t *item, size_t length, int flags)
119 {
120     if (NULL == item)
121     {
122         return CA_STATUS_INVALID_PARAM;
123     }
124
125     //skip read operation if requested zero length
126     if (0 == length)
127     {
128         return CA_STATUS_OK;
129     }
130
131     unsigned char *buffer = item->data + item->len;
132
133     int len = recv(item->fd, buffer, length, flags);
134
135     if (len < 0)
136     {
137         OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
138         return CA_RECEIVE_FAILED;
139     }
140     else if (0 == len)
141     {
142         OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
143         return CA_DESTINATION_DISCONNECTED;
144     }
145
146     OIC_LOG_V(DEBUG, TAG, "recv len = %d", len);
147     OIC_LOG_BUFFER(DEBUG, TAG, buffer, len);
148
149     item->len += len;
150
151     return CA_STATUS_OK;
152 }
153
154 static void CATCPDestroyMutex()
155 {
156     if (g_mutexObjectList)
157     {
158         ca_mutex_free(g_mutexObjectList);
159         g_mutexObjectList = NULL;
160     }
161 }
162
163 static CAResult_t CATCPCreateMutex()
164 {
165     if (!g_mutexObjectList)
166     {
167         g_mutexObjectList = ca_mutex_new();
168         if (!g_mutexObjectList)
169         {
170             OIC_LOG(ERROR, TAG, "Failed to created mutex!");
171             return CA_STATUS_FAILED;
172         }
173     }
174
175     return CA_STATUS_OK;
176 }
177
178 static void CATCPDestroyCond()
179 {
180     if (g_condObjectList)
181     {
182         ca_cond_free(g_condObjectList);
183         g_condObjectList = NULL;
184     }
185 }
186
187 static CAResult_t CATCPCreateCond()
188 {
189     if (!g_condObjectList)
190     {
191         g_condObjectList = ca_cond_new();
192         if (!g_condObjectList)
193         {
194             OIC_LOG(ERROR, TAG, "Failed to created cond!");
195             return CA_STATUS_FAILED;
196         }
197     }
198     return CA_STATUS_OK;
199 }
200
201 static void CAReceiveHandler(void *data)
202 {
203     (void)data;
204     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
205
206     while (!caglobals.tcp.terminate)
207     {
208         CAFindReadyMessage();
209     }
210
211     ca_mutex_lock(g_mutexObjectList);
212     ca_cond_signal(g_condObjectList);
213     ca_mutex_unlock(g_mutexObjectList);
214
215     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
216 }
217
218 static void CAFindReadyMessage()
219 {
220     fd_set readFds;
221     struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
222
223     FD_ZERO(&readFds);
224
225     if (-1 != caglobals.tcp.ipv4.fd)
226     {
227         FD_SET(caglobals.tcp.ipv4.fd, &readFds);
228     }
229     if (-1 != caglobals.tcp.ipv6.fd)
230     {
231         FD_SET(caglobals.tcp.ipv6.fd, &readFds);
232     }
233     if (-1 != caglobals.tcp.shutdownFds[0])
234     {
235         FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
236     }
237     if (-1 != caglobals.tcp.connectionFds[0])
238     {
239         FD_SET(caglobals.tcp.connectionFds[0], &readFds);
240     }
241
242     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
243     for (size_t i = 0; i < length; i++)
244     {
245         CATCPSessionInfo_t *svritem =
246                 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
247         if (svritem && 0 <= svritem->fd)
248         {
249             FD_SET(svritem->fd, &readFds);
250         }
251     }
252
253     int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
254
255     if (caglobals.tcp.terminate)
256     {
257         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
258         return;
259     }
260     if (0 >= ret)
261     {
262         if (0 > ret)
263         {
264             OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
265         }
266         return;
267     }
268
269     CASelectReturned(&readFds);
270 }
271
272 static void CASelectReturned(fd_set *readFds)
273 {
274     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
275
276     if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
277     {
278         CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
279         return;
280     }
281     else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
282     {
283         CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
284         return;
285     }
286     else if (-1 != caglobals.tcp.connectionFds[0] &&
287             FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
288     {
289         // new connection was created from remote device.
290         // exit the function to update read file descriptor.
291         char buf[MAX_ADDR_STR_SIZE_CA] = {0};
292         ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
293         if (-1 == len)
294         {
295             return;
296         }
297         OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
298         FD_CLR(caglobals.tcp.connectionFds[0], readFds);
299         return;
300     }
301     else
302     {
303         uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
304         for (size_t i = 0; i < length; i++)
305         {
306             CATCPSessionInfo_t *svritem =
307                     (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
308             if (svritem && svritem->fd >= 0)
309             {
310                 if (FD_ISSET(svritem->fd, readFds))
311                 {
312                     CAReceiveMessage(svritem->fd);
313                     if (-1 != svritem->fd)
314                     {
315                         FD_CLR(svritem->fd, readFds);
316                     }
317                 }
318             }
319         }
320     }
321 }
322
323 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
324 {
325     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
326
327     struct sockaddr_storage clientaddr;
328     socklen_t clientlen = sizeof (struct sockaddr_in);
329     if (flag & CA_IPV6)
330     {
331         clientlen = sizeof(struct sockaddr_in6);
332     }
333
334     int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
335     if (-1 != sockfd)
336     {
337         CATCPSessionInfo_t *svritem =
338                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
339         if (!svritem)
340         {
341             OIC_LOG(ERROR, TAG, "Out of memory");
342             close(sockfd);
343             return;
344         }
345
346         svritem->fd = sockfd;
347         svritem->sep.endpoint.flags = flag;
348         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
349         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
350                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
351
352         ca_mutex_lock(g_mutexObjectList);
353         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
354         if (!result)
355         {
356             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
357             close(sockfd);
358             OICFree(svritem);
359             ca_mutex_unlock(g_mutexObjectList);
360             return;
361         }
362         ca_mutex_unlock(g_mutexObjectList);
363
364         CHECKFD(sockfd);
365     }
366 }
367
368 #ifdef __WITH_TLS__
369 static bool CAIsTlsMessage(const unsigned char* data, size_t length)
370 {
371     if (NULL == data || 0 == length)
372     {
373         OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
374         return false;
375     }
376
377     unsigned char first_byte = data[0];
378
379     //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
380     //handshake = [16], application_data = [17] in HEX
381     const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
382     size_t i = 0;
383
384     for (i = 0; i < sizeof(tls_head_type); i++)
385     {
386         if(tls_head_type[i] == first_byte)
387         {
388             return true;
389         }
390     }
391
392     return false;
393 }
394 #endif
395
396 /**
397  * Clean socket state data
398  *
399  * @param[in/out] item - socket state data
400  */
401 static void CACleanData(CATCPSessionInfo_t *svritem)
402 {
403     if (svritem)
404     {
405         OICFree(svritem->data);
406         svritem->data = NULL;
407         svritem->len = 0;
408         svritem->totalLen = 0;
409         svritem->protocol = UNKNOWN;
410     }
411 }
412
413 /**
414  * Read message header from socket item->fd
415  *
416  * @param[in/out] item - used socket, buffer, current received message length and protocol
417  * @return             - CA_STATUS_OK or appropriate error code
418  */
419 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
420 {
421     CAResult_t res = CA_STATUS_OK;
422
423     if (NULL == svritem)
424     {
425         return CA_STATUS_INVALID_PARAM;
426     }
427
428     if (NULL == svritem->data)
429     {
430         // allocate memory for message header (CoAP header size because it is bigger)
431         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
432         if (NULL == svritem->data)
433         {
434             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
435             return CA_MEMORY_ALLOC_FAILED;
436         }
437     }
438
439     //read data (assume TLS header) from remote device.
440     //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
441     res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
442
443     //return if any error occurs
444     if (CA_STATUS_OK != res)
445     {
446         return res;
447     }
448
449     //if not enough data received - read them on next CAReceiveMessage() call
450     if (svritem->len < TLS_HEADER_SIZE)
451     {
452         OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
453         return CA_STATUS_OK;
454     }
455
456     //if enough data received - parse header
457 #ifdef __WITH_TLS__
458     if (CAIsTlsMessage(svritem->data, svritem->len))
459     {
460         svritem->protocol = TLS;
461
462         //[3][4] bytes in tls header are tls payload length
463         unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
464         OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
465
466         svritem->totalLen = message_length + TLS_HEADER_SIZE;
467     }
468     else
469 #endif
470     {
471         svritem->protocol = COAP;
472
473         //seems CoAP data received. read full coap header.
474         coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
475
476         size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
477
478         if (svritem->len < headerLen)
479         {
480             //read required bytes to have full CoAP header
481             //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
482             res = CARecv(svritem, headerLen - svritem->len, 0);
483
484             //return if any error occurs
485             if (CA_STATUS_OK != res)
486             {
487                 return res;
488             }
489
490             //if not enough data received - read them on next CAReceiveMessage() call
491             if (svritem->len < headerLen)
492             {
493                 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
494                 return CA_STATUS_OK;
495             }
496         }
497
498         //calculate CoAP message length
499         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
500     }
501
502     unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
503     if (NULL == buffer)
504     {
505         OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
506         return CA_MEMORY_ALLOC_FAILED;
507     }
508     svritem->data = buffer;
509
510     return CA_STATUS_OK;
511 }
512
513 /**
514  * Read message payload from socket item->fd
515
516  *
517  * @param[in/out] item - used socket, buffer and to update received message length
518  * @return             - CA_STATUS_OK or appropriate error code
519  */
520 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
521 {
522     if (NULL == svritem)
523     {
524         return CA_STATUS_INVALID_PARAM;
525     }
526
527     return CARecv(svritem, svritem->totalLen - svritem->len, 0);
528 }
529
530 /**
531  * Pass received data to app layer depending on protocol
532  *
533  * @param[in/out] item - used buffer, received message length and protocol
534  */
535 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
536 {
537     if (NULL == svritem)
538     {
539         return;
540     }
541
542     switch(svritem->protocol)
543     {
544         case COAP:
545         {
546             if (g_packetReceivedCallback)
547             {
548                 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
549             }
550         }
551         break;
552         case TLS:
553 #ifdef __WITH_TLS__
554         {
555             int ret = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
556
557             OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, ret);
558         }
559         break;
560 #endif
561         case UNKNOWN: /* pass through */
562         default:
563             OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
564         break;
565     }
566 }
567
568 static void CAReceiveMessage(int fd)
569 {
570     CAResult_t res = CA_STATUS_OK;
571
572     //get remote device information from file descriptor.
573     size_t index = 0;
574     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
575     if (!svritem)
576     {
577         OIC_LOG(ERROR, TAG, "there is no connection information in list");
578         return;
579     }
580
581     //totalLen filled only when header fully read and parsed
582     if (0 == svritem->totalLen)
583     {
584         res = CAReadHeader(svritem);
585     }
586     else
587     {
588         res = CAReadPayload(svritem);
589
590         //when successfully read all required data - pass them to upper layer.
591         if (CA_STATUS_OK == res && svritem->len == svritem->totalLen)
592         {
593             CAExecuteRequest(svritem);
594             CACleanData(svritem);
595         }
596     }
597
598     //disconnect session and clean-up data if any error occurs
599     if (res != CA_STATUS_OK)
600     {
601 #ifdef __WITH_TLS__
602         if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
603         {
604             OIC_LOG(ERROR, TAG, "Failed to close TLS session");
605         }
606 #endif
607         CASearchAndDeleteTCPSession(&(svritem->sep.endpoint));
608         return;
609     }
610 }
611
612 static void CAWakeUpForReadFdsUpdate(const char *host)
613 {
614     if (caglobals.tcp.connectionFds[1] != -1)
615     {
616         ssize_t len = 0;
617         do
618         {
619             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
620         } while ((len == -1) && (errno == EINTR));
621
622         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
623         {
624             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
625         }
626     }
627 }
628
629 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
630                                          struct sockaddr_storage *sockaddr)
631 {
632     struct addrinfo *addrs = NULL;
633     struct addrinfo hints = { .ai_family = family,
634                               .ai_protocol   = IPPROTO_TCP,
635                               .ai_socktype = SOCK_STREAM,
636                               .ai_flags = AI_NUMERICHOST };
637
638     int r = getaddrinfo(host, NULL, &hints, &addrs);
639     if (r)
640     {
641         if (EAI_SYSTEM == r)
642         {
643             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
644         }
645         else
646         {
647             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
648         }
649         freeaddrinfo(addrs);
650         return CA_STATUS_FAILED;
651     }
652     // assumption: in this case, getaddrinfo will only return one addrinfo
653     // or first is the one we want.
654     if (addrs[0].ai_family == AF_INET6)
655     {
656         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
657         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
658     }
659     else
660     {
661         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
662         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
663     }
664     freeaddrinfo(addrs);
665     return CA_STATUS_OK;
666 }
667
668 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
669 {
670     // #1. create tcp socket.
671     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
672     if (-1 == fd)
673     {
674         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
675         return -1;
676     }
677
678     // #2. convert address from string to binary.
679     struct sockaddr_storage sa = { .ss_family = family };
680     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
681                                             svritem->sep.endpoint.port, &sa);
682     if (CA_STATUS_OK != res)
683     {
684         close(fd);
685         return -1;
686     }
687
688     // #3. set socket length.
689     socklen_t socklen = 0;
690     if (sa.ss_family == AF_INET6)
691     {
692         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
693         if (!sock6->sin6_scope_id)
694         {
695             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
696         }
697         socklen = sizeof(struct sockaddr_in6);
698     }
699     else
700     {
701         socklen = sizeof(struct sockaddr_in);
702     }
703
704     // #4. connect to remote server device.
705     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
706     {
707         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
708         close(fd);
709         return -1;
710     }
711
712     OIC_LOG(DEBUG, TAG, "connect socket success");
713     CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
714     return fd;
715 }
716
717 static int CACreateAcceptSocket(int family, CASocket_t *sock)
718 {
719     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
720
721     if (sock->fd != -1)
722     {
723         OIC_LOG(DEBUG, TAG, "accept socket created already");
724         return sock->fd;
725     }
726
727     socklen_t socklen = 0;
728     struct sockaddr_storage server = { .ss_family = family };
729
730     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
731     if (fd < 0)
732     {
733         OIC_LOG(ERROR, TAG, "Failed to create socket");
734         goto exit;
735     }
736
737     if (family == AF_INET6)
738     {
739         // the socket is restricted to sending and receiving IPv6 packets only.
740         int on = 1;
741         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
742         {
743             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
744             goto exit;
745         }
746         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
747         socklen = sizeof (struct sockaddr_in6);
748     }
749     else
750     {
751         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
752         socklen = sizeof (struct sockaddr_in);
753     }
754
755     int reuse = 1;
756     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
757     {
758         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
759         goto exit;
760     }
761
762     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
763     {
764         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
765         goto exit;
766     }
767
768     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
769     {
770         OIC_LOG(ERROR, TAG, "listen() error");
771         goto exit;
772     }
773
774     if (!sock->port)  // return the assigned port
775     {
776         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
777         {
778             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
779             goto exit;
780         }
781         sock->port = ntohs(family == AF_INET6 ?
782                       ((struct sockaddr_in6 *)&server)->sin6_port :
783                       ((struct sockaddr_in *)&server)->sin_port);
784     }
785
786     return fd;
787
788 exit:
789     if (fd >= 0)
790     {
791         close(fd);
792     }
793     return -1;
794 }
795
796 static void CAInitializePipe(int *fds)
797 {
798     int ret = pipe(fds);
799     if (-1 != ret)
800     {
801         ret = fcntl(fds[0], F_GETFD);
802         if (-1 != ret)
803         {
804             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
805         }
806         if (-1 != ret)
807         {
808             ret = fcntl(fds[1], F_GETFD);
809         }
810         if (-1 != ret)
811         {
812             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
813         }
814         if (-1 == ret)
815         {
816             close(fds[1]);
817             close(fds[0]);
818
819             fds[0] = -1;
820             fds[1] = -1;
821
822             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
823         }
824     }
825 }
826
827 #define NEWSOCKET(FAMILY, NAME) \
828     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
829     if (caglobals.tcp.NAME.fd == -1) \
830     { \
831         caglobals.tcp.NAME.port = 0; \
832         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
833     } \
834     CHECKFD(caglobals.tcp.NAME.fd);
835
836 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
837 {
838     if (caglobals.tcp.started)
839     {
840         return CA_STATUS_OK;
841     }
842
843     if (!caglobals.tcp.ipv4tcpenabled)
844     {
845         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
846     }
847     if (!caglobals.tcp.ipv6tcpenabled)
848     {
849         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
850     }
851
852     CAResult_t res = CATCPCreateMutex();
853     if (CA_STATUS_OK == res)
854     {
855         res = CATCPCreateCond();
856     }
857     if (CA_STATUS_OK != res)
858     {
859         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
860         return res;
861     }
862
863     ca_mutex_lock(g_mutexObjectList);
864     if (!caglobals.tcp.svrlist)
865     {
866         caglobals.tcp.svrlist = u_arraylist_create();
867     }
868     ca_mutex_unlock(g_mutexObjectList);
869
870     if (caglobals.server)
871     {
872         NEWSOCKET(AF_INET, ipv4);
873         NEWSOCKET(AF_INET6, ipv6);
874         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
875                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
876         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
877                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
878     }
879
880     // create pipe for fast shutdown
881     CAInitializePipe(caglobals.tcp.shutdownFds);
882     CHECKFD(caglobals.tcp.shutdownFds[0]);
883     CHECKFD(caglobals.tcp.shutdownFds[1]);
884
885     // create pipe for connection event
886     CAInitializePipe(caglobals.tcp.connectionFds);
887     CHECKFD(caglobals.tcp.connectionFds[0]);
888     CHECKFD(caglobals.tcp.connectionFds[1]);
889
890     caglobals.tcp.terminate = false;
891     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
892     if (CA_STATUS_OK != res)
893     {
894         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
895         return res;
896     }
897     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
898
899     caglobals.tcp.started = true;
900     return CA_STATUS_OK;
901 }
902
903 void CATCPStopServer()
904 {
905     // mutex lock
906     ca_mutex_lock(g_mutexObjectList);
907
908     // set terminate flag
909     caglobals.tcp.terminate = true;
910
911     if (caglobals.tcp.shutdownFds[1] != -1)
912     {
913         close(caglobals.tcp.shutdownFds[1]);
914         // receive thread will stop immediately
915     }
916
917     if (caglobals.tcp.connectionFds[1] != -1)
918     {
919         close(caglobals.tcp.connectionFds[1]);
920     }
921
922     if (caglobals.tcp.started)
923     {
924         ca_cond_wait(g_condObjectList, g_mutexObjectList);
925     }
926     caglobals.tcp.started = false;
927
928     // mutex unlock
929     ca_mutex_unlock(g_mutexObjectList);
930
931     if (-1 != caglobals.tcp.ipv4.fd)
932     {
933         close(caglobals.tcp.ipv4.fd);
934         caglobals.tcp.ipv4.fd = -1;
935     }
936
937     if (-1 != caglobals.tcp.ipv6.fd)
938     {
939         close(caglobals.tcp.ipv6.fd);
940         caglobals.tcp.ipv6.fd = -1;
941     }
942
943     CATCPDisconnectAll();
944     CATCPDestroyMutex();
945     CATCPDestroyCond();
946 }
947
948 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
949 {
950     g_packetReceivedCallback = callback;
951 }
952
953 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
954 {
955     g_connectionCallback = connHandler;
956 }
957
958 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
959 {
960     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
961
962     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
963             ((unsigned char *)data)[0] >> 4);
964
965     coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
966     if (!pdu)
967     {
968         OIC_LOG(ERROR, TAG, "outpdu is null");
969         return 0;
970     }
971
972     int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
973     if (0 >= ret)
974     {
975         OIC_LOG(ERROR, TAG, "pdu parse failed");
976         coap_delete_pdu(pdu);
977         return 0;
978     }
979
980     size_t payloadLen = 0;
981     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
982     OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
983               headerSize, pdu->length);
984     if (pdu->length > headerSize)
985     {
986         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
987     }
988
989     OICFree(pdu);
990
991     return payloadLen;
992 }
993
994 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
995                         size_t dlen, const char *fam)
996 {
997     // #1. get TCP Server object from list
998     size_t index = 0;
999     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1000     if (!svritem)
1001     {
1002         // if there is no connection info, connect to TCP Server
1003         svritem = CAConnectTCPSession(endpoint);
1004         if (!svritem)
1005         {
1006             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
1007             return -1;
1008         }
1009     }
1010
1011     // #2. check connection state
1012     if (svritem->fd < 0)
1013     {
1014         // if file descriptor value is wrong, remove TCP Server info from list
1015         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
1016         return -1;
1017     }
1018
1019     // #3. send data to TCP Server
1020     ssize_t remainLen = dlen;
1021     do
1022     {
1023         ssize_t len = send(svritem->fd, data, remainLen, 0);
1024         if (-1 == len)
1025         {
1026             if (EWOULDBLOCK != errno)
1027             {
1028                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1029                 return len;
1030             }
1031             continue;
1032         }
1033         data += len;
1034         remainLen -= len;
1035     } while (remainLen > 0);
1036
1037 #ifndef TB_LOG
1038     (void)fam;
1039 #endif
1040     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1041     return dlen;
1042 }
1043
1044 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1045 {
1046     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1047     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1048
1049     if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1050     {
1051         return sendData(endpoint, data, datalen, "ipv6");
1052     }
1053     if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1054     {
1055         return sendData(endpoint, data, datalen, "ipv4");
1056     }
1057     return -1;
1058 }
1059
1060 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1061 {
1062     VERIFY_NON_NULL(info, TAG, "info is NULL");
1063     VERIFY_NON_NULL(size, TAG, "size is NULL");
1064
1065     return CA_NOT_SUPPORTED;
1066 }
1067
1068 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
1069 {
1070     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1071
1072     // #1. create TCP server object
1073     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1074     if (!svritem)
1075     {
1076         OIC_LOG(ERROR, TAG, "Out of memory");
1077         return NULL;
1078     }
1079     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1080     svritem->sep.endpoint.adapter = endpoint->adapter;
1081     svritem->sep.endpoint.port = endpoint->port;
1082     svritem->sep.endpoint.flags = endpoint->flags;
1083     svritem->sep.endpoint.ifindex = endpoint->ifindex;
1084
1085     // #2. create the socket and connect to TCP server
1086     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1087     int fd = CATCPCreateSocket(family, svritem);
1088     if (-1 == fd)
1089     {
1090         OICFree(svritem);
1091         return NULL;
1092     }
1093
1094     // #3. add TCP connection info to list
1095     svritem->fd = fd;
1096     ca_mutex_lock(g_mutexObjectList);
1097     if (caglobals.tcp.svrlist)
1098     {
1099         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1100         if (!res)
1101         {
1102             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1103             close(svritem->fd);
1104             OICFree(svritem);
1105             ca_mutex_unlock(g_mutexObjectList);
1106             return NULL;
1107         }
1108     }
1109     ca_mutex_unlock(g_mutexObjectList);
1110
1111     CHECKFD(fd);
1112
1113     // pass the connection information to CA Common Layer.
1114     if (g_connectionCallback)
1115     {
1116         g_connectionCallback(&(svritem->sep.endpoint), true);
1117     }
1118
1119     return svritem;
1120 }
1121
1122 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
1123 {
1124     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
1125
1126     // close the socket and remove TCP connection info in list.
1127     if (svritem->fd >= 0)
1128     {
1129         shutdown(svritem->fd, SHUT_RDWR);
1130         close(svritem->fd);
1131         svritem->fd = -1;
1132     }
1133     u_arraylist_remove(caglobals.tcp.svrlist, index);
1134     OICFree(svritem->data);
1135     svritem->data = NULL;
1136
1137     // pass the connection information to CA Common Layer.
1138     if (g_connectionCallback)
1139     {
1140         g_connectionCallback(&(svritem->sep.endpoint), false);
1141     }
1142
1143     OICFree(svritem);
1144     svritem = NULL;
1145     return CA_STATUS_OK;
1146 }
1147
1148 void CATCPDisconnectAll()
1149 {
1150     ca_mutex_lock(g_mutexObjectList);
1151     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1152     CATCPSessionInfo_t *svritem = NULL;
1153     for (size_t i = 0; i < length; i++)
1154     {
1155         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1156         if (svritem && svritem->fd >= 0)
1157         {
1158             shutdown(svritem->fd, SHUT_RDWR);
1159             close(svritem->fd);
1160             OICFree(svritem->data);
1161             svritem->data = NULL;
1162
1163             // pass the connection information to CA Common Layer.
1164             if (g_connectionCallback)
1165             {
1166                 g_connectionCallback(&(svritem->sep.endpoint), false);
1167             }
1168         }
1169     }
1170     u_arraylist_destroy(caglobals.tcp.svrlist);
1171     caglobals.tcp.svrlist = NULL;
1172     ca_mutex_unlock(g_mutexObjectList);
1173
1174 #ifdef __WITH_TLS__
1175     CAcloseSslConnectionAll();
1176 #endif
1177
1178 }
1179
1180 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1181 {
1182     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1183     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1184
1185     // get connection info from list
1186     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1187     for (size_t i = 0; i < length; i++)
1188     {
1189         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1190                 caglobals.tcp.svrlist, i);
1191         if (!svritem)
1192         {
1193             continue;
1194         }
1195
1196         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1197                      sizeof(svritem->sep.endpoint.addr))
1198                 && (svritem->sep.endpoint.port == endpoint->port)
1199                 && (svritem->sep.endpoint.flags & endpoint->flags))
1200         {
1201             *index = i;
1202             return svritem;
1203         }
1204     }
1205
1206     return NULL;
1207 }
1208
1209 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1210 {
1211     ca_mutex_lock(g_mutexObjectList);
1212
1213     // check from the last item.
1214     CATCPSessionInfo_t *svritem = NULL;
1215     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1216     for (size_t i = 0; i < length; i++)
1217     {
1218         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1219
1220         if (svritem && svritem->fd == fd)
1221         {
1222             *index = i;
1223             ca_mutex_unlock(g_mutexObjectList);
1224             return svritem;
1225         }
1226     }
1227
1228     ca_mutex_unlock(g_mutexObjectList);
1229
1230     return NULL;
1231 }
1232
1233 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1234 {
1235     ca_mutex_lock(g_mutexObjectList);
1236
1237     CAResult_t result = CA_STATUS_OK;
1238     size_t index = 0;
1239     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1240     if (svritem)
1241     {
1242         result = CADisconnectTCPSession(svritem, index);
1243         if (CA_STATUS_OK != result)
1244         {
1245             OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1246         }
1247     }
1248
1249     ca_mutex_unlock(g_mutexObjectList);
1250     return result;
1251 }
1252
1253 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1254 {
1255     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1256
1257     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1258             ((unsigned char *)recvBuffer)[0] >> 4);
1259     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1260                                                         transport);
1261     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1262
1263     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1264     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1265     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1266
1267     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1268     return headerLen + optPaylaodLen;
1269 }
1270
1271 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1272 {
1273     g_tcpErrorHandler = errorHandleCallback;
1274 }