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