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"
42 #include "caadapterutils.h"
44 #include "oic_malloc.h"
47 #include "ca_adapter_net_tls.h"
51 * Logging tag for module name.
53 #define TAG "OIC_CA_TCP_SERVER"
56 * Maximum CoAP over TCP header length
57 * to know the total data length.
59 #define COAP_MAX_HEADER_SIZE 6
64 #define TLS_HEADER_SIZE 5
67 * Mutex to synchronize device object list.
69 static oc_mutex g_mutexObjectList = NULL;
72 * Conditional mutex to synchronize.
74 static oc_cond g_condObjectList = NULL;
77 * Maintains the callback to be notified when data received from remote device.
79 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
82 * Error callback to update error in TCP.
84 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
87 * Connected Callback to pass the connection information to RI.
89 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
91 static CAResult_t CATCPCreateMutex();
92 static void CATCPDestroyMutex();
93 static CAResult_t CATCPCreateCond();
94 static void CATCPDestroyCond();
95 static int CACreateAcceptSocket(int family, CASocket_t *sock);
96 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
97 static void CAFindReadyMessage();
98 static void CASelectReturned(fd_set *readFds);
99 static void CAReceiveMessage(int fd);
100 static void CAReceiveHandler(void *data);
101 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
103 #define CHECKFD(FD) \
104 if (FD > caglobals.tcp.maxfd) \
105 caglobals.tcp.maxfd = FD;
108 * Read length amount of data from socket item->fd
109 * Can read less data length then requested
110 * Actual read length added to item->len variable
112 * @param[in/out] item - used socket, buffer and to update received message length
113 * @param[in] length - length of data required to read
114 * @param[in] flags - additional info about socket
115 * @return - CA_STATUS_OK or appropriate error code
117 static CAResult_t CARecv(CATCPSessionInfo_t *item, size_t length, int flags)
121 return CA_STATUS_INVALID_PARAM;
124 //skip read operation if requested zero length
130 unsigned char *buffer = item->data + item->len;
132 int len = recv(item->fd, buffer, length, flags);
136 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
137 return CA_RECEIVE_FAILED;
141 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
142 return CA_DESTINATION_DISCONNECTED;
145 OIC_LOG_V(DEBUG, TAG, "recv len = %d", len);
146 OIC_LOG_BUFFER(DEBUG, TAG, buffer, len);
153 static void CATCPDestroyMutex()
155 if (g_mutexObjectList)
157 oc_mutex_free(g_mutexObjectList);
158 g_mutexObjectList = NULL;
162 static CAResult_t CATCPCreateMutex()
164 if (!g_mutexObjectList)
166 g_mutexObjectList = oc_mutex_new();
167 if (!g_mutexObjectList)
169 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
170 return CA_STATUS_FAILED;
177 static void CATCPDestroyCond()
179 if (g_condObjectList)
181 oc_cond_free(g_condObjectList);
182 g_condObjectList = NULL;
186 static CAResult_t CATCPCreateCond()
188 if (!g_condObjectList)
190 g_condObjectList = oc_cond_new();
191 if (!g_condObjectList)
193 OIC_LOG(ERROR, TAG, "Failed to created cond!");
194 return CA_STATUS_FAILED;
200 static void CAReceiveHandler(void *data)
203 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
205 while (!caglobals.tcp.terminate)
207 CAFindReadyMessage();
210 oc_mutex_lock(g_mutexObjectList);
211 oc_cond_signal(g_condObjectList);
212 oc_mutex_unlock(g_mutexObjectList);
214 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
217 static void CAFindReadyMessage()
220 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
224 if (-1 != caglobals.tcp.ipv4.fd)
226 FD_SET(caglobals.tcp.ipv4.fd, &readFds);
228 if (-1 != caglobals.tcp.ipv6.fd)
230 FD_SET(caglobals.tcp.ipv6.fd, &readFds);
232 if (-1 != caglobals.tcp.shutdownFds[0])
234 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
236 if (-1 != caglobals.tcp.connectionFds[0])
238 FD_SET(caglobals.tcp.connectionFds[0], &readFds);
241 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
242 for (size_t i = 0; i < length; i++)
244 CATCPSessionInfo_t *svritem =
245 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
246 if (svritem && 0 <= svritem->fd)
248 FD_SET(svritem->fd, &readFds);
252 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
254 if (caglobals.tcp.terminate)
256 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
263 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
268 CASelectReturned(&readFds);
271 static void CASelectReturned(fd_set *readFds)
273 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
275 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
277 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
280 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
282 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
285 else if (-1 != caglobals.tcp.connectionFds[0] &&
286 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
288 // new connection was created from remote device.
289 // exit the function to update read file descriptor.
290 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
291 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
296 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
297 FD_CLR(caglobals.tcp.connectionFds[0], readFds);
302 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
303 for (size_t i = 0; i < length; i++)
305 CATCPSessionInfo_t *svritem =
306 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
307 if (svritem && svritem->fd >= 0)
309 if (FD_ISSET(svritem->fd, readFds))
311 CAReceiveMessage(svritem->fd);
312 FD_CLR(svritem->fd, readFds);
319 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
321 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
323 struct sockaddr_storage clientaddr;
324 socklen_t clientlen = sizeof (struct sockaddr_in);
327 clientlen = sizeof(struct sockaddr_in6);
330 int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
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 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
346 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
348 oc_mutex_lock(g_mutexObjectList);
349 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
352 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
355 oc_mutex_unlock(g_mutexObjectList);
358 oc_mutex_unlock(g_mutexObjectList);
365 static bool CAIsTlsMessage(const unsigned char* data, size_t length)
367 if (NULL == data || 0 == length)
369 OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
373 unsigned char first_byte = data[0];
375 //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
376 //handshake = [16], application_data = [17] in HEX
377 const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
380 for (i = 0; i < sizeof(tls_head_type); i++)
382 if(tls_head_type[i] == first_byte)
393 * Clean socket state data
395 * @param[in/out] item - socket state data
397 static void CACleanData(CATCPSessionInfo_t *svritem)
401 OICFree(svritem->data);
402 svritem->data = NULL;
404 svritem->totalLen = 0;
405 svritem->protocol = UNKNOWN;
410 * Read message header from socket item->fd
412 * @param[in/out] item - used socket, buffer, current received message length and protocol
413 * @return - CA_STATUS_OK or appropriate error code
415 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
417 CAResult_t res = CA_STATUS_OK;
421 return CA_STATUS_INVALID_PARAM;
424 if (NULL == svritem->data)
426 // allocate memory for message header (CoAP header size because it is bigger)
427 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
428 if (NULL == svritem->data)
430 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
431 return CA_MEMORY_ALLOC_FAILED;
435 //read data (assume TLS header) from remote device.
436 //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
437 res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
439 //return if any error occurs
440 if (CA_STATUS_OK != res)
445 //if not enough data received - read them on next CAReceiveMessage() call
446 if (svritem->len < TLS_HEADER_SIZE)
448 OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
452 //if enough data received - parse header
454 if (CAIsTlsMessage(svritem->data, svritem->len))
456 svritem->protocol = TLS;
458 //[3][4] bytes in tls header are tls payload length
459 unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
460 OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
462 svritem->totalLen = message_length + TLS_HEADER_SIZE;
467 svritem->protocol = COAP;
469 //seems CoAP data received. read full coap header.
470 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
472 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
474 if (svritem->len < headerLen)
476 //read required bytes to have full CoAP header
477 //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
478 res = CARecv(svritem, headerLen - svritem->len, 0);
480 //return if any error occurs
481 if (CA_STATUS_OK != res)
486 //if not enough data received - read them on next CAReceiveMessage() call
487 if (svritem->len < headerLen)
489 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
494 //calculate CoAP message length
495 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
498 unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
501 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
502 return CA_MEMORY_ALLOC_FAILED;
504 svritem->data = buffer;
510 * Read message payload from socket item->fd
513 * @param[in/out] item - used socket, buffer and to update received message length
514 * @return - CA_STATUS_OK or appropriate error code
516 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
520 return CA_STATUS_INVALID_PARAM;
523 return CARecv(svritem, svritem->totalLen - svritem->len, 0);
527 * Pass received data to app layer depending on protocol
529 * @param[in/out] item - used buffer, received message length and protocol
531 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
538 switch(svritem->protocol)
542 if (g_packetReceivedCallback)
544 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
551 int ret = CAdecryptTls(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
553 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptTls returned %d", __func__, ret);
557 case UNKNOWN: /* pass through */
559 OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
564 static void CAReceiveMessage(int fd)
566 CAResult_t res = CA_STATUS_OK;
568 //get remote device information from file descriptor.
570 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
573 OIC_LOG(ERROR, TAG, "there is no connection information in list");
577 //totalLen filled only when header fully read and parsed
578 if (0 == svritem->totalLen)
580 res = CAReadHeader(svritem);
584 res = CAReadPayload(svritem);
586 //when successfully read all required data - pass them to upper layer.
587 if (CA_STATUS_OK == res && svritem->len == svritem->totalLen)
589 CAExecuteRequest(svritem);
590 CACleanData(svritem);
594 //disconnect session and clean-up data if any error occurs
595 if (res != CA_STATUS_OK)
597 CADisconnectTCPSession(svritem, index);
598 CACleanData(svritem);
602 static void CAWakeUpForReadFdsUpdate(const char *host)
604 if (caglobals.tcp.connectionFds[1] != -1)
609 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
610 } while ((len == -1) && (errno == EINTR));
612 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
614 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
619 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
620 struct sockaddr_storage *sockaddr)
622 struct addrinfo *addrs = NULL;
623 struct addrinfo hints = { .ai_family = family,
624 .ai_protocol = IPPROTO_TCP,
625 .ai_socktype = SOCK_STREAM,
626 .ai_flags = AI_NUMERICHOST };
628 int r = getaddrinfo(host, NULL, &hints, &addrs);
633 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
637 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
640 return CA_STATUS_FAILED;
642 // assumption: in this case, getaddrinfo will only return one addrinfo
643 // or first is the one we want.
644 if (addrs[0].ai_family == AF_INET6)
646 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
647 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
651 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
652 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
658 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
660 // #1. create tcp socket.
661 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
664 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
668 // #2. convert address from string to binary.
669 struct sockaddr_storage sa = { .ss_family = family };
670 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
671 svritem->sep.endpoint.port, &sa);
672 if (CA_STATUS_OK != res)
678 // #3. set socket length.
679 socklen_t socklen = 0;
680 if (sa.ss_family == AF_INET6)
682 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
683 if (!sock6->sin6_scope_id)
685 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
687 socklen = sizeof(struct sockaddr_in6);
691 socklen = sizeof(struct sockaddr_in);
694 // #4. connect to remote server device.
695 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
697 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
702 OIC_LOG(DEBUG, TAG, "connect socket success");
703 CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
707 static int CACreateAcceptSocket(int family, CASocket_t *sock)
709 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
713 OIC_LOG(DEBUG, TAG, "accept socket created already");
717 socklen_t socklen = 0;
718 struct sockaddr_storage server = { .ss_family = family };
720 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
723 OIC_LOG(ERROR, TAG, "Failed to create socket");
727 if (family == AF_INET6)
729 // the socket is restricted to sending and receiving IPv6 packets only.
731 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
733 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
736 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
737 socklen = sizeof (struct sockaddr_in6);
741 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
742 socklen = sizeof (struct sockaddr_in);
746 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
748 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
752 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
754 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
758 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
760 OIC_LOG(ERROR, TAG, "listen() error");
764 if (!sock->port) // return the assigned port
766 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
768 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
771 sock->port = ntohs(family == AF_INET6 ?
772 ((struct sockaddr_in6 *)&server)->sin6_port :
773 ((struct sockaddr_in *)&server)->sin_port);
786 static void CAInitializePipe(int *fds)
791 ret = fcntl(fds[0], F_GETFD);
794 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
798 ret = fcntl(fds[1], F_GETFD);
802 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
812 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
817 #define NEWSOCKET(FAMILY, NAME) \
818 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
819 if (caglobals.tcp.NAME.fd == -1) \
821 caglobals.tcp.NAME.port = 0; \
822 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
824 CHECKFD(caglobals.tcp.NAME.fd);
826 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
828 if (caglobals.tcp.started)
833 if (!caglobals.tcp.ipv4tcpenabled)
835 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
837 if (!caglobals.tcp.ipv6tcpenabled)
839 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
842 CAResult_t res = CATCPCreateMutex();
843 if (CA_STATUS_OK == res)
845 res = CATCPCreateCond();
847 if (CA_STATUS_OK != res)
849 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
853 oc_mutex_lock(g_mutexObjectList);
854 if (!caglobals.tcp.svrlist)
856 caglobals.tcp.svrlist = u_arraylist_create();
858 oc_mutex_unlock(g_mutexObjectList);
860 if (caglobals.server)
862 NEWSOCKET(AF_INET, ipv4);
863 NEWSOCKET(AF_INET6, ipv6);
864 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
865 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
866 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
867 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
870 // create pipe for fast shutdown
871 CAInitializePipe(caglobals.tcp.shutdownFds);
872 CHECKFD(caglobals.tcp.shutdownFds[0]);
873 CHECKFD(caglobals.tcp.shutdownFds[1]);
875 // create pipe for connection event
876 CAInitializePipe(caglobals.tcp.connectionFds);
877 CHECKFD(caglobals.tcp.connectionFds[0]);
878 CHECKFD(caglobals.tcp.connectionFds[1]);
880 caglobals.tcp.terminate = false;
881 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
882 if (CA_STATUS_OK != res)
884 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
887 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
889 caglobals.tcp.started = true;
893 void CATCPStopServer()
896 oc_mutex_lock(g_mutexObjectList);
898 // set terminate flag
899 caglobals.tcp.terminate = true;
901 if (caglobals.tcp.shutdownFds[1] != -1)
903 close(caglobals.tcp.shutdownFds[1]);
904 // receive thread will stop immediately
907 if (caglobals.tcp.connectionFds[1] != -1)
909 close(caglobals.tcp.connectionFds[1]);
912 if (caglobals.tcp.started)
914 oc_cond_wait(g_condObjectList, g_mutexObjectList);
916 caglobals.tcp.started = false;
919 oc_mutex_unlock(g_mutexObjectList);
921 if (-1 != caglobals.tcp.ipv4.fd)
923 close(caglobals.tcp.ipv4.fd);
924 caglobals.tcp.ipv4.fd = -1;
927 if (-1 != caglobals.tcp.ipv6.fd)
929 close(caglobals.tcp.ipv6.fd);
930 caglobals.tcp.ipv6.fd = -1;
933 CATCPDisconnectAll();
938 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
940 g_packetReceivedCallback = callback;
943 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
945 g_connectionCallback = connHandler;
948 static size_t CACheckPayloadLength(const void *data, size_t dlen)
950 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
952 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
953 ((unsigned char *)data)[0] >> 4);
955 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
958 OIC_LOG(ERROR, TAG, "outpdu is null");
962 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
965 OIC_LOG(ERROR, TAG, "pdu parse failed");
966 coap_delete_pdu(pdu);
970 size_t payloadLen = 0;
971 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
972 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
973 headerSize, pdu->length);
974 if (pdu->length > headerSize)
976 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
984 static void sendData(const CAEndpoint_t *endpoint, const void *data,
985 size_t dlen, const char *fam)
987 // #1. get TCP Server object from list
989 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
992 // if there is no connection info, connect to TCP Server
993 svritem = CAConnectTCPSession(endpoint);
996 OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
997 if (g_tcpErrorHandler)
999 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1005 // #2. check payload length
1007 if (false == CAIsTlsMessage(data, dlen))
1010 size_t payloadLen = CACheckPayloadLength(data, dlen);
1011 // if payload length is zero, disconnect from TCP server
1014 OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
1015 CADisconnectTCPSession(svritem, index);
1020 // #3. check connection state
1021 if (svritem->fd < 0)
1023 // if file descriptor value is wrong, remove TCP Server info from list
1024 OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
1025 CADisconnectTCPSession(svritem, index);
1026 if (g_tcpErrorHandler)
1028 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1033 // #4. send data to TCP Server
1034 ssize_t remainLen = dlen;
1037 ssize_t len = send(svritem->fd, data, remainLen, 0);
1040 if (EWOULDBLOCK != errno)
1042 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1043 if (g_tcpErrorHandler)
1045 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1053 } while (remainLen > 0);
1058 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1061 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1064 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1065 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1069 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1071 sendData(endpoint, data, datalen, "ipv6");
1073 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1075 sendData(endpoint, data, datalen, "ipv4");
1080 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1082 VERIFY_NON_NULL(info, TAG, "info is NULL");
1083 VERIFY_NON_NULL(size, TAG, "size is NULL");
1085 return CA_NOT_SUPPORTED;
1088 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
1090 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1092 // #1. create TCP server object
1093 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1096 OIC_LOG(ERROR, TAG, "Out of memory");
1099 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1100 svritem->sep.endpoint.adapter = endpoint->adapter;
1101 svritem->sep.endpoint.port = endpoint->port;
1102 svritem->sep.endpoint.flags = endpoint->flags;
1103 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1105 // #2. create the socket and connect to TCP server
1106 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1107 int fd = CATCPCreateSocket(family, svritem);
1114 // #3. add TCP connection info to list
1116 oc_mutex_lock(g_mutexObjectList);
1117 if (caglobals.tcp.svrlist)
1119 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1122 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1125 oc_mutex_unlock(g_mutexObjectList);
1129 oc_mutex_unlock(g_mutexObjectList);
1133 // pass the connection information to CA Common Layer.
1134 if (g_connectionCallback)
1136 g_connectionCallback(&(svritem->sep.endpoint), true);
1142 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
1144 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
1146 oc_mutex_lock(g_mutexObjectList);
1148 // close the socket and remove TCP connection info in list
1149 if (svritem->fd >= 0)
1153 u_arraylist_remove(caglobals.tcp.svrlist, index);
1154 OICFree(svritem->data);
1155 svritem->data = NULL;
1157 // pass the connection information to CA Common Layer.
1158 if (g_connectionCallback)
1160 g_connectionCallback(&(svritem->sep.endpoint), false);
1164 oc_mutex_unlock(g_mutexObjectList);
1166 return CA_STATUS_OK;
1169 void CATCPDisconnectAll()
1171 oc_mutex_lock(g_mutexObjectList);
1172 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1174 CATCPSessionInfo_t *svritem = NULL;
1175 for (size_t i = 0; i < length; i++)
1177 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1178 if (svritem && svritem->fd >= 0)
1180 shutdown(svritem->fd, SHUT_RDWR);
1183 OICFree(svritem->data);
1184 svritem->data = NULL;
1187 u_arraylist_destroy(caglobals.tcp.svrlist);
1188 oc_mutex_unlock(g_mutexObjectList);
1191 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1193 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1194 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1196 // get connection info from list
1197 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1198 for (size_t i = 0; i < length; i++)
1200 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1201 caglobals.tcp.svrlist, i);
1207 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1208 sizeof(svritem->sep.endpoint.addr))
1209 && (svritem->sep.endpoint.port == endpoint->port)
1210 && (svritem->sep.endpoint.flags & endpoint->flags))
1220 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1222 oc_mutex_lock(g_mutexObjectList);
1224 // check from the last item.
1225 CATCPSessionInfo_t *svritem = NULL;
1226 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1227 for (size_t i = 0; i < length; i++)
1229 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1231 if (svritem && svritem->fd == fd)
1234 oc_mutex_unlock(g_mutexObjectList);
1239 oc_mutex_unlock(g_mutexObjectList);
1244 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1246 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1248 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1249 ((unsigned char *)recvBuffer)[0] >> 4);
1250 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1252 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1254 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1255 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1256 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1258 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1259 return headerLen + optPaylaodLen;
1262 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1264 g_tcpErrorHandler = errorHandleCallback;