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,
305 OCResourceHandle resource,
309 uint8_t numVendorOptions,
310 OCHeaderOption * vendorOptions,
311 OCObserveAction observeAction,
312 OCObservationId observeID)
314 if (entityHandlerRequest)
316 entityHandlerRequest->resource = (OCResourceHandle) resource;
317 entityHandlerRequest->requestHandle = request;
318 entityHandlerRequest->method = method;
319 entityHandlerRequest->query = queryBuf;
320 entityHandlerRequest->obsInfo.action = observeAction;
321 entityHandlerRequest->obsInfo.obsId = observeID;
323 if(payload && payloadSize)
325 if(OCParsePayload(&entityHandlerRequest->payload, payload, payloadSize) != OC_STACK_OK)
327 return OC_STACK_ERROR;
332 entityHandlerRequest->payload = NULL;
335 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions;
336 entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions;
341 return OC_STACK_INVALID_PARAM;
345 * Find a server request in the server request list and delete
347 * @param serverRequest - server request to find and delete
349 void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
351 OCServerRequest* tmp;
354 LL_FOREACH(serverRequestList, tmp)
356 if (serverRequest == tmp)
358 DeleteServerRequest(tmp);
365 CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result)
367 CAResponseResult_t caResult = CA_BAD_REQ;
372 caResult = CA_SUCCESS;
375 caResult = CA_BAD_REQ;
377 case OC_EH_RESOURCE_CREATED:
378 caResult = CA_CREATED;
380 case OC_EH_RESOURCE_DELETED:
381 caResult = CA_DELETED;
384 caResult = CA_SUCCESS;
386 case OC_EH_FORBIDDEN:
387 caResult = CA_UNAUTHORIZED_REQ;
389 case OC_EH_RESOURCE_NOT_FOUND:
390 caResult = CA_NOT_FOUND;
393 caResult = CA_BAD_REQ;
401 * Handler function for sending a response from a single resource
403 * @param ehResponse - pointer to the response from the resource
409 OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
411 OCStackResult result = OC_STACK_ERROR;
412 CAEndpoint_t responseEndpoint = {};
413 CAResponseInfo_t responseInfo = {};
414 CAHeaderOption_t* optionsPointer = NULL;
416 if(!ehResponse || !ehResponse->requestHandle)
418 return OC_STACK_ERROR;
421 OCServerRequest *serverRequest = (OCServerRequest *)ehResponse->requestHandle;
423 CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
425 responseInfo.info.resourceUri = serverRequest->resourceUrl;
426 responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult);
428 if(serverRequest->notificationFlag && serverRequest->qos == OC_HIGH_QOS)
430 responseInfo.info.type = CA_MSG_CONFIRM;
432 else if(serverRequest->notificationFlag && serverRequest->qos != OC_HIGH_QOS)
434 responseInfo.info.type = CA_MSG_NONCONFIRM;
436 else if(!serverRequest->notificationFlag && !serverRequest->slowFlag &&
437 serverRequest->qos == OC_HIGH_QOS)
439 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
441 else if(!serverRequest->notificationFlag && serverRequest->slowFlag &&
442 serverRequest->qos == OC_HIGH_QOS)
444 responseInfo.info.type = CA_MSG_CONFIRM;
446 else if(!serverRequest->notificationFlag)
448 responseInfo.info.type = CA_MSG_NONCONFIRM;
451 responseInfo.info.messageId = serverRequest->coapID;
452 responseInfo.info.token = (CAToken_t)OICMalloc(CA_MAX_TOKEN_LEN+1);
453 if (!responseInfo.info.token)
455 OC_LOG(FATAL, TAG, "Memory alloc for token failed");
459 memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
460 responseInfo.info.tokenLength = serverRequest->tokenLength;
462 if(serverRequest->observeResult == OC_STACK_OK)
464 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
468 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions;
471 if(responseInfo.info.numOptions > 0)
473 responseInfo.info.options = (CAHeaderOption_t *)
474 OICCalloc(responseInfo.info.numOptions,
475 sizeof(CAHeaderOption_t));
477 if(!responseInfo.info.options)
479 OC_LOG(FATAL, TAG, PCF("Memory alloc for options failed"));
480 OICFree(responseInfo.info.token);
481 return OC_STACK_NO_MEMORY;
484 optionsPointer = responseInfo.info.options;
486 // TODO: This exposes CoAP specific details. At some point, this should be
487 // re-factored and handled in the CA layer.
488 if(serverRequest->observeResult == OC_STACK_OK)
490 responseInfo.info.options[0].protocolID = CA_COAP_ID;
491 responseInfo.info.options[0].optionID = COAP_OPTION_OBSERVE;
492 responseInfo.info.options[0].optionLength = sizeof(uint32_t);
493 memcpy(responseInfo.info.options[0].optionData,
494 &(serverRequest->observationOption), sizeof(uint32_t));
496 // Point to the next header option before copying vender specific header options
500 if (ehResponse->numSendVendorSpecificHeaderOptions)
502 memcpy(optionsPointer, ehResponse->sendVendorSpecificHeaderOptions,
503 sizeof(OCHeaderOption) *
504 ehResponse->numSendVendorSpecificHeaderOptions);
509 responseInfo.info.options = NULL;
512 // Put the JSON prefix and suffix around the payload
513 if(ehResponse->payload)
515 OCStackResult result;
516 if((result = OCConvertPayload(ehResponse->payload, &responseInfo.info.payload,
517 &responseInfo.info.payloadSize))
520 OC_LOG(ERROR, TAG, "Error converting payload");
524 if(responseInfo.info.payloadSize > MAX_RESPONSE_LENGTH)
526 OICFree(responseInfo.info.payload);
527 OC_LOG(ERROR, TAG, "Payload too long!");
528 return OC_STACK_INVALID_PARAM;
533 responseInfo.info.payload = NULL;
534 responseInfo.info.payloadSize = 0;
538 //TODO: Add other connectivity types to CAConnTypes[] when enabled
539 CATransportAdapter_t CAConnTypes[] = {CA_ADAPTER_IP};
540 const char * connTypes[] = {"IP"};
541 int size = sizeof(CAConnTypes)/ sizeof(CATransportAdapter_t);
542 CATransportAdapter_t adapter = responseEndpoint.adapter;
543 CAResult_t caResult = CA_STATUS_FAILED;
544 result = OC_STACK_OK;
546 // Default adapter, try to send response out on all adapters.
547 if (adapter == CA_DEFAULT_ADAPTER)
550 (CATransportAdapter_t)(CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE | CA_ADAPTER_RFCOMM_BTEDR);
553 for(int i = 0; i < size; i++ )
555 responseEndpoint.adapter = (CATransportAdapter_t)(adapter & CAConnTypes[i]);
556 if(responseEndpoint.adapter)
558 //The result is set to OC_STACK_OK only if CASendResponse succeeds in sending the
559 //response on all the n/w interfaces else it is set to OC_STACK_ERROR
560 caResult = CASendResponse(&responseEndpoint, &responseInfo);
561 if(caResult != CA_STATUS_OK)
563 OC_LOG_V(ERROR, TAG, "CASendResponse failed on %s", connTypes[i]);
564 result = CAResultToOCResult(caResult);
568 OC_LOG_V(INFO, TAG, "CASendResponse succeeded on %s", connTypes[i]);
574 OC_LOG(INFO, TAG, PCF("Calling CASendResponse with:"));
575 OC_LOG_V(INFO, TAG, "\tEndpoint address: %s", responseEndpoint.addr);
576 OC_LOG_V(INFO, TAG, "\tEndpoint adapter: %s", responseEndpoint.adapter);
577 OC_LOG_V(INFO, TAG, "\tResponse result : %s", responseInfo.result);
578 OC_LOG_V(INFO, TAG, "\tResponse for uri: %s", responseInfo.info.resourceUri);
580 CAResult_t caResult = CASendResponse(&responseEndpoint, &responseInfo);
581 if(caResult != CA_STATUS_OK)
583 OC_LOG(ERROR, TAG, PCF("CASendResponse failed"));
584 result = CAResultToOCResult(caResult);
588 result = OC_STACK_OK;
592 OICFree(responseInfo.info.payload);
593 OICFree(responseInfo.info.token);
594 OICFree(responseInfo.info.options);
596 FindAndDeleteServerRequest(serverRequest);
601 * Handler function for sending a response from multiple resources, such as a collection.
602 * Aggregates responses from multiple resource until all responses are received then sends the
603 * concatenated response
605 * TODO: Need to add a timeout in case a (remote?) resource does not respond
607 * @param ehResponse - pointer to the response from the resource
612 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
614 OCStackResult stackRet = OC_STACK_ERROR;
615 OCServerRequest * serverRequest = NULL;
616 OCServerResponse * serverResponse = NULL;
618 if(!ehResponse || !ehResponse->payload)
620 OC_LOG(ERROR, TAG, PCF("HandleAggregateResponse invalid parameters"));
621 return OC_STACK_INVALID_PARAM;
624 OC_LOG(INFO, TAG, "Inside HandleAggregateResponse");
626 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
627 serverResponse = GetServerResponseUsingHandle((OCServerRequest *)ehResponse->requestHandle);
633 OC_LOG(INFO, TAG, PCF("This is the first response fragment"));
634 stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle);
635 if (OC_STACK_OK != stackRet)
637 OC_LOG(ERROR, TAG, PCF("Error adding server response"));
640 VERIFY_NON_NULL(serverResponse);
643 if(serverResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION ||
644 ehResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
646 stackRet = OC_STACK_ERROR;
647 OC_LOG(ERROR, TAG, PCF("Error adding payload, as it was the incorrect type"));
651 OCRepPayloadAppend((OCRepPayload*)serverResponse->payload,
652 (OCRepPayload*)ehResponse->payload);
654 (serverRequest->numResponses)--;
656 if(serverRequest->numResponses == 0)
658 OC_LOG(INFO, TAG, PCF("This is the last response fragment"));
659 ehResponse->payload = serverResponse->payload;
660 stackRet = HandleSingleResponse(ehResponse);
661 //Delete the request and response
662 FindAndDeleteServerRequest(serverRequest);
663 FindAndDeleteServerResponse(serverResponse);
667 OC_LOG(INFO, TAG, PCF("More response fragments to come"));
668 stackRet = OC_STACK_OK;