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>
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
40 #include "catcpinterface.h"
41 #include "caipnwmonitor.h"
43 #include "caadapterutils.h"
45 #include "oic_malloc.h"
48 #include "ca_adapter_net_ssl.h"
52 * Logging tag for module name.
54 #define TAG "OIC_CA_TCP_SERVER"
57 * Maximum CoAP over TCP header length
58 * to know the total data length.
60 #define COAP_MAX_HEADER_SIZE 6
65 #define TLS_HEADER_SIZE 5
68 * Mutex to synchronize device object list.
70 static ca_mutex g_mutexObjectList = NULL;
73 * Conditional mutex to synchronize.
75 static ca_cond g_condObjectList = NULL;
78 * Maintains the callback to be notified when data received from remote device.
80 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
83 * Error callback to update error in TCP.
85 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
88 * Connected Callback to pass the connection information to RI.
90 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
92 static CAResult_t CATCPCreateMutex();
93 static void CATCPDestroyMutex();
94 static CAResult_t CATCPCreateCond();
95 static void CATCPDestroyCond();
96 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
97 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
98 static void CAFindReadyMessage();
99 static void CASelectReturned(fd_set *readFds);
100 static void CAReceiveMessage(int fd);
101 static void CAReceiveHandler(void *data);
102 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
104 #define CHECKFD(FD) \
105 if (FD > caglobals.tcp.maxfd) \
106 caglobals.tcp.maxfd = FD;
108 #define CLOSE_SOCKET(TYPE) \
109 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
111 close(caglobals.tcp.TYPE.fd); \
112 caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
115 #define CA_FD_SET(TYPE, FDS) \
116 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
118 FD_SET(caglobals.tcp.TYPE.fd, FDS); \
122 * Read length amount of data from socket item->fd
123 * Can read less data length then requested
124 * Actual read length added to item->len variable
126 * @param[in/out] item - used socket, buffer and to update received message length
127 * @param[in] length - length of data required to read
128 * @param[in] flags - additional info about socket
129 * @return - CA_STATUS_OK or appropriate error code
131 static CAResult_t CARecv(CATCPSessionInfo_t *item, size_t length, int flags)
135 return CA_STATUS_INVALID_PARAM;
138 //skip read operation if requested zero length
144 unsigned char *buffer = item->data + item->len;
146 int len = recv(item->fd, buffer, length, flags);
150 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
151 return CA_RECEIVE_FAILED;
155 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
156 item->state = DISCONNECTED;
157 return CA_DESTINATION_DISCONNECTED;
160 OIC_LOG_V(DEBUG, TAG, "recv len = %d", len);
161 OIC_LOG_BUFFER(DEBUG, TAG, buffer, len);
168 static void CATCPDestroyMutex()
170 if (g_mutexObjectList)
172 ca_mutex_free(g_mutexObjectList);
173 g_mutexObjectList = NULL;
177 static CAResult_t CATCPCreateMutex()
179 if (!g_mutexObjectList)
181 g_mutexObjectList = ca_mutex_new();
182 if (!g_mutexObjectList)
184 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
185 return CA_STATUS_FAILED;
192 static void CATCPDestroyCond()
194 if (g_condObjectList)
196 ca_cond_free(g_condObjectList);
197 g_condObjectList = NULL;
201 static CAResult_t CATCPCreateCond()
203 if (!g_condObjectList)
205 g_condObjectList = ca_cond_new();
206 if (!g_condObjectList)
208 OIC_LOG(ERROR, TAG, "Failed to created cond!");
209 return CA_STATUS_FAILED;
215 static void CAReceiveHandler(void *data)
218 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
220 while (!caglobals.tcp.terminate)
222 CAFindReadyMessage();
225 ca_mutex_lock(g_mutexObjectList);
226 ca_cond_signal(g_condObjectList);
227 ca_mutex_unlock(g_mutexObjectList);
229 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
232 static void CAFindReadyMessage()
235 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
238 CA_FD_SET(ipv4, &readFds);
239 CA_FD_SET(ipv6, &readFds);
241 if (OC_INVALID_SOCKET != caglobals.tcp.shutdownFds[0])
243 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
245 if (OC_INVALID_SOCKET != caglobals.tcp.connectionFds[0])
247 FD_SET(caglobals.tcp.connectionFds[0], &readFds);
250 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
251 for (size_t i = 0; i < length; i++)
253 CATCPSessionInfo_t *svritem =
254 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
255 if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
257 FD_SET(svritem->fd, &readFds);
261 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
263 if (caglobals.tcp.terminate)
265 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
271 CASelectReturned(&readFds);
275 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
279 static void CASelectReturned(fd_set *readFds)
281 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
283 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
285 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
288 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
290 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
293 else if (-1 != caglobals.tcp.connectionFds[0] &&
294 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
296 // new connection was created from remote device.
297 // exit the function to update read file descriptor.
298 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
299 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
304 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
305 FD_CLR(caglobals.tcp.connectionFds[0], readFds);
310 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
311 for (size_t i = 0; i < length; i++)
313 CATCPSessionInfo_t *svritem =
314 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
315 if (svritem && svritem->fd >= 0)
317 if (FD_ISSET(svritem->fd, readFds))
319 CAReceiveMessage(svritem->fd);
320 if (-1 != svritem->fd)
322 FD_CLR(svritem->fd, readFds);
330 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
332 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
334 struct sockaddr_storage clientaddr;
335 socklen_t clientlen = sizeof (struct sockaddr_in);
338 clientlen = sizeof(struct sockaddr_in6);
341 CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
342 if (OC_INVALID_SOCKET != sockfd)
344 CATCPSessionInfo_t *svritem =
345 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
348 OIC_LOG(ERROR, TAG, "Out of memory");
353 svritem->fd = sockfd;
354 svritem->sep.endpoint.flags = flag;
355 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
356 svritem->state = CONNECTED;
357 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
358 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
360 ca_mutex_lock(g_mutexObjectList);
361 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
364 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
367 ca_mutex_unlock(g_mutexObjectList);
370 ca_mutex_unlock(g_mutexObjectList);
377 static bool CAIsTlsMessage(const unsigned char* data, size_t length)
379 if (NULL == data || 0 == length)
381 OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
385 unsigned char first_byte = data[0];
387 //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
388 //handshake = [16], application_data = [17] in HEX
389 const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
392 for (i = 0; i < sizeof(tls_head_type); i++)
394 if(tls_head_type[i] == first_byte)
405 * Clean socket state data
407 * @param[in/out] item - socket state data
409 void CACleanData(CATCPSessionInfo_t *svritem)
413 OICFree(svritem->data);
414 svritem->data = NULL;
417 svritem->totalLen = 0;
418 svritem->protocol = UNKNOWN;
423 * Construct CoAP header and payload from buffer
425 * @param[in] svritem - used socket, buffer, current received message length and protocol
426 * @param[in/out] data - data buffer, this value is updated as data is copied to svritem
427 * @param[in/out] dataLength - length of data, this value decreased as data is copied to svritem
428 * @return - CA_STATUS_OK or appropriate error code
430 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
433 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
435 if (NULL == svritem || NULL == data || NULL == dataLength)
437 OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
438 return CA_STATUS_INVALID_PARAM;
441 unsigned char *inBuffer = *data;
442 size_t inLen = *dataLength;
443 OIC_LOG_V(DEBUG, TAG, "before-datalength : %u", *dataLength);
445 if (NULL == svritem->data && inLen > 0)
447 // allocate memory for message header (CoAP header size because it is bigger)
448 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
449 if (NULL == svritem->data)
451 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
452 return CA_MEMORY_ALLOC_FAILED;
455 // copy 1 byte to parse coap header length
456 memcpy(svritem->data, inBuffer, 1);
462 //if not enough data received - read them on next CAFillHeader() call
468 //if enough data received - parse header
469 svritem->protocol = COAP;
471 //seems CoAP data received. read full coap header.
472 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
473 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
477 if (svritem->len < headerLen)
479 copyLen = headerLen - svritem->len;
485 //read required bytes to have full CoAP header
486 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
487 svritem->len += copyLen;
491 //if not enough data received - read them on next CAFillHeader() call
492 if (svritem->len < headerLen)
496 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
500 //calculate CoAP message length
501 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
503 // allocate required memory
504 unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
507 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
508 return CA_MEMORY_ALLOC_FAILED;
510 svritem->data = buffer;
516 // read required bytes to have full CoAP payload
517 copyLen = svritem->totalLen - svritem->len;
523 //read required bytes to have full CoAP header
524 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
525 svritem->len += copyLen;
533 OIC_LOG_V(DEBUG, TAG, "after-datalength : %u", *dataLength);
534 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
539 * Read message header from socket item->fd
541 * @param[in/out] item - used socket, buffer, current received message length and protocol
542 * @return - CA_STATUS_OK or appropriate error code
544 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
546 CAResult_t res = CA_STATUS_OK;
550 return CA_STATUS_INVALID_PARAM;
553 if (NULL == svritem->data)
555 // allocate memory for message header (CoAP header size because it is bigger)
556 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
557 if (NULL == svritem->data)
559 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
560 return CA_MEMORY_ALLOC_FAILED;
564 //read data (assume TLS header) from remote device.
565 //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
566 res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
568 //return if any error occurs
569 if (CA_STATUS_OK != res)
574 //if not enough data received - read them on next CAReceiveMessage() call
575 if (svritem->len < TLS_HEADER_SIZE)
577 OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
581 //if enough data received - parse header
583 if (CAIsTlsMessage(svritem->data, svritem->len))
585 svritem->protocol = TLS;
587 //[3][4] bytes in tls header are tls payload length
588 unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
589 OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
591 svritem->totalLen = message_length + TLS_HEADER_SIZE;
596 svritem->protocol = COAP;
598 //seems CoAP data received. read full coap header.
599 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
601 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
603 if (svritem->len < headerLen)
605 //read required bytes to have full CoAP header
606 //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
607 res = CARecv(svritem, headerLen - svritem->len, 0);
609 //return if any error occurs
610 if (CA_STATUS_OK != res)
615 //if not enough data received - read them on next CAReceiveMessage() call
616 if (svritem->len < headerLen)
618 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
623 //calculate CoAP message length
624 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
627 unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
630 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
631 return CA_MEMORY_ALLOC_FAILED;
633 svritem->data = buffer;
639 * Read message payload from socket item->fd
642 * @param[in/out] item - used socket, buffer and to update received message length
643 * @return - CA_STATUS_OK or appropriate error code
645 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
649 return CA_STATUS_INVALID_PARAM;
652 return CARecv(svritem, svritem->totalLen - svritem->len, 0);
656 * Pass received data to app layer depending on protocol
658 * @param[in/out] item - used buffer, received message length and protocol
660 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
667 switch(svritem->protocol)
671 if (g_packetReceivedCallback)
673 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
680 int ret = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
682 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, ret);
686 case UNKNOWN: /* pass through */
688 OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
693 static void CAReceiveMessage(int fd)
695 CAResult_t res = CA_STATUS_OK;
697 //get remote device information from file descriptor.
699 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
702 OIC_LOG(ERROR, TAG, "there is no connection information in list");
709 if (svritem->sep.endpoint.flags & CA_SECURE)
711 svritem->protocol = TLS;
715 size_t tlsLength = 0;
717 if (TLS_HEADER_SIZE > svritem->tlsLen)
719 nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
723 //[3][4] bytes in tls header are tls payload length
724 tlsLength = TLS_HEADER_SIZE +
725 (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
726 OIC_LOG_V(DEBUG, TAG, "toal tls length = %u", tlsLength);
727 if (tlsLength > sizeof(svritem->tlsdata))
729 OIC_LOG_V(ERROR, TAG, "toal tls length is too big (buffer size : %u)",
730 sizeof(svritem->tlsdata));
731 return CA_STATUS_FAILED;
733 nbRead = tlsLength - svritem->tlsLen;
736 len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
739 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
740 res = CA_RECEIVE_FAILED;
744 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
745 res = CA_DESTINATION_DISCONNECTED;
749 svritem->tlsLen += len;
750 OIC_LOG_V(DEBUG, TAG, "nb_read : %u bytes , recv() : %d bytes, svritem->tlsLen : %u bytes",
751 nbRead, len, svritem->tlsLen);
752 if (tlsLength > 0 && tlsLength == svritem->tlsLen)
754 //when successfully read data - pass them to callback.
755 res = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->tlsdata, svritem->tlsLen);
757 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
765 unsigned char buffer[65535] = {0,}; // 65535 is the maximum size of ip packet
766 svritem->protocol = COAP;
768 len = recv(fd, buffer, sizeof(buffer), 0);
771 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
772 res = CA_RECEIVE_FAILED;
776 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
777 res = CA_DESTINATION_DISCONNECTED;
781 OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
782 //when successfully read data - pass them to callback.
783 if (g_packetReceivedCallback)
785 g_packetReceivedCallback(&svritem->sep, buffer, len);
790 //disconnect session and clean-up data if any error occurs
791 if (res != CA_STATUS_OK)
794 if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
796 OIC_LOG(ERROR, TAG, "Failed to close TLS session");
799 CASearchAndDeleteTCPSession(&(svritem->sep.endpoint));
804 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
806 if (caglobals.tcp.connectionFds[1] != -1)
811 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
812 } while ((len == -1) && (errno == EINTR));
814 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
816 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
823 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
824 struct sockaddr_storage *sockaddr)
826 struct addrinfo *addrs = NULL;
827 struct addrinfo hints = { .ai_family = family,
828 .ai_protocol = IPPROTO_TCP,
829 .ai_socktype = SOCK_STREAM,
830 .ai_flags = AI_NUMERICHOST };
832 int r = getaddrinfo(host, NULL, &hints, &addrs);
837 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
841 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
844 return CA_STATUS_FAILED;
846 // assumption: in this case, getaddrinfo will only return one addrinfo
847 // or first is the one we want.
848 if (addrs[0].ai_family == AF_INET6)
850 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
851 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
855 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
856 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
862 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
864 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
866 OIC_LOG_V(DEBUG, TAG, "try to connect with [%s:%u]",
867 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
869 // #1. create tcp socket.
870 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
873 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
874 return CA_SOCKET_OPERATION_FAILED;
878 // #2. convert address from string to binary.
879 struct sockaddr_storage sa = { .ss_family = family };
880 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
881 svritem->sep.endpoint.port, &sa);
882 if (CA_STATUS_OK != res)
884 OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
885 return CA_SOCKET_OPERATION_FAILED;
888 // #3. set socket length.
889 socklen_t socklen = 0;
890 if (sa.ss_family == AF_INET6)
892 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
893 if (!sock6->sin6_scope_id)
895 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
897 socklen = sizeof(struct sockaddr_in6);
901 socklen = sizeof(struct sockaddr_in);
904 // #4. connect to remote server device.
905 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
907 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
908 return CA_SOCKET_OPERATION_FAILED;
911 OIC_LOG(DEBUG, TAG, "connect socket success");
912 svritem->state = CONNECTED;
913 CHECKFD(svritem->fd);
914 ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
917 OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
918 return CA_SOCKET_OPERATION_FAILED;
923 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
925 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
927 if (OC_INVALID_SOCKET != sock->fd)
929 OIC_LOG(DEBUG, TAG, "accept socket created already");
933 socklen_t socklen = 0;
934 struct sockaddr_storage server = { .ss_family = family };
936 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
937 if (OC_INVALID_SOCKET == fd)
939 OIC_LOG(ERROR, TAG, "Failed to create socket");
943 if (family == AF_INET6)
945 // the socket is restricted to sending and receiving IPv6 packets only.
947 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
949 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
952 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
953 socklen = sizeof (struct sockaddr_in6);
957 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
958 socklen = sizeof (struct sockaddr_in);
962 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
964 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
968 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
970 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
974 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
976 OIC_LOG(ERROR, TAG, "listen() error");
980 if (!sock->port) // return the assigned port
982 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
984 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
987 sock->port = ntohs(family == AF_INET6 ?
988 ((struct sockaddr_in6 *)&server)->sin6_port :
989 ((struct sockaddr_in *)&server)->sin_port);
999 return OC_INVALID_SOCKET;
1002 static void CAInitializePipe(int *fds)
1004 int ret = pipe(fds);
1007 ret = fcntl(fds[0], F_GETFD);
1010 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1014 ret = fcntl(fds[1], F_GETFD);
1018 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1028 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1033 #define NEWSOCKET(FAMILY, NAME) \
1034 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1035 if (caglobals.tcp.NAME.fd == -1) \
1037 caglobals.tcp.NAME.port = 0; \
1038 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1040 CHECKFD(caglobals.tcp.NAME.fd);
1042 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1044 if (caglobals.tcp.started)
1046 OIC_LOG(DEBUG, TAG, "Adapter is started already");
1047 return CA_STATUS_OK;
1050 if (!caglobals.tcp.ipv4tcpenabled)
1052 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
1054 if (!caglobals.tcp.ipv6tcpenabled)
1056 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
1059 CAResult_t res = CATCPCreateMutex();
1060 if (CA_STATUS_OK == res)
1062 res = CATCPCreateCond();
1064 if (CA_STATUS_OK != res)
1066 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
1070 ca_mutex_lock(g_mutexObjectList);
1071 if (!caglobals.tcp.svrlist)
1073 caglobals.tcp.svrlist = u_arraylist_create();
1075 ca_mutex_unlock(g_mutexObjectList);
1077 if (caglobals.server)
1079 NEWSOCKET(AF_INET, ipv4);
1080 NEWSOCKET(AF_INET6, ipv6);
1081 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1082 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1083 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1084 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1087 // create pipe for fast shutdown
1088 CAInitializePipe(caglobals.tcp.shutdownFds);
1089 CHECKFD(caglobals.tcp.shutdownFds[0]);
1090 CHECKFD(caglobals.tcp.shutdownFds[1]);
1092 // create pipe for connection event
1093 CAInitializePipe(caglobals.tcp.connectionFds);
1094 CHECKFD(caglobals.tcp.connectionFds[0]);
1095 CHECKFD(caglobals.tcp.connectionFds[1]);
1097 caglobals.tcp.terminate = false;
1098 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
1099 if (CA_STATUS_OK != res)
1101 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1104 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
1106 caglobals.tcp.started = true;
1107 return CA_STATUS_OK;
1110 void CATCPStopServer()
1112 if (caglobals.tcp.terminate)
1114 OIC_LOG(DEBUG, TAG, "Adapter is not enabled");
1119 ca_mutex_lock(g_mutexObjectList);
1121 // set terminate flag.
1122 caglobals.tcp.terminate = true;
1124 if (caglobals.tcp.shutdownFds[1] != -1)
1126 close(caglobals.tcp.shutdownFds[1]);
1127 caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1128 // receive thread will stop immediately
1130 if (caglobals.tcp.connectionFds[1] != -1)
1132 close(caglobals.tcp.connectionFds[1]);
1133 caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1136 // close accept socket.
1140 if (caglobals.tcp.started)
1142 ca_cond_wait(g_condObjectList, g_mutexObjectList);
1144 caglobals.tcp.started = false;
1147 ca_mutex_unlock(g_mutexObjectList);
1149 CATCPDisconnectAll();
1150 CATCPDestroyMutex();
1153 OIC_LOG(DEBUG, TAG, "Adapter terminated successfully");
1156 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1158 g_packetReceivedCallback = callback;
1161 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1163 g_connectionCallback = connHandler;
1166 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1168 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1170 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1171 ((unsigned char *)data)[0] >> 4);
1173 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1176 OIC_LOG(ERROR, TAG, "outpdu is null");
1180 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1183 OIC_LOG(ERROR, TAG, "pdu parse failed");
1184 coap_delete_pdu(pdu);
1188 size_t payloadLen = 0;
1189 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1190 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1191 headerSize, pdu->length);
1192 if (pdu->length > headerSize)
1194 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1202 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1203 size_t dlen, const char *fam)
1205 OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1207 // #1. find a session info from list.
1208 CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1209 if (OC_INVALID_SOCKET == sockFd)
1211 // if there is no connection info, connect to remote device.
1212 sockFd = CAConnectTCPSession(endpoint);
1213 if (OC_INVALID_SOCKET == sockFd)
1215 OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1220 // #2. send data to remote device.
1221 ssize_t remainLen = dlen;
1224 ssize_t len = send(sockFd, data, remainLen, 0);
1227 if (EWOULDBLOCK != errno)
1229 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1236 } while (remainLen > 0);
1241 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1245 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1247 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1248 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1250 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1252 return sendData(endpoint, data, datalen, "ipv6");
1254 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1256 return sendData(endpoint, data, datalen, "ipv4");
1259 OIC_LOG(ERROR, TAG, "Not supported transport flags");
1263 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1265 VERIFY_NON_NULL(info, TAG, "info is NULL");
1266 VERIFY_NON_NULL(size, TAG, "size is NULL");
1268 return CA_NOT_SUPPORTED;
1271 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1273 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1275 // #1. create TCP server object
1276 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1279 OIC_LOG(ERROR, TAG, "Out of memory");
1280 return OC_INVALID_SOCKET;
1282 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1283 svritem->sep.endpoint.adapter = endpoint->adapter;
1284 svritem->sep.endpoint.port = endpoint->port;
1285 svritem->sep.endpoint.flags = endpoint->flags;
1286 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1287 svritem->state = CONNECTING;
1289 // #2. add TCP connection info to list
1290 ca_mutex_lock(g_mutexObjectList);
1291 if (caglobals.tcp.svrlist)
1293 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1296 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1299 ca_mutex_unlock(g_mutexObjectList);
1300 return OC_INVALID_SOCKET;
1303 ca_mutex_unlock(g_mutexObjectList);
1305 // #3. create the socket and connect to TCP server
1306 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1307 if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1309 return OC_INVALID_SOCKET;
1312 // #4. pass the connection information to CA Common Layer.
1313 if (g_connectionCallback)
1315 g_connectionCallback(&(svritem->sep.endpoint), true);
1321 CAResult_t CADisconnectTCPSession(size_t index)
1323 CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1326 OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1327 return CA_STATUS_OK;
1330 // close the socket and remove session info in list.
1331 if (removedData->fd >= 0)
1333 shutdown(removedData->fd, SHUT_RDWR);
1334 close(removedData->fd);
1335 removedData->fd = -1;
1336 removedData->state = (CONNECTED == removedData->state) ?
1337 DISCONNECTED : removedData->state;
1339 // pass the connection information to CA Common Layer.
1340 if (g_connectionCallback && DISCONNECTED == removedData->state)
1342 g_connectionCallback(&(removedData->sep.endpoint), false);
1345 OICFree(removedData->data);
1346 removedData->data = NULL;
1348 OICFree(removedData);
1351 OIC_LOG(DEBUG, TAG, "data is removed from session list");
1352 return CA_STATUS_OK;
1355 void CATCPDisconnectAll()
1357 ca_mutex_lock(g_mutexObjectList);
1359 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1360 for (ssize_t index = length; index > 0; index--)
1362 // disconnect session from remote device.
1363 CADisconnectTCPSession(index - 1);
1366 u_arraylist_destroy(caglobals.tcp.svrlist);
1367 caglobals.tcp.svrlist = NULL;
1369 ca_mutex_unlock(g_mutexObjectList);
1372 CAcloseSslConnectionAll();
1377 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1379 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1380 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1382 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1384 // get connection info from list
1385 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1386 for (size_t i = 0; i < length; i++)
1388 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1389 caglobals.tcp.svrlist, i);
1395 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1396 sizeof(svritem->sep.endpoint.addr))
1397 && (svritem->sep.endpoint.port == endpoint->port)
1398 && (svritem->sep.endpoint.flags & endpoint->flags))
1400 OIC_LOG(DEBUG, TAG, "Found in session list");
1406 OIC_LOG(DEBUG, TAG, "Session not found");
1410 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1412 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1414 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1416 // get connection info from list.
1417 ca_mutex_lock(g_mutexObjectList);
1418 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1419 for (size_t i = 0; i < length; i++)
1421 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1422 caglobals.tcp.svrlist, i);
1428 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1429 sizeof(svritem->sep.endpoint.addr))
1430 && (svritem->sep.endpoint.port == endpoint->port)
1431 && (svritem->sep.endpoint.flags & endpoint->flags))
1433 ca_mutex_unlock(g_mutexObjectList);
1434 OIC_LOG(DEBUG, TAG, "Found in session list");
1439 ca_mutex_unlock(g_mutexObjectList);
1440 OIC_LOG(DEBUG, TAG, "Session not found");
1441 return OC_INVALID_SOCKET;
1444 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1446 ca_mutex_lock(g_mutexObjectList);
1448 // check from the last item.
1449 CATCPSessionInfo_t *svritem = NULL;
1450 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1451 for (size_t i = 0; i < length; i++)
1453 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1455 if (svritem && svritem->fd == fd)
1458 ca_mutex_unlock(g_mutexObjectList);
1463 ca_mutex_unlock(g_mutexObjectList);
1468 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1470 ca_mutex_lock(g_mutexObjectList);
1472 CAResult_t result = CA_STATUS_OK;
1474 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1477 result = CADisconnectTCPSession(index);
1478 if (CA_STATUS_OK != result)
1480 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1484 ca_mutex_unlock(g_mutexObjectList);
1488 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1490 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1492 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1493 ((unsigned char *)recvBuffer)[0] >> 4);
1494 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1496 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1498 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1499 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1500 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1502 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1503 return headerLen + optPaylaodLen;
1506 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1508 g_tcpErrorHandler = errorHandleCallback;