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"
46 #include "oic_string.h"
49 #include "ca_adapter_net_ssl.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.");
268 CASelectReturned(&readFds);
272 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
277 static void CASelectReturned(fd_set *readFds)
279 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
281 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
283 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
286 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
288 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
291 else if (-1 != caglobals.tcp.connectionFds[0] &&
292 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
294 // new connection was created from remote device.
295 // exit the function to update read file descriptor.
296 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
297 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
302 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
303 FD_CLR(caglobals.tcp.connectionFds[0], readFds);
308 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
309 for (size_t i = 0; i < length; i++)
311 CATCPSessionInfo_t *svritem =
312 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
313 if (svritem && svritem->fd >= 0)
315 if (FD_ISSET(svritem->fd, readFds))
317 CAReceiveMessage(svritem->fd);
318 FD_CLR(svritem->fd, readFds);
325 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
327 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
329 struct sockaddr_storage clientaddr;
330 socklen_t clientlen = sizeof (struct sockaddr_in);
333 clientlen = sizeof(struct sockaddr_in6);
336 int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
339 CATCPSessionInfo_t *svritem =
340 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
343 OIC_LOG(ERROR, TAG, "Out of memory");
348 svritem->fd = sockfd;
349 svritem->sep.endpoint.flags = flag;
350 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
351 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
352 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
354 oc_mutex_lock(g_mutexObjectList);
355 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
358 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
361 oc_mutex_unlock(g_mutexObjectList);
364 oc_mutex_unlock(g_mutexObjectList);
371 static bool CAIsTlsMessage(const unsigned char* data, size_t length)
373 if (NULL == data || 0 == length)
375 OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
379 unsigned char first_byte = data[0];
381 //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
382 //handshake = [16], application_data = [17] in HEX
383 const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
386 for (i = 0; i < sizeof(tls_head_type); i++)
388 if(tls_head_type[i] == first_byte)
399 * Clean socket state data
401 * @param[in/out] item - socket state data
403 static void CACleanData(CATCPSessionInfo_t *svritem)
407 OICFree(svritem->data);
408 svritem->data = NULL;
410 svritem->totalLen = 0;
411 svritem->protocol = UNKNOWN;
416 * Read message header from socket item->fd
418 * @param[in/out] item - used socket, buffer, current received message length and protocol
419 * @return - CA_STATUS_OK or appropriate error code
421 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
423 CAResult_t res = CA_STATUS_OK;
427 return CA_STATUS_INVALID_PARAM;
430 if (NULL == svritem->data)
432 // allocate memory for message header (CoAP header size because it is bigger)
433 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
434 if (NULL == svritem->data)
436 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
437 return CA_MEMORY_ALLOC_FAILED;
441 //read data (assume TLS header) from remote device.
442 //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
443 res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
445 //return if any error occurs
446 if (CA_STATUS_OK != res)
451 //if not enough data received - read them on next CAReceiveMessage() call
452 if (svritem->len < TLS_HEADER_SIZE)
454 OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
458 //if enough data received - parse header
460 if (CAIsTlsMessage(svritem->data, svritem->len))
462 svritem->protocol = TLS;
464 //[3][4] bytes in tls header are tls payload length
465 unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
466 OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
468 svritem->totalLen = message_length + TLS_HEADER_SIZE;
473 svritem->protocol = COAP;
475 //seems CoAP data received. read full coap header.
476 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
478 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
480 if (svritem->len < headerLen)
482 //read required bytes to have full CoAP header
483 //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
484 res = CARecv(svritem, headerLen - svritem->len, 0);
486 //return if any error occurs
487 if (CA_STATUS_OK != res)
492 //if not enough data received - read them on next CAReceiveMessage() call
493 if (svritem->len < headerLen)
495 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
500 //calculate CoAP message length
501 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
504 unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
507 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
508 return CA_MEMORY_ALLOC_FAILED;
510 svritem->data = buffer;
516 * Read message payload from socket item->fd
519 * @param[in/out] item - used socket, buffer and to update received message length
520 * @return - CA_STATUS_OK or appropriate error code
522 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
526 return CA_STATUS_INVALID_PARAM;
529 return CARecv(svritem, svritem->totalLen - svritem->len, 0);
533 * Pass received data to app layer depending on protocol
535 * @param[in/out] item - used buffer, received message length and protocol
537 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
544 switch(svritem->protocol)
548 if (g_packetReceivedCallback)
550 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
557 int ret = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
559 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, ret);
563 case UNKNOWN: /* pass through */
565 OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
570 static void CAReceiveMessage(int fd)
572 CAResult_t res = CA_STATUS_OK;
574 //get remote device information from file descriptor.
576 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
579 OIC_LOG(ERROR, TAG, "there is no connection information in list");
583 //totalLen filled only when header fully read and parsed
584 if (0 == svritem->totalLen)
586 res = CAReadHeader(svritem);
590 res = CAReadPayload(svritem);
592 //when successfully read all required data - pass them to upper layer.
593 if (CA_STATUS_OK == res && svritem->len == svritem->totalLen)
595 CAExecuteRequest(svritem);
596 CACleanData(svritem);
600 //disconnect session and clean-up data if any error occurs
601 if (res != CA_STATUS_OK)
604 if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
606 OIC_LOG(ERROR, TAG, "Failed to close TLS session");
609 CADisconnectTCPSession(svritem, index);
610 CACleanData(svritem);
614 static void CAWakeUpForReadFdsUpdate(const char *host)
616 if (caglobals.tcp.connectionFds[1] != -1)
621 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
622 } while ((len == -1) && (errno == EINTR));
624 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
626 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
631 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
632 struct sockaddr_storage *sockaddr)
634 struct addrinfo *addrs = NULL;
635 struct addrinfo hints = { .ai_family = family,
636 .ai_protocol = IPPROTO_TCP,
637 .ai_socktype = SOCK_STREAM,
638 .ai_flags = AI_NUMERICHOST };
640 int r = getaddrinfo(host, NULL, &hints, &addrs);
645 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
649 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
652 return CA_STATUS_FAILED;
654 // assumption: in this case, getaddrinfo will only return one addrinfo
655 // or first is the one we want.
656 if (addrs[0].ai_family == AF_INET6)
658 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
659 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
663 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
664 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
670 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
672 VERIFY_NON_NULL_RET(svritem, TAG, "svritem", -1);
674 OIC_LOG_V(DEBUG, TAG, "try to connect with [%s:%u]",
675 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
677 // #1. create tcp socket.
678 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
681 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
685 // #2. convert address from string to binary.
686 struct sockaddr_storage sa = { .ss_family = family };
687 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
688 svritem->sep.endpoint.port, &sa);
689 if (CA_STATUS_OK != res)
695 // #3. set socket length.
696 socklen_t socklen = 0;
697 if (sa.ss_family == AF_INET6)
699 socklen = sizeof(struct sockaddr_in6);
703 socklen = sizeof(struct sockaddr_in);
706 // #4. connect to remote server device.
707 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
709 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
714 OIC_LOG(DEBUG, TAG, "connect socket success");
715 CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
719 static int CACreateAcceptSocket(int family, CASocket_t *sock)
721 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
725 OIC_LOG(DEBUG, TAG, "accept socket created already");
729 socklen_t socklen = 0;
730 struct sockaddr_storage server = { .ss_family = family };
732 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
735 OIC_LOG(ERROR, TAG, "Failed to create socket");
739 if (family == AF_INET6)
741 // the socket is restricted to sending and receiving IPv6 packets only.
743 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
745 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
748 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
749 socklen = sizeof (struct sockaddr_in6);
753 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
754 socklen = sizeof (struct sockaddr_in);
758 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
760 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
764 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
766 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
770 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
772 OIC_LOG(ERROR, TAG, "listen() error");
776 if (!sock->port) // return the assigned port
778 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
780 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
783 sock->port = ntohs(family == AF_INET6 ?
784 ((struct sockaddr_in6 *)&server)->sin6_port :
785 ((struct sockaddr_in *)&server)->sin_port);
798 static void CAInitializePipe(int *fds)
803 ret = fcntl(fds[0], F_GETFD);
806 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
810 ret = fcntl(fds[1], F_GETFD);
814 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
824 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
829 #define NEWSOCKET(FAMILY, NAME) \
830 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
831 if (caglobals.tcp.NAME.fd == -1) \
833 caglobals.tcp.NAME.port = 0; \
834 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
836 CHECKFD(caglobals.tcp.NAME.fd);
838 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
840 if (caglobals.tcp.started)
845 if (!caglobals.tcp.ipv4tcpenabled)
847 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
849 if (!caglobals.tcp.ipv6tcpenabled)
851 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
854 CAResult_t res = CATCPCreateMutex();
855 if (CA_STATUS_OK == res)
857 res = CATCPCreateCond();
859 if (CA_STATUS_OK != res)
861 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
865 oc_mutex_lock(g_mutexObjectList);
866 if (!caglobals.tcp.svrlist)
868 caglobals.tcp.svrlist = u_arraylist_create();
870 oc_mutex_unlock(g_mutexObjectList);
872 if (caglobals.server)
874 NEWSOCKET(AF_INET, ipv4);
875 NEWSOCKET(AF_INET6, ipv6);
876 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
877 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
878 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
879 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
882 // create pipe for fast shutdown
883 CAInitializePipe(caglobals.tcp.shutdownFds);
884 CHECKFD(caglobals.tcp.shutdownFds[0]);
885 CHECKFD(caglobals.tcp.shutdownFds[1]);
887 // create pipe for connection event
888 CAInitializePipe(caglobals.tcp.connectionFds);
889 CHECKFD(caglobals.tcp.connectionFds[0]);
890 CHECKFD(caglobals.tcp.connectionFds[1]);
892 caglobals.tcp.terminate = false;
893 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
894 if (CA_STATUS_OK != res)
896 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
899 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
901 caglobals.tcp.started = true;
905 void CATCPStopServer()
908 oc_mutex_lock(g_mutexObjectList);
910 // set terminate flag
911 caglobals.tcp.terminate = true;
913 if (caglobals.tcp.shutdownFds[1] != -1)
915 close(caglobals.tcp.shutdownFds[1]);
916 // receive thread will stop immediately
919 if (caglobals.tcp.connectionFds[1] != -1)
921 close(caglobals.tcp.connectionFds[1]);
924 if (caglobals.tcp.started)
926 oc_cond_wait(g_condObjectList, g_mutexObjectList);
928 caglobals.tcp.started = false;
931 oc_mutex_unlock(g_mutexObjectList);
933 if (-1 != caglobals.tcp.ipv4.fd)
935 close(caglobals.tcp.ipv4.fd);
936 caglobals.tcp.ipv4.fd = -1;
939 if (-1 != caglobals.tcp.ipv6.fd)
941 close(caglobals.tcp.ipv6.fd);
942 caglobals.tcp.ipv6.fd = -1;
945 CATCPDisconnectAll();
950 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
952 g_packetReceivedCallback = callback;
955 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
957 g_connectionCallback = connHandler;
960 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
962 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
964 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
965 ((unsigned char *)data)[0] >> 4);
967 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
970 OIC_LOG(ERROR, TAG, "outpdu is null");
974 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
977 OIC_LOG(ERROR, TAG, "pdu parse failed");
978 coap_delete_pdu(pdu);
982 size_t payloadLen = 0;
983 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
984 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
985 headerSize, pdu->length);
986 if (pdu->length > headerSize)
988 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
996 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
997 size_t dlen, const char *fam)
999 // #1. get TCP Server object from list
1001 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1004 // if there is no connection info, connect to TCP Server
1005 svritem = CAConnectTCPSession(endpoint);
1008 OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
1013 // #2. check connection state
1014 if (svritem->fd < 0)
1016 // if file descriptor value is wrong, remove TCP Server info from list
1017 OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
1021 // #3. send data to TCP Server
1022 ssize_t remainLen = dlen;
1025 ssize_t len = send(svritem->fd, data, remainLen, 0);
1028 if (EWOULDBLOCK != errno)
1030 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1037 } while (remainLen > 0);
1042 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1046 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1048 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1049 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1051 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1053 return sendData(endpoint, data, datalen, "ipv6");
1055 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1057 return sendData(endpoint, data, datalen, "ipv4");
1062 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1064 VERIFY_NON_NULL(info, TAG, "info is NULL");
1065 VERIFY_NON_NULL(size, TAG, "size is NULL");
1067 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1070 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1071 return CA_STATUS_FAILED;
1074 uint32_t len = u_arraylist_length(iflist);
1076 CAEndpoint_t *ep = (CAEndpoint_t *)OICCalloc(len, sizeof (CAEndpoint_t));
1079 OIC_LOG(ERROR, TAG, "Malloc Failed");
1080 u_arraylist_destroy(iflist);
1081 return CA_MEMORY_ALLOC_FAILED;
1084 for (uint32_t i = 0, j = 0; i < len; i++)
1086 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1092 ep[j].adapter = CA_ADAPTER_TCP;
1093 ep[j].ifindex = ifitem->index;
1095 if (ifitem->family == AF_INET6)
1097 ep[j].flags = CA_IPV6;
1098 ep[j].port = caglobals.tcp.ipv6.port;
1100 else if (ifitem->family == AF_INET)
1102 ep[j].flags = CA_IPV4;
1103 ep[j].port = caglobals.tcp.ipv4.port;
1109 OICStrcpy(ep[j].addr, sizeof(ep[j].addr), ifitem->addr);
1116 u_arraylist_destroy(iflist);
1118 return CA_STATUS_OK;
1121 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
1123 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1125 // #1. create TCP server object
1126 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1129 OIC_LOG(ERROR, TAG, "Out of memory");
1132 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1133 svritem->sep.endpoint.adapter = endpoint->adapter;
1134 svritem->sep.endpoint.port = endpoint->port;
1135 svritem->sep.endpoint.flags = endpoint->flags;
1136 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1138 // #2. create the socket and connect to TCP server
1139 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1140 int fd = CATCPCreateSocket(family, svritem);
1147 // #3. add TCP connection info to list
1149 oc_mutex_lock(g_mutexObjectList);
1150 if (caglobals.tcp.svrlist)
1152 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1155 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1158 oc_mutex_unlock(g_mutexObjectList);
1162 oc_mutex_unlock(g_mutexObjectList);
1166 // pass the connection information to CA Common Layer.
1167 if (g_connectionCallback)
1169 g_connectionCallback(&(svritem->sep.endpoint), true);
1175 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
1177 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
1179 oc_mutex_lock(g_mutexObjectList);
1181 // close the socket and remove TCP connection info in list
1182 if (svritem->fd >= 0)
1186 u_arraylist_remove(caglobals.tcp.svrlist, index);
1187 OICFree(svritem->data);
1188 svritem->data = NULL;
1190 // pass the connection information to CA Common Layer.
1191 if (g_connectionCallback)
1193 g_connectionCallback(&(svritem->sep.endpoint), false);
1197 oc_mutex_unlock(g_mutexObjectList);
1199 return CA_STATUS_OK;
1202 void CATCPDisconnectAll()
1204 oc_mutex_lock(g_mutexObjectList);
1205 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1207 CATCPSessionInfo_t *svritem = NULL;
1208 for (size_t i = 0; i < length; i++)
1210 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1211 if (svritem && svritem->fd >= 0)
1214 CAcloseSslConnection(&svritem->sep.endpoint);
1216 shutdown(svritem->fd, SHUT_RDWR);
1218 OICFree(svritem->data);
1219 svritem->data = NULL;
1221 // pass the connection information to CA Common Layer.
1222 if (g_connectionCallback)
1224 g_connectionCallback(&(svritem->sep.endpoint), false);
1228 u_arraylist_destroy(caglobals.tcp.svrlist);
1229 caglobals.tcp.svrlist = NULL;
1230 oc_mutex_unlock(g_mutexObjectList);
1233 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1235 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1236 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1238 // get connection info from list
1239 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1240 for (size_t i = 0; i < length; i++)
1242 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1243 caglobals.tcp.svrlist, i);
1249 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1250 sizeof(svritem->sep.endpoint.addr))
1251 && (svritem->sep.endpoint.port == endpoint->port)
1252 && (svritem->sep.endpoint.flags & endpoint->flags))
1262 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1264 oc_mutex_lock(g_mutexObjectList);
1266 // check from the last item.
1267 CATCPSessionInfo_t *svritem = NULL;
1268 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1269 for (size_t i = 0; i < length; i++)
1271 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1273 if (svritem && svritem->fd == fd)
1276 oc_mutex_unlock(g_mutexObjectList);
1281 oc_mutex_unlock(g_mutexObjectList);
1286 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1288 CAResult_t result = CA_STATUS_OK;
1290 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1293 result = CADisconnectTCPSession(svritem, index);
1294 if (CA_STATUS_OK != result)
1296 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1303 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1305 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1307 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1308 ((unsigned char *)recvBuffer)[0] >> 4);
1309 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1311 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1313 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1314 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1315 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1317 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1318 return headerLen + optPaylaodLen;
1321 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1323 g_tcpErrorHandler = errorHandleCallback;