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.");
263 CASelectReturned(&readFds);
267 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
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 if (-1 != svritem->fd)
314 FD_CLR(svritem->fd, readFds);
322 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
324 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
326 struct sockaddr_storage clientaddr;
327 socklen_t clientlen = sizeof (struct sockaddr_in);
330 clientlen = sizeof(struct sockaddr_in6);
333 int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
336 CATCPSessionInfo_t *svritem =
337 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
340 OIC_LOG(ERROR, TAG, "Out of memory");
345 svritem->fd = sockfd;
346 svritem->sep.endpoint.flags = flag;
347 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
348 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
349 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
351 ca_mutex_lock(g_mutexObjectList);
352 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
355 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
358 ca_mutex_unlock(g_mutexObjectList);
361 ca_mutex_unlock(g_mutexObjectList);
368 static bool CAIsTlsMessage(const unsigned char* data, size_t length)
370 if (NULL == data || 0 == length)
372 OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
376 unsigned char first_byte = data[0];
378 //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
379 //handshake = [16], application_data = [17] in HEX
380 const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
383 for (i = 0; i < sizeof(tls_head_type); i++)
385 if(tls_head_type[i] == first_byte)
396 * Clean socket state data
398 * @param[in/out] item - socket state data
400 static void CACleanData(CATCPSessionInfo_t *svritem)
404 OICFree(svritem->data);
405 svritem->data = NULL;
407 svritem->totalLen = 0;
408 svritem->protocol = UNKNOWN;
413 * Read message header from socket item->fd
415 * @param[in/out] item - used socket, buffer, current received message length and protocol
416 * @return - CA_STATUS_OK or appropriate error code
418 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
420 CAResult_t res = CA_STATUS_OK;
424 return CA_STATUS_INVALID_PARAM;
427 if (NULL == svritem->data)
429 // allocate memory for message header (CoAP header size because it is bigger)
430 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
431 if (NULL == svritem->data)
433 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
434 return CA_MEMORY_ALLOC_FAILED;
438 //read data (assume TLS header) from remote device.
439 //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
440 res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
442 //return if any error occurs
443 if (CA_STATUS_OK != res)
448 //if not enough data received - read them on next CAReceiveMessage() call
449 if (svritem->len < TLS_HEADER_SIZE)
451 OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
455 //if enough data received - parse header
457 if (CAIsTlsMessage(svritem->data, svritem->len))
459 svritem->protocol = TLS;
461 //[3][4] bytes in tls header are tls payload length
462 unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
463 OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
465 svritem->totalLen = message_length + TLS_HEADER_SIZE;
470 svritem->protocol = COAP;
472 //seems CoAP data received. read full coap header.
473 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
475 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
477 if (svritem->len < headerLen)
479 //read required bytes to have full CoAP header
480 //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
481 res = CARecv(svritem, headerLen - svritem->len, 0);
483 //return if any error occurs
484 if (CA_STATUS_OK != res)
489 //if not enough data received - read them on next CAReceiveMessage() call
490 if (svritem->len < headerLen)
492 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
497 //calculate CoAP message length
498 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
501 unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
504 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
505 return CA_MEMORY_ALLOC_FAILED;
507 svritem->data = buffer;
513 * Read message payload from socket item->fd
516 * @param[in/out] item - used socket, buffer and to update received message length
517 * @return - CA_STATUS_OK or appropriate error code
519 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
523 return CA_STATUS_INVALID_PARAM;
526 return CARecv(svritem, svritem->totalLen - svritem->len, 0);
530 * Pass received data to app layer depending on protocol
532 * @param[in/out] item - used buffer, received message length and protocol
534 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
541 switch(svritem->protocol)
545 if (g_packetReceivedCallback)
547 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
554 int ret = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
556 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, ret);
560 case UNKNOWN: /* pass through */
562 OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
567 static void CAReceiveMessage(int fd)
569 CAResult_t res = CA_STATUS_OK;
571 //get remote device information from file descriptor.
573 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
576 OIC_LOG(ERROR, TAG, "there is no connection information in list");
580 //totalLen filled only when header fully read and parsed
581 if (0 == svritem->totalLen)
583 res = CAReadHeader(svritem);
587 res = CAReadPayload(svritem);
589 //when successfully read all required data - pass them to upper layer.
590 if (CA_STATUS_OK == res && svritem->len == svritem->totalLen)
592 CAExecuteRequest(svritem);
593 CACleanData(svritem);
597 //disconnect session and clean-up data if any error occurs
598 if (res != CA_STATUS_OK)
601 if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
603 OIC_LOG(ERROR, TAG, "Failed to close TLS session");
606 CASearchAndDeleteTCPSession(&(svritem->sep.endpoint));
611 static void CAWakeUpForReadFdsUpdate(const char *host)
613 if (caglobals.tcp.connectionFds[1] != -1)
618 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
619 } while ((len == -1) && (errno == EINTR));
621 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
623 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
628 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
629 struct sockaddr_storage *sockaddr)
631 struct addrinfo *addrs = NULL;
632 struct addrinfo hints = { .ai_family = family,
633 .ai_protocol = IPPROTO_TCP,
634 .ai_socktype = SOCK_STREAM,
635 .ai_flags = AI_NUMERICHOST };
637 int r = getaddrinfo(host, NULL, &hints, &addrs);
642 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
646 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
649 return CA_STATUS_FAILED;
651 // assumption: in this case, getaddrinfo will only return one addrinfo
652 // or first is the one we want.
653 if (addrs[0].ai_family == AF_INET6)
655 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
656 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
660 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
661 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
667 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
669 // #1. create tcp socket.
670 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
673 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
677 // #2. convert address from string to binary.
678 struct sockaddr_storage sa = { .ss_family = family };
679 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
680 svritem->sep.endpoint.port, &sa);
681 if (CA_STATUS_OK != res)
687 // #3. set socket length.
688 socklen_t socklen = 0;
689 if (sa.ss_family == AF_INET6)
691 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
692 if (!sock6->sin6_scope_id)
694 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
696 socklen = sizeof(struct sockaddr_in6);
700 socklen = sizeof(struct sockaddr_in);
703 // #4. connect to remote server device.
704 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
706 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
711 OIC_LOG(DEBUG, TAG, "connect socket success");
712 CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
716 static int CACreateAcceptSocket(int family, CASocket_t *sock)
718 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
722 OIC_LOG(DEBUG, TAG, "accept socket created already");
726 socklen_t socklen = 0;
727 struct sockaddr_storage server = { .ss_family = family };
729 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
732 OIC_LOG(ERROR, TAG, "Failed to create socket");
736 if (family == AF_INET6)
738 // the socket is restricted to sending and receiving IPv6 packets only.
740 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
742 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
745 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
746 socklen = sizeof (struct sockaddr_in6);
750 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
751 socklen = sizeof (struct sockaddr_in);
755 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
757 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
761 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
763 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
767 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
769 OIC_LOG(ERROR, TAG, "listen() error");
773 if (!sock->port) // return the assigned port
775 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
777 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
780 sock->port = ntohs(family == AF_INET6 ?
781 ((struct sockaddr_in6 *)&server)->sin6_port :
782 ((struct sockaddr_in *)&server)->sin_port);
795 static void CAInitializePipe(int *fds)
800 ret = fcntl(fds[0], F_GETFD);
803 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
807 ret = fcntl(fds[1], F_GETFD);
811 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
821 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
826 #define NEWSOCKET(FAMILY, NAME) \
827 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
828 if (caglobals.tcp.NAME.fd == -1) \
830 caglobals.tcp.NAME.port = 0; \
831 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
833 CHECKFD(caglobals.tcp.NAME.fd);
835 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
837 if (caglobals.tcp.started)
842 if (!caglobals.tcp.ipv4tcpenabled)
844 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
846 if (!caglobals.tcp.ipv6tcpenabled)
848 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
851 CAResult_t res = CATCPCreateMutex();
852 if (CA_STATUS_OK == res)
854 res = CATCPCreateCond();
856 if (CA_STATUS_OK != res)
858 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
862 ca_mutex_lock(g_mutexObjectList);
863 if (!caglobals.tcp.svrlist)
865 caglobals.tcp.svrlist = u_arraylist_create();
867 ca_mutex_unlock(g_mutexObjectList);
869 if (caglobals.server)
871 NEWSOCKET(AF_INET, ipv4);
872 NEWSOCKET(AF_INET6, ipv6);
873 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
874 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
875 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
876 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
879 // create pipe for fast shutdown
880 CAInitializePipe(caglobals.tcp.shutdownFds);
881 CHECKFD(caglobals.tcp.shutdownFds[0]);
882 CHECKFD(caglobals.tcp.shutdownFds[1]);
884 // create pipe for connection event
885 CAInitializePipe(caglobals.tcp.connectionFds);
886 CHECKFD(caglobals.tcp.connectionFds[0]);
887 CHECKFD(caglobals.tcp.connectionFds[1]);
889 caglobals.tcp.terminate = false;
890 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
891 if (CA_STATUS_OK != res)
893 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
896 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
898 caglobals.tcp.started = true;
902 void CATCPStopServer()
905 ca_mutex_lock(g_mutexObjectList);
907 // set terminate flag
908 caglobals.tcp.terminate = true;
910 if (caglobals.tcp.shutdownFds[1] != -1)
912 close(caglobals.tcp.shutdownFds[1]);
913 // receive thread will stop immediately
916 if (caglobals.tcp.connectionFds[1] != -1)
918 close(caglobals.tcp.connectionFds[1]);
921 if (caglobals.tcp.started)
923 ca_cond_wait(g_condObjectList, g_mutexObjectList);
925 caglobals.tcp.started = false;
928 ca_mutex_unlock(g_mutexObjectList);
930 if (-1 != caglobals.tcp.ipv4.fd)
932 close(caglobals.tcp.ipv4.fd);
933 caglobals.tcp.ipv4.fd = -1;
936 if (-1 != caglobals.tcp.ipv6.fd)
938 close(caglobals.tcp.ipv6.fd);
939 caglobals.tcp.ipv6.fd = -1;
942 CATCPDisconnectAll();
947 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
949 g_packetReceivedCallback = callback;
952 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
954 g_connectionCallback = connHandler;
957 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
959 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
961 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
962 ((unsigned char *)data)[0] >> 4);
964 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
967 OIC_LOG(ERROR, TAG, "outpdu is null");
971 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
974 OIC_LOG(ERROR, TAG, "pdu parse failed");
975 coap_delete_pdu(pdu);
979 size_t payloadLen = 0;
980 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
981 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
982 headerSize, pdu->length);
983 if (pdu->length > headerSize)
985 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
993 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
994 size_t dlen, const char *fam)
996 // #1. get TCP Server object from list
998 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1001 // if there is no connection info, connect to TCP Server
1002 svritem = CAConnectTCPSession(endpoint);
1005 OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
1010 // #2. check connection state
1011 if (svritem->fd < 0)
1013 // if file descriptor value is wrong, remove TCP Server info from list
1014 OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
1018 // #3. send data to TCP Server
1019 ssize_t remainLen = dlen;
1022 ssize_t len = send(svritem->fd, data, remainLen, 0);
1025 if (EWOULDBLOCK != errno)
1027 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1034 } while (remainLen > 0);
1039 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1043 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1045 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1046 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1048 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1050 return sendData(endpoint, data, datalen, "ipv6");
1052 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1054 return sendData(endpoint, data, datalen, "ipv4");
1059 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1061 VERIFY_NON_NULL(info, TAG, "info is NULL");
1062 VERIFY_NON_NULL(size, TAG, "size is NULL");
1064 return CA_NOT_SUPPORTED;
1067 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
1069 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1071 // #1. create TCP server object
1072 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1075 OIC_LOG(ERROR, TAG, "Out of memory");
1078 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1079 svritem->sep.endpoint.adapter = endpoint->adapter;
1080 svritem->sep.endpoint.port = endpoint->port;
1081 svritem->sep.endpoint.flags = endpoint->flags;
1082 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1084 // #2. create the socket and connect to TCP server
1085 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1086 int fd = CATCPCreateSocket(family, svritem);
1093 // #3. add TCP connection info to list
1095 ca_mutex_lock(g_mutexObjectList);
1096 if (caglobals.tcp.svrlist)
1098 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1101 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1104 ca_mutex_unlock(g_mutexObjectList);
1108 ca_mutex_unlock(g_mutexObjectList);
1112 // pass the connection information to CA Common Layer.
1113 if (g_connectionCallback)
1115 g_connectionCallback(&(svritem->sep.endpoint), true);
1121 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
1123 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
1125 // close the socket and remove TCP connection info in list.
1126 if (svritem->fd >= 0)
1128 shutdown(svritem->fd, SHUT_RDWR);
1132 u_arraylist_remove(caglobals.tcp.svrlist, index);
1133 OICFree(svritem->data);
1134 svritem->data = NULL;
1136 // pass the connection information to CA Common Layer.
1137 if (g_connectionCallback)
1139 g_connectionCallback(&(svritem->sep.endpoint), false);
1144 return CA_STATUS_OK;
1147 void CATCPDisconnectAll()
1149 ca_mutex_lock(g_mutexObjectList);
1150 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1151 CATCPSessionInfo_t *svritem = NULL;
1152 for (size_t i = 0; i < length; i++)
1154 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1155 if (svritem && svritem->fd >= 0)
1157 shutdown(svritem->fd, SHUT_RDWR);
1159 OICFree(svritem->data);
1160 svritem->data = NULL;
1162 // pass the connection information to CA Common Layer.
1163 if (g_connectionCallback)
1165 g_connectionCallback(&(svritem->sep.endpoint), false);
1169 u_arraylist_destroy(caglobals.tcp.svrlist);
1170 caglobals.tcp.svrlist = NULL;
1171 ca_mutex_unlock(g_mutexObjectList);
1174 CAcloseSslConnectionAll();
1179 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1181 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1182 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1184 // get connection info from list
1185 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1186 for (size_t i = 0; i < length; i++)
1188 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1189 caglobals.tcp.svrlist, i);
1195 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1196 sizeof(svritem->sep.endpoint.addr))
1197 && (svritem->sep.endpoint.port == endpoint->port)
1198 && (svritem->sep.endpoint.flags & endpoint->flags))
1208 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1210 ca_mutex_lock(g_mutexObjectList);
1212 // check from the last item.
1213 CATCPSessionInfo_t *svritem = NULL;
1214 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1215 for (size_t i = 0; i < length; i++)
1217 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1219 if (svritem && svritem->fd == fd)
1222 ca_mutex_unlock(g_mutexObjectList);
1227 ca_mutex_unlock(g_mutexObjectList);
1232 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1234 ca_mutex_lock(g_mutexObjectList);
1236 CAResult_t result = CA_STATUS_OK;
1238 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1241 result = CADisconnectTCPSession(svritem, index);
1242 if (CA_STATUS_OK != result)
1244 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1248 ca_mutex_unlock(g_mutexObjectList);
1252 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1254 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1256 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1257 ((unsigned char *)recvBuffer)[0] >> 4);
1258 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1260 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1262 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1263 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1264 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1266 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1267 return headerLen + optPaylaodLen;
1270 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1272 g_tcpErrorHandler = errorHandleCallback;