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 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
32 #include "routingutility.h"
36 #include "cainterface.h"
42 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
44 #define TAG "ocserverrequest"
46 static struct OCServerRequest * serverRequestList = NULL;
47 static struct OCServerResponse * serverResponseList = NULL;
49 //-------------------------------------------------------------------------------------------------
51 //-------------------------------------------------------------------------------------------------
54 * Add a server response to the server response list
56 * @param response initialized server response that is created by this function
57 * @param requestHandle - handle of the response
62 static OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle)
66 return OC_STACK_INVALID_PARAM;
69 OCServerResponse * serverResponse = NULL;
71 serverResponse = (OCServerResponse *) OICCalloc(1, sizeof(OCServerResponse));
72 VERIFY_NON_NULL(serverResponse);
74 serverResponse->payload = NULL;
76 serverResponse->requestHandle = requestHandle;
78 *response = serverResponse;
79 OC_LOG(INFO, TAG, "Server Response Added!!");
80 LL_APPEND (serverResponseList, serverResponse);
86 OICFree(serverResponse);
87 serverResponse = NULL;
90 return OC_STACK_NO_MEMORY;
94 * Delete a server request from the server request list
96 * @param serverRequest - server request to delete
98 static void DeleteServerRequest(OCServerRequest * serverRequest)
102 LL_DELETE(serverRequestList, serverRequest);
103 OICFree(serverRequest->requestToken);
104 OICFree(serverRequest);
105 serverRequest = NULL;
106 OC_LOG(INFO, TAG, "Server Request Removed!!");
111 * Delete a server response from the server response list
113 * @param serverResponse - server response to delete
115 static void DeleteServerResponse(OCServerResponse * serverResponse)
119 LL_DELETE(serverResponseList, serverResponse);
120 OICFree(serverResponse->payload);
121 OICFree(serverResponse);
122 OC_LOG(INFO, TAG, "Server Response Removed!!");
127 * Find a server response and delete it from the server response list
129 * @param serverResponse - server response to find and delete
131 static void FindAndDeleteServerResponse(OCServerResponse * serverResponse)
133 OCServerResponse* tmp;
136 LL_FOREACH(serverResponseList, tmp)
138 if (serverResponse == tmp)
140 DeleteServerResponse(tmp);
148 * Ensure no accept header option is included when sending responses and add routing info to
151 * @param object CA remote endpoint.
152 * @param requestInfo CA request info.
154 * @return ::OC_STACK_OK on success, some other value upon failure.
156 static OCStackResult OCSendResponse(const CAEndpoint_t *object, CAResponseInfo_t *responseInfo)
158 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
159 // Add route info in RM option.
160 OCStackResult rmResult = RMAddInfo(object->routeData, &(responseInfo->info.options),
161 &(responseInfo->info.numOptions));
162 if(OC_STACK_OK != rmResult)
164 OC_LOG(ERROR, TAG, "Add option failed");
169 // Do not include the accept header option
170 responseInfo->info.acceptFormat = CA_FORMAT_UNDEFINED;
171 CAResult_t result = CASendResponse(object, responseInfo);
172 if(CA_STATUS_OK != result)
174 OC_LOG_V(ERROR, TAG, "CASendResponse failed with CA error %u", result);
175 return CAResultToOCResult(result);
180 //-------------------------------------------------------------------------------------------------
182 //-------------------------------------------------------------------------------------------------
185 * Get a server request from the server request list using the specified token.
187 * @param token - token of server request
188 * @param tokenLength - length of token
193 OCServerRequest * GetServerRequestUsingToken (const CAToken_t token, uint8_t tokenLength)
197 OC_LOG(ERROR, TAG, "Invalid Parameter Token");
201 OCServerRequest * out = NULL;
202 OC_LOG(INFO, TAG,"Get server request with token");
203 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
205 OC_LOG(INFO, TAG,"Found token");
206 LL_FOREACH (serverRequestList, out)
208 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->requestToken, tokenLength);
209 if(memcmp(out->requestToken, token, tokenLength) == 0)
214 OC_LOG(ERROR, TAG, "Server Request not found!!");
219 * Get a server request from the server request list using the specified handle
221 * @param handle - handle of server request
225 OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle)
227 OCServerRequest * out = NULL;
228 LL_FOREACH (serverRequestList, out)
235 OC_LOG(ERROR, TAG, "Server Request not found!!");
240 * Get a server response from the server response list using the specified handle
242 * @param handle - handle of server response
247 OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
249 OCServerResponse * out = NULL;
250 LL_FOREACH (serverResponseList, out)
252 if(out->requestHandle == handle)
257 OC_LOG(ERROR, TAG, "Server Response not found!!");
261 OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
262 uint8_t delayedResNeeded, uint8_t notificationFlag, OCMethod method,
263 uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
264 OCQualityOfService qos, char * query,
265 OCHeaderOption * rcvdVendorSpecificHeaderOptions,
266 uint8_t * payload, CAToken_t requestToken, uint8_t tokenLength,
267 char * resourceUrl, size_t reqTotalSize, OCPayloadFormat acceptFormat,
268 const OCDevAddr *devAddr)
272 return OC_STACK_INVALID_PARAM;
275 OCServerRequest * serverRequest = NULL;
277 OC_LOG_V(INFO, TAG, "addserverrequest entry!! [%s:%u]", devAddr->addr, devAddr->port);
279 serverRequest = (OCServerRequest *) OICCalloc(1, sizeof(OCServerRequest) +
280 (reqTotalSize ? reqTotalSize : 1) - 1);
281 VERIFY_NON_NULL(devAddr);
282 VERIFY_NON_NULL(serverRequest);
284 serverRequest->coapID = coapID;
285 serverRequest->delayedResNeeded = delayedResNeeded;
286 serverRequest->notificationFlag = notificationFlag;
288 serverRequest->method = method;
289 serverRequest->numRcvdVendorSpecificHeaderOptions = numRcvdVendorSpecificHeaderOptions;
290 serverRequest->observationOption = observationOption;
291 serverRequest->observeResult = OC_STACK_ERROR;
292 serverRequest->qos = qos;
293 serverRequest->acceptFormat = acceptFormat;
294 serverRequest->ehResponseHandler = HandleSingleResponse;
295 serverRequest->numResponses = 1;
299 OICStrcpy(serverRequest->query, sizeof(serverRequest->query), query);
302 if(rcvdVendorSpecificHeaderOptions)
304 memcpy(serverRequest->rcvdVendorSpecificHeaderOptions, rcvdVendorSpecificHeaderOptions,
305 MAX_HEADER_OPTIONS * sizeof(OCHeaderOption));
307 if(payload && reqTotalSize)
309 // destination is at least 1 greater than the source, so a NULL always exists in the
311 memcpy(serverRequest->payload, payload, reqTotalSize);
312 serverRequest->payloadSize = reqTotalSize;
315 serverRequest->requestComplete = 0;
318 // If tokenLength is zero, the return value depends on the
319 // particular library implementation (it may or may not be a null pointer).
322 serverRequest->requestToken = (CAToken_t) OICMalloc(tokenLength);
323 VERIFY_NON_NULL(serverRequest->requestToken);
324 memcpy(serverRequest->requestToken, requestToken, tokenLength);
328 serverRequest->tokenLength = tokenLength;
332 OICStrcpy(serverRequest->resourceUrl, sizeof(serverRequest->resourceUrl),
336 serverRequest->devAddr = *devAddr;
338 *request = serverRequest;
339 OC_LOG(INFO, TAG, "Server Request Added!!");
340 LL_APPEND (serverRequestList, serverRequest);
346 OICFree(serverRequest);
347 serverRequest = NULL;
350 return OC_STACK_NO_MEMORY;
353 OCStackResult FormOCEntityHandlerRequest(
354 OCEntityHandlerRequest * entityHandlerRequest,
355 OCRequestHandle request,
358 OCResourceHandle resource,
360 OCPayloadType payloadType,
363 uint8_t numVendorOptions,
364 OCHeaderOption * vendorOptions,
365 OCObserveAction observeAction,
366 OCObservationId observeID)
368 if (entityHandlerRequest)
370 entityHandlerRequest->resource = (OCResourceHandle) resource;
371 entityHandlerRequest->requestHandle = request;
372 entityHandlerRequest->method = method;
373 entityHandlerRequest->devAddr = *endpoint;
374 entityHandlerRequest->query = queryBuf;
375 entityHandlerRequest->obsInfo.action = observeAction;
376 entityHandlerRequest->obsInfo.obsId = observeID;
378 if(payload && payloadSize)
380 if(OCParsePayload(&entityHandlerRequest->payload, payloadType,
381 payload, payloadSize) != OC_STACK_OK)
383 return OC_STACK_ERROR;
388 entityHandlerRequest->payload = NULL;
391 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions;
392 entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions;
397 return OC_STACK_INVALID_PARAM;
401 * Find a server request in the server request list and delete
403 * @param serverRequest - server request to find and delete
405 void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
407 OCServerRequest* tmp;
410 LL_FOREACH(serverRequestList, tmp)
412 if (serverRequest == tmp)
414 DeleteServerRequest(tmp);
421 CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result, OCMethod method)
423 CAResponseResult_t caResult;
432 // This Response Code is like HTTP 204 "No Content" but only used in
433 // response to POST and PUT requests.
434 caResult = CA_CHANGED;
437 // This Response Code is like HTTP 200 "OK" but only used in response to
439 caResult = CA_CONTENT;
442 // This should not happen but,
443 // give it a value just in case but output an error
444 caResult = CA_CONTENT;
445 OC_LOG_V(ERROR, TAG, "Unexpected OC_EH_OK return code for method [d].", method);
449 caResult = CA_BAD_REQ;
451 case OC_EH_RESOURCE_CREATED:
452 caResult = CA_CREATED;
454 case OC_EH_RESOURCE_DELETED:
455 caResult = CA_DELETED;
458 caResult = CA_CONTENT;
460 case OC_EH_FORBIDDEN:
461 caResult = CA_UNAUTHORIZED_REQ;
463 case OC_EH_RESOURCE_NOT_FOUND:
464 caResult = CA_NOT_FOUND;
467 caResult = CA_BAD_REQ;
475 * Handler function for sending a response from a single resource
477 * @param ehResponse - pointer to the response from the resource
482 OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
484 OCStackResult result = OC_STACK_ERROR;
485 CAEndpoint_t responseEndpoint = {.adapter = CA_DEFAULT_ADAPTER};
486 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
487 CAHeaderOption_t* optionsPointer = NULL;
489 if(!ehResponse || !ehResponse->requestHandle)
491 return OC_STACK_ERROR;
494 OCServerRequest *serverRequest = (OCServerRequest *)ehResponse->requestHandle;
496 CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
498 responseInfo.info.resourceUri = serverRequest->resourceUrl;
499 responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult, serverRequest->method);
501 if(serverRequest->notificationFlag && serverRequest->qos == OC_HIGH_QOS)
503 responseInfo.info.type = CA_MSG_CONFIRM;
505 else if(serverRequest->notificationFlag && serverRequest->qos != OC_HIGH_QOS)
507 responseInfo.info.type = CA_MSG_NONCONFIRM;
509 else if(!serverRequest->notificationFlag && !serverRequest->slowFlag &&
510 serverRequest->qos == OC_HIGH_QOS)
512 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
514 else if(!serverRequest->notificationFlag && serverRequest->slowFlag &&
515 serverRequest->qos == OC_HIGH_QOS)
517 responseInfo.info.type = CA_MSG_CONFIRM;
519 else if(!serverRequest->notificationFlag)
521 responseInfo.info.type = CA_MSG_NONCONFIRM;
525 OC_LOG(ERROR, TAG, "default responseInfo type is NON");
526 responseInfo.info.type = CA_MSG_NONCONFIRM;
529 char rspToken[CA_MAX_TOKEN_LEN + 1] = {};
530 responseInfo.info.messageId = serverRequest->coapID;
531 responseInfo.info.token = (CAToken_t)rspToken;
533 memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
534 responseInfo.info.tokenLength = serverRequest->tokenLength;
536 if(serverRequest->observeResult == OC_STACK_OK)
538 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
542 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions;
545 if(responseInfo.info.numOptions > 0)
547 responseInfo.info.options = (CAHeaderOption_t *)
548 OICCalloc(responseInfo.info.numOptions,
549 sizeof(CAHeaderOption_t));
551 if(!responseInfo.info.options)
553 OC_LOG(FATAL, TAG, "Memory alloc for options failed");
554 return OC_STACK_NO_MEMORY;
557 optionsPointer = responseInfo.info.options;
559 // TODO: This exposes CoAP specific details. At some point, this should be
560 // re-factored and handled in the CA layer.
561 if(serverRequest->observeResult == OC_STACK_OK)
563 responseInfo.info.options[0].protocolID = CA_COAP_ID;
564 responseInfo.info.options[0].optionID = COAP_OPTION_OBSERVE;
565 responseInfo.info.options[0].optionLength = sizeof(uint32_t);
566 uint8_t* observationData = (uint8_t*)responseInfo.info.options[0].optionData;
567 uint32_t observationOption= serverRequest->observationOption;
569 for (size_t i=sizeof(uint32_t); i; --i)
571 observationData[i-1] = observationOption & 0xFF;
572 observationOption >>=8;
575 // Point to the next header option before copying vender specific header options
579 if (ehResponse->numSendVendorSpecificHeaderOptions)
581 memcpy(optionsPointer, ehResponse->sendVendorSpecificHeaderOptions,
582 sizeof(OCHeaderOption) *
583 ehResponse->numSendVendorSpecificHeaderOptions);
588 responseInfo.info.options = NULL;
591 responseInfo.isMulticast = false;
592 responseInfo.info.payload = NULL;
593 responseInfo.info.payloadSize = 0;
594 responseInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
596 // Put the JSON prefix and suffix around the payload
597 if(ehResponse->payload)
599 if (ehResponse->payload->type == PAYLOAD_TYPE_PRESENCE)
601 responseInfo.isMulticast = true;
605 responseInfo.isMulticast = false;
608 switch(serverRequest->acceptFormat)
610 case OC_FORMAT_UNDEFINED:
611 // No preference set by the client, so default to CBOR then
613 if((result = OCConvertPayload(ehResponse->payload, &responseInfo.info.payload,
614 &responseInfo.info.payloadSize))
617 OC_LOG(ERROR, TAG, "Error converting payload");
618 OICFree(responseInfo.info.options);
621 responseInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
624 responseInfo.result = CA_NOT_ACCEPTABLE;
629 CATransportAdapter_t CAConnTypes[] = {
631 CA_ADAPTER_GATT_BTLE,
632 CA_ADAPTER_RFCOMM_BTEDR
635 , CA_ADAPTER_REMOTE_ACCESS
643 size_t size = sizeof(CAConnTypes)/ sizeof(CATransportAdapter_t);
645 CATransportAdapter_t adapter = responseEndpoint.adapter;
646 // Default adapter, try to send response out on all adapters.
647 if (adapter == CA_DEFAULT_ADAPTER)
650 (CATransportAdapter_t)(
652 CA_ADAPTER_GATT_BTLE |
653 CA_ADAPTER_RFCOMM_BTEDR
656 | CA_ADAPTER_REMOTE_ACCESS
665 result = OC_STACK_OK;
666 OCStackResult tempResult = OC_STACK_OK;
668 for(size_t i = 0; i < size; i++ )
670 responseEndpoint.adapter = (CATransportAdapter_t)(adapter & CAConnTypes[i]);
671 if(responseEndpoint.adapter)
673 //The result is set to OC_STACK_OK only if OCSendResponse succeeds in sending the
674 //response on all the n/w interfaces else it is set to OC_STACK_ERROR
675 tempResult = OCSendResponse(&responseEndpoint, &responseInfo);
677 if(OC_STACK_OK != tempResult)
684 OC_LOG(INFO, TAG, "Calling OCSendResponse with:");
685 OC_LOG_V(INFO, TAG, "\tEndpoint address: %s", responseEndpoint.addr);
686 OC_LOG_V(INFO, TAG, "\tEndpoint adapter: %s", responseEndpoint.adapter);
687 OC_LOG_V(INFO, TAG, "\tResponse result : %s", responseInfo.result);
688 OC_LOG_V(INFO, TAG, "\tResponse for uri: %s", responseInfo.info.resourceUri);
690 result = OCSendResponse(&responseEndpoint, &responseInfo);
693 OICFree(responseInfo.info.payload);
694 OICFree(responseInfo.info.options);
696 FindAndDeleteServerRequest(serverRequest);
701 * Handler function for sending a response from multiple resources, such as a collection.
702 * Aggregates responses from multiple resource until all responses are received then sends the
703 * concatenated response
705 * TODO: Need to add a timeout in case a (remote?) resource does not respond
707 * @param ehResponse - pointer to the response from the resource
712 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
714 if(!ehResponse || !ehResponse->payload)
716 OC_LOG(ERROR, TAG, "HandleAggregateResponse invalid parameters");
717 return OC_STACK_INVALID_PARAM;
720 OC_LOG(INFO, TAG, "Inside HandleAggregateResponse");
722 OCServerRequest *serverRequest = GetServerRequestUsingHandle((OCServerRequest *)
723 ehResponse->requestHandle);
724 OCServerResponse *serverResponse = GetServerResponseUsingHandle((OCServerRequest *)
725 ehResponse->requestHandle);
727 OCStackResult stackRet = OC_STACK_ERROR;
732 OC_LOG(INFO, TAG, "This is the first response fragment");
733 stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle);
734 if (OC_STACK_OK != stackRet)
736 OC_LOG(ERROR, TAG, "Error adding server response");
739 VERIFY_NON_NULL(serverResponse);
742 if(ehResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
744 stackRet = OC_STACK_ERROR;
745 OC_LOG(ERROR, TAG, "Error adding payload, as it was the incorrect type");
749 if(!serverResponse->payload)
751 serverResponse->payload = ehResponse->payload;
755 OCRepPayloadAppend((OCRepPayload*)serverResponse->payload,
756 (OCRepPayload*)ehResponse->payload);
760 (serverRequest->numResponses)--;
762 if(serverRequest->numResponses == 0)
764 OC_LOG(INFO, TAG, "This is the last response fragment");
765 ehResponse->payload = serverResponse->payload;
766 stackRet = HandleSingleResponse(ehResponse);
767 //Delete the request and response
768 FindAndDeleteServerRequest(serverRequest);
769 FindAndDeleteServerResponse(serverResponse);
773 OC_LOG(INFO, TAG, "More response fragments to come");
774 stackRet = OC_STACK_OK;