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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1-2001 base
24 // specification (excluding the XSI extension).
25 // For POSIX.1-2001 base specification,
26 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
27 #define _POSIX_C_SOURCE 200112L
35 #include "ocresource.h"
36 #include "ocresourcehandler.h"
37 #include "ocobserve.h"
38 #include "occollection.h"
39 #include "oic_malloc.h"
40 #include "oic_string.h"
43 #include "ocpayload.h"
44 #include "secureresourcemanager.h"
46 #include "cainterface.h"
47 #include "rdpayload.h"
48 #include "ocpayload.h"
51 #include "rd_server.h"
54 #ifdef ROUTING_GATEWAY
55 #include "routingmanager.h"
59 #define TAG "OIC_RI_RESOURCE"
61 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
62 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
64 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
65 TAG, #arg " is NULL"); return (retVal); } }
67 extern OCResource *headResource;
68 static OCPlatformInfo savedPlatformInfo = {0};
69 static OCDeviceInfo savedDeviceInfo = {0};
72 * Prepares a Payload for response.
74 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
75 OCDiscoveryPayload* payload,
79 //-----------------------------------------------------------------------------
80 // Default resource entity handler function
81 //-----------------------------------------------------------------------------
82 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
83 OCEntityHandlerRequest * request, void* callbackParam)
85 //TODO ("Implement me!!!!");
86 // TODO: remove silence unused param warnings
90 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
93 /* This method will retrieve the port at which the secure resource is hosted */
94 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
98 if (endpoint->adapter == OC_ADAPTER_IP)
100 if (endpoint->flags & OC_IP_USE_V6)
102 p = caglobals.ip.u6s.port;
104 else if (endpoint->flags & OC_IP_USE_V4)
106 p = caglobals.ip.u4s.port;
115 * Function will extract 0, 1 or 2 filters from query.
116 * More than 2 filters or unsupported filters will result in error.
117 * If both filters are of the same supported type, the 2nd one will be picked.
118 * Resource and device filters in the SAME query are NOT validated
119 * and resources will likely not clear filters.
121 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
126 char *restOfQuery = NULL;
127 int numKeyValuePairsParsed = 0;
132 OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
134 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
138 if (numKeyValuePairsParsed >= 2)
140 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
141 return OC_STACK_INVALID_QUERY;
144 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
148 return OC_STACK_INVALID_QUERY;
150 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
152 *filterOne = value; // if
154 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
156 *filterTwo = value; // rt
160 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
161 return OC_STACK_INVALID_QUERY;
163 ++numKeyValuePairsParsed;
165 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
168 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
172 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
174 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
176 return OC_WELL_KNOWN_URI;
178 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
180 return OC_DEVICE_URI;
182 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
184 return OC_PLATFORM_URI;
186 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
188 return OC_RESOURCE_TYPES_URI;
190 #ifdef ROUTING_GATEWAY
191 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
193 return OC_GATEWAY_URI;
197 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
201 #endif //WITH_PRESENCE
202 return OC_UNKNOWN_URI;
205 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
206 char **filterOne, char **filterTwo)
208 if(!filterOne || !filterTwo)
210 return OC_STACK_INVALID_PARAM;
217 if (uri == OC_PRESENCE)
219 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
220 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
225 OCStackResult result = OC_STACK_OK;
229 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
235 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
236 OCRepPayload** payload)
238 OCRepPayload *tempPayload = OCRepPayloadCreate();
242 OCRepPayloadDestroy(tempPayload);
243 return OC_STACK_INVALID_PARAM;
248 return OC_STACK_NO_MEMORY;
251 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
253 OCResourceType *resType = resourcePtr->rsrcType;
256 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
257 resType = resType->next;
260 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
263 OCRepPayloadAddInterface(tempPayload, resInterface->name);
264 resInterface = resInterface->next;
267 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
270 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
271 resAttrib->attrValue);
272 resAttrib = resAttrib->next;
277 *payload = tempPayload;
281 OCRepPayloadAppend(*payload, tempPayload);
287 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
288 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
290 if (!resourcePtr || !payload)
292 return OC_STACK_INVALID_PARAM;
295 if (resourcePtr->resourceProperties & OC_SECURE)
297 if (GetSecurePortInfo(devAddr, &port) != OC_STACK_OK)
305 port = devAddr->port;
308 OCDiscoveryPayloadAddResource(payload, resourcePtr, port);
312 uint8_t IsCollectionResource (OCResource *resource)
319 if(resource->rsrcChildResourcesHead != NULL)
327 OCResource *FindResourceByUri(const char* resourceUri)
334 OCResource * pointer = headResource;
337 if (strcmp(resourceUri, pointer->uri) == 0)
341 pointer = pointer->next;
343 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
348 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
349 ResourceHandling *handling,
350 OCResource **resource)
352 if(!request || !handling || !resource)
354 return OC_STACK_INVALID_PARAM;
357 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
359 // Check if virtual resource
360 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
362 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
363 *handling = OC_RESOURCE_VIRTUAL;
364 *resource = headResource;
367 if (strlen((const char*)(request->resourceUrl)) == 0)
369 // Resource URL not specified
370 *handling = OC_RESOURCE_NOT_SPECIFIED;
371 return OC_STACK_NO_RESOURCE;
375 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
376 *resource = resourcePtr;
379 if(defaultDeviceHandler)
381 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
385 // Resource does not exist
386 // and default device handler does not exist
387 *handling = OC_RESOURCE_NOT_SPECIFIED;
388 return OC_STACK_NO_RESOURCE;
391 if (IsCollectionResource (resourcePtr))
393 // Collection resource
394 if (resourcePtr->entityHandler != defaultResourceEHandler)
396 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
401 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
407 // Resource not a collection
408 if (resourcePtr->entityHandler != defaultResourceEHandler)
410 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
415 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
422 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
424 OCStackResult result;
429 result = OC_STACK_OK;
432 result = OC_STACK_SLOW_RESOURCE;
435 result = OC_STACK_ERROR;
437 case OC_EH_FORBIDDEN:
438 result = OC_STACK_RESOURCE_ERROR;
440 case OC_EH_RESOURCE_CREATED:
441 result = OC_STACK_RESOURCE_CREATED;
443 case OC_EH_RESOURCE_DELETED:
444 result = OC_STACK_RESOURCE_DELETED;
446 case OC_EH_RESOURCE_NOT_FOUND:
447 result = OC_STACK_NO_RESOURCE;
450 result = OC_STACK_ERROR;
456 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
463 // Null or empty is analogous to no filter.
464 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
469 OCResourceType *resourceTypePtr = resource->rsrcType;
471 while (resourceTypePtr)
473 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
477 resourceTypePtr = resourceTypePtr->next;
480 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
484 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
491 // Null or empty is analogous to no filter.
492 if (interfaceFilter == NULL || *interfaceFilter == 0)
497 OCResourceInterface *interfacePtr = resource->rsrcInterface;
501 if (strcmp (interfacePtr->name, interfaceFilter) == 0)
505 interfacePtr = interfacePtr->next;
508 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
513 * If the filters are null, they will be assumed to NOT be present
514 * and the resource will not be matched against them.
515 * Function will return true if all non null AND non empty filters passed in find a match.
517 static bool includeThisResourceInResponse(OCResource *resource,
518 char *interfaceFilter,
519 char *resourceTypeFilter)
523 OIC_LOG(ERROR, TAG, "Invalid resource");
527 if ( resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
530 * At least one valid filter should be available to
531 * include the resource in discovery response
533 if (!((interfaceFilter && *interfaceFilter ) ||
534 (resourceTypeFilter && *resourceTypeFilter)))
536 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
537 resource", resource->uri);
541 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
542 !(resource->resourceProperties & OC_DISCOVERABLE))
544 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
548 return resourceMatchesIFFilter(resource, interfaceFilter) &&
549 resourceMatchesRTFilter(resource, resourceTypeFilter);
553 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
554 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
556 OCEntityHandlerResponse response = {0};
558 response.ehResult = ehResult;
559 response.payload = discoveryPayload;
560 response.persistentBufferFlag = 0;
561 response.requestHandle = (OCRequestHandle) request;
562 response.resourceHandle = (OCResourceHandle) resource;
564 return OCDoResponse(&response);
568 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
569 OCResource **payload, OCDevAddr *devAddr)
571 OCResourceCollectionPayload *repPayload;
574 return OC_STACK_ERROR;
576 if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
580 return OC_STACK_ERROR;
582 OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
585 return OC_STACK_NO_MEMORY;
588 ptr->uri = OICStrdup(repPayload->setLinks->href);
591 return OC_STACK_NO_MEMORY;
593 OCStringLL *rt = repPayload->setLinks->rt;
596 OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
600 return OC_STACK_NO_MEMORY;
603 temp->resourcetypename = OICStrdup(rt->value);
606 ptr->rsrcType = temp;
610 OCResourceType *type = ptr->rsrcType;
620 OCStringLL *itf = repPayload->setLinks->itf;
623 OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
628 return OC_STACK_NO_MEMORY;
631 temp->name = OICStrdup(itf->value);
632 if (!ptr->rsrcInterface)
634 ptr->rsrcInterface = temp;
638 OCResourceInterface *type = ptr->rsrcInterface;
648 ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
650 OCFreeCollectionResource(repPayload);
656 OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
657 on the resource directory");
659 return OC_STACK_ERROR;
663 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
665 if (!request || !resource)
667 return OC_STACK_INVALID_PARAM;
670 OCStackResult discoveryResult = OC_STACK_ERROR;
672 bool bMulticast = false; // Was the discovery request a multicast request?
673 OCPayload* payload = NULL;
675 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
677 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
679 // Step 1: Generate the response to discovery request
680 if (virtualUriInRequest == OC_WELL_KNOWN_URI)
682 char *interfaceQuery = NULL;
683 char *resourceTypeQuery = NULL;
685 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
686 &interfaceQuery, &resourceTypeQuery);
688 if (discoveryResult == OC_STACK_OK)
690 payload = (OCPayload *)OCDiscoveryPayloadCreate();
694 ((OCDiscoveryPayload*)payload)->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
695 VERIFY_NON_NULL(((OCDiscoveryPayload*)payload)->sid, ERROR, OC_STACK_NO_MEMORY);
696 memcpy(((OCDiscoveryPayload*)payload)->sid, OCGetServerInstanceIDString(), UUID_STRING_SIZE);
698 if (interfaceQuery && 0 == strcmp(OC_RSRVD_INTERFACE_LL, interfaceQuery))
700 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
702 discoveryResult = BuildVirtualResourceResponse(resource,
703 (OCDiscoveryPayload *)payload, &request->devAddr, false);
708 bool foundResourceAtRD = false;
709 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
712 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
714 OCResource *resource1 = NULL;
716 discoveryResult = checkResourceExistsAtRD(interfaceQuery,
717 resourceTypeQuery, &resource1, &devAddr);
718 if (discoveryResult != OC_STACK_OK)
722 discoveryResult = BuildVirtualResourceResponse(resource1,
723 (OCDiscoveryPayload*)payload, &devAddr, true);
726 ((OCDiscoveryPayload*)payload)->baseURI = OICStrdup(devAddr.addr);
728 OICFree(resource1->uri);
729 for (OCResourceType *rsrcRt = resource1->rsrcType, *rsrcRtNext = NULL; rsrcRt; )
731 rsrcRtNext = rsrcRt->next;
732 OICFree(rsrcRt->resourcetypename);
737 for (OCResourceInterface *rsrcPtr = resource1->rsrcInterface, *rsrcNext = NULL; rsrcPtr; )
739 rsrcNext = rsrcPtr->next;
740 OICFree(rsrcPtr->name);
744 foundResourceAtRD = true;
747 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
749 discoveryResult = BuildVirtualResourceResponse(resource,
750 (OCDiscoveryPayload*)payload, &request->devAddr, false);
753 // Set discoveryResult appropriately if no 'valid' resources are available
754 if (((OCDiscoveryPayload*)payload)->resources == NULL && !foundResourceAtRD)
756 discoveryResult = OC_STACK_NO_RESOURCE;
762 discoveryResult = OC_STACK_NO_MEMORY;
767 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
770 else if (virtualUriInRequest == OC_DEVICE_URI)
772 const char* deviceId = OCGetServerInstanceIDString();
775 discoveryResult = OC_STACK_ERROR;
779 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
780 savedDeviceInfo.types, OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
783 discoveryResult = OC_STACK_NO_MEMORY;
787 discoveryResult = OC_STACK_OK;
791 else if (virtualUriInRequest == OC_PLATFORM_URI)
793 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
796 discoveryResult = OC_STACK_NO_MEMORY;
800 discoveryResult = OC_STACK_OK;
803 #ifdef ROUTING_GATEWAY
804 else if (OC_GATEWAY_URI == virtualUriInRequest)
806 // Received request for a gateway
807 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
808 discoveryResult = RMHandleGatewayRequest(request, resource);
814 * Step 2: Send the discovery response
816 * Iotivity should respond to discovery requests in below manner:
817 * 1)If query filter matching fails and discovery request is multicast,
818 * it should NOT send any response.
819 * 2)If query filter matching fails and discovery request is unicast,
820 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
821 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
822 * request is multicast, it should NOT send any response.
823 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
824 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
828 if ((virtualUriInRequest == OC_PRESENCE) &&
829 (resource->resourceProperties & OC_ACTIVE))
831 // Presence uses observer notification api to respond via SendPresenceNotification.
832 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
836 #ifdef ROUTING_GATEWAY
837 // Gateway uses the RMHandleGatewayRequest to respond to the request.
838 if (OC_GATEWAY_URI != virtualUriInRequest)
841 if(discoveryResult == OC_STACK_OK)
843 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
845 else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
846 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
848 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) \
849 discovery request", discoveryResult, virtualUriInRequest);
850 SendNonPersistantDiscoveryResponse(request, resource, NULL,
851 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
855 // Ignoring the discovery request as per RFC 7252, Section #8.2
856 OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
857 any useful data to send");
861 OCPayloadDestroy(payload);
867 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
871 return OC_STACK_INVALID_PARAM;
874 OCStackResult result = OC_STACK_OK;
875 OCEntityHandlerResult ehResult = OC_EH_ERROR;
876 OCEntityHandlerRequest ehRequest = {0};
878 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
879 result = FormOCEntityHandlerRequest(&ehRequest,
880 (OCRequestHandle) request,
883 (OCResourceHandle) NULL, request->query,
884 PAYLOAD_TYPE_REPRESENTATION,
886 request->payloadSize,
887 request->numRcvdVendorSpecificHeaderOptions,
888 request->rcvdVendorSpecificHeaderOptions,
889 (OCObserveAction)request->observationOption,
891 VERIFY_SUCCESS(result, OC_STACK_OK);
893 // At this point we know for sure that defaultDeviceHandler exists
894 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
895 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
896 if(ehResult == OC_EH_SLOW)
898 OIC_LOG(INFO, TAG, "This is a slow resource");
899 request->slowFlag = 1;
901 else if(ehResult == OC_EH_ERROR)
903 FindAndDeleteServerRequest(request);
905 result = EntityHandlerCodeToOCStackCode(ehResult);
907 OCPayloadDestroy(ehRequest.payload);
912 HandleResourceWithEntityHandler (OCServerRequest *request,
913 OCResource *resource,
914 uint8_t collectionResource)
916 if(!request || ! resource)
918 return OC_STACK_INVALID_PARAM;
921 OCStackResult result = OC_STACK_ERROR;
922 OCEntityHandlerResult ehResult = OC_EH_ERROR;
923 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
924 ResourceObserver *resObs = NULL;
926 OCEntityHandlerRequest ehRequest = {0};
928 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
929 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
930 // check the security resource
931 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
933 type = PAYLOAD_TYPE_SECURITY;
937 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
939 type = PAYLOAD_TYPE_RD;
942 result = FormOCEntityHandlerRequest(&ehRequest,
943 (OCRequestHandle)request,
946 (OCResourceHandle)resource,
950 request->payloadSize,
951 request->numRcvdVendorSpecificHeaderOptions,
952 request->rcvdVendorSpecificHeaderOptions,
953 (OCObserveAction)request->observationOption,
955 VERIFY_SUCCESS(result, OC_STACK_OK);
957 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
959 OIC_LOG(INFO, TAG, "No observation requested");
960 ehFlag = OC_REQUEST_FLAG;
962 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
964 OIC_LOG(INFO, TAG, "Observation registration requested");
966 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
967 request->tokenLength);
971 OIC_LOG (INFO, TAG, "Observer with this token already present");
972 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
973 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
974 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
976 // server requests are usually free'd when the response is sent out
977 // for the request in ocserverrequest.c : HandleSingleResponse()
978 // Since we are making an early return and not responding, the server request
979 // needs to be deleted.
980 FindAndDeleteServerRequest (request);
984 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
985 VERIFY_SUCCESS(result, OC_STACK_OK);
987 result = AddObserver ((const char*)(request->resourceUrl),
988 (const char *)(request->query),
989 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
990 resource, request->qos, request->acceptFormat,
993 if(result == OC_STACK_OK)
995 OIC_LOG(INFO, TAG, "Added observer successfully");
996 request->observeResult = OC_STACK_OK;
997 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1001 result = OC_STACK_OK;
1003 // The error in observeResult for the request will be used when responding to this
1004 // request by omitting the observation option/sequence number.
1005 request->observeResult = OC_STACK_ERROR;
1006 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1007 ehFlag = OC_REQUEST_FLAG;
1011 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1012 !collectionResource)
1014 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1016 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1020 // Stack does not contain this observation request
1021 // Either token is incorrect or observation list is corrupted
1022 result = OC_STACK_ERROR;
1025 ehRequest.obsInfo.obsId = resObs->observeId;
1026 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1028 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1030 if(result == OC_STACK_OK)
1032 OIC_LOG(INFO, TAG, "Removed observer successfully");
1033 request->observeResult = OC_STACK_OK;
1037 result = OC_STACK_OK;
1038 request->observeResult = OC_STACK_ERROR;
1039 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1044 result = OC_STACK_ERROR;
1048 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1049 if(ehResult == OC_EH_SLOW)
1051 OIC_LOG(INFO, TAG, "This is a slow resource");
1052 request->slowFlag = 1;
1054 else if(ehResult == OC_EH_ERROR)
1056 FindAndDeleteServerRequest(request);
1058 result = EntityHandlerCodeToOCStackCode(ehResult);
1060 OCPayloadDestroy(ehRequest.payload);
1064 static OCStackResult
1065 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1066 OCResource *resource)
1068 if(!request || !resource)
1070 return OC_STACK_INVALID_PARAM;
1073 OCStackResult result = OC_STACK_ERROR;
1074 OCEntityHandlerRequest ehRequest = {0};
1076 result = FormOCEntityHandlerRequest(&ehRequest,
1077 (OCRequestHandle)request,
1080 (OCResourceHandle)resource,
1082 PAYLOAD_TYPE_REPRESENTATION,
1084 request->payloadSize,
1085 request->numRcvdVendorSpecificHeaderOptions,
1086 request->rcvdVendorSpecificHeaderOptions,
1087 (OCObserveAction)request->observationOption,
1088 (OCObservationId)0);
1089 if(result == OC_STACK_OK)
1091 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1094 OCPayloadDestroy(ehRequest.payload);
1099 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1101 OCStackResult ret = OC_STACK_OK;
1103 switch (resHandling)
1105 case OC_RESOURCE_VIRTUAL:
1107 ret = HandleVirtualResource (request, resource);
1110 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1112 ret = HandleDefaultDeviceEntityHandler(request);
1115 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1117 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1118 return OC_STACK_ERROR;
1120 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1122 ret = HandleResourceWithEntityHandler (request, resource, 0);
1125 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1127 ret = HandleResourceWithEntityHandler (request, resource, 1);
1130 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1132 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1135 case OC_RESOURCE_NOT_SPECIFIED:
1137 ret = OC_STACK_NO_RESOURCE;
1142 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1143 return OC_STACK_ERROR;
1149 void DeletePlatformInfo()
1151 OIC_LOG(INFO, TAG, "Deleting platform info.");
1153 OICFree(savedPlatformInfo.platformID);
1154 savedPlatformInfo.platformID = NULL;
1156 OICFree(savedPlatformInfo.manufacturerName);
1157 savedPlatformInfo.manufacturerName = NULL;
1159 OICFree(savedPlatformInfo.manufacturerUrl);
1160 savedPlatformInfo.manufacturerUrl = NULL;
1162 OICFree(savedPlatformInfo.modelNumber);
1163 savedPlatformInfo.modelNumber = NULL;
1165 OICFree(savedPlatformInfo.dateOfManufacture);
1166 savedPlatformInfo.dateOfManufacture = NULL;
1168 OICFree(savedPlatformInfo.platformVersion);
1169 savedPlatformInfo.platformVersion = NULL;
1171 OICFree(savedPlatformInfo.operatingSystemVersion);
1172 savedPlatformInfo.operatingSystemVersion = NULL;
1174 OICFree(savedPlatformInfo.hardwareVersion);
1175 savedPlatformInfo.hardwareVersion = NULL;
1177 OICFree(savedPlatformInfo.firmwareVersion);
1178 savedPlatformInfo.firmwareVersion = NULL;
1180 OICFree(savedPlatformInfo.supportUrl);
1181 savedPlatformInfo.supportUrl = NULL;
1183 OICFree(savedPlatformInfo.systemTime);
1184 savedPlatformInfo.systemTime = NULL;
1187 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1189 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1190 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1191 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1192 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1193 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1194 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1195 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1196 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1197 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1198 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1199 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1201 if ((!savedPlatformInfo.platformID && info.platformID)||
1202 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1203 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1204 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1205 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1206 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1207 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1208 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1209 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1210 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1211 (!savedPlatformInfo.systemTime && info.systemTime))
1213 DeletePlatformInfo();
1214 return OC_STACK_INVALID_PARAM;
1221 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1223 DeletePlatformInfo();
1225 OCStackResult res = DeepCopyPlatFormInfo(info);
1227 if (res != OC_STACK_OK)
1229 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1233 OIC_LOG(INFO, TAG, "Platform info saved.");
1239 void DeleteDeviceInfo()
1241 OIC_LOG(INFO, TAG, "Deleting device info.");
1243 OICFree(savedDeviceInfo.deviceName);
1244 OCFreeOCStringLL(savedDeviceInfo.types);
1245 savedDeviceInfo.deviceName = NULL;
1249 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1251 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1253 if(!savedDeviceInfo.deviceName && info.deviceName)
1256 return OC_STACK_NO_MEMORY;
1261 savedDeviceInfo.types = CloneOCStringLL(info.types);
1262 if(!savedDeviceInfo.types && info.types)
1265 return OC_STACK_NO_MEMORY;
1271 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1273 OCStackResult res = OC_STACK_OK;
1277 res = DeepCopyDeviceInfo(info);
1279 VERIFY_SUCCESS(res, OC_STACK_OK);
1281 if (OCGetServerInstanceIDString() == NULL)
1283 OIC_LOG(INFO, TAG, "Device ID generation failed");
1284 res = OC_STACK_ERROR;
1288 OIC_LOG(INFO, TAG, "Device initialized successfully.");