Removed the duplicated code in catcpserver.c
[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 "pdu.h"
42 #include "caadapterutils.h"
43 #include "camutex.h"
44 #include "oic_malloc.h"
45
46 #ifdef __WITH_TLS__
47 #include "ca_adapter_net_tls.h"
48 #endif
49
50 /**
51  * Logging tag for module name.
52  */
53 #define TAG "OIC_CA_TCP_SERVER"
54
55 /**
56  * Maximum CoAP over TCP header length
57  * to know the total data length.
58  */
59 #define COAP_MAX_HEADER_SIZE  6
60
61 /**
62  * TLS header size
63  */
64 #define TLS_HEADER_SIZE 5
65
66 /**
67  * Mutex to synchronize device object list.
68  */
69 static ca_mutex g_mutexObjectList = NULL;
70
71 /**
72  * Conditional mutex to synchronize.
73  */
74 static ca_cond g_condObjectList = NULL;
75
76 /**
77  * Maintains the callback to be notified when data received from remote device.
78  */
79 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
80
81 /**
82  * Error callback to update error in TCP.
83  */
84 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
85
86 /**
87  * Connected Callback to pass the connection information to RI.
88  */
89 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
90
91 static CAResult_t CATCPCreateMutex();
92 static void CATCPDestroyMutex();
93 static CAResult_t CATCPCreateCond();
94 static void CATCPDestroyCond();
95 static int CACreateAcceptSocket(int family, CASocket_t *sock);
96 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
97 static void CAFindReadyMessage();
98 static void CASelectReturned(fd_set *readFds);
99 static void CAReceiveMessage(int fd);
100 static void CAReceiveHandler(void *data);
101 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
102
103 #define CHECKFD(FD) \
104     if (FD > caglobals.tcp.maxfd) \
105         caglobals.tcp.maxfd = FD;
106
107 #define REALLOC(buffer, length) \
108 { \
109     unsigned char *tmpBuf = OICRealloc(buffer, length); \
110     if (!tmpBuf) \
111     { \
112         OIC_LOG(ERROR, TAG, "out of memory"); \
113         goto error; \
114     } \
115     buffer = tmpBuf; \
116 }
117
118 /**
119  * Read length amount of data from socket fd
120  * Made a few recv calls if required
121  *
122  * @param[in]  fd     - socket
123  * @param[out] item   - used to update received message length
124  * @param[out] data   - buffer to store data
125  * @param[in]  length - length of data required to read
126  * @param[in]  flags  - additional info about socket
127  */
128 #define RECV(fd, item, data, length, flags) \
129 { \
130     int remain_len = length; \
131     int len = 0; \
132     while (remain_len > 0) \
133     { \
134         len = recv(fd, data + item->len, remain_len, flags); \
135         OIC_LOG_V(DEBUG, TAG, "recv len = %d", len); \
136         OIC_LOG_BUFFER(DEBUG, TAG, data + item->len, len); \
137         if (2 == len && 0 == data[item->len] && 0 == data[item->len + 1]) \
138         { \
139             OIC_LOG(DEBUG, TAG, "received RESET message. Skip it"); \
140             continue; \
141         } \
142         if (len < 0) \
143         { \
144             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno)); \
145             goto error; \
146         } \
147         else if (0 == len) \
148         { \
149             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection"); \
150             goto error; \
151         } \
152         item->len += len; \
153         remain_len -= len; \
154     } \
155 }
156
157 static void CATCPDestroyMutex()
158 {
159     if (g_mutexObjectList)
160     {
161         ca_mutex_free(g_mutexObjectList);
162         g_mutexObjectList = NULL;
163     }
164 }
165
166 static CAResult_t CATCPCreateMutex()
167 {
168     if (!g_mutexObjectList)
169     {
170         g_mutexObjectList = ca_mutex_new();
171         if (!g_mutexObjectList)
172         {
173             OIC_LOG(ERROR, TAG, "Failed to created mutex!");
174             return CA_STATUS_FAILED;
175         }
176     }
177
178     return CA_STATUS_OK;
179 }
180
181 static void CATCPDestroyCond()
182 {
183     if (g_condObjectList)
184     {
185         ca_cond_free(g_condObjectList);
186         g_condObjectList = NULL;
187     }
188 }
189
190 static CAResult_t CATCPCreateCond()
191 {
192     if (!g_condObjectList)
193     {
194         g_condObjectList = ca_cond_new();
195         if (!g_condObjectList)
196         {
197             OIC_LOG(ERROR, TAG, "Failed to created cond!");
198             return CA_STATUS_FAILED;
199         }
200     }
201     return CA_STATUS_OK;
202 }
203
204 static void CAReceiveHandler(void *data)
205 {
206     (void)data;
207     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
208
209     while (!caglobals.tcp.terminate)
210     {
211         CAFindReadyMessage();
212     }
213
214     ca_mutex_lock(g_mutexObjectList);
215     ca_cond_signal(g_condObjectList);
216     ca_mutex_unlock(g_mutexObjectList);
217
218     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
219 }
220
221 static void CAFindReadyMessage()
222 {
223     fd_set readFds;
224     struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
225
226     FD_ZERO(&readFds);
227
228     if (-1 != caglobals.tcp.ipv4.fd)
229     {
230         FD_SET(caglobals.tcp.ipv4.fd, &readFds);
231     }
232     if (-1 != caglobals.tcp.ipv6.fd)
233     {
234         FD_SET(caglobals.tcp.ipv6.fd, &readFds);
235     }
236     if (-1 != caglobals.tcp.shutdownFds[0])
237     {
238         FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
239     }
240     if (-1 != caglobals.tcp.connectionFds[0])
241     {
242         FD_SET(caglobals.tcp.connectionFds[0], &readFds);
243     }
244
245     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
246     for (size_t i = 0; i < length; i++)
247     {
248         CATCPSessionInfo_t *svritem =
249                 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
250         if (svritem && 0 <= svritem->fd)
251         {
252             FD_SET(svritem->fd, &readFds);
253         }
254     }
255
256     int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
257
258     if (caglobals.tcp.terminate)
259     {
260         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
261         return;
262     }
263     if (0 >= ret)
264     {
265         if (0 > ret)
266         {
267             OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
268         }
269         return;
270     }
271
272     CASelectReturned(&readFds);
273 }
274
275 static void CASelectReturned(fd_set *readFds)
276 {
277     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
278
279     if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
280     {
281         CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
282         return;
283     }
284     else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
285     {
286         CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
287         return;
288     }
289     else if (-1 != caglobals.tcp.connectionFds[0] &&
290             FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
291     {
292         // new connection was created from remote device.
293         // exit the function to update read file descriptor.
294         char buf[MAX_ADDR_STR_SIZE_CA] = {0};
295         ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
296         if (-1 == len)
297         {
298             return;
299         }
300         OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
301         FD_CLR(caglobals.tcp.connectionFds[0], readFds);
302         return;
303     }
304     else
305     {
306         uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
307         for (size_t i = 0; i < length; i++)
308         {
309             CATCPSessionInfo_t *svritem =
310                     (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
311             if (svritem && svritem->fd >= 0)
312             {
313                 if (FD_ISSET(svritem->fd, readFds))
314                 {
315                     CAReceiveMessage(svritem->fd);
316                     FD_CLR(svritem->fd, readFds);
317                 }
318             }
319         }
320     }
321 }
322
323 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
324 {
325     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
326
327     struct sockaddr_storage clientaddr;
328     socklen_t clientlen = sizeof (struct sockaddr_in);
329     if (flag & CA_IPV6)
330     {
331         clientlen = sizeof(struct sockaddr_in6);
332     }
333
334     int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
335     if (-1 != sockfd)
336     {
337         CATCPSessionInfo_t *svritem =
338                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
339         if (!svritem)
340         {
341             OIC_LOG(ERROR, TAG, "Out of memory");
342             close(sockfd);
343             return;
344         }
345
346         svritem->fd = sockfd;
347         svritem->sep.endpoint.flags = flag;
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 CATCPSessionInfo_t * recvinfo)
369 {
370     if (recvinfo->data == NULL || recvinfo->len == 0)
371     {
372         OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
373         return false;
374     }
375
376     unsigned char first_byte = recvinfo->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 static void CAReceiveMessage(int fd)
396 {
397     // #1. get remote device information from file descriptor.
398     size_t index = 0;
399     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
400     if (!svritem)
401     {
402         OIC_LOG(ERROR, TAG, "there is no connection information in list");
403         return;
404     }
405
406     // #2. allocate memory for message header (CoAP header size because it is bigger)
407     svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
408     if (!svritem->data)
409     {
410         OIC_LOG(ERROR, TAG, "out of memory");
411         goto error;
412     }
413
414     // #3. read data (assume TLS header) from remote device.
415     RECV(fd, svritem, svritem->data, TLS_HEADER_SIZE, 0);
416
417 #ifdef __WITH_TLS__
418     if (CAIsTlsMessage(svritem))
419     {
420         // #4.1 get tls body length from tls header. [3][4] bytes are length of tls body in header
421         unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
422         OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
423
424         REALLOC(svritem->data, message_length + TLS_HEADER_SIZE);
425
426         RECV(fd, svritem, svritem->data, message_length, 0);
427
428         int ret = CAdecryptTls(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
429
430         OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptTls returned %d", __func__, ret);
431         goto success;
432     }
433     else
434 #endif
435     {
436         // #4.2 Seems CoAP data received. read full coap header.
437         coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
438
439         size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
440
441         if (svritem->len < headerLen)
442         {
443             // read required bytes to have full CoAP header
444             // usually it is 1 bytes (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
445             RECV(fd, svritem, svritem->data, headerLen - svritem->len, 0);
446         }
447
448         // #4.3 Calculate CoAP message length and read it
449         size_t total_length = CAGetTotalLengthFromHeader(svritem->data);
450         REALLOC(svritem->data, total_length);
451
452         RECV(fd, svritem, svritem->data, total_length - svritem->len, 0);
453
454         // #4.4. pass the received data information to upper layer.
455         if (g_packetReceivedCallback)
456         {
457             svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
458             g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
459         }
460         goto success;
461     }
462
463     error:
464     CADisconnectTCPSession(svritem, index);
465
466     success:
467     // initialize data info to receive next message.
468     OICFree(svritem->data);
469     svritem->data = NULL;
470     svritem->len = 0;
471
472     return;
473 }
474
475 static void CAWakeUpForReadFdsUpdate(const char *host)
476 {
477     if (caglobals.tcp.connectionFds[1] != -1)
478     {
479         ssize_t len = 0;
480         do
481         {
482             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
483         } while ((len == -1) && (errno == EINTR));
484
485         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
486         {
487             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
488         }
489     }
490 }
491
492 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
493                                          struct sockaddr_storage *sockaddr)
494 {
495     struct addrinfo *addrs = NULL;
496     struct addrinfo hints = { .ai_family = family,
497                               .ai_protocol   = IPPROTO_TCP,
498                               .ai_socktype = SOCK_STREAM,
499                               .ai_flags = AI_NUMERICHOST };
500
501     int r = getaddrinfo(host, NULL, &hints, &addrs);
502     if (r)
503     {
504         if (EAI_SYSTEM == r)
505         {
506             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
507         }
508         else
509         {
510             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
511         }
512         freeaddrinfo(addrs);
513         return CA_STATUS_FAILED;
514     }
515     // assumption: in this case, getaddrinfo will only return one addrinfo
516     // or first is the one we want.
517     if (addrs[0].ai_family == AF_INET6)
518     {
519         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
520         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
521     }
522     else
523     {
524         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
525         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
526     }
527     freeaddrinfo(addrs);
528     return CA_STATUS_OK;
529 }
530
531 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
532 {
533     // #1. create tcp socket.
534     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
535     if (-1 == fd)
536     {
537         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
538         return -1;
539     }
540
541     // #2. convert address from string to binary.
542     struct sockaddr_storage sa = { .ss_family = family };
543     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
544                                             svritem->sep.endpoint.port, &sa);
545     if (CA_STATUS_OK != res)
546     {
547         close(fd);
548         return -1;
549     }
550
551     // #3. set socket length.
552     socklen_t socklen = 0;
553     if (sa.ss_family == AF_INET6)
554     {
555         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
556         if (!sock6->sin6_scope_id)
557         {
558             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
559         }
560         socklen = sizeof(struct sockaddr_in6);
561     }
562     else
563     {
564         socklen = sizeof(struct sockaddr_in);
565     }
566
567     // #4. connect to remote server device.
568     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
569     {
570         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
571         close(fd);
572         return -1;
573     }
574
575     OIC_LOG(DEBUG, TAG, "connect socket success");
576     CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
577     return fd;
578 }
579
580 static int CACreateAcceptSocket(int family, CASocket_t *sock)
581 {
582     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
583
584     if (sock->fd != -1)
585     {
586         OIC_LOG(DEBUG, TAG, "accept socket created already");
587         return sock->fd;
588     }
589
590     socklen_t socklen = 0;
591     struct sockaddr_storage server = { .ss_family = family };
592
593     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
594     if (fd < 0)
595     {
596         OIC_LOG(ERROR, TAG, "Failed to create socket");
597         goto exit;
598     }
599
600     if (family == AF_INET6)
601     {
602         // the socket is re‐stricted to sending and receiving IPv6 packets only.
603         int on = 1;
604         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
605         {
606             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
607             goto exit;
608         }
609         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
610         socklen = sizeof (struct sockaddr_in6);
611     }
612     else
613     {
614         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
615         socklen = sizeof (struct sockaddr_in);
616     }
617
618     int reuse = 1;
619     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
620     {
621         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
622         goto exit;
623     }
624
625     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
626     {
627         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
628         goto exit;
629     }
630
631     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
632     {
633         OIC_LOG(ERROR, TAG, "listen() error");
634         goto exit;
635     }
636
637     if (!sock->port)  // return the assigned port
638     {
639         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
640         {
641             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
642             goto exit;
643         }
644         sock->port = ntohs(family == AF_INET6 ?
645                       ((struct sockaddr_in6 *)&server)->sin6_port :
646                       ((struct sockaddr_in *)&server)->sin_port);
647     }
648
649     return fd;
650
651 exit:
652     if (fd >= 0)
653     {
654         close(fd);
655     }
656     return -1;
657 }
658
659 static void CAInitializePipe(int *fds)
660 {
661     int ret = pipe(fds);
662     if (-1 != ret)
663     {
664         ret = fcntl(fds[0], F_GETFD);
665         if (-1 != ret)
666         {
667             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
668         }
669         if (-1 != ret)
670         {
671             ret = fcntl(fds[1], F_GETFD);
672         }
673         if (-1 != ret)
674         {
675             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
676         }
677         if (-1 == ret)
678         {
679             close(fds[1]);
680             close(fds[0]);
681
682             fds[0] = -1;
683             fds[1] = -1;
684
685             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
686         }
687     }
688 }
689
690 #define NEWSOCKET(FAMILY, NAME) \
691     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
692     if (caglobals.tcp.NAME.fd == -1) \
693     { \
694         caglobals.tcp.NAME.port = 0; \
695         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
696     } \
697     CHECKFD(caglobals.tcp.NAME.fd);
698
699 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
700 {
701     if (caglobals.tcp.started)
702     {
703         return CA_STATUS_OK;
704     }
705
706     if (!caglobals.tcp.ipv4tcpenabled)
707     {
708         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
709     }
710     if (!caglobals.tcp.ipv6tcpenabled)
711     {
712         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
713     }
714
715     CAResult_t res = CATCPCreateMutex();
716     if (CA_STATUS_OK == res)
717     {
718         res = CATCPCreateCond();
719     }
720     if (CA_STATUS_OK != res)
721     {
722         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
723         return res;
724     }
725
726     ca_mutex_lock(g_mutexObjectList);
727     if (!caglobals.tcp.svrlist)
728     {
729         caglobals.tcp.svrlist = u_arraylist_create();
730     }
731     ca_mutex_unlock(g_mutexObjectList);
732
733     if (caglobals.server)
734     {
735         NEWSOCKET(AF_INET, ipv4);
736         NEWSOCKET(AF_INET6, ipv6);
737         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
738                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
739         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
740                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
741     }
742
743     // create pipe for fast shutdown
744     CAInitializePipe(caglobals.tcp.shutdownFds);
745     CHECKFD(caglobals.tcp.shutdownFds[0]);
746     CHECKFD(caglobals.tcp.shutdownFds[1]);
747
748     // create pipe for connection event
749     CAInitializePipe(caglobals.tcp.connectionFds);
750     CHECKFD(caglobals.tcp.connectionFds[0]);
751     CHECKFD(caglobals.tcp.connectionFds[1]);
752
753     caglobals.tcp.terminate = false;
754     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
755     if (CA_STATUS_OK != res)
756     {
757         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
758         return res;
759     }
760     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
761
762     caglobals.tcp.started = true;
763     return CA_STATUS_OK;
764 }
765
766 void CATCPStopServer()
767 {
768     // mutex lock
769     ca_mutex_lock(g_mutexObjectList);
770
771     // set terminate flag
772     caglobals.tcp.terminate = true;
773
774     if (caglobals.tcp.shutdownFds[1] != -1)
775     {
776         close(caglobals.tcp.shutdownFds[1]);
777         // receive thread will stop immediately
778     }
779
780     if (caglobals.tcp.connectionFds[1] != -1)
781     {
782         close(caglobals.tcp.connectionFds[1]);
783     }
784
785     if (caglobals.tcp.started)
786     {
787         ca_cond_wait(g_condObjectList, g_mutexObjectList);
788     }
789     caglobals.tcp.started = false;
790
791     // mutex unlock
792     ca_mutex_unlock(g_mutexObjectList);
793
794     if (-1 != caglobals.tcp.ipv4.fd)
795     {
796         close(caglobals.tcp.ipv4.fd);
797         caglobals.tcp.ipv4.fd = -1;
798     }
799
800     if (-1 != caglobals.tcp.ipv6.fd)
801     {
802         close(caglobals.tcp.ipv6.fd);
803         caglobals.tcp.ipv6.fd = -1;
804     }
805
806     CATCPDisconnectAll();
807     CATCPDestroyMutex();
808     CATCPDestroyCond();
809 }
810
811 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
812 {
813     g_packetReceivedCallback = callback;
814 }
815
816 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
817 {
818     g_connectionCallback = connHandler;
819 }
820
821 static void sendData(const CAEndpoint_t *endpoint, const void *data,
822                      size_t dlen, const char *fam)
823 {
824     // #1. get TCP Server object from list
825     size_t index = 0;
826     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
827     if (!svritem)
828     {
829         // if there is no connection info, connect to TCP Server
830         svritem = CAConnectTCPSession(endpoint);
831         if (!svritem)
832         {
833             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
834             if (g_tcpErrorHandler)
835             {
836                 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
837             }
838             return;
839         }
840     }
841
842     // #2. check connection state
843     if (svritem->fd < 0)
844     {
845         // if file descriptor value is wrong, remove TCP Server info from list
846         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
847         CADisconnectTCPSession(svritem, index);
848         if (g_tcpErrorHandler)
849         {
850             g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
851         }
852         return;
853     }
854
855     // #4. send data to TCP Server
856     ssize_t remainLen = dlen;
857     do
858     {
859         ssize_t len = send(svritem->fd, data, remainLen, 0);
860         if (-1 == len)
861         {
862             if (EWOULDBLOCK != errno)
863             {
864                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
865                 if (g_tcpErrorHandler)
866                 {
867                     g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
868                 }
869                 return;
870             }
871             continue;
872         }
873         data += len;
874         remainLen -= len;
875     } while (remainLen > 0);
876
877     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
878 }
879
880 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
881                    bool isMulticast)
882 {
883     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
884     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
885
886     if (!isMulticast)
887     {
888         if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
889         {
890             sendData(endpoint, data, datalen, "ipv6");
891         }
892         if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
893         {
894             sendData(endpoint, data, datalen, "ipv4");
895         }
896     }
897 }
898
899 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
900 {
901     VERIFY_NON_NULL(info, TAG, "info is NULL");
902     VERIFY_NON_NULL(size, TAG, "size is NULL");
903
904     return CA_NOT_SUPPORTED;
905 }
906
907 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
908 {
909     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
910
911     // #1. create TCP server object
912     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
913     if (!svritem)
914     {
915         OIC_LOG(ERROR, TAG, "Out of memory");
916         return NULL;
917     }
918     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
919     svritem->sep.endpoint.adapter = endpoint->adapter;
920     svritem->sep.endpoint.port = endpoint->port;
921     svritem->sep.endpoint.flags = endpoint->flags;
922     svritem->sep.endpoint.ifindex = endpoint->ifindex;
923
924     // #2. create the socket and connect to TCP server
925     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
926     int fd = CATCPCreateSocket(family, svritem);
927     if (-1 == fd)
928     {
929         OICFree(svritem);
930         return NULL;
931     }
932
933     // #3. add TCP connection info to list
934     svritem->fd = fd;
935     ca_mutex_lock(g_mutexObjectList);
936     if (caglobals.tcp.svrlist)
937     {
938         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
939         if (!res)
940         {
941             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
942             close(svritem->fd);
943             OICFree(svritem);
944             ca_mutex_unlock(g_mutexObjectList);
945             return NULL;
946         }
947     }
948     ca_mutex_unlock(g_mutexObjectList);
949
950     CHECKFD(fd);
951
952     // pass the connection information to CA Common Layer.
953     if (g_connectionCallback)
954     {
955         g_connectionCallback(&(svritem->sep.endpoint), true);
956     }
957
958     return svritem;
959 }
960
961 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
962 {
963     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
964
965     ca_mutex_lock(g_mutexObjectList);
966
967     // close the socket and remove TCP connection info in list
968     if (svritem->fd >= 0)
969     {
970         close(svritem->fd);
971     }
972     u_arraylist_remove(caglobals.tcp.svrlist, index);
973     OICFree(svritem->data);
974     svritem->data = NULL;
975
976     // pass the connection information to CA Common Layer.
977     if (g_connectionCallback)
978     {
979         g_connectionCallback(&(svritem->sep.endpoint), false);
980     }
981
982     OICFree(svritem);
983     ca_mutex_unlock(g_mutexObjectList);
984
985     return CA_STATUS_OK;
986 }
987
988 void CATCPDisconnectAll()
989 {
990     ca_mutex_lock(g_mutexObjectList);
991     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
992
993     CATCPSessionInfo_t *svritem = NULL;
994     for (size_t i = 0; i < length; i++)
995     {
996         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
997         if (svritem && svritem->fd >= 0)
998         {
999             shutdown(svritem->fd, SHUT_RDWR);
1000             close(svritem->fd);
1001
1002             OICFree(svritem->data);
1003             svritem->data = NULL;
1004         }
1005     }
1006     u_arraylist_destroy(caglobals.tcp.svrlist);
1007     ca_mutex_unlock(g_mutexObjectList);
1008 }
1009
1010 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1011 {
1012     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1013     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1014
1015     // get connection info from list
1016     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1017     for (size_t i = 0; i < length; i++)
1018     {
1019         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1020                 caglobals.tcp.svrlist, i);
1021         if (!svritem)
1022         {
1023             continue;
1024         }
1025
1026         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1027                      sizeof(svritem->sep.endpoint.addr))
1028                 && (svritem->sep.endpoint.port == endpoint->port)
1029                 && (svritem->sep.endpoint.flags & endpoint->flags))
1030         {
1031             *index = i;
1032             return svritem;
1033         }
1034     }
1035
1036     return NULL;
1037 }
1038
1039 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1040 {
1041     ca_mutex_lock(g_mutexObjectList);
1042
1043     // check from the last item.
1044     CATCPSessionInfo_t *svritem = NULL;
1045     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1046     for (size_t i = 0; i < length; i++)
1047     {
1048         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1049
1050         if (svritem && svritem->fd == fd)
1051         {
1052             *index = i;
1053             ca_mutex_unlock(g_mutexObjectList);
1054             return svritem;
1055         }
1056     }
1057
1058     ca_mutex_unlock(g_mutexObjectList);
1059
1060     return NULL;
1061 }
1062
1063 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1064 {
1065     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1066
1067     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
1068             ((unsigned char *)recvBuffer)[0] >> 4);
1069     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1070                                                         transport);
1071     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1072
1073     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1074     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1075     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1076
1077     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1078     return headerLen + optPaylaodLen;
1079 }
1080
1081 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1082 {
1083     g_tcpErrorHandler = errorHandleCallback;
1084 }