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 * An unique identifier of receive thread.
88 static uint32_t g_recvThreadId = 0;
91 * Mutex to synchronize device object list.
93 static oc_mutex g_mutexObjectList = NULL;
96 * Conditional mutex to synchronize.
98 static oc_cond g_condObjectList = NULL;
101 * Maintains the callback to be notified when data received from remote device.
103 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
106 * Error callback to update error in TCP.
108 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
111 * Connected Callback to pass the connection information to RI.
113 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
115 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
116 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
117 static void CAFindReadyMessage();
118 static void CASelectReturned(fd_set *readFds);
119 static void CAReceiveMessage(int fd);
120 static void CAReceiveHandler(void *data);
121 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
122 static void CATCPInitializeSocket();
124 #define CHECKFD(FD) \
125 if (FD > caglobals.tcp.maxfd) \
126 caglobals.tcp.maxfd = FD;
128 #define CLOSE_SOCKET(TYPE) \
129 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
131 close(caglobals.tcp.TYPE.fd); \
132 caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
135 #define CA_FD_SET(TYPE, FDS) \
136 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
138 FD_SET(caglobals.tcp.TYPE.fd, FDS); \
141 void CATCPDestroyMutex()
143 if (g_mutexObjectList)
145 oc_mutex_free(g_mutexObjectList);
146 g_mutexObjectList = NULL;
150 CAResult_t CATCPCreateMutex()
152 if (!g_mutexObjectList)
154 g_mutexObjectList = oc_mutex_new();
155 if (!g_mutexObjectList)
157 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
158 return CA_STATUS_FAILED;
165 void CATCPDestroyCond()
167 if (g_condObjectList)
169 oc_cond_free(g_condObjectList);
170 g_condObjectList = NULL;
174 CAResult_t CATCPCreateCond()
176 if (!g_condObjectList)
178 g_condObjectList = oc_cond_new();
179 if (!g_condObjectList)
181 OIC_LOG(ERROR, TAG, "Failed to created cond!");
182 return CA_STATUS_FAILED;
188 static void CAReceiveHandler(void *data)
191 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
193 while (!caglobals.tcp.terminate)
195 CAFindReadyMessage();
198 oc_mutex_lock(g_mutexObjectList);
199 oc_cond_signal(g_condObjectList);
200 oc_mutex_unlock(g_mutexObjectList);
202 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
205 static void CAFindReadyMessage()
208 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
211 CA_FD_SET(ipv4, &readFds);
212 CA_FD_SET(ipv4s, &readFds);
213 CA_FD_SET(ipv6, &readFds);
214 CA_FD_SET(ipv6s, &readFds);
216 if (OC_INVALID_SOCKET != caglobals.tcp.shutdownFds[0])
218 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
221 if (OC_INVALID_SOCKET != caglobals.tcp.connectionFds[0])
223 FD_SET(caglobals.tcp.connectionFds[0], &readFds);
226 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
227 for (size_t i = 0; i < length; i++)
229 CATCPSessionInfo_t *svritem =
230 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
231 if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
233 FD_SET(svritem->fd, &readFds);
237 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
239 if (caglobals.tcp.terminate)
241 OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
248 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
253 CASelectReturned(&readFds);
256 static void CASelectReturned(fd_set *readFds)
258 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
260 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
262 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
265 else if (caglobals.tcp.ipv4s.fd != -1 && FD_ISSET(caglobals.tcp.ipv4s.fd, readFds))
267 CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
270 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
272 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
275 else if (caglobals.tcp.ipv6s.fd != -1 && FD_ISSET(caglobals.tcp.ipv6s.fd, readFds))
277 CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
280 else if (-1 != caglobals.tcp.connectionFds[0] &&
281 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
283 // new connection was created from remote device.
284 // exit the function to update read file descriptor.
285 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
286 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
291 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
296 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
297 for (size_t i = 0; i < length; i++)
299 CATCPSessionInfo_t *svritem =
300 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
301 if (svritem && svritem->fd >= 0)
303 if (FD_ISSET(svritem->fd, readFds))
305 CAReceiveMessage(svritem->fd);
312 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
314 OIC_LOG_V(INFO, TAG, "In %s", __func__);
315 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
317 if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
319 OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
321 sock->fd = OC_INVALID_SOCKET;
325 struct sockaddr_storage clientaddr;
326 socklen_t clientlen = sizeof (struct sockaddr_in);
329 clientlen = sizeof(struct sockaddr_in6);
332 CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
333 if (OC_INVALID_SOCKET != sockfd)
335 CATCPSessionInfo_t *svritem =
336 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
339 OIC_LOG(ERROR, TAG, "Out of memory");
344 svritem->fd = sockfd;
345 svritem->sep.endpoint.flags = flag;
346 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
347 svritem->state = CONNECTED;
348 svritem->isClient = false;
349 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
350 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
352 oc_mutex_lock(g_mutexObjectList);
353 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
356 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
359 oc_mutex_unlock(g_mutexObjectList);
362 oc_mutex_unlock(g_mutexObjectList);
366 // pass the connection information to CA Common Layer.
367 if (g_connectionCallback)
369 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
372 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
376 * Clean socket state data
378 * @param[in/out] item - socket state data
380 void CACleanData(CATCPSessionInfo_t *svritem)
384 OICFree(svritem->data);
385 svritem->data = NULL;
390 svritem->totalLen = 0;
392 svritem->protocol = UNKNOWN;
397 * Construct CoAP header and payload from buffer
399 * @param[in] svritem - used socket, buffer, current received message length and protocol
400 * @param[in/out] data - data buffer, this value is updated as data is copied to svritem
401 * @param[in/out] dataLength - length of data, this value decreased as data is copied to svritem
402 * @return - CA_STATUS_OK or appropriate error code
404 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
407 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
409 if (NULL == svritem || NULL == data || NULL == dataLength)
411 OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
412 return CA_STATUS_INVALID_PARAM;
415 unsigned char *inBuffer = *data;
416 size_t inLen = *dataLength;
417 OIC_LOG_V(DEBUG, TAG, "before-datalength : %u", *dataLength);
419 if (NULL == svritem->data && inLen > 0)
421 // allocate memory for message header (CoAP header size because it is bigger)
422 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
423 if (NULL == svritem->data)
425 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
426 return CA_MEMORY_ALLOC_FAILED;
429 // copy 1 byte to parse coap header length
430 memcpy(svritem->data, inBuffer, 1);
432 svritem->bufLen = COAP_MAX_HEADER_SIZE;
437 //if not enough data received - read them on next CAFillHeader() call
443 //if enough data received - parse header
444 svritem->protocol = COAP;
446 //seems CoAP data received. read full coap header.
447 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
448 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
452 if (svritem->len < headerLen)
454 copyLen = headerLen - svritem->len;
460 //read required bytes to have full CoAP header
461 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
462 svritem->len += copyLen;
466 //if not enough data received - read them on next CAFillHeader() call
467 if (svritem->len < headerLen)
471 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
475 //calculate CoAP message length
476 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
482 // Calculate length of data to be copied.
483 copyLen = svritem->totalLen - svritem->len;
489 // Is buffer not big enough for remaining data ?
490 if (svritem->len + copyLen > svritem->bufLen)
492 // Resize buffer to accommodate enough space
493 size_t extLen = svritem->totalLen - svritem->bufLen;
494 if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
496 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
499 // Allocate required memory
500 unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
503 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
504 return CA_MEMORY_ALLOC_FAILED;
507 svritem->data = buffer;
508 svritem->bufLen += extLen;
511 // Read required bytes to have full CoAP payload
512 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
513 svritem->len += copyLen;
521 OIC_LOG_V(DEBUG, TAG, "after-datalength : %u", *dataLength);
522 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
526 static void CAReceiveMessage(int fd)
528 CAResult_t res = CA_STATUS_OK;
530 //get remote device information from file descriptor.
532 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
535 OIC_LOG(ERROR, TAG, "there is no connection information in list");
542 if (svritem->sep.endpoint.flags & CA_SECURE)
544 svritem->protocol = TLS;
548 size_t tlsLength = 0;
550 if (TLS_HEADER_SIZE > svritem->tlsLen)
552 nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
556 //[3][4] bytes in tls header are tls payload length
557 tlsLength = TLS_HEADER_SIZE +
558 (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
559 OIC_LOG_V(DEBUG, TAG, "total tls length = %u", tlsLength);
560 if (tlsLength > sizeof(svritem->tlsdata))
562 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
563 sizeof(svritem->tlsdata));
564 if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
566 OIC_LOG(ERROR, TAG, "Failed to close TLS session");
568 CASearchAndDeleteTCPSession(&(svritem->sep.endpoint));
571 nbRead = tlsLength - svritem->tlsLen;
574 len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
577 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
578 res = CA_RECEIVE_FAILED;
582 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
583 svritem->state = DISCONNECTED;
584 res = CA_DESTINATION_DISCONNECTED;
588 svritem->tlsLen += len;
589 OIC_LOG_V(DEBUG, TAG, "nb_read : %u bytes , recv() : %d bytes, svritem->tlsLen : %u bytes",
590 nbRead, len, svritem->tlsLen);
591 if (tlsLength > 0 && tlsLength == svritem->tlsLen)
593 //when successfully read data - pass them to callback.
594 res = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->tlsdata, svritem->tlsLen);
596 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
604 svritem->protocol = COAP;
606 // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
607 len = recv(fd, svritem->tlsdata, sizeof(svritem->tlsdata), 0);
610 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
611 res = CA_RECEIVE_FAILED;
615 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
616 res = CA_DESTINATION_DISCONNECTED;
620 OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
621 //when successfully read data - pass them to callback.
622 if (g_packetReceivedCallback)
624 res = g_packetReceivedCallback(&svritem->sep, svritem->tlsdata, len);
629 //disconnect session and clean-up data if any error occurs
630 if (res != CA_STATUS_OK)
632 if (CA_STATUS_OK != CATCPDisconnectSession(&svritem->sep.endpoint))
634 CASearchAndDeleteTCPSession(&svritem->sep.endpoint);
635 OIC_LOG(ERROR, TAG, "Failed to disconnect TCP session");
642 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
644 if (caglobals.tcp.connectionFds[1] != -1)
649 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
650 } while ((len == -1) && (errno == EINTR));
652 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
654 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
661 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
662 struct sockaddr_storage *sockaddr)
664 struct addrinfo *addrs = NULL;
665 struct addrinfo hints = { .ai_family = family,
666 .ai_protocol = IPPROTO_TCP,
667 .ai_socktype = SOCK_STREAM,
668 .ai_flags = AI_NUMERICHOST };
670 int r = getaddrinfo(host, NULL, &hints, &addrs);
675 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
679 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
682 return CA_STATUS_FAILED;
684 // assumption: in this case, getaddrinfo will only return one addrinfo
685 // or first is the one we want.
686 if (addrs[0].ai_family == AF_INET6)
688 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
689 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
693 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
694 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
700 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
702 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
704 OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
705 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
707 // #1. create tcp socket.
708 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
711 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
712 return CA_SOCKET_OPERATION_FAILED;
716 // #2. convert address from string to binary.
717 struct sockaddr_storage sa = { .ss_family = family };
718 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
719 svritem->sep.endpoint.port, &sa);
720 if (CA_STATUS_OK != res)
722 OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
723 return CA_SOCKET_OPERATION_FAILED;
726 // #3. set socket length.
727 socklen_t socklen = 0;
728 if (sa.ss_family == AF_INET6)
730 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
731 if (!sock6->sin6_scope_id)
733 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
735 socklen = sizeof(struct sockaddr_in6);
739 socklen = sizeof(struct sockaddr_in);
742 // #4. connect to remote server device.
743 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
745 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
746 CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
747 svritem->sep.endpoint.port, 0, false, strerror(errno));
748 return CA_SOCKET_OPERATION_FAILED;
751 OIC_LOG(INFO, TAG, "connect socket success");
752 svritem->state = CONNECTED;
753 CHECKFD(svritem->fd);
754 ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
757 OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
758 return CA_SOCKET_OPERATION_FAILED;
763 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
765 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
767 if (OC_INVALID_SOCKET != sock->fd)
769 OIC_LOG(DEBUG, TAG, "accept socket created already");
773 socklen_t socklen = 0;
774 struct sockaddr_storage server = { .ss_family = family };
776 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
777 if (OC_INVALID_SOCKET == fd)
779 OIC_LOG(ERROR, TAG, "Failed to create socket");
783 if (family == AF_INET6)
785 // the socket is restricted to sending and receiving IPv6 packets only.
787 //TODO: enable once IPv6 is supported
789 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
791 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
795 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
796 socklen = sizeof (struct sockaddr_in6);
800 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
801 socklen = sizeof (struct sockaddr_in);
805 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
807 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
811 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
813 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
817 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
819 OIC_LOG(ERROR, TAG, "listen() error");
823 if (sock->port) // use the given port
826 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
828 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
830 return OC_INVALID_SOCKET;
833 else // return the assigned port
835 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
837 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
840 sock->port = ntohs(family == AF_INET6 ?
841 ((struct sockaddr_in6 *)&server)->sin6_port :
842 ((struct sockaddr_in *)&server)->sin_port);
852 return OC_INVALID_SOCKET;
855 static void CAInitializePipe(int *fds)
858 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
859 /* Temporary workaround: By pass F_GETFD / F_SETFD */
869 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
874 ret = fcntl(fds[0], F_GETFD);
877 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
881 ret = fcntl(fds[1], F_GETFD);
885 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
895 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
901 #define NEWSOCKET(FAMILY, NAME) \
902 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
903 if (caglobals.tcp.NAME.fd == -1) \
905 caglobals.tcp.NAME.port = 0; \
906 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
908 CHECKFD(caglobals.tcp.NAME.fd);
910 void CATCPInitializeSocket()
913 NEWSOCKET(AF_INET, ipv4);
915 NEWSOCKET(AF_INET, ipv4s);
918 //TODO Enable once TizenRT supports IPv6
921 NEWSOCKET(AF_INET6, ipv6);
923 NEWSOCKET(AF_INET6, ipv6s);
927 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
928 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
929 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
930 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
932 OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
933 caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
934 OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
935 caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
939 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
941 oc_mutex_lock(g_mutexObjectList);
942 if (caglobals.tcp.started)
944 oc_mutex_unlock(g_mutexObjectList);
945 OIC_LOG(INFO, TAG, "Adapter is started already");
949 g_threadPool = threadPool;
951 if (!caglobals.tcp.ipv4tcpenabled)
953 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
955 if (!caglobals.tcp.ipv6tcpenabled)
957 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
960 caglobals.tcp.terminate = false;
961 if (!caglobals.tcp.svrlist)
963 caglobals.tcp.svrlist = u_arraylist_create();
966 if (caglobals.server)
968 CATCPInitializeSocket();
971 // create pipe for fast shutdown
972 CAInitializePipe(caglobals.tcp.shutdownFds);
973 CHECKFD(caglobals.tcp.shutdownFds[0]);
974 CHECKFD(caglobals.tcp.shutdownFds[1]);
976 // create pipe for connection event
977 CAInitializePipe(caglobals.tcp.connectionFds);
978 CHECKFD(caglobals.tcp.connectionFds[0]);
979 CHECKFD(caglobals.tcp.connectionFds[1]);
981 CAResult_t res = CA_STATUS_OK;
983 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_recvThreadId);
985 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_recvThreadId,
986 "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
988 if (CA_STATUS_OK != res)
991 oc_mutex_unlock(g_mutexObjectList);
992 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
997 caglobals.tcp.started = true;
998 oc_mutex_unlock(g_mutexObjectList);
1000 OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1001 return CA_STATUS_OK;
1004 void CATCPStopServer()
1006 oc_mutex_lock(g_mutexObjectList);
1007 if (caglobals.tcp.terminate)
1009 oc_mutex_unlock(g_mutexObjectList);
1010 OIC_LOG(INFO, TAG, "Adapter is not enabled");
1014 // set terminate flag.
1015 caglobals.tcp.terminate = true;
1017 // close accept socket.
1018 #ifndef __WITH_TLS__
1022 CLOSE_SOCKET(ipv4s);
1023 CLOSE_SOCKET(ipv6s);
1026 close(caglobals.tcp.connectionFds[1]);
1027 close(caglobals.tcp.connectionFds[0]);
1028 caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1029 caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1031 if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1033 close(caglobals.tcp.shutdownFds[1]);
1034 caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1035 // receive thread will stop immediately
1038 if (caglobals.tcp.started)
1040 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1041 caglobals.tcp.started = false;
1044 if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1046 close(caglobals.tcp.shutdownFds[0]);
1047 caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1050 CAResult_t res = ca_thread_pool_remove_task(g_threadPool, g_recvThreadId);
1051 if (CA_STATUS_OK != res)
1053 OIC_LOG(ERROR, TAG, "ca_thread_pool_remove_task failed");
1056 oc_mutex_unlock(g_mutexObjectList);
1058 CATCPDisconnectAll();
1061 OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1064 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1066 g_packetReceivedCallback = callback;
1069 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1071 g_connectionCallback = connHandler;
1074 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1076 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1078 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1079 ((unsigned char *)data)[0] >> 4);
1081 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1084 OIC_LOG(ERROR, TAG, "outpdu is null");
1085 OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1089 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1092 OIC_LOG(ERROR, TAG, "pdu parse failed");
1093 coap_delete_pdu(pdu);
1097 size_t payloadLen = 0;
1098 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1099 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1100 headerSize, pdu->length);
1101 if (pdu->length > headerSize)
1103 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1111 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1112 size_t dlen, const char *fam)
1114 OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1116 // #1. find a session info from list.
1117 CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1118 if (OC_INVALID_SOCKET == sockFd)
1120 // if there is no connection info, connect to remote device.
1121 sockFd = CAConnectTCPSession(endpoint);
1122 if (OC_INVALID_SOCKET == sockFd)
1124 OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1129 // #2. send data to remote device.
1130 ssize_t remainLen = dlen;
1131 size_t sendCounter = 0;
1135 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1137 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1141 if (EWOULDBLOCK != errno && EAGAIN != errno)
1143 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1144 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1145 len, false, strerror(errno));
1149 OIC_LOG_V(WARNING, TAG, "send blocked. trying %zu attempt from 25", sendCounter);
1150 if(sendCounter >= 25)
1158 } while (remainLen > 0);
1163 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1164 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1169 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1171 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1172 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1174 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1176 return sendData(endpoint, data, datalen, "ipv6");
1178 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1180 return sendData(endpoint, data, datalen, "ipv4");
1183 OIC_LOG(ERROR, TAG, "Not supported transport flags");
1187 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1189 VERIFY_NON_NULL(info, TAG, "info is NULL");
1190 VERIFY_NON_NULL(size, TAG, "size is NULL");
1192 return CA_NOT_SUPPORTED;
1195 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1197 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1199 // #1. create TCP server object
1200 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1203 OIC_LOG(ERROR, TAG, "Out of memory");
1204 return OC_INVALID_SOCKET;
1206 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1207 svritem->sep.endpoint.adapter = endpoint->adapter;
1208 svritem->sep.endpoint.port = endpoint->port;
1209 svritem->sep.endpoint.flags = endpoint->flags;
1210 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1211 svritem->state = CONNECTING;
1212 svritem->isClient = true;
1214 // #2. add TCP connection info to list
1215 oc_mutex_lock(g_mutexObjectList);
1216 if (caglobals.tcp.svrlist)
1218 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1221 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1224 oc_mutex_unlock(g_mutexObjectList);
1225 return OC_INVALID_SOCKET;
1228 oc_mutex_unlock(g_mutexObjectList);
1230 // #3. create the socket and connect to TCP server
1231 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1232 if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1234 return OC_INVALID_SOCKET;
1237 // #4. pass the connection information to CA Common Layer.
1238 if (g_connectionCallback)
1240 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1246 CAResult_t CADisconnectTCPSession(size_t index)
1248 CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1251 OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1252 return CA_STATUS_OK;
1255 // close the socket and remove session info in list.
1256 if (removedData->fd >= 0)
1258 shutdown(removedData->fd, SHUT_RDWR);
1259 close(removedData->fd);
1260 removedData->fd = -1;
1261 removedData->state = (CONNECTED == removedData->state) ?
1262 DISCONNECTED : removedData->state;
1264 // pass the connection information to CA Common Layer.
1265 if (g_connectionCallback && DISCONNECTED == removedData->state)
1267 g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1270 OICFree(removedData->data);
1271 removedData->data = NULL;
1273 OICFree(removedData);
1276 OIC_LOG(DEBUG, TAG, "data is removed from session list");
1278 if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1280 CATCPInitializeSocket();
1282 return CA_STATUS_OK;
1285 void CATCPDisconnectAll()
1287 OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1289 oc_mutex_lock(g_mutexObjectList);
1291 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1292 for (ssize_t index = length; index > 0; index--)
1294 // disconnect session from remote device.
1295 CADisconnectTCPSession(index - 1);
1298 u_arraylist_destroy(caglobals.tcp.svrlist);
1299 caglobals.tcp.svrlist = NULL;
1301 oc_mutex_unlock(g_mutexObjectList);
1304 CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1307 OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1310 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1312 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1313 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1315 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1317 // get connection info from list
1318 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1319 for (size_t i = 0; i < length; i++)
1321 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1322 caglobals.tcp.svrlist, i);
1328 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1329 sizeof(svritem->sep.endpoint.addr))
1330 && (svritem->sep.endpoint.port == endpoint->port)
1331 && (svritem->sep.endpoint.flags & endpoint->flags))
1333 OIC_LOG(DEBUG, TAG, "Found in session list");
1339 OIC_LOG(DEBUG, TAG, "Session not found");
1343 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1345 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1347 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1349 // get connection info from list.
1350 oc_mutex_lock(g_mutexObjectList);
1351 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1352 for (size_t i = 0; i < length; i++)
1354 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1355 caglobals.tcp.svrlist, i);
1361 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1362 sizeof(svritem->sep.endpoint.addr))
1363 && (svritem->sep.endpoint.port == endpoint->port)
1364 && (svritem->sep.endpoint.flags & endpoint->flags))
1366 oc_mutex_unlock(g_mutexObjectList);
1367 OIC_LOG(DEBUG, TAG, "Found in session list");
1372 oc_mutex_unlock(g_mutexObjectList);
1373 OIC_LOG(DEBUG, TAG, "Session not found");
1374 return OC_INVALID_SOCKET;
1377 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1379 oc_mutex_lock(g_mutexObjectList);
1381 // check from the last item.
1382 CATCPSessionInfo_t *svritem = NULL;
1383 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1384 for (size_t i = 0; i < length; i++)
1386 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1388 if (svritem && svritem->fd == fd)
1391 oc_mutex_unlock(g_mutexObjectList);
1396 oc_mutex_unlock(g_mutexObjectList);
1401 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1403 oc_mutex_lock(g_mutexObjectList);
1405 CAResult_t result = CA_STATUS_OK;
1407 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1410 result = CADisconnectTCPSession(index);
1411 if (CA_STATUS_OK != result)
1413 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1417 oc_mutex_unlock(g_mutexObjectList);
1421 void CATCPCloseInProgressConnections()
1423 OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1425 oc_mutex_lock(g_mutexObjectList);
1427 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1428 for (size_t index = 0; index < length; index++)
1430 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1431 caglobals.tcp.svrlist, index);
1437 // Session which are connecting state
1438 if (svritem->fd >= 0 && svritem->state == CONNECTING)
1440 shutdown(svritem->fd, SHUT_RDWR);
1443 svritem->state = DISCONNECTED;
1447 oc_mutex_unlock(g_mutexObjectList);
1449 OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1452 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1454 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1456 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1457 ((unsigned char *)recvBuffer)[0] >> 4);
1458 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1460 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1462 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1463 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1464 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1466 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1467 return headerLen + optPaylaodLen;
1470 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1472 g_tcpErrorHandler = errorHandleCallback;