Merge branch 'master' into cloud-interface
[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     if (flag & CA_IPV6)
292     {
293         clientlen = sizeof(struct sockaddr_in6);
294     }
295
296     int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
297     if (-1 != sockfd)
298     {
299         CATCPSessionInfo_t *svritem =
300                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
301         if (!svritem)
302         {
303             OIC_LOG(ERROR, TAG, "Out of memory");
304             close(sockfd);
305             return;
306         }
307
308         svritem->fd = sockfd;
309         svritem->sep.endpoint.flags = flag;
310         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
311                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
312
313         ca_mutex_lock(g_mutexObjectList);
314         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
315         if (!result)
316         {
317             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
318             close(sockfd);
319             OICFree(svritem);
320             ca_mutex_unlock(g_mutexObjectList);
321             return;
322         }
323         ca_mutex_unlock(g_mutexObjectList);
324
325         CHECKFD(sockfd);
326     }
327 }
328
329 static void CAReceiveMessage(int fd)
330 {
331     // #1. get remote device information from file descriptor.
332     size_t index = 0;
333     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
334     if (!svritem)
335     {
336         OIC_LOG(ERROR, TAG, "there is no connection information in list");
337         return;
338     }
339
340     // #2. get already allocated memory size.
341     size_t bufSize = (svritem->totalDataLen == 0) ? TCP_MAX_HEADER_LEN : svritem->totalDataLen;
342     if (!svritem->recvData)
343     {
344         svritem->recvData = (unsigned char *) OICCalloc(1, bufSize);
345         if (!svritem->recvData)
346         {
347             OIC_LOG(ERROR, TAG, "out of memory");
348             CADisconnectTCPSession(svritem, index);
349             return;
350         }
351     }
352
353     // #3. receive data from remote device.
354     ssize_t recvLen = recv(fd, svritem->recvData + svritem->recvDataLen,
355                            bufSize - svritem->recvDataLen, 0);
356     if (recvLen <= 0)
357     {
358         if(EWOULDBLOCK != errno)
359         {
360             OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
361             CADisconnectTCPSession(svritem, index);
362         }
363         return;
364     }
365     svritem->recvDataLen += recvLen;
366
367     // #4. get actual data length from coap over tcp header.
368     if (!svritem->totalDataLen)
369     {
370         coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
371                 ((unsigned char *) svritem->recvData)[0] >> 4);
372
373         size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
374         if (svritem->recvDataLen >= headerLen)
375         {
376             svritem->totalDataLen = CAGetTotalLengthFromHeader(
377                     (unsigned char *) svritem->recvData);
378             bufSize = svritem->totalDataLen;
379             unsigned char *newBuf = OICRealloc(svritem->recvData, bufSize);
380             if (!newBuf)
381             {
382                 OIC_LOG(ERROR, TAG, "out of memory");
383                 CADisconnectTCPSession(svritem, index);
384                 return;
385             }
386             svritem->recvData = newBuf;
387         }
388     }
389
390     // #5. pass the received data information to upper layer.
391     if ((svritem->totalDataLen == svritem->recvDataLen) && g_packetReceivedCallback)
392     {
393         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
394         g_packetReceivedCallback(&svritem->sep, svritem->recvData, svritem->recvDataLen);
395         OIC_LOG_V(DEBUG, TAG, "total received data len:%d", svritem->recvDataLen);
396
397         // initialize data info to receive next message.
398         OICFree(svritem->recvData);
399         svritem->recvData = NULL;
400         svritem->recvDataLen = 0;
401         svritem->totalDataLen = 0;
402     }
403
404     return;
405 }
406
407 static void CAWakeUpForReadFdsUpdate(const char *host)
408 {
409     if (caglobals.tcp.connectionFds[1] != -1)
410     {
411         ssize_t len = 0;
412         do
413         {
414             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
415         } while ((len == -1) && (errno == EINTR));
416
417         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
418         {
419             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
420         }
421     }
422 }
423
424 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
425                                          struct sockaddr_storage *sockaddr)
426 {
427     struct addrinfo *addrs = NULL;
428     struct addrinfo hints = { .ai_family = family,
429                               .ai_protocol   = IPPROTO_TCP,
430                               .ai_socktype = SOCK_STREAM,
431                               .ai_flags = AI_NUMERICHOST };
432
433     int r = getaddrinfo(host, NULL, &hints, &addrs);
434     if (r)
435     {
436         if (EAI_SYSTEM == r)
437         {
438             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
439         }
440         else
441         {
442             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
443         }
444         freeaddrinfo(addrs);
445         return CA_STATUS_FAILED;
446     }
447     // assumption: in this case, getaddrinfo will only return one addrinfo
448     // or first is the one we want.
449     if (addrs[0].ai_family == AF_INET6)
450     {
451         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
452         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
453     }
454     else
455     {
456         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
457         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
458     }
459     freeaddrinfo(addrs);
460     return CA_STATUS_OK;
461 }
462
463 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
464 {
465     // #1. create tcp socket.
466     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
467     if (-1 == fd)
468     {
469         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
470         return -1;
471     }
472
473     // #2. convert address from string to binary.
474     struct sockaddr_storage sa = { .ss_family = family };
475     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
476                                             svritem->sep.endpoint.port, &sa);
477     if (CA_STATUS_OK != res)
478     {
479         close(fd);
480         return -1;
481     }
482
483     // #3. set socket length.
484     socklen_t socklen;
485     if (sa.ss_family == AF_INET6)
486     {
487         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
488         if (!sock6->sin6_scope_id)
489         {
490             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
491         }
492         socklen = sizeof(struct sockaddr_in6);
493     }
494     else
495     {
496         socklen = sizeof(struct sockaddr_in);
497     }
498
499     // #4. connect to remote server device.
500     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
501     {
502         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
503         close(fd);
504         return -1;
505     }
506
507     OIC_LOG(DEBUG, TAG, "connect socket success");
508     CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
509     return fd;
510 }
511
512 static int CACreateAcceptSocket(int family, CASocket_t *sock)
513 {
514     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
515
516     if (sock->fd != -1)
517     {
518         OIC_LOG(DEBUG, TAG, "accept socket created already");
519         return sock->fd;
520     }
521
522     socklen_t socklen;
523     struct sockaddr_storage server = { .ss_family = family };
524
525     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
526     if (fd < 0)
527     {
528         OIC_LOG(ERROR, TAG, "Failed to create socket");
529         goto exit;
530     }
531
532     if (family == AF_INET6)
533     {
534         // the socket is re‐stricted to sending and receiving IPv6 packets only.
535         int on = 1;
536         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
537         {
538             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
539             goto exit;
540         }
541         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
542         socklen = sizeof (struct sockaddr_in6);
543     }
544     else
545     {
546         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
547         socklen = sizeof (struct sockaddr_in);
548     }
549
550     int reuse = 1;
551     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
552     {
553         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
554         goto exit;
555     }
556
557     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
558     {
559         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
560         goto exit;
561     }
562
563     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
564     {
565         OIC_LOG(ERROR, TAG, "listen() error");
566         goto exit;
567     }
568
569     if (!sock->port)  // return the assigned port
570     {
571         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
572         {
573             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
574             goto exit;
575         }
576         sock->port = ntohs(family == AF_INET6 ?
577                       ((struct sockaddr_in6 *)&server)->sin6_port :
578                       ((struct sockaddr_in *)&server)->sin_port);
579     }
580
581     return fd;
582
583 exit:
584     if (fd >= 0)
585     {
586         close(fd);
587     }
588     return -1;
589 }
590
591 static void CAInitializePipe(int *fds)
592 {
593     int ret = pipe(fds);
594     if (-1 != ret)
595     {
596         ret = fcntl(fds[0], F_GETFD);
597         if (-1 != ret)
598         {
599             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
600         }
601         if (-1 != ret)
602         {
603             ret = fcntl(fds[1], F_GETFD);
604         }
605         if (-1 != ret)
606         {
607             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
608         }
609         if (-1 == ret)
610         {
611             close(fds[1]);
612             close(fds[0]);
613
614             fds[0] = -1;
615             fds[1] = -1;
616
617             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
618         }
619     }
620 }
621
622 #define NEWSOCKET(FAMILY, NAME) \
623     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
624     if (caglobals.tcp.NAME.fd == -1) \
625     { \
626         caglobals.tcp.NAME.port = 0; \
627         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
628     } \
629     CHECKFD(caglobals.tcp.NAME.fd);
630
631 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
632 {
633     if (caglobals.tcp.started)
634     {
635         return CA_STATUS_OK;
636     }
637
638     if (!caglobals.tcp.ipv4tcpenabled)
639     {
640         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
641     }
642     if (!caglobals.tcp.ipv6tcpenabled)
643     {
644         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
645     }
646
647     CAResult_t res = CATCPCreateMutex();
648     if (CA_STATUS_OK == res)
649     {
650         res = CATCPCreateCond();
651     }
652     if (CA_STATUS_OK != res)
653     {
654         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
655         return res;
656     }
657
658     ca_mutex_lock(g_mutexObjectList);
659     if (!caglobals.tcp.svrlist)
660     {
661         caglobals.tcp.svrlist = u_arraylist_create();
662     }
663     ca_mutex_unlock(g_mutexObjectList);
664
665     if (caglobals.server)
666     {
667         NEWSOCKET(AF_INET, ipv4);
668         NEWSOCKET(AF_INET6, ipv6);
669         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
670                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
671         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
672                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
673     }
674
675     // create pipe for fast shutdown
676     CAInitializePipe(caglobals.tcp.shutdownFds);
677     CHECKFD(caglobals.tcp.shutdownFds[0]);
678     CHECKFD(caglobals.tcp.shutdownFds[1]);
679
680     // create pipe for connection event
681     CAInitializePipe(caglobals.tcp.connectionFds);
682     CHECKFD(caglobals.tcp.connectionFds[0]);
683     CHECKFD(caglobals.tcp.connectionFds[1]);
684
685     caglobals.tcp.terminate = false;
686     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
687     if (CA_STATUS_OK != res)
688     {
689         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
690         return res;
691     }
692     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
693
694     caglobals.tcp.started = true;
695     return CA_STATUS_OK;
696 }
697
698 void CATCPStopServer()
699 {
700     // mutex lock
701     ca_mutex_lock(g_mutexObjectList);
702
703     // set terminate flag
704     caglobals.tcp.terminate = true;
705
706     if (caglobals.tcp.shutdownFds[1] != -1)
707     {
708         close(caglobals.tcp.shutdownFds[1]);
709         // receive thread will stop immediately
710     }
711
712     if (caglobals.tcp.connectionFds[1] != -1)
713     {
714         close(caglobals.tcp.connectionFds[1]);
715     }
716
717     if (caglobals.tcp.started)
718     {
719         ca_cond_wait(g_condObjectList, g_mutexObjectList);
720     }
721     caglobals.tcp.started = false;
722
723     // mutex unlock
724     ca_mutex_unlock(g_mutexObjectList);
725
726     if (-1 != caglobals.tcp.ipv4.fd)
727     {
728         close(caglobals.tcp.ipv4.fd);
729         caglobals.tcp.ipv4.fd = -1;
730     }
731
732     if (-1 != caglobals.tcp.ipv6.fd)
733     {
734         close(caglobals.tcp.ipv6.fd);
735         caglobals.tcp.ipv6.fd = -1;
736     }
737
738     CATCPDisconnectAll();
739     CATCPDestroyMutex();
740     CATCPDestroyCond();
741 }
742
743 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
744 {
745     g_packetReceivedCallback = callback;
746 }
747
748 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
749 {
750     g_connectionCallback = connHandler;
751 }
752
753 static size_t CACheckPayloadLength(const void *data, size_t dlen)
754 {
755     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
756
757     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
758             ((unsigned char *)data)[0] >> 4);
759
760     coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
761     if (!pdu)
762     {
763         OIC_LOG(ERROR, TAG, "outpdu is null");
764         return 0;
765     }
766
767     int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
768     if (0 >= ret)
769     {
770         OIC_LOG(ERROR, TAG, "pdu parse failed");
771         coap_delete_pdu(pdu);
772         return 0;
773     }
774
775     size_t payloadLen = 0;
776     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
777     OIC_LOG_V(DEBUG, TAG, "headerSize : %d, pdu length : %d",
778               headerSize, pdu->length);
779     if (pdu->length > headerSize)
780     {
781         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
782     }
783
784     OICFree(pdu);
785
786     return payloadLen;
787 }
788
789 static void sendData(const CAEndpoint_t *endpoint, const void *data,
790                      size_t dlen, const char *fam)
791 {
792     // #1. get TCP Server object from list
793     size_t index = 0;
794     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
795     if (!svritem)
796     {
797         // if there is no connection info, connect to TCP Server
798         svritem = CAConnectTCPSession(endpoint);
799         if (!svritem)
800         {
801             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
802             if (g_tcpErrorHandler)
803             {
804                 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
805             }
806             return;
807         }
808     }
809
810     // #2. check payload length
811     size_t payloadLen = CACheckPayloadLength(data, dlen);
812     // if payload length is zero, disconnect from TCP server
813     if (!payloadLen)
814     {
815         OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
816         CADisconnectTCPSession(svritem, index);
817         return;
818     }
819
820     // #3. check connection state
821     if (svritem->fd < 0)
822     {
823         // if file descriptor value is wrong, remove TCP Server info from list
824         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
825         CADisconnectTCPSession(svritem, index);
826         if (g_tcpErrorHandler)
827         {
828             g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
829         }
830         return;
831     }
832
833     // #4. send data to TCP Server
834     ssize_t remainLen = dlen;
835     do
836     {
837         ssize_t len = send(svritem->fd, data, remainLen, 0);
838         if (-1 == len)
839         {
840             if (EWOULDBLOCK != errno)
841             {
842                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
843                 if (g_tcpErrorHandler)
844                 {
845                     g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
846                 }
847                 return;
848             }
849             continue;
850         }
851         data += len;
852         remainLen -= len;
853     } while (remainLen > 0);
854
855     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
856 }
857
858 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
859                    bool isMulticast)
860 {
861     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
862     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
863
864     if (!isMulticast)
865     {
866         if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
867         {
868             sendData(endpoint, data, datalen, "ipv6");
869         }
870         if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
871         {
872             sendData(endpoint, data, datalen, "ipv4");
873         }
874     }
875 }
876
877 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
878 {
879     VERIFY_NON_NULL(info, TAG, "info is NULL");
880     VERIFY_NON_NULL(size, TAG, "size is NULL");
881
882     return CA_NOT_SUPPORTED;
883 }
884
885 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
886 {
887     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
888
889     // #1. create TCP server object
890     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
891     if (!svritem)
892     {
893         OIC_LOG(ERROR, TAG, "Out of memory");
894         return NULL;
895     }
896     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
897     svritem->sep.endpoint.adapter = endpoint->adapter;
898     svritem->sep.endpoint.port = endpoint->port;
899     svritem->sep.endpoint.flags = endpoint->flags;
900     svritem->sep.endpoint.ifindex = endpoint->ifindex;
901
902     // #2. create the socket and connect to TCP server
903     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
904     int fd = CATCPCreateSocket(family, svritem);
905     if (-1 == fd)
906     {
907         OICFree(svritem);
908         return NULL;
909     }
910
911     // #3. add TCP connection info to list
912     svritem->fd = fd;
913     ca_mutex_lock(g_mutexObjectList);
914     if (caglobals.tcp.svrlist)
915     {
916         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
917         if (!res)
918         {
919             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
920             close(svritem->fd);
921             OICFree(svritem);
922             ca_mutex_unlock(g_mutexObjectList);
923             return NULL;
924         }
925     }
926     ca_mutex_unlock(g_mutexObjectList);
927
928     CHECKFD(fd);
929
930     // pass the connection information to CA Common Layer.
931     if (g_connectionCallback)
932     {
933         g_connectionCallback(&(svritem->sep.endpoint), true);
934     }
935
936     return svritem;
937 }
938
939 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
940 {
941     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
942
943     ca_mutex_lock(g_mutexObjectList);
944
945     // close the socket and remove TCP connection info in list
946     if (svritem->fd >= 0)
947     {
948         close(svritem->fd);
949     }
950     u_arraylist_remove(caglobals.tcp.svrlist, index);
951     OICFree(svritem->recvData);
952
953     // pass the connection information to CA Common Layer.
954     if (g_connectionCallback)
955     {
956         g_connectionCallback(&(svritem->sep.endpoint), false);
957     }
958
959     OICFree(svritem);
960     ca_mutex_unlock(g_mutexObjectList);
961
962     return CA_STATUS_OK;
963 }
964
965 void CATCPDisconnectAll()
966 {
967     ca_mutex_lock(g_mutexObjectList);
968     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
969
970     CATCPSessionInfo_t *svritem = NULL;
971     for (size_t i = 0; i < length; i++)
972     {
973         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
974         if (svritem && svritem->fd >= 0)
975         {
976             shutdown(svritem->fd, SHUT_RDWR);
977             close(svritem->fd);
978             OICFree(svritem->recvData);
979         }
980     }
981     u_arraylist_destroy(caglobals.tcp.svrlist);
982     ca_mutex_unlock(g_mutexObjectList);
983 }
984
985 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
986 {
987     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
988     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
989
990     // get connection info from list
991     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
992     for (size_t i = 0; i < length; i++)
993     {
994         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
995                 caglobals.tcp.svrlist, i);
996         if (!svritem)
997         {
998             continue;
999         }
1000
1001         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1002                      sizeof(svritem->sep.endpoint.addr))
1003                 && (svritem->sep.endpoint.port == endpoint->port)
1004                 && (svritem->sep.endpoint.flags & endpoint->flags))
1005         {
1006             *index = i;
1007             return svritem;
1008         }
1009     }
1010
1011     return NULL;
1012 }
1013
1014 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1015 {
1016     ca_mutex_lock(g_mutexObjectList);
1017
1018     // check from the last item.
1019     CATCPSessionInfo_t *svritem = NULL;
1020     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1021     for (size_t i = 0; i < length; i++)
1022     {
1023         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1024
1025         if (svritem && svritem->fd == fd)
1026         {
1027             *index = i;
1028             ca_mutex_unlock(g_mutexObjectList);
1029             return svritem;
1030         }
1031     }
1032
1033     ca_mutex_unlock(g_mutexObjectList);
1034
1035     return NULL;
1036 }
1037
1038 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1039 {
1040     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1041
1042     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
1043             ((unsigned char *)recvBuffer)[0] >> 4);
1044     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1045                                                         transport);
1046     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1047
1048     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
1049     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
1050     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
1051
1052     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1053     return headerLen + optPaylaodLen;
1054 }
1055
1056 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1057 {
1058     g_tcpErrorHandler = errorHandleCallback;
1059 }