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"
28 #include "cainterface.h"
34 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
36 #define TAG PCF("ocserverrequest")
38 static struct OCServerRequest * serverRequestList = NULL;
39 static struct OCServerResponse * serverResponseList = NULL;
41 //-------------------------------------------------------------------------------------------------
43 //-------------------------------------------------------------------------------------------------
46 * Add a server response to the server response list
48 * @param response initialized server response that is created by this function
49 * @param requestHandle - handle of the response
54 static OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle)
56 OCServerResponse * serverResponse = NULL;
58 serverResponse = (OCServerResponse *) OCCalloc(1, sizeof(OCServerResponse));
59 VERIFY_NON_NULL(serverResponse);
61 serverResponse->payload = (char *) OCCalloc(1, MAX_RESPONSE_LENGTH);
62 VERIFY_NON_NULL(serverResponse->payload);
64 serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH;
65 serverResponse->requestHandle = requestHandle;
67 *response = serverResponse;
68 OC_LOG(INFO, TAG, PCF("Server Response Added!!"));
69 LL_APPEND (serverResponseList, serverResponse);
75 OCFree(serverResponse);
76 serverResponse = NULL;
79 return OC_STACK_NO_MEMORY;
83 * Delete a server request from the server request list
85 * @param serverRequest - server request to delete
87 static void DeleteServerRequest(OCServerRequest * serverRequest)
91 LL_DELETE(serverRequestList, serverRequest);
92 OCFree(serverRequest);
94 OC_LOG(INFO, TAG, PCF("Server Request Removed!!"));
99 * Delete a server response from the server response list
101 * @param serverResponse - server response to delete
103 static void DeleteServerResponse(OCServerResponse * serverResponse)
107 LL_DELETE(serverResponseList, serverResponse);
108 OCFree(serverResponse->payload);
109 OCFree(serverResponse);
110 OC_LOG(INFO, TAG, PCF("Server Response Removed!!"));
115 * Find a server response and delete it from the server response list
117 * @param serverResponse - server response to find and delete
119 static void FindAndDeleteServerResponse(OCServerResponse * serverResponse)
121 OCServerResponse* tmp;
124 LL_FOREACH(serverResponseList, tmp)
126 if (serverResponse == tmp)
128 DeleteServerResponse(tmp);
135 //-------------------------------------------------------------------------------------------------
137 //-------------------------------------------------------------------------------------------------
140 * Get a server request from the server request list using the specified token.
142 * @param token - token of server request
143 * @param tokenLength - length of token
148 OCServerRequest * GetServerRequestUsingToken (const CAToken_t token, uint8_t tokenLength)
152 OC_LOG(ERROR, TAG, PCF("Invalid Parameter Token"));
156 OCServerRequest * out = NULL;
157 LL_FOREACH (serverRequestList, out)
159 OC_LOG(INFO, TAG,PCF("comparing tokens"));
160 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
161 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->requestToken, tokenLength);
162 if(memcmp(out->requestToken, token, tokenLength) == 0)
167 OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
172 * Get a server request from the server request list using the specified handle
174 * @param handle - handle of server request
178 OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle)
180 OCServerRequest * out = NULL;
181 LL_FOREACH (serverRequestList, out)
188 OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
193 * Get a server response from the server response list using the specified handle
195 * @param handle - handle of server response
200 OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
202 OCServerResponse * out = NULL;
203 LL_FOREACH (serverResponseList, out)
205 if(out->requestHandle == handle)
210 OC_LOG(ERROR, TAG, PCF("Server Response not found!!"));
215 * Add a server request to the server request list
217 * @param request - initialized server request that is created by this function
218 * @param coapID - ID of CoAP pdu
219 * @param delayedResNeeded - delayed response required 0=no 1=yes
220 * @param secured - secure endpoint 0=no 1=yes
221 * @param notificationFlag - //TODO: remove - does not appear to be used any longer
222 * @param method - RESTful method
223 * @param numRcvdVendorSpecificHeaderOptions - number of received vendor specific header options
224 * @param observationOption - value of observation option
225 * @param qos - request QOS
226 * @param query - request query
227 * @param rcvdVendorSpecificHeaderOptions - received vendor specific header options
228 * @param reqJSONPayload - request JSON payload
229 * @param requestToken - request token
230 * @param tokenLength - request token length
231 * @param resourceUrl - URL of resource
232 * @param reqTotalSize - total size of the request
233 * @param addressInfo - CA Address
234 * @param connectivityType - connection type
239 OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
240 uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
241 uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
242 OCQualityOfService qos, char * query,
243 OCHeaderOption * rcvdVendorSpecificHeaderOptions,
244 char * reqJSONPayload, CAToken_t requestToken,
246 char * resourceUrl, size_t reqTotalSize,
247 CAAddress_t *addressInfo, CATransportType_t connectivityType)
249 OCServerRequest * serverRequest = NULL;
251 //Note: OCServerRequest includes 1 byte for the JSON Payload. payloadSize is calculated
252 //as the required length of the string, so this will result in enough room for the
253 //null terminator as well.
254 serverRequest = (OCServerRequest *) OCCalloc(1, sizeof(OCServerRequest) +
255 (reqTotalSize ? reqTotalSize : 1) - 1);
256 VERIFY_NON_NULL(serverRequest);
258 serverRequest->coapID = coapID;
259 serverRequest->delayedResNeeded = delayedResNeeded;
260 serverRequest->secured = secured;
261 serverRequest->notificationFlag = notificationFlag;
263 serverRequest->method = method;
264 serverRequest->numRcvdVendorSpecificHeaderOptions = numRcvdVendorSpecificHeaderOptions;
265 serverRequest->observationOption = observationOption;
266 serverRequest->observeResult = OC_STACK_ERROR;
267 serverRequest->qos = qos;
268 serverRequest->ehResponseHandler = HandleSingleResponse;
269 serverRequest->numResponses = 1;
273 strncpy((char*)serverRequest->query,
274 (const char*)query, sizeof(serverRequest->query) - 1);
277 if(rcvdVendorSpecificHeaderOptions)
279 memcpy(serverRequest->rcvdVendorSpecificHeaderOptions, rcvdVendorSpecificHeaderOptions,
280 MAX_HEADER_OPTIONS * sizeof(OCHeaderOption));
282 if(reqJSONPayload && reqTotalSize)
284 // destination is at least 1 greater than the source, so a NULL always exists in the
286 strncpy((char*)serverRequest->reqJSONPayload,
287 (const char*)reqJSONPayload, reqTotalSize - 1);
289 serverRequest->requestComplete = 0;
292 // If tokenLength is zero, the return value depends on the
293 // particular library implementation (it may or may not be a null pointer).
296 serverRequest->requestToken = (CAToken_t) OCMalloc(tokenLength);
297 VERIFY_NON_NULL(serverRequest->requestToken);
298 memcpy(serverRequest->requestToken, requestToken, tokenLength);
302 serverRequest->tokenLength = tokenLength;
306 strncpy((char*)serverRequest->resourceUrl,
307 (const char*)resourceUrl, sizeof(serverRequest->resourceUrl) - 1);
312 serverRequest->addressInfo = *addressInfo;
314 serverRequest->connectivityType = connectivityType;
316 *request = serverRequest;
317 OC_LOG(INFO, TAG, PCF("Server Request Added!!"));
318 LL_APPEND (serverRequestList, serverRequest);
324 OCFree(serverRequest);
325 serverRequest = NULL;
328 return OC_STACK_NO_MEMORY;
332 * Form the OCEntityHandlerRequest struct that is passed to a resource's entity handler
334 * @param entityHandlerRequest - pointer to the OCEntityHandlerRequest struct that is created
335 * @param request - request handle
336 * @param method - RESTful method
337 * @param resource - resource handle
338 * @param queryBuf - resource query of request
339 * @param bufReqPayload - JSON payload of request
340 * @param numVendorOptions - number of vendor options
341 * @param vendorOptions - vendor options
342 * @param observeAction - observe action flag
343 * @param observeID - observe ID
348 OCStackResult FormOCEntityHandlerRequest(
349 OCEntityHandlerRequest * entityHandlerRequest,
350 OCRequestHandle request,
352 OCResourceHandle resource,
354 char * bufReqPayload,
355 uint8_t numVendorOptions,
356 OCHeaderOption * vendorOptions,
357 OCObserveAction observeAction,
358 OCObservationId observeID)
360 if (entityHandlerRequest)
362 memset(entityHandlerRequest, 0, sizeof(OCEntityHandlerRequest));
363 entityHandlerRequest->requestHandle = request;
364 entityHandlerRequest->method = method;
365 entityHandlerRequest->resource = (OCResourceHandle) resource;
366 entityHandlerRequest->query = queryBuf;
367 entityHandlerRequest->reqJSONPayload = bufReqPayload;
368 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions;
369 entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions;
371 entityHandlerRequest->obsInfo.action = observeAction;
372 entityHandlerRequest->obsInfo.obsId = observeID;
376 return OC_STACK_INVALID_PARAM;
380 * Find a server request in the server request list and delete
382 * @param serverRequest - server request to find and delete
384 void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
386 OCServerRequest* tmp;
389 LL_FOREACH(serverRequestList, tmp)
391 if (serverRequest == tmp)
393 DeleteServerRequest(tmp);
400 CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result)
402 CAResponseResult_t caResult = CA_BAD_REQ;
407 caResult = CA_SUCCESS;
410 caResult = CA_BAD_REQ;
412 case OC_EH_RESOURCE_CREATED:
413 caResult = CA_CREATED;
415 case OC_EH_RESOURCE_DELETED:
416 caResult = CA_DELETED;
419 caResult = CA_SUCCESS;
421 case OC_EH_FORBIDDEN:
422 caResult = CA_BAD_REQ;
424 case OC_EH_RESOURCE_NOT_FOUND:
425 caResult = CA_NOT_FOUND;
428 caResult = CA_BAD_REQ;
436 * Handler function for sending a response from a single resource
438 * @param ehResponse - pointer to the response from the resource
444 OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
446 OCStackResult result = OC_STACK_ERROR;
447 CARemoteEndpoint_t responseEndpoint = {};
448 CAResponseInfo_t responseInfo = {};
449 CAHeaderOption_t* optionsPointer = NULL;
451 OC_LOG_V(INFO, TAG, "Inside HandleSingleResponse: %s", ehResponse->payload);
453 if(!ehResponse || !ehResponse->requestHandle)
455 return OC_STACK_ERROR;
458 OCServerRequest *serverRequest = (OCServerRequest *)ehResponse->requestHandle;
461 responseEndpoint.resourceUri = (CAURI_t) serverRequest->resourceUrl;
462 responseEndpoint.addressInfo = serverRequest->addressInfo;
463 responseEndpoint.transportType = serverRequest->connectivityType;
464 responseEndpoint.isSecured = serverRequest->secured;
466 responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult);
468 if(serverRequest->notificationFlag && serverRequest->qos == OC_HIGH_QOS)
470 responseInfo.info.type = CA_MSG_CONFIRM;
472 else if(serverRequest->notificationFlag && serverRequest->qos != OC_HIGH_QOS)
474 responseInfo.info.type = CA_MSG_NONCONFIRM;
476 else if(!serverRequest->notificationFlag && !serverRequest->slowFlag &&
477 serverRequest->qos == OC_HIGH_QOS)
479 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
481 else if(!serverRequest->notificationFlag && serverRequest->slowFlag &&
482 serverRequest->qos == OC_HIGH_QOS)
484 responseInfo.info.type = CA_MSG_CONFIRM;
486 else if(!serverRequest->notificationFlag)
488 responseInfo.info.type = CA_MSG_NONCONFIRM;
491 responseInfo.info.messageId = serverRequest->coapID;
492 responseInfo.info.token = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
493 if (!responseInfo.info.token)
495 OC_LOG(FATAL, TAG, "Response Info Token is NULL");
499 memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
500 responseInfo.info.tokenLength = serverRequest->tokenLength;
502 if(serverRequest->observeResult == OC_STACK_OK)
504 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
508 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions;
511 if(responseInfo.info.numOptions > 0)
513 responseInfo.info.options = (CAHeaderOption_t *)
514 OCCalloc(responseInfo.info.numOptions,
515 sizeof(CAHeaderOption_t));
517 if(!responseInfo.info.options)
519 OC_LOG(FATAL, TAG, PCF("options is NULL"));
520 return OC_STACK_NO_MEMORY;
523 optionsPointer = responseInfo.info.options;
525 // TODO: This exposes CoAP specific details. At some point, this should be
526 // re-factored and handled in the CA layer.
527 if(serverRequest->observeResult == OC_STACK_OK)
529 responseInfo.info.options[0].protocolID = CA_COAP_ID;
530 responseInfo.info.options[0].optionID = COAP_OPTION_OBSERVE;
531 responseInfo.info.options[0].optionLength = sizeof(uint32_t);
532 memcpy(responseInfo.info.options[0].optionData,
533 &(serverRequest->observationOption), sizeof(uint32_t));
535 // Point to the next header option before copying vender specific header options
539 if (ehResponse->numSendVendorSpecificHeaderOptions)
541 memcpy(optionsPointer, ehResponse->sendVendorSpecificHeaderOptions,
542 sizeof(OCHeaderOption) *
543 ehResponse->numSendVendorSpecificHeaderOptions);
548 responseInfo.info.options = NULL;
551 char payload[MAX_RESPONSE_LENGTH] = {};
553 // Put the JSON prefix and suffix around the payload
554 strcpy(payload, (const char *)OC_JSON_PREFIX);
555 strncat(payload, (const char *)ehResponse->payload, ehResponse->payloadSize);
556 strcat(payload, (const char *)OC_JSON_SUFFIX);
557 responseInfo.info.payload = (CAPayload_t)payload;
560 //TODO: Add other connectivity types to CAConnTypes[] when enabled
561 CATransportType_t CAConnTypes[] = {CA_IPV4};
562 const char * connTypes[] = {"ip transport"};
563 int size = sizeof(CAConnTypes)/ sizeof(CATransportType_t);
564 CATransportType_t connType = responseEndpoint.transportType;
565 CAResult_t caResult = CA_STATUS_FAILED;
566 result = OC_STACK_OK;
568 //Sending response on all n/w interfaces
569 for(int i = 0; i < size; i++ )
571 responseEndpoint.transportType = (CATransportType_t)(connType & CAConnTypes[i]);
572 if(responseEndpoint.transportType)
574 //The result is set to OC_STACK_OK only if CASendResponse succeeds in sending the
575 //response on all the n/w interfaces else it is set to OC_STACK_ERROR
576 caResult = CASendResponse(&responseEndpoint, &responseInfo);
577 if(caResult != CA_STATUS_OK)
579 OC_LOG_V(ERROR, TAG, "CASendResponse failed on %s", connTypes[i]);
580 result = CAResultToOCResult(caResult);
584 OC_LOG_V(INFO, TAG, "CASendResponse succeeded on %s", connTypes[i]);
589 CAResult_t caResult = CASendResponse(&responseEndpoint, &responseInfo);
590 if(caResult != CA_STATUS_OK)
592 OC_LOG(ERROR, TAG, PCF("CASendResponse failed"));
593 result = CAResultToOCResult(caResult);
597 result = OC_STACK_OK;
601 OCFree(responseInfo.info.options);
603 FindAndDeleteServerRequest(serverRequest);
608 * Handler function for sending a response from multiple resources, such as a collection.
609 * Aggregates responses from multiple resource until all responses are received then sends the
610 * concatenated response
612 * TODO: Need to add a timeout in case a (remote?) resource does not respond
614 * @param ehResponse - pointer to the response from the resource
619 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
621 OCStackResult stackRet = OC_STACK_ERROR;
622 OCServerRequest * serverRequest = NULL;
623 OCServerResponse * serverResponse = NULL;
624 uint16_t bufferNeeded = 0;
626 if(!ehResponse || !ehResponse->payload)
628 OC_LOG(ERROR, TAG, PCF("HandleAggregateResponse invalid parameters"));
629 return OC_STACK_INVALID_PARAM;
632 OC_LOG_V(INFO, TAG, "Inside HandleAggregateResponse: %s", ehResponse->payload);
634 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
635 serverResponse = GetServerResponseUsingHandle((OCServerRequest *)ehResponse->requestHandle);
641 OC_LOG(INFO, TAG, PCF("This is the first response fragment"));
642 stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle);
643 if (OC_STACK_OK != stackRet)
645 OC_LOG(ERROR, TAG, PCF("Error adding server response"));
648 VERIFY_NON_NULL(serverResponse);
649 VERIFY_NON_NULL(serverResponse->payload);
652 // If there is more than 1 response, then we need to allow for a null-termination
653 // in the server response payload buffer AND the JSON response separator
654 bufferNeeded = ehResponse->payloadSize + 1;
655 if (serverRequest->numResponses > 1)
657 bufferNeeded += strlen(OC_JSON_SEPARATOR_STR);
659 if(serverResponse->remainingPayloadSize >= bufferNeeded)
661 OC_LOG(ERROR, TAG, PCF("There is room in response buffer"));
663 strncat((char *)serverResponse->payload,
664 (char *)ehResponse->payload,
665 serverResponse->remainingPayloadSize);
666 OC_LOG_V(INFO, TAG, "Current aggregated response ...%s", serverResponse->payload);
667 serverResponse->remainingPayloadSize -= strlen((char *)ehResponse->payload);
668 (serverRequest->numResponses)--;
669 if(serverRequest->numResponses == 0)
671 OC_LOG(INFO, TAG, PCF("This is the last response fragment"));
672 ehResponse->payload = serverResponse->payload;
673 ehResponse->payloadSize = strlen((char *) serverResponse->payload) + 1;
674 stackRet = HandleSingleResponse(ehResponse);
675 //Delete the request and response
676 FindAndDeleteServerRequest(serverRequest);
677 FindAndDeleteServerResponse(serverResponse);
681 OC_LOG(INFO, TAG, PCF("More response fragments to come"));
682 strncat((char *)serverResponse->payload,
683 OC_JSON_SEPARATOR_STR,
684 serverResponse->remainingPayloadSize);
685 OC_LOG_V(INFO, TAG, "Current aggregated response ...%s", serverResponse->payload);
686 serverResponse->remainingPayloadSize -= strlen(OC_JSON_SEPARATOR_STR);
687 stackRet = OC_STACK_OK;
692 OC_LOG(ERROR, TAG, PCF("No room in response buffer"));
693 //Delete the request and response
694 FindAndDeleteServerRequest(serverRequest);
695 FindAndDeleteServerResponse(serverResponse);
696 stackRet = OC_STACK_NO_MEMORY;