Use `URI` all caps in documentation
[iotivity.git] / resource / csdk / connectivity / src / tcp_adapter / catcpserver.c
1 /* ****************************************************************
2  *
3  * Copyright 2015 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  ******************************************************************/
20
21 #include "iotivity_config.h"
22 #include "iotivity_debug.h"
23 #include <sys/types.h>
24 #ifdef HAVE_SYS_SOCKET_H
25 #include <sys/socket.h>
26 #endif
27 #ifdef HAVE_WS2TCPIP_H
28 #include <ws2tcpip.h>
29 #endif
30 #ifdef HAVE_SYS_SELECT_H
31 #include <sys/select.h>
32 #endif
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
35 #endif
36 #ifdef HAVE_SYS_POLL_H
37 #include <sys/poll.h>
38 #endif
39 #include <stdio.h>
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43 #include <fcntl.h>
44 #ifdef HAVE_ARPA_INET_H
45 #include <arpa/inet.h>
46 #endif
47 #ifdef HAVE_NETINET_IN_H
48 #include <netinet/in.h>
49 #endif
50 #ifdef HAVE_NET_IF_H
51 #include <net/if.h>
52 #endif
53 #include <errno.h>
54 #include <assert.h>
55
56 #ifdef HAVE_NETDB_H
57 #include <netdb.h>
58 #endif
59
60 #include "catcpinterface.h"
61 #include "caipnwmonitor.h"
62 #include "caadapterutils.h"
63 #include "octhread.h"
64 #include "oic_malloc.h"
65 #include "oic_string.h"
66
67 #include <coap/pdu.h>
68 #include <coap/utlist.h>
69 #include <inttypes.h>
70
71 #ifdef __WITH_TLS__
72 #include "ca_adapter_net_ssl.h"
73 #endif
74
75 /**
76  * Logging tag for module name.
77  */
78 #define TAG "OIC_CA_TCP_SERVER"
79
80 /**
81  * Maximum CoAP over TCP header length
82  * to know the total data length.
83  */
84 #define COAP_MAX_HEADER_SIZE  6
85
86 /**
87  * TLS header size
88  */
89 #define TLS_HEADER_SIZE 5
90
91 /**
92  * Mutex to synchronize device object list.
93  */
94 static oc_mutex g_mutexObjectList = NULL;
95
96 /**
97  * Conditional mutex to synchronize.
98  */
99 static oc_cond g_condObjectList = NULL;
100
101 /**
102  * Maintains the callback to be notified when data received from remote device.
103  */
104 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
105
106 /**
107  * Error callback to update error in TCP.
108  */
109 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
110
111 /**
112  * Connected Callback to pass the connection information to RI.
113  */
114 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
115
116 /**
117  * Store the connected TCP session information.
118  */
119 static CATCPSessionInfo_t *g_sessionList = NULL;
120
121 static CAResult_t CATCPCreateMutex(void);
122 static void CATCPDestroyMutex(void);
123 static CAResult_t CATCPCreateCond(void);
124 static void CATCPDestroyCond(void);
125 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
126 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
127 static void CAFindReadyMessage(void);
128 #if !defined(WSA_WAIT_EVENT_0)
129 static void CASelectReturned(fd_set *readFds);
130 #else
131 static void CASocketEventReturned(CASocketFd_t socket, long networkEvents);
132 #endif
133 static CAResult_t CAReceiveMessage(CATCPSessionInfo_t *svritem);
134 static void CAReceiveHandler(void *data);
135 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
136
137 #if defined(WSA_WAIT_EVENT_0)
138 #define CHECKFD(FD)
139 #else
140 #define CHECKFD(FD) \
141 do \
142 { \
143     if (FD > caglobals.tcp.maxfd) \
144     { \
145         caglobals.tcp.maxfd = FD; \
146     } \
147 } while (0)
148 #endif
149
150 #define CLOSE_SOCKET(TYPE) \
151     if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
152     { \
153         OC_CLOSE_SOCKET(caglobals.tcp.TYPE.fd); \
154         caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
155     }
156
157 #define CA_FD_SET(TYPE, FDS) \
158     if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
159     { \
160         FD_SET(caglobals.tcp.TYPE.fd, FDS); \
161     }
162
163 #define CA_TCP_RESPONSE_CLASS(C) (((C) >> 5)*100)
164
165 #define CA_TCP_RESPONSE_CODE(C) \
166     (CA_TCP_RESPONSE_CLASS(C) \
167             + (C - COAP_RESPONSE_CODE(CA_TCP_RESPONSE_CLASS(C))))
168
169 static void CATCPDestroyMutex(void)
170 {
171     if (g_mutexObjectList)
172     {
173         oc_mutex_free(g_mutexObjectList);
174         g_mutexObjectList = NULL;
175     }
176 }
177
178 static CAResult_t CATCPCreateMutex(void)
179 {
180     if (!g_mutexObjectList)
181     {
182         g_mutexObjectList =  oc_mutex_new_recursive();
183         if (!g_mutexObjectList)
184         {
185             OIC_LOG(ERROR, TAG, "Failed to created mutex!");
186             return CA_STATUS_FAILED;
187         }
188     }
189
190     return CA_STATUS_OK;
191 }
192
193 static void CATCPDestroyCond(void)
194 {
195     if (g_condObjectList)
196     {
197         oc_cond_free(g_condObjectList);
198         g_condObjectList = NULL;
199     }
200 }
201
202 static CAResult_t CATCPCreateCond(void)
203 {
204     if (!g_condObjectList)
205     {
206         g_condObjectList = oc_cond_new();
207         if (!g_condObjectList)
208         {
209             OIC_LOG(ERROR, TAG, "Failed to created cond!");
210             return CA_STATUS_FAILED;
211         }
212     }
213     return CA_STATUS_OK;
214 }
215
216 static void CAReceiveHandler(void *data)
217 {
218     (void)data;
219     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
220
221     while (!caglobals.tcp.terminate)
222     {
223         CAFindReadyMessage();
224     }
225
226     oc_mutex_lock(g_mutexObjectList);
227     oc_cond_signal(g_condObjectList);
228     oc_mutex_unlock(g_mutexObjectList);
229
230     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
231 }
232
233 #if !defined(WSA_WAIT_EVENT_0)
234
235 static void CAFindReadyMessage(void)
236 {
237     fd_set readFds;
238     struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
239
240     FD_ZERO(&readFds);
241     CA_FD_SET(ipv4, &readFds);
242     CA_FD_SET(ipv4s, &readFds);
243     CA_FD_SET(ipv6, &readFds);
244     CA_FD_SET(ipv6s, &readFds);
245
246     if (OC_INVALID_SOCKET != caglobals.tcp.shutdownFds[0])
247     {
248         FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
249     }
250     if (OC_INVALID_SOCKET != caglobals.tcp.connectionFds[0])
251     {
252         FD_SET(caglobals.tcp.connectionFds[0], &readFds);
253     }
254
255     CATCPSessionInfo_t *session = NULL;
256     LL_FOREACH(g_sessionList, session)
257     {
258         if (session && session->fd != OC_INVALID_SOCKET && session->state == CONNECTED)
259         {
260             FD_SET(session->fd, &readFds);
261         }
262     }
263
264     int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
265
266     if (caglobals.tcp.terminate)
267     {
268         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
269         return;
270     }
271
272     if (0 == ret)
273     {
274         return;
275     }
276     else if (0 < ret)
277     {
278         CASelectReturned(&readFds);
279     }
280     else // if (0 > ret)
281     {
282         OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
283         return;
284     }
285 }
286
287 static void CASelectReturned(fd_set *readFds)
288 {
289     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
290
291     if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
292     {
293         CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
294         return;
295     }
296     else if (caglobals.tcp.ipv4s.fd != -1 && FD_ISSET(caglobals.tcp.ipv4s.fd, readFds))
297     {
298         CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
299         return;
300     }
301     else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
302     {
303         CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
304         return;
305     }
306     else if (caglobals.tcp.ipv6s.fd != -1 && FD_ISSET(caglobals.tcp.ipv6s.fd, readFds))
307     {
308         CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
309         return;
310     }
311     else if (-1 != caglobals.tcp.connectionFds[0] &&
312             FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
313     {
314         // new connection was created from remote device.
315         // exit the function to update read file descriptor.
316         char buf[MAX_ADDR_STR_SIZE_CA] = {0};
317         ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
318         if (-1 == len)
319         {
320             return;
321         }
322         OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
323         return;
324     }
325     else
326     {
327         oc_mutex_lock(g_mutexObjectList);
328         CATCPSessionInfo_t *session = NULL;
329         CATCPSessionInfo_t *tmp = NULL;
330         LL_FOREACH_SAFE(g_sessionList, session, tmp)
331         {
332             if (session && session->fd != OC_INVALID_SOCKET)
333             {
334                 if (FD_ISSET(session->fd, readFds))
335                 {
336                     CAResult_t res = CAReceiveMessage(session);
337                     //disconnect session and clean-up data if any error occurs
338                     if (res != CA_STATUS_OK)
339                     {
340 #ifdef __WITH_TLS__
341                         if (CA_STATUS_OK != CAcloseSslConnection(&session->sep.endpoint))
342                         {
343                             OIC_LOG(ERROR, TAG, "Failed to close TLS session");
344                         }
345 #endif
346                         LL_DELETE(g_sessionList, session);
347                         CADisconnectTCPSession(session);
348                         oc_mutex_unlock(g_mutexObjectList);
349                         return;
350                     }
351                 }
352             }
353         }
354         oc_mutex_unlock(g_mutexObjectList);
355     }
356 }
357
358 #else // if defined(WSA_WAIT_EVENT_0)
359
360 /**
361  * Push an exiting socket event to listen on
362  *
363  * @param[in] s              Socket to push
364  * @param[in] socketArray    Array in which to add socket
365  * @param[in] event          Event to push
366  * @param[in] eventArray     Array in which to add event
367  * @param[in,out] eventIndex Current length of arrays
368  * @param[in] arraySize      Maximum length of arrays
369  * @return true on success, false on failure
370  */
371 static bool CAPushEvent(CASocketFd_t s, CASocketFd_t* socketArray,
372                         HANDLE event, HANDLE* eventArray, int* eventIndex, int arraySize)
373 {
374     if (*eventIndex == arraySize)
375     {
376         return false;
377     }
378
379     assert(*eventIndex >= 0);
380     socketArray[*eventIndex] = s;
381     eventArray[(*eventIndex)++] = event;
382     return true;
383 }
384
385 /**
386  * Push a new socket event to listen on
387  *
388  * @param[in] s              Socket to push
389  * @param[in] socketArray    Array in which to add socket
390  * @param[in] eventArray     Array in which to add event
391  * @param[in,out] eventIndex Current length of arrays
392  * @param[in] arraySize      Maximum length of arrays
393  * @return true on success, false on failure
394  */
395 static bool CAPushSocket(CASocketFd_t s, CASocketFd_t* socketArray,
396                          HANDLE *eventArray, int *eventIndex, int arraySize)
397 {
398     if (s == OC_INVALID_SOCKET)
399     {
400         // Nothing to push.
401         return true;
402     }
403
404     WSAEVENT newEvent = WSACreateEvent();
405     if (WSA_INVALID_EVENT == newEvent)
406     {
407         OIC_LOG_V(ERROR, TAG, "WSACreateEvent(NewEvent) failed %u", WSAGetLastError());
408         return false;
409     }
410
411     if (0 != WSAEventSelect(s, newEvent, FD_READ | FD_ACCEPT))
412     {
413         OIC_LOG_V(ERROR, TAG, "WSAEventSelect failed %u", WSAGetLastError());
414         OC_VERIFY(WSACloseEvent(newEvent));
415         return false;
416     }
417
418     if (!CAPushEvent(s, socketArray, newEvent, eventArray, eventIndex, arraySize))
419     {
420         OIC_LOG_V(ERROR, TAG, "CAPushEvent failed");
421         OC_VERIFY(WSACloseEvent(newEvent));
422         return false;
423     }
424
425     return true;
426 }
427
428 #define EVENT_ARRAY_SIZE 64
429
430 /**
431  * Process any message that is ready
432  */
433 static void CAFindReadyMessage(void)
434 {
435     CASocketFd_t socketArray[EVENT_ARRAY_SIZE] = {0};
436     HANDLE eventArray[_countof(socketArray)];
437     int arraySize = 0;
438
439     if (OC_INVALID_SOCKET != caglobals.tcp.ipv4.fd)
440     {
441         CAPushSocket(caglobals.tcp.ipv4.fd, socketArray, eventArray, &arraySize, _countof(socketArray));
442     }
443     if (OC_INVALID_SOCKET != caglobals.tcp.ipv6.fd)
444     {
445         CAPushSocket(caglobals.tcp.ipv6.fd, socketArray, eventArray, &arraySize, _countof(socketArray));
446     }
447     if (WSA_INVALID_EVENT != caglobals.tcp.updateEvent)
448     {
449         CAPushEvent(OC_INVALID_SOCKET, socketArray,
450                     caglobals.tcp.updateEvent, eventArray, &arraySize, _countof(socketArray));
451     }
452
453     int svrlistBeginIndex = arraySize;
454
455     while (!caglobals.tcp.terminate)
456     {
457         CATCPSessionInfo_t *session = NULL;
458         LL_FOREACH(g_sessionList, session)
459         {
460             if (session && OC_INVALID_SOCKET != session->fd && (arraySize < EVENT_ARRAY_SIZE))
461             {
462                  CAPushSocket(session->fd, socketArray, eventArray, &arraySize, _countof(socketArray));
463             }
464         }
465
466         // Should not have overflowed buffer
467         assert(arraySize <= (_countof(socketArray)));
468
469         DWORD ret = WSAWaitForMultipleEvents(arraySize, eventArray, FALSE, WSA_INFINITE, FALSE);
470         assert(ret < (WSA_WAIT_EVENT_0 + arraySize));
471         DWORD eventIndex = ret - WSA_WAIT_EVENT_0;
472
473         if (caglobals.tcp.updateEvent == eventArray[eventIndex])
474         {
475             OC_VERIFY(WSAResetEvent(caglobals.tcp.updateEvent));
476         }
477         else
478         {
479             // WSAEnumNetworkEvents also resets the event
480             WSANETWORKEVENTS networkEvents;
481             int enumResult = WSAEnumNetworkEvents(socketArray[eventIndex], eventArray[eventIndex], &networkEvents);
482             if (SOCKET_ERROR != enumResult)
483             {
484                 CASocketEventReturned(socketArray[eventIndex], networkEvents.lNetworkEvents);
485             }
486             else
487             {
488                 OIC_LOG_V(ERROR, TAG, "WSAEnumNetworkEvents failed %u", WSAGetLastError());
489                 break;
490             }
491         }
492
493         // Close events associated with svrlist
494         while (arraySize > svrlistBeginIndex)
495         {
496             arraySize--;
497             OC_VERIFY(WSACloseEvent(eventArray[arraySize]));
498             eventArray[arraySize] = NULL;
499         }
500     }
501
502     // Close events
503     while (arraySize > 0)
504     {
505         arraySize--;
506         OC_VERIFY(WSACloseEvent(eventArray[arraySize]));
507     }
508
509     if (caglobals.tcp.terminate)
510     {
511         caglobals.tcp.updateEvent = WSA_INVALID_EVENT;
512     }
513 }
514
515 /**
516  * Process an event (accept or receive) that is ready on a socket
517  *
518  * @param[in] s Socket to process
519  */
520 static void CASocketEventReturned(CASocketFd_t s, long networkEvents)
521 {
522     if (caglobals.tcp.terminate)
523     {
524         return;
525     }
526
527     assert(s != OC_INVALID_SOCKET);
528
529     if (FD_ACCEPT & networkEvents)
530     {
531         if ((caglobals.tcp.ipv4.fd != OC_INVALID_SOCKET) && (caglobals.tcp.ipv4.fd == s))
532         {
533             CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
534         }
535         else if ((caglobals.tcp.ipv6.fd != OC_INVALID_SOCKET) && (caglobals.tcp.ipv6.fd == s))
536         {
537             CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
538         }
539     }
540
541     if (FD_READ & networkEvents)
542     {
543         oc_mutex_lock(g_mutexObjectList);
544         CATCPSessionInfo_t *session = NULL;
545         CATCPSessionInfo_t *tmp = NULL;
546         LL_FOREACH_SAFE(g_sessionList, session, tmp)
547         {
548             if (session && (session->fd == s))
549             {
550                 CAResult_t res = CAReceiveMessage(session);
551                 //disconnect session and clean-up data if any error occurs
552                 if (res != CA_STATUS_OK)
553                 {
554 #ifdef __WITH_TLS__
555                     if (CA_STATUS_OK != CAcloseSslConnection(&session->sep.endpoint))
556                     {
557                         OIC_LOG(ERROR, TAG, "Failed to close TLS session");
558                     }
559 #endif
560                     LL_DELETE(g_sessionList, session);
561                     CADisconnectTCPSession(session);
562                     oc_mutex_unlock(g_mutexObjectList);
563                     return;
564                 }
565             }
566         }
567         oc_mutex_unlock(g_mutexObjectList);
568     }
569 }
570
571 #endif // WSA_WAIT_EVENT_0
572
573 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
574 {
575     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
576
577     struct sockaddr_storage clientaddr;
578     socklen_t clientlen = sizeof (struct sockaddr_in);
579     if (flag & CA_IPV6)
580     {
581         clientlen = sizeof(struct sockaddr_in6);
582     }
583
584     CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
585     if (OC_INVALID_SOCKET != sockfd)
586     {
587         CATCPSessionInfo_t *svritem =
588                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
589         if (!svritem)
590         {
591             OIC_LOG(ERROR, TAG, "Out of memory");
592             OC_CLOSE_SOCKET(sockfd);
593             return;
594         }
595
596         svritem->fd = sockfd;
597         svritem->sep.endpoint.flags = flag;
598         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
599         svritem->state = CONNECTED;
600         svritem->isClient = false;
601         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
602                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
603
604         oc_mutex_lock(g_mutexObjectList);
605         LL_APPEND(g_sessionList, svritem);
606         oc_mutex_unlock(g_mutexObjectList);
607
608         CHECKFD(sockfd);
609
610         // pass the connection information to CA Common Layer.
611         if (g_connectionCallback)
612         {
613             g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
614         }
615     }
616 }
617
618 /**
619  * Clean socket state data
620  *
621  * @param[in,out] item - socket state data
622  */
623 void CACleanData(CATCPSessionInfo_t *svritem)
624 {
625     if (svritem)
626     {
627         OICFree(svritem->data);
628         svritem->data = NULL;
629         svritem->len = 0;
630         svritem->tlsLen = 0;
631         svritem->totalLen = 0;
632         svritem->protocol = UNKNOWN;
633     }
634 }
635
636 /**
637  * Construct CoAP header and payload from buffer
638  *
639  * @param[in] svritem - used socket, buffer, current received message length and protocol
640  * @param[in,out]  data  - data buffer, this value is updated as data is copied to svritem
641  * @param[in,out]  dataLength  - length of data, this value decreased as data is copied to svritem
642  * @return             - CA_STATUS_OK or appropriate error code
643  */
644 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
645                           size_t *dataLength)
646 {
647     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
648
649     if (NULL == svritem || NULL == data || NULL == dataLength)
650     {
651         OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
652         return CA_STATUS_INVALID_PARAM;
653     }
654
655     unsigned char *inBuffer = *data;
656     size_t inLen = *dataLength;
657     OIC_LOG_V(DEBUG, TAG, "before-datalength : %" PRIuPTR, *dataLength);
658
659     if (NULL == svritem->data && inLen > 0)
660     {
661         // allocate memory for message header (CoAP header size because it is bigger)
662         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
663         if (NULL == svritem->data)
664         {
665             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
666             return CA_MEMORY_ALLOC_FAILED;
667         }
668
669         // copy 1 byte to parse coap header length
670         memcpy(svritem->data, inBuffer, 1);
671         svritem->len = 1;
672         inBuffer++;
673         inLen--;
674     }
675
676     //if not enough data received - read them on next CAFillHeader() call
677     if (0 == inLen)
678     {
679         return CA_STATUS_OK;
680     }
681
682     //if enough data received - parse header
683     svritem->protocol = COAP;
684
685     //seems CoAP data received. read full coap header.
686     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
687     size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
688     size_t copyLen = 0;
689
690     // HEADER
691     if (svritem->len < headerLen)
692     {
693         copyLen = headerLen - svritem->len;
694         if (inLen < copyLen)
695         {
696             copyLen = inLen;
697         }
698
699         //read required bytes to have full CoAP header
700         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
701         svritem->len += copyLen;
702         inBuffer += copyLen;
703         inLen -= copyLen;
704
705         //if not enough data received - read them on next CAFillHeader() call
706         if (svritem->len < headerLen)
707         {
708             *data = inBuffer;
709             *dataLength = inLen;
710             OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
711             return CA_STATUS_OK;
712         }
713
714         //calculate CoAP message length
715         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
716
717         // allocate required memory
718         unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
719         if (NULL == buffer)
720         {
721             OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
722             return CA_MEMORY_ALLOC_FAILED;
723         }
724         svritem->data = buffer;
725     }
726
727     // PAYLOAD
728     if (inLen > 0)
729     {
730         // read required bytes to have full CoAP payload
731         copyLen = svritem->totalLen - svritem->len;
732         if (inLen < copyLen)
733         {
734             copyLen = inLen;
735         }
736
737         //read required bytes to have full CoAP header
738         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
739         svritem->len += copyLen;
740         inBuffer += copyLen;
741         inLen -= copyLen;
742     }
743
744     *data = inBuffer;
745     *dataLength = inLen;
746
747     OIC_LOG_V(DEBUG, TAG, "after-datalength : %" PRIuPTR, *dataLength);
748     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
749     return CA_STATUS_OK;
750 }
751
752 static CAResult_t CAReceiveMessage(CATCPSessionInfo_t *svritem)
753 {
754     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
755
756     // read data
757     int len = 0;
758     CAResult_t res = CA_STATUS_OK;
759     if (svritem->sep.endpoint.flags & CA_SECURE)
760     {
761         svritem->protocol = TLS;
762
763 #ifdef __WITH_TLS__
764         size_t nbRead = 0;
765         size_t tlsLength = 0;
766
767         if (TLS_HEADER_SIZE > svritem->tlsLen)
768         {
769             nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
770         }
771         else
772         {
773             //[3][4] bytes in tls header are tls payload length
774             tlsLength = TLS_HEADER_SIZE +
775                             (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
776             OIC_LOG_V(DEBUG, TAG, "total tls length = %" PRIuPTR, tlsLength);
777             if (tlsLength > sizeof(svritem->tlsdata))
778             {
779                 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %" PRIuPTR ")",
780                                     sizeof(svritem->tlsdata));
781                 if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
782                 {
783                     OIC_LOG(ERROR, TAG, "Failed to close TLS session");
784                 }
785                 CASearchAndDeleteTCPSession(&(svritem->sep.endpoint));
786                 return CA_RECEIVE_FAILED;
787             }
788             nbRead = tlsLength - svritem->tlsLen;
789         }
790
791         len = recv(svritem->fd, (char*)svritem->tlsdata + svritem->tlsLen, (int)nbRead, 0);
792         if (len < 0)
793         {
794             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
795             res = CA_RECEIVE_FAILED;
796         }
797         else if (0 == len)
798         {
799             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
800             res = CA_DESTINATION_DISCONNECTED;
801         }
802         else
803         {
804             svritem->tlsLen += len;
805             OIC_LOG_V(DEBUG, TAG, "nb_read : %" PRIuPTR " bytes , recv() : %d bytes, svritem->tlsLen : %" PRIuPTR " bytes",
806                                 nbRead, len, svritem->tlsLen);
807             if (tlsLength > 0 && tlsLength == svritem->tlsLen)
808             {
809                 //when successfully read data - pass them to callback.
810                 res = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->tlsdata, (int)svritem->tlsLen);
811                 svritem->tlsLen = 0;
812                 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
813             }
814         }
815 #endif
816
817     }
818     else
819     {
820         svritem->protocol = COAP;
821
822         // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
823         len = recv(svritem->fd, (char*)svritem->tlsdata, sizeof(svritem->tlsdata), 0);
824         if (len < 0)
825         {
826             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
827             res = CA_RECEIVE_FAILED;
828         }
829         else if (0 == len)
830         {
831             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
832             res = CA_DESTINATION_DISCONNECTED;
833         }
834         else
835         {
836             OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
837             //when successfully read data - pass them to callback.
838             if (g_packetReceivedCallback)
839             {
840                 g_packetReceivedCallback(&svritem->sep, svritem->tlsdata, len);
841             }
842         }
843     }
844
845     return res;
846 }
847
848 #if !defined(WSA_WAIT_EVENT_0)
849 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
850 {
851     if (caglobals.tcp.connectionFds[1] != -1)
852     {
853         ssize_t len = 0;
854         do
855         {
856             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
857         } while ((len == -1) && (errno == EINTR));
858
859         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
860         {
861             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
862         }
863         return len;
864     }
865     return -1;
866 }
867 #else
868 static void CAWakeUpForReadFdsUpdate()
869 {
870     if (WSA_INVALID_EVENT != caglobals.tcp.updateEvent)
871     {
872         if (!WSASetEvent(caglobals.tcp.updateEvent))
873         {
874             OIC_LOG_V(DEBUG, TAG, "CAWakeUpForReadFdsUpdate: set shutdown event failed: %u", GetLastError());
875         }
876     }
877 }
878 #endif
879
880 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
881 {
882     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
883
884     OIC_LOG_V(DEBUG, TAG, "try to connect with [%s:%u]",
885               svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
886
887     // #1. create tcp socket.
888     CASocketFd_t fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
889     if (OC_INVALID_SOCKET == fd)
890     {
891         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
892         return CA_SOCKET_OPERATION_FAILED;
893     }
894     svritem->fd = fd;
895
896     // #2. convert address from string to binary.
897     struct sockaddr_storage sa = { .ss_family = (short)family };
898     CAResult_t res = CAConvertNameToAddr(svritem->sep.endpoint.addr,
899                                          svritem->sep.endpoint.port, &sa);
900     if (CA_STATUS_OK != res)
901     {
902         OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
903         return CA_SOCKET_OPERATION_FAILED;
904     }
905
906     // #3. set socket length.
907     socklen_t socklen = 0;
908     if (sa.ss_family == AF_INET6)
909     {
910         socklen = sizeof(struct sockaddr_in6);
911     }
912     else
913     {
914         socklen = sizeof(struct sockaddr_in);
915     }
916
917     // #4. connect to remote server device.
918     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
919     {
920         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
921         CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
922                            svritem->sep.endpoint.port, 0, false, strerror(errno));
923         return CA_SOCKET_OPERATION_FAILED;
924     }
925
926     OIC_LOG(DEBUG, TAG, "connect socket success");
927     svritem->state = CONNECTED;
928     CHECKFD(svritem->fd);
929 #if !defined(WSA_WAIT_EVENT_0)
930     ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
931     if (-1 == len)
932     {
933         OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
934         return CA_SOCKET_OPERATION_FAILED;
935     }
936 #else
937     CAWakeUpForReadFdsUpdate();
938 #endif
939     return CA_STATUS_OK;
940 }
941
942 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
943 {
944     VERIFY_NON_NULL_RET(sock, TAG, "sock", OC_INVALID_SOCKET);
945
946     if (OC_INVALID_SOCKET != sock->fd)
947     {
948         OIC_LOG(DEBUG, TAG, "accept socket created already");
949         return sock->fd;
950     }
951
952     socklen_t socklen = 0;
953     struct sockaddr_storage server = { .ss_family = (short)family };
954
955     CASocketFd_t fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
956     if (OC_INVALID_SOCKET == fd)
957     {
958         OIC_LOG(ERROR, TAG, "Failed to create socket");
959         goto exit;
960     }
961
962     if (family == AF_INET6)
963     {
964         // the socket is restricted to sending and receiving IPv6 packets only.
965         int on = 1;
966         if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&on), sizeof (on)))
967         {
968             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
969             goto exit;
970         }
971         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
972         socklen = sizeof (struct sockaddr_in6);
973     }
974     else
975     {
976         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
977         socklen = sizeof (struct sockaddr_in);
978     }
979
980     int reuse = 1;
981     if (OC_SOCKET_ERROR == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&reuse), sizeof(reuse)))
982     {
983         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
984         goto exit;
985     }
986
987     if (OC_SOCKET_ERROR == bind(fd, (struct sockaddr *)&server, socklen))
988     {
989         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
990         goto exit;
991     }
992
993     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
994     {
995         OIC_LOG(ERROR, TAG, "listen() error");
996         goto exit;
997     }
998
999     if (!sock->port)  // return the assigned port
1000     {
1001         if (OC_SOCKET_ERROR == getsockname(fd, (struct sockaddr *)&server, &socklen))
1002         {
1003             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
1004             goto exit;
1005         }
1006         sock->port = ntohs(family == AF_INET6 ?
1007                       ((struct sockaddr_in6 *)&server)->sin6_port :
1008                       ((struct sockaddr_in *)&server)->sin_port);
1009     }
1010
1011     return fd;
1012
1013 exit:
1014     if (fd != OC_INVALID_SOCKET)
1015     {
1016         OC_CLOSE_SOCKET(fd);
1017     }
1018     return OC_INVALID_SOCKET;
1019 }
1020
1021 #if !defined(WSA_WAIT_EVENT_0)
1022 static void CAInitializePipe(int *fds)
1023 {
1024     int ret = pipe(fds);
1025     if (-1 != ret)
1026     {
1027         ret = fcntl(fds[0], F_GETFD);
1028         if (-1 != ret)
1029         {
1030             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1031         }
1032         if (-1 != ret)
1033         {
1034             ret = fcntl(fds[1], F_GETFD);
1035         }
1036         if (-1 != ret)
1037         {
1038             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1039         }
1040         if (-1 == ret)
1041         {
1042             close(fds[1]);
1043             close(fds[0]);
1044
1045             fds[0] = -1;
1046             fds[1] = -1;
1047
1048             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1049         }
1050     }
1051 }
1052 #endif
1053
1054 #define NEWSOCKET(FAMILY, NAME) \
1055     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1056     if (caglobals.tcp.NAME.fd == OC_INVALID_SOCKET) \
1057     { \
1058         caglobals.tcp.NAME.port = 0; \
1059         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1060     } \
1061     CHECKFD(caglobals.tcp.NAME.fd);
1062
1063 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1064 {
1065     if (caglobals.tcp.started)
1066     {
1067         OIC_LOG(DEBUG, TAG, "Adapter is started already");
1068         return CA_STATUS_OK;
1069     }
1070
1071     if (!caglobals.tcp.ipv4tcpenabled)
1072     {
1073         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
1074     }
1075     if (!caglobals.tcp.ipv6tcpenabled)
1076     {
1077         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
1078     }
1079
1080     CAResult_t res = CATCPCreateMutex();
1081     if (CA_STATUS_OK == res)
1082     {
1083         res = CATCPCreateCond();
1084     }
1085     if (CA_STATUS_OK != res)
1086     {
1087         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
1088         return res;
1089     }
1090
1091     if (caglobals.tcp.ipv6tcpenabled)
1092     {
1093         NEWSOCKET(AF_INET6, ipv6);
1094         NEWSOCKET(AF_INET6, ipv6s);
1095         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1096                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1097         OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1098                   caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1099     }
1100
1101     if (caglobals.tcp.ipv4tcpenabled)
1102     {
1103         NEWSOCKET(AF_INET, ipv4);
1104         NEWSOCKET(AF_INET, ipv4s);
1105         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1106                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1107         OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1108                   caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1109     }
1110
1111     // create mechanism for fast shutdown
1112 #ifdef WSA_WAIT_EVENT_0
1113     caglobals.tcp.updateEvent = WSACreateEvent();
1114     if (WSA_INVALID_EVENT == caglobals.tcp.updateEvent)
1115     {
1116         OIC_LOG(ERROR, TAG, "failed to create shutdown event");
1117         return res;
1118     }
1119 #else
1120     CAInitializePipe(caglobals.tcp.shutdownFds);
1121     CHECKFD(caglobals.tcp.shutdownFds[0]);
1122     CHECKFD(caglobals.tcp.shutdownFds[1]);
1123 #endif
1124
1125 #ifndef WSA_WAIT_EVENT_0
1126     CAInitializePipe(caglobals.tcp.connectionFds);
1127     CHECKFD(caglobals.tcp.connectionFds[0]);
1128     CHECKFD(caglobals.tcp.connectionFds[1]);
1129 #endif
1130
1131     caglobals.tcp.terminate = false;
1132     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
1133     if (CA_STATUS_OK != res)
1134     {
1135         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1136         return res;
1137     }
1138     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
1139
1140     caglobals.tcp.started = true;
1141     return CA_STATUS_OK;
1142 }
1143
1144 void CATCPStopServer(void)
1145 {
1146     if (caglobals.tcp.terminate)
1147     {
1148         OIC_LOG(DEBUG, TAG, "Adapter is not enabled");
1149         return;
1150     }
1151
1152     // mutex lock
1153     oc_mutex_lock(g_mutexObjectList);
1154
1155     // set terminate flag.
1156     caglobals.tcp.terminate = true;
1157
1158 #if !defined(WSA_WAIT_EVENT_0)
1159     if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1160     {
1161         close(caglobals.tcp.shutdownFds[1]);
1162         caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1163         // receive thread will stop immediately
1164     }
1165 #else
1166     // unit tests sometimes stop the TCP Server after starting just the UDP Server.
1167     if (caglobals.tcp.updateEvent != NULL)
1168     {
1169         // receive thread will stop immediately.
1170         if (!WSASetEvent(caglobals.tcp.updateEvent))
1171         {
1172             OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %u", GetLastError());
1173         }
1174     }
1175 #endif
1176
1177     // close accept socket.
1178     CLOSE_SOCKET(ipv4);
1179     CLOSE_SOCKET(ipv4s);
1180     CLOSE_SOCKET(ipv6);
1181     CLOSE_SOCKET(ipv6s);
1182
1183     if (caglobals.tcp.started)
1184     {
1185         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1186         caglobals.tcp.started = false;
1187     }
1188
1189 #if !defined(WSA_WAIT_EVENT_0)
1190     close(caglobals.tcp.connectionFds[1]);
1191     close(caglobals.tcp.connectionFds[0]);
1192     caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1193     caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1194
1195     close(caglobals.tcp.shutdownFds[0]);
1196     caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1197 #endif
1198
1199     // mutex unlock
1200     oc_mutex_unlock(g_mutexObjectList);
1201
1202     CATCPDisconnectAll();
1203     CATCPDestroyMutex();
1204     CATCPDestroyCond();
1205
1206     OIC_LOG(DEBUG, TAG, "Adapter terminated successfully");
1207 }
1208
1209 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1210 {
1211     g_packetReceivedCallback = callback;
1212 }
1213
1214 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1215 {
1216     g_connectionCallback = connHandler;
1217 }
1218
1219 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1220 {
1221     VERIFY_NON_NULL_RET(data, TAG, "data", 0);
1222
1223     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1224             ((unsigned char *)data)[0] >> 4);
1225
1226     coap_pdu_t *pdu = coap_pdu_init2(0, 0,
1227                                      ntohs((unsigned short)COAP_INVALID_TID),
1228                                      dlen, transport);
1229     if (!pdu)
1230     {
1231         OIC_LOG(ERROR, TAG, "outpdu is null");
1232         OIC_LOG_V(DEBUG, TAG, "data length: %" PRIuPTR, dlen);
1233         return 0;
1234     }
1235
1236     int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1237     if (0 >= ret)
1238     {
1239         OIC_LOG(ERROR, TAG, "pdu parse failed");
1240         coap_delete_pdu(pdu);
1241         return 0;
1242     }
1243
1244     size_t payloadLen = 0;
1245     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1246     OIC_LOG_V(DEBUG, TAG, "headerSize : %" PRIuPTR ", pdu length : %d",
1247               headerSize, pdu->length);
1248     if (pdu->length > headerSize)
1249     {
1250         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1251     }
1252
1253     OICFree(pdu);
1254
1255     return payloadLen;
1256 }
1257
1258 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1259                         size_t dlen, const char *fam)
1260 {
1261     OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %" PRIuPTR " bytes", dlen);
1262
1263     // #1. find a session info from list.
1264     CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1265     if (OC_INVALID_SOCKET == sockFd)
1266     {
1267         // if there is no connection info, connect to remote device.
1268         sockFd = CAConnectTCPSession(endpoint);
1269         if (OC_INVALID_SOCKET == sockFd)
1270         {
1271             OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1272             return -1;
1273         }
1274     }
1275
1276     // #2. send data to remote device.
1277     ssize_t remainLen = dlen;
1278     do
1279     {
1280         int dataToSend = (remainLen > INT_MAX) ? INT_MAX : (int)remainLen;
1281         ssize_t len = send(sockFd, data, dataToSend, 0);
1282         if (-1 == len)
1283         {
1284             if (EWOULDBLOCK != errno)
1285             {
1286                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1287                 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1288                                    len, false, strerror(errno));
1289                 return len;
1290             }
1291             continue;
1292         }
1293         data = ((char*)data) + len;
1294         remainLen -= len;
1295     } while (remainLen > 0);
1296
1297 #ifndef TB_LOG
1298     (void)fam;
1299 #endif
1300     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %" PRIuPTR " bytes", fam, dlen);
1301     CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1302                        dlen, true, NULL);
1303     return dlen;
1304 }
1305
1306 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1307 {
1308     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
1309     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1310     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1311
1312     if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1313     {
1314         return sendData(endpoint, data, datalen, "ipv6");
1315     }
1316     if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1317     {
1318         return sendData(endpoint, data, datalen, "ipv4");
1319     }
1320
1321     OIC_LOG(ERROR, TAG, "Not supported transport flags");
1322     return -1;
1323 }
1324
1325 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, size_t *size)
1326 {
1327     VERIFY_NON_NULL(info, TAG, "info is NULL");
1328     VERIFY_NON_NULL(size, TAG, "size is NULL");
1329
1330     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1331     if (!iflist)
1332     {
1333         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1334         return CA_STATUS_FAILED;
1335     }
1336
1337 #ifdef __WITH_TLS__
1338     const size_t endpointsPerInterface = 2;
1339 #else
1340     const size_t endpointsPerInterface = 1;
1341 #endif
1342
1343     size_t interfaces = u_arraylist_length(iflist);
1344     for (size_t i = 0; i < u_arraylist_length(iflist); i++)
1345     {
1346         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1347         if (!ifitem)
1348         {
1349             continue;
1350         }
1351
1352         if ((ifitem->family == AF_INET6 && !caglobals.ip.ipv6enabled) ||
1353             (ifitem->family == AF_INET && !caglobals.ip.ipv4enabled))
1354         {
1355             interfaces--;
1356         }
1357     }
1358
1359     if (!interfaces)
1360     {
1361         OIC_LOG(DEBUG, TAG, "network interface size is zero");
1362         return CA_STATUS_OK;
1363     }
1364
1365     size_t totalEndpoints = interfaces * endpointsPerInterface;
1366     CAEndpoint_t *ep = (CAEndpoint_t *)OICCalloc(totalEndpoints, sizeof (CAEndpoint_t));
1367     if (!ep)
1368     {
1369         OIC_LOG(ERROR, TAG, "Malloc Failed");
1370         u_arraylist_destroy(iflist);
1371         return CA_MEMORY_ALLOC_FAILED;
1372     }
1373
1374     for (size_t i = 0, j = 0; i < u_arraylist_length(iflist); i++)
1375     {
1376         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1377         if (!ifitem)
1378         {
1379             continue;
1380         }
1381
1382         if ((ifitem->family == AF_INET6 && !caglobals.ip.ipv6enabled) ||
1383             (ifitem->family == AF_INET && !caglobals.ip.ipv4enabled))
1384         {
1385             continue;
1386         }
1387
1388         ep[j].adapter = CA_ADAPTER_TCP;
1389         ep[j].ifindex = ifitem->index;
1390
1391         if (ifitem->family == AF_INET6)
1392         {
1393             ep[j].flags = CA_IPV6;
1394             ep[j].port = caglobals.tcp.ipv6.port;
1395         }
1396         else if (ifitem->family == AF_INET)
1397         {
1398             ep[j].flags = CA_IPV4;
1399             ep[j].port = caglobals.tcp.ipv4.port;
1400         }
1401         else
1402         {
1403             continue;
1404         }
1405         OICStrcpy(ep[j].addr, sizeof(ep[j].addr), ifitem->addr);
1406
1407 #ifdef __WITH_TLS__
1408         j++;
1409
1410         ep[j].adapter = CA_ADAPTER_TCP;
1411         ep[j].ifindex = ifitem->index;
1412
1413         if (ifitem->family == AF_INET6)
1414         {
1415             ep[j].flags = CA_IPV6 | CA_SECURE;
1416             ep[j].port = caglobals.tcp.ipv6s.port;
1417         }
1418         else
1419         {
1420             ep[j].flags = CA_IPV4 | CA_SECURE;
1421             ep[j].port = caglobals.tcp.ipv4s.port;
1422         }
1423         OICStrcpy(ep[j].addr, sizeof(ep[j].addr), ifitem->addr);
1424 #endif
1425         j++;
1426     }
1427
1428     *info = ep;
1429     *size = totalEndpoints;
1430
1431     u_arraylist_destroy(iflist);
1432
1433     return CA_STATUS_OK;
1434 }
1435
1436 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1437 {
1438     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
1439     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1440
1441     // #1. create TCP server object
1442     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1443     if (!svritem)
1444     {
1445         OIC_LOG(ERROR, TAG, "Out of memory");
1446         return OC_INVALID_SOCKET;
1447     }
1448     svritem->sep.endpoint = *endpoint;
1449     svritem->state = CONNECTING;
1450     svritem->isClient = true;
1451
1452     // #2. add TCP connection info to list
1453     oc_mutex_lock(g_mutexObjectList);
1454     LL_APPEND(g_sessionList, svritem);
1455     oc_mutex_unlock(g_mutexObjectList);
1456
1457     // #3. create the socket and connect to TCP server
1458     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1459     if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1460     {
1461         return OC_INVALID_SOCKET;
1462     }
1463
1464     // #4. pass the connection information to CA Common Layer.
1465     if (g_connectionCallback)
1466     {
1467         g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1468     }
1469
1470     return svritem->fd;
1471 }
1472
1473 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *removedData)
1474 {
1475     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
1476
1477     VERIFY_NON_NULL(removedData, TAG, "removedData is NULL");
1478
1479     // close the socket and remove session info in list.
1480     if (removedData->fd != OC_INVALID_SOCKET)
1481     {
1482         shutdown(removedData->fd, SHUT_RDWR);
1483         OC_CLOSE_SOCKET(removedData->fd);
1484         removedData->fd = OC_INVALID_SOCKET;
1485         OIC_LOG(DEBUG, TAG, "close socket");
1486         removedData->state = (CONNECTED == removedData->state) ?
1487                                     DISCONNECTED : removedData->state;
1488
1489         // pass the connection information to CA Common Layer.
1490         if (g_connectionCallback && DISCONNECTED == removedData->state)
1491         {
1492             g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1493         }
1494     }
1495     OICFree(removedData->data);
1496     removedData->data = NULL;
1497
1498     OICFree(removedData);
1499
1500     OIC_LOG(DEBUG, TAG, "data is removed from session list");
1501     return CA_STATUS_OK;
1502 }
1503
1504 void CATCPDisconnectAll(void)
1505 {
1506     oc_mutex_lock(g_mutexObjectList);
1507     CATCPSessionInfo_t *session = NULL;
1508     CATCPSessionInfo_t *tmp = NULL;
1509     LL_FOREACH_SAFE(g_sessionList, session, tmp)
1510     {
1511         if (session)
1512         {
1513             LL_DELETE(g_sessionList, session);
1514             // disconnect session from remote device.
1515             CADisconnectTCPSession(session);
1516         }
1517     }
1518
1519     g_sessionList = NULL;
1520     oc_mutex_unlock(g_mutexObjectList);
1521
1522 #ifdef __WITH_TLS__
1523     CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1524 #endif
1525
1526 }
1527
1528 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint)
1529 {
1530     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1531
1532     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1533
1534     // get connection info from list
1535     CATCPSessionInfo_t *session = NULL;
1536     LL_FOREACH(g_sessionList, session)
1537     {
1538         if (!strncmp(session->sep.endpoint.addr, endpoint->addr,
1539                      sizeof(session->sep.endpoint.addr))
1540                 && (session->sep.endpoint.port == endpoint->port)
1541                 && (session->sep.endpoint.flags & endpoint->flags))
1542         {
1543             OIC_LOG(DEBUG, TAG, "Found in session list");
1544             return session;
1545         }
1546     }
1547
1548     OIC_LOG(DEBUG, TAG, "Session not found");
1549     return NULL;
1550 }
1551
1552 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1553 {
1554     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1555
1556     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1557
1558     // get connection info from list.
1559     oc_mutex_lock(g_mutexObjectList);
1560     CATCPSessionInfo_t *session = NULL;
1561     LL_FOREACH(g_sessionList, session)
1562     {
1563         if (!strncmp(session->sep.endpoint.addr, endpoint->addr,
1564                      sizeof(session->sep.endpoint.addr))
1565                 && (session->sep.endpoint.port == endpoint->port)
1566                 && (session->sep.endpoint.flags & endpoint->flags))
1567         {
1568             oc_mutex_unlock(g_mutexObjectList);
1569             OIC_LOG(DEBUG, TAG, "Found in session list");
1570             return session->fd;
1571         }
1572     }
1573
1574     oc_mutex_unlock(g_mutexObjectList);
1575     OIC_LOG(DEBUG, TAG, "Session not found");
1576     return OC_INVALID_SOCKET;
1577 }
1578
1579 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1580 {
1581     VERIFY_NON_NULL(endpoint, TAG, "endpoint is NULL");
1582
1583     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1584
1585     // get connection info from list
1586     CATCPSessionInfo_t *session = NULL;
1587     CATCPSessionInfo_t *tmp = NULL;
1588
1589     oc_mutex_lock(g_mutexObjectList);
1590     LL_FOREACH_SAFE(g_sessionList, session, tmp)
1591     {
1592         if (!strncmp(session->sep.endpoint.addr, endpoint->addr,
1593                      sizeof(session->sep.endpoint.addr))
1594                 && (session->sep.endpoint.port == endpoint->port)
1595                 && (session->sep.endpoint.flags & endpoint->flags))
1596         {
1597             OIC_LOG(DEBUG, TAG, "Found in session list");
1598             LL_DELETE(g_sessionList, session);
1599             CADisconnectTCPSession(session);
1600             oc_mutex_unlock(g_mutexObjectList);
1601             return CA_STATUS_OK;
1602         }
1603     }
1604     oc_mutex_unlock(g_mutexObjectList);
1605
1606     OIC_LOG(DEBUG, TAG, "Session not found");
1607     return CA_STATUS_OK;
1608 }
1609
1610 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1611 {
1612     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1613
1614     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1615             ((unsigned char *)recvBuffer)[0] >> 4);
1616     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1617                                                         transport);
1618     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1619
1620     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%" PRIuPTR "]", optPaylaodLen);
1621     OIC_LOG_V(DEBUG, TAG, "header length [%" PRIuPTR "]", headerLen);
1622     OIC_LOG_V(DEBUG, TAG, "total data length [%" PRIuPTR "]", headerLen + optPaylaodLen);
1623
1624     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1625     return headerLen + optPaylaodLen;
1626 }
1627
1628 uint32_t CAGetCodeFromHeader(const unsigned char *recvBuffer)
1629 {
1630     OIC_LOG(DEBUG, TAG, "IN - CAGetCodeFromHeader");
1631
1632     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1633                 ((unsigned char *)recvBuffer)[0] >> 4);
1634     size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
1635     uint32_t code = CA_TCP_RESPONSE_CODE(recvBuffer[headerLen -1]);
1636
1637     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1638     OIC_LOG_V(DEBUG, TAG, "code [%d]", code);
1639
1640     OIC_LOG(DEBUG, TAG, "OUT - CAGetCodeFromHeader");
1641     return code;
1642 }
1643
1644 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1645 {
1646     g_tcpErrorHandler = errorHandleCallback;
1647 }
1648
1649 CACSMExchangeState_t CAGetCSMState(const CAEndpoint_t *endpoint)
1650 {
1651     oc_mutex_lock(g_mutexObjectList);
1652
1653     CACSMExchangeState_t csmState = NONE;
1654     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint);
1655     if (svritem)
1656     {
1657         csmState = svritem->CSMState;
1658     }
1659
1660     oc_mutex_unlock(g_mutexObjectList);
1661     return csmState;
1662 }
1663
1664 void CAUpdateCSMState(const CAEndpoint_t *endpoint, CACSMExchangeState_t state)
1665 {
1666     oc_mutex_lock(g_mutexObjectList);
1667
1668     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint);
1669     if (svritem)
1670     {
1671         svritem->CSMState = state;
1672     }
1673
1674     oc_mutex_unlock(g_mutexObjectList);
1675     return;
1676 }