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