Merge branch 'plugin-interface' into master
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / camessagehandler.c
1 /* *****************************************************************
2  *
3  * Copyright 2014 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 <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdint.h>
25
26 #include "cainterface.h"
27 #include "camessagehandler.h"
28 #include "caremotehandler.h"
29 #include "caprotocolmessage.h"
30 #include "logger.h"
31 #include "config.h" /* for coap protocol */
32 #include "oic_malloc.h"
33 #include "canetworkconfigurator.h"
34 #include "caadapterutils.h"
35 #include "cainterfacecontroller.h"
36 #include "caretransmission.h"
37
38 #ifdef WITH_BWT
39 #include "cablockwisetransfer.h"
40 #endif
41
42 #ifndef  SINGLE_THREAD
43 #include "uqueue.h"
44 #include "cathreadpool.h" /* for thread pool */
45 #include "caqueueingthread.h"
46
47 #define SINGLE_HANDLE
48 #define MAX_THREAD_POOL_SIZE    20
49
50 // thread pool handle
51 static ca_thread_pool_t g_threadPoolHandle = NULL;
52
53 // message handler main thread
54 static CAQueueingThread_t g_sendThread;
55 static CAQueueingThread_t g_receiveThread;
56
57 #else
58 #define CA_MAX_RT_ARRAY_SIZE    3
59 #endif  /* SINGLE_THREAD */
60
61 #define TAG "CA_MSG_HNDLR"
62
63 static CARetransmission_t g_retransmissionContext;
64
65 // handler field
66 static CARequestCallback g_requestHandler = NULL;
67 static CAResponseCallback g_responseHandler = NULL;
68 static CAErrorCallback g_errorHandler = NULL;
69
70 static void CAErrorHandler(const CAEndpoint_t *endpoint,
71                            const void *data, uint32_t dataLen,
72                            CAResult_t result);
73
74 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
75                                        const CARemoteId_t *identity,
76                                        const void *data, CADataType_t dataType);
77
78 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
79                             CAResult_t result);
80
81 #ifdef SINGLE_THREAD
82 static void CAProcessReceivedData(CAData_t *data);
83 #endif
84 static void CADestroyData(void *data, uint32_t size);
85 static void CALogPayloadInfo(CAInfo_t *info);
86 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id,
87                                 CAToken_t token, uint8_t tokenLength);
88
89 #ifdef WITH_BWT
90 void CAAddDataToSendThread(CAData_t *data)
91 {
92     VERIFY_NON_NULL_VOID(data, TAG, "data");
93
94     // add thread
95     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
96 }
97
98 void CAAddDataToReceiveThread(CAData_t *data)
99 {
100     VERIFY_NON_NULL_VOID(data, TAG, "data");
101
102     // add thread
103     CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
104 }
105 #endif
106
107 static bool CAIsSelectedNetworkAvailable()
108 {
109     u_arraylist_t *list = CAGetSelectedNetworkList();
110     if (!list || u_arraylist_length(list) == 0)
111     {
112         OIC_LOG(ERROR, TAG, "No selected network");
113         return false;
114     }
115
116     return true;
117 }
118
119 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
120                                        const CARemoteId_t *identity,
121                                        const void *data, CADataType_t dataType)
122 {
123     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
124     CAInfo_t *info = NULL;
125     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
126     if (!cadata)
127     {
128         OIC_LOG(ERROR, TAG, "memory allocation failed");
129         return NULL;
130     }
131
132     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
133     if (!ep)
134     {
135         OIC_LOG(ERROR, TAG, "endpoint clone failed");
136         OICFree(cadata);
137         return NULL;
138     }
139
140     OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
141     CAResult_t result;
142
143     if(CA_RESPONSE_DATA == dataType)
144     {
145         CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
146         if (!resInfo)
147         {
148             OIC_LOG(ERROR, TAG, "memory allocation failed");
149             OICFree(cadata);
150             CAFreeEndpoint(ep);
151             return NULL;
152         }
153
154         result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
155         if (CA_STATUS_OK != result)
156         {
157             OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
158             CAFreeEndpoint(ep);
159             CADestroyResponseInfoInternal(resInfo);
160             OICFree(cadata);
161             return NULL;
162         }
163         cadata->responseInfo = resInfo;
164         info = &resInfo->info;
165         if (identity)
166         {
167             info->identity = *identity;
168         }
169         OIC_LOG(DEBUG, TAG, "Response Info :");
170         CALogPayloadInfo(info);
171     }
172     else if (CA_REQUEST_DATA == dataType)
173     {
174         CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
175         if (!reqInfo)
176         {
177             OIC_LOG(ERROR, TAG, "memory allocation failed");
178             OICFree(cadata);
179             CAFreeEndpoint(ep);
180             return NULL;
181         }
182
183         result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
184         if (CA_STATUS_OK != result)
185         {
186             OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
187             CAFreeEndpoint(ep);
188             CADestroyRequestInfoInternal(reqInfo);
189             OICFree(cadata);
190             return NULL;
191         }
192
193         if (CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId,
194                                 reqInfo->info.token, reqInfo->info.tokenLength))
195         {
196             OIC_LOG(ERROR, TAG, "Second Request with same Token, Drop it");
197             CAFreeEndpoint(ep);
198             CADestroyRequestInfoInternal(reqInfo);
199             OICFree(cadata);
200             return NULL;
201         }
202
203         cadata->requestInfo = reqInfo;
204         info = &reqInfo->info;
205         if (identity)
206         {
207             info->identity = *identity;
208         }
209         OIC_LOG(DEBUG, TAG, "Request Info :");
210         CALogPayloadInfo(info);
211    }
212     else if (CA_ERROR_DATA == dataType)
213     {
214         CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
215         if (!errorInfo)
216         {
217             OIC_LOG(ERROR, TAG, "Memory allocation failed!");
218             OICFree(cadata);
219             CAFreeEndpoint(ep);
220             return NULL;
221         }
222
223         CAResult_t result = CAGetErrorInfoFromPDU(data, endpoint, errorInfo);
224         if (CA_STATUS_OK != result)
225         {
226             OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
227             CAFreeEndpoint(ep);
228             OICFree(errorInfo);
229             OICFree(cadata);
230             return NULL;
231         }
232
233         cadata->errorInfo = errorInfo;
234         info = &errorInfo->info;
235         if (identity)
236         {
237             info->identity = *identity;
238         }
239         OIC_LOG(DEBUG, TAG, "error Info :");
240         CALogPayloadInfo(info);
241     }
242
243     cadata->remoteEndpoint = ep;
244     cadata->dataType = dataType;
245
246     return cadata;
247
248     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
249 }
250
251 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
252 {
253     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
254     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
255
256     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
257     if (!ep)
258     {
259         OIC_LOG(ERROR, TAG, "clone failed");
260         return;
261     }
262
263     CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
264
265     if (!resInfo)
266     {
267         OIC_LOG(ERROR, TAG, "calloc failed");
268         CAFreeEndpoint(ep);
269         return;
270     }
271
272     resInfo->result = CA_RETRANSMIT_TIMEOUT;
273     resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
274     resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
275
276     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info),
277                                        endpoint);
278     if (CA_STATUS_OK != res)
279     {
280         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
281         CADestroyResponseInfoInternal(resInfo);
282         CAFreeEndpoint(ep);
283         return;
284     }
285
286     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
287     if (NULL == cadata)
288     {
289         OIC_LOG(ERROR, TAG, "memory allocation failed !");
290         CAFreeEndpoint(ep);
291         CADestroyResponseInfoInternal(resInfo);
292         return;
293     }
294
295     cadata->type = SEND_TYPE_UNICAST;
296     cadata->remoteEndpoint = ep;
297     cadata->requestInfo = NULL;
298     cadata->responseInfo = resInfo;
299
300 #ifdef SINGLE_THREAD
301     CAProcessReceivedData(cadata);
302 #else
303     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
304 #endif
305 }
306
307 static void CADestroyData(void *data, uint32_t size)
308 {
309     OIC_LOG(DEBUG, TAG, "CADestroyData IN");
310     if ((size_t)size < sizeof(CAData_t))
311     {
312         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
313     }
314     CAData_t *cadata = (CAData_t *) data;
315
316     if (NULL == cadata)
317     {
318         OIC_LOG(ERROR, TAG, "cadata is NULL");
319         return;
320     }
321
322     if (NULL != cadata->remoteEndpoint)
323     {
324         CAFreeEndpoint(cadata->remoteEndpoint);
325     }
326
327     if (NULL != cadata->requestInfo)
328     {
329         CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
330     }
331
332     if (NULL != cadata->responseInfo)
333     {
334         CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
335     }
336
337     if (NULL != cadata->errorInfo)
338     {
339         CADestroyErrorInfoInternal(cadata->errorInfo);
340     }
341
342     OICFree(cadata);
343     OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
344 }
345
346 #ifdef SINGLE_THREAD
347 static void CAProcessReceivedData(CAData_t *data)
348 {
349     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
350     if (!data)
351     {
352         OIC_LOG(ERROR, TAG, "thread data error!!");
353         return;
354     }
355
356     // parse the data and call the callbacks.
357     // #1 parse the data
358     // #2 get endpoint
359     CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
360     if (!rep)
361     {
362         OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
363         return;
364     }
365
366     if (data->requestInfo && g_requestHandler)
367     {
368         g_requestHandler(rep, data->requestInfo);
369     }
370     else if (data->responseInfo && g_responseHandler)
371     {
372         g_responseHandler(rep, data->responseInfo);
373     }
374     else if (data->errorInfo && g_errorHandler)
375     {
376         g_errorHandler(rep, data->errorInfo);
377     }
378
379 #ifdef SINGLE_THREAD
380     CADestroyData(data, sizeof(CAData_t));
381 #endif
382
383     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
384 }
385 #endif
386
387 #ifndef SINGLE_THREAD
388
389 static void CAReceiveThreadProcess(void *threadData)
390 {
391 #ifndef SINGLE_HANDLE
392     CAData_t *data = (CAData_t *) threadData;
393     CAProcessReceivedData(data);
394 #else
395     (void)threadData;
396 #endif
397 }
398 #endif
399
400 static CAResult_t CAProcessSendData(const CAData_t *data)
401 {
402     VERIFY_NON_NULL(data, TAG, "data");
403     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
404
405     CAResult_t res = CA_STATUS_FAILED;
406
407     CASendDataType_t type = data->type;
408
409     coap_pdu_t *pdu = NULL;
410     CAInfo_t *info = NULL;
411     coap_list_t *options = NULL;
412     coap_transport_type transport;
413
414     if (SEND_TYPE_UNICAST == type)
415     {
416         OIC_LOG(DEBUG,TAG,"Unicast message");
417 #ifdef ROUTING_GATEWAY
418         /*
419          * When forwarding a packet, do not attempt retransmission as its the responsibility of
420          * packet originator node
421          */
422         bool skipRetransmission = false;
423 #endif
424
425         if (NULL != data->requestInfo)
426         {
427             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
428
429             info = &data->requestInfo->info;
430 #ifdef ROUTING_GATEWAY
431             skipRetransmission = data->requestInfo->info.skipRetransmission;
432 #endif
433             pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
434                                 &options, &transport);
435         }
436         else if (NULL != data->responseInfo)
437         {
438             OIC_LOG(DEBUG, TAG, "responseInfo is available..");
439
440             info = &data->responseInfo->info;
441 #ifdef ROUTING_GATEWAY
442             skipRetransmission = data->responseInfo->info.skipRetransmission;
443 #endif
444             pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
445                                 &options, &transport);
446         }
447         else
448         {
449             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
450             return CA_STATUS_INVALID_PARAM;
451         }
452
453         // interface controller function call.
454         if (NULL != pdu)
455         {
456 #ifdef WITH_BWT
457             if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
458 #ifdef TCP_ADAPTER
459                     && CA_ADAPTER_TCP != data->remoteEndpoint->adapter
460 #endif
461                     )
462             {
463                 // Blockwise transfer
464                 if (NULL != info)
465                 {
466                     CAResult_t res = CAAddBlockOption(&pdu, info,
467                                                       data->remoteEndpoint,
468                                                       &options);
469                     if (CA_STATUS_OK != res)
470                     {
471                         OIC_LOG(INFO, TAG, "to write block option has failed");
472                         CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
473                         coap_delete_list(options);
474                         coap_delete_pdu(pdu);
475                         return res;
476                     }
477                 }
478             }
479 #endif
480             CALogPDUInfo(pdu, data->remoteEndpoint);
481
482             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
483             if (CA_STATUS_OK != res)
484             {
485                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
486                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
487                 coap_delete_list(options);
488                 coap_delete_pdu(pdu);
489                 return res;
490             }
491
492 #ifdef TCP_ADAPTER
493             if (CA_ADAPTER_TCP == data->remoteEndpoint->adapter)
494             {
495                 OIC_LOG(INFO, TAG, "retransmission will be not worked");
496             }
497             else
498 #endif
499 #ifdef ROUTING_GATEWAY
500             if(!skipRetransmission)
501 #endif
502             {
503                 // for retransmission
504                 res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint,
505                                                pdu->hdr, pdu->length);
506                 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
507                 {
508                     //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
509                     OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
510                     coap_delete_list(options);
511                     coap_delete_pdu(pdu);
512                     return res;
513                 }
514             }
515
516             coap_delete_list(options);
517             coap_delete_pdu(pdu);
518         }
519         else
520         {
521             OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
522             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
523             return CA_SEND_FAILED;
524         }
525     }
526     else if (SEND_TYPE_MULTICAST == type)
527     {
528         OIC_LOG(DEBUG,TAG,"Multicast message");
529         if (NULL != data->requestInfo)
530         {
531             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
532
533             info = &data->requestInfo->info;
534             pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
535
536             if (NULL != pdu)
537             {
538 #ifdef WITH_BWT
539                 if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
540 #ifdef TCP_ADAPTER
541                         && CA_ADAPTER_TCP != data->remoteEndpoint->adapter
542 #endif
543                         )
544                 {
545                     // Blockwise transfer
546                     CAResult_t res = CAAddBlockOption(&pdu, &data->requestInfo->info,
547                                                       data->remoteEndpoint,
548                                                       &options);
549                     if (CA_STATUS_OK != res)
550                     {
551                         OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
552                         CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
553                         coap_delete_list(options);
554                         coap_delete_pdu(pdu);
555                         return res;
556                     }
557                 }
558 #endif
559             }
560             else
561             {
562                 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
563                 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
564                 return CA_SEND_FAILED;
565             }
566         }
567         else if (NULL != data->responseInfo)
568         {
569             OIC_LOG(DEBUG, TAG, "responseInfo is available..");
570
571             info = &data->responseInfo->info;
572             pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
573                                 &options, &transport);
574
575             if (NULL != pdu)
576             {
577 #ifdef WITH_BWT
578                 if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
579 #ifdef TCP_ADAPTER
580                         && CA_ADAPTER_TCP != data->remoteEndpoint->adapter
581 #endif
582                         )
583                 {
584                     // Blockwise transfer
585                     if (NULL != info)
586                     {
587                         CAResult_t res = CAAddBlockOption(&pdu, info,
588                                                           data->remoteEndpoint,
589                                                           &options);
590                         if (CA_STATUS_OK != res)
591                         {
592                             OIC_LOG(INFO, TAG, "to write block option has failed");
593                             CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
594                             coap_delete_list(options);
595                             coap_delete_pdu(pdu);
596                             return res;
597                         }
598                     }
599                 }
600 #endif
601             }
602             else
603             {
604                 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
605                 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
606                 return CA_SEND_FAILED;
607             }
608         }
609         else
610         {
611             OIC_LOG(ERROR, TAG, "request or response info is empty");
612             return CA_SEND_FAILED;
613         }
614
615         CALogPDUInfo(pdu, data->remoteEndpoint);
616
617         OIC_LOG(DEBUG, TAG, "pdu to send :");
618         OIC_LOG_BUFFER(DEBUG, TAG,  pdu->hdr, pdu->length);
619
620         res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
621         if (CA_STATUS_OK != res)
622         {
623             OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
624             CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
625             coap_delete_list(options);
626             coap_delete_pdu(pdu);
627             return res;
628         }
629
630         coap_delete_list(options);
631         coap_delete_pdu(pdu);
632     }
633
634     return CA_STATUS_OK;
635 }
636
637 #ifndef SINGLE_THREAD
638 static void CASendThreadProcess(void *threadData)
639 {
640     CAData_t *data = (CAData_t *) threadData;
641     CAProcessSendData(data);
642 }
643
644 #endif
645
646 /*
647  * If a second message arrives with the same message ID, token and the other address
648  * family, drop it.  Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
649  */
650 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
651                                 CAToken_t token, uint8_t tokenLength)
652 {
653     if (!ep)
654     {
655         return true;
656     }
657     if (ep->adapter != CA_ADAPTER_IP)
658     {
659         return false;
660     }
661     if (!caglobals.ip.dualstack)
662     {
663         return false;
664     }
665
666     if (tokenLength > CA_MAX_TOKEN_LEN)
667     {
668         /*
669          * If token length is more than CA_MAX_TOKEN_LEN,
670          * we compare the first CA_MAX_TOKEN_LEN bytes only.
671          */
672         tokenLength = CA_MAX_TOKEN_LEN;
673     }
674
675     bool ret = false;
676     CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
677
678     for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
679     {
680         CAHistoryItem_t *item = &(history->items[i]);
681         if (id == item->messageId && tokenLength == item->tokenLength
682             && memcmp(item->token, token, tokenLength) == 0)
683         {
684             if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
685             {
686                 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
687                                             familyFlags & CA_IPV6 ? '6' : '4');
688                 ret = true;
689                 break;
690             }
691         }
692     }
693
694     history->items[history->nextIndex].flags = familyFlags;
695     history->items[history->nextIndex].messageId = id;
696     if (token && tokenLength)
697     {
698         memcpy(history->items[history->nextIndex].token, token, tokenLength);
699         history->items[history->nextIndex].tokenLength = tokenLength;
700     }
701
702     if (++history->nextIndex >= HISTORYSIZE)
703     {
704         history->nextIndex = 0;
705     }
706
707     return ret;
708 }
709
710 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
711                                      const void *data, uint32_t dataLen)
712 {
713     VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
714     VERIFY_NON_NULL_VOID(data, TAG, "data");
715
716     OIC_LOG(DEBUG, TAG, "received pdu data :");
717     OIC_LOG_BUFFER(DEBUG, TAG,  data, dataLen);
718
719     uint32_t code = CA_NOT_FOUND;
720     CAData_t *cadata = NULL;
721
722     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
723                                                 &(sep->endpoint));
724     if (NULL == pdu)
725     {
726         OIC_LOG(ERROR, TAG, "Parse PDU failed");
727         return;
728     }
729
730     OIC_LOG_V(DEBUG, TAG, "code = %d", code);
731     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
732     {
733         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
734         if (!cadata)
735         {
736             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
737             coap_delete_pdu(pdu);
738             return;
739         }
740     }
741     else
742     {
743         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
744         if (!cadata)
745         {
746             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
747             coap_delete_pdu(pdu);
748             return;
749         }
750
751 #ifdef TCP_ADAPTER
752         if (CA_ADAPTER_TCP == sep->endpoint.adapter)
753         {
754             OIC_LOG(INFO, TAG, "retransmission is not supported");
755         }
756         else
757 #endif
758         {
759             // for retransmission
760             void *retransmissionPdu = NULL;
761             CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
762                                          pdu->length, &retransmissionPdu);
763
764             // get token from saved data in retransmission list
765             if (retransmissionPdu && CA_EMPTY == code)
766             {
767                 if (cadata->responseInfo)
768                 {
769                     CAInfo_t *info = &cadata->responseInfo->info;
770                     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
771                                                        info, &(sep->endpoint));
772                     if (CA_STATUS_OK != res)
773                     {
774                         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
775                         OICFree(info->token);
776                         info->tokenLength = 0;
777                     }
778                 }
779             }
780             OICFree(retransmissionPdu);
781         }
782     }
783
784     cadata->type = SEND_TYPE_UNICAST;
785
786 #ifdef SINGLE_THREAD
787     CAProcessReceivedData(cadata);
788 #else
789 #ifdef WITH_BWT
790     if (CA_ADAPTER_GATT_BTLE != sep->endpoint.adapter
791 #ifdef TCP_ADAPTER
792             && CA_ADAPTER_TCP != sep->endpoint.adapter
793 #endif
794             )
795     {
796         CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
797         if (CA_NOT_SUPPORTED == res)
798         {
799             OIC_LOG(ERROR, TAG, "this message does not have block option");
800             CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
801         }
802         else
803         {
804             CADestroyData(cadata, sizeof(CAData_t));
805         }
806     }
807     else
808 #endif
809     {
810         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
811     }
812 #endif
813
814     coap_delete_pdu(pdu);
815 }
816
817 static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
818 {
819     (void)info;
820     (void)status;
821     OIC_LOG(DEBUG, TAG, "IN");
822
823     OIC_LOG(DEBUG, TAG, "OUT");
824 }
825
826 void CAHandleRequestResponseCallbacks()
827 {
828 #ifdef SINGLE_THREAD
829     CAReadData();
830     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
831 #else
832 #ifdef SINGLE_HANDLE
833     // parse the data and call the callbacks.
834     // #1 parse the data
835     // #2 get endpoint
836
837     ca_mutex_lock(g_receiveThread.threadMutex);
838
839     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
840
841     ca_mutex_unlock(g_receiveThread.threadMutex);
842
843     if (NULL == item)
844     {
845         return;
846     }
847
848     // get values
849     void *msg = item->msg;
850
851     if (NULL == msg)
852     {
853         return;
854     }
855
856     // get endpoint
857     CAData_t *td = (CAData_t *) msg;
858
859     if (td->requestInfo && g_requestHandler)
860     {
861         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
862         g_requestHandler(td->remoteEndpoint, td->requestInfo);
863     }
864     else if (td->responseInfo && g_responseHandler)
865     {
866         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
867         g_responseHandler(td->remoteEndpoint, td->responseInfo);
868     }
869     else if (td->errorInfo && g_errorHandler)
870     {
871         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
872         g_errorHandler(td->remoteEndpoint, td->errorInfo);
873     }
874
875     CADestroyData(msg, sizeof(CAData_t));
876     OICFree(item);
877
878 #endif /* SINGLE_HANDLE */
879 #endif
880 }
881
882 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
883                                    CADataType_t dataType)
884 {
885     OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
886
887     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
888     if (!cadata)
889     {
890         OIC_LOG(ERROR, TAG, "memory allocation failed");
891         return NULL;
892     }
893
894     if(CA_REQUEST_DATA == dataType)
895     {
896         // clone request info
897         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
898
899         if(!request)
900         {
901             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
902             OICFree(cadata);
903             return NULL;
904         }
905
906         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
907         cadata->requestInfo =  request;
908     }
909     else if(CA_RESPONSE_DATA == dataType)
910     {
911         // clone response info
912         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
913
914         if(!response)
915         {
916             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
917             OICFree(cadata);
918             return NULL;
919         }
920
921         cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
922         cadata->responseInfo = response;
923     }
924     else
925     {
926         OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
927         OICFree(cadata);
928         return NULL;
929     }
930
931     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
932     if (!ep)
933     {
934         OIC_LOG(ERROR, TAG, "endpoint clone failed");
935         CADestroyData(cadata, sizeof(CAData_t));
936         return NULL;
937     }
938
939     cadata->remoteEndpoint = ep;
940     cadata->dataType = dataType;
941     return cadata;
942 }
943
944 CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInfo_t *request)
945 {
946     VERIFY_NON_NULL(object, TAG, "object");
947     VERIFY_NON_NULL(request, TAG, "request");
948
949     if (false == CAIsSelectedNetworkAvailable())
950     {
951         return CA_STATUS_FAILED;
952     }
953
954 #ifdef ARDUINO
955     // If max retransmission queue is reached, then don't handle new request
956     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
957     {
958         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
959         return CA_SEND_FAILED;
960     }
961 #endif /* ARDUINO */
962
963     CAData_t *data = CAPrepareSendData(object, request, CA_REQUEST_DATA);
964     if(!data)
965     {
966         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
967         return CA_MEMORY_ALLOC_FAILED;
968     }
969
970 #ifdef SINGLE_THREAD
971     CAResult_t result = CAProcessSendData(data);
972     if(CA_STATUS_OK != result)
973     {
974         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
975         return result;
976     }
977
978     CADestroyData(data, sizeof(CAData_t));
979 #else
980 #ifdef WITH_BWT
981     if (CA_ADAPTER_GATT_BTLE != object->adapter
982 #ifdef TCP_ADAPTER
983             && CA_ADAPTER_TCP != object->adapter
984 #endif
985             )
986     {
987         // send block data
988         CAResult_t res = CASendBlockWiseData(data);
989         if(CA_NOT_SUPPORTED == res)
990         {
991             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
992             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
993             return CA_STATUS_OK;
994         }
995         else
996         {
997             CADestroyData(data, sizeof(CAData_t));
998         }
999         return res;
1000     }
1001     else
1002 #endif
1003     {
1004         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1005     }
1006 #endif
1007
1008     return CA_STATUS_OK;
1009 }
1010
1011 CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
1012                                    const CAResponseInfo_t *response)
1013 {
1014     VERIFY_NON_NULL(object, TAG, "object");
1015     VERIFY_NON_NULL(response, TAG, "response");
1016
1017     if (false == CAIsSelectedNetworkAvailable())
1018     {
1019         return CA_STATUS_FAILED;
1020     }
1021
1022     CAData_t *data = CAPrepareSendData(object, response, CA_RESPONSE_DATA);
1023     if(!data)
1024     {
1025         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
1026         return CA_MEMORY_ALLOC_FAILED;
1027     }
1028
1029 #ifdef SINGLE_THREAD
1030     CAResult_t result = CAProcessSendData(data);
1031     if(result != CA_STATUS_OK)
1032     {
1033         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
1034         return result;
1035     }
1036
1037     CADestroyData(data, sizeof(CAData_t));
1038 #else
1039 #ifdef WITH_BWT
1040     if (CA_ADAPTER_GATT_BTLE != object->adapter
1041 #ifdef TCP_ADAPTER
1042             && CA_ADAPTER_TCP != object->adapter
1043 #endif
1044             )
1045     {
1046         // send block data
1047         CAResult_t res = CASendBlockWiseData(data);
1048         if(CA_NOT_SUPPORTED == res)
1049         {
1050             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
1051             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1052             return CA_STATUS_OK;
1053         }
1054         else
1055         {
1056             CADestroyData(data, sizeof(CAData_t));
1057         }
1058         return res;
1059     }
1060     else
1061 #endif
1062     {
1063         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1064     }
1065 #endif
1066
1067     return CA_STATUS_OK;
1068 }
1069
1070 CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
1071                                       uint8_t tokenLength, const CAHeaderOption_t *options,
1072                                       uint8_t numOptions)
1073 {
1074     (void)resourceUri;
1075     (void)token;
1076     (void)tokenLength;
1077     (void)options;
1078     (void)numOptions;
1079     return CA_NOT_SUPPORTED;
1080 }
1081
1082 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1083                              CAErrorCallback errorHandler)
1084 {
1085     g_requestHandler = ReqHandler;
1086     g_responseHandler = RespHandler;
1087     g_errorHandler = errorHandler;
1088 }
1089
1090 CAResult_t CAInitializeMessageHandler()
1091 {
1092     CASetPacketReceivedCallback(CAReceivedPacketCallback);
1093
1094     CASetNetworkChangeCallback(CANetworkChangedCallback);
1095     CASetErrorHandleCallback(CAErrorHandler);
1096
1097 #ifndef SINGLE_THREAD
1098     // create thread pool
1099     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1100
1101     if (CA_STATUS_OK != res)
1102     {
1103         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1104         return res;
1105     }
1106
1107     // send thread initialize
1108     if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1109                                                    CASendThreadProcess, CADestroyData))
1110     {
1111         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1112         return CA_STATUS_FAILED;
1113     }
1114
1115     // start send thread
1116     res = CAQueueingThreadStart(&g_sendThread);
1117
1118     if (CA_STATUS_OK != res)
1119     {
1120         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1121         ca_thread_pool_free(g_threadPoolHandle);
1122         g_threadPoolHandle = NULL;
1123         return res;
1124     }
1125
1126     // receive thread initialize
1127     if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1128                                                    CAReceiveThreadProcess, CADestroyData))
1129     {
1130         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1131         return CA_STATUS_FAILED;
1132     }
1133
1134 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1135     // start receive thread
1136     res = CAQueueingThreadStart(&gReceiveThread);
1137
1138     if (res != CA_STATUS_OK)
1139     {
1140         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1141         return res;
1142     }
1143 #endif /* SINGLE_HANDLE */
1144
1145     // retransmission initialize
1146     CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle, CASendUnicastData,
1147                                CATimeoutCallback, NULL);
1148
1149 #ifdef WITH_BWT
1150     // block-wise transfer initialize
1151     CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1152 #endif
1153
1154     // start retransmission
1155     res = CARetransmissionStart(&g_retransmissionContext);
1156
1157     if (CA_STATUS_OK != res)
1158     {
1159         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1160         return res;
1161     }
1162
1163     // initialize interface adapters by controller
1164     CAInitializeAdapters(g_threadPoolHandle);
1165 #else
1166     // retransmission initialize
1167     CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1168                                CATimeoutCallback, NULL);
1169     CAInitializeAdapters();
1170 #endif
1171
1172     return CA_STATUS_OK;
1173 }
1174
1175 void CATerminateMessageHandler()
1176 {
1177 #ifndef SINGLE_THREAD
1178     CATransportAdapter_t connType;
1179     u_arraylist_t *list = CAGetSelectedNetworkList();
1180     uint32_t length = u_arraylist_length(list);
1181
1182     uint32_t i = 0;
1183     for (i = 0; i < length; i++)
1184     {
1185         void* ptrType = u_arraylist_get(list, i);
1186
1187         if (NULL == ptrType)
1188         {
1189             continue;
1190         }
1191
1192         connType = *(CATransportAdapter_t *)ptrType;
1193         CAStopAdapter(connType);
1194     }
1195
1196     // stop retransmission
1197     if (NULL != g_retransmissionContext.threadMutex)
1198     {
1199         CARetransmissionStop(&g_retransmissionContext);
1200     }
1201
1202     // stop thread
1203     // delete thread data
1204     if (NULL != g_sendThread.threadMutex)
1205     {
1206         CAQueueingThreadStop(&g_sendThread);
1207     }
1208
1209     // stop thread
1210     // delete thread data
1211     if (NULL != g_receiveThread.threadMutex)
1212     {
1213 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1214         CAQueueingThreadStop(&gReceiveThread);
1215 #endif /* SINGLE_HANDLE */
1216     }
1217
1218     // destroy thread pool
1219     if (NULL != g_threadPoolHandle)
1220     {
1221         ca_thread_pool_free(g_threadPoolHandle);
1222         g_threadPoolHandle = NULL;
1223     }
1224
1225 #ifdef WITH_BWT
1226     CATerminateBlockWiseTransfer();
1227 #endif
1228     CARetransmissionDestroy(&g_retransmissionContext);
1229     CAQueueingThreadDestroy(&g_sendThread);
1230     CAQueueingThreadDestroy(&g_receiveThread);
1231
1232     // terminate interface adapters by controller
1233     CATerminateAdapters();
1234 #else
1235     // terminate interface adapters by controller
1236     CATerminateAdapters();
1237
1238     // stop retransmission
1239     CARetransmissionStop(&g_retransmissionContext);
1240     CARetransmissionDestroy(&g_retransmissionContext);
1241 #endif
1242 }
1243
1244 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
1245 {
1246     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1247
1248     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1249
1250 #ifdef TCP_ADAPTER
1251     if (CA_ADAPTER_TCP == endpoint->adapter)
1252     {
1253         OIC_LOG(DEBUG, TAG, "pdu header data :");
1254         OIC_LOG_BUFFER(DEBUG, TAG,  pdu->hdr, pdu->length);
1255     }
1256     else
1257 #endif
1258     {
1259         OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
1260
1261         OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
1262
1263         OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1264
1265         OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
1266                        pdu->hdr->coap_hdr_udp_t.token_length);
1267     }
1268 }
1269
1270 static void CALogPayloadInfo(CAInfo_t *info)
1271 {
1272     if(info)
1273     {
1274         if (info->options)
1275         {
1276             for (uint32_t i = 0; i < info->numOptions; i++)
1277             {
1278                 OIC_LOG_V(DEBUG, TAG, "optionID: %d", info->options[i].optionID);
1279
1280                 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1281             }
1282         }
1283
1284         if (info->payload)
1285         {
1286             OIC_LOG_V(DEBUG, TAG, "payload: %p(%u)", info->payload,
1287                       info->payloadSize);
1288         }
1289
1290         if (info->token)
1291         {
1292             OIC_LOG(DEBUG, TAG, "token:");
1293             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1294                            info->tokenLength);
1295         }
1296         OIC_LOG_V(DEBUG, TAG, "msgID: %d", info->messageId);
1297     }
1298     else
1299     {
1300         OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1301     }
1302 }
1303
1304 void CAErrorHandler(const CAEndpoint_t *endpoint,
1305                     const void *data, uint32_t dataLen,
1306                     CAResult_t result)
1307 {
1308     OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1309
1310 #ifndef SINGLE_THREAD
1311
1312     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1313     VERIFY_NON_NULL_VOID(data, TAG, "data");
1314
1315     uint32_t code = CA_NOT_FOUND;
1316     //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1317     //Get PDU data
1318     coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1319     if (NULL == pdu)
1320     {
1321         OIC_LOG(ERROR, TAG, "Parse PDU failed");
1322         return;
1323     }
1324
1325     CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1326     if(!cadata)
1327     {
1328         OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1329         coap_delete_pdu(pdu);
1330         return;
1331     }
1332
1333     cadata->errorInfo->result = result;
1334
1335     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1336     coap_delete_pdu(pdu);
1337 #endif
1338
1339     OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1340     return;
1341 }
1342
1343 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1344 {
1345     OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1346 #ifndef SINGLE_THREAD
1347     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1348     if (!cadata)
1349     {
1350         OIC_LOG(ERROR, TAG, "memory allocation failed");
1351         return;
1352     }
1353
1354     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1355     if (!ep)
1356     {
1357         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1358         OICFree(cadata);
1359         return;
1360     }
1361
1362     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1363     if (!errorInfo)
1364     {
1365         OICFree(cadata);
1366         CAFreeEndpoint(ep);
1367         return;
1368     }
1369
1370     CAResult_t res = CACloneInfo(info, &errorInfo->info);
1371     if (CA_STATUS_OK != res)
1372     {
1373         OICFree(cadata);
1374         OICFree(errorInfo);
1375         CAFreeEndpoint(ep);
1376         return;
1377     }
1378
1379     errorInfo->result = result;
1380     cadata->remoteEndpoint = ep;
1381     cadata->errorInfo = errorInfo;
1382     cadata->dataType = CA_ERROR_DATA;
1383
1384     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1385 #endif
1386     OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1387 }