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