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