Support HighQoS and Cancel Observe in CA and RI
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / camessagehandler_singlethread.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_singlethread.h"
28 #include "caremotehandler.h"
29 #include "cainterfacecontroller_singlethread.h"
30 #include "caprotocolmessage.h"
31 #include "caretransmission_singlethread.h"
32 #include "logger.h"
33 #include "config.h" /* for coap protocol */
34 #include "oic_malloc.h"
35
36 #define TAG "CAMH_ST"
37
38 #define CA_MAX_RT_ARRAY_SIZE    3
39
40 typedef enum
41 {
42     SEND_TYPE_MULTICAST = 0, SEND_TYPE_UNICAST
43 } CASendDataType_t;
44
45 typedef struct
46 {
47     CASendDataType_t type;
48     CARemoteEndpoint_t *remoteEndpoint;
49     CARequestInfo_t *requestInfo;
50     CAResponseInfo_t *responseInfo;
51     CAHeaderOption_t *options;
52     uint8_t numOptions;
53 } CAData_t;
54
55
56 static CARetransmission_t g_retransmissionContext;
57
58 // handler field
59 static CARequestCallback g_requestHandler = NULL;
60 static CAResponseCallback g_responseHandler = NULL;
61
62 static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
63 {
64     OIC_LOG(DEBUG, TAG, "IN");
65     CARemoteEndpoint_t* ep = CACloneRemoteEndpoint(endpoint);
66     if (NULL == ep)
67     {
68         OIC_LOG(ERROR, TAG, "clone failed");
69         return;
70     }
71
72     CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
73
74     if (NULL == resInfo)
75     {
76         OIC_LOG(ERROR, TAG, "calloc failed");
77         CADestroyRemoteEndpointInternal(ep);
78         return;
79     }
80
81     resInfo->result = CA_RETRANSMIT_TIMEOUT;
82     resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
83     resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
84
85     if (g_responseHandler)
86     {
87         g_responseHandler(ep, resInfo);
88     }
89
90     CADestroyRemoteEndpointInternal(ep);
91     OICFree(resInfo);
92
93     OIC_LOG(DEBUG, TAG, "OUT");
94 }
95 static void CAProcessData(const CAData_t *data)
96 {
97     OIC_LOG(DEBUG, TAG, "IN");
98     VERIFY_NON_NULL_VOID(data, TAG, "data");
99     VERIFY_NON_NULL_VOID(data->remoteEndpoint, TAG, "remoteEndpoint");
100
101     CAResult_t res = CA_STATUS_FAILED;
102
103     CASendDataType_t type = data->type;
104
105     if (SEND_TYPE_UNICAST == type)
106     {
107         coap_pdu_t *pdu = NULL;
108
109         if (NULL != data->requestInfo)
110         {
111             OIC_LOG(DEBUG, TAG, "reqInfo avlbl");
112
113             pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
114                                                data->requestInfo->method,
115                                                data->requestInfo->info);
116         }
117         else if (NULL != data->responseInfo)
118         {
119             OIC_LOG(DEBUG, TAG, "resInfo avlbl");
120
121             pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
122                                                data->responseInfo->result,
123                                                data->responseInfo->info);
124         }
125         else
126         {
127             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
128         }
129
130         // interface controller function call.
131         if (NULL != pdu)
132         {
133             CALogPDUInfo(pdu);
134
135             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
136             if (CA_STATUS_OK != res)
137             {
138                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
139                 coap_delete_pdu(pdu);
140                 return;
141             }
142             // for retransmission
143             res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
144                                            pdu->length);
145             if (CA_STATUS_OK != res)
146             {
147                 OIC_LOG_V(INFO, TAG, "retransmissions will not be working: %d", res);
148                 coap_delete_pdu(pdu);
149                 return;
150             }
151
152             coap_delete_pdu(pdu);
153         }
154     }
155     else if (SEND_TYPE_MULTICAST == type)
156     {
157         OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
158
159         CAInfo_t info = { 0 };
160
161         info.options = data->options;
162         info.numOptions = data->numOptions;
163         info.token = data->requestInfo->info.token;
164         info.tokenLength = data->requestInfo->info.tokenLength;
165         info.type = data->requestInfo->info.type;
166         info.messageId = data->requestInfo->info.messageId;
167         info.payload = data->requestInfo->info.payload;
168
169         coap_pdu_t *pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri, CA_GET,
170                                                        info);
171
172         if (NULL != pdu)
173         {
174             CALogPDUInfo(pdu);
175             res = CASendMulticastData(pdu->hdr, pdu->length);
176             if(CA_STATUS_OK != res)
177             {
178                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
179                 coap_delete_pdu(pdu);
180                 return;
181             }
182             coap_delete_pdu(pdu);
183         }
184     }
185
186     OIC_LOG(DEBUG, TAG, "OUT");
187 }
188
189 static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
190 {
191     OIC_LOG(DEBUG, TAG, "IN");
192     VERIFY_NON_NULL_VOID(data, TAG, "data");
193
194     uint32_t code = CA_NOT_FOUND;
195     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
196
197     if (NULL == pdu)
198     {
199         OIC_LOG(ERROR, TAG, "Parse PDU failed");
200         return;
201     }
202
203     char uri[CA_MAX_URI_LENGTH] = { 0, };
204     uint32_t bufLen = sizeof(uri);
205
206     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
207     {
208         CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
209         if (NULL == ReqInfo)
210         {
211             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
212             coap_delete_pdu(pdu);
213             return;
214         }
215
216         CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, bufLen);
217         if (CA_STATUS_OK != res)
218         {
219             OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
220             OICFree(ReqInfo);
221             coap_delete_pdu(pdu);
222             return;
223         }
224
225         if (NULL != ReqInfo->info.options)
226         {
227             for (uint32_t i = 0; i < ReqInfo->info.numOptions; i++)
228             {
229                 OIC_LOG_V(DEBUG, TAG, "optionID: %d", ReqInfo->info.options[i].optionID);
230
231                 OIC_LOG_V(DEBUG, TAG, "list: %s", ReqInfo->info.options[i].optionData);
232             }
233         }
234
235         if (NULL != ReqInfo->info.payload)
236         {
237             OIC_LOG_V(DEBUG, TAG, "Request- payload: %s", ReqInfo->info.payload);
238         }
239
240         OIC_LOG_V(DEBUG, TAG, "code: %d", ReqInfo->method);
241         OIC_LOG(DEBUG, TAG, "token:");
242         OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
243         if (NULL != endpoint)
244         {
245             endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
246             if (NULL == endpoint->resourceUri)
247             {
248                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
249                 OICFree(ReqInfo);
250                 coap_delete_pdu(pdu);
251                 return;
252             }
253             memcpy(endpoint->resourceUri, uri, bufLen);
254             endpoint->resourceUri[bufLen] = '\0';
255             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
256         }
257
258         if (ReqInfo)
259         {
260             if (g_requestHandler)
261             {
262                 g_requestHandler(endpoint, ReqInfo);
263             }
264
265             CADestroyRequestInfoInternal(ReqInfo);
266         }
267     }
268     else
269     {
270         CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
271         if (NULL == ResInfo)
272         {
273             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
274             coap_delete_pdu(pdu);
275             return;
276         }
277
278         CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, bufLen);
279         if (CA_STATUS_OK != res)
280         {
281             OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
282             OICFree(ResInfo);
283             coap_delete_pdu(pdu);
284             return;
285         }
286
287         if (NULL != ResInfo->info.options)
288         {
289             for (uint32_t i = 0; i < ResInfo->info.numOptions; i++)
290             {
291                 OIC_LOG_V(DEBUG, TAG, "optionID: %d", ResInfo->info.options[i].optionID);
292
293                 OIC_LOG_V(DEBUG, TAG, "list: %s", ResInfo->info.options[i].optionData);
294             }
295         }
296
297         if (NULL != ResInfo->info.payload)
298         {
299             OIC_LOG_V(DEBUG, TAG, "payload: %s", ResInfo->info.payload);
300         }
301         OIC_LOG_V(DEBUG, TAG, "code: %d", ResInfo->result);
302
303         if (NULL != endpoint)
304         {
305             endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
306             if (NULL == endpoint->resourceUri)
307             {
308                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
309                 OICFree(ResInfo);
310                 coap_delete_pdu(pdu);
311                 return;
312             }
313             memcpy(endpoint->resourceUri, uri, bufLen);
314             endpoint->resourceUri[bufLen] = '\0';
315             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
316         }
317
318         // for retransmission
319         void *retransmissionPdu = NULL;
320         CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr, pdu->length,
321                                      &retransmissionPdu);
322
323         // get token from saved data in retransmission list
324         if (retransmissionPdu && CA_EMPTY == code)
325         {
326             CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
327                                                &(ResInfo->info));
328             if(res != CA_STATUS_OK)
329             {
330                 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
331                 OICFree(ResInfo->info.token);
332             }
333         }
334         OICFree(retransmissionPdu);
335
336         if (NULL != ResInfo)
337         {
338             if (g_responseHandler)
339             {
340                 g_responseHandler(endpoint, ResInfo);
341             }
342             CADestroyResponseInfoInternal(ResInfo);
343         }
344     }
345
346     if (endpoint && endpoint->resourceUri)
347     {
348         OICFree(endpoint->resourceUri);
349         endpoint->resourceUri = NULL;
350     }
351     if (pdu)
352     {
353         coap_delete_pdu(pdu);
354     }
355     OIC_LOG(DEBUG, TAG, "OUT");
356 }
357
358 static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
359 {
360     OIC_LOG(DEBUG, TAG, "IN");
361
362     OIC_LOG(DEBUG, TAG, "OUT");
363 }
364
365 void CAHandleRequestResponseCallbacks()
366 {
367     CAReadData();
368     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
369 }
370
371 CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request)
372 {
373     OIC_LOG(DEBUG, TAG, "IN");
374
375     VERIFY_NON_NULL(object, TAG, "object");
376     VERIFY_NON_NULL(request, TAG, "request");
377
378     // If max retransmission queue is reached, then don't handle new request
379     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
380     {
381         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
382         return CA_SEND_FAILED;
383     }
384
385     // allocate & initialize
386     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
387     CA_MEMORY_ALLOC_CHECK(data);
388
389     // save data
390     data->type = SEND_TYPE_UNICAST;
391     data->remoteEndpoint = object;
392     data->requestInfo = request;
393     data->responseInfo = NULL;
394
395     CAProcessData(data);
396     OICFree(data);
397     OIC_LOG(DEBUG, TAG, "OUT");
398     return CA_STATUS_OK;
399
400 // memory error label.
401 memory_error_exit:
402     OICFree(data);
403     OIC_LOG(DEBUG, TAG, "OUT");
404     return CA_MEMORY_ALLOC_FAILED;
405 }
406
407 CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
408                                        const CARequestInfo_t *request)
409 {
410     OIC_LOG(DEBUG, TAG, "IN");
411
412     if (NULL == object || NULL == request || NULL == object->resourceUri)
413     {
414         return CA_STATUS_INVALID_PARAM;
415     }
416
417     if ((request->method < CA_GET) || (request->method > CA_DELETE))
418     {
419         OIC_LOG(ERROR, TAG, "Invalid method type!");
420
421         return CA_STATUS_INVALID_PARAM;
422     }
423
424     // allocate & initialize
425     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
426     CA_MEMORY_ALLOC_CHECK(data);
427
428     CAAddress_t addr = {0};
429     CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr,
430                                                                         object->connectivityType);
431
432     // save data
433     data->type = SEND_TYPE_MULTICAST;
434     data->remoteEndpoint = remoteEndpoint;
435     data->requestInfo = request;
436     data->responseInfo = NULL;
437
438     CAProcessData(data);
439     CADestroyRemoteEndpointInternal(remoteEndpoint);
440
441     OICFree(data);
442     OIC_LOG(DEBUG, TAG, "OUT");
443     return CA_STATUS_OK;
444
445 // memory error label.
446 memory_error_exit:
447
448     OICFree(data);
449     OIC_LOG(DEBUG, TAG, "OUT");
450     return CA_MEMORY_ALLOC_FAILED;
451 }
452
453 CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
454                                    const CAResponseInfo_t *response)
455 {
456     OIC_LOG(DEBUG, TAG, "IN");
457     VERIFY_NON_NULL(object, TAG, "object");
458     VERIFY_NON_NULL(response, TAG, "response");
459
460     // allocate & initialize
461     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
462     CA_MEMORY_ALLOC_CHECK(data);
463
464     // save data
465     data->type = SEND_TYPE_UNICAST;
466     data->remoteEndpoint = object;
467     data->requestInfo = NULL;
468     data->responseInfo = response;
469
470     CAProcessData(data);
471
472     OICFree(data);
473     OIC_LOG(DEBUG, TAG, "OUT");
474     return CA_STATUS_OK;
475
476 // memory error label.
477 memory_error_exit:
478     OICFree(data);
479     OIC_LOG(DEBUG, TAG, "OUT");
480
481     return CA_MEMORY_ALLOC_FAILED;
482 }
483
484 CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
485                                       uint8_t tokenLength, const CAHeaderOption_t *options,
486                                       uint8_t numOptions)
487 {
488     OIC_LOG(DEBUG, TAG, "IN");
489     VERIFY_NON_NULL(resourceUri, TAG, "resourceUri is NULL");
490     VERIFY_NON_NULL(token, TAG, "Token is NULL");
491
492     // allocate & initialize
493     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
494     CA_MEMORY_ALLOC_CHECK(data);
495
496     CAAddress_t addr = {0};
497     CARemoteEndpoint_t *remoteEndpoint =
498             CACreateRemoteEndpointInternal(resourceUri, addr,
499                                            CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE);
500
501     // create request info
502     CARequestInfo_t *reqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
503     CA_MEMORY_ALLOC_CHECK(reqInfo);
504
505     // save request info data
506     reqInfo->method = CA_GET;
507     reqInfo->info.type = CA_MSG_NONCONFIRM;
508
509     reqInfo->info.token = token;
510     reqInfo->info.tokenLength = tokenLength;
511
512     // save data
513     data->type = SEND_TYPE_MULTICAST;
514     data->remoteEndpoint = remoteEndpoint;
515     data->requestInfo = reqInfo;
516
517     data->responseInfo = NULL;
518     data->options = NULL;
519     data->numOptions = 0;
520     CAHeaderOption_t *headerOption = NULL;
521     if (NULL != options && numOptions > 0)
522     {
523         // copy data
524         headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * numOptions);
525         CA_MEMORY_ALLOC_CHECK(headerOption);
526         memcpy(headerOption, options, sizeof(CAHeaderOption_t) * numOptions);
527
528         data->options = headerOption;
529         data->numOptions = numOptions;
530     }
531
532     CAProcessData(data);
533
534     CADestroyRemoteEndpoint(remoteEndpoint);
535     OICFree(headerOption);
536     OICFree(data);
537     OICFree(reqInfo);
538     OIC_LOG(DEBUG, TAG, "OUT");
539     return CA_STATUS_OK;
540
541 // memory error label.
542 memory_error_exit:
543
544     CADestroyRemoteEndpointInternal(remoteEndpoint);
545
546     OICFree(reqInfo);
547     OICFree(data);
548     OIC_LOG(DEBUG, TAG, "OUT");
549     return CA_MEMORY_ALLOC_FAILED;
550 }
551
552 void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
553 {
554     OIC_LOG(DEBUG, TAG, "IN");
555     g_requestHandler = ReqHandler;
556     g_responseHandler = RespHandler;
557     OIC_LOG(DEBUG, TAG, "OUT");
558 }
559
560 CAResult_t CAInitializeMessageHandler()
561 {
562     OIC_LOG(DEBUG, TAG, "IN");
563     CASetPacketReceivedCallback(CAReceivedPacketCallback);
564
565     CASetNetworkChangeCallback(CANetworkChangedCallback);
566
567     // retransmission initialize
568     CARetransmissionInitialize(&g_retransmissionContext, CASendUnicastData,
569                                CATimeoutCallback, NULL);
570
571     CAInitializeAdapters();
572     OIC_LOG(DEBUG, TAG, "OUT");
573     return CA_STATUS_OK;
574 }
575
576 void CATerminateMessageHandler()
577 {
578     OIC_LOG(DEBUG, TAG, "IN");
579     // terminate interface adapters by controller
580     CATerminateAdapters();
581
582     // stop retransmission
583     CARetransmissionStop(&g_retransmissionContext);
584     CARetransmissionDestroy(&g_retransmissionContext);
585
586     OIC_LOG(DEBUG, TAG, "OUT");
587 }
588
589 void CALogPDUInfo(coap_pdu_t *pdu)
590 {
591     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
592
593     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
594
595     OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
596
597     OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
598
599     OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", ntohs(pdu->hdr->id));
600
601     OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
602
603     OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->token, pdu->hdr->token_length);
604 }
605