TCPServer's CAReceiveMessage fix
[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
46 #ifdef __WITH_TLS__
47 #include "ca_adapter_net_tls.h"
48 #endif
49
50 /**
51  * Logging tag for module name.
52  */
53 #define TAG "OIC_CA_TCP_SERVER"
54
55 /**
56  * Maximum CoAP over TCP header length
57  * to know the total data length.
58  */
59 #define COAP_MAX_HEADER_SIZE  6
60
61 /**
62  * TLS header size
63  */
64 #define TLS_HEADER_SIZE 5
65
66 /**
67  * Mutex to synchronize device object list.
68  */
69 static ca_mutex g_mutexObjectList = NULL;
70
71 /**
72  * Conditional mutex to synchronize.
73  */
74 static ca_cond g_condObjectList = NULL;
75
76 /**
77  * Maintains the callback to be notified when data received from remote device.
78  */
79 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
80
81 /**
82  * Error callback to update error in TCP.
83  */
84 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
85
86 /**
87  * Connected Callback to pass the connection information to RI.
88  */
89 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
90
91 static CAResult_t CATCPCreateMutex();
92 static void CATCPDestroyMutex();
93 static CAResult_t CATCPCreateCond();
94 static void CATCPDestroyCond();
95 static int CACreateAcceptSocket(int family, CASocket_t *sock);
96 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
97 static void CAFindReadyMessage();
98 static void CASelectReturned(fd_set *readFds);
99 static void CAReceiveMessage(int fd);
100 static void CAReceiveHandler(void *data);
101 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
102
103 #define CHECKFD(FD) \
104     if (FD > caglobals.tcp.maxfd) \
105         caglobals.tcp.maxfd = FD;
106
107 /**
108  * Read length amount of data from socket item->fd
109  * Can read less data length then requested
110  * Actual read length added to item->len variable
111  *
112  * @param[in/out] item - used socket, buffer and to update received message length
113  * @param[in]  length  - length of data required to read
114  * @param[in]  flags   - additional info about socket
115  * @return             - CA_STATUS_OK or appropriate error code
116  */
117 static CAResult_t CARecv(CATCPSessionInfo_t *item, size_t length, int flags)
118 {
119     if (NULL == item)
120     {
121         return CA_STATUS_INVALID_PARAM;
122     }
123
124     //skip read operation if requested zero length
125     if (0 == length)
126     {
127         return CA_STATUS_OK;
128     }
129
130     unsigned char *buffer = item->data + item->len;
131
132     int len = recv(item->fd, buffer, length, flags);
133
134     if (len < 0)
135     {
136         OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
137         return CA_RECEIVE_FAILED;
138     }
139     else if (0 == len)
140     {
141         OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
142         return CA_DESTINATION_DISCONNECTED;
143     }
144
145     OIC_LOG_V(DEBUG, TAG, "recv len = %d", len);
146     OIC_LOG_BUFFER(DEBUG, TAG, buffer, len);
147
148     item->len += len;
149
150     return CA_STATUS_OK;
151 }
152
153 static void CATCPDestroyMutex()
154 {
155     if (g_mutexObjectList)
156     {
157         ca_mutex_free(g_mutexObjectList);
158         g_mutexObjectList = NULL;
159     }
160 }
161
162 static CAResult_t CATCPCreateMutex()
163 {
164     if (!g_mutexObjectList)
165     {
166         g_mutexObjectList = ca_mutex_new();
167         if (!g_mutexObjectList)
168         {
169             OIC_LOG(ERROR, TAG, "Failed to created mutex!");
170             return CA_STATUS_FAILED;
171         }
172     }
173
174     return CA_STATUS_OK;
175 }
176
177 static void CATCPDestroyCond()
178 {
179     if (g_condObjectList)
180     {
181         ca_cond_free(g_condObjectList);
182         g_condObjectList = NULL;
183     }
184 }
185
186 static CAResult_t CATCPCreateCond()
187 {
188     if (!g_condObjectList)
189     {
190         g_condObjectList = ca_cond_new();
191         if (!g_condObjectList)
192         {
193             OIC_LOG(ERROR, TAG, "Failed to created cond!");
194             return CA_STATUS_FAILED;
195         }
196     }
197     return CA_STATUS_OK;
198 }
199
200 static void CAReceiveHandler(void *data)
201 {
202     (void)data;
203     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
204
205     while (!caglobals.tcp.terminate)
206     {
207         CAFindReadyMessage();
208     }
209
210     ca_mutex_lock(g_mutexObjectList);
211     ca_cond_signal(g_condObjectList);
212     ca_mutex_unlock(g_mutexObjectList);
213
214     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
215 }
216
217 static void CAFindReadyMessage()
218 {
219     fd_set readFds;
220     struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
221
222     FD_ZERO(&readFds);
223
224     if (-1 != caglobals.tcp.ipv4.fd)
225     {
226         FD_SET(caglobals.tcp.ipv4.fd, &readFds);
227     }
228     if (-1 != caglobals.tcp.ipv6.fd)
229     {
230         FD_SET(caglobals.tcp.ipv6.fd, &readFds);
231     }
232     if (-1 != caglobals.tcp.shutdownFds[0])
233     {
234         FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
235     }
236     if (-1 != caglobals.tcp.connectionFds[0])
237     {
238         FD_SET(caglobals.tcp.connectionFds[0], &readFds);
239     }
240
241     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
242     for (size_t i = 0; i < length; i++)
243     {
244         CATCPSessionInfo_t *svritem =
245                 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
246         if (svritem && 0 <= svritem->fd)
247         {
248             FD_SET(svritem->fd, &readFds);
249         }
250     }
251
252     int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
253
254     if (caglobals.tcp.terminate)
255     {
256         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
257         return;
258     }
259     if (0 >= ret)
260     {
261         if (0 > ret)
262         {
263             OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
264         }
265         return;
266     }
267
268     CASelectReturned(&readFds);
269 }
270
271 static void CASelectReturned(fd_set *readFds)
272 {
273     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
274
275     if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
276     {
277         CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
278         return;
279     }
280     else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
281     {
282         CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
283         return;
284     }
285     else if (-1 != caglobals.tcp.connectionFds[0] &&
286             FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
287     {
288         // new connection was created from remote device.
289         // exit the function to update read file descriptor.
290         char buf[MAX_ADDR_STR_SIZE_CA] = {0};
291         ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
292         if (-1 == len)
293         {
294             return;
295         }
296         OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
297         FD_CLR(caglobals.tcp.connectionFds[0], readFds);
298         return;
299     }
300     else
301     {
302         uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
303         for (size_t i = 0; i < length; i++)
304         {
305             CATCPSessionInfo_t *svritem =
306                     (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
307             if (svritem && svritem->fd >= 0)
308             {
309                 if (FD_ISSET(svritem->fd, readFds))
310                 {
311                     CAReceiveMessage(svritem->fd);
312                     FD_CLR(svritem->fd, readFds);
313                 }
314             }
315         }
316     }
317 }
318
319 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
320 {
321     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
322
323     struct sockaddr_storage clientaddr;
324     socklen_t clientlen = sizeof (struct sockaddr_in);
325     if (flag & CA_IPV6)
326     {
327         clientlen = sizeof(struct sockaddr_in6);
328     }
329
330     int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
331     if (-1 != sockfd)
332     {
333         CATCPSessionInfo_t *svritem =
334                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
335         if (!svritem)
336         {
337             OIC_LOG(ERROR, TAG, "Out of memory");
338             close(sockfd);
339             return;
340         }
341
342         svritem->fd = sockfd;
343         svritem->sep.endpoint.flags = flag;
344         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
345                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
346
347         ca_mutex_lock(g_mutexObjectList);
348         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
349         if (!result)
350         {
351             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
352             close(sockfd);
353             OICFree(svritem);
354             ca_mutex_unlock(g_mutexObjectList);
355             return;
356         }
357         ca_mutex_unlock(g_mutexObjectList);
358
359         CHECKFD(sockfd);
360     }
361 }
362
363 #ifdef __WITH_TLS__
364 static bool CAIsTlsMessage(const CATCPSessionInfo_t * recvinfo)
365 {
366     if (recvinfo->data == NULL || recvinfo->len == 0)
367     {
368         OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
369         return false;
370     }
371
372     unsigned char first_byte = recvinfo->data[0];
373
374     //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
375     //handshake = [16], application_data = [17] in HEX
376     const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
377     size_t i = 0;
378
379     for (i = 0; i < sizeof(tls_head_type); i++)
380     {
381         if(tls_head_type[i] == first_byte)
382         {
383             return true;
384         }
385     }
386
387     return false;
388 }
389 #endif
390
391 /**
392  * Clean socket state data
393  *
394  * @param[in/out] item - socket state data
395  */
396 static void CACleanData(CATCPSessionInfo_t *svritem)
397 {
398     if (svritem)
399     {
400         OICFree(svritem->data);
401         svritem->data = NULL;
402         svritem->len = 0;
403         svritem->totalLen = 0;
404         svritem->protocol = UNKNOWN;
405     }
406 }
407
408 /**
409  * Read message header from socket item->fd
410  *
411  * @param[in/out] item - used socket, buffer, current received message length and protocol
412  * @return             - CA_STATUS_OK or appropriate error code
413  */
414 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
415 {
416     CAResult_t res = CA_STATUS_OK;
417
418     if (NULL == svritem)
419     {
420         return CA_STATUS_INVALID_PARAM;
421     }
422
423     if (NULL == svritem->data)
424     {
425         // allocate memory for message header (CoAP header size because it is bigger)
426         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
427         if (NULL == svritem->data)
428         {
429             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
430             return CA_MEMORY_ALLOC_FAILED;
431         }
432     }
433
434     //read data (assume TLS header) from remote device.
435     //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
436     res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
437
438     //return if any error occurs
439     if (CA_STATUS_OK != res)
440     {
441         return res;
442     }
443
444     //if not enough data received - read them on next CAReceiveMessage() call
445     if (svritem->len < TLS_HEADER_SIZE)
446     {
447         OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
448         return CA_STATUS_OK;
449     }
450
451     //if enough data received - parse header
452 #ifdef __WITH_TLS__
453     if (CAIsTlsMessage(svritem))
454     {
455         svritem->protocol = TLS;
456
457         //[3][4] bytes in tls header are tls payload length
458         unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
459         OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
460
461         svritem->totalLen = message_length + TLS_HEADER_SIZE;
462     }
463     else
464 #endif
465     {
466         svritem->protocol = COAP;
467
468         //seems CoAP data received. read full coap header.
469         coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
470
471         size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
472
473         if (svritem->len < headerLen)
474         {
475             //read required bytes to have full CoAP header
476             //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
477             res = CARecv(svritem, headerLen - svritem->len, 0);
478
479             //return if any error occurs
480             if (CA_STATUS_OK != res)
481             {
482                 return res;
483             }
484
485             //if not enough data received - read them on next CAReceiveMessage() call
486             if (svritem->len < headerLen)
487             {
488                 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
489                 return CA_STATUS_OK;
490             }
491         }
492
493         //calculate CoAP message length
494         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
495     }
496
497     unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
498     if (NULL == buffer)
499     {
500         OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
501         return CA_MEMORY_ALLOC_FAILED;
502     }
503     svritem->data = buffer;
504
505     return CA_STATUS_OK;
506 }
507
508 /**
509  * Read message payload from socket item->fd
510
511  *
512  * @param[in/out] item - used socket, buffer and to update received message length
513  * @return             - CA_STATUS_OK or appropriate error code
514  */
515 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
516 {
517     if (NULL == svritem)
518     {
519         return CA_STATUS_INVALID_PARAM;
520     }
521
522     return CARecv(svritem, svritem->totalLen - svritem->len, 0);
523 }
524
525 /**
526  * Pass received data to app layer depending on protocol
527  *
528  * @param[in/out] item - used buffer, received message length and protocol
529  */
530 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
531 {
532     if (NULL == svritem)
533     {
534         return;
535     }
536
537     switch(svritem->protocol)
538     {
539         case COAP:
540         {
541             if (g_packetReceivedCallback)
542             {
543                 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
544             }
545         }
546         break;
547         case TLS:
548 #ifdef __WITH_TLS__
549         {
550             int ret = CAdecryptTls(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
551
552             OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptTls returned %d", __func__, ret);
553         }
554         break;
555 #endif
556         case UNKNOWN: /* pass through */
557         default:
558             OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
559         break;
560     }
561 }
562
563 static void CAReceiveMessage(int fd)
564 {
565     CAResult_t res = CA_STATUS_OK;
566
567     //get remote device information from file descriptor.
568     size_t index = 0;
569     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
570     if (!svritem)
571     {
572         OIC_LOG(ERROR, TAG, "there is no connection information in list");
573         return;
574     }
575
576     //totalLen filled only when header fully read and parsed
577     if (0 == svritem->totalLen)
578     {
579         res = CAReadHeader(svritem);
580     }
581     else
582     {
583         res = CAReadPayload(svritem);
584
585         //when successfully read all required data - pass them to upper layer.
586         if (CA_STATUS_OK == res && svritem->len == svritem->totalLen)
587         {
588             CAExecuteRequest(svritem);
589             CACleanData(svritem);
590         }
591     }
592
593     //disconnect session and clean-up data if any error occurs
594     if (res != CA_STATUS_OK)
595     {
596         CADisconnectTCPSession(svritem, index);
597         CACleanData(svritem);
598     }
599 }
600
601 static void CAWakeUpForReadFdsUpdate(const char *host)
602 {
603     if (caglobals.tcp.connectionFds[1] != -1)
604     {
605         ssize_t len = 0;
606         do
607         {
608             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
609         } while ((len == -1) && (errno == EINTR));
610
611         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
612         {
613             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
614         }
615     }
616 }
617
618 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
619                                          struct sockaddr_storage *sockaddr)
620 {
621     struct addrinfo *addrs = NULL;
622     struct addrinfo hints = { .ai_family = family,
623                               .ai_protocol   = IPPROTO_TCP,
624                               .ai_socktype = SOCK_STREAM,
625                               .ai_flags = AI_NUMERICHOST };
626
627     int r = getaddrinfo(host, NULL, &hints, &addrs);
628     if (r)
629     {
630         if (EAI_SYSTEM == r)
631         {
632             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
633         }
634         else
635         {
636             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
637         }
638         freeaddrinfo(addrs);
639         return CA_STATUS_FAILED;
640     }
641     // assumption: in this case, getaddrinfo will only return one addrinfo
642     // or first is the one we want.
643     if (addrs[0].ai_family == AF_INET6)
644     {
645         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
646         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
647     }
648     else
649     {
650         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
651         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
652     }
653     freeaddrinfo(addrs);
654     return CA_STATUS_OK;
655 }
656
657 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
658 {
659     // #1. create tcp socket.
660     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
661     if (-1 == fd)
662     {
663         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
664         return -1;
665     }
666
667     // #2. convert address from string to binary.
668     struct sockaddr_storage sa = { .ss_family = family };
669     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
670                                             svritem->sep.endpoint.port, &sa);
671     if (CA_STATUS_OK != res)
672     {
673         close(fd);
674         return -1;
675     }
676
677     // #3. set socket length.
678     socklen_t socklen = 0;
679     if (sa.ss_family == AF_INET6)
680     {
681         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
682         if (!sock6->sin6_scope_id)
683         {
684             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
685         }
686         socklen = sizeof(struct sockaddr_in6);
687     }
688     else
689     {
690         socklen = sizeof(struct sockaddr_in);
691     }
692
693     // #4. connect to remote server device.
694     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
695     {
696         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
697         close(fd);
698         return -1;
699     }
700
701     OIC_LOG(DEBUG, TAG, "connect socket success");
702     CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
703     return fd;
704 }
705
706 static int CACreateAcceptSocket(int family, CASocket_t *sock)
707 {
708     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
709
710     if (sock->fd != -1)
711     {
712         OIC_LOG(DEBUG, TAG, "accept socket created already");
713         return sock->fd;
714     }
715
716     socklen_t socklen = 0;
717     struct sockaddr_storage server = { .ss_family = family };
718
719     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
720     if (fd < 0)
721     {
722         OIC_LOG(ERROR, TAG, "Failed to create socket");
723         goto exit;
724     }
725
726     if (family == AF_INET6)
727     {
728         // the socket is re‐stricted to sending and receiving IPv6 packets only.
729         int on = 1;
730         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
731         {
732             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
733             goto exit;
734         }
735         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
736         socklen = sizeof (struct sockaddr_in6);
737     }
738     else
739     {
740         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
741         socklen = sizeof (struct sockaddr_in);
742     }
743
744     int reuse = 1;
745     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
746     {
747         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
748         goto exit;
749     }
750
751     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
752     {
753         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
754         goto exit;
755     }
756
757     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
758     {
759         OIC_LOG(ERROR, TAG, "listen() error");
760         goto exit;
761     }
762
763     if (!sock->port)  // return the assigned port
764     {
765         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
766         {
767             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
768             goto exit;
769         }
770         sock->port = ntohs(family == AF_INET6 ?
771                       ((struct sockaddr_in6 *)&server)->sin6_port :
772                       ((struct sockaddr_in *)&server)->sin_port);
773     }
774
775     return fd;
776
777 exit:
778     if (fd >= 0)
779     {
780         close(fd);
781     }
782     return -1;
783 }
784
785 static void CAInitializePipe(int *fds)
786 {
787     int ret = pipe(fds);
788     if (-1 != ret)
789     {
790         ret = fcntl(fds[0], F_GETFD);
791         if (-1 != ret)
792         {
793             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
794         }
795         if (-1 != ret)
796         {
797             ret = fcntl(fds[1], F_GETFD);
798         }
799         if (-1 != ret)
800         {
801             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
802         }
803         if (-1 == ret)
804         {
805             close(fds[1]);
806             close(fds[0]);
807
808             fds[0] = -1;
809             fds[1] = -1;
810
811             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
812         }
813     }
814 }
815
816 #define NEWSOCKET(FAMILY, NAME) \
817     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
818     if (caglobals.tcp.NAME.fd == -1) \
819     { \
820         caglobals.tcp.NAME.port = 0; \
821         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
822     } \
823     CHECKFD(caglobals.tcp.NAME.fd);
824
825 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
826 {
827     if (caglobals.tcp.started)
828     {
829         return CA_STATUS_OK;
830     }
831
832     if (!caglobals.tcp.ipv4tcpenabled)
833     {
834         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
835     }
836     if (!caglobals.tcp.ipv6tcpenabled)
837     {
838         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
839     }
840
841     CAResult_t res = CATCPCreateMutex();
842     if (CA_STATUS_OK == res)
843     {
844         res = CATCPCreateCond();
845     }
846     if (CA_STATUS_OK != res)
847     {
848         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
849         return res;
850     }
851
852     ca_mutex_lock(g_mutexObjectList);
853     if (!caglobals.tcp.svrlist)
854     {
855         caglobals.tcp.svrlist = u_arraylist_create();
856     }
857     ca_mutex_unlock(g_mutexObjectList);
858
859     if (caglobals.server)
860     {
861         NEWSOCKET(AF_INET, ipv4);
862         NEWSOCKET(AF_INET6, ipv6);
863         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
864                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
865         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
866                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
867     }
868
869     // create pipe for fast shutdown
870     CAInitializePipe(caglobals.tcp.shutdownFds);
871     CHECKFD(caglobals.tcp.shutdownFds[0]);
872     CHECKFD(caglobals.tcp.shutdownFds[1]);
873
874     // create pipe for connection event
875     CAInitializePipe(caglobals.tcp.connectionFds);
876     CHECKFD(caglobals.tcp.connectionFds[0]);
877     CHECKFD(caglobals.tcp.connectionFds[1]);
878
879     caglobals.tcp.terminate = false;
880     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
881     if (CA_STATUS_OK != res)
882     {
883         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
884         return res;
885     }
886     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
887
888     caglobals.tcp.started = true;
889     return CA_STATUS_OK;
890 }
891
892 void CATCPStopServer()
893 {
894     // mutex lock
895     ca_mutex_lock(g_mutexObjectList);
896
897     // set terminate flag
898     caglobals.tcp.terminate = true;
899
900     if (caglobals.tcp.shutdownFds[1] != -1)
901     {
902         close(caglobals.tcp.shutdownFds[1]);
903         // receive thread will stop immediately
904     }
905
906     if (caglobals.tcp.connectionFds[1] != -1)
907     {
908         close(caglobals.tcp.connectionFds[1]);
909     }
910
911     if (caglobals.tcp.started)
912     {
913         ca_cond_wait(g_condObjectList, g_mutexObjectList);
914     }
915     caglobals.tcp.started = false;
916
917     // mutex unlock
918     ca_mutex_unlock(g_mutexObjectList);
919
920     if (-1 != caglobals.tcp.ipv4.fd)
921     {
922         close(caglobals.tcp.ipv4.fd);
923         caglobals.tcp.ipv4.fd = -1;
924     }
925
926     if (-1 != caglobals.tcp.ipv6.fd)
927     {
928         close(caglobals.tcp.ipv6.fd);
929         caglobals.tcp.ipv6.fd = -1;
930     }
931
932     CATCPDisconnectAll();
933     CATCPDestroyMutex();
934     CATCPDestroyCond();
935 }
936
937 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
938 {
939     g_packetReceivedCallback = callback;
940 }
941
942 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
943 {
944     g_connectionCallback = connHandler;
945 }
946
947 static size_t CACheckPayloadLength(const void *data, size_t dlen)
948 {
949     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
950
951     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
952             ((unsigned char *)data)[0] >> 4);
953
954     coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
955     if (!pdu)
956     {
957         OIC_LOG(ERROR, TAG, "outpdu is null");
958         return 0;
959     }
960
961     int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
962     if (0 >= ret)
963     {
964         OIC_LOG(ERROR, TAG, "pdu parse failed");
965         coap_delete_pdu(pdu);
966         return 0;
967     }
968
969     size_t payloadLen = 0;
970     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
971     OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
972               headerSize, pdu->length);
973     if (pdu->length > headerSize)
974     {
975         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
976     }
977
978     OICFree(pdu);
979
980     return payloadLen;
981 }
982
983 static void sendData(const CAEndpoint_t *endpoint, const void *data,
984                      size_t dlen, const char *fam)
985 {
986     // #1. get TCP Server object from list
987     size_t index = 0;
988     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
989     if (!svritem)
990     {
991         // if there is no connection info, connect to TCP Server
992         svritem = CAConnectTCPSession(endpoint);
993         if (!svritem)
994         {
995             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
996             if (g_tcpErrorHandler)
997             {
998                 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
999             }
1000             return;
1001         }
1002     }
1003
1004     // #2. check payload length
1005 #ifdef __WITH_TLS__
1006     if (false == CAIsTlsMessage(svritem))
1007 #endif
1008     {
1009         size_t payloadLen = CACheckPayloadLength(data, dlen);
1010         // if payload length is zero, disconnect from TCP server
1011         if (!payloadLen)
1012         {
1013             OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
1014             CADisconnectTCPSession(svritem, index);
1015             return;
1016         }
1017     }
1018
1019     // #3. check connection state
1020     if (svritem->fd < 0)
1021     {
1022         // if file descriptor value is wrong, remove TCP Server info from list
1023         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
1024         CADisconnectTCPSession(svritem, index);
1025         if (g_tcpErrorHandler)
1026         {
1027             g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1028         }
1029         return;
1030     }
1031
1032     // #4. send data to TCP Server
1033     ssize_t remainLen = dlen;
1034     do
1035     {
1036         ssize_t len = send(svritem->fd, data, remainLen, 0);
1037         if (-1 == len)
1038         {
1039             if (EWOULDBLOCK != errno)
1040             {
1041                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1042                 if (g_tcpErrorHandler)
1043                 {
1044                     g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1045                 }
1046                 return;
1047             }
1048             continue;
1049         }
1050         data += len;
1051         remainLen -= len;
1052     } while (remainLen > 0);
1053
1054     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1055 }
1056
1057 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1058                    bool isMulticast)
1059 {
1060     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1061     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1062
1063     if (!isMulticast)
1064     {
1065         if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1066         {
1067             sendData(endpoint, data, datalen, "ipv6");
1068         }
1069         if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1070         {
1071             sendData(endpoint, data, datalen, "ipv4");
1072         }
1073     }
1074 }
1075
1076 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1077 {
1078     VERIFY_NON_NULL(info, TAG, "info is NULL");
1079     VERIFY_NON_NULL(size, TAG, "size is NULL");
1080
1081     return CA_NOT_SUPPORTED;
1082 }
1083
1084 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
1085 {
1086     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1087
1088     // #1. create TCP server object
1089     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1090     if (!svritem)
1091     {
1092         OIC_LOG(ERROR, TAG, "Out of memory");
1093         return NULL;
1094     }
1095     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1096     svritem->sep.endpoint.adapter = endpoint->adapter;
1097     svritem->sep.endpoint.port = endpoint->port;
1098     svritem->sep.endpoint.flags = endpoint->flags;
1099     svritem->sep.endpoint.ifindex = endpoint->ifindex;
1100
1101     // #2. create the socket and connect to TCP server
1102     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1103     int fd = CATCPCreateSocket(family, svritem);
1104     if (-1 == fd)
1105     {
1106         OICFree(svritem);
1107         return NULL;
1108     }
1109
1110     // #3. add TCP connection info to list
1111     svritem->fd = fd;
1112     ca_mutex_lock(g_mutexObjectList);
1113     if (caglobals.tcp.svrlist)
1114     {
1115         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1116         if (!res)
1117         {
1118             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1119             close(svritem->fd);
1120             OICFree(svritem);
1121             ca_mutex_unlock(g_mutexObjectList);
1122             return NULL;
1123         }
1124     }
1125     ca_mutex_unlock(g_mutexObjectList);
1126
1127     CHECKFD(fd);
1128
1129     // pass the connection information to CA Common Layer.
1130     if (g_connectionCallback)
1131     {
1132         g_connectionCallback(&(svritem->sep.endpoint), true);
1133     }
1134
1135     return svritem;
1136 }
1137
1138 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
1139 {
1140     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
1141
1142     ca_mutex_lock(g_mutexObjectList);
1143
1144     // close the socket and remove TCP connection info in list
1145     if (svritem->fd >= 0)
1146     {
1147         close(svritem->fd);
1148     }
1149     u_arraylist_remove(caglobals.tcp.svrlist, index);
1150     OICFree(svritem->data);
1151     svritem->data = NULL;
1152
1153     // pass the connection information to CA Common Layer.
1154     if (g_connectionCallback)
1155     {
1156         g_connectionCallback(&(svritem->sep.endpoint), false);
1157     }
1158
1159     OICFree(svritem);
1160     ca_mutex_unlock(g_mutexObjectList);
1161
1162     return CA_STATUS_OK;
1163 }
1164
1165 void CATCPDisconnectAll()
1166 {
1167     ca_mutex_lock(g_mutexObjectList);
1168     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1169
1170     CATCPSessionInfo_t *svritem = NULL;
1171     for (size_t i = 0; i < length; i++)
1172     {
1173         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1174         if (svritem && svritem->fd >= 0)
1175         {
1176             shutdown(svritem->fd, SHUT_RDWR);
1177             close(svritem->fd);
1178
1179             OICFree(svritem->data);
1180             svritem->data = NULL;
1181         }
1182     }
1183     u_arraylist_destroy(caglobals.tcp.svrlist);
1184     ca_mutex_unlock(g_mutexObjectList);
1185 }
1186
1187 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1188 {
1189     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1190     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1191
1192     // get connection info from list
1193     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1194     for (size_t i = 0; i < length; i++)
1195     {
1196         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1197                 caglobals.tcp.svrlist, i);
1198         if (!svritem)
1199         {
1200             continue;
1201         }
1202
1203         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1204                      sizeof(svritem->sep.endpoint.addr))
1205                 && (svritem->sep.endpoint.port == endpoint->port)
1206                 && (svritem->sep.endpoint.flags & endpoint->flags))
1207         {
1208             *index = i;
1209             return svritem;
1210         }
1211     }
1212
1213     return NULL;
1214 }
1215
1216 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1217 {
1218     ca_mutex_lock(g_mutexObjectList);
1219
1220     // check from the last item.
1221     CATCPSessionInfo_t *svritem = NULL;
1222     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1223     for (size_t i = 0; i < length; i++)
1224     {
1225         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1226
1227         if (svritem && svritem->fd == fd)
1228         {
1229             *index = i;
1230             ca_mutex_unlock(g_mutexObjectList);
1231             return svritem;
1232         }
1233     }
1234
1235     ca_mutex_unlock(g_mutexObjectList);
1236
1237     return NULL;
1238 }
1239
1240 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1241 {
1242     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1243
1244     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
1245             ((unsigned char *)recvBuffer)[0] >> 4);
1246     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1247                                                         transport);
1248     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1249
1250     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1251     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1252     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1253
1254     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1255     return headerLen + optPaylaodLen;
1256 }
1257
1258 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1259 {
1260     g_tcpErrorHandler = errorHandleCallback;
1261 }