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