Imported Upstream version 0.9.1
[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 = data->requestInfo->info;
160
161         info.options = data->options;
162         info.numOptions = data->numOptions;
163
164         coap_pdu_t *pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri, CA_GET,
165                                                        info);
166
167         if (NULL != pdu)
168         {
169             CALogPDUInfo(pdu);
170             res = CASendMulticastData(pdu->hdr, pdu->length);
171             if(CA_STATUS_OK != res)
172             {
173                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
174                 coap_delete_pdu(pdu);
175                 return;
176             }
177             coap_delete_pdu(pdu);
178         }
179     }
180
181     OIC_LOG(DEBUG, TAG, "OUT");
182 }
183
184 static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
185 {
186     OIC_LOG(DEBUG, TAG, "IN");
187     VERIFY_NON_NULL_VOID(data, TAG, "data");
188
189     uint32_t code = CA_NOT_FOUND;
190     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
191
192     if (NULL == pdu)
193     {
194         OIC_LOG(ERROR, TAG, "Parse PDU failed");
195         return;
196     }
197
198     char uri[CA_MAX_URI_LENGTH] = { 0, };
199     uint32_t bufLen = sizeof(uri);
200
201     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
202     {
203         CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
204         if (NULL == ReqInfo)
205         {
206             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
207             coap_delete_pdu(pdu);
208             return;
209         }
210
211         CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, bufLen);
212         if (CA_STATUS_OK != res)
213         {
214             OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
215             OICFree(ReqInfo);
216             coap_delete_pdu(pdu);
217             return;
218         }
219
220         if (NULL != ReqInfo->info.options)
221         {
222             for (uint32_t i = 0; i < ReqInfo->info.numOptions; i++)
223             {
224                 OIC_LOG_V(DEBUG, TAG, "optionID: %d", ReqInfo->info.options[i].optionID);
225
226                 OIC_LOG_V(DEBUG, TAG, "list: %s", ReqInfo->info.options[i].optionData);
227             }
228         }
229
230         if (NULL != ReqInfo->info.payload)
231         {
232             OIC_LOG_V(DEBUG, TAG, "Request- payload: %s", ReqInfo->info.payload);
233         }
234
235         OIC_LOG_V(DEBUG, TAG, "code: %d", ReqInfo->method);
236         OIC_LOG(DEBUG, TAG, "token:");
237         OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
238         if (NULL != endpoint)
239         {
240             endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
241             if (NULL == endpoint->resourceUri)
242             {
243                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
244                 OICFree(ReqInfo);
245                 coap_delete_pdu(pdu);
246                 return;
247             }
248             memcpy(endpoint->resourceUri, uri, bufLen);
249             endpoint->resourceUri[bufLen] = '\0';
250             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
251         }
252
253         if (ReqInfo)
254         {
255             if (g_requestHandler)
256             {
257                 g_requestHandler(endpoint, ReqInfo);
258             }
259
260             CADestroyRequestInfoInternal(ReqInfo);
261         }
262     }
263     else
264     {
265         CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
266         if (NULL == ResInfo)
267         {
268             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
269             coap_delete_pdu(pdu);
270             return;
271         }
272
273         CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, bufLen);
274         if (CA_STATUS_OK != res)
275         {
276             OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
277             OICFree(ResInfo);
278             coap_delete_pdu(pdu);
279             return;
280         }
281
282         if (NULL != ResInfo->info.options)
283         {
284             for (uint32_t i = 0; i < ResInfo->info.numOptions; i++)
285             {
286                 OIC_LOG_V(DEBUG, TAG, "optionID: %d", ResInfo->info.options[i].optionID);
287
288                 OIC_LOG_V(DEBUG, TAG, "list: %s", ResInfo->info.options[i].optionData);
289             }
290         }
291
292         if (NULL != ResInfo->info.payload)
293         {
294             OIC_LOG_V(DEBUG, TAG, "payload: %s", ResInfo->info.payload);
295         }
296         OIC_LOG_V(DEBUG, TAG, "code: %d", ResInfo->result);
297
298         if (NULL != endpoint)
299         {
300             endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
301             if (NULL == endpoint->resourceUri)
302             {
303                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
304                 OICFree(ResInfo);
305                 coap_delete_pdu(pdu);
306                 return;
307             }
308             memcpy(endpoint->resourceUri, uri, bufLen);
309             endpoint->resourceUri[bufLen] = '\0';
310             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
311         }
312
313         // for retransmission
314         void *retransmissionPdu = NULL;
315         CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr, pdu->length,
316                                      &retransmissionPdu);
317
318         // get token from saved data in retransmission list
319         if (retransmissionPdu && CA_EMPTY == code)
320         {
321             CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
322                                                &(ResInfo->info));
323             if(CA_STATUS_OK != res)
324             {
325                 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
326                 OICFree(ResInfo->info.token);
327             }
328         }
329         OICFree(retransmissionPdu);
330
331         if (NULL != ResInfo)
332         {
333             if (g_responseHandler)
334             {
335                 g_responseHandler(endpoint, ResInfo);
336             }
337             CADestroyResponseInfoInternal(ResInfo);
338         }
339     }
340
341     if (endpoint && endpoint->resourceUri)
342     {
343         OICFree(endpoint->resourceUri);
344         endpoint->resourceUri = NULL;
345     }
346     if (pdu)
347     {
348         coap_delete_pdu(pdu);
349     }
350     OIC_LOG(DEBUG, TAG, "OUT");
351 }
352
353 static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
354 {
355     OIC_LOG(DEBUG, TAG, "IN");
356
357     OIC_LOG(DEBUG, TAG, "OUT");
358 }
359
360 void CAHandleRequestResponseCallbacks()
361 {
362     CAReadData();
363     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
364 }
365
366 CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request)
367 {
368     OIC_LOG(DEBUG, TAG, "IN");
369
370     VERIFY_NON_NULL(object, TAG, "object");
371     VERIFY_NON_NULL(request, TAG, "request");
372
373     // If max retransmission queue is reached, then don't handle new request
374     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
375     {
376         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
377         return CA_SEND_FAILED;
378     }
379
380     // allocate & initialize
381     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
382     CA_MEMORY_ALLOC_CHECK(data);
383
384     // save data
385     data->type = SEND_TYPE_UNICAST;
386     data->remoteEndpoint = object;
387     data->requestInfo = request;
388     data->responseInfo = NULL;
389
390     CAProcessData(data);
391     OICFree(data);
392     OIC_LOG(DEBUG, TAG, "OUT");
393     return CA_STATUS_OK;
394
395 // memory error label.
396 memory_error_exit:
397     OICFree(data);
398     OIC_LOG(DEBUG, TAG, "OUT");
399     return CA_MEMORY_ALLOC_FAILED;
400 }
401
402 CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
403                                        const CARequestInfo_t *request)
404 {
405     OIC_LOG(DEBUG, TAG, "IN");
406
407     if (NULL == object || NULL == request || NULL == object->resourceUri)
408     {
409         return CA_STATUS_INVALID_PARAM;
410     }
411
412     if ((request->method < CA_GET) || (request->method > CA_DELETE))
413     {
414         OIC_LOG(ERROR, TAG, "Invalid method type!");
415
416         return CA_STATUS_INVALID_PARAM;
417     }
418
419     // allocate & initialize
420     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
421     CA_MEMORY_ALLOC_CHECK(data);
422
423     CAAddress_t addr = {0};
424     CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr,
425                                                                         object->transportType);
426
427     // save data
428     data->type = SEND_TYPE_MULTICAST;
429     data->remoteEndpoint = remoteEndpoint;
430     data->requestInfo = request;
431     data->responseInfo = NULL;
432
433     CAProcessData(data);
434     CADestroyRemoteEndpointInternal(remoteEndpoint);
435
436     OICFree(data);
437     OIC_LOG(DEBUG, TAG, "OUT");
438     return CA_STATUS_OK;
439
440 // memory error label.
441 memory_error_exit:
442
443     OICFree(data);
444     OIC_LOG(DEBUG, TAG, "OUT");
445     return CA_MEMORY_ALLOC_FAILED;
446 }
447
448 CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
449                                    const CAResponseInfo_t *response)
450 {
451     OIC_LOG(DEBUG, TAG, "IN");
452     VERIFY_NON_NULL(object, TAG, "object");
453     VERIFY_NON_NULL(response, TAG, "response");
454
455     // allocate & initialize
456     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
457     CA_MEMORY_ALLOC_CHECK(data);
458
459     // save data
460     data->type = SEND_TYPE_UNICAST;
461     data->remoteEndpoint = object;
462     data->requestInfo = NULL;
463     data->responseInfo = response;
464
465     CAProcessData(data);
466
467     OICFree(data);
468     OIC_LOG(DEBUG, TAG, "OUT");
469     return CA_STATUS_OK;
470
471 // memory error label.
472 memory_error_exit:
473     OICFree(data);
474     OIC_LOG(DEBUG, TAG, "OUT");
475
476     return CA_MEMORY_ALLOC_FAILED;
477 }
478
479 CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
480                                       uint8_t tokenLength, const CAHeaderOption_t *options,
481                                       uint8_t numOptions)
482 {
483     OIC_LOG(DEBUG, TAG, "IN");
484     VERIFY_NON_NULL(resourceUri, TAG, "resourceUri is NULL");
485     VERIFY_NON_NULL(token, TAG, "Token is NULL");
486
487     // allocate & initialize
488     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
489     CA_MEMORY_ALLOC_CHECK(data);
490
491     CAAddress_t addr = {0};
492     CARemoteEndpoint_t *remoteEndpoint =
493             CACreateRemoteEndpointInternal(resourceUri, addr, CA_IPV4 | CA_EDR | CA_LE);
494
495     // create request info
496     CARequestInfo_t *reqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
497     CA_MEMORY_ALLOC_CHECK(reqInfo);
498
499     // save request info data
500     reqInfo->method = CA_GET;
501     reqInfo->info.type = CA_MSG_NONCONFIRM;
502
503     reqInfo->info.token = token;
504     reqInfo->info.tokenLength = tokenLength;
505
506     // save data
507     data->type = SEND_TYPE_MULTICAST;
508     data->remoteEndpoint = remoteEndpoint;
509     data->requestInfo = reqInfo;
510
511     data->responseInfo = NULL;
512     data->options = NULL;
513     data->numOptions = 0;
514     CAHeaderOption_t *headerOption = NULL;
515     if (NULL != options && numOptions > 0)
516     {
517         // copy data
518         headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * numOptions);
519         CA_MEMORY_ALLOC_CHECK(headerOption);
520         memcpy(headerOption, options, sizeof(CAHeaderOption_t) * numOptions);
521
522         data->options = headerOption;
523         data->numOptions = numOptions;
524     }
525
526     CAProcessData(data);
527
528     CADestroyRemoteEndpoint(remoteEndpoint);
529     OICFree(headerOption);
530     OICFree(data);
531     OICFree(reqInfo);
532     OIC_LOG(DEBUG, TAG, "OUT");
533     return CA_STATUS_OK;
534
535 // memory error label.
536 memory_error_exit:
537
538     CADestroyRemoteEndpointInternal(remoteEndpoint);
539
540     OICFree(reqInfo);
541     OICFree(data);
542     OIC_LOG(DEBUG, TAG, "OUT");
543     return CA_MEMORY_ALLOC_FAILED;
544 }
545
546 void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
547 {
548     OIC_LOG(DEBUG, TAG, "IN");
549     g_requestHandler = ReqHandler;
550     g_responseHandler = RespHandler;
551     OIC_LOG(DEBUG, TAG, "OUT");
552 }
553
554 CAResult_t CAInitializeMessageHandler()
555 {
556     OIC_LOG(DEBUG, TAG, "IN");
557     CASetPacketReceivedCallback(CAReceivedPacketCallback);
558
559     CASetNetworkChangeCallback(CANetworkChangedCallback);
560
561     // retransmission initialize
562     CARetransmissionInitialize(&g_retransmissionContext, CASendUnicastData,
563                                CATimeoutCallback, NULL);
564
565     CAInitializeAdapters();
566     OIC_LOG(DEBUG, TAG, "OUT");
567     return CA_STATUS_OK;
568 }
569
570 void CATerminateMessageHandler()
571 {
572     OIC_LOG(DEBUG, TAG, "IN");
573     // terminate interface adapters by controller
574     CATerminateAdapters();
575
576     // stop retransmission
577     CARetransmissionStop(&g_retransmissionContext);
578     CARetransmissionDestroy(&g_retransmissionContext);
579
580     OIC_LOG(DEBUG, TAG, "OUT");
581 }
582
583 void CALogPDUInfo(coap_pdu_t *pdu)
584 {
585     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
586
587     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
588
589     OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
590
591     OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
592
593     OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", ntohs(pdu->hdr->id));
594
595     OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
596
597     OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->token, pdu->hdr->token_length);
598 }
599