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");
622 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
624 if (caglobals.tcp.connectionFds[1] != -1)
629 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
630 } while ((len == -1) && (errno == EINTR));
632 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
634 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
641 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
642 struct sockaddr_storage *sockaddr)
644 struct addrinfo *addrs = NULL;
645 struct addrinfo hints = { .ai_family = family,
646 .ai_protocol = IPPROTO_TCP,
647 .ai_socktype = SOCK_STREAM,
648 .ai_flags = AI_NUMERICHOST };
650 int r = getaddrinfo(host, NULL, &hints, &addrs);
655 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
659 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
662 return CA_STATUS_FAILED;
664 // assumption: in this case, getaddrinfo will only return one addrinfo
665 // or first is the one we want.
666 if (addrs[0].ai_family == AF_INET6)
668 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
669 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
673 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
674 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
680 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
682 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
684 OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
685 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
687 // #1. create tcp socket.
688 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
691 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
692 return CA_SOCKET_OPERATION_FAILED;
696 // #2. convert address from string to binary.
697 struct sockaddr_storage sa = { .ss_family = family };
698 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
699 svritem->sep.endpoint.port, &sa);
700 if (CA_STATUS_OK != res)
702 OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
703 return CA_SOCKET_OPERATION_FAILED;
706 // #3. set socket length.
707 socklen_t socklen = 0;
708 if (sa.ss_family == AF_INET6)
710 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
711 if (!sock6->sin6_scope_id)
713 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
715 socklen = sizeof(struct sockaddr_in6);
719 socklen = sizeof(struct sockaddr_in);
722 // #4. connect to remote server device.
723 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
725 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
726 CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
727 svritem->sep.endpoint.port, 0, false, strerror(errno));
728 return CA_SOCKET_OPERATION_FAILED;
731 OIC_LOG(INFO, TAG, "connect socket success");
732 svritem->state = CONNECTED;
733 CHECKFD(svritem->fd);
734 ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
737 OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
738 return CA_SOCKET_OPERATION_FAILED;
743 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
745 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
747 if (OC_INVALID_SOCKET != sock->fd)
749 OIC_LOG(DEBUG, TAG, "accept socket created already");
753 socklen_t socklen = 0;
754 struct sockaddr_storage server = { .ss_family = family };
756 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
757 if (OC_INVALID_SOCKET == fd)
759 OIC_LOG(ERROR, TAG, "Failed to create socket");
763 if (family == AF_INET6)
765 // the socket is restricted to sending and receiving IPv6 packets only.
767 //TODO: enable once IPv6 is supported
769 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
771 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
775 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
776 socklen = sizeof (struct sockaddr_in6);
780 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
781 socklen = sizeof (struct sockaddr_in);
785 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
787 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
791 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
793 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
797 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
799 OIC_LOG(ERROR, TAG, "listen() error");
803 if (sock->port) // use the given port
806 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
808 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
810 return OC_INVALID_SOCKET;
813 else // return the assigned port
815 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
817 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
820 sock->port = ntohs(family == AF_INET6 ?
821 ((struct sockaddr_in6 *)&server)->sin6_port :
822 ((struct sockaddr_in *)&server)->sin_port);
832 return OC_INVALID_SOCKET;
835 static void CAInitializePipe(int *fds)
838 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
839 /* Temporary workaround: By pass F_GETFD / F_SETFD */
849 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
854 ret = fcntl(fds[0], F_GETFD);
857 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
861 ret = fcntl(fds[1], F_GETFD);
865 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
875 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
881 #define NEWSOCKET(FAMILY, NAME) \
882 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
883 if (caglobals.tcp.NAME.fd == -1) \
885 caglobals.tcp.NAME.port = 0; \
886 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
888 CHECKFD(caglobals.tcp.NAME.fd);
890 void CATCPInitializeSocket()
893 NEWSOCKET(AF_INET, ipv4);
895 NEWSOCKET(AF_INET, ipv4s);
898 //TODO Enable once TizenRT supports IPv6
901 NEWSOCKET(AF_INET6, ipv6);
903 NEWSOCKET(AF_INET6, ipv6s);
907 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
908 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
909 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
910 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
912 OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
913 caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
914 OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
915 caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
919 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
921 oc_mutex_lock(g_mutexObjectList);
922 if (caglobals.tcp.started)
924 oc_mutex_unlock(g_mutexObjectList);
925 OIC_LOG(INFO, TAG, "Adapter is started already");
929 g_threadPool = threadPool;
931 if (!caglobals.tcp.ipv4tcpenabled)
933 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
935 if (!caglobals.tcp.ipv6tcpenabled)
937 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
940 caglobals.tcp.terminate = false;
941 if (!caglobals.tcp.svrlist)
943 caglobals.tcp.svrlist = u_arraylist_create();
946 if (caglobals.server)
948 CATCPInitializeSocket();
951 // create pipe for fast shutdown
952 CAInitializePipe(caglobals.tcp.shutdownFds);
953 CHECKFD(caglobals.tcp.shutdownFds[0]);
954 CHECKFD(caglobals.tcp.shutdownFds[1]);
956 // create pipe for connection event
957 CAInitializePipe(caglobals.tcp.connectionFds);
958 CHECKFD(caglobals.tcp.connectionFds[0]);
959 CHECKFD(caglobals.tcp.connectionFds[1]);
961 CAResult_t res = CA_STATUS_OK;
963 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_recvThreadId);
965 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_recvThreadId,
966 "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
968 if (CA_STATUS_OK != res)
971 oc_mutex_unlock(g_mutexObjectList);
972 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
977 caglobals.tcp.started = true;
978 oc_mutex_unlock(g_mutexObjectList);
980 OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
984 void CATCPStopServer()
986 oc_mutex_lock(g_mutexObjectList);
987 if (caglobals.tcp.terminate)
989 oc_mutex_unlock(g_mutexObjectList);
990 OIC_LOG(INFO, TAG, "Adapter is not enabled");
994 // set terminate flag.
995 caglobals.tcp.terminate = true;
997 // close accept socket.
1002 CLOSE_SOCKET(ipv4s);
1003 CLOSE_SOCKET(ipv6s);
1006 close(caglobals.tcp.connectionFds[1]);
1007 close(caglobals.tcp.connectionFds[0]);
1008 caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1009 caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1011 if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1013 close(caglobals.tcp.shutdownFds[1]);
1014 caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1015 // receive thread will stop immediately
1018 if (caglobals.tcp.started)
1020 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1021 caglobals.tcp.started = false;
1024 if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1026 close(caglobals.tcp.shutdownFds[0]);
1027 caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1030 CAResult_t res = ca_thread_pool_remove_task(g_threadPool, g_recvThreadId);
1031 if (CA_STATUS_OK != res)
1033 OIC_LOG(ERROR, TAG, "ca_thread_pool_remove_task failed");
1036 oc_mutex_unlock(g_mutexObjectList);
1038 CATCPDisconnectAll();
1041 OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1044 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1046 g_packetReceivedCallback = callback;
1049 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1051 g_connectionCallback = connHandler;
1054 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1056 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1058 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1059 ((unsigned char *)data)[0] >> 4);
1061 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1064 OIC_LOG(ERROR, TAG, "outpdu is null");
1065 OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1069 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1072 OIC_LOG(ERROR, TAG, "pdu parse failed");
1073 coap_delete_pdu(pdu);
1077 size_t payloadLen = 0;
1078 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1079 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1080 headerSize, pdu->length);
1081 if (pdu->length > headerSize)
1083 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1091 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1092 size_t dlen, const char *fam)
1094 OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1096 // #1. find a session info from list.
1097 CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1098 if (OC_INVALID_SOCKET == sockFd)
1100 // if there is no connection info, connect to remote device.
1101 sockFd = CAConnectTCPSession(endpoint);
1102 if (OC_INVALID_SOCKET == sockFd)
1104 OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1109 // #2. send data to remote device.
1110 ssize_t remainLen = dlen;
1113 size_t sendCounter = 0;
1115 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1117 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1121 if (EWOULDBLOCK != errno && EAGAIN != errno)
1123 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1124 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1125 len, false, strerror(errno));
1129 OIC_LOG_V(WARNING, TAG, "send blocked. trying %zu attempt from 100", sendCounter);
1130 if(sendCounter >= 100)
1138 } while (remainLen > 0);
1143 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1144 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1149 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1151 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1152 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1154 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1156 return sendData(endpoint, data, datalen, "ipv6");
1158 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1160 return sendData(endpoint, data, datalen, "ipv4");
1163 OIC_LOG(ERROR, TAG, "Not supported transport flags");
1167 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1169 VERIFY_NON_NULL(info, TAG, "info is NULL");
1170 VERIFY_NON_NULL(size, TAG, "size is NULL");
1172 return CA_NOT_SUPPORTED;
1175 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1177 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1179 // #1. create TCP server object
1180 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1183 OIC_LOG(ERROR, TAG, "Out of memory");
1184 return OC_INVALID_SOCKET;
1186 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1187 svritem->sep.endpoint.adapter = endpoint->adapter;
1188 svritem->sep.endpoint.port = endpoint->port;
1189 svritem->sep.endpoint.flags = endpoint->flags;
1190 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1191 svritem->state = CONNECTING;
1192 svritem->isClient = true;
1194 // #2. add TCP connection info to list
1195 oc_mutex_lock(g_mutexObjectList);
1196 if (caglobals.tcp.svrlist)
1198 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1201 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1204 oc_mutex_unlock(g_mutexObjectList);
1205 return OC_INVALID_SOCKET;
1208 oc_mutex_unlock(g_mutexObjectList);
1210 // #3. create the socket and connect to TCP server
1211 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1212 if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1214 return OC_INVALID_SOCKET;
1217 // #4. pass the connection information to CA Common Layer.
1218 if (g_connectionCallback)
1220 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1226 CAResult_t CADisconnectTCPSession(size_t index)
1228 CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1231 OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1232 return CA_STATUS_OK;
1235 // close the socket and remove session info in list.
1236 if (removedData->fd >= 0)
1238 shutdown(removedData->fd, SHUT_RDWR);
1239 close(removedData->fd);
1240 removedData->fd = -1;
1241 removedData->state = (CONNECTED == removedData->state) ?
1242 DISCONNECTED : removedData->state;
1244 // pass the connection information to CA Common Layer.
1245 if (g_connectionCallback && DISCONNECTED == removedData->state)
1247 g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1250 OICFree(removedData->data);
1251 removedData->data = NULL;
1253 OICFree(removedData);
1256 OIC_LOG(DEBUG, TAG, "data is removed from session list");
1258 if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1260 CATCPInitializeSocket();
1262 return CA_STATUS_OK;
1265 void CATCPDisconnectAll()
1267 oc_mutex_lock(g_mutexObjectList);
1269 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1270 for (ssize_t index = length; index > 0; index--)
1272 // disconnect session from remote device.
1273 CADisconnectTCPSession(index - 1);
1276 u_arraylist_destroy(caglobals.tcp.svrlist);
1277 caglobals.tcp.svrlist = NULL;
1279 oc_mutex_unlock(g_mutexObjectList);
1282 CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1287 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1289 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1290 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1292 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1294 // get connection info from list
1295 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1296 for (size_t i = 0; i < length; i++)
1298 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1299 caglobals.tcp.svrlist, i);
1305 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1306 sizeof(svritem->sep.endpoint.addr))
1307 && (svritem->sep.endpoint.port == endpoint->port)
1308 && (svritem->sep.endpoint.flags & endpoint->flags))
1310 OIC_LOG(DEBUG, TAG, "Found in session list");
1316 OIC_LOG(DEBUG, TAG, "Session not found");
1320 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1322 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1324 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1326 // get connection info from list.
1327 oc_mutex_lock(g_mutexObjectList);
1328 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1329 for (size_t i = 0; i < length; i++)
1331 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1332 caglobals.tcp.svrlist, i);
1338 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1339 sizeof(svritem->sep.endpoint.addr))
1340 && (svritem->sep.endpoint.port == endpoint->port)
1341 && (svritem->sep.endpoint.flags & endpoint->flags))
1343 oc_mutex_unlock(g_mutexObjectList);
1344 OIC_LOG(DEBUG, TAG, "Found in session list");
1349 oc_mutex_unlock(g_mutexObjectList);
1350 OIC_LOG(DEBUG, TAG, "Session not found");
1351 return OC_INVALID_SOCKET;
1354 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1356 oc_mutex_lock(g_mutexObjectList);
1358 // check from the last item.
1359 CATCPSessionInfo_t *svritem = NULL;
1360 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1361 for (size_t i = 0; i < length; i++)
1363 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1365 if (svritem && svritem->fd == fd)
1368 oc_mutex_unlock(g_mutexObjectList);
1373 oc_mutex_unlock(g_mutexObjectList);
1378 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1380 oc_mutex_lock(g_mutexObjectList);
1382 CAResult_t result = CA_STATUS_OK;
1384 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1387 result = CADisconnectTCPSession(index);
1388 if (CA_STATUS_OK != result)
1390 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1394 oc_mutex_unlock(g_mutexObjectList);
1398 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1400 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1402 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1403 ((unsigned char *)recvBuffer)[0] >> 4);
1404 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1406 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1408 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1409 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1410 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1412 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1413 return headerLen + optPaylaodLen;
1416 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1418 g_tcpErrorHandler = errorHandleCallback;