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