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) &&
502 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
503 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
507 interfacePtr = interfacePtr->next;
510 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
515 * If the filters are null, they will be assumed to NOT be present
516 * and the resource will not be matched against them.
517 * Function will return true if all non null AND non empty filters passed in find a match.
519 static bool includeThisResourceInResponse(OCResource *resource,
520 char *interfaceFilter,
521 char *resourceTypeFilter)
525 OIC_LOG(ERROR, TAG, "Invalid resource");
529 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
532 * At least one valid filter should be available to
533 * include the resource in discovery response
535 if (!(resourceTypeFilter && *resourceTypeFilter))
537 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
538 resource", resource->uri);
542 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
543 !(resource->resourceProperties & OC_DISCOVERABLE))
545 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
549 return resourceMatchesIFFilter(resource, interfaceFilter) &&
550 resourceMatchesRTFilter(resource, resourceTypeFilter);
554 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
555 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
557 OCEntityHandlerResponse response = {0};
559 response.ehResult = ehResult;
560 response.payload = discoveryPayload;
561 response.persistentBufferFlag = 0;
562 response.requestHandle = (OCRequestHandle) request;
563 response.resourceHandle = (OCResourceHandle) resource;
565 return OCDoResponse(&response);
569 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
570 OCResource **payload, OCDevAddr *devAddr)
572 OCResourceCollectionPayload *repPayload;
575 return OC_STACK_ERROR;
577 if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
581 return OC_STACK_ERROR;
583 OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
586 return OC_STACK_NO_MEMORY;
589 ptr->uri = OICStrdup(repPayload->setLinks->href);
592 return OC_STACK_NO_MEMORY;
594 OCStringLL *rt = repPayload->setLinks->rt;
597 OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
601 return OC_STACK_NO_MEMORY;
604 temp->resourcetypename = OICStrdup(rt->value);
607 ptr->rsrcType = temp;
611 OCResourceType *type = ptr->rsrcType;
621 OCStringLL *itf = repPayload->setLinks->itf;
624 OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
629 return OC_STACK_NO_MEMORY;
632 temp->name = OICStrdup(itf->value);
633 if (!ptr->rsrcInterface)
635 ptr->rsrcInterface = temp;
639 OCResourceInterface *type = ptr->rsrcInterface;
649 ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
651 OCFreeCollectionResource(repPayload);
657 OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
658 on the resource directory");
660 return OC_STACK_ERROR;
664 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
666 if (!request || !resource)
668 return OC_STACK_INVALID_PARAM;
671 OCStackResult discoveryResult = OC_STACK_ERROR;
673 bool bMulticast = false; // Was the discovery request a multicast request?
674 OCPayload* payload = NULL;
676 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
678 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
680 // Step 1: Generate the response to discovery request
681 if (virtualUriInRequest == OC_WELL_KNOWN_URI)
683 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
685 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
686 return OC_STACK_UNAUTHORIZED_REQ;
689 char *interfaceQuery = NULL;
690 char *resourceTypeQuery = NULL;
692 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
693 &interfaceQuery, &resourceTypeQuery);
694 bool interfaceQueryAllocated = false;
695 if (!interfaceQuery && !resourceTypeQuery)
697 interfaceQueryAllocated = true;
698 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
701 if (discoveryResult == OC_STACK_OK)
703 payload = (OCPayload *)OCDiscoveryPayloadCreate();
707 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
708 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
709 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
710 memcpy(discPayload->sid, OCGetServerInstanceIDString(), UUID_STRING_SIZE);
711 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
713 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
716 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
718 if (resourceTypeQuery && resourceMatchesRTFilter(resource, resourceTypeQuery))
723 if (resource->resourceProperties & OC_DISCOVERABLE)
730 discoveryResult = BuildVirtualResourceResponse(resource,
731 discPayload, &request->devAddr, false);
737 if ((interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))) ||
740 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
741 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
742 if (savedDeviceInfo.deviceName)
744 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
745 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
747 discPayload->type = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
748 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
749 OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_LL);
750 OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_DEFAULT);
751 VERIFY_NON_NULL(discPayload->interface, ERROR, OC_STACK_NO_MEMORY);
753 bool foundResourceAtRD = false;
754 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
757 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
759 OCResource *resource1 = NULL;
761 discoveryResult = checkResourceExistsAtRD(interfaceQuery,
762 resourceTypeQuery, &resource1, &devAddr);
763 if (discoveryResult != OC_STACK_OK)
767 discoveryResult = BuildVirtualResourceResponse(resource1,
768 discPayload, &devAddr, true);
771 discPayload->baseURI = OICStrdup(devAddr.addr);
773 OCDiscoveryResourceDestroy(resource1);
774 foundResourceAtRD = true;
777 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
779 discoveryResult = BuildVirtualResourceResponse(resource,
780 discPayload, &request->devAddr, false);
783 // Set discoveryResult appropriately if no 'valid' resources are available
784 if (discPayload->resources == NULL && !foundResourceAtRD)
786 discoveryResult = OC_STACK_NO_RESOURCE;
792 discoveryResult = OC_STACK_NO_MEMORY;
797 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
799 if (interfaceQueryAllocated)
801 OICFree(interfaceQuery);
804 else if (virtualUriInRequest == OC_DEVICE_URI)
806 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
808 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
809 return OC_STACK_UNAUTHORIZED_REQ;
812 const char* deviceId = OCGetServerInstanceIDString();
815 discoveryResult = OC_STACK_ERROR;
819 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
820 savedDeviceInfo.types, OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
823 discoveryResult = OC_STACK_NO_MEMORY;
827 discoveryResult = OC_STACK_OK;
831 else if (virtualUriInRequest == OC_PLATFORM_URI)
833 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
835 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
836 return OC_STACK_UNAUTHORIZED_REQ;
839 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
842 discoveryResult = OC_STACK_NO_MEMORY;
846 discoveryResult = OC_STACK_OK;
849 #ifdef ROUTING_GATEWAY
850 else if (OC_GATEWAY_URI == virtualUriInRequest)
852 // Received request for a gateway
853 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
854 discoveryResult = RMHandleGatewayRequest(request, resource);
860 * Step 2: Send the discovery response
862 * Iotivity should respond to discovery requests in below manner:
863 * 1)If query filter matching fails and discovery request is multicast,
864 * it should NOT send any response.
865 * 2)If query filter matching fails and discovery request is unicast,
866 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
867 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
868 * request is multicast, it should NOT send any response.
869 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
870 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
874 if ((virtualUriInRequest == OC_PRESENCE) &&
875 (resource->resourceProperties & OC_ACTIVE))
877 // Presence uses observer notification api to respond via SendPresenceNotification.
878 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
882 #ifdef ROUTING_GATEWAY
883 // Gateway uses the RMHandleGatewayRequest to respond to the request.
884 if (OC_GATEWAY_URI != virtualUriInRequest)
887 if(discoveryResult == OC_STACK_OK)
889 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
891 else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
892 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
894 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) \
895 discovery request", discoveryResult, virtualUriInRequest);
896 SendNonPersistantDiscoveryResponse(request, resource, NULL,
897 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
901 // Ignoring the discovery request as per RFC 7252, Section #8.2
902 OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
903 any useful data to send");
907 OCPayloadDestroy(payload);
913 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
917 return OC_STACK_INVALID_PARAM;
920 OCStackResult result = OC_STACK_OK;
921 OCEntityHandlerResult ehResult = OC_EH_ERROR;
922 OCEntityHandlerRequest ehRequest = {0};
924 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
925 result = FormOCEntityHandlerRequest(&ehRequest,
926 (OCRequestHandle) request,
929 (OCResourceHandle) NULL, request->query,
930 PAYLOAD_TYPE_REPRESENTATION,
932 request->payloadSize,
933 request->numRcvdVendorSpecificHeaderOptions,
934 request->rcvdVendorSpecificHeaderOptions,
935 (OCObserveAction)request->observationOption,
937 VERIFY_SUCCESS(result, OC_STACK_OK);
939 // At this point we know for sure that defaultDeviceHandler exists
940 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
941 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
942 if(ehResult == OC_EH_SLOW)
944 OIC_LOG(INFO, TAG, "This is a slow resource");
945 request->slowFlag = 1;
947 else if(ehResult == OC_EH_ERROR)
949 FindAndDeleteServerRequest(request);
951 result = EntityHandlerCodeToOCStackCode(ehResult);
953 OCPayloadDestroy(ehRequest.payload);
958 HandleResourceWithEntityHandler (OCServerRequest *request,
959 OCResource *resource,
960 uint8_t collectionResource)
962 if(!request || ! resource)
964 return OC_STACK_INVALID_PARAM;
967 OCStackResult result = OC_STACK_ERROR;
968 OCEntityHandlerResult ehResult = OC_EH_ERROR;
969 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
970 ResourceObserver *resObs = NULL;
972 OCEntityHandlerRequest ehRequest = {0};
974 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
975 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
976 // check the security resource
977 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
979 type = PAYLOAD_TYPE_SECURITY;
983 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
985 type = PAYLOAD_TYPE_RD;
988 result = FormOCEntityHandlerRequest(&ehRequest,
989 (OCRequestHandle)request,
992 (OCResourceHandle)resource,
996 request->payloadSize,
997 request->numRcvdVendorSpecificHeaderOptions,
998 request->rcvdVendorSpecificHeaderOptions,
999 (OCObserveAction)request->observationOption,
1001 VERIFY_SUCCESS(result, OC_STACK_OK);
1003 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1005 OIC_LOG(INFO, TAG, "No observation requested");
1006 ehFlag = OC_REQUEST_FLAG;
1008 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
1010 OIC_LOG(INFO, TAG, "Observation registration requested");
1012 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1013 request->tokenLength);
1017 OIC_LOG (INFO, TAG, "Observer with this token already present");
1018 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1019 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1020 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1022 // server requests are usually free'd when the response is sent out
1023 // for the request in ocserverrequest.c : HandleSingleResponse()
1024 // Since we are making an early return and not responding, the server request
1025 // needs to be deleted.
1026 FindAndDeleteServerRequest (request);
1030 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1031 VERIFY_SUCCESS(result, OC_STACK_OK);
1033 result = AddObserver ((const char*)(request->resourceUrl),
1034 (const char *)(request->query),
1035 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1036 resource, request->qos, request->acceptFormat,
1039 if(result == OC_STACK_OK)
1041 OIC_LOG(INFO, TAG, "Added observer successfully");
1042 request->observeResult = OC_STACK_OK;
1043 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1047 result = OC_STACK_OK;
1049 // The error in observeResult for the request will be used when responding to this
1050 // request by omitting the observation option/sequence number.
1051 request->observeResult = OC_STACK_ERROR;
1052 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1053 ehFlag = OC_REQUEST_FLAG;
1057 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1058 !collectionResource)
1060 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1062 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1066 // Stack does not contain this observation request
1067 // Either token is incorrect or observation list is corrupted
1068 result = OC_STACK_ERROR;
1071 ehRequest.obsInfo.obsId = resObs->observeId;
1072 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1074 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1076 if(result == OC_STACK_OK)
1078 OIC_LOG(INFO, TAG, "Removed observer successfully");
1079 request->observeResult = OC_STACK_OK;
1083 result = OC_STACK_OK;
1084 request->observeResult = OC_STACK_ERROR;
1085 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1090 result = OC_STACK_ERROR;
1094 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1095 if(ehResult == OC_EH_SLOW)
1097 OIC_LOG(INFO, TAG, "This is a slow resource");
1098 request->slowFlag = 1;
1100 else if(ehResult == OC_EH_ERROR)
1102 FindAndDeleteServerRequest(request);
1104 result = EntityHandlerCodeToOCStackCode(ehResult);
1106 OCPayloadDestroy(ehRequest.payload);
1110 static OCStackResult
1111 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1112 OCResource *resource)
1114 if(!request || !resource)
1116 return OC_STACK_INVALID_PARAM;
1119 OCStackResult result = OC_STACK_ERROR;
1120 OCEntityHandlerRequest ehRequest = {0};
1122 result = FormOCEntityHandlerRequest(&ehRequest,
1123 (OCRequestHandle)request,
1126 (OCResourceHandle)resource,
1128 PAYLOAD_TYPE_REPRESENTATION,
1130 request->payloadSize,
1131 request->numRcvdVendorSpecificHeaderOptions,
1132 request->rcvdVendorSpecificHeaderOptions,
1133 (OCObserveAction)request->observationOption,
1134 (OCObservationId)0);
1135 if(result == OC_STACK_OK)
1137 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1140 OCPayloadDestroy(ehRequest.payload);
1145 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1147 OCStackResult ret = OC_STACK_OK;
1149 switch (resHandling)
1151 case OC_RESOURCE_VIRTUAL:
1153 ret = HandleVirtualResource (request, resource);
1156 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1158 ret = HandleDefaultDeviceEntityHandler(request);
1161 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1163 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1164 return OC_STACK_ERROR;
1166 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1168 ret = HandleResourceWithEntityHandler (request, resource, 0);
1171 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1173 ret = HandleResourceWithEntityHandler (request, resource, 1);
1176 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1178 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1181 case OC_RESOURCE_NOT_SPECIFIED:
1183 ret = OC_STACK_NO_RESOURCE;
1188 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1189 return OC_STACK_ERROR;
1195 void DeletePlatformInfo()
1197 OIC_LOG(INFO, TAG, "Deleting platform info.");
1199 OICFree(savedPlatformInfo.platformID);
1200 savedPlatformInfo.platformID = NULL;
1202 OICFree(savedPlatformInfo.manufacturerName);
1203 savedPlatformInfo.manufacturerName = NULL;
1205 OICFree(savedPlatformInfo.manufacturerUrl);
1206 savedPlatformInfo.manufacturerUrl = NULL;
1208 OICFree(savedPlatformInfo.modelNumber);
1209 savedPlatformInfo.modelNumber = NULL;
1211 OICFree(savedPlatformInfo.dateOfManufacture);
1212 savedPlatformInfo.dateOfManufacture = NULL;
1214 OICFree(savedPlatformInfo.platformVersion);
1215 savedPlatformInfo.platformVersion = NULL;
1217 OICFree(savedPlatformInfo.operatingSystemVersion);
1218 savedPlatformInfo.operatingSystemVersion = NULL;
1220 OICFree(savedPlatformInfo.hardwareVersion);
1221 savedPlatformInfo.hardwareVersion = NULL;
1223 OICFree(savedPlatformInfo.firmwareVersion);
1224 savedPlatformInfo.firmwareVersion = NULL;
1226 OICFree(savedPlatformInfo.supportUrl);
1227 savedPlatformInfo.supportUrl = NULL;
1229 OICFree(savedPlatformInfo.systemTime);
1230 savedPlatformInfo.systemTime = NULL;
1233 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1235 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1236 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1237 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1238 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1239 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1240 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1241 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1242 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1243 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1244 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1245 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1247 if ((!savedPlatformInfo.platformID && info.platformID)||
1248 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1249 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1250 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1251 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1252 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1253 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1254 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1255 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1256 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1257 (!savedPlatformInfo.systemTime && info.systemTime))
1259 DeletePlatformInfo();
1260 return OC_STACK_INVALID_PARAM;
1267 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1269 DeletePlatformInfo();
1271 OCStackResult res = DeepCopyPlatFormInfo(info);
1273 if (res != OC_STACK_OK)
1275 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1279 OIC_LOG(INFO, TAG, "Platform info saved.");
1285 void DeleteDeviceInfo()
1287 OIC_LOG(INFO, TAG, "Deleting device info.");
1289 OICFree(savedDeviceInfo.deviceName);
1290 OCFreeOCStringLL(savedDeviceInfo.types);
1291 savedDeviceInfo.deviceName = NULL;
1295 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1297 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1299 if(!savedDeviceInfo.deviceName && info.deviceName)
1302 return OC_STACK_NO_MEMORY;
1307 savedDeviceInfo.types = CloneOCStringLL(info.types);
1308 if(!savedDeviceInfo.types && info.types)
1311 return OC_STACK_NO_MEMORY;
1317 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1319 OCStackResult res = OC_STACK_OK;
1323 res = DeepCopyDeviceInfo(info);
1325 VERIFY_SUCCESS(res, OC_STACK_OK);
1327 if (OCGetServerInstanceIDString() == NULL)
1329 OIC_LOG(INFO, TAG, "Device ID generation failed");
1330 res = OC_STACK_ERROR;
1334 OIC_LOG(INFO, TAG, "Device initialized successfully.");