Merge branch 'master' into 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, int ret);
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, ret);
220 }
221
222 static void CASelectReturned(fd_set *readFds, int ret)
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 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
619 {
620     if (caglobals.tcp.started)
621     {
622         return CA_STATUS_OK;
623     }
624
625     if (!caglobals.tcp.ipv4tcpenabled)
626     {
627         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
628     }
629     if (!caglobals.tcp.ipv6tcpenabled)
630     {
631         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
632     }
633
634     CAResult_t res = CATCPCreateMutex();
635     if (CA_STATUS_OK == res)
636     {
637         res = CATCPCreateCond();
638     }
639     if (CA_STATUS_OK != res)
640     {
641         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
642         return res;
643     }
644
645     ca_mutex_lock(g_mutexObjectList);
646     if (!caglobals.tcp.svrlist)
647     {
648         caglobals.tcp.svrlist = u_arraylist_create();
649     }
650     ca_mutex_unlock(g_mutexObjectList);
651
652     if (caglobals.server)
653     {
654         caglobals.tcp.ipv4.fd = CACreateAcceptSocket(AF_INET, &caglobals.tcp.ipv4);
655         CHECKFD(caglobals.tcp.ipv4.fd);
656         caglobals.tcp.ipv6.fd = CACreateAcceptSocket(AF_INET6, &caglobals.tcp.ipv6);
657         CHECKFD(caglobals.tcp.ipv6.fd);
658
659         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
660                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
661         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
662                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
663     }
664
665     // create pipe for fast shutdown
666     CAInitializePipe(caglobals.tcp.shutdownFds);
667     CHECKFD(caglobals.tcp.shutdownFds[0]);
668     CHECKFD(caglobals.tcp.shutdownFds[1]);
669
670     // create pipe for connection event
671     CAInitializePipe(caglobals.tcp.connectionFds);
672     CHECKFD(caglobals.tcp.connectionFds[0]);
673     CHECKFD(caglobals.tcp.connectionFds[1]);
674
675     caglobals.tcp.terminate = false;
676     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
677     if (CA_STATUS_OK != res)
678     {
679         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
680         return res;
681     }
682     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
683
684     caglobals.tcp.started = true;
685     return CA_STATUS_OK;
686 }
687
688 void CATCPStopServer()
689 {
690     // mutex lock
691     ca_mutex_lock(g_mutexObjectList);
692
693     // set terminate flag
694     caglobals.tcp.terminate = true;
695
696     if (caglobals.tcp.shutdownFds[1] != -1)
697     {
698         close(caglobals.tcp.shutdownFds[1]);
699         // receive thread will stop immediately
700     }
701
702     if (caglobals.tcp.connectionFds[1] != -1)
703     {
704         close(caglobals.tcp.connectionFds[1]);
705     }
706
707     if (caglobals.tcp.started)
708     {
709         ca_cond_wait(g_condObjectList, g_mutexObjectList);
710     }
711     caglobals.tcp.started = false;
712
713     // mutex unlock
714     ca_mutex_unlock(g_mutexObjectList);
715
716     if (-1 != caglobals.tcp.ipv4.fd)
717     {
718         close(caglobals.tcp.ipv4.fd);
719         caglobals.tcp.ipv4.fd = -1;
720     }
721
722     if (-1 != caglobals.tcp.ipv6.fd)
723     {
724         close(caglobals.tcp.ipv6.fd);
725         caglobals.tcp.ipv6.fd = -1;
726     }
727
728     CATCPDisconnectAll();
729     CATCPDestroyMutex();
730     CATCPDestroyCond();
731 }
732
733 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
734 {
735     g_packetReceivedCallback = callback;
736 }
737
738 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
739 {
740     g_connectionCallback = connHandler;
741 }
742
743 static size_t CACheckPayloadLength(const void *data, size_t dlen)
744 {
745     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
746
747     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
748             ((unsigned char *)data)[0] >> 4);
749
750     coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
751     if (!pdu)
752     {
753         OIC_LOG(ERROR, TAG, "outpdu is null");
754         return 0;
755     }
756
757     int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
758     if (0 >= ret)
759     {
760         OIC_LOG(ERROR, TAG, "pdu parse failed");
761         coap_delete_pdu(pdu);
762         return 0;
763     }
764
765     size_t payloadLen = 0;
766     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
767     OIC_LOG_V(DEBUG, TAG, "headerSize : %d, pdu length : %d",
768               headerSize, pdu->length);
769     if (pdu->length > headerSize)
770     {
771         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
772     }
773
774     OICFree(pdu);
775
776     return payloadLen;
777 }
778
779 static void sendData(const CAEndpoint_t *endpoint, const void *data,
780                      size_t dlen, const char *fam)
781 {
782     // #1. get TCP Server object from list
783     size_t index = 0;
784     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
785     if (!svritem)
786     {
787         // if there is no connection info, connect to TCP Server
788         svritem = CAConnectTCPSession(endpoint);
789         if (!svritem)
790         {
791             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
792             if (g_tcpErrorHandler)
793             {
794                 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
795             }
796             return;
797         }
798     }
799
800     // #2. check payload length
801     size_t payloadLen = CACheckPayloadLength(data, dlen);
802     // if payload length is zero, disconnect from TCP server
803     if (!payloadLen)
804     {
805         OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
806         CADisconnectTCPSession(svritem, index);
807         return;
808     }
809
810     // #3. check connection state
811     if (svritem->fd < 0)
812     {
813         // if file descriptor value is wrong, remove TCP Server info from list
814         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
815         CADisconnectTCPSession(svritem, index);
816         if (g_tcpErrorHandler)
817         {
818             g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
819         }
820         return;
821     }
822
823     // #4. send data to TCP Server
824     ssize_t remainLen = dlen;
825     do
826     {
827         ssize_t len = send(svritem->fd, data, remainLen, 0);
828         if (-1 == len)
829         {
830             if (EWOULDBLOCK != errno)
831             {
832                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
833                 if (g_tcpErrorHandler)
834                 {
835                     g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
836                 }
837                 return;
838             }
839             continue;
840         }
841         data += len;
842         remainLen -= len;
843     } while (remainLen > 0);
844
845     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
846 }
847
848 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
849                    bool isMulticast)
850 {
851     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
852     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
853
854     if (!isMulticast)
855     {
856         if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
857         {
858             sendData(endpoint, data, datalen, "ipv6");
859         }
860         if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
861         {
862             sendData(endpoint, data, datalen, "ipv4");
863         }
864     }
865 }
866
867 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
868 {
869     VERIFY_NON_NULL(info, TAG, "info is NULL");
870     VERIFY_NON_NULL(size, TAG, "size is NULL");
871
872     return CA_NOT_SUPPORTED;
873 }
874
875 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
876 {
877     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
878
879     // #1. create TCP server object
880     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
881     if (!svritem)
882     {
883         OIC_LOG(ERROR, TAG, "Out of memory");
884         return NULL;
885     }
886     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
887     svritem->sep.endpoint.port = endpoint->port;
888     svritem->sep.endpoint.flags = endpoint->flags;
889     svritem->sep.endpoint.interface = endpoint->interface;
890
891     // #2. create the socket and connect to TCP server
892     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
893     int fd = CATCPCreateSocket(family, svritem);
894     if (-1 == fd)
895     {
896         OICFree(svritem);
897         return NULL;
898     }
899
900     // #3. add TCP connection info to list
901     svritem->fd = fd;
902     ca_mutex_lock(g_mutexObjectList);
903     if (caglobals.tcp.svrlist)
904     {
905         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
906         if (!res)
907         {
908             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
909             close(svritem->fd);
910             OICFree(svritem);
911             ca_mutex_unlock(g_mutexObjectList);
912             return NULL;
913         }
914     }
915     ca_mutex_unlock(g_mutexObjectList);
916
917     CHECKFD(fd);
918
919     // pass the connection information to CA Common Layer.
920     if (g_connectionCallback)
921     {
922         g_connectionCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, true);
923     }
924
925     return svritem;
926 }
927
928 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
929 {
930     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
931
932     ca_mutex_lock(g_mutexObjectList);
933
934     // close the socket and remove TCP connection info in list
935     if (svritem->fd >= 0)
936     {
937         close(svritem->fd);
938     }
939     u_arraylist_remove(caglobals.tcp.svrlist, index);
940     OICFree(svritem->recvData);
941
942     // pass the connection information to CA Common Layer.
943     if (g_connectionCallback)
944     {
945         g_connectionCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, false);
946     }
947
948     OICFree(svritem);
949     ca_mutex_unlock(g_mutexObjectList);
950
951     return CA_STATUS_OK;
952 }
953
954 void CATCPDisconnectAll()
955 {
956     ca_mutex_lock(g_mutexObjectList);
957     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
958
959     CATCPSessionInfo_t *svritem = NULL;
960     for (size_t i = 0; i < length; i++)
961     {
962         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
963         if (svritem && svritem->fd >= 0)
964         {
965             shutdown(svritem->fd, SHUT_RDWR);
966             close(svritem->fd);
967             OICFree(svritem->recvData);
968         }
969     }
970     u_arraylist_destroy(caglobals.tcp.svrlist);
971     ca_mutex_unlock(g_mutexObjectList);
972 }
973
974 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
975 {
976     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
977     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
978
979     // get connection info from list
980     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
981     for (size_t i = 0; i < length; i++)
982     {
983         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
984                 caglobals.tcp.svrlist, i);
985         if (!svritem)
986         {
987             continue;
988         }
989
990         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
991                      sizeof(svritem->sep.endpoint.addr))
992                 && (svritem->sep.endpoint.port == endpoint->port)
993                 && (svritem->sep.endpoint.flags & endpoint->flags))
994         {
995             *index = i;
996             return svritem;
997         }
998     }
999
1000     return NULL;
1001 }
1002
1003 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1004 {
1005     ca_mutex_lock(g_mutexObjectList);
1006
1007     // check from the last item.
1008     CATCPSessionInfo_t *svritem = NULL;
1009     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1010     for (size_t i = 0; i < length; i++)
1011     {
1012         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1013
1014         if (svritem && svritem->fd == fd)
1015         {
1016             *index = i;
1017             ca_mutex_unlock(g_mutexObjectList);
1018             return svritem;
1019         }
1020     }
1021
1022     ca_mutex_unlock(g_mutexObjectList);
1023
1024     return NULL;
1025 }
1026
1027 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1028 {
1029     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1030
1031     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
1032             ((unsigned char *)recvBuffer)[0] >> 4);
1033     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1034                                                         transport);
1035     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1036
1037     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
1038     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
1039     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
1040
1041     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1042     return headerLen + optPaylaodLen;
1043 }
1044
1045 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1046 {
1047     g_tcpErrorHandler = errorHandleCallback;
1048 }