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