Merge branch 'tizen' into tizen_5.5
[platform/upstream/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 <sys/types.h>
22 #include <sys/socket.h>
23 #include <sys/ioctl.h>
24 #if defined(__TIZEN__)
25 #include <ifaddrs.h>
26 #endif
27 #ifdef __TIZENRT__
28 #include <tinyara/config.h>
29 #include <poll.h>
30 #else
31 #include <sys/poll.h>
32 #endif
33 #include <stdio.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <arpa/inet.h>
37 #include <netinet/in.h>
38 #include <netinet/tcp.h>
39 #include <net/if.h>
40 #include <errno.h>
41
42 #ifndef WITH_ARDUINO
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <netdb.h>
46 #endif
47
48 #include "catcpinterface.h"
49 #include "caipnwmonitor.h"
50 #include <coap/pdu.h>
51 #include "caadapterutils.h"
52 #include "catcpserver_mutex.h"
53 #include "octhread.h"
54 #include "oic_malloc.h"
55 #include "oic_string.h"
56
57 #ifdef __WITH_TLS__
58 #include "ca_adapter_net_ssl.h"
59 #endif
60
61 /**
62  * Logging tag for module name.
63  */
64 //#define TAG "OIC_CA_TCP_SERVER"
65 #define TAG TCP_SERVER_TAG
66
67 /**
68  * Maximum CoAP over TCP header length
69  * to know the total data length.
70  */
71 #define COAP_MAX_HEADER_SIZE  6
72
73 /**
74  * TLS header size
75  */
76 #define TLS_HEADER_SIZE 5
77
78 /**
79  * Max Connection Counts.
80  */
81 #define MAX_CONNECTION_COUNTS   500
82
83 #define COAP_TCP_MAX_BUFFER_CHUNK_SIZE 65530 //64kb - 6 (coap+tcp max header size)
84
85 #define MILLISECONDS_PER_SECOND   (1000)
86
87 /**
88  * Thread pool.
89  */
90 static ca_thread_pool_t g_threadPool = NULL;
91
92 /**
93  * Thread task id.
94  */
95 static uint32_t g_taskId = 0;
96
97 /**
98  * Maintains the callback to be notified when data received from remote device.
99  */
100 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
101
102 /**
103  * Error callback to update error in TCP.
104  */
105 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
106
107 /**
108  * Connected Callback to pass the connection information to RI.
109  */
110 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
111
112 /**
113  * Error code to hold the errno(Timeout, Destination unreachable, etc) when send/recv fails.
114  * Main purpose is to hold the reason for connection drop when keep-alive is in use.
115  * To indicate normal disconnection, 0 will be assigned.
116  */
117 static int g_lastErrorCode;
118
119 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
120 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
121 static void CAFindReadyMessage();
122 static void CAPollReturned(struct pollfd *readFds, size_t size);
123 static void CAReceiveMessage(int fd);
124 static void CAReceiveHandler(void *data);
125 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
126 static void CATCPInitializeSocket();
127 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index);
128
129 #if defined(__TIZEN__)
130 static char g_cloudproxyUri[CA_MAX_URI_LENGTH];
131
132 static char g_interfaceName[CA_MAX_INTERFACE_NAME_LEN];
133
134 CAResult_t CASetCloudAddressForProxy(const char *uri)
135 {
136     if (uri == NULL)
137         memset(g_cloudproxyUri, '\0', sizeof (g_cloudproxyUri));
138     else
139         OICStrcpy(g_cloudproxyUri, sizeof (g_cloudproxyUri), uri);
140     return CA_STATUS_OK;
141 }
142
143 const char *CAGetCloudAddressForProxy()
144 {
145     if (g_cloudproxyUri[0] == '\0')
146         return NULL;
147     return g_cloudproxyUri;
148 }
149
150 CAResult_t CASetTCPServerSocketBindIP(const char* ifname)
151 {
152     CAResult_t res = CA_STATUS_OK;
153 #ifdef TCP_ADAPTER
154     VERIFY_NON_NULL_RET(ifname, TAG, "Interface name is NULL", CA_STATUS_INVALID_PARAM);
155
156     OIC_LOG(DEBUG, TAG, "Setting Socket Bind");
157     caglobals.tcp.bindenabled = true;
158     OICStrcpy(g_interfaceName, sizeof (g_interfaceName), ifname);
159 #else
160     OIC_LOG(DEBUG, TAG, "Not supported!");
161     res = CA_NOT_SUPPORTED;
162 #endif
163     return res;
164 }
165 #endif
166
167 #define MAX_TCP_SOCK_COUNT 4
168
169 #define CLOSE_SOCKET(TYPE) \
170     if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
171     { \
172         close(caglobals.tcp.TYPE.fd); \
173         caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
174     }
175
176 #define CA_FD_SET(TYPE, FDS, COUNT) \
177         FDS[COUNT].fd = caglobals.tcp.TYPE.fd; \
178         FDS[COUNT].events = POLLIN;
179
180 static void CAReceiveHandler(void *data)
181 {
182     (void)data;
183     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
184
185     while (true)
186     {
187         oc_mutex_lock(g_mutexObjectList);
188         if (caglobals.tcp.terminate)
189         {
190             oc_mutex_unlock(g_mutexObjectList);
191             break;
192         }
193         oc_mutex_unlock(g_mutexObjectList);
194         CAFindReadyMessage();
195     }
196
197     oc_mutex_lock(g_mutexObjectList);
198     oc_cond_signal(g_condObjectList);
199     oc_mutex_unlock(g_mutexObjectList);
200
201     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
202 }
203
204 static void CAFindReadyMessage()
205 {
206     int timeout = (caglobals.tcp.selectTimeout * 1000);
207     size_t counter = 0;
208
209     oc_mutex_lock(g_mutexObjectList);
210     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
211
212     // Consider 4 tcp sockets(ipv4, ipv4s, ipv6, ipv6s) + 1 connection fd + all sockets in svrlist
213     struct pollfd *readFds = (struct pollfd *)OICCalloc(MAX_TCP_SOCK_COUNT + 1 + length, sizeof(struct pollfd));
214     if (NULL == readFds)
215     {
216         OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
217         oc_mutex_unlock(g_mutexObjectList);
218         return;
219     }
220
221     // 4 tcp sockets
222     CA_FD_SET(ipv4, readFds, counter);
223     counter++;
224     CA_FD_SET(ipv4s, readFds, counter);
225     counter++;
226     CA_FD_SET(ipv6, readFds, counter);
227     counter++;
228     CA_FD_SET(ipv6s, readFds, counter);
229     counter++;
230
231     // 1 connection fd
232     readFds[counter].fd = caglobals.tcp.connectionFds[0];
233     readFds[counter].events = POLLIN;
234     counter++;
235
236     // All sockets in svrlist
237     for (size_t i = 0; i < length; i++)
238     {
239         CATCPSessionInfo_t *svritem =
240                 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
241         if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
242         {
243             readFds[counter].fd = svritem->fd;
244             readFds[counter].events = POLLIN;
245             counter++;
246         }
247     }
248     oc_mutex_unlock(g_mutexObjectList);
249     int ret = poll(readFds, counter, timeout);
250
251     oc_mutex_lock(g_mutexObjectList);
252     if (caglobals.tcp.terminate)
253     {
254         OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
255         oc_mutex_unlock(g_mutexObjectList);
256         OICFree(readFds);
257         return;
258     }
259     oc_mutex_unlock(g_mutexObjectList);
260
261     if (ret > 0)
262     {
263         CAPollReturned(readFds, counter);
264     }
265     else if (ret == 0)
266     {
267         usleep(1000); /* some of the fields are not set by kernel on repeatedly calling
268                          poll.Applying a sleep will solve this by providing a delay between
269                          each subsequent poll system call */
270     }
271     else if (ret < 0)
272     {
273         OIC_LOG_V(FATAL, TAG, "poll error %s", strerror(errno));
274     }
275
276     OICFree(readFds);
277 }
278
279 static void CAPollReturned(struct pollfd *readFds, size_t size)
280 {
281     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
282
283     if (caglobals.tcp.ipv4.fd != -1 && readFds[0].revents == POLLIN)
284     {
285         CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
286         return;
287     }
288     else if (caglobals.tcp.ipv4s.fd != -1 && readFds[1].revents == POLLIN)
289     {
290         CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
291         return;
292     }
293     else if (caglobals.tcp.ipv6.fd != -1 && readFds[2].revents == POLLIN)
294     {
295         CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
296         return;
297     }
298     else if (caglobals.tcp.ipv6s.fd != -1 && readFds[3].revents == POLLIN)
299     {
300         CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
301         return;
302     }
303     else if (-1 != caglobals.tcp.connectionFds[0] && readFds[4].revents != 0)
304     {
305             // new connection was created from remote device.
306             // exit the function to update read file descriptor.
307             char buf[MAX_ADDR_STR_SIZE_CA] = {0};
308             ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
309             if (-1 == len)
310             {
311                 return;
312             }
313             OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
314             return;
315     }
316     else
317     {
318         int *readFDList = NULL;
319         size_t readFDListSize = 0;
320
321         oc_mutex_lock(g_mutexObjectList);
322         uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
323
324         readFDList = (int*) OICCalloc(length, sizeof(int));
325         if (NULL == readFDList)
326         {
327             OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
328             oc_mutex_unlock(g_mutexObjectList);
329             return;
330         }
331
332         for (size_t i = 0; i < length; i++)
333         {
334             CATCPSessionInfo_t *svritem =
335                     (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
336             if (svritem && svritem->fd >= 0)
337             {
338                 size_t j = 0;
339                 while (j < size)
340                 {
341                     if (svritem->fd == readFds[j].fd)
342                     {
343                         break;
344                     }
345                     j++;
346                 }
347
348                 if (j < size  && readFds[j].revents != 0)
349                 {
350                     readFDList[readFDListSize++] = svritem->fd;
351                 }
352             }
353         }
354         oc_mutex_unlock(g_mutexObjectList);
355
356         // Read incomming messages from fds
357         for (size_t i = 0; i < readFDListSize; i++)
358         {
359             CAReceiveMessage(readFDList[i]);
360         }
361
362         OICFree(readFDList);
363     }
364 }
365
366 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
367 {
368     OIC_LOG_V(INFO, TAG, "In %s", __func__);
369     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
370
371     if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
372     {
373         OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
374         close(sock->fd);
375         sock->fd = OC_INVALID_SOCKET;
376         return;
377     }
378
379     struct sockaddr_storage clientaddr;
380     socklen_t clientlen = sizeof (struct sockaddr_in);
381     if (flag & CA_IPV6)
382     {
383         clientlen = sizeof(struct sockaddr_in6);
384     }
385
386     CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
387     if (OC_INVALID_SOCKET != sockfd)
388     {
389         CATCPSessionInfo_t *svritem =
390                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
391         if (!svritem)
392         {
393             OIC_LOG(ERROR, TAG, "Out of memory");
394             close(sockfd);
395             return;
396         }
397
398         svritem->fd = sockfd;
399         svritem->sep.endpoint.flags = flag;
400         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
401         svritem->state = CONNECTED;
402         svritem->isClient = false;
403         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
404                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
405
406         // Allocate message buffer
407         svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
408         if (!svritem->tlsdata)
409         {
410             OIC_LOG(ERROR, TAG, "Out of memory");
411             close(sockfd);
412             OICFree(svritem);
413             return;
414         }
415
416         oc_mutex_lock(g_mutexObjectList);
417         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
418         if (!result)
419         {
420             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
421             close(sockfd);
422             OICFree(svritem->tlsdata);
423             OICFree(svritem);
424             oc_mutex_unlock(g_mutexObjectList);
425             return;
426         }
427         oc_mutex_unlock(g_mutexObjectList);
428
429         // pass the connection information to CA Common Layer.
430         if (g_connectionCallback)
431         {
432             g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
433         }
434     }
435     OIC_LOG_V(INFO, TAG, "Out %s", __func__);
436 }
437
438 /**
439  * Clean socket state data
440  *
441  * @param[in/out] item - socket state data
442  */
443 void CACleanData(CATCPSessionInfo_t *svritem)
444 {
445     if (svritem)
446     {
447         OICFree(svritem->data);
448         svritem->data = NULL;
449         svritem->len = 0;
450 #ifdef __WITH_TLS__
451         svritem->tlsLen = 0;
452 #endif
453         svritem->totalLen = 0;
454         svritem->bufLen = 0;
455         svritem->protocol = UNKNOWN;
456     }
457 }
458
459 /**
460  * Construct CoAP header and payload from buffer
461  *
462  * @param[in] svritem - used socket, buffer, current received message length and protocol
463  * @param[in/out]  data  - data buffer, this value is updated as data is copied to svritem
464  * @param[in/out]  dataLength  - length of data, this value decreased as data is copied to svritem
465  * @return             - CA_STATUS_OK or appropriate error code
466  */
467 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
468                           size_t *dataLength)
469 {
470     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
471
472     if (NULL == svritem || NULL == data || NULL == dataLength)
473     {
474         OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
475         return CA_STATUS_INVALID_PARAM;
476     }
477
478     unsigned char *inBuffer = *data;
479     size_t inLen = *dataLength;
480     OIC_LOG_V(DEBUG, TAG, "before-datalength : %zd", *dataLength);
481
482     if (NULL == svritem->data && inLen > 0)
483     {
484         // allocate memory for message header (CoAP header size because it is bigger)
485         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
486         if (NULL == svritem->data)
487         {
488             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
489             return CA_MEMORY_ALLOC_FAILED;
490         }
491
492         // copy 1 byte to parse coap header length
493         memcpy(svritem->data, inBuffer, 1);
494         svritem->len = 1;
495         svritem->bufLen = COAP_MAX_HEADER_SIZE;
496         inBuffer++;
497         inLen--;
498     }
499
500     //if not enough data received - read them on next CAFillHeader() call
501     if (0 == inLen)
502     {
503         return CA_STATUS_OK;
504     }
505
506     //if enough data received - parse header
507     svritem->protocol = COAP;
508
509     //seems CoAP data received. read full coap header.
510     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
511     size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
512     size_t copyLen = 0;
513
514     // HEADER
515     if (svritem->len < headerLen)
516     {
517         copyLen = headerLen - svritem->len;
518         if (inLen < copyLen)
519         {
520             copyLen = inLen;
521         }
522
523         //read required bytes to have full CoAP header
524         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
525         svritem->len += copyLen;
526         inBuffer += copyLen;
527         inLen -= copyLen;
528
529         //if not enough data received - read them on next CAFillHeader() call
530         if (svritem->len < headerLen)
531         {
532             *data = inBuffer;
533             *dataLength = inLen;
534             OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
535             return CA_STATUS_OK;
536         }
537
538         //calculate CoAP message length
539         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
540     }
541
542     // PAYLOAD
543     if (inLen > 0)
544     {
545         // Calculate length of data to be copied.
546         copyLen = svritem->totalLen - svritem->len;
547         if (inLen < copyLen)
548         {
549             copyLen = inLen;
550         }
551
552         // Is buffer not big enough for remaining data ?
553         if (svritem->len + copyLen > svritem->bufLen)
554         {
555             // Resize buffer to accommodate enough space
556             size_t extLen = svritem->totalLen - svritem->bufLen;
557             if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
558             {
559                 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
560             }
561
562             // Allocate required memory
563             unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
564             if (NULL == buffer)
565             {
566                 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
567                 return CA_MEMORY_ALLOC_FAILED;
568             }
569
570             svritem->data = buffer;
571             svritem->bufLen += extLen;
572         }
573
574         // Read required bytes to have full CoAP payload
575         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
576         svritem->len += copyLen;
577         inBuffer += copyLen;
578         inLen -= copyLen;
579     }
580
581     *data = inBuffer;
582     *dataLength = inLen;
583
584     OIC_LOG_V(DEBUG, TAG, "after-datalength : %zd", *dataLength);
585     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
586     return CA_STATUS_OK;
587 }
588
589 static void CAReceiveMessage(int fd)
590 {
591     CAResult_t res = CA_STATUS_OK;
592
593     oc_mutex_lock(g_mutexObjectList);
594
595     //get remote device information from file descriptor.
596     size_t index = 0;
597     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
598     if (!svritem)
599     {
600         OIC_LOG(ERROR, TAG, "there is no connection information in list");
601         oc_mutex_unlock(g_mutexObjectList);
602         return;
603     }
604
605     CASecureEndpoint_t peerEP = svritem->sep;
606     int len = 0;
607     if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection
608     {
609         svritem->protocol = TLS;
610
611 #ifdef __WITH_TLS__
612         size_t nbRead = 0;
613         size_t tlsLength = 0;
614
615         if (TLS_HEADER_SIZE > svritem->tlsLen)
616         {
617             nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
618         }
619         else
620         {
621             //[3][4] bytes in tls header are tls payload length
622             tlsLength = TLS_HEADER_SIZE +
623                             (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
624             OIC_LOG_V(DEBUG, TAG, "total tls length = %zd", tlsLength);
625             if (tlsLength > TLS_DATA_MAX_SIZE)
626             {
627                 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
628                                     TLS_DATA_MAX_SIZE);
629                 oc_mutex_unlock(g_mutexObjectList);
630                 CATCPDisconnectSession(&peerEP.endpoint);
631                 return;
632             }
633             nbRead = tlsLength - svritem->tlsLen;
634         }
635
636         len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
637         if (len < 0)
638         {
639             g_lastErrorCode = errno;
640             OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
641             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(g_lastErrorCode));
642             res = CA_RECEIVE_FAILED;
643         }
644         else if (0 == len)
645         {
646             g_lastErrorCode = 0;
647             OIC_LOG(DEBUG, TAG, "Set g_lastErrorCode to 0");
648             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
649             svritem->state = DISCONNECTED;
650             res = CA_DESTINATION_DISCONNECTED;
651         }
652         else
653         {
654             svritem->tlsLen += len;
655             OIC_LOG_V(DEBUG, TAG, "nb_read : %zd bytes , recv() : %d bytes, svritem->tlsLen : %zd bytes",
656                                 nbRead, len, svritem->tlsLen);
657             if (tlsLength > 0 && tlsLength == svritem->tlsLen)
658             {
659                 // When successfully read data - pass them to callback.
660                 // Dont invoke callback locking mutex
661                 unsigned char *mesBuf = svritem->tlsdata;
662                 size_t mesBufLen = svritem->tlsLen;
663                 svritem->tlsdata = NULL;
664                 oc_mutex_unlock(g_mutexObjectList);
665
666                 res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen);
667                 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
668
669                 // Check for the svritem and reset buffer
670                 oc_mutex_lock(g_mutexObjectList);
671                 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
672                 if (svritem)
673                 {
674                     svritem->tlsdata = mesBuf;
675                     svritem->tlsLen = 0;
676                 }
677                 else
678                 {
679                     // svritem does not exist, thus free the message buffer
680                     OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
681                     OICFree(mesBuf);
682                 }
683             }
684         }
685 #endif
686     }
687     else // Non-Secure connection
688     {
689         svritem->protocol = COAP;
690
691         // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
692         len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0);
693         if (len < 0)
694         {
695             g_lastErrorCode = errno;
696             OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
697             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(g_lastErrorCode));
698             res = CA_RECEIVE_FAILED;
699         }
700         else if (0 == len)
701         {
702             g_lastErrorCode = 0;
703             OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to 0");
704             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
705             res = CA_DESTINATION_DISCONNECTED;
706         }
707         else
708         {
709             //when successfully read data - pass them to callback.
710             OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
711             if (g_packetReceivedCallback)
712             {
713                 // Dont invoke callback locking mutex
714                 unsigned char *mesBuf = svritem->tlsdata;
715                 svritem->tlsdata = NULL;
716                 oc_mutex_unlock(g_mutexObjectList);
717
718                 res = g_packetReceivedCallback(&peerEP, mesBuf, len);
719
720                 // Check for the svritem and reset buffer
721                 oc_mutex_lock(g_mutexObjectList);
722                 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
723                 if (svritem)
724                 {
725                     svritem->tlsdata = mesBuf;
726                     svritem->tlsLen = 0;
727                 }
728                 else
729                 {
730                     // svritem does not exist, thus free the message buffer
731                     OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
732                     OICFree(mesBuf);
733                 }
734             }
735         }
736     }
737
738     oc_mutex_unlock(g_mutexObjectList);
739
740     if (res != CA_STATUS_OK)
741     {
742         CATCPDisconnectSession(&peerEP.endpoint);
743     }
744 }
745
746 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
747 {
748     if (caglobals.tcp.connectionFds[1] != -1)
749     {
750         ssize_t len = 0;
751         do
752         {
753             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
754         } while ((len == -1) && (errno == EINTR));
755
756         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
757         {
758             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
759         }
760         return len;
761     }
762     return -1;
763 }
764
765 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
766                                          struct sockaddr_storage *sockaddr)
767 {
768     struct addrinfo *addrs = NULL;
769     struct addrinfo hints = { .ai_family = family,
770                               .ai_protocol   = IPPROTO_TCP,
771                               .ai_socktype = SOCK_STREAM,
772                               .ai_flags = AI_NUMERICHOST };
773
774     int r = getaddrinfo(host, NULL, &hints, &addrs);
775     if (r)
776     {
777         if (EAI_SYSTEM == r)
778         {
779             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
780         }
781         else
782         {
783             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
784         }
785         freeaddrinfo(addrs);
786         return CA_STATUS_FAILED;
787     }
788     // assumption: in this case, getaddrinfo will only return one addrinfo
789     // or first is the one we want.
790     if (addrs[0].ai_family == AF_INET6)
791     {
792         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
793         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
794     }
795     else
796     {
797         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
798         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
799     }
800     freeaddrinfo(addrs);
801     return CA_STATUS_OK;
802 }
803
804 #if defined(__TIZEN__)
805 static char * CATCPGetInterfaceAddr()
806 {
807     struct ifaddrs *ifaddr, *ifa;
808     int family, s, n;
809     char *host = (uint8_t *)OICMalloc(NI_MAXHOST);
810
811     if (getifaddrs(&ifaddr) == -1)
812     {
813         OIC_LOG_V(ERROR, TAG, "getifaddrs failed: errno %s", strerror(errno));
814         OICFree(host);
815         return NULL;
816     }
817
818     for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++)
819     {
820         if (ifa->ifa_addr == NULL)
821             continue;
822
823         family = ifa->ifa_addr->sa_family;
824         OIC_LOG_V(DEBUG, TAG,"Interface name: %s",ifa->ifa_name);
825
826         if ((strncmp(g_interfaceName,ifa->ifa_name,strlen(ifa->ifa_name))==0)
827             && (family == AF_INET || family == AF_INET6))
828         {
829             s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6),
830                                         host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
831             if (s != 0)
832             {
833                 OIC_LOG_V(ERROR, TAG, "getnameinfo failed: errno %s", strerror(errno));
834                 freeifaddrs(ifaddr);
835                 OICFree(host);
836                 return NULL;
837             }
838
839             OIC_LOG_V(DEBUG, TAG, "Interface address: %s", host);
840             freeifaddrs(ifaddr);
841             return host;
842         }
843     }
844
845     freeifaddrs(ifaddr);
846     OICFree(host);
847     OIC_LOG(ERROR, TAG, "Interface address not found");
848     return NULL;
849 }
850 #endif
851
852 #if defined(__TIZEN__)
853 static int CAGetHTTPStatusCode(char * response) {
854     char *resp, *code_plus, *ptrSave;
855     int ret = -1;
856
857     resp = strdup(response);
858     strtok_r(resp, " ", &ptrSave);  /* skip HTTP version */
859     code_plus = strtok_r(NULL, " ", &ptrSave);
860
861     ret = code_plus ? atoi(code_plus) : -1;
862     free(resp);
863     return ret;
864 }
865 #endif
866
867 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
868 {
869     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
870
871     OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
872               svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
873
874     // #1. create tcp socket.
875     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
876     if (-1 == fd)
877     {
878         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
879         return CA_SOCKET_OPERATION_FAILED;
880     }
881     svritem->fd = fd;
882
883     // #2. convert address from string to binary.
884     struct sockaddr_storage sa = { .ss_family = family };
885     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
886                                             svritem->sep.endpoint.port, &sa);
887     if (CA_STATUS_OK != res)
888     {
889         OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
890         return CA_SOCKET_OPERATION_FAILED;
891     }
892
893     // #3. set socket length.
894     socklen_t socklen = 0;
895     if (sa.ss_family == AF_INET6)
896     {
897         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
898         if (!sock6->sin6_scope_id)
899         {
900             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
901         }
902         socklen = sizeof(struct sockaddr_in6);
903     }
904     else
905     {
906         socklen = sizeof(struct sockaddr_in);
907     }
908
909 #if defined(__TIZEN__)
910     if (caglobals.tcp.bindenabled)
911     {
912         char *host_address = CATCPGetInterfaceAddr();
913         if (host_address)
914         {
915             if (sa.ss_family == AF_INET)
916             {
917                 struct sockaddr_in client;
918                 memset(&client, 0x00, sizeof(client));
919                 client.sin_family = AF_INET;
920                 inet_pton(AF_INET, host_address, &(client.sin_addr.s_addr));
921                 if (-1 == bind(fd, (struct sockaddr *)&client, socklen))
922                 {
923                     OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
924                     OICFree(host_address);
925                     return CA_SOCKET_OPERATION_FAILED;
926                 }
927             }
928             else
929             {
930                 struct sockaddr_in6 client6;
931                 memset(&client6, 0x00, sizeof(client6));
932                 client6.sin6_family = AF_INET6;
933                 inet_pton(AF_INET6, host_address, &client6.sin6_addr.s6_addr);
934                 if (-1 == bind(fd, (struct sockaddr *)&client6, socklen))
935                 {
936                     OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
937                     OICFree(host_address);
938                     return CA_SOCKET_OPERATION_FAILED;
939                 }
940             }
941             OICFree(host_address);
942         }
943     }
944 #endif
945
946     // #4. connect to remote server device.
947     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
948     {
949         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
950         CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
951                            svritem->sep.endpoint.port, 0, false, strerror(errno));
952         return CA_SOCKET_OPERATION_FAILED;
953     }
954
955     OIC_LOG(INFO, TAG, "connect socket success");
956     svritem->state = CONNECTED;
957     ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
958     if (-1 == len)
959     {
960         OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
961         return CA_SOCKET_OPERATION_FAILED;
962     }
963
964 #if defined(__TIZEN__)
965     // #5. Send HTTP CONNECT to proxy if proxy
966
967     const char *cloud_address = CAGetCloudAddressForProxy();
968     OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)");
969
970     if(cloud_address && *cloud_address)
971     {
972         char message[4096];
973         int len = snprintf(message, 4096,
974                 "CONNECT %s HTTP/1.1\r\n"
975                 "Host: %s\r\n\r\n", cloud_address, cloud_address
976         );
977
978         ssize_t l = send(fd, message, len, 0);
979         if(l != len)
980         {
981             OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %zd)", len, l);
982             close(fd);
983             svritem->fd = -1;
984             return CA_SOCKET_OPERATION_FAILED;
985         }
986
987         // maybe this should be called in other thread, it causes bottleneck.
988         OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message);
989
990         *message = '\0';
991         OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy...");
992
993         l = recv(fd, message, 4096, 0);
994
995         OIC_LOG_V(INFO, TAG, "Received data : '%s'", message);
996         OIC_LOG_V(INFO, TAG, "Received len = %zd", l);
997
998         int status_code = CAGetHTTPStatusCode(message);
999
1000         OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code);
1001         if(status_code < 200 || status_code > 299)
1002         {
1003             OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %d", status_code);
1004             close(fd);
1005             svritem->fd = -1;
1006             return CA_SOCKET_OPERATION_FAILED;
1007         }
1008     }
1009 #endif
1010
1011     return CA_STATUS_OK;
1012 }
1013
1014 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
1015 {
1016     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
1017
1018     if (OC_INVALID_SOCKET != sock->fd)
1019     {
1020         OIC_LOG(DEBUG, TAG, "accept socket created already");
1021         return sock->fd;
1022     }
1023
1024     socklen_t socklen = 0;
1025     struct sockaddr_storage server = { .ss_family = family };
1026
1027     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
1028     if (OC_INVALID_SOCKET == fd)
1029     {
1030         OIC_LOG(ERROR, TAG, "Failed to create socket");
1031         goto exit;
1032     }
1033
1034     if (family == AF_INET6)
1035     {
1036         // the socket is restricted to sending and receiving IPv6 packets only.
1037         int on = 1;
1038 //TODO: enable once IPv6 is supported
1039 #ifndef __TIZENRT__
1040         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
1041         {
1042             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
1043             goto exit;
1044         }
1045 #endif
1046         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
1047         socklen = sizeof (struct sockaddr_in6);
1048     }
1049     else
1050     {
1051         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
1052         socklen = sizeof (struct sockaddr_in);
1053     }
1054
1055     int reuse = 1;
1056     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
1057     {
1058         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
1059         goto exit;
1060     }
1061
1062     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
1063     {
1064         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1065         goto exit;
1066     }
1067
1068     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
1069     {
1070         OIC_LOG(ERROR, TAG, "listen() error");
1071         goto exit;
1072     }
1073
1074     if (sock->port) // use the given port
1075     {
1076         int on = 1;
1077         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
1078         {
1079             OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
1080             close(fd);
1081             return OC_INVALID_SOCKET;
1082         }
1083     }
1084     else  // return the assigned port
1085     {
1086         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
1087         {
1088             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
1089             goto exit;
1090         }
1091         sock->port = ntohs(family == AF_INET6 ?
1092                       ((struct sockaddr_in6 *)&server)->sin6_port :
1093                       ((struct sockaddr_in *)&server)->sin_port);
1094     }
1095
1096     return fd;
1097
1098 exit:
1099     if (fd >= 0)
1100     {
1101         close(fd);
1102     }
1103     return OC_INVALID_SOCKET;
1104 }
1105
1106 static void CAInitializePipe(int *fds)
1107 {
1108     int ret = pipe(fds);
1109 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
1110 /* Temporary workaround: By pass F_GETFD / F_SETFD */
1111 #ifdef __TIZENRT__
1112     if (-1 == ret)
1113     {
1114         close(fds[1]);
1115         close(fds[0]);
1116
1117         fds[0] = -1;
1118         fds[1] = -1;
1119
1120         OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1121     }
1122 #else
1123     if (-1 != ret)
1124     {
1125         ret = fcntl(fds[0], F_GETFD);
1126         if (-1 != ret)
1127         {
1128             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1129         }
1130         if (-1 != ret)
1131         {
1132             ret = fcntl(fds[1], F_GETFD);
1133         }
1134         if (-1 != ret)
1135         {
1136             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1137         }
1138         if (-1 == ret)
1139         {
1140             close(fds[1]);
1141             close(fds[0]);
1142
1143             fds[0] = -1;
1144             fds[1] = -1;
1145
1146             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1147         }
1148     }
1149 #endif
1150 }
1151
1152 #ifndef DISABLE_TCP_SERVER
1153 #define NEWSOCKET(FAMILY, NAME) \
1154     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1155     if (caglobals.tcp.NAME.fd == -1) \
1156     { \
1157         caglobals.tcp.NAME.port = 0; \
1158         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1159     } \
1160
1161 void CATCPInitializeSocket()
1162 {
1163 #ifndef __WITH_TLS__
1164         NEWSOCKET(AF_INET, ipv4);
1165 #else
1166         NEWSOCKET(AF_INET, ipv4s);
1167 #endif
1168
1169 //TODO Enable once TizenRT supports IPv6
1170 #ifndef __TIZENRT__
1171 #ifndef __WITH_TLS__
1172         NEWSOCKET(AF_INET6, ipv6);
1173 #else
1174         NEWSOCKET(AF_INET6, ipv6s);
1175 #endif
1176 #endif
1177 #ifndef __WITH_TLS__
1178         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1179                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1180         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1181                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1182 #else
1183         OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1184                   caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1185         OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1186                   caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1187 #endif
1188 }
1189 #endif // DISABLE_TCP_SERVER
1190
1191 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1192 {
1193     oc_mutex_lock(g_mutexObjectList);
1194     if (caglobals.tcp.started)
1195     {
1196         oc_mutex_unlock(g_mutexObjectList);
1197         OIC_LOG(INFO, TAG, "Adapter is started already");
1198         return CA_STATUS_OK;
1199     }
1200
1201     g_threadPool = threadPool;
1202
1203     if (!caglobals.tcp.ipv4tcpenabled)
1204     {
1205         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
1206     }
1207     if (!caglobals.tcp.ipv6tcpenabled)
1208     {
1209         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
1210     }
1211
1212     caglobals.tcp.terminate = false;
1213     if (!caglobals.tcp.svrlist)
1214     {
1215         caglobals.tcp.svrlist = u_arraylist_create();
1216     }
1217
1218 #ifndef DISABLE_TCP_SERVER
1219     if (caglobals.server)
1220     {
1221         CATCPInitializeSocket();
1222     }
1223 #endif
1224
1225 #ifndef __TIZENRT__
1226     // create pipe for fast shutdown
1227     CAInitializePipe(caglobals.tcp.shutdownFds);
1228 #endif
1229     // create pipe for connection event
1230     CAInitializePipe(caglobals.tcp.connectionFds);
1231
1232     CAResult_t res = CA_STATUS_OK;
1233 #ifndef __TIZENRT__
1234     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_taskId);
1235 #else
1236     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1237                                  "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1238 #endif
1239     if (CA_STATUS_OK != res)
1240     {
1241         oc_mutex_unlock(g_mutexObjectList);
1242         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1243         CATCPStopServer();
1244         return res;
1245     }
1246
1247     caglobals.tcp.started = true;
1248     oc_mutex_unlock(g_mutexObjectList);
1249
1250     OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1251     return CA_STATUS_OK;
1252 }
1253
1254 void CATCPStopServer()
1255 {
1256     oc_mutex_lock(g_mutexObjectList);
1257     if (caglobals.tcp.terminate)
1258     {
1259         oc_mutex_unlock(g_mutexObjectList);
1260         OIC_LOG(INFO, TAG, "Adapter is not enabled");
1261         return;
1262     }
1263
1264     // set terminate flag.
1265     caglobals.tcp.terminate = true;
1266
1267     oc_mutex_lock(g_mutexSend);
1268     oc_cond_signal(g_condSend);
1269     oc_mutex_unlock(g_mutexSend);
1270
1271 #ifdef __TIZENRT__
1272     if (caglobals.tcp.started)
1273     {
1274         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1275         caglobals.tcp.started = false;
1276     }
1277 #endif
1278
1279     // close accept socket.
1280 #ifndef __WITH_TLS__
1281     CLOSE_SOCKET(ipv4);
1282     CLOSE_SOCKET(ipv6);
1283 #else
1284     CLOSE_SOCKET(ipv4s);
1285     CLOSE_SOCKET(ipv6s);
1286 #endif
1287
1288     if (caglobals.tcp.connectionFds[1] != OC_INVALID_SOCKET)
1289     {
1290         close(caglobals.tcp.connectionFds[1]);
1291         caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1292     }
1293     if (caglobals.tcp.connectionFds[0] != OC_INVALID_SOCKET)
1294     {
1295         close(caglobals.tcp.connectionFds[0]);
1296         caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1297     }
1298 #ifndef __TIZENRT__
1299     if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1300     {
1301         close(caglobals.tcp.shutdownFds[1]);
1302         caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1303         // receive thread will stop immediately
1304     }
1305     if (caglobals.tcp.started)
1306     {
1307         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1308         caglobals.tcp.started = false;
1309     }
1310     if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1311     {
1312         close(caglobals.tcp.shutdownFds[0]);
1313         caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1314     }
1315 #endif
1316     oc_mutex_unlock(g_mutexObjectList);
1317
1318 #ifndef __TIZENRT__
1319     ca_thread_pool_remove_task(g_threadPool, g_taskId);
1320 #endif
1321
1322     CATCPDisconnectAll();
1323     sleep(1);
1324     OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1325 }
1326
1327 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1328 {
1329     g_packetReceivedCallback = callback;
1330 }
1331
1332 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1333 {
1334     g_connectionCallback = connHandler;
1335 }
1336
1337 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1338 {
1339     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1340
1341     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1342             ((unsigned char *)data)[0] >> 4);
1343
1344     coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1345     if (!pdu)
1346     {
1347         OIC_LOG(ERROR, TAG, "outpdu is null");
1348         OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1349         return 0;
1350     }
1351
1352     int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1353     if (0 >= ret)
1354     {
1355         OIC_LOG(ERROR, TAG, "pdu parse failed");
1356         coap_delete_pdu(pdu);
1357         return 0;
1358     }
1359
1360     size_t payloadLen = 0;
1361     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1362     OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1363               headerSize, pdu->length);
1364     if (pdu->length > headerSize)
1365     {
1366         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1367     }
1368
1369     OICFree(pdu);
1370
1371     return payloadLen;
1372 }
1373
1374 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1375                         size_t dlen, const char *fam)
1376 {
1377     OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1378
1379     // #1. find a session info from list.
1380     CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1381     if (OC_INVALID_SOCKET == sockFd)
1382     {
1383         // if there is no connection info, connect to remote device.
1384         sockFd = CAConnectTCPSession(endpoint);
1385         if (OC_INVALID_SOCKET == sockFd)
1386         {
1387             OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1388             return -1;
1389         }
1390     }
1391
1392     // #2. send data to remote device.
1393     ssize_t remainLen = dlen;
1394     unsigned int sendRetryTime = 1;
1395     do
1396     {
1397 #ifdef MSG_NOSIGNAL
1398         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1399 #else
1400         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1401 #endif
1402         if (-1 == len)
1403         {
1404             g_lastErrorCode = errno;
1405             OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
1406             if (EWOULDBLOCK != g_lastErrorCode && EAGAIN != g_lastErrorCode)
1407             {
1408                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(g_lastErrorCode));
1409                 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1410                                    len, false, strerror(g_lastErrorCode));
1411                 return len;
1412             }
1413
1414             // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds
1415             if (sendRetryTime > 32)
1416             {
1417                 return len;
1418             }
1419
1420             unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND;
1421             OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime);
1422
1423             oc_mutex_lock(g_mutexSend);
1424             oc_cond_wait_for(g_condSend, g_mutexSend, waitTime);
1425             oc_mutex_unlock(g_mutexSend);
1426
1427             oc_mutex_lock(g_mutexObjectList);
1428             if (caglobals.tcp.terminate)
1429             {
1430                 oc_mutex_unlock(g_mutexObjectList);
1431                 return len;
1432             }
1433             oc_mutex_unlock(g_mutexObjectList);
1434
1435             sendRetryTime = (sendRetryTime << 1);
1436
1437             continue;
1438         }
1439         sendRetryTime = 1;
1440         data += len;
1441         remainLen -= len;
1442     } while (remainLen > 0);
1443
1444 #ifndef TB_LOG
1445     (void)fam;
1446 #endif
1447     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1448     CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1449                        dlen, true, NULL);
1450     return dlen;
1451 }
1452
1453 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1454 {
1455     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1456     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1457
1458     if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1459     {
1460         return sendData(endpoint, data, datalen, "ipv6");
1461     }
1462     if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1463     {
1464         return sendData(endpoint, data, datalen, "ipv4");
1465     }
1466
1467     OIC_LOG(ERROR, TAG, "Not supported transport flags");
1468     return -1;
1469 }
1470
1471 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1472 {
1473     VERIFY_NON_NULL(info, TAG, "info is NULL");
1474     VERIFY_NON_NULL(size, TAG, "size is NULL");
1475
1476     return CA_NOT_SUPPORTED;
1477 }
1478
1479 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1480 {
1481     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1482
1483     // #1. create TCP server object
1484     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1485     if (!svritem)
1486     {
1487         OIC_LOG(ERROR, TAG, "Out of memory");
1488         return OC_INVALID_SOCKET;
1489     }
1490     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1491     svritem->sep.endpoint.adapter = endpoint->adapter;
1492     svritem->sep.endpoint.port = endpoint->port;
1493     svritem->sep.endpoint.flags = endpoint->flags;
1494     svritem->sep.endpoint.ifindex = endpoint->ifindex;
1495     svritem->state = CONNECTING;
1496     svritem->isClient = true;
1497
1498     // Allocate message buffer
1499     svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1500     if (!svritem->tlsdata)
1501     {
1502         OIC_LOG(ERROR, TAG, "Out of memory");
1503         OICFree(svritem);
1504         return OC_INVALID_SOCKET;
1505     }
1506
1507     // #2. add TCP connection info to list
1508     oc_mutex_lock(g_mutexObjectList);
1509     if (caglobals.tcp.svrlist)
1510     {
1511         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1512         if (!res)
1513         {
1514             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1515             close(svritem->fd);
1516             OICFree(svritem->tlsdata);
1517             OICFree(svritem);
1518             oc_mutex_unlock(g_mutexObjectList);
1519             return OC_INVALID_SOCKET;
1520         }
1521     }
1522     oc_mutex_unlock(g_mutexObjectList);
1523
1524     // #3. create the socket and connect to TCP server
1525     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1526     if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1527     {
1528         return OC_INVALID_SOCKET;
1529     }
1530
1531     // #4. pass the connection information to CA Common Layer.
1532     if (g_connectionCallback)
1533     {
1534         g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1535     }
1536
1537     return svritem->fd;
1538 }
1539
1540 CAResult_t CADisconnectTCPSession(size_t index)
1541 {
1542     CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1543     if (!removedData)
1544     {
1545         OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1546         return CA_STATUS_OK;
1547     }
1548
1549     // close the socket and remove session info in list.
1550     if (removedData->fd >= 0)
1551     {
1552         shutdown(removedData->fd, SHUT_RDWR);
1553         close(removedData->fd);
1554         removedData->fd = -1;
1555         removedData->state = (CONNECTED == removedData->state) ?
1556                                     DISCONNECTED : removedData->state;
1557
1558         // pass the connection information to CA Common Layer.
1559         if (g_connectionCallback && DISCONNECTED == removedData->state)
1560         {
1561             g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1562         }
1563     }
1564     OICFree(removedData->data);
1565     removedData->data = NULL;
1566
1567     OICFree(removedData->tlsdata);
1568     removedData->tlsdata = NULL;
1569
1570     OICFree(removedData);
1571     removedData = NULL;
1572
1573     OIC_LOG(DEBUG, TAG, "data is removed from session list");
1574
1575 #ifndef DISABLE_TCP_SERVER
1576     if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1577     {
1578         CATCPInitializeSocket();
1579     }
1580 #endif
1581
1582     return CA_STATUS_OK;
1583 }
1584
1585 void CATCPDisconnectAll()
1586 {
1587     OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1588
1589     oc_mutex_lock(g_mutexObjectList);
1590
1591     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1592     for (ssize_t index = length; index > 0; index--)
1593     {
1594         // disconnect session from remote device.
1595         CADisconnectTCPSession(index - 1);
1596     }
1597
1598     u_arraylist_destroy(caglobals.tcp.svrlist);
1599     caglobals.tcp.svrlist = NULL;
1600
1601     oc_mutex_unlock(g_mutexObjectList);
1602
1603 #ifdef __WITH_TLS__
1604     CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1605 #endif
1606
1607     OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1608 }
1609
1610 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1611 {
1612     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1613     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1614
1615     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1616
1617     // get connection info from list
1618     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1619     for (size_t i = 0; i < length; i++)
1620     {
1621         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1622                 caglobals.tcp.svrlist, i);
1623         if (!svritem)
1624         {
1625             continue;
1626         }
1627
1628         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1629                      sizeof(svritem->sep.endpoint.addr))
1630                 && (svritem->sep.endpoint.port == endpoint->port)
1631                 && (svritem->sep.endpoint.flags & endpoint->flags))
1632         {
1633             OIC_LOG(DEBUG, TAG, "Found in session list");
1634             *index = i;
1635             return svritem;
1636         }
1637     }
1638
1639     OIC_LOG(DEBUG, TAG, "Session not found");
1640     return NULL;
1641 }
1642
1643 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1644 {
1645     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1646
1647     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1648
1649     // get connection info from list.
1650     oc_mutex_lock(g_mutexObjectList);
1651     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1652     for (size_t i = 0; i < length; i++)
1653     {
1654         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1655                 caglobals.tcp.svrlist, i);
1656         if (!svritem)
1657         {
1658             continue;
1659         }
1660
1661         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1662                      sizeof(svritem->sep.endpoint.addr))
1663                 && (svritem->sep.endpoint.port == endpoint->port)
1664                 && (svritem->sep.endpoint.flags & endpoint->flags))
1665         {
1666             oc_mutex_unlock(g_mutexObjectList);
1667             OIC_LOG(DEBUG, TAG, "Found in session list");
1668             return svritem->fd;
1669         }
1670     }
1671
1672     oc_mutex_unlock(g_mutexObjectList);
1673     OIC_LOG(DEBUG, TAG, "Session not found");
1674     return OC_INVALID_SOCKET;
1675 }
1676
1677 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1678 {
1679
1680     // check from the last item.
1681     CATCPSessionInfo_t *svritem = NULL;
1682     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1683     for (size_t i = 0; i < length; i++)
1684     {
1685         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1686
1687         if (svritem && svritem->fd == fd)
1688         {
1689             *index = i;
1690             oc_mutex_unlock(g_mutexObjectList);
1691             return svritem;
1692         }
1693     }
1694
1695
1696     return NULL;
1697 }
1698
1699 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1700 {
1701     CATCPSessionInfo_t *svritem = NULL;
1702     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1703     for (size_t i = 0; i < length; i++)
1704     {
1705         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1706
1707         if (svritem && svritem->fd == fd)
1708         {
1709             *index = i;
1710             return svritem;
1711         }
1712     }
1713
1714     return NULL;
1715 }
1716
1717 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1718 {
1719     oc_mutex_lock(g_mutexObjectList);
1720
1721     CAResult_t result = CA_STATUS_OK;
1722     size_t index = 0;
1723     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1724     if (svritem)
1725     {
1726         result = CADisconnectTCPSession(index);
1727         if (CA_STATUS_OK != result)
1728         {
1729             OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1730         }
1731     }
1732
1733     oc_mutex_unlock(g_mutexObjectList);
1734     return result;
1735 }
1736
1737 void CATCPCloseInProgressConnections()
1738 {
1739     OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1740
1741     oc_mutex_lock(g_mutexObjectList);
1742
1743     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1744     for (size_t index = 0; index < length; index++)
1745     {
1746         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1747                 caglobals.tcp.svrlist, index);
1748         if (!svritem)
1749         {
1750             continue;
1751         }
1752
1753         // Session which are connecting state
1754         if (svritem->fd >= 0 && svritem->state == CONNECTING)
1755         {
1756             shutdown(svritem->fd, SHUT_RDWR);
1757             close(svritem->fd);
1758             svritem->fd = -1;
1759             svritem->state = DISCONNECTED;
1760         }
1761     }
1762
1763     oc_mutex_unlock(g_mutexObjectList);
1764
1765     OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1766 }
1767
1768 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1769 {
1770     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1771
1772     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1773             ((unsigned char *)recvBuffer)[0] >> 4);
1774     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1775                                                         transport);
1776     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1777
1778     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1779     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1780     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1781
1782     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1783     return headerLen + optPaylaodLen;
1784 }
1785
1786 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1787 {
1788     g_tcpErrorHandler = errorHandleCallback;
1789 }
1790
1791 CAResult_t CASetKeepAlive(const CAEndpoint_t *endpoint, int time, int cnt, int intvl)
1792 {
1793     OIC_LOG(INFO, TAG, "IN - CATCPSetKeepAlive");
1794
1795     VERIFY_NON_NULL(endpoint, TAG, "endpoint is NULL");
1796
1797     size_t index = 0;
1798     bool revertKeepAliveSetting = false;
1799     CAResult_t result = CA_STATUS_OK;
1800     oc_mutex_lock(g_mutexObjectList);
1801     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1802     if (!svritem)
1803     {
1804         // There is no connection with the given endpoint, so the parameter is considered to be invalid.
1805         result = CA_STATUS_INVALID_PARAM;
1806         goto exit;
1807     }
1808
1809     if (svritem->fd < 0 || svritem->state != CONNECTED)
1810     {
1811         result = CA_DESTINATION_DISCONNECTED;
1812         goto exit;
1813     }
1814
1815     int option = 1;
1816     if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1817     {
1818         OIC_LOG_V(ERROR, TAG, "setsockopt SO_KEEPALIVE failed on socket(%d): %s",
1819             svritem->fd, strerror(errno));
1820         result = CA_SOCKET_OPERATION_FAILED;
1821         goto exit;
1822     }
1823
1824     if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPIDLE, &time, sizeof(time)))
1825     {
1826         OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPIDLE failed on socket(%d): %s",
1827             svritem->fd, strerror(errno));
1828         revertKeepAliveSetting = true;
1829         result = CA_SOCKET_OPERATION_FAILED;
1830         goto exit;
1831     }
1832
1833     if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)))
1834     {
1835         OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPCNT failed on socket(%d): %s",
1836             svritem->fd, strerror(errno));
1837         revertKeepAliveSetting = true;
1838         result = CA_SOCKET_OPERATION_FAILED;
1839         goto exit;
1840     }
1841
1842     if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)))
1843     {
1844         OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPINTVL failed on socket(%d): %s",
1845             svritem->fd, strerror(errno));
1846         revertKeepAliveSetting = true;
1847         result = CA_SOCKET_OPERATION_FAILED;
1848     }
1849
1850 exit:
1851     if (revertKeepAliveSetting)
1852     {
1853         // Unset SO_KEEPALIVE
1854         option = 0;
1855         if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1856         {
1857             OIC_LOG_V(ERROR, TAG, "unset SO_KEEPALIVE failed on socket(%d): %s",
1858                 svritem->fd, strerror(errno));
1859         }
1860     }
1861     oc_mutex_unlock(g_mutexObjectList);
1862     OIC_LOG(INFO, TAG, "OUT - CATCPSetKeepAlive");
1863     return result;
1864 }
1865
1866 CAResult_t CAUnSetKeepAlive(const CAEndpoint_t *endpoint)
1867 {
1868     OIC_LOG(INFO, TAG, "IN - CATCPUnSetKeepAlive");
1869
1870     VERIFY_NON_NULL(endpoint, TAG, "endpoint is NULL");
1871
1872     size_t index = 0;
1873     CAResult_t result = CA_STATUS_OK;
1874     oc_mutex_lock(g_mutexObjectList);
1875     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1876     if (!svritem)
1877     {
1878         // There is no connection with the given endpoint, so the parameter is considered to be invalid.
1879         result = CA_STATUS_INVALID_PARAM;
1880         goto exit;
1881     }
1882
1883     if (svritem->fd < 0 || svritem->state != CONNECTED)
1884     {
1885         result = CA_DESTINATION_DISCONNECTED;
1886         goto exit;
1887     }
1888
1889     int option = 0;
1890     if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1891     {
1892         OIC_LOG_V(ERROR, TAG, "setsockopt SO_KEEPALIVE failed on socket(%d): %s",
1893             svritem->fd, strerror(errno));
1894         result = CA_SOCKET_OPERATION_FAILED;
1895     }
1896
1897 exit:
1898     oc_mutex_unlock(g_mutexObjectList);
1899     OIC_LOG(INFO, TAG, "OUT - CATCPUnSetKeepAlive");
1900     return result;
1901 }
1902
1903 int CAGetLastErrorCode()
1904 {
1905     return g_lastErrorCode;
1906 }