[IOT-1346] Enable network status monitoring for tcp network
[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                     FD_CLR(svritem->fd, readFds);
314                 }
315             }
316         }
317     }
318 }
319
320 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
321 {
322     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
323
324     struct sockaddr_storage clientaddr;
325     socklen_t clientlen = sizeof (struct sockaddr_in);
326     if (flag & CA_IPV6)
327     {
328         clientlen = sizeof(struct sockaddr_in6);
329     }
330
331     int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
332     if (-1 != sockfd)
333     {
334         CATCPSessionInfo_t *svritem =
335                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
336         if (!svritem)
337         {
338             OIC_LOG(ERROR, TAG, "Out of memory");
339             close(sockfd);
340             return;
341         }
342
343         svritem->fd = sockfd;
344         svritem->sep.endpoint.flags = flag;
345         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
346         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
347                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
348
349         ca_mutex_lock(g_mutexObjectList);
350         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
351         if (!result)
352         {
353             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
354             close(sockfd);
355             OICFree(svritem);
356             ca_mutex_unlock(g_mutexObjectList);
357             return;
358         }
359         ca_mutex_unlock(g_mutexObjectList);
360
361         CHECKFD(sockfd);
362     }
363 }
364
365 #ifdef __WITH_TLS__
366 static bool CAIsTlsMessage(const unsigned char* data, size_t length)
367 {
368     if (NULL == data || 0 == length)
369     {
370         OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
371         return false;
372     }
373
374     unsigned char first_byte = data[0];
375
376     //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
377     //handshake = [16], application_data = [17] in HEX
378     const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
379     size_t i = 0;
380
381     for (i = 0; i < sizeof(tls_head_type); i++)
382     {
383         if(tls_head_type[i] == first_byte)
384         {
385             return true;
386         }
387     }
388
389     return false;
390 }
391 #endif
392
393 /**
394  * Clean socket state data
395  *
396  * @param[in/out] item - socket state data
397  */
398 static void CACleanData(CATCPSessionInfo_t *svritem)
399 {
400     if (svritem)
401     {
402         OICFree(svritem->data);
403         svritem->data = NULL;
404         svritem->len = 0;
405         svritem->totalLen = 0;
406         svritem->protocol = UNKNOWN;
407     }
408 }
409
410 /**
411  * Read message header from socket item->fd
412  *
413  * @param[in/out] item - used socket, buffer, current received message length and protocol
414  * @return             - CA_STATUS_OK or appropriate error code
415  */
416 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
417 {
418     CAResult_t res = CA_STATUS_OK;
419
420     if (NULL == svritem)
421     {
422         return CA_STATUS_INVALID_PARAM;
423     }
424
425     if (NULL == svritem->data)
426     {
427         // allocate memory for message header (CoAP header size because it is bigger)
428         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
429         if (NULL == svritem->data)
430         {
431             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
432             return CA_MEMORY_ALLOC_FAILED;
433         }
434     }
435
436     //read data (assume TLS header) from remote device.
437     //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
438     res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
439
440     //return if any error occurs
441     if (CA_STATUS_OK != res)
442     {
443         return res;
444     }
445
446     //if not enough data received - read them on next CAReceiveMessage() call
447     if (svritem->len < TLS_HEADER_SIZE)
448     {
449         OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
450         return CA_STATUS_OK;
451     }
452
453     //if enough data received - parse header
454 #ifdef __WITH_TLS__
455     if (CAIsTlsMessage(svritem->data, svritem->len))
456     {
457         svritem->protocol = TLS;
458
459         //[3][4] bytes in tls header are tls payload length
460         unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
461         OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
462
463         svritem->totalLen = message_length + TLS_HEADER_SIZE;
464     }
465     else
466 #endif
467     {
468         svritem->protocol = COAP;
469
470         //seems CoAP data received. read full coap header.
471         coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
472
473         size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
474
475         if (svritem->len < headerLen)
476         {
477             //read required bytes to have full CoAP header
478             //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
479             res = CARecv(svritem, headerLen - svritem->len, 0);
480
481             //return if any error occurs
482             if (CA_STATUS_OK != res)
483             {
484                 return res;
485             }
486
487             //if not enough data received - read them on next CAReceiveMessage() call
488             if (svritem->len < headerLen)
489             {
490                 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
491                 return CA_STATUS_OK;
492             }
493         }
494
495         //calculate CoAP message length
496         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
497     }
498
499     unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
500     if (NULL == buffer)
501     {
502         OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
503         return CA_MEMORY_ALLOC_FAILED;
504     }
505     svritem->data = buffer;
506
507     return CA_STATUS_OK;
508 }
509
510 /**
511  * Read message payload from socket item->fd
512
513  *
514  * @param[in/out] item - used socket, buffer and to update received message length
515  * @return             - CA_STATUS_OK or appropriate error code
516  */
517 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
518 {
519     if (NULL == svritem)
520     {
521         return CA_STATUS_INVALID_PARAM;
522     }
523
524     return CARecv(svritem, svritem->totalLen - svritem->len, 0);
525 }
526
527 /**
528  * Pass received data to app layer depending on protocol
529  *
530  * @param[in/out] item - used buffer, received message length and protocol
531  */
532 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
533 {
534     if (NULL == svritem)
535     {
536         return;
537     }
538
539     switch(svritem->protocol)
540     {
541         case COAP:
542         {
543             if (g_packetReceivedCallback)
544             {
545                 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
546             }
547         }
548         break;
549         case TLS:
550 #ifdef __WITH_TLS__
551         {
552             int ret = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
553
554             OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, ret);
555         }
556         break;
557 #endif
558         case UNKNOWN: /* pass through */
559         default:
560             OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
561         break;
562     }
563 }
564
565 static void CAReceiveMessage(int fd)
566 {
567     CAResult_t res = CA_STATUS_OK;
568
569     //get remote device information from file descriptor.
570     size_t index = 0;
571     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
572     if (!svritem)
573     {
574         OIC_LOG(ERROR, TAG, "there is no connection information in list");
575         return;
576     }
577
578     //totalLen filled only when header fully read and parsed
579     if (0 == svritem->totalLen)
580     {
581         res = CAReadHeader(svritem);
582     }
583     else
584     {
585         res = CAReadPayload(svritem);
586
587         //when successfully read all required data - pass them to upper layer.
588         if (CA_STATUS_OK == res && svritem->len == svritem->totalLen)
589         {
590             CAExecuteRequest(svritem);
591             CACleanData(svritem);
592         }
593     }
594
595     //disconnect session and clean-up data if any error occurs
596     if (res != CA_STATUS_OK)
597     {
598         CADisconnectTCPSession(svritem, index);
599         CACleanData(svritem);
600     }
601 }
602
603 static void CAWakeUpForReadFdsUpdate(const char *host)
604 {
605     if (caglobals.tcp.connectionFds[1] != -1)
606     {
607         ssize_t len = 0;
608         do
609         {
610             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
611         } while ((len == -1) && (errno == EINTR));
612
613         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
614         {
615             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
616         }
617     }
618 }
619
620 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
621                                          struct sockaddr_storage *sockaddr)
622 {
623     struct addrinfo *addrs = NULL;
624     struct addrinfo hints = { .ai_family = family,
625                               .ai_protocol   = IPPROTO_TCP,
626                               .ai_socktype = SOCK_STREAM,
627                               .ai_flags = AI_NUMERICHOST };
628
629     int r = getaddrinfo(host, NULL, &hints, &addrs);
630     if (r)
631     {
632         if (EAI_SYSTEM == r)
633         {
634             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
635         }
636         else
637         {
638             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
639         }
640         freeaddrinfo(addrs);
641         return CA_STATUS_FAILED;
642     }
643     // assumption: in this case, getaddrinfo will only return one addrinfo
644     // or first is the one we want.
645     if (addrs[0].ai_family == AF_INET6)
646     {
647         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
648         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
649     }
650     else
651     {
652         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
653         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
654     }
655     freeaddrinfo(addrs);
656     return CA_STATUS_OK;
657 }
658
659 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
660 {
661     // #1. create tcp socket.
662     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
663     if (-1 == fd)
664     {
665         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
666         return -1;
667     }
668
669     // #2. convert address from string to binary.
670     struct sockaddr_storage sa = { .ss_family = family };
671     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
672                                             svritem->sep.endpoint.port, &sa);
673     if (CA_STATUS_OK != res)
674     {
675         close(fd);
676         return -1;
677     }
678
679     // #3. set socket length.
680     socklen_t socklen = 0;
681     if (sa.ss_family == AF_INET6)
682     {
683         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
684         if (!sock6->sin6_scope_id)
685         {
686             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
687         }
688         socklen = sizeof(struct sockaddr_in6);
689     }
690     else
691     {
692         socklen = sizeof(struct sockaddr_in);
693     }
694
695     // #4. connect to remote server device.
696     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
697     {
698         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
699         close(fd);
700         return -1;
701     }
702
703     OIC_LOG(DEBUG, TAG, "connect socket success");
704     CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
705     return fd;
706 }
707
708 static int CACreateAcceptSocket(int family, CASocket_t *sock)
709 {
710     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
711
712     if (sock->fd != -1)
713     {
714         OIC_LOG(DEBUG, TAG, "accept socket created already");
715         return sock->fd;
716     }
717
718     socklen_t socklen = 0;
719     struct sockaddr_storage server = { .ss_family = family };
720
721     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
722     if (fd < 0)
723     {
724         OIC_LOG(ERROR, TAG, "Failed to create socket");
725         goto exit;
726     }
727
728     if (family == AF_INET6)
729     {
730         // the socket is restricted to sending and receiving IPv6 packets only.
731         int on = 1;
732         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
733         {
734             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
735             goto exit;
736         }
737         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
738         socklen = sizeof (struct sockaddr_in6);
739     }
740     else
741     {
742         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
743         socklen = sizeof (struct sockaddr_in);
744     }
745
746     int reuse = 1;
747     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
748     {
749         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
750         goto exit;
751     }
752
753     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
754     {
755         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
756         goto exit;
757     }
758
759     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
760     {
761         OIC_LOG(ERROR, TAG, "listen() error");
762         goto exit;
763     }
764
765     if (!sock->port)  // return the assigned port
766     {
767         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
768         {
769             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
770             goto exit;
771         }
772         sock->port = ntohs(family == AF_INET6 ?
773                       ((struct sockaddr_in6 *)&server)->sin6_port :
774                       ((struct sockaddr_in *)&server)->sin_port);
775     }
776
777     return fd;
778
779 exit:
780     if (fd >= 0)
781     {
782         close(fd);
783     }
784     return -1;
785 }
786
787 static void CAInitializePipe(int *fds)
788 {
789     int ret = pipe(fds);
790     if (-1 != ret)
791     {
792         ret = fcntl(fds[0], F_GETFD);
793         if (-1 != ret)
794         {
795             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
796         }
797         if (-1 != ret)
798         {
799             ret = fcntl(fds[1], F_GETFD);
800         }
801         if (-1 != ret)
802         {
803             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
804         }
805         if (-1 == ret)
806         {
807             close(fds[1]);
808             close(fds[0]);
809
810             fds[0] = -1;
811             fds[1] = -1;
812
813             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
814         }
815     }
816 }
817
818 #define NEWSOCKET(FAMILY, NAME) \
819     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
820     if (caglobals.tcp.NAME.fd == -1) \
821     { \
822         caglobals.tcp.NAME.port = 0; \
823         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
824     } \
825     CHECKFD(caglobals.tcp.NAME.fd);
826
827 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
828 {
829     if (caglobals.tcp.started)
830     {
831         return CA_STATUS_OK;
832     }
833
834     if (!caglobals.tcp.ipv4tcpenabled)
835     {
836         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
837     }
838     if (!caglobals.tcp.ipv6tcpenabled)
839     {
840         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
841     }
842
843     CAResult_t res = CATCPCreateMutex();
844     if (CA_STATUS_OK == res)
845     {
846         res = CATCPCreateCond();
847     }
848     if (CA_STATUS_OK != res)
849     {
850         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
851         return res;
852     }
853
854     ca_mutex_lock(g_mutexObjectList);
855     if (!caglobals.tcp.svrlist)
856     {
857         caglobals.tcp.svrlist = u_arraylist_create();
858     }
859     ca_mutex_unlock(g_mutexObjectList);
860
861     if (caglobals.server)
862     {
863         NEWSOCKET(AF_INET, ipv4);
864         NEWSOCKET(AF_INET6, ipv6);
865         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
866                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
867         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
868                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
869     }
870
871     // create pipe for fast shutdown
872     CAInitializePipe(caglobals.tcp.shutdownFds);
873     CHECKFD(caglobals.tcp.shutdownFds[0]);
874     CHECKFD(caglobals.tcp.shutdownFds[1]);
875
876     // create pipe for connection event
877     CAInitializePipe(caglobals.tcp.connectionFds);
878     CHECKFD(caglobals.tcp.connectionFds[0]);
879     CHECKFD(caglobals.tcp.connectionFds[1]);
880
881     caglobals.tcp.terminate = false;
882     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
883     if (CA_STATUS_OK != res)
884     {
885         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
886         return res;
887     }
888     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
889
890     caglobals.tcp.started = true;
891     return CA_STATUS_OK;
892 }
893
894 void CATCPStopServer()
895 {
896     // mutex lock
897     ca_mutex_lock(g_mutexObjectList);
898
899     // set terminate flag
900     caglobals.tcp.terminate = true;
901
902     if (caglobals.tcp.shutdownFds[1] != -1)
903     {
904         close(caglobals.tcp.shutdownFds[1]);
905         // receive thread will stop immediately
906     }
907
908     if (caglobals.tcp.connectionFds[1] != -1)
909     {
910         close(caglobals.tcp.connectionFds[1]);
911     }
912
913     if (caglobals.tcp.started)
914     {
915         ca_cond_wait(g_condObjectList, g_mutexObjectList);
916     }
917     caglobals.tcp.started = false;
918
919     // mutex unlock
920     ca_mutex_unlock(g_mutexObjectList);
921
922     if (-1 != caglobals.tcp.ipv4.fd)
923     {
924         close(caglobals.tcp.ipv4.fd);
925         caglobals.tcp.ipv4.fd = -1;
926     }
927
928     if (-1 != caglobals.tcp.ipv6.fd)
929     {
930         close(caglobals.tcp.ipv6.fd);
931         caglobals.tcp.ipv6.fd = -1;
932     }
933
934     CATCPDisconnectAll();
935     CATCPDestroyMutex();
936     CATCPDestroyCond();
937 }
938
939 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
940 {
941     g_packetReceivedCallback = callback;
942 }
943
944 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
945 {
946     g_connectionCallback = connHandler;
947 }
948
949 static size_t CACheckPayloadLength(const void *data, size_t dlen)
950 {
951     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
952
953     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
954             ((unsigned char *)data)[0] >> 4);
955
956     coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
957     if (!pdu)
958     {
959         OIC_LOG(ERROR, TAG, "outpdu is null");
960         return 0;
961     }
962
963     int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
964     if (0 >= ret)
965     {
966         OIC_LOG(ERROR, TAG, "pdu parse failed");
967         coap_delete_pdu(pdu);
968         return 0;
969     }
970
971     size_t payloadLen = 0;
972     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
973     OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
974               headerSize, pdu->length);
975     if (pdu->length > headerSize)
976     {
977         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
978     }
979
980     OICFree(pdu);
981
982     return payloadLen;
983 }
984
985 static void sendData(const CAEndpoint_t *endpoint, const void *data,
986                      size_t dlen, const char *fam)
987 {
988     // #1. get TCP Server object from list
989     size_t index = 0;
990     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
991     if (!svritem)
992     {
993         // if there is no connection info, connect to TCP Server
994         svritem = CAConnectTCPSession(endpoint);
995         if (!svritem)
996         {
997             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
998             if (g_tcpErrorHandler)
999             {
1000                 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1001             }
1002             return;
1003         }
1004     }
1005
1006     // #2. check payload length
1007 #ifdef __WITH_TLS__
1008     if (false == CAIsTlsMessage(data, dlen))
1009 #endif
1010     {
1011         size_t payloadLen = CACheckPayloadLength(data, dlen);
1012         // if payload length is zero, disconnect from TCP server
1013         if (!payloadLen)
1014         {
1015             OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
1016             CADisconnectTCPSession(svritem, index);
1017             return;
1018         }
1019     }
1020
1021     // #3. check connection state
1022     if (svritem->fd < 0)
1023     {
1024         // if file descriptor value is wrong, remove TCP Server info from list
1025         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
1026         CADisconnectTCPSession(svritem, index);
1027         if (g_tcpErrorHandler)
1028         {
1029             g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1030         }
1031         return;
1032     }
1033
1034     // #4. send data to TCP Server
1035     ssize_t remainLen = dlen;
1036     do
1037     {
1038         ssize_t len = send(svritem->fd, data, remainLen, 0);
1039         if (-1 == len)
1040         {
1041             if (EWOULDBLOCK != errno)
1042             {
1043                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1044                 if (g_tcpErrorHandler)
1045                 {
1046                     g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1047                 }
1048                 return;
1049             }
1050             continue;
1051         }
1052         data += len;
1053         remainLen -= len;
1054     } while (remainLen > 0);
1055
1056 #ifndef TB_LOG
1057     (void)fam;
1058 #endif
1059     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1060 }
1061
1062 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1063                    bool isMulticast)
1064 {
1065     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1066     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1067
1068     if (!isMulticast)
1069     {
1070         if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1071         {
1072             sendData(endpoint, data, datalen, "ipv6");
1073         }
1074         if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1075         {
1076             sendData(endpoint, data, datalen, "ipv4");
1077         }
1078     }
1079 }
1080
1081 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1082 {
1083     VERIFY_NON_NULL(info, TAG, "info is NULL");
1084     VERIFY_NON_NULL(size, TAG, "size is NULL");
1085
1086     return CA_NOT_SUPPORTED;
1087 }
1088
1089 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
1090 {
1091     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1092
1093     // #1. create TCP server object
1094     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1095     if (!svritem)
1096     {
1097         OIC_LOG(ERROR, TAG, "Out of memory");
1098         return NULL;
1099     }
1100     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1101     svritem->sep.endpoint.adapter = endpoint->adapter;
1102     svritem->sep.endpoint.port = endpoint->port;
1103     svritem->sep.endpoint.flags = endpoint->flags;
1104     svritem->sep.endpoint.ifindex = endpoint->ifindex;
1105
1106     // #2. create the socket and connect to TCP server
1107     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1108     int fd = CATCPCreateSocket(family, svritem);
1109     if (-1 == fd)
1110     {
1111         OICFree(svritem);
1112         return NULL;
1113     }
1114
1115     // #3. add TCP connection info to list
1116     svritem->fd = fd;
1117     ca_mutex_lock(g_mutexObjectList);
1118     if (caglobals.tcp.svrlist)
1119     {
1120         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1121         if (!res)
1122         {
1123             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1124             close(svritem->fd);
1125             OICFree(svritem);
1126             ca_mutex_unlock(g_mutexObjectList);
1127             return NULL;
1128         }
1129     }
1130     ca_mutex_unlock(g_mutexObjectList);
1131
1132     CHECKFD(fd);
1133
1134     // pass the connection information to CA Common Layer.
1135     if (g_connectionCallback)
1136     {
1137         g_connectionCallback(&(svritem->sep.endpoint), true);
1138     }
1139
1140     return svritem;
1141 }
1142
1143 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
1144 {
1145     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
1146
1147     ca_mutex_lock(g_mutexObjectList);
1148
1149 #ifdef __WITH_TLS__
1150     if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
1151     {
1152         OIC_LOG(ERROR, TAG, "Failed to close TLS session");
1153     }
1154 #endif
1155
1156     // close the socket and remove TCP connection info in list
1157     if (svritem->fd >= 0)
1158     {
1159         close(svritem->fd);
1160     }
1161     u_arraylist_remove(caglobals.tcp.svrlist, index);
1162     OICFree(svritem->data);
1163     svritem->data = NULL;
1164
1165     // pass the connection information to CA Common Layer.
1166     if (g_connectionCallback)
1167     {
1168         g_connectionCallback(&(svritem->sep.endpoint), false);
1169     }
1170
1171     OICFree(svritem);
1172     ca_mutex_unlock(g_mutexObjectList);
1173
1174     return CA_STATUS_OK;
1175 }
1176
1177 void CATCPDisconnectAll()
1178 {
1179     ca_mutex_lock(g_mutexObjectList);
1180     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1181
1182     CATCPSessionInfo_t *svritem = NULL;
1183     for (size_t i = 0; i < length; i++)
1184     {
1185         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1186         if (svritem && svritem->fd >= 0)
1187         {
1188 #ifdef __WITH_TLS__
1189             if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
1190             {
1191                 OIC_LOG(ERROR, TAG, "Failed to close TLS session");
1192             }
1193 #endif
1194             shutdown(svritem->fd, SHUT_RDWR);
1195             close(svritem->fd);
1196             OICFree(svritem->data);
1197             svritem->data = NULL;
1198
1199             // pass the connection information to CA Common Layer.
1200             if (g_connectionCallback)
1201             {
1202                 g_connectionCallback(&(svritem->sep.endpoint), false);
1203             }
1204         }
1205     }
1206     u_arraylist_destroy(caglobals.tcp.svrlist);
1207     caglobals.tcp.svrlist = NULL;
1208     ca_mutex_unlock(g_mutexObjectList);
1209 }
1210
1211 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1212 {
1213     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1214     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1215
1216     // get connection info from list
1217     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1218     for (size_t i = 0; i < length; i++)
1219     {
1220         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1221                 caglobals.tcp.svrlist, i);
1222         if (!svritem)
1223         {
1224             continue;
1225         }
1226
1227         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1228                      sizeof(svritem->sep.endpoint.addr))
1229                 && (svritem->sep.endpoint.port == endpoint->port)
1230                 && (svritem->sep.endpoint.flags & endpoint->flags))
1231         {
1232             *index = i;
1233             return svritem;
1234         }
1235     }
1236
1237     return NULL;
1238 }
1239
1240 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1241 {
1242     ca_mutex_lock(g_mutexObjectList);
1243
1244     // check from the last item.
1245     CATCPSessionInfo_t *svritem = NULL;
1246     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1247     for (size_t i = 0; i < length; i++)
1248     {
1249         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1250
1251         if (svritem && svritem->fd == fd)
1252         {
1253             *index = i;
1254             ca_mutex_unlock(g_mutexObjectList);
1255             return svritem;
1256         }
1257     }
1258
1259     ca_mutex_unlock(g_mutexObjectList);
1260
1261     return NULL;
1262 }
1263
1264 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1265 {
1266     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1267
1268     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1269             ((unsigned char *)recvBuffer)[0] >> 4);
1270     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1271                                                         transport);
1272     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1273
1274     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1275     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1276     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1277
1278     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1279     return headerLen + optPaylaodLen;
1280 }
1281
1282 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1283 {
1284     g_tcpErrorHandler = errorHandleCallback;
1285 }