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;
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             g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
793             return;
794         }
795     }
796
797     // #2. check payload length
798     size_t payloadLen = CACheckPayloadLength(data, dlen);
799     // if payload length is zero, disconnect from TCP server
800     if (!payloadLen)
801     {
802         OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
803         CADisconnectTCPSession(svritem, index);
804         return;
805     }
806
807     // #3. check connection state
808     if (svritem->fd < 0)
809     {
810         // if file descriptor value is wrong, remove TCP Server info from list
811         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
812         CADisconnectTCPSession(svritem, index);
813         g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
814         return;
815     }
816
817     // #4. send data to TCP Server
818     ssize_t remainLen = dlen;
819     do
820     {
821         ssize_t len = send(svritem->fd, data, remainLen, 0);
822         if (-1 == len)
823         {
824             if (EWOULDBLOCK != errno)
825             {
826                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
827                 g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
828                 return;
829             }
830             continue;
831         }
832         data += len;
833         remainLen -= len;
834     } while (remainLen > 0);
835
836     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
837 }
838
839 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
840                    bool isMulticast)
841 {
842     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
843     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
844
845     if (!isMulticast)
846     {
847         if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
848         {
849             sendData(endpoint, data, datalen, "ipv6");
850         }
851         if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
852         {
853             sendData(endpoint, data, datalen, "ipv4");
854         }
855     }
856 }
857
858 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
859 {
860     VERIFY_NON_NULL(info, TAG, "info is NULL");
861     VERIFY_NON_NULL(size, TAG, "size is NULL");
862
863     return CA_NOT_SUPPORTED;
864 }
865
866 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
867 {
868     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
869
870     // #1. create TCP server object
871     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
872     if (!svritem)
873     {
874         OIC_LOG(ERROR, TAG, "Out of memory");
875         return NULL;
876     }
877     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
878     svritem->sep.endpoint.port = endpoint->port;
879     svritem->sep.endpoint.flags = endpoint->flags;
880     svritem->sep.endpoint.interface = endpoint->interface;
881
882     // #2. create the socket and connect to TCP server
883     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
884     int fd = CATCPCreateSocket(family, svritem);
885     if (-1 == fd)
886     {
887         OICFree(svritem);
888         return NULL;
889     }
890
891     // #3. add TCP connection info to list
892     svritem->fd = fd;
893     ca_mutex_lock(g_mutexObjectList);
894     if (caglobals.tcp.svrlist)
895     {
896         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
897         if (!res)
898         {
899             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
900             close(svritem->fd);
901             OICFree(svritem);
902             ca_mutex_unlock(g_mutexObjectList);
903             return NULL;
904         }
905     }
906     ca_mutex_unlock(g_mutexObjectList);
907
908     CHECKFD(fd);
909
910     // pass the connection information to CA Common Layer.
911     if (g_connectionCallback)
912     {
913         g_connectionCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, true);
914     }
915
916     return svritem;
917 }
918
919 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
920 {
921     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
922
923     ca_mutex_lock(g_mutexObjectList);
924
925     // close the socket and remove TCP connection info in list
926     if (svritem->fd >= 0)
927     {
928         close(svritem->fd);
929     }
930     u_arraylist_remove(caglobals.tcp.svrlist, index);
931     OICFree(svritem->recvData);
932
933     // pass the connection information to CA Common Layer.
934     if (g_connectionCallback)
935     {
936         g_connectionCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, false);
937     }
938
939     OICFree(svritem);
940     ca_mutex_unlock(g_mutexObjectList);
941
942     return CA_STATUS_OK;
943 }
944
945 void CATCPDisconnectAll()
946 {
947     ca_mutex_lock(g_mutexObjectList);
948     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
949
950     CATCPSessionInfo_t *svritem = NULL;
951     for (size_t i = 0; i < length; i++)
952     {
953         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
954         if (svritem && svritem->fd >= 0)
955         {
956             shutdown(svritem->fd, SHUT_RDWR);
957             close(svritem->fd);
958             OICFree(svritem->recvData);
959         }
960     }
961     u_arraylist_destroy(caglobals.tcp.svrlist);
962     ca_mutex_unlock(g_mutexObjectList);
963 }
964
965 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
966 {
967     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
968     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
969
970     // get connection info from list
971     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
972     for (size_t i = 0; i < length; i++)
973     {
974         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
975                 caglobals.tcp.svrlist, i);
976         if (!svritem)
977         {
978             continue;
979         }
980
981         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
982                      sizeof(svritem->sep.endpoint.addr))
983                 && (svritem->sep.endpoint.port == endpoint->port)
984                 && (svritem->sep.endpoint.flags & endpoint->flags))
985         {
986             *index = i;
987             return svritem;
988         }
989     }
990
991     return NULL;
992 }
993
994 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
995 {
996     ca_mutex_lock(g_mutexObjectList);
997
998     // check from the last item.
999     CATCPSessionInfo_t *svritem = NULL;
1000     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1001     for (size_t i = 0; i < length; i++)
1002     {
1003         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1004
1005         if (svritem && svritem->fd == fd)
1006         {
1007             *index = i;
1008             ca_mutex_unlock(g_mutexObjectList);
1009             return svritem;
1010         }
1011     }
1012
1013     ca_mutex_unlock(g_mutexObjectList);
1014
1015     return NULL;
1016 }
1017
1018 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1019 {
1020     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1021
1022     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
1023             ((unsigned char *)recvBuffer)[0] >> 4);
1024     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1025                                                         transport);
1026     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1027
1028     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
1029     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
1030     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
1031
1032     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1033     return headerLen + optPaylaodLen;
1034 }
1035
1036 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1037 {
1038     g_TCPErrorHandler = errorHandleCallback;
1039 }