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 "ocresource"
54 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
55 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
57 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
58 TAG, #arg " is NULL"); return (retVal); } }
60 extern OCResource *headResource;
61 static OCPlatformInfo savedPlatformInfo = {0};
62 static OCDeviceInfo savedDeviceInfo = {0};
65 * Prepares a Payload for response.
67 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
68 OCDiscoveryPayload* payload,
72 //-----------------------------------------------------------------------------
73 // Default resource entity handler function
74 //-----------------------------------------------------------------------------
75 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
76 OCEntityHandlerRequest * request, void* callbackParam)
78 //TODO ("Implement me!!!!");
79 // TODO: remove silence unused param warnings
83 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
86 /* This method will retrieve the port at which the secure resource is hosted */
87 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
91 if (endpoint->adapter == OC_ADAPTER_IP)
93 if (endpoint->flags & OC_IP_USE_V6)
95 p = caglobals.ip.u6s.port;
97 else if (endpoint->flags & OC_IP_USE_V4)
99 p = caglobals.ip.u4s.port;
108 * Function will extract 0, 1 or 2 filters from query.
109 * More than 2 filters or unsupported filters will result in error.
110 * If both filters are of the same supported type, the 2nd one will be picked.
111 * Resource and device filters in the SAME query are NOT validated
112 * and resources will likely not clear filters.
114 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
119 char *restOfQuery = NULL;
120 int numKeyValuePairsParsed = 0;
125 OC_LOG_V(INFO, TAG, "Extracting params from %s", query);
127 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
131 if (numKeyValuePairsParsed >= 2)
133 OC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
134 return OC_STACK_INVALID_QUERY;
137 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
141 return OC_STACK_INVALID_QUERY;
143 else if (strcmp (key, OC_RSRVD_INTERFACE) == 0)
145 *filterOne = value; // if
147 else if (strcmp (key, OC_RSRVD_RESOURCE_TYPE) == 0)
149 *filterTwo = value; // rt
153 OC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
154 return OC_STACK_INVALID_QUERY;
156 ++numKeyValuePairsParsed;
158 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
161 OC_LOG_V(INFO, TAG, "Extracted params %s and %s.", *filterOne, *filterTwo);
165 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
167 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
169 return OC_WELL_KNOWN_URI;
171 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
173 return OC_DEVICE_URI;
175 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
177 return OC_PLATFORM_URI;
179 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
181 return OC_RESOURCE_TYPES_URI;
183 #ifdef ROUTING_GATEWAY
184 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
186 return OC_GATEWAY_URI;
190 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
194 #endif //WITH_PRESENCE
195 return OC_UNKNOWN_URI;
198 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
199 char **filterOne, char **filterTwo)
201 if(!filterOne || !filterTwo)
203 return OC_STACK_INVALID_PARAM;
210 if (uri == OC_PRESENCE)
212 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
213 OC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
218 OCStackResult result = OC_STACK_OK;
222 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
228 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
229 OCRepPayload** payload)
231 OCRepPayload *tempPayload = OCRepPayloadCreate();
235 OCRepPayloadDestroy(tempPayload);
236 return OC_STACK_INVALID_PARAM;
241 return OC_STACK_NO_MEMORY;
244 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
246 OCResourceType *resType = resourcePtr->rsrcType;
249 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
250 resType = resType->next;
253 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
256 OCRepPayloadAddInterface(tempPayload, resInterface->name);
257 resInterface = resInterface->next;
260 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
263 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
264 resAttrib->attrValue);
265 resAttrib = resAttrib->next;
270 *payload = tempPayload;
274 OCRepPayloadAppend(*payload, tempPayload);
280 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
281 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
283 if (!resourcePtr || !payload)
285 return OC_STACK_INVALID_PARAM;
288 if (resourcePtr->resourceProperties & OC_SECURE)
290 if (GetSecurePortInfo(devAddr, &port) != OC_STACK_OK)
298 port = devAddr->port;
301 OCDiscoveryPayloadAddResource(payload, resourcePtr, port);
305 uint8_t IsCollectionResource (OCResource *resource)
312 for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
314 if (resource->rsrcResources[i])
322 OCResource *FindResourceByUri(const char* resourceUri)
329 OCResource * pointer = headResource;
332 if (strcmp(resourceUri, pointer->uri) == 0)
336 pointer = pointer->next;
338 OC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
343 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
344 ResourceHandling *handling,
345 OCResource **resource)
347 if(!request || !handling || !resource)
349 return OC_STACK_INVALID_PARAM;
352 OC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
354 // Check if virtual resource
355 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
357 OC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
358 *handling = OC_RESOURCE_VIRTUAL;
359 *resource = headResource;
362 if (strlen((const char*)(request->resourceUrl)) == 0)
364 // Resource URL not specified
365 *handling = OC_RESOURCE_NOT_SPECIFIED;
366 return OC_STACK_NO_RESOURCE;
370 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
371 *resource = resourcePtr;
374 if(defaultDeviceHandler)
376 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
380 // Resource does not exist
381 // and default device handler does not exist
382 *handling = OC_RESOURCE_NOT_SPECIFIED;
383 return OC_STACK_NO_RESOURCE;
386 if (IsCollectionResource (resourcePtr))
388 // Collection resource
389 if (resourcePtr->entityHandler != defaultResourceEHandler)
391 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
396 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
402 // Resource not a collection
403 if (resourcePtr->entityHandler != defaultResourceEHandler)
405 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
410 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
417 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
419 OCStackResult result;
424 result = OC_STACK_OK;
427 result = OC_STACK_SLOW_RESOURCE;
430 result = OC_STACK_ERROR;
432 case OC_EH_FORBIDDEN:
433 result = OC_STACK_RESOURCE_ERROR;
435 case OC_EH_RESOURCE_CREATED:
436 result = OC_STACK_RESOURCE_CREATED;
438 case OC_EH_RESOURCE_DELETED:
439 result = OC_STACK_RESOURCE_DELETED;
441 case OC_EH_RESOURCE_NOT_FOUND:
442 result = OC_STACK_NO_RESOURCE;
445 result = OC_STACK_ERROR;
451 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
458 // Null or empty is analogous to no filter.
459 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
464 OCResourceType *resourceTypePtr = resource->rsrcType;
466 while (resourceTypePtr)
468 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
472 resourceTypePtr = resourceTypePtr->next;
475 OC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
479 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
486 // Null or empty is analogous to no filter.
487 if (interfaceFilter == NULL || *interfaceFilter == 0)
492 OCResourceInterface *interfacePtr = resource->rsrcInterface;
496 if (strcmp (interfacePtr->name, interfaceFilter) == 0)
500 interfacePtr = interfacePtr->next;
503 OC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
508 * If the filters are null, they will be assumed to NOT be present
509 * and the resource will not be matched against them.
510 * Function will return true if all non null AND non empty filters passed in find a match.
512 static bool includeThisResourceInResponse(OCResource *resource,
513 char *interfaceFilter,
514 char *resourceTypeFilter)
518 OC_LOG(ERROR, TAG, "Invalid resource");
522 if ( resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
525 * At least one valid filter should be available to
526 * include the resource in discovery response
528 if (!((interfaceFilter && *interfaceFilter ) ||
529 (resourceTypeFilter && *resourceTypeFilter)))
531 OC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
532 resource", resource->uri);
536 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
537 !(resource->resourceProperties & OC_DISCOVERABLE))
539 OC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
543 return resourceMatchesIFFilter(resource, interfaceFilter) &&
544 resourceMatchesRTFilter(resource, resourceTypeFilter);
548 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
549 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
551 OCEntityHandlerResponse response = {0};
553 response.ehResult = ehResult;
554 response.payload = discoveryPayload;
555 response.persistentBufferFlag = 0;
556 response.requestHandle = (OCRequestHandle) request;
557 response.resourceHandle = (OCResourceHandle) resource;
559 return OCDoResponse(&response);
563 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
564 OCResource **payload, OCDevAddr *devAddr)
566 OCResourceCollectionPayload *repPayload;
569 return OC_STACK_ERROR;
571 if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
575 return OC_STACK_ERROR;
577 OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
580 return OC_STACK_NO_MEMORY;
583 ptr->uri = OICStrdup(repPayload->setLinks->href);
586 return OC_STACK_NO_MEMORY;
588 OCStringLL *rt = repPayload->setLinks->rt;
591 OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
595 return OC_STACK_NO_MEMORY;
598 temp->resourcetypename = OICStrdup(rt->value);
601 ptr->rsrcType = temp;
605 OCResourceType *type = ptr->rsrcType;
615 OCStringLL *itf = repPayload->setLinks->itf;
618 OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
623 return OC_STACK_NO_MEMORY;
626 temp->name = OICStrdup(itf->value);
627 if (!ptr->rsrcInterface)
629 ptr->rsrcInterface = temp;
633 OCResourceInterface *type = ptr->rsrcInterface;
643 ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
645 OCFreeCollectionResource(repPayload);
651 OC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
652 on the resource directory");
654 return OC_STACK_ERROR;
658 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
660 if (!request || !resource)
662 return OC_STACK_INVALID_PARAM;
665 OCStackResult discoveryResult = OC_STACK_ERROR;
667 bool bMulticast = false; // Was the discovery request a multicast request?
668 OCPayload* payload = NULL;
670 OC_LOG(INFO, TAG, "Entering HandleVirtualResource");
672 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
674 // Step 1: Generate the response to discovery request
675 if (virtualUriInRequest == OC_WELL_KNOWN_URI)
677 char *filterOne = NULL;
678 char *filterTwo = NULL;
680 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
681 &filterOne, &filterTwo);
683 if (discoveryResult == OC_STACK_OK)
685 payload = (OCPayload*)OCDiscoveryPayloadCreate();
689 ((OCDiscoveryPayload*)payload)->sid = (uint8_t*)OICCalloc(1, UUID_SIZE);
690 memcpy(((OCDiscoveryPayload*)payload)->sid, OCGetServerInstanceID(), UUID_SIZE);
692 bool foundResourceAtRD = false;
693 for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
696 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
698 OCResource *resource = NULL;
700 discoveryResult = checkResourceExistsAtRD(filterOne, filterTwo,
701 &resource, &devAddr);
702 if (discoveryResult != OC_STACK_OK)
706 discoveryResult = BuildVirtualResourceResponse(resource,
707 (OCDiscoveryPayload*)payload,
711 ((OCDiscoveryPayload*)payload)->baseURI = OICStrdup(devAddr.addr);
713 foundResourceAtRD = true;
716 if(!foundResourceAtRD && includeThisResourceInResponse(resource, filterOne, filterTwo))
718 discoveryResult = BuildVirtualResourceResponse(resource,
719 (OCDiscoveryPayload*)payload,
720 &request->devAddr, false);
723 // Set discoveryResult appropriately if no 'valid' resources are available
724 if (((OCDiscoveryPayload*)payload)->resources == NULL && !foundResourceAtRD)
726 discoveryResult = OC_STACK_NO_RESOURCE;
731 discoveryResult = OC_STACK_NO_MEMORY;
736 OC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
739 else if (virtualUriInRequest == OC_DEVICE_URI)
741 const OicUuid_t* deviceId = OCGetServerInstanceID();
744 discoveryResult = OC_STACK_ERROR;
748 payload = (OCPayload*) OCDevicePayloadCreate((const uint8_t*) &deviceId->id, savedDeviceInfo.deviceName,
749 OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
752 discoveryResult = OC_STACK_NO_MEMORY;
756 discoveryResult = OC_STACK_OK;
760 else if (virtualUriInRequest == OC_PLATFORM_URI)
762 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
765 discoveryResult = OC_STACK_NO_MEMORY;
769 discoveryResult = OC_STACK_OK;
772 #ifdef ROUTING_GATEWAY
773 else if (OC_GATEWAY_URI == virtualUriInRequest)
775 // Received request for a gateway
776 OC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
777 discoveryResult = RMHandleGatewayRequest(request, resource);
783 * Step 2: Send the discovery response
785 * Iotivity should respond to discovery requests in below manner:
786 * 1)If query filter matching fails and discovery request is multicast,
787 * it should NOT send any response.
788 * 2)If query filter matching fails and discovery request is unicast,
789 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
790 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
791 * request is multicast, it should NOT send any response.
792 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
793 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
797 if ((virtualUriInRequest == OC_PRESENCE) &&
798 (resource->resourceProperties & OC_ACTIVE))
800 // Presence uses observer notification api to respond via SendPresenceNotification.
801 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
805 #ifdef ROUTING_GATEWAY
806 // Gateway uses the RMHandleGatewayRequest to respond to the request.
807 if (OC_GATEWAY_URI != virtualUriInRequest)
810 if(discoveryResult == OC_STACK_OK)
812 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
814 else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
815 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
817 OC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) \
818 discovery request", discoveryResult, virtualUriInRequest);
819 SendNonPersistantDiscoveryResponse(request, resource, NULL,
820 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
824 // Ignoring the discovery request as per RFC 7252, Section #8.2
825 OC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
826 any useful data to send");
830 OCPayloadDestroy(payload);
836 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
840 return OC_STACK_INVALID_PARAM;
843 OCStackResult result = OC_STACK_OK;
844 OCEntityHandlerResult ehResult = OC_EH_ERROR;
845 OCEntityHandlerRequest ehRequest = {0};
847 OC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
848 result = FormOCEntityHandlerRequest(&ehRequest,
849 (OCRequestHandle) request,
852 (OCResourceHandle) NULL, request->query,
853 PAYLOAD_TYPE_REPRESENTATION,
855 request->payloadSize,
856 request->numRcvdVendorSpecificHeaderOptions,
857 request->rcvdVendorSpecificHeaderOptions,
858 (OCObserveAction)request->observationOption,
860 VERIFY_SUCCESS(result, OC_STACK_OK);
862 // At this point we know for sure that defaultDeviceHandler exists
863 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
864 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
865 if(ehResult == OC_EH_SLOW)
867 OC_LOG(INFO, TAG, "This is a slow resource");
868 request->slowFlag = 1;
870 else if(ehResult == OC_EH_ERROR)
872 FindAndDeleteServerRequest(request);
874 result = EntityHandlerCodeToOCStackCode(ehResult);
876 OCPayloadDestroy(ehRequest.payload);
881 HandleResourceWithEntityHandler (OCServerRequest *request,
882 OCResource *resource,
883 uint8_t collectionResource)
885 if(!request || ! resource)
887 return OC_STACK_INVALID_PARAM;
890 OCStackResult result = OC_STACK_ERROR;
891 OCEntityHandlerResult ehResult = OC_EH_ERROR;
892 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
893 ResourceObserver *resObs = NULL;
895 OCEntityHandlerRequest ehRequest = {0};
897 OC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
898 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
899 // check the security resource
900 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
902 type = PAYLOAD_TYPE_SECURITY;
906 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
908 type = PAYLOAD_TYPE_RD;
911 result = FormOCEntityHandlerRequest(&ehRequest,
912 (OCRequestHandle)request,
915 (OCResourceHandle)resource,
919 request->payloadSize,
920 request->numRcvdVendorSpecificHeaderOptions,
921 request->rcvdVendorSpecificHeaderOptions,
922 (OCObserveAction)request->observationOption,
924 VERIFY_SUCCESS(result, OC_STACK_OK);
926 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
928 OC_LOG(INFO, TAG, "No observation requested");
929 ehFlag = OC_REQUEST_FLAG;
931 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
933 OC_LOG(INFO, TAG, "Observation registration requested");
935 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
936 request->tokenLength);
940 OC_LOG (INFO, TAG, "Observer with this token already present");
941 OC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
942 OC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
943 OC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
945 // server requests are usually free'd when the response is sent out
946 // for the request in ocserverrequest.c : HandleSingleResponse()
947 // Since we are making an early return and not responding, the server request
948 // needs to be deleted.
949 FindAndDeleteServerRequest (request);
953 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
954 VERIFY_SUCCESS(result, OC_STACK_OK);
956 result = AddObserver ((const char*)(request->resourceUrl),
957 (const char *)(request->query),
958 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
959 resource, request->qos, request->acceptFormat,
962 if(result == OC_STACK_OK)
964 OC_LOG(INFO, TAG, "Added observer successfully");
965 request->observeResult = OC_STACK_OK;
966 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
970 result = OC_STACK_OK;
972 // The error in observeResult for the request will be used when responding to this
973 // request by omitting the observation option/sequence number.
974 request->observeResult = OC_STACK_ERROR;
975 OC_LOG(ERROR, TAG, "Observer Addition failed");
976 ehFlag = OC_REQUEST_FLAG;
980 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
983 OC_LOG(INFO, TAG, "Deregistering observation requested");
985 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
989 // Stack does not contain this observation request
990 // Either token is incorrect or observation list is corrupted
991 result = OC_STACK_ERROR;
994 ehRequest.obsInfo.obsId = resObs->observeId;
995 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
997 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
999 if(result == OC_STACK_OK)
1001 OC_LOG(INFO, TAG, "Removed observer successfully");
1002 request->observeResult = OC_STACK_OK;
1006 result = OC_STACK_OK;
1007 request->observeResult = OC_STACK_ERROR;
1008 OC_LOG(ERROR, TAG, "Observer Removal failed");
1013 result = OC_STACK_ERROR;
1017 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1018 if(ehResult == OC_EH_SLOW)
1020 OC_LOG(INFO, TAG, "This is a slow resource");
1021 request->slowFlag = 1;
1023 else if(ehResult == OC_EH_ERROR)
1025 FindAndDeleteServerRequest(request);
1027 result = EntityHandlerCodeToOCStackCode(ehResult);
1029 OCPayloadDestroy(ehRequest.payload);
1033 static OCStackResult
1034 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1035 OCResource *resource)
1037 if(!request || !resource)
1039 return OC_STACK_INVALID_PARAM;
1042 OCStackResult result = OC_STACK_ERROR;
1043 OCEntityHandlerRequest ehRequest = {0};
1045 result = FormOCEntityHandlerRequest(&ehRequest,
1046 (OCRequestHandle)request,
1049 (OCResourceHandle)resource,
1051 PAYLOAD_TYPE_REPRESENTATION,
1053 request->payloadSize,
1054 request->numRcvdVendorSpecificHeaderOptions,
1055 request->rcvdVendorSpecificHeaderOptions,
1056 (OCObserveAction)request->observationOption,
1057 (OCObservationId)0);
1058 if(result == OC_STACK_OK)
1060 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1063 OCPayloadDestroy(ehRequest.payload);
1068 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1070 OCStackResult ret = OC_STACK_OK;
1072 switch (resHandling)
1074 case OC_RESOURCE_VIRTUAL:
1076 ret = HandleVirtualResource (request, resource);
1079 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1081 ret = HandleDefaultDeviceEntityHandler(request);
1084 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1086 OC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1087 return OC_STACK_ERROR;
1089 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1091 ret = HandleResourceWithEntityHandler (request, resource, 0);
1094 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1096 ret = HandleResourceWithEntityHandler (request, resource, 1);
1099 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1101 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1104 case OC_RESOURCE_NOT_SPECIFIED:
1106 ret = OC_STACK_NO_RESOURCE;
1111 OC_LOG(INFO, TAG, "Invalid Resource Determination");
1112 return OC_STACK_ERROR;
1118 void DeletePlatformInfo()
1120 OC_LOG(INFO, TAG, "Deleting platform info.");
1122 OICFree(savedPlatformInfo.platformID);
1123 savedPlatformInfo.platformID = NULL;
1125 OICFree(savedPlatformInfo.manufacturerName);
1126 savedPlatformInfo.manufacturerName = NULL;
1128 OICFree(savedPlatformInfo.manufacturerUrl);
1129 savedPlatformInfo.manufacturerUrl = NULL;
1131 OICFree(savedPlatformInfo.modelNumber);
1132 savedPlatformInfo.modelNumber = NULL;
1134 OICFree(savedPlatformInfo.dateOfManufacture);
1135 savedPlatformInfo.dateOfManufacture = NULL;
1137 OICFree(savedPlatformInfo.platformVersion);
1138 savedPlatformInfo.platformVersion = NULL;
1140 OICFree(savedPlatformInfo.operatingSystemVersion);
1141 savedPlatformInfo.operatingSystemVersion = NULL;
1143 OICFree(savedPlatformInfo.hardwareVersion);
1144 savedPlatformInfo.hardwareVersion = NULL;
1146 OICFree(savedPlatformInfo.firmwareVersion);
1147 savedPlatformInfo.firmwareVersion = NULL;
1149 OICFree(savedPlatformInfo.supportUrl);
1150 savedPlatformInfo.supportUrl = NULL;
1152 OICFree(savedPlatformInfo.systemTime);
1153 savedPlatformInfo.systemTime = NULL;
1156 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1158 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1159 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1160 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1161 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1162 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1163 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1164 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1165 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1166 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1167 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1168 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1170 if ((!savedPlatformInfo.platformID && info.platformID)||
1171 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1172 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1173 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1174 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1175 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1176 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1177 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1178 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1179 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1180 (!savedPlatformInfo.systemTime && info.systemTime))
1182 DeletePlatformInfo();
1183 return OC_STACK_INVALID_PARAM;
1190 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1192 DeletePlatformInfo();
1194 OCStackResult res = DeepCopyPlatFormInfo(info);
1196 if (res != OC_STACK_OK)
1198 OC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1202 OC_LOG(INFO, TAG, "Platform info saved.");
1208 void DeleteDeviceInfo()
1210 OC_LOG(INFO, TAG, "Deleting device info.");
1212 OICFree(savedDeviceInfo.deviceName);
1213 savedDeviceInfo.deviceName = NULL;
1216 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1218 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1220 if(!savedDeviceInfo.deviceName && info.deviceName)
1223 return OC_STACK_NO_MEMORY;
1229 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1231 OCStackResult res = OC_STACK_OK;
1235 res = DeepCopyDeviceInfo(info);
1237 VERIFY_SUCCESS(res, OC_STACK_OK);
1239 if(OCGetServerInstanceID() == NULL)
1241 OC_LOG(INFO, TAG, "Device ID generation failed");
1242 res = OC_STACK_ERROR;
1246 OC_LOG(INFO, TAG, "Device initialized successfully.");