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 "caipinterface.h"
43 #include "caadapterutils.h"
45 #include "oic_malloc.h"
46 #include "oic_string.h"
49 #include "ca_adapter_net_tls.h"
53 * Logging tag for module name.
55 #define TAG "OIC_CA_TCP_SERVER"
58 * Maximum CoAP over TCP header length
59 * to know the total data length.
61 #define COAP_MAX_HEADER_SIZE 6
66 #define TLS_HEADER_SIZE 5
69 * Mutex to synchronize device object list.
71 static oc_mutex g_mutexObjectList = NULL;
74 * Conditional mutex to synchronize.
76 static oc_cond g_condObjectList = NULL;
79 * Maintains the callback to be notified when data received from remote device.
81 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
84 * Error callback to update error in TCP.
86 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
89 * Connected Callback to pass the connection information to RI.
91 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
93 static CAResult_t CATCPCreateMutex();
94 static void CATCPDestroyMutex();
95 static CAResult_t CATCPCreateCond();
96 static void CATCPDestroyCond();
97 static int CACreateAcceptSocket(int family, CASocket_t *sock);
98 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
99 static void CAFindReadyMessage();
100 static void CASelectReturned(fd_set *readFds);
101 static void CAReceiveMessage(int fd);
102 static void CAReceiveHandler(void *data);
103 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
105 #define CHECKFD(FD) \
106 if (FD > caglobals.tcp.maxfd) \
107 caglobals.tcp.maxfd = FD;
110 * Read length amount of data from socket item->fd
111 * Can read less data length then requested
112 * Actual read length added to item->len variable
114 * @param[in/out] item - used socket, buffer and to update received message length
115 * @param[in] length - length of data required to read
116 * @param[in] flags - additional info about socket
117 * @return - CA_STATUS_OK or appropriate error code
119 static CAResult_t CARecv(CATCPSessionInfo_t *item, size_t length, int flags)
123 return CA_STATUS_INVALID_PARAM;
126 //skip read operation if requested zero length
132 unsigned char *buffer = item->data + item->len;
134 int len = recv(item->fd, buffer, length, flags);
138 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
139 return CA_RECEIVE_FAILED;
143 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
144 return CA_DESTINATION_DISCONNECTED;
147 OIC_LOG_V(DEBUG, TAG, "recv len = %d", len);
148 OIC_LOG_BUFFER(DEBUG, TAG, buffer, len);
155 static void CATCPDestroyMutex()
157 if (g_mutexObjectList)
159 oc_mutex_free(g_mutexObjectList);
160 g_mutexObjectList = NULL;
164 static CAResult_t CATCPCreateMutex()
166 if (!g_mutexObjectList)
168 g_mutexObjectList = oc_mutex_new();
169 if (!g_mutexObjectList)
171 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
172 return CA_STATUS_FAILED;
179 static void CATCPDestroyCond()
181 if (g_condObjectList)
183 oc_cond_free(g_condObjectList);
184 g_condObjectList = NULL;
188 static CAResult_t CATCPCreateCond()
190 if (!g_condObjectList)
192 g_condObjectList = oc_cond_new();
193 if (!g_condObjectList)
195 OIC_LOG(ERROR, TAG, "Failed to created cond!");
196 return CA_STATUS_FAILED;
202 static void CAReceiveHandler(void *data)
205 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
207 while (!caglobals.tcp.terminate)
209 CAFindReadyMessage();
212 oc_mutex_lock(g_mutexObjectList);
213 oc_cond_signal(g_condObjectList);
214 oc_mutex_unlock(g_mutexObjectList);
216 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
219 static void CAFindReadyMessage()
222 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
226 if (-1 != caglobals.tcp.ipv4.fd)
228 FD_SET(caglobals.tcp.ipv4.fd, &readFds);
230 if (-1 != caglobals.tcp.ipv6.fd)
232 FD_SET(caglobals.tcp.ipv6.fd, &readFds);
234 if (-1 != caglobals.tcp.shutdownFds[0])
236 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
238 if (-1 != caglobals.tcp.connectionFds[0])
240 FD_SET(caglobals.tcp.connectionFds[0], &readFds);
243 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
244 for (size_t i = 0; i < length; i++)
246 CATCPSessionInfo_t *svritem =
247 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
248 if (svritem && 0 <= svritem->fd)
250 FD_SET(svritem->fd, &readFds);
254 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
256 if (caglobals.tcp.terminate)
258 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
265 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
270 CASelectReturned(&readFds);
273 static void CASelectReturned(fd_set *readFds)
275 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
277 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
279 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
282 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
284 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
287 else if (-1 != caglobals.tcp.connectionFds[0] &&
288 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
290 // new connection was created from remote device.
291 // exit the function to update read file descriptor.
292 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
293 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
298 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
299 FD_CLR(caglobals.tcp.connectionFds[0], readFds);
304 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
305 for (size_t i = 0; i < length; i++)
307 CATCPSessionInfo_t *svritem =
308 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
309 if (svritem && svritem->fd >= 0)
311 if (FD_ISSET(svritem->fd, readFds))
313 CAReceiveMessage(svritem->fd);
314 FD_CLR(svritem->fd, readFds);
321 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
323 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
325 struct sockaddr_storage clientaddr;
326 socklen_t clientlen = sizeof (struct sockaddr_in);
329 clientlen = sizeof(struct sockaddr_in6);
332 int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
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 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
348 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
350 oc_mutex_lock(g_mutexObjectList);
351 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
354 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
357 oc_mutex_unlock(g_mutexObjectList);
360 oc_mutex_unlock(g_mutexObjectList);
367 static bool CAIsTlsMessage(const unsigned char* data, size_t length)
369 if (NULL == data || 0 == length)
371 OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
375 unsigned char first_byte = data[0];
377 //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
378 //handshake = [16], application_data = [17] in HEX
379 const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
382 for (i = 0; i < sizeof(tls_head_type); i++)
384 if(tls_head_type[i] == first_byte)
395 * Clean socket state data
397 * @param[in/out] item - socket state data
399 static void CACleanData(CATCPSessionInfo_t *svritem)
403 OICFree(svritem->data);
404 svritem->data = NULL;
406 svritem->totalLen = 0;
407 svritem->protocol = UNKNOWN;
412 * Read message header from socket item->fd
414 * @param[in/out] item - used socket, buffer, current received message length and protocol
415 * @return - CA_STATUS_OK or appropriate error code
417 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
419 CAResult_t res = CA_STATUS_OK;
423 return CA_STATUS_INVALID_PARAM;
426 if (NULL == svritem->data)
428 // allocate memory for message header (CoAP header size because it is bigger)
429 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
430 if (NULL == svritem->data)
432 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
433 return CA_MEMORY_ALLOC_FAILED;
437 //read data (assume TLS header) from remote device.
438 //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
439 res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
441 //return if any error occurs
442 if (CA_STATUS_OK != res)
447 //if not enough data received - read them on next CAReceiveMessage() call
448 if (svritem->len < TLS_HEADER_SIZE)
450 OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
454 //if enough data received - parse header
456 if (CAIsTlsMessage(svritem->data, svritem->len))
458 svritem->protocol = TLS;
460 //[3][4] bytes in tls header are tls payload length
461 unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
462 OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
464 svritem->totalLen = message_length + TLS_HEADER_SIZE;
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);
474 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
476 if (svritem->len < headerLen)
478 //read required bytes to have full CoAP header
479 //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
480 res = CARecv(svritem, headerLen - svritem->len, 0);
482 //return if any error occurs
483 if (CA_STATUS_OK != res)
488 //if not enough data received - read them on next CAReceiveMessage() call
489 if (svritem->len < headerLen)
491 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
496 //calculate CoAP message length
497 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
500 unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
503 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
504 return CA_MEMORY_ALLOC_FAILED;
506 svritem->data = buffer;
512 * Read message payload from socket item->fd
515 * @param[in/out] item - used socket, buffer and to update received message length
516 * @return - CA_STATUS_OK or appropriate error code
518 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
522 return CA_STATUS_INVALID_PARAM;
525 return CARecv(svritem, svritem->totalLen - svritem->len, 0);
529 * Pass received data to app layer depending on protocol
531 * @param[in/out] item - used buffer, received message length and protocol
533 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
540 switch(svritem->protocol)
544 if (g_packetReceivedCallback)
546 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
553 int ret = CAdecryptTls(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
555 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptTls returned %d", __func__, ret);
559 case UNKNOWN: /* pass through */
561 OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
566 static void CAReceiveMessage(int fd)
568 CAResult_t res = CA_STATUS_OK;
570 //get remote device information from file descriptor.
572 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
575 OIC_LOG(ERROR, TAG, "there is no connection information in list");
579 //totalLen filled only when header fully read and parsed
580 if (0 == svritem->totalLen)
582 res = CAReadHeader(svritem);
586 res = CAReadPayload(svritem);
588 //when successfully read all required data - pass them to upper layer.
589 if (CA_STATUS_OK == res && svritem->len == svritem->totalLen)
591 CAExecuteRequest(svritem);
592 CACleanData(svritem);
596 //disconnect session and clean-up data if any error occurs
597 if (res != CA_STATUS_OK)
599 CADisconnectTCPSession(svritem, index);
600 CACleanData(svritem);
604 static void CAWakeUpForReadFdsUpdate(const char *host)
606 if (caglobals.tcp.connectionFds[1] != -1)
611 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
612 } while ((len == -1) && (errno == EINTR));
614 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
616 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
621 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
622 struct sockaddr_storage *sockaddr)
624 struct addrinfo *addrs = NULL;
625 struct addrinfo hints = { .ai_family = family,
626 .ai_protocol = IPPROTO_TCP,
627 .ai_socktype = SOCK_STREAM,
628 .ai_flags = AI_NUMERICHOST };
630 int r = getaddrinfo(host, NULL, &hints, &addrs);
635 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
639 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
642 return CA_STATUS_FAILED;
644 // assumption: in this case, getaddrinfo will only return one addrinfo
645 // or first is the one we want.
646 if (addrs[0].ai_family == AF_INET6)
648 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
649 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
653 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
654 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
660 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
662 // #1. create tcp socket.
663 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
666 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
670 // #2. convert address from string to binary.
671 struct sockaddr_storage sa = { .ss_family = family };
672 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
673 svritem->sep.endpoint.port, &sa);
674 if (CA_STATUS_OK != res)
680 // #3. set socket length.
681 socklen_t socklen = 0;
682 if (sa.ss_family == AF_INET6)
684 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
685 if (!sock6->sin6_scope_id)
687 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
689 socklen = sizeof(struct sockaddr_in6);
693 socklen = sizeof(struct sockaddr_in);
696 // #4. connect to remote server device.
697 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
699 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
704 OIC_LOG(DEBUG, TAG, "connect socket success");
705 CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
709 static int CACreateAcceptSocket(int family, CASocket_t *sock)
711 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
715 OIC_LOG(DEBUG, TAG, "accept socket created already");
719 socklen_t socklen = 0;
720 struct sockaddr_storage server = { .ss_family = family };
722 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
725 OIC_LOG(ERROR, TAG, "Failed to create socket");
729 if (family == AF_INET6)
731 // the socket is restricted to sending and receiving IPv6 packets only.
733 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
735 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
738 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
739 socklen = sizeof (struct sockaddr_in6);
743 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
744 socklen = sizeof (struct sockaddr_in);
748 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
750 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
754 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
756 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
760 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
762 OIC_LOG(ERROR, TAG, "listen() error");
766 if (!sock->port) // return the assigned port
768 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
770 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
773 sock->port = ntohs(family == AF_INET6 ?
774 ((struct sockaddr_in6 *)&server)->sin6_port :
775 ((struct sockaddr_in *)&server)->sin_port);
788 static void CAInitializePipe(int *fds)
793 ret = fcntl(fds[0], F_GETFD);
796 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
800 ret = fcntl(fds[1], F_GETFD);
804 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
814 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
819 #define NEWSOCKET(FAMILY, NAME) \
820 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
821 if (caglobals.tcp.NAME.fd == -1) \
823 caglobals.tcp.NAME.port = 0; \
824 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
826 CHECKFD(caglobals.tcp.NAME.fd);
828 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
830 if (caglobals.tcp.started)
835 if (!caglobals.tcp.ipv4tcpenabled)
837 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
839 if (!caglobals.tcp.ipv6tcpenabled)
841 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
844 CAResult_t res = CATCPCreateMutex();
845 if (CA_STATUS_OK == res)
847 res = CATCPCreateCond();
849 if (CA_STATUS_OK != res)
851 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
855 oc_mutex_lock(g_mutexObjectList);
856 if (!caglobals.tcp.svrlist)
858 caglobals.tcp.svrlist = u_arraylist_create();
860 oc_mutex_unlock(g_mutexObjectList);
862 if (caglobals.server)
864 NEWSOCKET(AF_INET, ipv4);
865 NEWSOCKET(AF_INET6, ipv6);
866 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
867 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
868 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
869 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
872 // create pipe for fast shutdown
873 CAInitializePipe(caglobals.tcp.shutdownFds);
874 CHECKFD(caglobals.tcp.shutdownFds[0]);
875 CHECKFD(caglobals.tcp.shutdownFds[1]);
877 // create pipe for connection event
878 CAInitializePipe(caglobals.tcp.connectionFds);
879 CHECKFD(caglobals.tcp.connectionFds[0]);
880 CHECKFD(caglobals.tcp.connectionFds[1]);
882 caglobals.tcp.terminate = false;
883 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
884 if (CA_STATUS_OK != res)
886 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
889 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
891 caglobals.tcp.started = true;
895 void CATCPStopServer()
898 oc_mutex_lock(g_mutexObjectList);
900 // set terminate flag
901 caglobals.tcp.terminate = true;
903 if (caglobals.tcp.shutdownFds[1] != -1)
905 close(caglobals.tcp.shutdownFds[1]);
906 // receive thread will stop immediately
909 if (caglobals.tcp.connectionFds[1] != -1)
911 close(caglobals.tcp.connectionFds[1]);
914 if (caglobals.tcp.started)
916 oc_cond_wait(g_condObjectList, g_mutexObjectList);
918 caglobals.tcp.started = false;
921 oc_mutex_unlock(g_mutexObjectList);
923 if (-1 != caglobals.tcp.ipv4.fd)
925 close(caglobals.tcp.ipv4.fd);
926 caglobals.tcp.ipv4.fd = -1;
929 if (-1 != caglobals.tcp.ipv6.fd)
931 close(caglobals.tcp.ipv6.fd);
932 caglobals.tcp.ipv6.fd = -1;
935 CATCPDisconnectAll();
940 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
942 g_packetReceivedCallback = callback;
945 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
947 g_connectionCallback = connHandler;
950 static size_t CACheckPayloadLength(const void *data, size_t dlen)
952 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
954 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
955 ((unsigned char *)data)[0] >> 4);
957 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
960 OIC_LOG(ERROR, TAG, "outpdu is null");
964 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
967 OIC_LOG(ERROR, TAG, "pdu parse failed");
968 coap_delete_pdu(pdu);
972 size_t payloadLen = 0;
973 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
974 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
975 headerSize, pdu->length);
976 if (pdu->length > headerSize)
978 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
986 static void sendData(const CAEndpoint_t *endpoint, const void *data,
987 size_t dlen, const char *fam)
989 // #1. get TCP Server object from list
991 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
994 // if there is no connection info, connect to TCP Server
995 svritem = CAConnectTCPSession(endpoint);
998 OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
999 if (g_tcpErrorHandler)
1001 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1007 // #2. check payload length
1009 if (false == CAIsTlsMessage(data, dlen))
1012 size_t payloadLen = CACheckPayloadLength(data, dlen);
1013 // if payload length is zero, disconnect from TCP server
1016 OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
1017 CADisconnectTCPSession(svritem, index);
1022 // #3. check connection state
1023 if (svritem->fd < 0)
1025 // if file descriptor value is wrong, remove TCP Server info from list
1026 OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
1027 CADisconnectTCPSession(svritem, index);
1028 if (g_tcpErrorHandler)
1030 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1035 // #4. send data to TCP Server
1036 ssize_t remainLen = dlen;
1039 ssize_t len = send(svritem->fd, data, remainLen, 0);
1042 if (EWOULDBLOCK != errno)
1044 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1045 if (g_tcpErrorHandler)
1047 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1055 } while (remainLen > 0);
1060 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1063 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1066 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1067 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1071 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1073 sendData(endpoint, data, datalen, "ipv6");
1075 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1077 sendData(endpoint, data, datalen, "ipv4");
1082 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1084 VERIFY_NON_NULL(info, TAG, "info is NULL");
1085 VERIFY_NON_NULL(size, TAG, "size is NULL");
1087 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1090 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1091 return CA_STATUS_FAILED;
1094 uint32_t len = u_arraylist_length(iflist);
1096 CAEndpoint_t *ep = (CAEndpoint_t *)OICCalloc(len, sizeof (CAEndpoint_t));
1099 OIC_LOG(ERROR, TAG, "Malloc Failed");
1100 u_arraylist_destroy(iflist);
1101 return CA_MEMORY_ALLOC_FAILED;
1104 for (uint32_t i = 0, j = 0; i < len; i++)
1106 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1112 ep[j].adapter = CA_ADAPTER_TCP;
1115 if (ifitem->family == AF_INET6)
1117 ep[j].flags = CA_IPV6;
1118 ep[j].port = caglobals.tcp.ipv6.port;
1120 else if (ifitem->family == AF_INET)
1122 ep[j].flags = CA_IPV4;
1123 ep[j].port = caglobals.tcp.ipv4.port;
1129 OICStrcpy(ep[j].addr, sizeof(ep[j].addr), ifitem->addr);
1136 u_arraylist_destroy(iflist);
1138 return CA_STATUS_OK;
1141 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
1143 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1145 // #1. create TCP server object
1146 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1149 OIC_LOG(ERROR, TAG, "Out of memory");
1152 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1153 svritem->sep.endpoint.adapter = endpoint->adapter;
1154 svritem->sep.endpoint.port = endpoint->port;
1155 svritem->sep.endpoint.flags = endpoint->flags;
1156 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1158 // #2. create the socket and connect to TCP server
1159 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1160 int fd = CATCPCreateSocket(family, svritem);
1167 // #3. add TCP connection info to list
1169 oc_mutex_lock(g_mutexObjectList);
1170 if (caglobals.tcp.svrlist)
1172 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1175 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1178 oc_mutex_unlock(g_mutexObjectList);
1182 oc_mutex_unlock(g_mutexObjectList);
1186 // pass the connection information to CA Common Layer.
1187 if (g_connectionCallback)
1189 g_connectionCallback(&(svritem->sep.endpoint), true);
1195 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
1197 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
1199 oc_mutex_lock(g_mutexObjectList);
1201 // close the socket and remove TCP connection info in list
1202 if (svritem->fd >= 0)
1206 u_arraylist_remove(caglobals.tcp.svrlist, index);
1207 OICFree(svritem->data);
1208 svritem->data = NULL;
1210 // pass the connection information to CA Common Layer.
1211 if (g_connectionCallback)
1213 g_connectionCallback(&(svritem->sep.endpoint), false);
1217 oc_mutex_unlock(g_mutexObjectList);
1219 return CA_STATUS_OK;
1222 void CATCPDisconnectAll()
1224 oc_mutex_lock(g_mutexObjectList);
1225 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1227 CATCPSessionInfo_t *svritem = NULL;
1228 for (size_t i = 0; i < length; i++)
1230 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1231 if (svritem && svritem->fd >= 0)
1233 shutdown(svritem->fd, SHUT_RDWR);
1236 OICFree(svritem->data);
1237 svritem->data = NULL;
1240 u_arraylist_destroy(caglobals.tcp.svrlist);
1241 oc_mutex_unlock(g_mutexObjectList);
1244 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1246 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1247 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1249 // get connection info from list
1250 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1251 for (size_t i = 0; i < length; i++)
1253 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1254 caglobals.tcp.svrlist, i);
1260 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1261 sizeof(svritem->sep.endpoint.addr))
1262 && (svritem->sep.endpoint.port == endpoint->port)
1263 && (svritem->sep.endpoint.flags & endpoint->flags))
1273 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1275 oc_mutex_lock(g_mutexObjectList);
1277 // check from the last item.
1278 CATCPSessionInfo_t *svritem = NULL;
1279 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1280 for (size_t i = 0; i < length; i++)
1282 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1284 if (svritem && svritem->fd == fd)
1287 oc_mutex_unlock(g_mutexObjectList);
1292 oc_mutex_unlock(g_mutexObjectList);
1297 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1299 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1301 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1302 ((unsigned char *)recvBuffer)[0] >> 4);
1303 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1305 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1307 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1308 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1309 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1311 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1312 return headerLen + optPaylaodLen;
1315 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1317 g_tcpErrorHandler = errorHandleCallback;