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 = {.adapter = CA_DEFAULT_ADAPTER};
415 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
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 char rspToken[CA_MAX_TOKEN_LEN + 1] = {};
454 responseInfo.info.messageId = serverRequest->coapID;
455 responseInfo.info.token = (CAToken_t)rspToken;
457 memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
458 responseInfo.info.tokenLength = serverRequest->tokenLength;
460 if(serverRequest->observeResult == OC_STACK_OK)
462 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
466 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions;
469 if(responseInfo.info.numOptions > 0)
471 responseInfo.info.options = (CAHeaderOption_t *)
472 OICCalloc(responseInfo.info.numOptions,
473 sizeof(CAHeaderOption_t));
475 if(!responseInfo.info.options)
477 OC_LOG(FATAL, TAG, PCF("Memory alloc for options failed"));
478 return OC_STACK_NO_MEMORY;
481 optionsPointer = responseInfo.info.options;
483 // TODO: This exposes CoAP specific details. At some point, this should be
484 // re-factored and handled in the CA layer.
485 if(serverRequest->observeResult == OC_STACK_OK)
487 responseInfo.info.options[0].protocolID = CA_COAP_ID;
488 responseInfo.info.options[0].optionID = COAP_OPTION_OBSERVE;
489 responseInfo.info.options[0].optionLength = sizeof(uint32_t);
490 memcpy(responseInfo.info.options[0].optionData,
491 &(serverRequest->observationOption), sizeof(uint32_t));
493 // Point to the next header option before copying vender specific header options
497 if (ehResponse->numSendVendorSpecificHeaderOptions)
499 memcpy(optionsPointer, ehResponse->sendVendorSpecificHeaderOptions,
500 sizeof(OCHeaderOption) *
501 ehResponse->numSendVendorSpecificHeaderOptions);
506 responseInfo.info.options = NULL;
509 // Put the JSON prefix and suffix around the payload
510 if(ehResponse->payload)
512 OCStackResult result;
513 if((result = OCConvertPayload(ehResponse->payload, &responseInfo.info.payload,
514 &responseInfo.info.payloadSize))
517 OC_LOG(ERROR, TAG, "Error converting payload");
518 OICFree(responseInfo.info.options);
522 if(responseInfo.info.payloadSize > MAX_RESPONSE_LENGTH)
524 OICFree(responseInfo.info.payload);
525 OC_LOG(ERROR, TAG, "Payload too long!");
526 OICFree(responseInfo.info.options);
527 return OC_STACK_INVALID_PARAM;
532 responseInfo.info.payload = NULL;
533 responseInfo.info.payloadSize = 0;
537 CATransportAdapter_t CAConnTypes[] = {
539 CA_ADAPTER_GATT_BTLE,
540 CA_ADAPTER_RFCOMM_BTEDR
543 , CA_ADAPTER_REMOTE_ACCESS
547 int size = sizeof(CAConnTypes)/ sizeof(CATransportAdapter_t);
549 CATransportAdapter_t adapter = responseEndpoint.adapter;
550 CAResult_t caResult = CA_STATUS_FAILED;
551 result = OC_STACK_OK;
553 // Default adapter, try to send response out on all adapters.
554 if (adapter == CA_DEFAULT_ADAPTER)
557 (CATransportAdapter_t)(
559 CA_ADAPTER_GATT_BTLE |
560 CA_ADAPTER_RFCOMM_BTEDR
563 | CA_ADAPTER_REMOTE_ACCESS
568 for(int i = 0; i < size; i++ )
570 responseEndpoint.adapter = (CATransportAdapter_t)(adapter & CAConnTypes[i]);
571 if(responseEndpoint.adapter)
573 //The result is set to OC_STACK_OK only if CASendResponse succeeds in sending the
574 //response on all the n/w interfaces else it is set to OC_STACK_ERROR
575 caResult = CASendResponse(&responseEndpoint, &responseInfo);
576 if(caResult != CA_STATUS_OK)
578 OC_LOG_V(ERROR, TAG, "CASendResponse failed with CA error %u", caResult);
579 result = CAResultToOCResult(caResult);
585 OC_LOG(INFO, TAG, PCF("Calling CASendResponse with:"));
586 OC_LOG_V(INFO, TAG, "\tEndpoint address: %s", responseEndpoint.addr);
587 OC_LOG_V(INFO, TAG, "\tEndpoint adapter: %s", responseEndpoint.adapter);
588 OC_LOG_V(INFO, TAG, "\tResponse result : %s", responseInfo.result);
589 OC_LOG_V(INFO, TAG, "\tResponse for uri: %s", responseInfo.info.resourceUri);
591 CAResult_t caResult = CASendResponse(&responseEndpoint, &responseInfo);
592 if(caResult != CA_STATUS_OK)
594 OC_LOG(ERROR, TAG, PCF("CASendResponse failed"));
595 result = CAResultToOCResult(caResult);
599 result = OC_STACK_OK;
603 OICFree(responseInfo.info.payload);
604 OICFree(responseInfo.info.options);
606 FindAndDeleteServerRequest(serverRequest);
611 * Handler function for sending a response from multiple resources, such as a collection.
612 * Aggregates responses from multiple resource until all responses are received then sends the
613 * concatenated response
615 * TODO: Need to add a timeout in case a (remote?) resource does not respond
617 * @param ehResponse - pointer to the response from the resource
622 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
624 OCStackResult stackRet = OC_STACK_ERROR;
625 OCServerRequest * serverRequest = NULL;
626 OCServerResponse * serverResponse = NULL;
628 if(!ehResponse || !ehResponse->payload)
630 OC_LOG(ERROR, TAG, PCF("HandleAggregateResponse invalid parameters"));
631 return OC_STACK_INVALID_PARAM;
634 OC_LOG(INFO, TAG, "Inside HandleAggregateResponse");
636 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
637 serverResponse = GetServerResponseUsingHandle((OCServerRequest *)ehResponse->requestHandle);
643 OC_LOG(INFO, TAG, PCF("This is the first response fragment"));
644 stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle);
645 if (OC_STACK_OK != stackRet)
647 OC_LOG(ERROR, TAG, PCF("Error adding server response"));
650 VERIFY_NON_NULL(serverResponse);
653 if(ehResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
655 stackRet = OC_STACK_ERROR;
656 OC_LOG(ERROR, TAG, PCF("Error adding payload, as it was the incorrect type"));
660 if(!serverResponse->payload)
662 serverResponse->payload = ehResponse->payload;
666 OCRepPayloadAppend((OCRepPayload*)serverResponse->payload,
667 (OCRepPayload*)ehResponse->payload);
671 (serverRequest->numResponses)--;
673 if(serverRequest->numResponses == 0)
675 OC_LOG(INFO, TAG, PCF("This is the last response fragment"));
676 ehResponse->payload = serverResponse->payload;
677 stackRet = HandleSingleResponse(ehResponse);
678 //Delete the request and response
679 FindAndDeleteServerRequest(serverRequest);
680 FindAndDeleteServerResponse(serverResponse);
684 OC_LOG(INFO, TAG, PCF("More response fragments to come"));
685 stackRet = OC_STACK_OK;