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 "ocobserve.h"
26 #include "oic_malloc.h"
27 #include "oic_string.h"
28 #include "ocpayload.h"
29 #include "ocpayloadcbor.h"
32 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
33 #include "routingutility.h"
37 #include "cainterface.h"
39 #include <coap/utlist.h>
43 #define VERIFY_NON_NULL(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
45 #define TAG "OIC_RI_SERVERREQUEST"
47 static struct OCServerRequest * serverRequestList = NULL;
48 static struct OCServerResponse * serverResponseList = NULL;
50 //-------------------------------------------------------------------------------------------------
52 //-------------------------------------------------------------------------------------------------
55 * Add a server response to the server response list
57 * @param response initialized server response that is created by this function
58 * @param requestHandle - handle of the response
63 static OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle)
67 return OC_STACK_INVALID_PARAM;
70 OCServerResponse * serverResponse = NULL;
72 serverResponse = (OCServerResponse *) OICCalloc(1, sizeof(OCServerResponse));
73 VERIFY_NON_NULL(serverResponse);
75 serverResponse->payload = NULL;
77 serverResponse->requestHandle = requestHandle;
79 *response = serverResponse;
80 OIC_LOG(INFO, TAG, "Server Response Added!!");
81 LL_APPEND (serverResponseList, serverResponse);
87 OICFree(serverResponse);
88 serverResponse = NULL;
91 return OC_STACK_NO_MEMORY;
95 * Delete a server request from the server request list
97 * @param serverRequest - server request to delete
99 static void DeleteServerRequest(OCServerRequest * serverRequest)
103 LL_DELETE(serverRequestList, serverRequest);
104 OICFree(serverRequest->requestToken);
105 OICFree(serverRequest);
106 serverRequest = NULL;
107 OIC_LOG(INFO, TAG, "Server Request Removed!!");
112 * Delete a server response from the server response list
114 * @param serverResponse - server response to delete
116 static void DeleteServerResponse(OCServerResponse * serverResponse)
120 LL_DELETE(serverResponseList, serverResponse);
121 OCPayloadDestroy(serverResponse->payload);
122 OICFree(serverResponse);
123 OIC_LOG(INFO, TAG, "Server Response Removed!!");
128 * Find a server response and delete it from the server response list
130 * @param serverResponse - server response to find and delete
132 static void FindAndDeleteServerResponse(OCServerResponse * serverResponse)
134 OCServerResponse* tmp;
137 LL_FOREACH(serverResponseList, tmp)
139 if (serverResponse == tmp)
141 DeleteServerResponse(tmp);
149 * Ensure no accept header option is included when sending responses and add routing info to
152 * @param object CA remote endpoint.
153 * @param requestInfo CA request info.
155 * @return ::OC_STACK_OK on success, some other value upon failure.
157 static OCStackResult OCSendResponse(const CAEndpoint_t *object, CAResponseInfo_t *responseInfo)
159 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
160 // Add route info in RM option.
161 OCStackResult rmResult = RMAddInfo(object->routeData, responseInfo, false, NULL);
162 if(OC_STACK_OK != rmResult)
164 OIC_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 OIC_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 OIC_LOG(ERROR, TAG, "Invalid Parameter Token");
201 OCServerRequest * out = NULL;
202 OIC_LOG(INFO, TAG,"Get server request with token");
203 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
205 OIC_LOG(INFO, TAG,"Found token");
206 LL_FOREACH (serverRequestList, out)
208 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->requestToken, tokenLength);
209 if(memcmp(out->requestToken, token, tokenLength) == 0)
214 OIC_LOG(INFO, 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 OCRequestHandle handle)
227 OCServerRequest * out = NULL;
228 LL_FOREACH (serverRequestList, out)
230 if(out->requestId == handle)
235 OIC_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 OCRequestHandle handle)
249 OCServerResponse * out = NULL;
250 LL_FOREACH (serverResponseList, out)
252 if(out->requestHandle == handle)
257 OIC_LOG(INFO, 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 OIC_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;
296 serverRequest->requestId = OCGetRandom();
300 OICStrcpy(serverRequest->query, sizeof(serverRequest->query), query);
303 if(rcvdVendorSpecificHeaderOptions)
305 memcpy(serverRequest->rcvdVendorSpecificHeaderOptions, rcvdVendorSpecificHeaderOptions,
306 MAX_HEADER_OPTIONS * sizeof(OCHeaderOption));
308 if(payload && reqTotalSize)
310 // destination is at least 1 greater than the source, so a NULL always exists in the
312 memcpy(serverRequest->payload, payload, reqTotalSize);
313 serverRequest->payloadSize = reqTotalSize;
316 serverRequest->requestComplete = 0;
319 // If tokenLength is zero, the return value depends on the
320 // particular library implementation (it may or may not be a null pointer).
323 serverRequest->requestToken = (CAToken_t) OICMalloc(tokenLength);
324 VERIFY_NON_NULL(serverRequest->requestToken);
325 memcpy(serverRequest->requestToken, requestToken, tokenLength);
328 serverRequest->tokenLength = tokenLength;
332 OICStrcpy(serverRequest->resourceUrl, sizeof(serverRequest->resourceUrl),
336 serverRequest->devAddr = *devAddr;
338 *request = serverRequest;
339 OIC_LOG(INFO, TAG, "Server Request Added!!");
340 LL_APPEND (serverRequestList, serverRequest);
346 OICFree(serverRequest->requestToken);
347 OICFree(serverRequest);
348 serverRequest = NULL;
351 return OC_STACK_NO_MEMORY;
354 OCStackResult FormOCEntityHandlerRequest(
355 OCEntityHandlerRequest * entityHandlerRequest,
356 OCRequestHandle request,
359 OCResourceHandle resource,
361 OCPayloadType payloadType,
364 uint8_t numVendorOptions,
365 OCHeaderOption * vendorOptions,
366 OCObserveAction observeAction,
367 OCObservationId observeID,
370 if (entityHandlerRequest)
372 entityHandlerRequest->resource = (OCResourceHandle) resource;
373 entityHandlerRequest->requestHandle = request;
374 entityHandlerRequest->method = method;
375 entityHandlerRequest->devAddr = *endpoint;
376 entityHandlerRequest->query = queryBuf;
377 entityHandlerRequest->obsInfo.action = observeAction;
378 entityHandlerRequest->obsInfo.obsId = observeID;
379 entityHandlerRequest->messageID = messageID;
381 if(payload && payloadSize)
383 if(OCParsePayload(&entityHandlerRequest->payload, payloadType,
384 payload, payloadSize) != OC_STACK_OK)
386 return OC_STACK_ERROR;
391 entityHandlerRequest->payload = NULL;
394 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions;
395 entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions;
400 return OC_STACK_INVALID_PARAM;
404 * Find a server request in the server request list and delete
406 * @param serverRequest - server request to find and delete
408 void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
410 OCServerRequest* tmp;
413 LL_FOREACH(serverRequestList, tmp)
415 if (serverRequest == tmp)
417 DeleteServerRequest(tmp);
424 CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result, OCMethod method)
426 CAResponseResult_t caResult = CA_BAD_REQ;
430 // Successful Client Request
431 case OC_EH_RESOURCE_CREATED: // 2.01
432 if (method == OC_REST_POST || method == OC_REST_PUT)
434 caResult = CA_CREATED;
437 case OC_EH_RESOURCE_DELETED: // 2.02
438 if (method == OC_REST_POST || method == OC_REST_DELETE)
440 caResult = CA_DELETED;
443 case OC_EH_SLOW: // 2.05
444 caResult = CA_CONTENT;
447 case OC_EH_CHANGED: // 2.04
448 case OC_EH_CONTENT: // 2.05
449 if (method == OC_REST_POST || method == OC_REST_PUT)
451 caResult = CA_CHANGED;
453 else if (method == OC_REST_GET)
455 caResult = CA_CONTENT;
458 case OC_EH_VALID: // 2.03
461 // Unsuccessful Client Request
462 case OC_EH_UNAUTHORIZED_REQ: // 4.01
463 caResult = CA_UNAUTHORIZED_REQ;
465 case OC_EH_BAD_OPT: // 4.02
466 caResult = CA_BAD_OPT;
468 case OC_EH_FORBIDDEN: // 4.03
469 caResult = CA_FORBIDDEN_REQ;
471 case OC_EH_RESOURCE_NOT_FOUND: // 4.04
472 caResult = CA_NOT_FOUND;
474 case OC_EH_METHOD_NOT_ALLOWED: // 4.05
475 caResult = CA_METHOD_NOT_ALLOWED;
477 case OC_EH_NOT_ACCEPTABLE: // 4.06
478 caResult = CA_NOT_ACCEPTABLE;
480 case OC_EH_INTERNAL_SERVER_ERROR: // 5.00
481 caResult = CA_INTERNAL_SERVER_ERROR;
483 case OC_EH_NOT_IMPLEMENTED: // 5.01
484 caResult = CA_NOT_IMPLEMENTED;
486 case OC_EH_BAD_GATEWAY: // 5.02
487 caResult = CA_BAD_GATEWAY;
489 case OC_EH_SERVICE_UNAVAILABLE: // 5.03
490 caResult = CA_SERVICE_UNAVAILABLE;
492 case OC_EH_RETRANSMIT_TIMEOUT: // 5.04
493 caResult = CA_RETRANSMIT_TIMEOUT;
495 case OC_EH_PROXY_NOT_SUPPORTED: // 5.05
496 caResult = CA_PROXY_NOT_SUPPORTED;
499 caResult = CA_BAD_REQ;
507 * Handler function for sending a response from a single resource
509 * @param ehResponse - pointer to the response from the resource
514 OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
516 OCStackResult result = OC_STACK_ERROR;
517 CAEndpoint_t responseEndpoint = {.adapter = CA_DEFAULT_ADAPTER};
518 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
519 CAHeaderOption_t* optionsPointer = NULL;
521 if(!ehResponse || !ehResponse->requestHandle)
523 OIC_LOG(ERROR, TAG, "ehResponse/requestHandle is NULL");
524 return OC_STACK_ERROR;
527 OCServerRequest *serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
528 if (NULL == serverRequest)
530 OIC_LOG(ERROR, TAG, "No serverRequest matching with ehResponse");
531 return OC_STACK_ERROR;
534 CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
536 responseInfo.info.messageId = serverRequest->coapID;
537 responseInfo.info.resourceUri = serverRequest->resourceUrl;
538 responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult, serverRequest->method);
539 responseInfo.info.dataType = CA_RESPONSE_DATA;
541 if(serverRequest->notificationFlag && serverRequest->qos == OC_HIGH_QOS)
543 responseInfo.info.type = CA_MSG_CONFIRM;
545 else if(serverRequest->notificationFlag && serverRequest->qos != OC_HIGH_QOS)
547 responseInfo.info.type = CA_MSG_NONCONFIRM;
549 else if(!serverRequest->notificationFlag && !serverRequest->slowFlag &&
550 serverRequest->qos == OC_HIGH_QOS)
552 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
554 else if(!serverRequest->notificationFlag && serverRequest->slowFlag &&
555 serverRequest->qos == OC_HIGH_QOS)
557 // To assign new messageId in CA.
558 responseInfo.info.messageId = 0;
559 responseInfo.info.type = CA_MSG_CONFIRM;
561 else if(!serverRequest->notificationFlag)
563 responseInfo.info.type = CA_MSG_NONCONFIRM;
567 OIC_LOG(ERROR, TAG, "default responseInfo type is NON");
568 responseInfo.info.type = CA_MSG_NONCONFIRM;
571 char rspToken[CA_MAX_TOKEN_LEN + 1] = {0};
572 responseInfo.info.messageId = serverRequest->coapID;
573 responseInfo.info.token = (CAToken_t)rspToken;
575 memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
576 responseInfo.info.tokenLength = serverRequest->tokenLength;
578 if((serverRequest->observeResult == OC_STACK_OK)&&
579 (serverRequest->observationOption != MAX_SEQUENCE_NUMBER + 1))
581 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
585 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions;
588 if(responseInfo.info.numOptions > 0)
590 responseInfo.info.options = (CAHeaderOption_t *)
591 OICCalloc(responseInfo.info.numOptions,
592 sizeof(CAHeaderOption_t));
594 if(!responseInfo.info.options)
596 OIC_LOG(FATAL, TAG, "Memory alloc for options failed");
597 return OC_STACK_NO_MEMORY;
600 optionsPointer = responseInfo.info.options;
602 // TODO: This exposes CoAP specific details. At some point, this should be
603 // re-factored and handled in the CA layer.
604 if(serverRequest->observeResult == OC_STACK_OK)
606 responseInfo.info.options[0].protocolID = CA_COAP_ID;
607 responseInfo.info.options[0].optionID = COAP_OPTION_OBSERVE;
608 responseInfo.info.options[0].optionLength = sizeof(uint32_t);
609 uint8_t* observationData = (uint8_t*)responseInfo.info.options[0].optionData;
610 uint32_t observationOption= serverRequest->observationOption;
612 for (size_t i=sizeof(uint32_t); i; --i)
614 observationData[i-1] = observationOption & 0xFF;
615 observationOption >>=8;
618 // Point to the next header option before copying vender specific header options
622 if (ehResponse->numSendVendorSpecificHeaderOptions)
624 memcpy(optionsPointer, ehResponse->sendVendorSpecificHeaderOptions,
625 sizeof(OCHeaderOption) *
626 ehResponse->numSendVendorSpecificHeaderOptions);
631 responseInfo.info.options = NULL;
634 responseInfo.isMulticast = false;
635 responseInfo.info.payload = NULL;
636 responseInfo.info.payloadSize = 0;
637 responseInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
639 // Put the JSON prefix and suffix around the payload
640 if(ehResponse->payload)
643 if (ehResponse->payload->type == PAYLOAD_TYPE_PRESENCE)
645 responseInfo.isMulticast = true;
650 responseInfo.isMulticast = false;
653 switch(serverRequest->acceptFormat)
655 case OC_FORMAT_UNDEFINED:
656 // No preference set by the client, so default to CBOR then
658 if((result = OCConvertPayload(ehResponse->payload, &responseInfo.info.payload,
659 &responseInfo.info.payloadSize))
662 OIC_LOG(ERROR, TAG, "Error converting payload");
663 OICFree(responseInfo.info.options);
666 // Add CONTENT_FORMAT OPT if payload exist
667 if (responseInfo.info.payloadSize > 0)
669 responseInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
673 responseInfo.result = CA_NOT_ACCEPTABLE;
678 CATransportAdapter_t CAConnTypes[] = {
680 CA_ADAPTER_GATT_BTLE,
681 CA_ADAPTER_RFCOMM_BTEDR,
684 , CA_ADAPTER_REMOTE_ACCESS
689 size_t size = sizeof(CAConnTypes)/ sizeof(CATransportAdapter_t);
691 CATransportAdapter_t adapter = responseEndpoint.adapter;
692 // Default adapter, try to send response out on all adapters.
693 if (adapter == CA_DEFAULT_ADAPTER)
696 (CATransportAdapter_t)(
698 CA_ADAPTER_GATT_BTLE |
699 CA_ADAPTER_RFCOMM_BTEDR |
702 | CA_ADAPTER_REMOTE_ACCESS
708 result = OC_STACK_OK;
709 OCStackResult tempResult = OC_STACK_OK;
711 for(size_t i = 0; i < size; i++ )
713 responseEndpoint.adapter = (CATransportAdapter_t)(adapter & CAConnTypes[i]);
714 if(responseEndpoint.adapter)
716 //The result is set to OC_STACK_OK only if OCSendResponse succeeds in sending the
717 //response on all the n/w interfaces else it is set to OC_STACK_ERROR
718 tempResult = OCSendResponse(&responseEndpoint, &responseInfo);
720 if(OC_STACK_OK != tempResult)
727 OIC_LOG(INFO, TAG, "Calling OCSendResponse with:");
728 OIC_LOG_V(INFO, TAG, "\tEndpoint address: %s", responseEndpoint.addr);
729 OIC_LOG_V(INFO, TAG, "\tEndpoint adapter: %s", responseEndpoint.adapter);
730 OIC_LOG_V(INFO, TAG, "\tResponse result : %s", responseInfo.result);
731 OIC_LOG_V(INFO, TAG, "\tResponse for uri: %s", responseInfo.info.resourceUri);
733 result = OCSendResponse(&responseEndpoint, &responseInfo);
736 OICFree(responseInfo.info.payload);
737 OICFree(responseInfo.info.options);
739 FindAndDeleteServerRequest(serverRequest);
744 * Handler function for sending a response from multiple resources, such as a collection.
745 * Aggregates responses from multiple resource until all responses are received then sends the
746 * concatenated response
748 * TODO: Need to add a timeout in case a (remote?) resource does not respond
750 * @param ehResponse - pointer to the response from the resource
755 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
757 if(!ehResponse || !ehResponse->payload)
759 OIC_LOG(ERROR, TAG, "HandleAggregateResponse invalid parameters");
760 return OC_STACK_INVALID_PARAM;
763 OIC_LOG(INFO, TAG, "Inside HandleAggregateResponse");
765 OCServerRequest *serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
766 OCServerResponse *serverResponse = GetServerResponseUsingHandle(ehResponse->requestHandle);
768 OCStackResult stackRet = OC_STACK_ERROR;
773 OIC_LOG(INFO, TAG, "This is the first response fragment");
774 stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle);
775 if (OC_STACK_OK != stackRet)
777 OIC_LOG(ERROR, TAG, "Error adding server response");
780 VERIFY_NON_NULL(serverResponse);
783 if(ehResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
785 stackRet = OC_STACK_ERROR;
786 OIC_LOG(ERROR, TAG, "Error adding payload, as it was the incorrect type");
790 OCRepPayload *newPayload = OCRepPayloadBatchClone((OCRepPayload *)ehResponse->payload);
792 if(!serverResponse->payload)
794 serverResponse->payload = (OCPayload *)newPayload;
798 OCRepPayloadAppend((OCRepPayload*)serverResponse->payload,
799 (OCRepPayload*)newPayload);
802 (serverRequest->numResponses)--;
804 if(serverRequest->numResponses == 0)
806 OIC_LOG(INFO, TAG, "This is the last response fragment");
807 ehResponse->payload = serverResponse->payload;
808 ehResponse->ehResult = OC_EH_OK;
809 stackRet = HandleSingleResponse(ehResponse);
810 //Delete the request and response
811 FindAndDeleteServerRequest(serverRequest);
812 FindAndDeleteServerResponse(serverResponse);
816 OIC_LOG(INFO, TAG, "More response fragments to come");
817 stackRet = OC_STACK_OK;