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 OCServerRequest * GetServerRequestUsingToken (const CAToken_t token, uint8_t tokenLength)
45 OC_LOG(ERROR, TAG, PCF("Invalid Parameter Token"));
49 OCServerRequest * out = NULL;
50 LL_FOREACH (serverRequestList, out)
52 OC_LOG(INFO, TAG,PCF("comparing tokens"));
53 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
54 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->requestToken, tokenLength);
55 if(memcmp(out->requestToken, token, tokenLength) == 0)
60 OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
64 OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle)
66 OCServerRequest * out = NULL;
67 LL_FOREACH (serverRequestList, out)
74 OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
78 OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
80 OCServerResponse * out = NULL;
81 LL_FOREACH (serverResponseList, out)
83 if(out->requestHandle == handle)
88 OC_LOG(ERROR, TAG, PCF("Server Response not found!!"));
92 OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
93 uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
94 uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
95 OCQualityOfService qos, char * query,
96 OCHeaderOption * rcvdVendorSpecificHeaderOptions,
97 char * reqJSONPayload, CAToken_t * requestToken,
99 char * resourceUrl, size_t reqTotalSize,
100 CAAddress_t *addressInfo, CAConnectivityType_t connectivityType)
102 OCServerRequest * serverRequest = NULL;
104 //Note: OCServerRequest includes 1 byte for the JSON Payload. payloadSize is calculated
105 //as the required length of the string, so this will result in enough room for the
106 //null terminator as well.
107 serverRequest = (OCServerRequest *) OCCalloc(1, sizeof(OCServerRequest) +
108 (reqTotalSize ? reqTotalSize : 1) - 1);
109 VERIFY_NON_NULL(serverRequest);
111 serverRequest->coapID = coapID;
112 serverRequest->delayedResNeeded = delayedResNeeded;
113 serverRequest->secured = secured;
114 serverRequest->notificationFlag = notificationFlag;
116 serverRequest->method = method;
117 serverRequest->numRcvdVendorSpecificHeaderOptions = numRcvdVendorSpecificHeaderOptions;
118 serverRequest->observationOption = observationOption;
119 serverRequest->observeResult = OC_STACK_ERROR;
120 serverRequest->qos = qos;
121 serverRequest->ehResponseHandler = HandleSingleResponse;
122 serverRequest->numResponses = 1;
126 strncpy((char*)serverRequest->query,
127 (const char*)query, sizeof(serverRequest->query) - 1);
130 if(rcvdVendorSpecificHeaderOptions)
132 memcpy(serverRequest->rcvdVendorSpecificHeaderOptions, rcvdVendorSpecificHeaderOptions,
133 MAX_HEADER_OPTIONS * sizeof(OCHeaderOption));
135 if(reqJSONPayload && reqTotalSize)
137 // destination is at least 1 greater than the source, so a NULL always exists in the
139 strncpy((char*)serverRequest->reqJSONPayload,
140 (const char*)reqJSONPayload, reqTotalSize - 1);
142 serverRequest->requestComplete = 0;
145 // If tokenLength is zero, the return value depends on the
146 // particular library implementation (it may or may not be a null pointer).
149 serverRequest->requestToken = (CAToken_t) OCMalloc(tokenLength);
150 VERIFY_NON_NULL(serverRequest->requestToken);
151 memcpy(serverRequest->requestToken, *requestToken, tokenLength);
155 serverRequest->tokenLength = tokenLength;
159 strncpy((char*)serverRequest->resourceUrl,
160 (const char*)resourceUrl, sizeof(serverRequest->resourceUrl) - 1);
165 serverRequest->addressInfo = *addressInfo;
167 serverRequest->connectivityType = connectivityType;
169 *request = serverRequest;
170 OC_LOG(INFO, TAG, PCF("Server Request Added!!"));
171 LL_APPEND (serverRequestList, serverRequest);
177 OCFree(serverRequest);
178 serverRequest = NULL;
181 return OC_STACK_NO_MEMORY;
184 OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle)
186 OCServerResponse * serverResponse = NULL;
188 serverResponse = (OCServerResponse *) OCCalloc(1, sizeof(OCServerResponse));
189 VERIFY_NON_NULL(serverResponse);
191 serverResponse->payload = (char *) OCCalloc(1, MAX_RESPONSE_LENGTH);
192 VERIFY_NON_NULL(serverResponse->payload);
194 serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH;
195 serverResponse->requestHandle = requestHandle;
197 *response = serverResponse;
198 OC_LOG(INFO, TAG, PCF("Server Response Added!!"));
199 LL_APPEND (serverResponseList, serverResponse);
205 OCFree(serverResponse);
206 serverResponse = NULL;
209 return OC_STACK_NO_MEMORY;
212 // Form the OCEntityHandlerRequest struct
213 OCStackResult FormOCEntityHandlerRequest(
214 OCEntityHandlerRequest * entityHandlerRequest,
215 OCRequestHandle request,
217 OCResourceHandle resource,
219 char * bufReqPayload,
220 uint8_t numVendorOptions,
221 OCHeaderOption * vendorOptions,
222 OCObserveAction observeAction,
223 OCObservationId observeID)
225 if (entityHandlerRequest)
227 memset(entityHandlerRequest, 0, sizeof(OCEntityHandlerRequest));
228 entityHandlerRequest->requestHandle = request;
229 entityHandlerRequest->method = method;
230 entityHandlerRequest->resource = (OCResourceHandle) resource;
231 entityHandlerRequest->query = queryBuf;
232 entityHandlerRequest->reqJSONPayload = bufReqPayload;
233 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions;
234 entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions;
236 entityHandlerRequest->obsInfo.action = observeAction;
237 entityHandlerRequest->obsInfo.obsId = observeID;
241 return OC_STACK_INVALID_PARAM;
244 void FindAndDeleteServerResponse(OCServerResponse * serverResponse)
246 OCServerResponse* tmp;
249 LL_FOREACH(serverResponseList, tmp)
251 if (serverResponse == tmp)
253 DeleteServerResponse(tmp);
260 void DeleteServerResponse(OCServerResponse * serverResponse)
264 LL_DELETE(serverResponseList, serverResponse);
265 OCFree(serverResponse->payload);
266 OCFree(serverResponse);
267 OC_LOG(INFO, TAG, PCF("Server Response Removed!!"));
271 void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
273 OCServerRequest* tmp;
276 LL_FOREACH(serverRequestList, tmp)
278 if (serverRequest == tmp)
280 DeleteServerRequest(tmp);
287 void DeleteServerRequest(OCServerRequest * serverRequest)
291 LL_DELETE(serverRequestList, serverRequest);
292 OCFree(serverRequest);
293 serverRequest = NULL;
294 OC_LOG(INFO, TAG, PCF("Server Request Removed!!"));
298 OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
300 OCStackResult result = OC_STACK_ERROR;
301 CARemoteEndpoint_t responseEndpoint = {};
302 CAResponseInfo_t responseInfo = {};
303 CAHeaderOption_t* optionsPointer = NULL;
307 OC_LOG(ERROR, TAG, PCF("HandleSingleResponse invalid parameters"));
308 return OC_STACK_INVALID_PARAM;
311 OC_LOG_V(INFO, TAG, "Inside HandleSingleResponse: %s", ehResponse->payload);
313 OCServerRequest *serverRequest = (OCServerRequest *)ehResponse->requestHandle;
316 responseEndpoint.resourceUri = (CAURI_t) serverRequest->resourceUrl;
317 responseEndpoint.addressInfo = serverRequest->addressInfo;
318 responseEndpoint.connectivityType = serverRequest->connectivityType;
319 responseEndpoint.isSecured = serverRequest->secured;
321 switch (ehResponse->ehResult)
324 responseInfo.result = CA_SUCCESS;
327 responseInfo.result = CA_BAD_REQ;
329 case OC_EH_RESOURCE_CREATED:
330 responseInfo.result = CA_CREATED;
332 case OC_EH_RESOURCE_DELETED:
333 responseInfo.result = CA_DELETED;
336 responseInfo.result = CA_SUCCESS;
338 case OC_EH_FORBIDDEN:
339 responseInfo.result = CA_BAD_REQ;
342 responseInfo.result = CA_BAD_REQ;
345 responseInfo.info.type = qualityOfServiceToMessageType(serverRequest->qos);
346 char token[CA_MAX_TOKEN_LEN] = {};
347 responseInfo.info.token = token;
348 memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
349 responseInfo.info.tokenLength = serverRequest->tokenLength;
351 if(serverRequest->observeResult == OC_STACK_OK)
353 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
357 responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions;
360 if(responseInfo.info.numOptions > 0)
362 responseInfo.info.options = (CAHeaderOption_t *)
363 OCCalloc(responseInfo.info.numOptions,
364 sizeof(CAHeaderOption_t));
366 if(!responseInfo.info.options)
368 OC_LOG(FATAL, TAG, PCF("options is NULL"));
369 return OC_STACK_NO_MEMORY;
372 optionsPointer = responseInfo.info.options;
374 // TODO: This exposes CoAP specific details. At some point, this should be
375 // re-factored and handled in the CA layer.
376 if(serverRequest->observeResult == OC_STACK_OK)
378 responseInfo.info.options[0].protocolID = CA_COAP_ID;
379 responseInfo.info.options[0].optionID = COAP_OPTION_OBSERVE;
380 responseInfo.info.options[0].optionLength = sizeof(uint32_t);
381 memcpy(responseInfo.info.options[0].optionData,
382 &(serverRequest->observationOption), sizeof(uint32_t));
384 // Point to the next header option before copying vender specific header options
388 if (ehResponse->numSendVendorSpecificHeaderOptions)
390 memcpy(optionsPointer, ehResponse->sendVendorSpecificHeaderOptions,
391 sizeof(OCHeaderOption) *
392 ehResponse->numSendVendorSpecificHeaderOptions);
397 responseInfo.info.options = NULL;
400 char payload[MAX_RESPONSE_LENGTH] = {};
402 // Put the JSON prefix and suffix around the payload
403 strcpy(payload, (const char *)OC_JSON_PREFIX);
404 strncat(payload, (const char *)ehResponse->payload, ehResponse->payloadSize);
405 strcat(payload, (const char *)OC_JSON_SUFFIX);
406 responseInfo.info.payload = (CAPayload_t)payload;
409 //TODO: Add other connectivity types to CAConnTypes[] when enabled
410 CAConnectivityType_t CAConnTypes[] = {CA_ETHERNET, CA_WIFI};
411 const char * connTypes[] = {"ethernet", "wifi"};
412 int size = sizeof(CAConnTypes)/ sizeof(CAConnectivityType_t);
413 CAConnectivityType_t connType = responseEndpoint.connectivityType;
414 CAResult_t caResult = CA_STATUS_FAILED;
415 result = OC_STACK_OK;
417 //Sending response on all n/w interfaces
418 for(int i = 0; i < size; i++ )
420 responseEndpoint.connectivityType = (CAConnectivityType_t)(connType & CAConnTypes[i]);
421 if(responseEndpoint.connectivityType)
423 //The result is set to OC_STACK_OK only if CASendResponse succeeds in sending the
424 //response on all the n/w interfaces else it is set to OC_STACK_ERROR
425 caResult = CASendResponse(&responseEndpoint, &responseInfo);
426 if(caResult != CA_STATUS_OK)
428 OC_LOG_V(ERROR, TAG, "CASendResponse failed on %s", connTypes[i]);
429 result = CAResultToOCResult(caResult);
433 OC_LOG_V(INFO, TAG, "CASendResponse succeeded on %s", connTypes[i]);
438 CAResult_t caResult = CASendResponse(&responseEndpoint, &responseInfo);
439 if(caResult != CA_STATUS_OK)
441 OC_LOG(ERROR, TAG, PCF("CASendResponse failed"));
442 result = CAResultToOCResult(caResult);
446 result = OC_STACK_OK;
450 OCFree(responseInfo.info.options);
452 FindAndDeleteServerRequest(serverRequest);
456 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
458 OCStackResult stackRet = OC_STACK_ERROR;
459 OCServerRequest * serverRequest = NULL;
460 OCServerResponse * serverResponse = NULL;
461 uint16_t bufferNeeded = 0;
463 if(!ehResponse || !ehResponse->payload)
465 OC_LOG(ERROR, TAG, PCF("HandleAggregateResponse invalid parameters"));
466 return OC_STACK_INVALID_PARAM;
469 OC_LOG_V(INFO, TAG, "Inside HandleAggregateResponse: %s", ehResponse->payload);
471 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
472 serverResponse = GetServerResponseUsingHandle((OCServerRequest *)ehResponse->requestHandle);
478 OC_LOG(INFO, TAG, PCF("This is the first response fragment"));
479 stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle);
480 if (OC_STACK_OK != stackRet)
482 OC_LOG(ERROR, TAG, PCF("Error adding server response"));
485 VERIFY_NON_NULL(serverResponse);
486 VERIFY_NON_NULL(serverResponse->payload);
489 // If there is more than 1 response, then we need to allow for a null-termination
490 // in the server response payload buffer AND the JSON response separator
491 bufferNeeded = ehResponse->payloadSize + 1;
492 if (serverRequest->numResponses > 1)
494 bufferNeeded += strlen(OC_JSON_SEPARATOR_STR);
496 if(serverResponse->remainingPayloadSize >= bufferNeeded)
498 OC_LOG(ERROR, TAG, PCF("There is room in response buffer"));
500 strncat((char *)serverResponse->payload,
501 (char *)ehResponse->payload,
502 serverResponse->remainingPayloadSize);
503 OC_LOG_V(INFO, TAG, "Current aggregated response ...%s", serverResponse->payload);
504 serverResponse->remainingPayloadSize -= strlen((char *)ehResponse->payload);
505 (serverRequest->numResponses)--;
506 if(serverRequest->numResponses == 0)
508 OC_LOG(INFO, TAG, PCF("This is the last response fragment"));
509 ehResponse->payload = serverResponse->payload;
510 ehResponse->payloadSize = strlen((char *) serverResponse->payload) + 1;
511 stackRet = HandleSingleResponse(ehResponse);
512 //Delete the request and response
513 FindAndDeleteServerRequest(serverRequest);
514 FindAndDeleteServerResponse(serverResponse);
518 OC_LOG(INFO, TAG, PCF("More response fragments to come"));
519 strncat((char *)serverResponse->payload,
520 OC_JSON_SEPARATOR_STR,
521 serverResponse->remainingPayloadSize);
522 OC_LOG_V(INFO, TAG, "Current aggregated response ...%s", serverResponse->payload);
523 serverResponse->remainingPayloadSize -= strlen(OC_JSON_SEPARATOR_STR);
524 stackRet = OC_STACK_OK;
529 OC_LOG(ERROR, TAG, PCF("No room in response buffer"));
530 //Delete the request and response
531 FindAndDeleteServerRequest(serverRequest);
532 FindAndDeleteServerResponse(serverResponse);
533 stackRet = OC_STACK_NO_MEMORY;