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