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
81 static ca_thread_pool_t g_threadPool = NULL;
84 * An unique identifier of receive thread.
86 static uint32_t g_recvThreadId = 0;
89 * Mutex to synchronize device object list.
91 static oc_mutex g_mutexObjectList = NULL;
94 * Conditional mutex to synchronize.
96 static oc_cond g_condObjectList = NULL;
99 * Maintains the callback to be notified when data received from remote device.
101 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
104 * Error callback to update error in TCP.
106 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
109 * Connected Callback to pass the connection information to RI.
111 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
113 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
114 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
115 static void CAFindReadyMessage();
116 static void CASelectReturned(fd_set *readFds);
117 static void CAReceiveMessage(int fd);
118 static void CAReceiveHandler(void *data);
119 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
120 static void CATCPInitializeSocket();
122 #define CHECKFD(FD) \
123 if (FD > caglobals.tcp.maxfd) \
124 caglobals.tcp.maxfd = FD;
126 #define CLOSE_SOCKET(TYPE) \
127 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
129 close(caglobals.tcp.TYPE.fd); \
130 caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
133 #define CA_FD_SET(TYPE, FDS) \
134 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
136 FD_SET(caglobals.tcp.TYPE.fd, FDS); \
139 void CATCPDestroyMutex()
141 if (g_mutexObjectList)
143 oc_mutex_free(g_mutexObjectList);
144 g_mutexObjectList = NULL;
148 CAResult_t CATCPCreateMutex()
150 if (!g_mutexObjectList)
152 g_mutexObjectList = oc_mutex_new();
153 if (!g_mutexObjectList)
155 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
156 return CA_STATUS_FAILED;
163 void CATCPDestroyCond()
165 if (g_condObjectList)
167 oc_cond_free(g_condObjectList);
168 g_condObjectList = NULL;
172 CAResult_t CATCPCreateCond()
174 if (!g_condObjectList)
176 g_condObjectList = oc_cond_new();
177 if (!g_condObjectList)
179 OIC_LOG(ERROR, TAG, "Failed to created cond!");
180 return CA_STATUS_FAILED;
186 static void CAReceiveHandler(void *data)
189 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
191 while (!caglobals.tcp.terminate)
193 CAFindReadyMessage();
196 oc_mutex_lock(g_mutexObjectList);
197 oc_cond_signal(g_condObjectList);
198 oc_mutex_unlock(g_mutexObjectList);
200 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
203 static void CAFindReadyMessage()
206 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
209 CA_FD_SET(ipv4, &readFds);
210 CA_FD_SET(ipv4s, &readFds);
211 CA_FD_SET(ipv6, &readFds);
212 CA_FD_SET(ipv6s, &readFds);
214 if (OC_INVALID_SOCKET != caglobals.tcp.shutdownFds[0])
216 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
219 if (OC_INVALID_SOCKET != caglobals.tcp.connectionFds[0])
221 FD_SET(caglobals.tcp.connectionFds[0], &readFds);
224 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
225 for (size_t i = 0; i < length; i++)
227 CATCPSessionInfo_t *svritem =
228 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
229 if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
231 FD_SET(svritem->fd, &readFds);
235 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
237 if (caglobals.tcp.terminate)
239 OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
246 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
251 CASelectReturned(&readFds);
254 static void CASelectReturned(fd_set *readFds)
256 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
258 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
260 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
263 else if (caglobals.tcp.ipv4s.fd != -1 && FD_ISSET(caglobals.tcp.ipv4s.fd, readFds))
265 CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
268 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
270 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
273 else if (caglobals.tcp.ipv6s.fd != -1 && FD_ISSET(caglobals.tcp.ipv6s.fd, readFds))
275 CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
278 else if (-1 != caglobals.tcp.connectionFds[0] &&
279 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
281 // new connection was created from remote device.
282 // exit the function to update read file descriptor.
283 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
284 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
289 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
294 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
295 for (size_t i = 0; i < length; i++)
297 CATCPSessionInfo_t *svritem =
298 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
299 if (svritem && svritem->fd >= 0)
301 if (FD_ISSET(svritem->fd, readFds))
303 CAReceiveMessage(svritem->fd);
310 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
312 OIC_LOG_V(INFO, TAG, "In %s", __func__);
313 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
315 if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
317 OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
319 sock->fd = OC_INVALID_SOCKET;
323 struct sockaddr_storage clientaddr;
324 socklen_t clientlen = sizeof (struct sockaddr_in);
327 clientlen = sizeof(struct sockaddr_in6);
330 CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
331 if (OC_INVALID_SOCKET != sockfd)
333 CATCPSessionInfo_t *svritem =
334 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
337 OIC_LOG(ERROR, TAG, "Out of memory");
342 svritem->fd = sockfd;
343 svritem->sep.endpoint.flags = flag;
344 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
345 svritem->state = CONNECTED;
346 svritem->isClient = false;
347 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
348 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
350 oc_mutex_lock(g_mutexObjectList);
351 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
354 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
357 oc_mutex_unlock(g_mutexObjectList);
360 oc_mutex_unlock(g_mutexObjectList);
364 // pass the connection information to CA Common Layer.
365 if (g_connectionCallback)
367 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
370 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
374 * Clean socket state data
376 * @param[in/out] item - socket state data
378 void CACleanData(CATCPSessionInfo_t *svritem)
382 OICFree(svritem->data);
383 svritem->data = NULL;
388 svritem->totalLen = 0;
389 svritem->protocol = UNKNOWN;
394 * Construct CoAP header and payload from buffer
396 * @param[in] svritem - used socket, buffer, current received message length and protocol
397 * @param[in/out] data - data buffer, this value is updated as data is copied to svritem
398 * @param[in/out] dataLength - length of data, this value decreased as data is copied to svritem
399 * @return - CA_STATUS_OK or appropriate error code
401 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
404 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
406 if (NULL == svritem || NULL == data || NULL == dataLength)
408 OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
409 return CA_STATUS_INVALID_PARAM;
412 unsigned char *inBuffer = *data;
413 size_t inLen = *dataLength;
414 OIC_LOG_V(DEBUG, TAG, "before-datalength : %u", *dataLength);
416 if (NULL == svritem->data && inLen > 0)
418 // allocate memory for message header (CoAP header size because it is bigger)
419 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
420 if (NULL == svritem->data)
422 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
423 return CA_MEMORY_ALLOC_FAILED;
426 // copy 1 byte to parse coap header length
427 memcpy(svritem->data, inBuffer, 1);
433 //if not enough data received - read them on next CAFillHeader() call
439 //if enough data received - parse header
440 svritem->protocol = COAP;
442 //seems CoAP data received. read full coap header.
443 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
444 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
448 if (svritem->len < headerLen)
450 copyLen = headerLen - svritem->len;
456 //read required bytes to have full CoAP header
457 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
458 svritem->len += copyLen;
462 //if not enough data received - read them on next CAFillHeader() call
463 if (svritem->len < headerLen)
467 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
471 //calculate CoAP message length
472 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
474 // allocate required memory
475 unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
478 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
479 return CA_MEMORY_ALLOC_FAILED;
481 svritem->data = buffer;
487 // read required bytes to have full CoAP payload
488 copyLen = svritem->totalLen - svritem->len;
494 //read required bytes to have full CoAP header
495 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
496 svritem->len += copyLen;
504 OIC_LOG_V(DEBUG, TAG, "after-datalength : %u", *dataLength);
505 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
509 static void CAReceiveMessage(int fd)
511 CAResult_t res = CA_STATUS_OK;
513 //get remote device information from file descriptor.
515 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
518 OIC_LOG(ERROR, TAG, "there is no connection information in list");
525 if (svritem->sep.endpoint.flags & CA_SECURE)
527 svritem->protocol = TLS;
531 size_t tlsLength = 0;
533 if (TLS_HEADER_SIZE > svritem->tlsLen)
535 nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
539 //[3][4] bytes in tls header are tls payload length
540 tlsLength = TLS_HEADER_SIZE +
541 (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
542 OIC_LOG_V(DEBUG, TAG, "total tls length = %u", tlsLength);
543 if (tlsLength > sizeof(svritem->tlsdata))
545 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
546 sizeof(svritem->tlsdata));
547 if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
549 OIC_LOG(ERROR, TAG, "Failed to close TLS session");
551 CASearchAndDeleteTCPSession(&(svritem->sep.endpoint));
554 nbRead = tlsLength - svritem->tlsLen;
557 len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
560 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
561 res = CA_RECEIVE_FAILED;
565 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
566 svritem->state = DISCONNECTED;
567 res = CA_DESTINATION_DISCONNECTED;
571 svritem->tlsLen += len;
572 OIC_LOG_V(DEBUG, TAG, "nb_read : %u bytes , recv() : %d bytes, svritem->tlsLen : %u bytes",
573 nbRead, len, svritem->tlsLen);
574 if (tlsLength > 0 && tlsLength == svritem->tlsLen)
576 //when successfully read data - pass them to callback.
577 res = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->tlsdata, svritem->tlsLen);
579 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
587 svritem->protocol = COAP;
589 // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
590 len = recv(fd, svritem->tlsdata, sizeof(svritem->tlsdata), 0);
593 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
594 res = CA_RECEIVE_FAILED;
598 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
599 res = CA_DESTINATION_DISCONNECTED;
603 OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
604 //when successfully read data - pass them to callback.
605 if (g_packetReceivedCallback)
607 res = g_packetReceivedCallback(&svritem->sep, svritem->tlsdata, len);
612 //disconnect session and clean-up data if any error occurs
613 if (res != CA_STATUS_OK)
615 if (CA_STATUS_OK != CATCPDisconnectSession(&svritem->sep.endpoint))
617 OIC_LOG(ERROR, TAG, "Failed to disconnect TCP session");
620 CASearchAndDeleteTCPSession(&svritem->sep.endpoint);
625 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
627 if (caglobals.tcp.connectionFds[1] != -1)
632 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
633 } while ((len == -1) && (errno == EINTR));
635 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
637 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
644 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
645 struct sockaddr_storage *sockaddr)
647 struct addrinfo *addrs = NULL;
648 struct addrinfo hints = { .ai_family = family,
649 .ai_protocol = IPPROTO_TCP,
650 .ai_socktype = SOCK_STREAM,
651 .ai_flags = AI_NUMERICHOST };
653 int r = getaddrinfo(host, NULL, &hints, &addrs);
658 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
662 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
665 return CA_STATUS_FAILED;
667 // assumption: in this case, getaddrinfo will only return one addrinfo
668 // or first is the one we want.
669 if (addrs[0].ai_family == AF_INET6)
671 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
672 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
676 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
677 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
683 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
685 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
687 OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
688 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
690 // #1. create tcp socket.
691 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
694 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
695 return CA_SOCKET_OPERATION_FAILED;
699 // #2. convert address from string to binary.
700 struct sockaddr_storage sa = { .ss_family = family };
701 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
702 svritem->sep.endpoint.port, &sa);
703 if (CA_STATUS_OK != res)
705 OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
706 return CA_SOCKET_OPERATION_FAILED;
709 // #3. set socket length.
710 socklen_t socklen = 0;
711 if (sa.ss_family == AF_INET6)
713 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
714 if (!sock6->sin6_scope_id)
716 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
718 socklen = sizeof(struct sockaddr_in6);
722 socklen = sizeof(struct sockaddr_in);
725 // #4. connect to remote server device.
726 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
728 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
729 CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
730 svritem->sep.endpoint.port, 0, false, strerror(errno));
731 return CA_SOCKET_OPERATION_FAILED;
734 OIC_LOG(INFO, TAG, "connect socket success");
735 svritem->state = CONNECTED;
736 CHECKFD(svritem->fd);
737 ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
740 OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
741 return CA_SOCKET_OPERATION_FAILED;
746 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
748 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
750 if (OC_INVALID_SOCKET != sock->fd)
752 OIC_LOG(DEBUG, TAG, "accept socket created already");
756 socklen_t socklen = 0;
757 struct sockaddr_storage server = { .ss_family = family };
759 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
760 if (OC_INVALID_SOCKET == fd)
762 OIC_LOG(ERROR, TAG, "Failed to create socket");
766 if (family == AF_INET6)
768 // the socket is restricted to sending and receiving IPv6 packets only.
770 //TODO: enable once IPv6 is supported
772 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
774 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
778 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
779 socklen = sizeof (struct sockaddr_in6);
783 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
784 socklen = sizeof (struct sockaddr_in);
788 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
790 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
794 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
796 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
800 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
802 OIC_LOG(ERROR, TAG, "listen() error");
806 if (sock->port) // use the given port
809 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
811 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
813 return OC_INVALID_SOCKET;
816 else // return the assigned port
818 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
820 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
823 sock->port = ntohs(family == AF_INET6 ?
824 ((struct sockaddr_in6 *)&server)->sin6_port :
825 ((struct sockaddr_in *)&server)->sin_port);
835 return OC_INVALID_SOCKET;
838 static void CAInitializePipe(int *fds)
841 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
842 /* Temporary workaround: By pass F_GETFD / F_SETFD */
852 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
857 ret = fcntl(fds[0], F_GETFD);
860 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
864 ret = fcntl(fds[1], F_GETFD);
868 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
878 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
884 #define NEWSOCKET(FAMILY, NAME) \
885 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
886 if (caglobals.tcp.NAME.fd == -1) \
888 caglobals.tcp.NAME.port = 0; \
889 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
891 CHECKFD(caglobals.tcp.NAME.fd);
893 void CATCPInitializeSocket()
896 NEWSOCKET(AF_INET, ipv4);
898 NEWSOCKET(AF_INET, ipv4s);
901 //TODO Enable once TizenRT supports IPv6
904 NEWSOCKET(AF_INET6, ipv6);
906 NEWSOCKET(AF_INET6, ipv6s);
910 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
911 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
912 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
913 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
915 OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
916 caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
917 OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
918 caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
922 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
924 oc_mutex_lock(g_mutexObjectList);
925 if (caglobals.tcp.started)
927 oc_mutex_unlock(g_mutexObjectList);
928 OIC_LOG(INFO, TAG, "Adapter is started already");
932 g_threadPool = threadPool;
934 if (!caglobals.tcp.ipv4tcpenabled)
936 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
938 if (!caglobals.tcp.ipv6tcpenabled)
940 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
943 caglobals.tcp.terminate = false;
944 if (!caglobals.tcp.svrlist)
946 caglobals.tcp.svrlist = u_arraylist_create();
949 if (caglobals.server)
951 CATCPInitializeSocket();
954 // create pipe for fast shutdown
955 CAInitializePipe(caglobals.tcp.shutdownFds);
956 CHECKFD(caglobals.tcp.shutdownFds[0]);
957 CHECKFD(caglobals.tcp.shutdownFds[1]);
959 // create pipe for connection event
960 CAInitializePipe(caglobals.tcp.connectionFds);
961 CHECKFD(caglobals.tcp.connectionFds[0]);
962 CHECKFD(caglobals.tcp.connectionFds[1]);
964 CAResult_t res = CA_STATUS_OK;
966 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_recvThreadId);
968 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_recvThreadId,
969 "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
971 if (CA_STATUS_OK != res)
974 oc_mutex_unlock(g_mutexObjectList);
975 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
980 caglobals.tcp.started = true;
981 oc_mutex_unlock(g_mutexObjectList);
983 OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
987 void CATCPStopServer()
989 oc_mutex_lock(g_mutexObjectList);
990 if (caglobals.tcp.terminate)
992 oc_mutex_unlock(g_mutexObjectList);
993 OIC_LOG(INFO, TAG, "Adapter is not enabled");
997 // set terminate flag.
998 caglobals.tcp.terminate = true;
1000 // close accept socket.
1001 #ifndef __WITH_TLS__
1005 CLOSE_SOCKET(ipv4s);
1006 CLOSE_SOCKET(ipv6s);
1009 close(caglobals.tcp.connectionFds[1]);
1010 close(caglobals.tcp.connectionFds[0]);
1011 caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1012 caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1014 if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1016 close(caglobals.tcp.shutdownFds[1]);
1017 caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1018 // receive thread will stop immediately
1021 if (caglobals.tcp.started)
1023 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1024 caglobals.tcp.started = false;
1027 if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1029 close(caglobals.tcp.shutdownFds[0]);
1030 caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1033 CAResult_t res = ca_thread_pool_remove_task(g_threadPool, g_recvThreadId);
1034 if (CA_STATUS_OK != res)
1036 OIC_LOG(ERROR, TAG, "ca_thread_pool_remove_task failed");
1039 oc_mutex_unlock(g_mutexObjectList);
1041 CATCPDisconnectAll();
1044 OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1047 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1049 g_packetReceivedCallback = callback;
1052 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1054 g_connectionCallback = connHandler;
1057 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1059 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1061 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1062 ((unsigned char *)data)[0] >> 4);
1064 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1067 OIC_LOG(ERROR, TAG, "outpdu is null");
1068 OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1072 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1075 OIC_LOG(ERROR, TAG, "pdu parse failed");
1076 coap_delete_pdu(pdu);
1080 size_t payloadLen = 0;
1081 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1082 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1083 headerSize, pdu->length);
1084 if (pdu->length > headerSize)
1086 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1094 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1095 size_t dlen, const char *fam)
1097 OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1099 // #1. find a session info from list.
1100 CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1101 if (OC_INVALID_SOCKET == sockFd)
1103 // if there is no connection info, connect to remote device.
1104 sockFd = CAConnectTCPSession(endpoint);
1105 if (OC_INVALID_SOCKET == sockFd)
1107 OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1112 // #2. send data to remote device.
1113 ssize_t remainLen = dlen;
1116 size_t sendCounter = 0;
1118 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1120 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1124 if (EWOULDBLOCK != errno && EAGAIN != errno)
1126 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1127 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1128 len, false, strerror(errno));
1132 OIC_LOG_V(WARNING, TAG, "send blocked. trying %zu attempt from 100", sendCounter);
1133 if(sendCounter >= 100)
1141 } while (remainLen > 0);
1146 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1147 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1152 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1154 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1155 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1157 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1159 return sendData(endpoint, data, datalen, "ipv6");
1161 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1163 return sendData(endpoint, data, datalen, "ipv4");
1166 OIC_LOG(ERROR, TAG, "Not supported transport flags");
1170 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1172 VERIFY_NON_NULL(info, TAG, "info is NULL");
1173 VERIFY_NON_NULL(size, TAG, "size is NULL");
1175 return CA_NOT_SUPPORTED;
1178 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1180 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1182 // #1. create TCP server object
1183 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1186 OIC_LOG(ERROR, TAG, "Out of memory");
1187 return OC_INVALID_SOCKET;
1189 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1190 svritem->sep.endpoint.adapter = endpoint->adapter;
1191 svritem->sep.endpoint.port = endpoint->port;
1192 svritem->sep.endpoint.flags = endpoint->flags;
1193 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1194 svritem->state = CONNECTING;
1195 svritem->isClient = true;
1197 // #2. add TCP connection info to list
1198 oc_mutex_lock(g_mutexObjectList);
1199 if (caglobals.tcp.svrlist)
1201 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1204 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1207 oc_mutex_unlock(g_mutexObjectList);
1208 return OC_INVALID_SOCKET;
1211 oc_mutex_unlock(g_mutexObjectList);
1213 // #3. create the socket and connect to TCP server
1214 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1215 if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1217 return OC_INVALID_SOCKET;
1220 // #4. pass the connection information to CA Common Layer.
1221 if (g_connectionCallback)
1223 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1229 CAResult_t CADisconnectTCPSession(size_t index)
1231 CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1234 OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1235 return CA_STATUS_OK;
1238 // close the socket and remove session info in list.
1239 if (removedData->fd >= 0)
1241 shutdown(removedData->fd, SHUT_RDWR);
1242 close(removedData->fd);
1243 removedData->fd = -1;
1244 removedData->state = (CONNECTED == removedData->state) ?
1245 DISCONNECTED : removedData->state;
1247 // pass the connection information to CA Common Layer.
1248 if (g_connectionCallback && DISCONNECTED == removedData->state)
1250 g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1253 OICFree(removedData->data);
1254 removedData->data = NULL;
1256 OICFree(removedData);
1259 OIC_LOG(DEBUG, TAG, "data is removed from session list");
1261 if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1263 CATCPInitializeSocket();
1265 return CA_STATUS_OK;
1268 void CATCPDisconnectAll()
1270 oc_mutex_lock(g_mutexObjectList);
1272 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1273 for (ssize_t index = length; index > 0; index--)
1275 // disconnect session from remote device.
1276 CADisconnectTCPSession(index - 1);
1279 u_arraylist_destroy(caglobals.tcp.svrlist);
1280 caglobals.tcp.svrlist = NULL;
1282 oc_mutex_unlock(g_mutexObjectList);
1285 CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1290 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1292 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1293 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1295 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1297 // get connection info from list
1298 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1299 for (size_t i = 0; i < length; i++)
1301 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1302 caglobals.tcp.svrlist, i);
1308 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1309 sizeof(svritem->sep.endpoint.addr))
1310 && (svritem->sep.endpoint.port == endpoint->port)
1311 && (svritem->sep.endpoint.flags & endpoint->flags))
1313 OIC_LOG(DEBUG, TAG, "Found in session list");
1319 OIC_LOG(DEBUG, TAG, "Session not found");
1323 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1325 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1327 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1329 // get connection info from list.
1330 oc_mutex_lock(g_mutexObjectList);
1331 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1332 for (size_t i = 0; i < length; i++)
1334 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1335 caglobals.tcp.svrlist, i);
1341 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1342 sizeof(svritem->sep.endpoint.addr))
1343 && (svritem->sep.endpoint.port == endpoint->port)
1344 && (svritem->sep.endpoint.flags & endpoint->flags))
1346 oc_mutex_unlock(g_mutexObjectList);
1347 OIC_LOG(DEBUG, TAG, "Found in session list");
1352 oc_mutex_unlock(g_mutexObjectList);
1353 OIC_LOG(DEBUG, TAG, "Session not found");
1354 return OC_INVALID_SOCKET;
1357 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1359 oc_mutex_lock(g_mutexObjectList);
1361 // check from the last item.
1362 CATCPSessionInfo_t *svritem = NULL;
1363 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1364 for (size_t i = 0; i < length; i++)
1366 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1368 if (svritem && svritem->fd == fd)
1371 oc_mutex_unlock(g_mutexObjectList);
1376 oc_mutex_unlock(g_mutexObjectList);
1381 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1383 oc_mutex_lock(g_mutexObjectList);
1385 CAResult_t result = CA_STATUS_OK;
1387 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1390 result = CADisconnectTCPSession(index);
1391 if (CA_STATUS_OK != result)
1393 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1397 oc_mutex_unlock(g_mutexObjectList);
1401 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1403 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1405 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1406 ((unsigned char *)recvBuffer)[0] >> 4);
1407 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1409 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1411 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1412 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1413 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1415 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1416 return headerLen + optPaylaodLen;
1419 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1421 g_tcpErrorHandler = errorHandleCallback;