Imported Upstream version 0.9.2
[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.h"
30 #include "caprotocolmessage.h"
31 #include "caretransmission.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     CAEndpoint_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 static CAErrorCallback g_errorHandler = NULL;
62
63 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
64 {
65     OIC_LOG(DEBUG, TAG, "IN");
66     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
67     if (NULL == ep)
68     {
69         OIC_LOG(ERROR, TAG, "clone failed");
70         return;
71     }
72
73     CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
74
75     if (NULL == resInfo)
76     {
77         OIC_LOG(ERROR, TAG, "calloc failed");
78         CAFreeEndpoint(ep);
79         return;
80     }
81
82     resInfo->result = CA_RETRANSMIT_TIMEOUT;
83     resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
84     resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
85
86     if (g_responseHandler)
87     {
88         g_responseHandler(ep, resInfo);
89     }
90
91     CAFreeEndpoint(ep);
92     OICFree(resInfo);
93
94     OIC_LOG(DEBUG, TAG, "OUT");
95 }
96 static void CAProcessData(const CAData_t *data)
97 {
98     OIC_LOG(DEBUG, TAG, "IN");
99     VERIFY_NON_NULL_VOID(data, TAG, "data");
100     VERIFY_NON_NULL_VOID(data->remoteEndpoint, TAG, "remoteEndpoint");
101
102     CAResult_t res = CA_STATUS_FAILED;
103
104     CASendDataType_t type = data->type;
105
106     if (SEND_TYPE_UNICAST == type)
107     {
108         OIC_LOG(DEBUG,TAG,"Unicast Message");
109         coap_pdu_t *pdu = NULL;
110
111         if (NULL != data->requestInfo)
112         {
113             OIC_LOG(DEBUG, TAG, "reqInfo avlbl");
114
115             pdu = (coap_pdu_t *)CAGeneratePDU(data->requestInfo->method, &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->responseInfo->result, &data->responseInfo->info);
122         }
123         else
124         {
125             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
126             return;
127         }
128
129         // interface controller function call.
130         if (NULL != pdu)
131         {
132             CALogPDUInfo(pdu);
133
134             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
135             if (CA_STATUS_OK != res)
136             {
137                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
138                 coap_delete_pdu(pdu);
139                 return;
140             }
141             // for retransmission
142             res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
143                                            pdu->length);
144             if (CA_STATUS_OK != res)
145             {
146                 OIC_LOG_V(INFO, TAG, "retransmissions will not be working: %d", res);
147                 coap_delete_pdu(pdu);
148                 return;
149             }
150
151             coap_delete_pdu(pdu);
152         }
153         else
154         {
155             OIC_LOG(ERROR,TAG, "Failed to Generate Unicast PDU");
156             return;
157         }
158     }
159     else if (SEND_TYPE_MULTICAST == type)
160     {
161         OIC_LOG(DEBUG,TAG,"Multicast Message");
162         if (NULL != data->requestInfo)
163         {
164             OIC_LOG(DEBUG, TAG, "reqInfo avlbl");
165
166             CAInfo_t *info = &data->requestInfo->info;
167
168             info->options = data->options;
169             info->numOptions = data->numOptions;
170
171             coap_pdu_t *pdu = (coap_pdu_t *)CAGeneratePDU(CA_GET, info);
172
173             if (NULL != pdu)
174             {
175                 CALogPDUInfo(pdu);
176                 res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
177                 if(CA_STATUS_OK != res)
178                 {
179                     OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
180                     coap_delete_pdu(pdu);
181                     return;
182                 }
183                 coap_delete_pdu(pdu);
184             }
185             else
186             {
187                 OIC_LOG(ERROR,TAG,"Failed to Generate Multicast PDU");
188             }
189         }
190         else
191         {
192             OIC_LOG(ERROR,TAG,"requestInfo is empty");
193         }
194     }
195
196     OIC_LOG(DEBUG, TAG, "OUT");
197 }
198
199 static void CAReceivedPacketCallback(CAEndpoint_t *endpoint, void *data, uint32_t dataLen)
200 {
201     OIC_LOG(DEBUG, TAG, "IN");
202     VERIFY_NON_NULL_VOID(data, TAG, "data");
203
204     uint32_t code = CA_NOT_FOUND;
205     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
206     OICFree(data);
207     if (NULL == pdu)
208     {
209         OIC_LOG(ERROR, TAG, "Parse PDU failed");
210         return;
211     }
212
213     char uri[CA_MAX_URI_LENGTH] = { };
214
215     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
216     {
217         CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
218         if (NULL == ReqInfo)
219         {
220             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
221             coap_delete_pdu(pdu);
222             return;
223         }
224
225         CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo);
226         if (CA_STATUS_OK != res)
227         {
228             OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
229             OICFree(ReqInfo);
230             coap_delete_pdu(pdu);
231             return;
232         }
233
234         if (NULL != ReqInfo->info.options)
235         {
236             for (uint32_t i = 0; i < ReqInfo->info.numOptions; i++)
237             {
238                 OIC_LOG_V(DEBUG, TAG, "optionID: %d", ReqInfo->info.options[i].optionID);
239
240                 OIC_LOG_V(DEBUG, TAG, "list: %s", ReqInfo->info.options[i].optionData);
241             }
242         }
243
244         if (NULL != ReqInfo->info.payload)
245         {
246             OIC_LOG_V(DEBUG, TAG, "Request- payload: %s", ReqInfo->info.payload);
247         }
248
249         OIC_LOG_V(DEBUG, TAG, "code: %d", ReqInfo->method);
250         OIC_LOG(DEBUG, TAG, "token:");
251         OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
252
253         if (g_requestHandler)
254         {
255             g_requestHandler(endpoint, ReqInfo);
256         }
257
258         CADestroyRequestInfoInternal(ReqInfo);
259     }
260     else
261     {
262         CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
263         if (NULL == ResInfo)
264         {
265             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
266             coap_delete_pdu(pdu);
267             return;
268         }
269
270         CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo);
271         if (CA_STATUS_OK != res)
272         {
273             OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
274             OICFree(ResInfo);
275             coap_delete_pdu(pdu);
276             return;
277         }
278
279         if (NULL != ResInfo->info.options)
280         {
281             for (uint32_t i = 0; i < ResInfo->info.numOptions; i++)
282             {
283                 OIC_LOG_V(DEBUG, TAG, "optionID: %d", ResInfo->info.options[i].optionID);
284
285                 OIC_LOG_V(DEBUG, TAG, "list: %s", ResInfo->info.options[i].optionData);
286             }
287         }
288
289         if (NULL != ResInfo->info.payload)
290         {
291             OIC_LOG_V(DEBUG, TAG, "payload: %s", ResInfo->info.payload);
292         }
293         OIC_LOG_V(DEBUG, TAG, "code: %d", ResInfo->result);
294
295         // for retransmission
296         void *retransmissionPdu = NULL;
297         CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr, pdu->length,
298                                      &retransmissionPdu);
299
300         // get token from saved data in retransmission list
301         if (retransmissionPdu && CA_EMPTY == code)
302         {
303             CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
304                                                &(ResInfo->info));
305             if(CA_STATUS_OK != res)
306             {
307                 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
308                 OICFree(ResInfo->info.token);
309             }
310         }
311         OICFree(retransmissionPdu);
312
313         if (NULL != ResInfo)
314         {
315             if (g_responseHandler)
316             {
317                 g_responseHandler(endpoint, ResInfo);
318             }
319             CADestroyResponseInfoInternal(ResInfo);
320         }
321     }
322
323     if (pdu)
324     {
325         coap_delete_pdu(pdu);
326     }
327     OIC_LOG(DEBUG, TAG, "OUT");
328 }
329
330 static void CANetworkChangedCallback(CAEndpoint_t *info, CANetworkStatus_t status)
331 {
332     OIC_LOG(DEBUG, TAG, "IN");
333
334     OIC_LOG(DEBUG, TAG, "OUT");
335 }
336
337 void CAHandleRequestResponseCallbacks()
338 {
339     CAReadData();
340     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
341 }
342
343 CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInfo_t *request)
344 {
345     OIC_LOG(DEBUG, TAG, "IN");
346
347     VERIFY_NON_NULL(object, TAG, "object");
348     VERIFY_NON_NULL(request, TAG, "request");
349
350     // If max retransmission queue is reached, then don't handle new request
351     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
352     {
353         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
354         return CA_SEND_FAILED;
355     }
356
357     // allocate & initialize
358     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
359     CA_MEMORY_ALLOC_CHECK(data);
360
361     // save data
362     data->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
363     data->remoteEndpoint = object;
364     data->requestInfo = request;
365     data->responseInfo = NULL;
366
367     CAProcessData(data);
368     OICFree(data);
369     OIC_LOG(DEBUG, TAG, "OUT");
370     return CA_STATUS_OK;
371
372 // memory error label.
373 memory_error_exit:
374     OICFree(data);
375     OIC_LOG(DEBUG, TAG, "OUT");
376     return CA_MEMORY_ALLOC_FAILED;
377 }
378
379 CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
380                                    const CAResponseInfo_t *response)
381 {
382     OIC_LOG(DEBUG, TAG, "IN");
383     VERIFY_NON_NULL(object, TAG, "object");
384     VERIFY_NON_NULL(response, TAG, "response");
385
386     // allocate & initialize
387     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
388     CA_MEMORY_ALLOC_CHECK(data);
389
390     // save data
391     data->type = SEND_TYPE_UNICAST;
392     data->remoteEndpoint = object;
393     data->requestInfo = NULL;
394     data->responseInfo = response;
395
396     CAProcessData(data);
397
398     OICFree(data);
399     OIC_LOG(DEBUG, TAG, "OUT");
400     return CA_STATUS_OK;
401
402 // memory error label.
403 memory_error_exit:
404     OICFree(data);
405     OIC_LOG(DEBUG, TAG, "OUT");
406
407     return CA_MEMORY_ALLOC_FAILED;
408 }
409
410 void CASetInterfaceCallbacks(CARequestCallback ReqHandler,
411                 CAResponseCallback RespHandler, CAErrorCallback errorHandler)
412 {
413     OIC_LOG(DEBUG, TAG, "IN");
414     g_requestHandler = ReqHandler;
415     g_responseHandler = RespHandler;
416     g_errorHandler = errorHandler;
417     OIC_LOG(DEBUG, TAG, "OUT");
418 }
419
420 CAResult_t CAInitializeMessageHandler()
421 {
422     OIC_LOG(DEBUG, TAG, "IN");
423     CASetPacketReceivedCallback(CAReceivedPacketCallback);
424
425     CASetNetworkChangeCallback(CANetworkChangedCallback);
426
427     // retransmission initialize
428     CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
429                                CATimeoutCallback, NULL);
430
431     CAInitializeAdapters(NULL);
432     OIC_LOG(DEBUG, TAG, "OUT");
433     return CA_STATUS_OK;
434 }
435
436 void CATerminateMessageHandler()
437 {
438     OIC_LOG(DEBUG, TAG, "IN");
439     // terminate interface adapters by controller
440     CATerminateAdapters();
441
442     // stop retransmission
443     CARetransmissionStop(&g_retransmissionContext);
444     CARetransmissionDestroy(&g_retransmissionContext);
445
446     OIC_LOG(DEBUG, TAG, "OUT");
447 }
448
449 void CALogPDUInfo(coap_pdu_t *pdu)
450 {
451     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
452
453     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
454
455     OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
456
457     OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
458
459     OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", ntohs(pdu->hdr->id));
460
461     OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
462
463     OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->token, pdu->hdr->token_length);
464 }
465