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
29 #include "ocresource.h"
30 #include "ocresourcehandler.h"
31 #include "ocobserve.h"
32 #include "occollection.h"
33 #include "oic_malloc.h"
34 #include "oic_string.h"
37 #include "ocpayload.h"
38 #include "secureresourcemanager.h"
40 #include "cainterface.h"
41 #include "rdpayload.h"
42 #include "ocpayload.h"
45 #include "rd_server.h"
48 #ifdef ROUTING_GATEWAY
49 #include "routingmanager.h"
53 #define TAG "OIC_RI_RESOURCE"
55 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
56 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
58 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
59 TAG, #arg " is NULL"); return (retVal); } }
61 extern OCResource *headResource;
62 static OCPlatformInfo savedPlatformInfo = {0};
63 static OCDeviceInfo savedDeviceInfo = {0};
66 * Prepares a Payload for response.
68 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
69 OCDiscoveryPayload* payload,
73 //-----------------------------------------------------------------------------
74 // Default resource entity handler function
75 //-----------------------------------------------------------------------------
76 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
77 OCEntityHandlerRequest * request, void* callbackParam)
79 //TODO ("Implement me!!!!");
80 // TODO: remove silence unused param warnings
84 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
87 /* This method will retrieve the port at which the secure resource is hosted */
88 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
92 if (endpoint->adapter == OC_ADAPTER_IP)
94 if (endpoint->flags & OC_IP_USE_V6)
96 p = caglobals.ip.u6s.port;
98 else if (endpoint->flags & OC_IP_USE_V4)
100 p = caglobals.ip.u4s.port;
109 * Function will extract 0, 1 or 2 filters from query.
110 * More than 2 filters or unsupported filters will result in error.
111 * If both filters are of the same supported type, the 2nd one will be picked.
112 * Resource and device filters in the SAME query are NOT validated
113 * and resources will likely not clear filters.
115 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
120 char *restOfQuery = NULL;
121 int numKeyValuePairsParsed = 0;
126 OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
128 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
132 if (numKeyValuePairsParsed >= 2)
134 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
135 return OC_STACK_INVALID_QUERY;
138 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
142 return OC_STACK_INVALID_QUERY;
144 else if (strcmp (key, OC_RSRVD_INTERFACE) == 0)
146 *filterOne = value; // if
148 else if (strcmp (key, OC_RSRVD_RESOURCE_TYPE) == 0)
150 *filterTwo = value; // rt
154 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
155 return OC_STACK_INVALID_QUERY;
157 ++numKeyValuePairsParsed;
159 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
162 OIC_LOG_V(INFO, TAG, "Extracted params %s and %s.", *filterOne, *filterTwo);
166 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
168 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
170 return OC_WELL_KNOWN_URI;
172 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
174 return OC_DEVICE_URI;
176 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
178 return OC_PLATFORM_URI;
180 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
182 return OC_RESOURCE_TYPES_URI;
184 #ifdef ROUTING_GATEWAY
185 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
187 return OC_GATEWAY_URI;
191 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
195 #endif //WITH_PRESENCE
196 return OC_UNKNOWN_URI;
199 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
200 char **filterOne, char **filterTwo)
202 if(!filterOne || !filterTwo)
204 return OC_STACK_INVALID_PARAM;
211 if (uri == OC_PRESENCE)
213 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
214 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
219 OCStackResult result = OC_STACK_OK;
223 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
229 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
230 OCRepPayload** payload)
232 OCRepPayload *tempPayload = OCRepPayloadCreate();
236 OCRepPayloadDestroy(tempPayload);
237 return OC_STACK_INVALID_PARAM;
242 return OC_STACK_NO_MEMORY;
245 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
247 OCResourceType *resType = resourcePtr->rsrcType;
250 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
251 resType = resType->next;
254 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
257 OCRepPayloadAddInterface(tempPayload, resInterface->name);
258 resInterface = resInterface->next;
261 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
264 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
265 resAttrib->attrValue);
266 resAttrib = resAttrib->next;
271 *payload = tempPayload;
275 OCRepPayloadAppend(*payload, tempPayload);
281 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
282 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
284 if (!resourcePtr || !payload)
286 return OC_STACK_INVALID_PARAM;
289 if (resourcePtr->resourceProperties & OC_SECURE)
291 if (GetSecurePortInfo(devAddr, &port) != OC_STACK_OK)
299 port = devAddr->port;
302 OCDiscoveryPayloadAddResource(payload, resourcePtr, port);
306 uint8_t IsCollectionResource (OCResource *resource)
313 if(resource->rsrcChildResourcesHead != NULL)
321 OCResource *FindResourceByUri(const char* resourceUri)
328 OCResource * pointer = headResource;
331 if (strcmp(resourceUri, pointer->uri) == 0)
335 pointer = pointer->next;
337 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
342 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
343 ResourceHandling *handling,
344 OCResource **resource)
346 if(!request || !handling || !resource)
348 return OC_STACK_INVALID_PARAM;
351 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
353 // Check if virtual resource
354 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
356 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
357 *handling = OC_RESOURCE_VIRTUAL;
358 *resource = headResource;
361 if (strlen((const char*)(request->resourceUrl)) == 0)
363 // Resource URL not specified
364 *handling = OC_RESOURCE_NOT_SPECIFIED;
365 return OC_STACK_NO_RESOURCE;
369 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
370 *resource = resourcePtr;
373 if(defaultDeviceHandler)
375 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
379 // Resource does not exist
380 // and default device handler does not exist
381 *handling = OC_RESOURCE_NOT_SPECIFIED;
382 return OC_STACK_NO_RESOURCE;
385 if (IsCollectionResource (resourcePtr))
387 // Collection resource
388 if (resourcePtr->entityHandler != defaultResourceEHandler)
390 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
395 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
401 // Resource not a collection
402 if (resourcePtr->entityHandler != defaultResourceEHandler)
404 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
409 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
416 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
418 OCStackResult result;
423 result = OC_STACK_OK;
426 result = OC_STACK_SLOW_RESOURCE;
429 result = OC_STACK_ERROR;
431 case OC_EH_FORBIDDEN:
432 result = OC_STACK_RESOURCE_ERROR;
434 case OC_EH_RESOURCE_CREATED:
435 result = OC_STACK_RESOURCE_CREATED;
437 case OC_EH_RESOURCE_DELETED:
438 result = OC_STACK_RESOURCE_DELETED;
440 case OC_EH_RESOURCE_NOT_FOUND:
441 result = OC_STACK_NO_RESOURCE;
444 result = OC_STACK_ERROR;
450 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
457 // Null or empty is analogous to no filter.
458 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
463 OCResourceType *resourceTypePtr = resource->rsrcType;
465 while (resourceTypePtr)
467 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
471 resourceTypePtr = resourceTypePtr->next;
474 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
478 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
485 // Null or empty is analogous to no filter.
486 if (interfaceFilter == NULL || *interfaceFilter == 0)
491 OCResourceInterface *interfacePtr = resource->rsrcInterface;
495 if (strcmp (interfacePtr->name, interfaceFilter) == 0)
499 interfacePtr = interfacePtr->next;
502 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
507 * If the filters are null, they will be assumed to NOT be present
508 * and the resource will not be matched against them.
509 * Function will return true if all non null AND non empty filters passed in find a match.
511 static bool includeThisResourceInResponse(OCResource *resource,
512 char *interfaceFilter,
513 char *resourceTypeFilter)
517 OIC_LOG(ERROR, TAG, "Invalid resource");
521 if ( resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
524 * At least one valid filter should be available to
525 * include the resource in discovery response
527 if (!((interfaceFilter && *interfaceFilter ) ||
528 (resourceTypeFilter && *resourceTypeFilter)))
530 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
531 resource", resource->uri);
535 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
536 !(resource->resourceProperties & OC_DISCOVERABLE))
538 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
542 return resourceMatchesIFFilter(resource, interfaceFilter) &&
543 resourceMatchesRTFilter(resource, resourceTypeFilter);
547 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
548 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
550 OCEntityHandlerResponse response = {0};
552 response.ehResult = ehResult;
553 response.payload = discoveryPayload;
554 response.persistentBufferFlag = 0;
555 response.requestHandle = (OCRequestHandle) request;
556 response.resourceHandle = (OCResourceHandle) resource;
558 return OCDoResponse(&response);
562 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
563 OCResource **payload, OCDevAddr *devAddr)
565 OCResourceCollectionPayload *repPayload;
568 return OC_STACK_ERROR;
570 if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
574 return OC_STACK_ERROR;
576 OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
579 return OC_STACK_NO_MEMORY;
582 ptr->uri = OICStrdup(repPayload->setLinks->href);
585 return OC_STACK_NO_MEMORY;
587 OCStringLL *rt = repPayload->setLinks->rt;
590 OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
594 return OC_STACK_NO_MEMORY;
597 temp->resourcetypename = OICStrdup(rt->value);
600 ptr->rsrcType = temp;
604 OCResourceType *type = ptr->rsrcType;
614 OCStringLL *itf = repPayload->setLinks->itf;
617 OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
622 return OC_STACK_NO_MEMORY;
625 temp->name = OICStrdup(itf->value);
626 if (!ptr->rsrcInterface)
628 ptr->rsrcInterface = temp;
632 OCResourceInterface *type = ptr->rsrcInterface;
642 ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
644 OCFreeCollectionResource(repPayload);
650 OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
651 on the resource directory");
653 return OC_STACK_ERROR;
657 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
659 if (!request || !resource)
661 return OC_STACK_INVALID_PARAM;
664 OCStackResult discoveryResult = OC_STACK_ERROR;
666 bool bMulticast = false; // Was the discovery request a multicast request?
667 OCPayload* payload = NULL;
669 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
671 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
673 // Step 1: Generate the response to discovery request
674 if (virtualUriInRequest == OC_WELL_KNOWN_URI)
676 char *filterOne = NULL;
677 char *filterTwo = NULL;
679 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
680 &filterOne, &filterTwo);
682 if (discoveryResult == OC_STACK_OK)
684 payload = (OCPayload*)OCDiscoveryPayloadCreate();
688 ((OCDiscoveryPayload*)payload)->sid = (uint8_t*)OICCalloc(1, UUID_SIZE);
689 memcpy(((OCDiscoveryPayload*)payload)->sid, OCGetServerInstanceID(), UUID_SIZE);
691 bool foundResourceAtRD = false;
692 for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
695 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
697 OCResource *resource = NULL;
699 discoveryResult = checkResourceExistsAtRD(filterOne, filterTwo,
700 &resource, &devAddr);
701 if (discoveryResult != OC_STACK_OK)
705 discoveryResult = BuildVirtualResourceResponse(resource,
706 (OCDiscoveryPayload*)payload,
710 ((OCDiscoveryPayload*)payload)->baseURI = OICStrdup(devAddr.addr);
712 foundResourceAtRD = true;
715 if(!foundResourceAtRD && includeThisResourceInResponse(resource, filterOne, filterTwo))
717 discoveryResult = BuildVirtualResourceResponse(resource,
718 (OCDiscoveryPayload*)payload,
719 &request->devAddr, false);
722 // Set discoveryResult appropriately if no 'valid' resources are available
723 if (((OCDiscoveryPayload*)payload)->resources == NULL && !foundResourceAtRD)
725 discoveryResult = OC_STACK_NO_RESOURCE;
730 discoveryResult = OC_STACK_NO_MEMORY;
735 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
738 else if (virtualUriInRequest == OC_DEVICE_URI)
740 const OicUuid_t* deviceId = OCGetServerInstanceID();
743 discoveryResult = OC_STACK_ERROR;
747 payload = (OCPayload*) OCDevicePayloadCreate((const uint8_t*) &deviceId->id, savedDeviceInfo.deviceName,
748 OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
751 discoveryResult = OC_STACK_NO_MEMORY;
755 discoveryResult = OC_STACK_OK;
759 else if (virtualUriInRequest == OC_PLATFORM_URI)
761 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
764 discoveryResult = OC_STACK_NO_MEMORY;
768 discoveryResult = OC_STACK_OK;
771 #ifdef ROUTING_GATEWAY
772 else if (OC_GATEWAY_URI == virtualUriInRequest)
774 // Received request for a gateway
775 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
776 discoveryResult = RMHandleGatewayRequest(request, resource);
782 * Step 2: Send the discovery response
784 * Iotivity should respond to discovery requests in below manner:
785 * 1)If query filter matching fails and discovery request is multicast,
786 * it should NOT send any response.
787 * 2)If query filter matching fails and discovery request is unicast,
788 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
789 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
790 * request is multicast, it should NOT send any response.
791 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
792 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
796 if ((virtualUriInRequest == OC_PRESENCE) &&
797 (resource->resourceProperties & OC_ACTIVE))
799 // Presence uses observer notification api to respond via SendPresenceNotification.
800 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
804 #ifdef ROUTING_GATEWAY
805 // Gateway uses the RMHandleGatewayRequest to respond to the request.
806 if (OC_GATEWAY_URI != virtualUriInRequest)
809 if(discoveryResult == OC_STACK_OK)
811 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
813 else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
814 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
816 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) \
817 discovery request", discoveryResult, virtualUriInRequest);
818 SendNonPersistantDiscoveryResponse(request, resource, NULL,
819 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
823 // Ignoring the discovery request as per RFC 7252, Section #8.2
824 OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
825 any useful data to send");
829 OCPayloadDestroy(payload);
835 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
839 return OC_STACK_INVALID_PARAM;
842 OCStackResult result = OC_STACK_OK;
843 OCEntityHandlerResult ehResult = OC_EH_ERROR;
844 OCEntityHandlerRequest ehRequest = {0};
846 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
847 result = FormOCEntityHandlerRequest(&ehRequest,
848 (OCRequestHandle) request,
851 (OCResourceHandle) NULL, request->query,
852 PAYLOAD_TYPE_REPRESENTATION,
854 request->payloadSize,
855 request->numRcvdVendorSpecificHeaderOptions,
856 request->rcvdVendorSpecificHeaderOptions,
857 (OCObserveAction)request->observationOption,
859 VERIFY_SUCCESS(result, OC_STACK_OK);
861 // At this point we know for sure that defaultDeviceHandler exists
862 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
863 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
864 if(ehResult == OC_EH_SLOW)
866 OIC_LOG(INFO, TAG, "This is a slow resource");
867 request->slowFlag = 1;
869 else if(ehResult == OC_EH_ERROR)
871 FindAndDeleteServerRequest(request);
873 result = EntityHandlerCodeToOCStackCode(ehResult);
875 OCPayloadDestroy(ehRequest.payload);
880 HandleResourceWithEntityHandler (OCServerRequest *request,
881 OCResource *resource,
882 uint8_t collectionResource)
884 if(!request || ! resource)
886 return OC_STACK_INVALID_PARAM;
889 OCStackResult result = OC_STACK_ERROR;
890 OCEntityHandlerResult ehResult = OC_EH_ERROR;
891 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
892 ResourceObserver *resObs = NULL;
894 OCEntityHandlerRequest ehRequest = {0};
896 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
897 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
898 // check the security resource
899 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
901 type = PAYLOAD_TYPE_SECURITY;
905 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
907 type = PAYLOAD_TYPE_RD;
910 result = FormOCEntityHandlerRequest(&ehRequest,
911 (OCRequestHandle)request,
914 (OCResourceHandle)resource,
918 request->payloadSize,
919 request->numRcvdVendorSpecificHeaderOptions,
920 request->rcvdVendorSpecificHeaderOptions,
921 (OCObserveAction)request->observationOption,
923 VERIFY_SUCCESS(result, OC_STACK_OK);
925 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
927 OIC_LOG(INFO, TAG, "No observation requested");
928 ehFlag = OC_REQUEST_FLAG;
930 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
932 OIC_LOG(INFO, TAG, "Observation registration requested");
934 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
935 request->tokenLength);
939 OIC_LOG (INFO, TAG, "Observer with this token already present");
940 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
941 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
942 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
944 // server requests are usually free'd when the response is sent out
945 // for the request in ocserverrequest.c : HandleSingleResponse()
946 // Since we are making an early return and not responding, the server request
947 // needs to be deleted.
948 FindAndDeleteServerRequest (request);
952 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
953 VERIFY_SUCCESS(result, OC_STACK_OK);
955 result = AddObserver ((const char*)(request->resourceUrl),
956 (const char *)(request->query),
957 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
958 resource, request->qos, request->acceptFormat,
961 if(result == OC_STACK_OK)
963 OIC_LOG(INFO, TAG, "Added observer successfully");
964 request->observeResult = OC_STACK_OK;
965 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
969 result = OC_STACK_OK;
971 // The error in observeResult for the request will be used when responding to this
972 // request by omitting the observation option/sequence number.
973 request->observeResult = OC_STACK_ERROR;
974 OIC_LOG(ERROR, TAG, "Observer Addition failed");
975 ehFlag = OC_REQUEST_FLAG;
979 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
982 OIC_LOG(INFO, TAG, "Deregistering observation requested");
984 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
988 // Stack does not contain this observation request
989 // Either token is incorrect or observation list is corrupted
990 result = OC_STACK_ERROR;
993 ehRequest.obsInfo.obsId = resObs->observeId;
994 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
996 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
998 if(result == OC_STACK_OK)
1000 OIC_LOG(INFO, TAG, "Removed observer successfully");
1001 request->observeResult = OC_STACK_OK;
1005 result = OC_STACK_OK;
1006 request->observeResult = OC_STACK_ERROR;
1007 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1012 result = OC_STACK_ERROR;
1016 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1017 if(ehResult == OC_EH_SLOW)
1019 OIC_LOG(INFO, TAG, "This is a slow resource");
1020 request->slowFlag = 1;
1022 else if(ehResult == OC_EH_ERROR)
1024 FindAndDeleteServerRequest(request);
1026 result = EntityHandlerCodeToOCStackCode(ehResult);
1028 OCPayloadDestroy(ehRequest.payload);
1032 static OCStackResult
1033 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1034 OCResource *resource)
1036 if(!request || !resource)
1038 return OC_STACK_INVALID_PARAM;
1041 OCStackResult result = OC_STACK_ERROR;
1042 OCEntityHandlerRequest ehRequest = {0};
1044 result = FormOCEntityHandlerRequest(&ehRequest,
1045 (OCRequestHandle)request,
1048 (OCResourceHandle)resource,
1050 PAYLOAD_TYPE_REPRESENTATION,
1052 request->payloadSize,
1053 request->numRcvdVendorSpecificHeaderOptions,
1054 request->rcvdVendorSpecificHeaderOptions,
1055 (OCObserveAction)request->observationOption,
1056 (OCObservationId)0);
1057 if(result == OC_STACK_OK)
1059 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1062 OCPayloadDestroy(ehRequest.payload);
1067 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1069 OCStackResult ret = OC_STACK_OK;
1071 switch (resHandling)
1073 case OC_RESOURCE_VIRTUAL:
1075 ret = HandleVirtualResource (request, resource);
1078 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1080 ret = HandleDefaultDeviceEntityHandler(request);
1083 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1085 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1086 return OC_STACK_ERROR;
1088 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1090 ret = HandleResourceWithEntityHandler (request, resource, 0);
1093 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1095 ret = HandleResourceWithEntityHandler (request, resource, 1);
1098 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1100 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1103 case OC_RESOURCE_NOT_SPECIFIED:
1105 ret = OC_STACK_NO_RESOURCE;
1110 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1111 return OC_STACK_ERROR;
1117 void DeletePlatformInfo()
1119 OIC_LOG(INFO, TAG, "Deleting platform info.");
1121 OICFree(savedPlatformInfo.platformID);
1122 savedPlatformInfo.platformID = NULL;
1124 OICFree(savedPlatformInfo.manufacturerName);
1125 savedPlatformInfo.manufacturerName = NULL;
1127 OICFree(savedPlatformInfo.manufacturerUrl);
1128 savedPlatformInfo.manufacturerUrl = NULL;
1130 OICFree(savedPlatformInfo.modelNumber);
1131 savedPlatformInfo.modelNumber = NULL;
1133 OICFree(savedPlatformInfo.dateOfManufacture);
1134 savedPlatformInfo.dateOfManufacture = NULL;
1136 OICFree(savedPlatformInfo.platformVersion);
1137 savedPlatformInfo.platformVersion = NULL;
1139 OICFree(savedPlatformInfo.operatingSystemVersion);
1140 savedPlatformInfo.operatingSystemVersion = NULL;
1142 OICFree(savedPlatformInfo.hardwareVersion);
1143 savedPlatformInfo.hardwareVersion = NULL;
1145 OICFree(savedPlatformInfo.firmwareVersion);
1146 savedPlatformInfo.firmwareVersion = NULL;
1148 OICFree(savedPlatformInfo.supportUrl);
1149 savedPlatformInfo.supportUrl = NULL;
1151 OICFree(savedPlatformInfo.systemTime);
1152 savedPlatformInfo.systemTime = NULL;
1155 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1157 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1158 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1159 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1160 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1161 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1162 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1163 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1164 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1165 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1166 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1167 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1169 if ((!savedPlatformInfo.platformID && info.platformID)||
1170 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1171 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1172 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1173 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1174 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1175 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1176 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1177 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1178 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1179 (!savedPlatformInfo.systemTime && info.systemTime))
1181 DeletePlatformInfo();
1182 return OC_STACK_INVALID_PARAM;
1189 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1191 DeletePlatformInfo();
1193 OCStackResult res = DeepCopyPlatFormInfo(info);
1195 if (res != OC_STACK_OK)
1197 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1201 OIC_LOG(INFO, TAG, "Platform info saved.");
1207 void DeleteDeviceInfo()
1209 OIC_LOG(INFO, TAG, "Deleting device info.");
1211 OICFree(savedDeviceInfo.deviceName);
1212 savedDeviceInfo.deviceName = NULL;
1215 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1217 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1219 if(!savedDeviceInfo.deviceName && info.deviceName)
1222 return OC_STACK_NO_MEMORY;
1228 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1230 OCStackResult res = OC_STACK_OK;
1234 res = DeepCopyDeviceInfo(info);
1236 VERIFY_SUCCESS(res, OC_STACK_OK);
1238 if(OCGetServerInstanceID() == NULL)
1240 OIC_LOG(INFO, TAG, "Device ID generation failed");
1241 res = OC_STACK_ERROR;
1245 OIC_LOG(INFO, TAG, "Device initialized successfully.");