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