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)
599 if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
601 OIC_LOG(ERROR, TAG, "Failed to close TLS session");
604 CADisconnectTCPSession(svritem, index);
605 CACleanData(svritem);
609 static void CAWakeUpForReadFdsUpdate(const char *host)
611 if (caglobals.tcp.connectionFds[1] != -1)
616 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
617 } while ((len == -1) && (errno == EINTR));
619 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
621 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
626 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
627 struct sockaddr_storage *sockaddr)
629 struct addrinfo *addrs = NULL;
630 struct addrinfo hints = { .ai_family = family,
631 .ai_protocol = IPPROTO_TCP,
632 .ai_socktype = SOCK_STREAM,
633 .ai_flags = AI_NUMERICHOST };
635 int r = getaddrinfo(host, NULL, &hints, &addrs);
640 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
644 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
647 return CA_STATUS_FAILED;
649 // assumption: in this case, getaddrinfo will only return one addrinfo
650 // or first is the one we want.
651 if (addrs[0].ai_family == AF_INET6)
653 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
654 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
658 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
659 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
665 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
667 // #1. create tcp socket.
668 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
671 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
675 // #2. convert address from string to binary.
676 struct sockaddr_storage sa = { .ss_family = family };
677 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
678 svritem->sep.endpoint.port, &sa);
679 if (CA_STATUS_OK != res)
685 // #3. set socket length.
686 socklen_t socklen = 0;
687 if (sa.ss_family == AF_INET6)
689 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
690 if (!sock6->sin6_scope_id)
692 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
694 socklen = sizeof(struct sockaddr_in6);
698 socklen = sizeof(struct sockaddr_in);
701 // #4. connect to remote server device.
702 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
704 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
709 OIC_LOG(DEBUG, TAG, "connect socket success");
710 CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
714 static int CACreateAcceptSocket(int family, CASocket_t *sock)
716 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
720 OIC_LOG(DEBUG, TAG, "accept socket created already");
724 socklen_t socklen = 0;
725 struct sockaddr_storage server = { .ss_family = family };
727 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
730 OIC_LOG(ERROR, TAG, "Failed to create socket");
734 if (family == AF_INET6)
736 // the socket is restricted to sending and receiving IPv6 packets only.
738 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
740 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
743 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
744 socklen = sizeof (struct sockaddr_in6);
748 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
749 socklen = sizeof (struct sockaddr_in);
753 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
755 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
759 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
761 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
765 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
767 OIC_LOG(ERROR, TAG, "listen() error");
771 if (!sock->port) // return the assigned port
773 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
775 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
778 sock->port = ntohs(family == AF_INET6 ?
779 ((struct sockaddr_in6 *)&server)->sin6_port :
780 ((struct sockaddr_in *)&server)->sin_port);
793 static void CAInitializePipe(int *fds)
798 ret = fcntl(fds[0], F_GETFD);
801 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
805 ret = fcntl(fds[1], F_GETFD);
809 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
819 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
824 #define NEWSOCKET(FAMILY, NAME) \
825 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
826 if (caglobals.tcp.NAME.fd == -1) \
828 caglobals.tcp.NAME.port = 0; \
829 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
831 CHECKFD(caglobals.tcp.NAME.fd);
833 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
835 if (caglobals.tcp.started)
840 if (!caglobals.tcp.ipv4tcpenabled)
842 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
844 if (!caglobals.tcp.ipv6tcpenabled)
846 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
849 CAResult_t res = CATCPCreateMutex();
850 if (CA_STATUS_OK == res)
852 res = CATCPCreateCond();
854 if (CA_STATUS_OK != res)
856 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
860 ca_mutex_lock(g_mutexObjectList);
861 if (!caglobals.tcp.svrlist)
863 caglobals.tcp.svrlist = u_arraylist_create();
865 ca_mutex_unlock(g_mutexObjectList);
867 if (caglobals.server)
869 NEWSOCKET(AF_INET, ipv4);
870 NEWSOCKET(AF_INET6, ipv6);
871 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
872 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
873 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
874 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
877 // create pipe for fast shutdown
878 CAInitializePipe(caglobals.tcp.shutdownFds);
879 CHECKFD(caglobals.tcp.shutdownFds[0]);
880 CHECKFD(caglobals.tcp.shutdownFds[1]);
882 // create pipe for connection event
883 CAInitializePipe(caglobals.tcp.connectionFds);
884 CHECKFD(caglobals.tcp.connectionFds[0]);
885 CHECKFD(caglobals.tcp.connectionFds[1]);
887 caglobals.tcp.terminate = false;
888 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
889 if (CA_STATUS_OK != res)
891 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
894 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
896 caglobals.tcp.started = true;
900 void CATCPStopServer()
903 ca_mutex_lock(g_mutexObjectList);
905 // set terminate flag
906 caglobals.tcp.terminate = true;
908 if (caglobals.tcp.shutdownFds[1] != -1)
910 close(caglobals.tcp.shutdownFds[1]);
911 // receive thread will stop immediately
914 if (caglobals.tcp.connectionFds[1] != -1)
916 close(caglobals.tcp.connectionFds[1]);
919 if (caglobals.tcp.started)
921 ca_cond_wait(g_condObjectList, g_mutexObjectList);
923 caglobals.tcp.started = false;
926 ca_mutex_unlock(g_mutexObjectList);
928 if (-1 != caglobals.tcp.ipv4.fd)
930 close(caglobals.tcp.ipv4.fd);
931 caglobals.tcp.ipv4.fd = -1;
934 if (-1 != caglobals.tcp.ipv6.fd)
936 close(caglobals.tcp.ipv6.fd);
937 caglobals.tcp.ipv6.fd = -1;
940 CATCPDisconnectAll();
945 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
947 g_packetReceivedCallback = callback;
950 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
952 g_connectionCallback = connHandler;
955 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
957 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
959 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
960 ((unsigned char *)data)[0] >> 4);
962 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
965 OIC_LOG(ERROR, TAG, "outpdu is null");
969 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
972 OIC_LOG(ERROR, TAG, "pdu parse failed");
973 coap_delete_pdu(pdu);
977 size_t payloadLen = 0;
978 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
979 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
980 headerSize, pdu->length);
981 if (pdu->length > headerSize)
983 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
991 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
992 size_t dlen, const char *fam)
994 // #1. get TCP Server object from list
996 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
999 // if there is no connection info, connect to TCP Server
1000 svritem = CAConnectTCPSession(endpoint);
1003 OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
1008 // #2. check connection state
1009 if (svritem->fd < 0)
1011 // if file descriptor value is wrong, remove TCP Server info from list
1012 OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
1016 // #3. send data to TCP Server
1017 ssize_t remainLen = dlen;
1020 ssize_t len = send(svritem->fd, data, remainLen, 0);
1023 if (EWOULDBLOCK != errno)
1025 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1032 } while (remainLen > 0);
1037 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1041 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1043 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1044 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1046 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1048 return sendData(endpoint, data, datalen, "ipv6");
1050 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1052 return sendData(endpoint, data, datalen, "ipv4");
1057 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1059 VERIFY_NON_NULL(info, TAG, "info is NULL");
1060 VERIFY_NON_NULL(size, TAG, "size is NULL");
1062 return CA_NOT_SUPPORTED;
1065 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
1067 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1069 // #1. create TCP server object
1070 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1073 OIC_LOG(ERROR, TAG, "Out of memory");
1076 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1077 svritem->sep.endpoint.adapter = endpoint->adapter;
1078 svritem->sep.endpoint.port = endpoint->port;
1079 svritem->sep.endpoint.flags = endpoint->flags;
1080 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1082 // #2. create the socket and connect to TCP server
1083 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1084 int fd = CATCPCreateSocket(family, svritem);
1091 // #3. add TCP connection info to list
1093 ca_mutex_lock(g_mutexObjectList);
1094 if (caglobals.tcp.svrlist)
1096 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1099 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1102 ca_mutex_unlock(g_mutexObjectList);
1106 ca_mutex_unlock(g_mutexObjectList);
1110 // pass the connection information to CA Common Layer.
1111 if (g_connectionCallback)
1113 g_connectionCallback(&(svritem->sep.endpoint), true);
1119 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
1121 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
1123 ca_mutex_lock(g_mutexObjectList);
1125 // close the socket and remove TCP connection info in list
1126 if (svritem->fd >= 0)
1130 u_arraylist_remove(caglobals.tcp.svrlist, index);
1131 OICFree(svritem->data);
1132 svritem->data = NULL;
1134 // pass the connection information to CA Common Layer.
1135 if (g_connectionCallback)
1137 g_connectionCallback(&(svritem->sep.endpoint), false);
1141 ca_mutex_unlock(g_mutexObjectList);
1143 return CA_STATUS_OK;
1146 void CATCPDisconnectAll()
1148 ca_mutex_lock(g_mutexObjectList);
1149 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1150 CATCPSessionInfo_t *svritem = NULL;
1151 for (size_t i = 0; i < length; i++)
1153 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1154 if (svritem && svritem->fd >= 0)
1156 shutdown(svritem->fd, SHUT_RDWR);
1158 OICFree(svritem->data);
1159 svritem->data = NULL;
1161 // pass the connection information to CA Common Layer.
1162 if (g_connectionCallback)
1164 g_connectionCallback(&(svritem->sep.endpoint), false);
1168 u_arraylist_destroy(caglobals.tcp.svrlist);
1169 caglobals.tcp.svrlist = NULL;
1170 ca_mutex_unlock(g_mutexObjectList);
1173 CAcloseSslConnectionAll();
1178 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1180 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1181 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1183 // get connection info from list
1184 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1185 for (size_t i = 0; i < length; i++)
1187 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1188 caglobals.tcp.svrlist, i);
1194 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1195 sizeof(svritem->sep.endpoint.addr))
1196 && (svritem->sep.endpoint.port == endpoint->port)
1197 && (svritem->sep.endpoint.flags & endpoint->flags))
1207 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1209 ca_mutex_lock(g_mutexObjectList);
1211 // check from the last item.
1212 CATCPSessionInfo_t *svritem = NULL;
1213 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1214 for (size_t i = 0; i < length; i++)
1216 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1218 if (svritem && svritem->fd == fd)
1221 ca_mutex_unlock(g_mutexObjectList);
1226 ca_mutex_unlock(g_mutexObjectList);
1231 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1233 CAResult_t result = CA_STATUS_OK;
1235 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1238 result = CADisconnectTCPSession(svritem, index);
1239 if (CA_STATUS_OK != result)
1241 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1248 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1250 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1252 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1253 ((unsigned char *)recvBuffer)[0] >> 4);
1254 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1256 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1258 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1259 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1260 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1262 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1263 return headerLen + optPaylaodLen;
1266 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1268 g_tcpErrorHandler = errorHandleCallback;