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