1 /* ****************************************************************j
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/ioctl.h>
26 #include <sys/types.h>
28 #include <sys/select.h>
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
41 #include "catcpinterface.h"
43 #include "caadapterutils.h"
45 #include "oic_malloc.h"
46 #include "oic_string.h"
49 * Logging tag for module name.
51 #define TAG "TCP_SERVER"
54 * Server port number for local test.
56 #define SERVER_PORT 8000
59 * Maximum CoAP over TCP header length
60 * to know the total data length.
62 #define TCP_MAX_HEADER_LEN 6
65 * Accept server file descriptor.
67 static int g_acceptServerFD = -1;
70 * Mutex to synchronize device object list.
72 static ca_mutex g_mutexObjectList = NULL;
75 * Conditional mutex to synchronize.
77 static ca_cond g_condObjectList = NULL;
80 * Maintains the callback to be notified when data received from remote device.
82 static CATCPPacketReceivedCallback g_packetReceivedCallback;
85 * Error callback to update error in TCP.
87 static CATCPErrorHandleCallback g_TCPErrorHandler = NULL;
89 static CAResult_t CATCPCreateMutex();
90 static void CATCPDestroyMutex();
91 static CAResult_t CATCPCreateCond();
92 static void CATCPDestroyCond();
93 static CAResult_t CACreateAcceptSocket();
94 static void CAAcceptConnection();
95 static void CAFindReadyMessage();
96 static void CASelectReturned(fd_set *readFds, int ret);
97 static void CAReceiveMessage(int fd);
98 static void CAReceiveHandler(void *data);
99 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
101 #define CHECKFD(FD) \
102 if (FD > caglobals.tcp.maxfd) \
103 caglobals.tcp.maxfd = FD;
105 static void CATCPDestroyMutex()
107 if (g_mutexObjectList)
109 ca_mutex_free(g_mutexObjectList);
110 g_mutexObjectList = NULL;
114 static CAResult_t CATCPCreateMutex()
116 if (!g_mutexObjectList)
118 g_mutexObjectList = ca_mutex_new();
119 if (!g_mutexObjectList)
121 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
122 return CA_STATUS_FAILED;
129 static void CATCPDestroyCond()
131 if (g_condObjectList)
133 ca_cond_free(g_condObjectList);
134 g_condObjectList = NULL;
138 static CAResult_t CATCPCreateCond()
140 if (!g_condObjectList)
142 g_condObjectList = ca_cond_new();
143 if (!g_condObjectList)
145 OIC_LOG(ERROR, TAG, "Failed to created cond!");
146 return CA_STATUS_FAILED;
152 static void CAReceiveHandler(void *data)
155 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
157 while (!caglobals.tcp.terminate)
159 CAFindReadyMessage();
162 ca_mutex_lock(g_mutexObjectList);
163 ca_cond_signal(g_condObjectList);
164 ca_mutex_unlock(g_mutexObjectList);
166 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
169 static void CAFindReadyMessage()
172 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
176 if (-1 != g_acceptServerFD)
178 FD_SET(g_acceptServerFD, &readFds);
180 if (-1 != caglobals.tcp.shutdownFds[0])
182 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
185 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
186 for (size_t i = 0; i < length; i++)
188 CATCPSessionInfo_t *svritem =
189 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
190 if (svritem && 0 <= svritem->fd)
192 FD_SET(svritem->fd, &readFds);
196 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
198 if (caglobals.tcp.terminate)
200 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
207 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
212 CASelectReturned(&readFds, ret);
215 static void CASelectReturned(fd_set *readFds, int ret)
219 if (g_acceptServerFD != -1 && FD_ISSET(g_acceptServerFD, readFds))
221 CAAcceptConnection();
226 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
227 for (size_t i = 0; i < length; i++)
229 CATCPSessionInfo_t *svritem =
230 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
231 if (svritem && svritem->fd >= 0)
233 if (FD_ISSET(svritem->fd, readFds))
235 CAReceiveMessage(svritem->fd);
236 FD_CLR(svritem->fd, readFds);
243 static void CAAcceptConnection()
245 struct sockaddr_storage clientaddr;
246 socklen_t clientlen = sizeof (struct sockaddr_in);
248 int sockfd = accept(g_acceptServerFD, (struct sockaddr *)&clientaddr,
252 CATCPSessionInfo_t *svritem =
253 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
256 OIC_LOG(ERROR, TAG, "Out of memory");
261 svritem->fd = sockfd;
262 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
263 (char *) &svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
265 ca_mutex_lock(g_mutexObjectList);
266 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
269 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
272 ca_mutex_unlock(g_mutexObjectList);
275 ca_mutex_unlock(g_mutexObjectList);
281 static void CAReceiveMessage(int fd)
283 // #1. get remote device information from file descriptor.
285 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
288 OIC_LOG(ERROR, TAG, "there is no connection information in list");
292 // #2. get already allocated memory size.
293 size_t bufSize = (svritem->totalDataLen == 0) ? TCP_MAX_HEADER_LEN : svritem->totalDataLen;
294 if (!svritem->recvData)
296 svritem->recvData = (unsigned char *) OICCalloc(1, bufSize);
297 if (!svritem->recvData)
299 OIC_LOG(ERROR, TAG, "out of memory");
300 CADisconnectTCPSession(svritem, index);
305 // #3. receive data from remote device.
306 ssize_t recvLen = recv(fd, svritem->recvData + svritem->recvDataLen,
307 bufSize - svritem->recvDataLen, 0);
310 if(EWOULDBLOCK != errno)
312 OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
313 CADisconnectTCPSession(svritem, index);
317 svritem->recvDataLen += recvLen;
319 // #4. get actual data length from coap over tcp header.
320 if (!svritem->totalDataLen)
322 coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
323 ((unsigned char *) svritem->recvData)[0] >> 4);
325 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
326 if (svritem->recvDataLen >= headerLen)
328 svritem->totalDataLen = CAGetTotalLengthFromHeader(
329 (unsigned char *) svritem->recvData);
330 bufSize = svritem->totalDataLen;
331 unsigned char *newBuf = OICRealloc(svritem->recvData, bufSize);
334 OIC_LOG(ERROR, TAG, "out of memory");
335 CADisconnectTCPSession(svritem, index);
338 svritem->recvData = newBuf;
342 // #5. pass the received data information to upper layer.
343 if ((svritem->totalDataLen == svritem->recvDataLen) && g_packetReceivedCallback)
345 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
346 g_packetReceivedCallback(&svritem->sep, svritem->recvData, svritem->recvDataLen);
347 OIC_LOG_V(DEBUG, TAG, "total received data len:%d", svritem->recvDataLen);
349 // initialize data info to receive next message.
350 OICFree(svritem->recvData);
351 svritem->recvData = NULL;
352 svritem->recvDataLen = 0;
353 svritem->totalDataLen = 0;
359 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo)
362 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
365 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
369 struct sockaddr_storage sa = { .ss_family = family };
370 CAConvertNameToAddr(tcpServerInfo->sep.endpoint.addr, tcpServerInfo->sep.endpoint.port, &sa);
371 socklen_t socklen = sizeof (struct sockaddr_in);
373 // connect to TCP server
374 int ret = connect(fd, (struct sockaddr *)&sa, socklen);
377 OIC_LOG(DEBUG, TAG, "connect socket success");
379 else if (EINPROGRESS == errno)
381 OIC_LOG(DEBUG, TAG, "EINPROGRESS");
383 socklen_t len = sizeof(error);
384 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
386 OIC_LOG(ERROR, TAG, "getsockopt() error");
392 if (ECONNREFUSED == error)
394 OIC_LOG(ERROR, TAG, "connection refused");
397 OIC_LOG(ERROR, TAG, "failed to connect socket");
400 OIC_LOG(DEBUG, TAG, "connect socket success");
404 OIC_LOG(ERROR, TAG, "failed to connect socket");
418 static CAResult_t CACreateAcceptSocket()
421 struct sockaddr_in server = { .sin_addr.s_addr = INADDR_ANY,
422 .sin_family = AF_INET,
423 .sin_port = htons(SERVER_PORT) };
425 g_acceptServerFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
426 if (g_acceptServerFD < 0)
428 OIC_LOG(ERROR, TAG, "Failed to create socket");
432 if (-1 == setsockopt(g_acceptServerFD, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
434 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
438 int serverlen = sizeof(server);
439 if (-1 == bind(g_acceptServerFD, (struct sockaddr *)&server, serverlen))
441 OIC_LOG(ERROR, TAG, "bind() error");
445 if (listen(g_acceptServerFD, caglobals.tcp.listenBacklog) != 0)
447 OIC_LOG(ERROR, TAG, "listen() error");
451 CHECKFD(g_acceptServerFD);
456 if (g_acceptServerFD >= 0)
458 close(g_acceptServerFD);
459 g_acceptServerFD = -1;
461 return CA_STATUS_FAILED;
464 static void CAInitializePipe()
466 int ret = pipe(caglobals.tcp.shutdownFds);
469 ret = fcntl(caglobals.tcp.shutdownFds[0], F_GETFD);
472 ret = fcntl(caglobals.tcp.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
476 ret = fcntl(caglobals.tcp.shutdownFds[1], F_GETFD);
480 ret = fcntl(caglobals.tcp.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
484 close(caglobals.tcp.shutdownFds[1]);
485 close(caglobals.tcp.shutdownFds[0]);
487 caglobals.tcp.shutdownFds[0] = -1;
488 caglobals.tcp.shutdownFds[1] = -1;
490 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
495 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
497 if (caglobals.tcp.started)
502 if (!caglobals.tcp.ipv4tcpenabled)
504 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
507 CAResult_t res = CATCPCreateMutex();
508 if (CA_STATUS_OK == res)
510 res = CATCPCreateCond();
512 if (CA_STATUS_OK != res)
514 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
518 ca_mutex_lock(g_mutexObjectList);
519 if (!caglobals.tcp.svrlist)
521 caglobals.tcp.svrlist = u_arraylist_create();
523 ca_mutex_unlock(g_mutexObjectList);
525 res = CACreateAcceptSocket();
526 if (CA_STATUS_OK != res)
528 OIC_LOG(ERROR, TAG, "failed to create accept socket");
532 // create pipe for fast shutdown
534 CHECKFD(caglobals.tcp.shutdownFds[0]);
535 CHECKFD(caglobals.tcp.shutdownFds[1]);
537 caglobals.tcp.terminate = false;
538 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
539 if (CA_STATUS_OK != res)
541 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
544 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
546 caglobals.tcp.started = true;
550 void CATCPStopServer()
553 ca_mutex_lock(g_mutexObjectList);
555 // set terminate flag
556 caglobals.tcp.terminate = true;
557 caglobals.tcp.started = false;
559 if (caglobals.tcp.shutdownFds[1] != -1)
561 close(caglobals.tcp.shutdownFds[1]);
562 // receive thread will stop immediately
565 ca_cond_wait(g_condObjectList, g_mutexObjectList);
568 ca_mutex_unlock(g_mutexObjectList);
570 if (-1 != g_acceptServerFD)
572 close(g_acceptServerFD);
573 g_acceptServerFD = -1;
576 CATCPDisconnectAll();
581 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
583 g_packetReceivedCallback = callback;
586 static size_t CACheckPayloadLength(const void *data, size_t dlen)
588 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
590 coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
591 ((unsigned char *)data)[0] >> 4);
593 coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
596 OIC_LOG(ERROR, TAG, "outpdu is null");
600 int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
603 OIC_LOG(ERROR, TAG, "pdu parse failed");
604 coap_delete_pdu(pdu);
608 size_t payloadLen = 0;
609 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
610 OIC_LOG_V(DEBUG, TAG, "headerSize : %d, pdu length : %d",
611 headerSize, pdu->length);
612 if (pdu->length > headerSize)
614 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
622 static void sendData(const CAEndpoint_t *endpoint,
623 const void *data, size_t dlen)
625 // #1. get TCP Server object from list
627 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
630 // if there is no connection info, connect to TCP Server
631 svritem = CAConnectTCPSession(endpoint);
634 OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
635 g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
640 // #2. check payload length
641 size_t payloadLen = CACheckPayloadLength(data, dlen);
642 // if payload length is zero, disconnect from TCP server
645 OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
646 CADisconnectTCPSession(svritem, index);
650 // #3. check connection state
653 // if file descriptor value is wrong, remove TCP Server info from list
654 OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
655 CADisconnectTCPSession(svritem, index);
656 g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
660 // #4. send data to TCP Server
661 ssize_t remainLen = dlen;
664 ssize_t len = send(svritem->fd, data, remainLen, 0);
667 if (EWOULDBLOCK != errno)
669 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
670 g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
677 } while (remainLen > 0);
679 OIC_LOG_V(INFO, TAG, "unicast ipv4tcp sendTo is successful: %zu bytes", dlen);
682 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
685 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
686 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
690 if (caglobals.tcp.ipv4tcpenabled && (endpoint->adapter & CA_ADAPTER_TCP))
692 sendData(endpoint, data, datalen);
697 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
699 VERIFY_NON_NULL(info, TAG, "info is NULL");
700 VERIFY_NON_NULL(size, TAG, "size is NULL");
702 return CA_NOT_SUPPORTED;
705 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
707 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
709 // #1. create TCP server object
710 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
713 OIC_LOG(ERROR, TAG, "Out of memory");
716 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
717 svritem->sep.endpoint.port = endpoint->port;
719 // #2. create the socket and connect to TCP server
720 if (caglobals.tcp.ipv4tcpenabled)
722 int fd = CATCPCreateSocket(AF_INET, svritem);
729 // #3. add TCP connection info to list
731 ca_mutex_lock(g_mutexObjectList);
732 if (caglobals.tcp.svrlist)
734 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
737 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
740 ca_mutex_unlock(g_mutexObjectList);
744 ca_mutex_unlock(g_mutexObjectList);
752 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
754 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
756 ca_mutex_lock(g_mutexObjectList);
758 // close the socket and remove TCP connection info in list
759 if (svritem->fd >= 0)
763 u_arraylist_remove(caglobals.tcp.svrlist, index);
764 OICFree(svritem->recvData);
766 ca_mutex_unlock(g_mutexObjectList);
771 void CATCPDisconnectAll()
773 ca_mutex_lock(g_mutexObjectList);
774 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
776 CATCPSessionInfo_t *svritem = NULL;
777 for (size_t i = 0; i < length; i++)
779 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
780 if (svritem && svritem->fd >= 0)
782 shutdown(svritem->fd, SHUT_RDWR);
784 OICFree(svritem->recvData);
787 u_arraylist_destroy(caglobals.tcp.svrlist);
788 ca_mutex_unlock(g_mutexObjectList);
791 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint,
794 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
795 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
797 // get connection info from list
798 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
799 for (size_t i = 0; i < length; i++)
801 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
802 caglobals.tcp.svrlist, i);
808 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr))
809 && (svritem->sep.endpoint.port == endpoint->port))
819 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
821 ca_mutex_lock(g_mutexObjectList);
823 // check from the last item.
824 CATCPSessionInfo_t *svritem = NULL;
825 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
826 for (size_t i = 0; i < length; i++)
828 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
830 if (svritem && svritem->fd == fd)
833 ca_mutex_unlock(g_mutexObjectList);
838 ca_mutex_unlock(g_mutexObjectList);
843 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
845 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
847 coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
848 ((unsigned char *)recvBuffer)[0] >> 4);
849 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
851 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
853 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
854 OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
855 OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
857 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
858 return headerLen + optPaylaodLen;
861 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
863 g_TCPErrorHandler = errorHandleCallback;