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 int 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 int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
104 #define CHECKFD(FD) \
105 if (FD > caglobals.tcp.maxfd) \
106 caglobals.tcp.maxfd = FD;
109 * Read length amount of data from socket item->fd
110 * Can read less data length then requested
111 * Actual read length added to item->len variable
113 * @param[in/out] item - used socket, buffer and to update received message length
114 * @param[in] length - length of data required to read
115 * @param[in] flags - additional info about socket
116 * @return - CA_STATUS_OK or appropriate error code
118 static CAResult_t CARecv(CATCPSessionInfo_t *item, size_t length, int flags)
122 return CA_STATUS_INVALID_PARAM;
125 //skip read operation if requested zero length
131 unsigned char *buffer = item->data + item->len;
133 int len = recv(item->fd, buffer, length, flags);
137 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
138 return CA_RECEIVE_FAILED;
142 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
143 return CA_DESTINATION_DISCONNECTED;
146 OIC_LOG_V(DEBUG, TAG, "recv len = %d", len);
147 OIC_LOG_BUFFER(DEBUG, TAG, buffer, len);
154 static void CATCPDestroyMutex()
156 if (g_mutexObjectList)
158 ca_mutex_free(g_mutexObjectList);
159 g_mutexObjectList = NULL;
163 static CAResult_t CATCPCreateMutex()
165 if (!g_mutexObjectList)
167 g_mutexObjectList = ca_mutex_new();
168 if (!g_mutexObjectList)
170 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
171 return CA_STATUS_FAILED;
178 static void CATCPDestroyCond()
180 if (g_condObjectList)
182 ca_cond_free(g_condObjectList);
183 g_condObjectList = NULL;
187 static CAResult_t CATCPCreateCond()
189 if (!g_condObjectList)
191 g_condObjectList = ca_cond_new();
192 if (!g_condObjectList)
194 OIC_LOG(ERROR, TAG, "Failed to created cond!");
195 return CA_STATUS_FAILED;
201 static void CAReceiveHandler(void *data)
204 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
206 while (!caglobals.tcp.terminate)
208 CAFindReadyMessage();
211 ca_mutex_lock(g_mutexObjectList);
212 ca_cond_signal(g_condObjectList);
213 ca_mutex_unlock(g_mutexObjectList);
215 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
218 static void CAFindReadyMessage()
221 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
225 if (-1 != caglobals.tcp.ipv4.fd)
227 FD_SET(caglobals.tcp.ipv4.fd, &readFds);
229 if (-1 != caglobals.tcp.ipv6.fd)
231 FD_SET(caglobals.tcp.ipv6.fd, &readFds);
233 if (-1 != caglobals.tcp.shutdownFds[0])
235 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
237 if (-1 != caglobals.tcp.connectionFds[0])
239 FD_SET(caglobals.tcp.connectionFds[0], &readFds);
242 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
243 for (size_t i = 0; i < length; i++)
245 CATCPSessionInfo_t *svritem =
246 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
247 if (svritem && 0 <= svritem->fd)
249 FD_SET(svritem->fd, &readFds);
253 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
255 if (caglobals.tcp.terminate)
257 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
264 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
269 CASelectReturned(&readFds);
272 static void CASelectReturned(fd_set *readFds)
274 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
276 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
278 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
281 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
283 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
286 else if (-1 != caglobals.tcp.connectionFds[0] &&
287 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
289 // new connection was created from remote device.
290 // exit the function to update read file descriptor.
291 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
292 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
297 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
298 FD_CLR(caglobals.tcp.connectionFds[0], readFds);
303 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
304 for (size_t i = 0; i < length; i++)
306 CATCPSessionInfo_t *svritem =
307 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
308 if (svritem && svritem->fd >= 0)
310 if (FD_ISSET(svritem->fd, readFds))
312 CAReceiveMessage(svritem->fd);
313 FD_CLR(svritem->fd, readFds);
320 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
322 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
324 struct sockaddr_storage clientaddr;
325 socklen_t clientlen = sizeof (struct sockaddr_in);
328 clientlen = sizeof(struct sockaddr_in6);
331 int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
334 CATCPSessionInfo_t *svritem =
335 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
338 OIC_LOG(ERROR, TAG, "Out of memory");
343 svritem->fd = sockfd;
344 svritem->sep.endpoint.flags = flag;
345 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
346 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
347 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
349 ca_mutex_lock(g_mutexObjectList);
350 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
353 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
356 ca_mutex_unlock(g_mutexObjectList);
359 ca_mutex_unlock(g_mutexObjectList);
366 static bool CAIsTlsMessage(const unsigned char* data, size_t length)
368 if (NULL == data || 0 == length)
370 OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
374 unsigned char first_byte = data[0];
376 //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
377 //handshake = [16], application_data = [17] in HEX
378 const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
381 for (i = 0; i < sizeof(tls_head_type); i++)
383 if(tls_head_type[i] == first_byte)
394 * Clean socket state data
396 * @param[in/out] item - socket state data
398 static void CACleanData(CATCPSessionInfo_t *svritem)
402 OICFree(svritem->data);
403 svritem->data = NULL;
405 svritem->totalLen = 0;
406 svritem->protocol = UNKNOWN;
411 * Read message header from socket item->fd
413 * @param[in/out] item - used socket, buffer, current received message length and protocol
414 * @return - CA_STATUS_OK or appropriate error code
416 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
418 CAResult_t res = CA_STATUS_OK;
422 return CA_STATUS_INVALID_PARAM;
425 if (NULL == svritem->data)
427 // allocate memory for message header (CoAP header size because it is bigger)
428 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
429 if (NULL == svritem->data)
431 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
432 return CA_MEMORY_ALLOC_FAILED;
436 //read data (assume TLS header) from remote device.
437 //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
438 res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
440 //return if any error occurs
441 if (CA_STATUS_OK != res)
446 //if not enough data received - read them on next CAReceiveMessage() call
447 if (svritem->len < TLS_HEADER_SIZE)
449 OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
453 //if enough data received - parse header
455 if (CAIsTlsMessage(svritem->data, svritem->len))
457 svritem->protocol = TLS;
459 //[3][4] bytes in tls header are tls payload length
460 unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
461 OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
463 svritem->totalLen = message_length + TLS_HEADER_SIZE;
468 svritem->protocol = COAP;
470 //seems CoAP data received. read full coap header.
471 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);
475 if (svritem->len < headerLen)
477 //read required bytes to have full CoAP header
478 //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
479 res = CARecv(svritem, headerLen - svritem->len, 0);
481 //return if any error occurs
482 if (CA_STATUS_OK != res)
487 //if not enough data received - read them on next CAReceiveMessage() call
488 if (svritem->len < headerLen)
490 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
495 //calculate CoAP message length
496 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
499 unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
502 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
503 return CA_MEMORY_ALLOC_FAILED;
505 svritem->data = buffer;
511 * Read message payload from socket item->fd
514 * @param[in/out] item - used socket, buffer and to update received message length
515 * @return - CA_STATUS_OK or appropriate error code
517 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
521 return CA_STATUS_INVALID_PARAM;
524 return CARecv(svritem, svritem->totalLen - svritem->len, 0);
528 * Pass received data to app layer depending on protocol
530 * @param[in/out] item - used buffer, received message length and protocol
532 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
539 switch(svritem->protocol)
543 if (g_packetReceivedCallback)
545 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
552 int ret = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
554 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, ret);
558 case UNKNOWN: /* pass through */
560 OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
565 static void CAReceiveMessage(int fd)
567 CAResult_t res = CA_STATUS_OK;
569 //get remote device information from file descriptor.
571 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
574 OIC_LOG(ERROR, TAG, "there is no connection information in list");
578 //totalLen filled only when header fully read and parsed
579 if (0 == svritem->totalLen)
581 res = CAReadHeader(svritem);
585 res = CAReadPayload(svritem);
587 //when successfully read all required data - pass them to upper layer.
588 if (CA_STATUS_OK == res && svritem->len == svritem->totalLen)
590 CAExecuteRequest(svritem);
591 CACleanData(svritem);
595 //disconnect session and clean-up data if any error occurs
596 if (res != CA_STATUS_OK)
598 CADisconnectTCPSession(svritem, index);
599 CACleanData(svritem);
603 static void CAWakeUpForReadFdsUpdate(const char *host)
605 if (caglobals.tcp.connectionFds[1] != -1)
610 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
611 } while ((len == -1) && (errno == EINTR));
613 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
615 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
620 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
621 struct sockaddr_storage *sockaddr)
623 struct addrinfo *addrs = NULL;
624 struct addrinfo hints = { .ai_family = family,
625 .ai_protocol = IPPROTO_TCP,
626 .ai_socktype = SOCK_STREAM,
627 .ai_flags = AI_NUMERICHOST };
629 int r = getaddrinfo(host, NULL, &hints, &addrs);
634 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
638 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
641 return CA_STATUS_FAILED;
643 // assumption: in this case, getaddrinfo will only return one addrinfo
644 // or first is the one we want.
645 if (addrs[0].ai_family == AF_INET6)
647 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
648 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
652 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
653 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
659 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
661 // #1. create tcp socket.
662 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
665 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
669 // #2. convert address from string to binary.
670 struct sockaddr_storage sa = { .ss_family = family };
671 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
672 svritem->sep.endpoint.port, &sa);
673 if (CA_STATUS_OK != res)
679 // #3. set socket length.
680 socklen_t socklen = 0;
681 if (sa.ss_family == AF_INET6)
683 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
684 if (!sock6->sin6_scope_id)
686 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
688 socklen = sizeof(struct sockaddr_in6);
692 socklen = sizeof(struct sockaddr_in);
695 // #4. connect to remote server device.
696 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
698 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
703 OIC_LOG(DEBUG, TAG, "connect socket success");
704 CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
708 static int CACreateAcceptSocket(int family, CASocket_t *sock)
710 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
714 OIC_LOG(DEBUG, TAG, "accept socket created already");
718 socklen_t socklen = 0;
719 struct sockaddr_storage server = { .ss_family = family };
721 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
724 OIC_LOG(ERROR, TAG, "Failed to create socket");
728 if (family == AF_INET6)
730 // the socket is restricted to sending and receiving IPv6 packets only.
732 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
734 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
737 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
738 socklen = sizeof (struct sockaddr_in6);
742 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
743 socklen = sizeof (struct sockaddr_in);
747 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
749 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
753 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
755 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
759 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
761 OIC_LOG(ERROR, TAG, "listen() error");
765 if (!sock->port) // return the assigned port
767 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
769 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
772 sock->port = ntohs(family == AF_INET6 ?
773 ((struct sockaddr_in6 *)&server)->sin6_port :
774 ((struct sockaddr_in *)&server)->sin_port);
787 static void CAInitializePipe(int *fds)
792 ret = fcntl(fds[0], F_GETFD);
795 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
799 ret = fcntl(fds[1], F_GETFD);
803 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
813 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
818 #define NEWSOCKET(FAMILY, NAME) \
819 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
820 if (caglobals.tcp.NAME.fd == -1) \
822 caglobals.tcp.NAME.port = 0; \
823 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
825 CHECKFD(caglobals.tcp.NAME.fd);
827 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
829 if (caglobals.tcp.started)
834 if (!caglobals.tcp.ipv4tcpenabled)
836 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
838 if (!caglobals.tcp.ipv6tcpenabled)
840 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
843 CAResult_t res = CATCPCreateMutex();
844 if (CA_STATUS_OK == res)
846 res = CATCPCreateCond();
848 if (CA_STATUS_OK != res)
850 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
854 ca_mutex_lock(g_mutexObjectList);
855 if (!caglobals.tcp.svrlist)
857 caglobals.tcp.svrlist = u_arraylist_create();
859 ca_mutex_unlock(g_mutexObjectList);
861 if (caglobals.server)
863 NEWSOCKET(AF_INET, ipv4);
864 NEWSOCKET(AF_INET6, ipv6);
865 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
866 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
867 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
868 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
871 // create pipe for fast shutdown
872 CAInitializePipe(caglobals.tcp.shutdownFds);
873 CHECKFD(caglobals.tcp.shutdownFds[0]);
874 CHECKFD(caglobals.tcp.shutdownFds[1]);
876 // create pipe for connection event
877 CAInitializePipe(caglobals.tcp.connectionFds);
878 CHECKFD(caglobals.tcp.connectionFds[0]);
879 CHECKFD(caglobals.tcp.connectionFds[1]);
881 caglobals.tcp.terminate = false;
882 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
883 if (CA_STATUS_OK != res)
885 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
888 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
890 caglobals.tcp.started = true;
894 void CATCPStopServer()
897 ca_mutex_lock(g_mutexObjectList);
899 // set terminate flag
900 caglobals.tcp.terminate = true;
902 if (caglobals.tcp.shutdownFds[1] != -1)
904 close(caglobals.tcp.shutdownFds[1]);
905 // receive thread will stop immediately
908 if (caglobals.tcp.connectionFds[1] != -1)
910 close(caglobals.tcp.connectionFds[1]);
913 if (caglobals.tcp.started)
915 ca_cond_wait(g_condObjectList, g_mutexObjectList);
917 caglobals.tcp.started = false;
920 ca_mutex_unlock(g_mutexObjectList);
922 if (-1 != caglobals.tcp.ipv4.fd)
924 close(caglobals.tcp.ipv4.fd);
925 caglobals.tcp.ipv4.fd = -1;
928 if (-1 != caglobals.tcp.ipv6.fd)
930 close(caglobals.tcp.ipv6.fd);
931 caglobals.tcp.ipv6.fd = -1;
934 CATCPDisconnectAll();
939 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
941 g_packetReceivedCallback = callback;
944 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
946 g_connectionCallback = connHandler;
949 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
951 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
953 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
954 ((unsigned char *)data)[0] >> 4);
956 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
959 OIC_LOG(ERROR, TAG, "outpdu is null");
963 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
966 OIC_LOG(ERROR, TAG, "pdu parse failed");
967 coap_delete_pdu(pdu);
971 size_t payloadLen = 0;
972 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
973 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
974 headerSize, pdu->length);
975 if (pdu->length > headerSize)
977 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
985 static void sendData(const CAEndpoint_t *endpoint, const void *data,
986 size_t dlen, const char *fam)
988 // #1. get TCP Server object from list
990 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
993 // if there is no connection info, connect to TCP Server
994 svritem = CAConnectTCPSession(endpoint);
997 OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
998 if (g_tcpErrorHandler)
1000 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1006 // #2. check connection state
1007 if (svritem->fd < 0)
1009 // if file descriptor value is wrong, remove TCP Server info from list
1010 OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
1011 CADisconnectTCPSession(svritem, index);
1012 if (g_tcpErrorHandler)
1014 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1019 // #3. send data to TCP Server
1020 ssize_t remainLen = dlen;
1023 ssize_t len = send(svritem->fd, data, remainLen, 0);
1026 if (EWOULDBLOCK != errno)
1028 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1029 if (g_tcpErrorHandler)
1031 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1039 } while (remainLen > 0);
1044 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1047 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1050 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1051 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1055 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1057 sendData(endpoint, data, datalen, "ipv6");
1059 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1061 sendData(endpoint, data, datalen, "ipv4");
1066 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1068 VERIFY_NON_NULL(info, TAG, "info is NULL");
1069 VERIFY_NON_NULL(size, TAG, "size is NULL");
1071 return CA_NOT_SUPPORTED;
1074 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
1076 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1078 // #1. create TCP server object
1079 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1082 OIC_LOG(ERROR, TAG, "Out of memory");
1085 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1086 svritem->sep.endpoint.adapter = endpoint->adapter;
1087 svritem->sep.endpoint.port = endpoint->port;
1088 svritem->sep.endpoint.flags = endpoint->flags;
1089 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1091 // #2. create the socket and connect to TCP server
1092 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1093 int fd = CATCPCreateSocket(family, svritem);
1100 // #3. add TCP connection info to list
1102 ca_mutex_lock(g_mutexObjectList);
1103 if (caglobals.tcp.svrlist)
1105 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1108 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1111 ca_mutex_unlock(g_mutexObjectList);
1115 ca_mutex_unlock(g_mutexObjectList);
1119 // pass the connection information to CA Common Layer.
1120 if (g_connectionCallback)
1122 g_connectionCallback(&(svritem->sep.endpoint), true);
1128 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
1130 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
1132 ca_mutex_lock(g_mutexObjectList);
1135 if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
1137 OIC_LOG(ERROR, TAG, "Failed to close TLS session");
1141 // close the socket and remove TCP connection info in list
1142 if (svritem->fd >= 0)
1146 u_arraylist_remove(caglobals.tcp.svrlist, index);
1147 OICFree(svritem->data);
1148 svritem->data = NULL;
1150 // pass the connection information to CA Common Layer.
1151 if (g_connectionCallback)
1153 g_connectionCallback(&(svritem->sep.endpoint), false);
1157 ca_mutex_unlock(g_mutexObjectList);
1159 return CA_STATUS_OK;
1162 void CATCPDisconnectAll()
1164 ca_mutex_lock(g_mutexObjectList);
1165 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1167 CATCPSessionInfo_t *svritem = NULL;
1168 for (size_t i = 0; i < length; i++)
1170 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1171 if (svritem && svritem->fd >= 0)
1174 if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
1176 OIC_LOG(ERROR, TAG, "Failed to close TLS session");
1179 shutdown(svritem->fd, SHUT_RDWR);
1181 OICFree(svritem->data);
1182 svritem->data = NULL;
1184 // pass the connection information to CA Common Layer.
1185 if (g_connectionCallback)
1187 g_connectionCallback(&(svritem->sep.endpoint), false);
1191 u_arraylist_destroy(caglobals.tcp.svrlist);
1192 caglobals.tcp.svrlist = NULL;
1193 ca_mutex_unlock(g_mutexObjectList);
1196 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1198 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1199 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1201 // get connection info from list
1202 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1203 for (size_t i = 0; i < length; i++)
1205 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1206 caglobals.tcp.svrlist, i);
1212 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1213 sizeof(svritem->sep.endpoint.addr))
1214 && (svritem->sep.endpoint.port == endpoint->port)
1215 && (svritem->sep.endpoint.flags & endpoint->flags))
1225 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1227 ca_mutex_lock(g_mutexObjectList);
1229 // check from the last item.
1230 CATCPSessionInfo_t *svritem = NULL;
1231 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1232 for (size_t i = 0; i < length; i++)
1234 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1236 if (svritem && svritem->fd == fd)
1239 ca_mutex_unlock(g_mutexObjectList);
1244 ca_mutex_unlock(g_mutexObjectList);
1249 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1251 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1253 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1254 ((unsigned char *)recvBuffer)[0] >> 4);
1255 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1257 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1259 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1260 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1261 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1263 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1264 return headerLen + optPaylaodLen;
1267 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1269 g_tcpErrorHandler = errorHandleCallback;