1 /* ****************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <sys/select.h>
24 #include <sys/ioctl.h>
26 #include <tinyara/config.h>
34 #include <arpa/inet.h>
35 #include <netinet/in.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
45 #include "catcpinterface.h"
46 #include "caipnwmonitor.h"
48 #include "caadapterutils.h"
50 #include "oic_malloc.h"
53 #include "ca_adapter_net_ssl.h"
57 * Logging tag for module name.
59 //#define TAG "OIC_CA_TCP_SERVER"
60 #define TAG TCP_SERVER_TAG
63 * Maximum CoAP over TCP header length
64 * to know the total data length.
66 #define COAP_MAX_HEADER_SIZE 6
71 #define TLS_HEADER_SIZE 5
74 * Max Connection Counts.
76 #define MAX_CONNECTION_COUNTS 500
78 #define COAP_TCP_MAX_BUFFER_CHUNK_SIZE 65530 //64kb - 6 (coap+tcp max header size)
83 static ca_thread_pool_t g_threadPool = NULL;
86 * Mutex to synchronize device object list.
88 static oc_mutex g_mutexObjectList = NULL;
91 * Conditional mutex to synchronize.
93 static oc_cond g_condObjectList = NULL;
96 * Maintains the callback to be notified when data received from remote device.
98 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
101 * Error callback to update error in TCP.
103 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
106 * Connected Callback to pass the connection information to RI.
108 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
110 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
111 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
112 static void CAFindReadyMessage();
113 static void CASelectReturned(fd_set *readFds);
114 static void CAReceiveMessage(int fd);
115 static void CAReceiveHandler(void *data);
116 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
117 static void CATCPInitializeSocket();
118 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index);
120 #define CHECKFD(FD) \
121 if (FD > caglobals.tcp.maxfd) \
122 caglobals.tcp.maxfd = FD;
124 #define CLOSE_SOCKET(TYPE) \
125 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
127 close(caglobals.tcp.TYPE.fd); \
128 caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
131 #define CA_FD_SET(TYPE, FDS) \
132 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
134 FD_SET(caglobals.tcp.TYPE.fd, FDS); \
137 void CATCPDestroyMutex()
139 if (g_mutexObjectList)
141 oc_mutex_free(g_mutexObjectList);
142 g_mutexObjectList = NULL;
146 CAResult_t CATCPCreateMutex()
148 if (!g_mutexObjectList)
150 g_mutexObjectList = oc_mutex_new();
151 if (!g_mutexObjectList)
153 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
154 return CA_STATUS_FAILED;
161 void CATCPDestroyCond()
163 if (g_condObjectList)
165 oc_cond_free(g_condObjectList);
166 g_condObjectList = NULL;
170 CAResult_t CATCPCreateCond()
172 if (!g_condObjectList)
174 g_condObjectList = oc_cond_new();
175 if (!g_condObjectList)
177 OIC_LOG(ERROR, TAG, "Failed to created cond!");
178 return CA_STATUS_FAILED;
184 static void CAReceiveHandler(void *data)
187 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
189 while (!caglobals.tcp.terminate)
191 CAFindReadyMessage();
194 oc_mutex_lock(g_mutexObjectList);
195 oc_cond_signal(g_condObjectList);
196 oc_mutex_unlock(g_mutexObjectList);
198 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
201 static void CAFindReadyMessage()
204 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
207 CA_FD_SET(ipv4, &readFds);
208 CA_FD_SET(ipv4s, &readFds);
209 CA_FD_SET(ipv6, &readFds);
210 CA_FD_SET(ipv6s, &readFds);
212 if (OC_INVALID_SOCKET != caglobals.tcp.shutdownFds[0])
214 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
217 if (OC_INVALID_SOCKET != caglobals.tcp.connectionFds[0])
219 FD_SET(caglobals.tcp.connectionFds[0], &readFds);
222 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
223 for (size_t i = 0; i < length; i++)
225 CATCPSessionInfo_t *svritem =
226 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
227 if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
229 FD_SET(svritem->fd, &readFds);
233 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
235 if (caglobals.tcp.terminate)
237 OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
244 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
249 CASelectReturned(&readFds);
252 static void CASelectReturned(fd_set *readFds)
254 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
256 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
258 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
261 else if (caglobals.tcp.ipv4s.fd != -1 && FD_ISSET(caglobals.tcp.ipv4s.fd, readFds))
263 CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
266 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
268 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
271 else if (caglobals.tcp.ipv6s.fd != -1 && FD_ISSET(caglobals.tcp.ipv6s.fd, readFds))
273 CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
276 else if (-1 != caglobals.tcp.connectionFds[0] &&
277 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
279 // new connection was created from remote device.
280 // exit the function to update read file descriptor.
281 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
282 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
287 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
292 int *readFDList = NULL;
293 size_t readFDListSize = 0;
295 oc_mutex_lock(g_mutexObjectList);
296 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
298 readFDList = (int*) OICCalloc(length, sizeof(int));
299 if (NULL == readFDList)
301 OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
302 oc_mutex_unlock(g_mutexObjectList);
306 for (size_t i = 0; i < length; i++)
308 CATCPSessionInfo_t *svritem =
309 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
310 if (svritem && svritem->fd >= 0)
312 if (FD_ISSET(svritem->fd, readFds))
314 readFDList[readFDListSize++] = svritem->fd;
318 oc_mutex_unlock(g_mutexObjectList);
320 // Read incomming messages from fds
321 for (size_t i = 0; i < readFDListSize; i++)
323 CAReceiveMessage(readFDList[i]);
330 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
332 OIC_LOG_V(INFO, TAG, "In %s", __func__);
333 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
335 if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
337 OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
339 sock->fd = OC_INVALID_SOCKET;
343 struct sockaddr_storage clientaddr;
344 socklen_t clientlen = sizeof (struct sockaddr_in);
347 clientlen = sizeof(struct sockaddr_in6);
350 CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
351 if (OC_INVALID_SOCKET != sockfd)
353 CATCPSessionInfo_t *svritem =
354 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
357 OIC_LOG(ERROR, TAG, "Out of memory");
362 svritem->fd = sockfd;
363 svritem->sep.endpoint.flags = flag;
364 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
365 svritem->state = CONNECTED;
366 svritem->isClient = false;
367 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
368 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
370 // Allocate message buffer
371 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
372 if (!svritem->tlsdata)
374 OIC_LOG(ERROR, TAG, "Out of memory");
380 oc_mutex_lock(g_mutexObjectList);
381 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
384 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
386 OICFree(svritem->tlsdata);
388 oc_mutex_unlock(g_mutexObjectList);
391 oc_mutex_unlock(g_mutexObjectList);
395 // pass the connection information to CA Common Layer.
396 if (g_connectionCallback)
398 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
401 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
405 * Clean socket state data
407 * @param[in/out] item - socket state data
409 void CACleanData(CATCPSessionInfo_t *svritem)
413 OICFree(svritem->data);
414 svritem->data = NULL;
419 svritem->totalLen = 0;
421 svritem->protocol = UNKNOWN;
426 * Construct CoAP header and payload from buffer
428 * @param[in] svritem - used socket, buffer, current received message length and protocol
429 * @param[in/out] data - data buffer, this value is updated as data is copied to svritem
430 * @param[in/out] dataLength - length of data, this value decreased as data is copied to svritem
431 * @return - CA_STATUS_OK or appropriate error code
433 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
436 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
438 if (NULL == svritem || NULL == data || NULL == dataLength)
440 OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
441 return CA_STATUS_INVALID_PARAM;
444 unsigned char *inBuffer = *data;
445 size_t inLen = *dataLength;
446 OIC_LOG_V(DEBUG, TAG, "before-datalength : %u", *dataLength);
448 if (NULL == svritem->data && inLen > 0)
450 // allocate memory for message header (CoAP header size because it is bigger)
451 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
452 if (NULL == svritem->data)
454 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
455 return CA_MEMORY_ALLOC_FAILED;
458 // copy 1 byte to parse coap header length
459 memcpy(svritem->data, inBuffer, 1);
461 svritem->bufLen = COAP_MAX_HEADER_SIZE;
466 //if not enough data received - read them on next CAFillHeader() call
472 //if enough data received - parse header
473 svritem->protocol = COAP;
475 //seems CoAP data received. read full coap header.
476 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
477 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
481 if (svritem->len < headerLen)
483 copyLen = headerLen - svritem->len;
489 //read required bytes to have full CoAP header
490 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
491 svritem->len += copyLen;
495 //if not enough data received - read them on next CAFillHeader() call
496 if (svritem->len < headerLen)
500 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
504 //calculate CoAP message length
505 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
511 // Calculate length of data to be copied.
512 copyLen = svritem->totalLen - svritem->len;
518 // Is buffer not big enough for remaining data ?
519 if (svritem->len + copyLen > svritem->bufLen)
521 // Resize buffer to accommodate enough space
522 size_t extLen = svritem->totalLen - svritem->bufLen;
523 if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
525 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
528 // Allocate required memory
529 unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
532 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
533 return CA_MEMORY_ALLOC_FAILED;
536 svritem->data = buffer;
537 svritem->bufLen += extLen;
540 // Read required bytes to have full CoAP payload
541 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
542 svritem->len += copyLen;
550 OIC_LOG_V(DEBUG, TAG, "after-datalength : %u", *dataLength);
551 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
555 static void CAReceiveMessage(int fd)
557 CAResult_t res = CA_STATUS_OK;
559 oc_mutex_lock(g_mutexObjectList);
561 //get remote device information from file descriptor.
563 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
566 OIC_LOG(ERROR, TAG, "there is no connection information in list");
567 oc_mutex_unlock(g_mutexObjectList);
571 CASecureEndpoint_t peerEP = svritem->sep;
573 if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection
575 svritem->protocol = TLS;
579 size_t tlsLength = 0;
581 if (TLS_HEADER_SIZE > svritem->tlsLen)
583 nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
587 //[3][4] bytes in tls header are tls payload length
588 tlsLength = TLS_HEADER_SIZE +
589 (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
590 OIC_LOG_V(DEBUG, TAG, "total tls length = %u", tlsLength);
591 if (tlsLength > TLS_DATA_MAX_SIZE)
593 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
595 oc_mutex_unlock(g_mutexObjectList);
596 CATCPDisconnectSession(&peerEP.endpoint);
599 nbRead = tlsLength - svritem->tlsLen;
602 len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
605 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
606 res = CA_RECEIVE_FAILED;
610 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
611 svritem->state = DISCONNECTED;
612 res = CA_DESTINATION_DISCONNECTED;
616 svritem->tlsLen += len;
617 OIC_LOG_V(DEBUG, TAG, "nb_read : %u bytes , recv() : %d bytes, svritem->tlsLen : %u bytes",
618 nbRead, len, svritem->tlsLen);
619 if (tlsLength > 0 && tlsLength == svritem->tlsLen)
621 // When successfully read data - pass them to callback.
622 // Dont invoke callback locking mutex
623 unsigned char *mesBuf = svritem->tlsdata;
624 size_t mesBufLen = svritem->tlsLen;
625 svritem->tlsdata = NULL;
626 oc_mutex_unlock(g_mutexObjectList);
628 res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen);
629 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
631 // Check for the svritem and reset buffer
632 oc_mutex_lock(g_mutexObjectList);
633 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
636 svritem->tlsdata = mesBuf;
641 // svritem does not exist, thus free the message buffer
642 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
649 else // Non-Secure connection
651 svritem->protocol = COAP;
653 // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
654 len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0);
657 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
658 res = CA_RECEIVE_FAILED;
662 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
663 res = CA_DESTINATION_DISCONNECTED;
667 //when successfully read data - pass them to callback.
668 OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
669 if (g_packetReceivedCallback)
671 // Dont invoke callback locking mutex
672 unsigned char *mesBuf = svritem->tlsdata;
673 svritem->tlsdata = NULL;
674 oc_mutex_unlock(g_mutexObjectList);
676 res = g_packetReceivedCallback(&peerEP, mesBuf, len);
678 // Check for the svritem and reset buffer
679 oc_mutex_lock(g_mutexObjectList);
680 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
683 svritem->tlsdata = mesBuf;
688 // svritem does not exist, thus free the message buffer
689 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
696 oc_mutex_unlock(g_mutexObjectList);
698 if (res != CA_STATUS_OK)
700 CATCPDisconnectSession(&peerEP.endpoint);
704 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
706 if (caglobals.tcp.connectionFds[1] != -1)
711 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
712 } while ((len == -1) && (errno == EINTR));
714 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
716 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
723 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
724 struct sockaddr_storage *sockaddr)
726 struct addrinfo *addrs = NULL;
727 struct addrinfo hints = { .ai_family = family,
728 .ai_protocol = IPPROTO_TCP,
729 .ai_socktype = SOCK_STREAM,
730 .ai_flags = AI_NUMERICHOST };
732 int r = getaddrinfo(host, NULL, &hints, &addrs);
737 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
741 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
744 return CA_STATUS_FAILED;
746 // assumption: in this case, getaddrinfo will only return one addrinfo
747 // or first is the one we want.
748 if (addrs[0].ai_family == AF_INET6)
750 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
751 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
755 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
756 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
762 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
764 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
766 OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
767 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
769 // #1. create tcp socket.
770 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
773 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
774 return CA_SOCKET_OPERATION_FAILED;
778 // #2. convert address from string to binary.
779 struct sockaddr_storage sa = { .ss_family = family };
780 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
781 svritem->sep.endpoint.port, &sa);
782 if (CA_STATUS_OK != res)
784 OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
785 return CA_SOCKET_OPERATION_FAILED;
788 // #3. set socket length.
789 socklen_t socklen = 0;
790 if (sa.ss_family == AF_INET6)
792 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
793 if (!sock6->sin6_scope_id)
795 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
797 socklen = sizeof(struct sockaddr_in6);
801 socklen = sizeof(struct sockaddr_in);
804 // #4. connect to remote server device.
805 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
807 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
808 CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
809 svritem->sep.endpoint.port, 0, false, strerror(errno));
810 return CA_SOCKET_OPERATION_FAILED;
813 OIC_LOG(INFO, TAG, "connect socket success");
814 svritem->state = CONNECTED;
815 CHECKFD(svritem->fd);
816 ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
819 OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
820 return CA_SOCKET_OPERATION_FAILED;
825 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
827 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
829 if (OC_INVALID_SOCKET != sock->fd)
831 OIC_LOG(DEBUG, TAG, "accept socket created already");
835 socklen_t socklen = 0;
836 struct sockaddr_storage server = { .ss_family = family };
838 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
839 if (OC_INVALID_SOCKET == fd)
841 OIC_LOG(ERROR, TAG, "Failed to create socket");
845 if (family == AF_INET6)
847 // the socket is restricted to sending and receiving IPv6 packets only.
849 //TODO: enable once IPv6 is supported
851 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
853 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
857 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
858 socklen = sizeof (struct sockaddr_in6);
862 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
863 socklen = sizeof (struct sockaddr_in);
867 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
869 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
873 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
875 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
879 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
881 OIC_LOG(ERROR, TAG, "listen() error");
885 if (sock->port) // use the given port
888 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
890 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
892 return OC_INVALID_SOCKET;
895 else // return the assigned port
897 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
899 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
902 sock->port = ntohs(family == AF_INET6 ?
903 ((struct sockaddr_in6 *)&server)->sin6_port :
904 ((struct sockaddr_in *)&server)->sin_port);
914 return OC_INVALID_SOCKET;
917 static void CAInitializePipe(int *fds)
920 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
921 /* Temporary workaround: By pass F_GETFD / F_SETFD */
931 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
936 ret = fcntl(fds[0], F_GETFD);
939 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
943 ret = fcntl(fds[1], F_GETFD);
947 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
957 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
963 #define NEWSOCKET(FAMILY, NAME) \
964 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
965 if (caglobals.tcp.NAME.fd == -1) \
967 caglobals.tcp.NAME.port = 0; \
968 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
970 CHECKFD(caglobals.tcp.NAME.fd);
972 void CATCPInitializeSocket()
975 NEWSOCKET(AF_INET, ipv4);
977 NEWSOCKET(AF_INET, ipv4s);
980 //TODO Enable once TizenRT supports IPv6
983 NEWSOCKET(AF_INET6, ipv6);
985 NEWSOCKET(AF_INET6, ipv6s);
989 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
990 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
991 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
992 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
994 OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
995 caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
996 OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
997 caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1001 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1003 oc_mutex_lock(g_mutexObjectList);
1004 if (caglobals.tcp.started)
1006 oc_mutex_unlock(g_mutexObjectList);
1007 OIC_LOG(INFO, TAG, "Adapter is started already");
1008 return CA_STATUS_OK;
1011 g_threadPool = threadPool;
1013 if (!caglobals.tcp.ipv4tcpenabled)
1015 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
1017 if (!caglobals.tcp.ipv6tcpenabled)
1019 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
1022 caglobals.tcp.terminate = false;
1023 if (!caglobals.tcp.svrlist)
1025 caglobals.tcp.svrlist = u_arraylist_create();
1028 if (caglobals.server)
1030 CATCPInitializeSocket();
1033 // create pipe for fast shutdown
1034 CAInitializePipe(caglobals.tcp.shutdownFds);
1035 CHECKFD(caglobals.tcp.shutdownFds[0]);
1036 CHECKFD(caglobals.tcp.shutdownFds[1]);
1038 // create pipe for connection event
1039 CAInitializePipe(caglobals.tcp.connectionFds);
1040 CHECKFD(caglobals.tcp.connectionFds[0]);
1041 CHECKFD(caglobals.tcp.connectionFds[1]);
1043 CAResult_t res = CA_STATUS_OK;
1045 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL);
1047 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1048 "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1050 if (CA_STATUS_OK != res)
1052 oc_mutex_unlock(g_mutexObjectList);
1053 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1058 caglobals.tcp.started = true;
1059 oc_mutex_unlock(g_mutexObjectList);
1061 OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1062 return CA_STATUS_OK;
1065 void CATCPStopServer()
1067 oc_mutex_lock(g_mutexObjectList);
1068 if (caglobals.tcp.terminate)
1070 oc_mutex_unlock(g_mutexObjectList);
1071 OIC_LOG(INFO, TAG, "Adapter is not enabled");
1075 // set terminate flag.
1076 caglobals.tcp.terminate = true;
1079 if (caglobals.tcp.started)
1081 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1082 caglobals.tcp.started = false;
1086 // close accept socket.
1087 #ifndef __WITH_TLS__
1091 CLOSE_SOCKET(ipv4s);
1092 CLOSE_SOCKET(ipv6s);
1095 close(caglobals.tcp.connectionFds[1]);
1096 close(caglobals.tcp.connectionFds[0]);
1097 caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1098 caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1100 if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1102 close(caglobals.tcp.shutdownFds[1]);
1103 caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1104 // receive thread will stop immediately
1106 if (caglobals.tcp.started)
1108 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1109 caglobals.tcp.started = false;
1111 if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1113 close(caglobals.tcp.shutdownFds[0]);
1114 caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1117 oc_mutex_unlock(g_mutexObjectList);
1119 CATCPDisconnectAll();
1122 OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1125 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1127 g_packetReceivedCallback = callback;
1130 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1132 g_connectionCallback = connHandler;
1135 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1137 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1139 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1140 ((unsigned char *)data)[0] >> 4);
1142 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1145 OIC_LOG(ERROR, TAG, "outpdu is null");
1146 OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1150 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1153 OIC_LOG(ERROR, TAG, "pdu parse failed");
1154 coap_delete_pdu(pdu);
1158 size_t payloadLen = 0;
1159 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1160 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1161 headerSize, pdu->length);
1162 if (pdu->length > headerSize)
1164 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1172 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1173 size_t dlen, const char *fam)
1175 OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1177 // #1. find a session info from list.
1178 CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1179 if (OC_INVALID_SOCKET == sockFd)
1181 // if there is no connection info, connect to remote device.
1182 sockFd = CAConnectTCPSession(endpoint);
1183 if (OC_INVALID_SOCKET == sockFd)
1185 OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1190 // #2. send data to remote device.
1191 ssize_t remainLen = dlen;
1192 size_t sendCounter = 0;
1196 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1198 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1202 if (EWOULDBLOCK != errno && EAGAIN != errno)
1204 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1205 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1206 len, false, strerror(errno));
1210 OIC_LOG_V(WARNING, TAG, "send blocked. trying %zu attempt from 25", sendCounter);
1211 if(sendCounter >= 25)
1219 } while (remainLen > 0);
1224 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1225 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1230 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1232 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1233 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1235 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1237 return sendData(endpoint, data, datalen, "ipv6");
1239 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1241 return sendData(endpoint, data, datalen, "ipv4");
1244 OIC_LOG(ERROR, TAG, "Not supported transport flags");
1248 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1250 VERIFY_NON_NULL(info, TAG, "info is NULL");
1251 VERIFY_NON_NULL(size, TAG, "size is NULL");
1253 return CA_NOT_SUPPORTED;
1256 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1258 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1260 // #1. create TCP server object
1261 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1264 OIC_LOG(ERROR, TAG, "Out of memory");
1265 return OC_INVALID_SOCKET;
1267 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1268 svritem->sep.endpoint.adapter = endpoint->adapter;
1269 svritem->sep.endpoint.port = endpoint->port;
1270 svritem->sep.endpoint.flags = endpoint->flags;
1271 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1272 svritem->state = CONNECTING;
1273 svritem->isClient = true;
1275 // Allocate message buffer
1276 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1277 if (!svritem->tlsdata)
1279 OIC_LOG(ERROR, TAG, "Out of memory");
1281 return OC_INVALID_SOCKET;
1284 // #2. add TCP connection info to list
1285 oc_mutex_lock(g_mutexObjectList);
1286 if (caglobals.tcp.svrlist)
1288 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1291 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1293 OICFree(svritem->tlsdata);
1295 oc_mutex_unlock(g_mutexObjectList);
1296 return OC_INVALID_SOCKET;
1299 oc_mutex_unlock(g_mutexObjectList);
1301 // #3. create the socket and connect to TCP server
1302 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1303 if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1305 return OC_INVALID_SOCKET;
1308 // #4. pass the connection information to CA Common Layer.
1309 if (g_connectionCallback)
1311 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1317 CAResult_t CADisconnectTCPSession(size_t index)
1319 CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1322 OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1323 return CA_STATUS_OK;
1326 // close the socket and remove session info in list.
1327 if (removedData->fd >= 0)
1329 shutdown(removedData->fd, SHUT_RDWR);
1330 close(removedData->fd);
1331 removedData->fd = -1;
1332 removedData->state = (CONNECTED == removedData->state) ?
1333 DISCONNECTED : removedData->state;
1335 // pass the connection information to CA Common Layer.
1336 if (g_connectionCallback && DISCONNECTED == removedData->state)
1338 g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1341 OICFree(removedData->data);
1342 removedData->data = NULL;
1344 OICFree(removedData->tlsdata);
1345 removedData->tlsdata = NULL;
1347 OICFree(removedData);
1350 OIC_LOG(DEBUG, TAG, "data is removed from session list");
1352 if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1354 CATCPInitializeSocket();
1356 return CA_STATUS_OK;
1359 void CATCPDisconnectAll()
1361 OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1363 oc_mutex_lock(g_mutexObjectList);
1365 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1366 for (ssize_t index = length; index > 0; index--)
1368 // disconnect session from remote device.
1369 CADisconnectTCPSession(index - 1);
1372 u_arraylist_destroy(caglobals.tcp.svrlist);
1373 caglobals.tcp.svrlist = NULL;
1375 oc_mutex_unlock(g_mutexObjectList);
1378 CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1381 OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1384 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1386 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1387 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1389 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1391 // get connection info from list
1392 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1393 for (size_t i = 0; i < length; i++)
1395 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1396 caglobals.tcp.svrlist, i);
1402 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1403 sizeof(svritem->sep.endpoint.addr))
1404 && (svritem->sep.endpoint.port == endpoint->port)
1405 && (svritem->sep.endpoint.flags & endpoint->flags))
1407 OIC_LOG(DEBUG, TAG, "Found in session list");
1413 OIC_LOG(DEBUG, TAG, "Session not found");
1417 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1419 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1421 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1423 // get connection info from list.
1424 oc_mutex_lock(g_mutexObjectList);
1425 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1426 for (size_t i = 0; i < length; i++)
1428 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1429 caglobals.tcp.svrlist, i);
1435 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1436 sizeof(svritem->sep.endpoint.addr))
1437 && (svritem->sep.endpoint.port == endpoint->port)
1438 && (svritem->sep.endpoint.flags & endpoint->flags))
1440 oc_mutex_unlock(g_mutexObjectList);
1441 OIC_LOG(DEBUG, TAG, "Found in session list");
1446 oc_mutex_unlock(g_mutexObjectList);
1447 OIC_LOG(DEBUG, TAG, "Session not found");
1448 return OC_INVALID_SOCKET;
1451 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1454 // check from the last item.
1455 CATCPSessionInfo_t *svritem = NULL;
1456 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1457 for (size_t i = 0; i < length; i++)
1459 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1461 if (svritem && svritem->fd == fd)
1464 oc_mutex_unlock(g_mutexObjectList);
1473 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1475 CATCPSessionInfo_t *svritem = NULL;
1476 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1477 for (size_t i = 0; i < length; i++)
1479 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1481 if (svritem && svritem->fd == fd)
1491 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1493 oc_mutex_lock(g_mutexObjectList);
1495 CAResult_t result = CA_STATUS_OK;
1497 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1500 result = CADisconnectTCPSession(index);
1501 if (CA_STATUS_OK != result)
1503 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1507 oc_mutex_unlock(g_mutexObjectList);
1511 void CATCPCloseInProgressConnections()
1513 OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1515 oc_mutex_lock(g_mutexObjectList);
1517 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1518 for (size_t index = 0; index < length; index++)
1520 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1521 caglobals.tcp.svrlist, index);
1527 // Session which are connecting state
1528 if (svritem->fd >= 0 && svritem->state == CONNECTING)
1530 shutdown(svritem->fd, SHUT_RDWR);
1533 svritem->state = DISCONNECTED;
1537 oc_mutex_unlock(g_mutexObjectList);
1539 OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1542 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1544 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1546 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1547 ((unsigned char *)recvBuffer)[0] >> 4);
1548 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1550 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1552 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1553 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1554 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1556 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1557 return headerLen + optPaylaodLen;
1560 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1562 g_tcpErrorHandler = errorHandleCallback;