1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 #include "ocserverrequest.h"
24 #include "ocresourcehandler.h"
25 #include "oic_malloc.h"
26 #include "oic_string.h"
27 #include "ocpayload.h"
28 #include "ocpayloadcbor.h"
31 #include "cainterface.h"
37 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
39 #define TAG PCF("ocserverrequest")
41 static struct OCServerRequest * serverRequestList = NULL;
42 static struct OCServerResponse * serverResponseList = NULL;
44 //-------------------------------------------------------------------------------------------------
46 //-------------------------------------------------------------------------------------------------
49 * Add a server response to the server response list
51 * @param response initialized server response that is created by this function
52 * @param requestHandle - handle of the response
57 static OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle)
59 OCServerResponse * serverResponse = NULL;
61 serverResponse = (OCServerResponse *) OICCalloc(1, sizeof(OCServerResponse));
62 VERIFY_NON_NULL(serverResponse);
64 serverResponse->payload = NULL;
66 serverResponse->requestHandle = requestHandle;
68 *response = serverResponse;
69 OC_LOG(INFO, TAG, PCF("Server Response Added!!"));
70 LL_APPEND (serverResponseList, serverResponse);
76 OICFree(serverResponse);
77 serverResponse = NULL;
80 return OC_STACK_NO_MEMORY;
84 * Delete a server request from the server request list
86 * @param serverRequest - server request to delete
88 static void DeleteServerRequest(OCServerRequest * serverRequest)
92 LL_DELETE(serverRequestList, serverRequest);
93 OICFree(serverRequest->requestToken);
94 OICFree(serverRequest);
96 OC_LOG(INFO, TAG, PCF("Server Request Removed!!"));
101 * Delete a server response from the server response list
103 * @param serverResponse - server response to delete
105 static void DeleteServerResponse(OCServerResponse * serverResponse)
109 LL_DELETE(serverResponseList, serverResponse);
110 OICFree(serverResponse->payload);
111 OICFree(serverResponse);
112 OC_LOG(INFO, TAG, PCF("Server Response Removed!!"));
117 * Find a server response and delete it from the server response list
119 * @param serverResponse - server response to find and delete
121 static void FindAndDeleteServerResponse(OCServerResponse * serverResponse)
123 OCServerResponse* tmp;
126 LL_FOREACH(serverResponseList, tmp)
128 if (serverResponse == tmp)
130 DeleteServerResponse(tmp);
137 //-------------------------------------------------------------------------------------------------
139 //-------------------------------------------------------------------------------------------------
142 * Get a server request from the server request list using the specified token.
144 * @param token - token of server request
145 * @param tokenLength - length of token
150 OCServerRequest * GetServerRequestUsingToken (const CAToken_t token, uint8_t tokenLength)
154 OC_LOG(ERROR, TAG, PCF("Invalid Parameter Token"));
158 OCServerRequest * out = NULL;
159 OC_LOG(INFO, TAG,PCF("Get server request with token"));
160 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
162 OC_LOG(INFO, TAG,PCF("Found token"));
163 LL_FOREACH (serverRequestList, out)
165 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->requestToken, tokenLength);
166 if(memcmp(out->requestToken, token, tokenLength) == 0)
171 OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
176 * Get a server request from the server request list using the specified handle
178 * @param handle - handle of server request
182 OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle)
184 OCServerRequest * out = NULL;
185 LL_FOREACH (serverRequestList, out)
192 OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
197 * Get a server response from the server response list using the specified handle
199 * @param handle - handle of server response
204 OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
206 OCServerResponse * out = NULL;
207 LL_FOREACH (serverResponseList, out)
209 if(out->requestHandle == handle)
214 OC_LOG(ERROR, TAG, PCF("Server Response not found!!"));
218 OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
219 uint8_t delayedResNeeded, uint8_t notificationFlag, OCMethod method,
220 uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
221 OCQualityOfService qos, char * query,
222 OCHeaderOption * rcvdVendorSpecificHeaderOptions,
223 uint8_t * payload, CAToken_t requestToken, uint8_t tokenLength,
224 char * resourceUrl, size_t reqTotalSize, const OCDevAddr *devAddr)
226 OCServerRequest * serverRequest = NULL;
228 serverRequest = (OCServerRequest *) OICCalloc(1, sizeof(OCServerRequest) +
229 (reqTotalSize ? reqTotalSize : 1) - 1);
230 VERIFY_NON_NULL(devAddr);
231 VERIFY_NON_NULL(serverRequest);
233 serverRequest->coapID = coapID;
234 serverRequest->delayedResNeeded = delayedResNeeded;
235 serverRequest->notificationFlag = notificationFlag;
237 serverRequest->method = method;
238 serverRequest->numRcvdVendorSpecificHeaderOptions = numRcvdVendorSpecificHeaderOptions;
239 serverRequest->observationOption = observationOption;
240 serverRequest->observeResult = OC_STACK_ERROR;
241 serverRequest->qos = qos;
242 serverRequest->ehResponseHandler = HandleSingleResponse;
243 serverRequest->numResponses = 1;
247 OICStrcpy(serverRequest->query, sizeof(serverRequest->query), query);
250 if(rcvdVendorSpecificHeaderOptions)
252 memcpy(serverRequest->rcvdVendorSpecificHeaderOptions, rcvdVendorSpecificHeaderOptions,
253 MAX_HEADER_OPTIONS * sizeof(OCHeaderOption));
255 if(payload && reqTotalSize)
257 // destination is at least 1 greater than the source, so a NULL always exists in the
259 memcpy(serverRequest->payload, payload, reqTotalSize);
260 serverRequest->payloadSize = reqTotalSize;
263 serverRequest->requestComplete = 0;
266 // If tokenLength is zero, the return value depends on the
267 // particular library implementation (it may or may not be a null pointer).
270 serverRequest->requestToken = (CAToken_t) OICMalloc(tokenLength);
271 VERIFY_NON_NULL(serverRequest->requestToken);
272 memcpy(serverRequest->requestToken, requestToken, tokenLength);
276 serverRequest->tokenLength = tokenLength;
280 OICStrcpy(serverRequest->resourceUrl, sizeof(serverRequest->resourceUrl),
284 serverRequest->devAddr = *devAddr;
286 *request = serverRequest;
287 OC_LOG(INFO, TAG, PCF("Server Request Added!!"));
288 LL_APPEND (serverRequestList, serverRequest);
294 OICFree(serverRequest);
295 serverRequest = NULL;
298 return OC_STACK_NO_MEMORY;
301 OCStackResult FormOCEntityHandlerRequest(
302 OCEntityHandlerRequest * entityHandlerRequest,
303 OCRequestHandle request,
306 OCResourceHandle resource,
310 uint8_t numVendorOptions,
311 OCHeaderOption * vendorOptions,
312 OCObserveAction observeAction,
313 OCObservationId observeID)
315 if (entityHandlerRequest)
317 entityHandlerRequest->resource = (OCResourceHandle) resource;
318 entityHandlerRequest->requestHandle = request;
319 entityHandlerRequest->method = method;
320 entityHandlerRequest->devAddr = *endpoint;
321 entityHandlerRequest->query = queryBuf;
322 entityHandlerRequest->obsInfo.action = observeAction;
323 entityHandlerRequest->obsInfo.obsId = observeID;
325 if(payload && payloadSize)
327 if(OCParsePayload(&entityHandlerRequest->payload, payload, payloadSize) != OC_STACK_OK)
329 return OC_STACK_ERROR;
334 entityHandlerRequest->payload = NULL;
337 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions;
338 entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions;
343 return OC_STACK_INVALID_PARAM;
347 * Find a server request in the server request list and delete
349 * @param serverRequest - server request to find and delete
351 void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
353 OCServerRequest* tmp;
356 LL_FOREACH(serverRequestList, tmp)
358 if (serverRequest == tmp)
360 DeleteServerRequest(tmp);
367 CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result)
369 CAResponseResult_t caResult = CA_BAD_REQ;
374 caResult = CA_SUCCESS;
377 caResult = CA_BAD_REQ;
379 case OC_EH_RESOURCE_CREATED:
380 caResult = CA_CREATED;
382 case OC_EH_RESOURCE_DELETED:
383 caResult = CA_DELETED;
386 caResult = CA_SUCCESS;
388 case OC_EH_FORBIDDEN:
389 caResult = CA_UNAUTHORIZED_REQ;
391 case OC_EH_RESOURCE_NOT_FOUND:
392 caResult = CA_NOT_FOUND;
395 caResult = CA_BAD_REQ;
403 * Handler function for sending a response from a single resource
405 * @param ehResponse - pointer to the response from the resource
411 OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
413 OCStackResult result = OC_STACK_ERROR;
414 CAEndpoint_t responseEndpoint = {};
415 CAResponseInfo_t responseInfo = {};
416 CAHeaderOption_t* optionsPointer = NULL;
418 if(!ehResponse || !ehResponse->requestHandle)
420 return OC_STACK_ERROR;
423 OCServerRequest *serverRequest = (OCServerRequest *)ehResponse->requestHandle;
425 CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
427 responseInfo.info.resourceUri = serverRequest->resourceUrl;
428 responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult);
430 if(serverRequest->notificationFlag && serverRequest->qos == OC_HIGH_QOS)
432 responseInfo.info.type = CA_MSG_CONFIRM;
434 else if(serverRequest->notificationFlag && serverRequest->qos != OC_HIGH_QOS)
436 responseInfo.info.type = CA_MSG_NONCONFIRM;
438 else if(!serverRequest->notificationFlag && !serverRequest->slowFlag &&
439 serverRequest->qos == OC_HIGH_QOS)
441 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
443 else if(!serverRequest->notificationFlag && serverRequest->slowFlag &&
444 serverRequest->qos == OC_HIGH_QOS)
446 responseInfo.info.type = CA_MSG_CONFIRM;
448 else if(!serverRequest->notificationFlag)
450 responseInfo.info.type = CA_MSG_NONCONFIRM;
453 responseInfo.info.messageId = serverRequest->coapID;
454 responseInfo.info.token = (CAToken_t)OICMalloc(CA_MAX_TOKEN_LEN+1);
455 if (!responseInfo.info.token)
457 OC_LOG(FATAL, TAG, "Memory alloc for token failed");
461 memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
462 responseInfo.info.tokenLength = serverRequest->tokenLength;
464 if(serverRequest->observeResult == OC_STACK_OK)
466 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
470 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions;
473 if(responseInfo.info.numOptions > 0)
475 responseInfo.info.options = (CAHeaderOption_t *)
476 OICCalloc(responseInfo.info.numOptions,
477 sizeof(CAHeaderOption_t));
479 if(!responseInfo.info.options)
481 OC_LOG(FATAL, TAG, PCF("Memory alloc for options failed"));
482 OICFree(responseInfo.info.token);
483 return OC_STACK_NO_MEMORY;
486 optionsPointer = responseInfo.info.options;
488 // TODO: This exposes CoAP specific details. At some point, this should be
489 // re-factored and handled in the CA layer.
490 if(serverRequest->observeResult == OC_STACK_OK)
492 responseInfo.info.options[0].protocolID = CA_COAP_ID;
493 responseInfo.info.options[0].optionID = COAP_OPTION_OBSERVE;
494 responseInfo.info.options[0].optionLength = sizeof(uint32_t);
495 memcpy(responseInfo.info.options[0].optionData,
496 &(serverRequest->observationOption), sizeof(uint32_t));
498 // Point to the next header option before copying vender specific header options
502 if (ehResponse->numSendVendorSpecificHeaderOptions)
504 memcpy(optionsPointer, ehResponse->sendVendorSpecificHeaderOptions,
505 sizeof(OCHeaderOption) *
506 ehResponse->numSendVendorSpecificHeaderOptions);
511 responseInfo.info.options = NULL;
514 // Put the JSON prefix and suffix around the payload
515 if(ehResponse->payload)
517 OCStackResult result;
518 if((result = OCConvertPayload(ehResponse->payload, &responseInfo.info.payload,
519 &responseInfo.info.payloadSize))
522 OC_LOG(ERROR, TAG, "Error converting payload");
526 if(responseInfo.info.payloadSize > MAX_RESPONSE_LENGTH)
528 OICFree(responseInfo.info.payload);
529 OC_LOG(ERROR, TAG, "Payload too long!");
530 return OC_STACK_INVALID_PARAM;
535 responseInfo.info.payload = NULL;
536 responseInfo.info.payloadSize = 0;
540 CATransportAdapter_t CAConnTypes[] = {
542 CA_ADAPTER_GATT_BTLE,
543 CA_ADAPTER_RFCOMM_BTEDR
546 , CA_ADAPTER_REMOTE_ACCESS
550 int size = sizeof(CAConnTypes)/ sizeof(CATransportAdapter_t);
552 CATransportAdapter_t adapter = responseEndpoint.adapter;
553 CAResult_t caResult = CA_STATUS_FAILED;
554 result = OC_STACK_OK;
556 // Default adapter, try to send response out on all adapters.
557 if (adapter == CA_DEFAULT_ADAPTER)
560 (CATransportAdapter_t)(
562 CA_ADAPTER_GATT_BTLE |
563 CA_ADAPTER_RFCOMM_BTEDR
566 | CA_ADAPTER_REMOTE_ACCESS
571 for(int i = 0; i < size; i++ )
573 responseEndpoint.adapter = (CATransportAdapter_t)(adapter & CAConnTypes[i]);
574 if(responseEndpoint.adapter)
576 //The result is set to OC_STACK_OK only if CASendResponse succeeds in sending the
577 //response on all the n/w interfaces else it is set to OC_STACK_ERROR
578 caResult = CASendResponse(&responseEndpoint, &responseInfo);
579 if(caResult != CA_STATUS_OK)
581 OC_LOG_V(ERROR, TAG, "CASendResponse failed with CA error %u", caResult);
582 result = CAResultToOCResult(caResult);
588 OC_LOG(INFO, TAG, PCF("Calling CASendResponse with:"));
589 OC_LOG_V(INFO, TAG, "\tEndpoint address: %s", responseEndpoint.addr);
590 OC_LOG_V(INFO, TAG, "\tEndpoint adapter: %s", responseEndpoint.adapter);
591 OC_LOG_V(INFO, TAG, "\tResponse result : %s", responseInfo.result);
592 OC_LOG_V(INFO, TAG, "\tResponse for uri: %s", responseInfo.info.resourceUri);
594 CAResult_t caResult = CASendResponse(&responseEndpoint, &responseInfo);
595 if(caResult != CA_STATUS_OK)
597 OC_LOG(ERROR, TAG, PCF("CASendResponse failed"));
598 result = CAResultToOCResult(caResult);
602 result = OC_STACK_OK;
606 OICFree(responseInfo.info.payload);
607 OICFree(responseInfo.info.token);
608 OICFree(responseInfo.info.options);
610 FindAndDeleteServerRequest(serverRequest);
615 * Handler function for sending a response from multiple resources, such as a collection.
616 * Aggregates responses from multiple resource until all responses are received then sends the
617 * concatenated response
619 * TODO: Need to add a timeout in case a (remote?) resource does not respond
621 * @param ehResponse - pointer to the response from the resource
626 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
628 OCStackResult stackRet = OC_STACK_ERROR;
629 OCServerRequest * serverRequest = NULL;
630 OCServerResponse * serverResponse = NULL;
632 if(!ehResponse || !ehResponse->payload)
634 OC_LOG(ERROR, TAG, PCF("HandleAggregateResponse invalid parameters"));
635 return OC_STACK_INVALID_PARAM;
638 OC_LOG(INFO, TAG, "Inside HandleAggregateResponse");
640 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
641 serverResponse = GetServerResponseUsingHandle((OCServerRequest *)ehResponse->requestHandle);
647 OC_LOG(INFO, TAG, PCF("This is the first response fragment"));
648 stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle);
649 if (OC_STACK_OK != stackRet)
651 OC_LOG(ERROR, TAG, PCF("Error adding server response"));
654 VERIFY_NON_NULL(serverResponse);
657 if(ehResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
659 stackRet = OC_STACK_ERROR;
660 OC_LOG(ERROR, TAG, PCF("Error adding payload, as it was the incorrect type"));
664 if(!serverResponse->payload)
666 serverResponse->payload = (OCPayload*)OCRepPayloadCreate();
667 serverResponse->payload = ehResponse->payload;
671 OCRepPayloadAppend((OCRepPayload*)serverResponse->payload,
672 (OCRepPayload*)ehResponse->payload);
676 (serverRequest->numResponses)--;
678 if(serverRequest->numResponses == 0)
680 OC_LOG(INFO, TAG, PCF("This is the last response fragment"));
681 ehResponse->payload = serverResponse->payload;
682 stackRet = HandleSingleResponse(ehResponse);
683 //Delete the request and response
684 FindAndDeleteServerRequest(serverRequest);
685 FindAndDeleteServerResponse(serverResponse);
689 OC_LOG(INFO, TAG, PCF("More response fragments to come"));
690 stackRet = OC_STACK_OK;