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 /* This method will retrieve the tcp port */
116 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
120 if (endpoint->adapter == OC_ADAPTER_IP)
122 if (endpoint->flags & OC_IP_USE_V4)
124 p = caglobals.tcp.ipv4.port;
126 else if (endpoint->flags & OC_IP_USE_V6)
128 p = caglobals.tcp.ipv6.port;
138 * Function will extract 0, 1 or 2 filters from query.
139 * More than 2 filters or unsupported filters will result in error.
140 * If both filters are of the same supported type, the 2nd one will be picked.
141 * Resource and device filters in the SAME query are NOT validated
142 * and resources will likely not clear filters.
144 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
149 char *restOfQuery = NULL;
150 int numKeyValuePairsParsed = 0;
155 OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
157 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
161 if (numKeyValuePairsParsed >= 2)
163 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
164 return OC_STACK_INVALID_QUERY;
167 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
171 return OC_STACK_INVALID_QUERY;
173 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
175 *filterOne = value; // if
177 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
179 *filterTwo = value; // rt
183 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
184 return OC_STACK_INVALID_QUERY;
186 ++numKeyValuePairsParsed;
188 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
191 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
195 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
197 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
199 return OC_WELL_KNOWN_URI;
201 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
203 return OC_DEVICE_URI;
205 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
207 return OC_PLATFORM_URI;
209 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
211 return OC_RESOURCE_TYPES_URI;
213 #ifdef ROUTING_GATEWAY
214 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
216 return OC_GATEWAY_URI;
220 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
224 #endif //WITH_PRESENCE
225 return OC_UNKNOWN_URI;
228 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
229 char **filterOne, char **filterTwo)
231 if(!filterOne || !filterTwo)
233 return OC_STACK_INVALID_PARAM;
240 if (uri == OC_PRESENCE)
242 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
243 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
248 OCStackResult result = OC_STACK_OK;
252 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
258 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
259 OCRepPayload** payload)
261 OCRepPayload *tempPayload = OCRepPayloadCreate();
265 OCRepPayloadDestroy(tempPayload);
266 return OC_STACK_INVALID_PARAM;
271 return OC_STACK_NO_MEMORY;
274 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
276 OCResourceType *resType = resourcePtr->rsrcType;
279 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
280 resType = resType->next;
283 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
286 OCRepPayloadAddInterface(tempPayload, resInterface->name);
287 resInterface = resInterface->next;
290 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
293 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
294 resAttrib->attrValue);
295 resAttrib = resAttrib->next;
300 *payload = tempPayload;
304 OCRepPayloadAppend(*payload, tempPayload);
310 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
311 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
313 if (!resourcePtr || !payload)
315 return OC_STACK_INVALID_PARAM;
317 uint16_t securePort = 0;
318 if (resourcePtr->resourceProperties & OC_SECURE)
320 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
328 securePort = devAddr->port;
331 uint16_t tcpPort = 0;
333 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
339 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
343 uint8_t IsCollectionResource (OCResource *resource)
350 if(resource->rsrcChildResourcesHead != NULL)
358 OCResource *FindResourceByUri(const char* resourceUri)
365 OCResource * pointer = headResource;
368 if (strcmp(resourceUri, pointer->uri) == 0)
372 pointer = pointer->next;
374 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
379 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
380 ResourceHandling *handling,
381 OCResource **resource)
383 if(!request || !handling || !resource)
385 return OC_STACK_INVALID_PARAM;
388 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
390 // Check if virtual resource
391 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
393 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
394 *handling = OC_RESOURCE_VIRTUAL;
395 *resource = headResource;
398 if (strlen((const char*)(request->resourceUrl)) == 0)
400 // Resource URL not specified
401 *handling = OC_RESOURCE_NOT_SPECIFIED;
402 return OC_STACK_NO_RESOURCE;
406 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
407 *resource = resourcePtr;
410 if(defaultDeviceHandler)
412 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
416 // Resource does not exist
417 // and default device handler does not exist
418 *handling = OC_RESOURCE_NOT_SPECIFIED;
419 return OC_STACK_NO_RESOURCE;
422 if (IsCollectionResource (resourcePtr))
424 // Collection resource
425 if (resourcePtr->entityHandler != defaultResourceEHandler)
427 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
432 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
438 // Resource not a collection
439 if (resourcePtr->entityHandler != defaultResourceEHandler)
441 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
446 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
453 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
455 OCStackResult result;
460 result = OC_STACK_OK;
463 result = OC_STACK_SLOW_RESOURCE;
466 result = OC_STACK_ERROR;
468 case OC_EH_FORBIDDEN:
469 result = OC_STACK_RESOURCE_ERROR;
471 case OC_EH_RESOURCE_CREATED:
472 result = OC_STACK_RESOURCE_CREATED;
474 case OC_EH_RESOURCE_DELETED:
475 result = OC_STACK_RESOURCE_DELETED;
477 case OC_EH_RESOURCE_NOT_FOUND:
478 result = OC_STACK_NO_RESOURCE;
481 result = OC_STACK_ERROR;
487 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
494 // Null or empty is analogous to no filter.
495 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
500 OCResourceType *resourceTypePtr = resource->rsrcType;
502 while (resourceTypePtr)
504 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
508 resourceTypePtr = resourceTypePtr->next;
511 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
515 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
522 // Null or empty is analogous to no filter.
523 if (interfaceFilter == NULL || *interfaceFilter == 0)
528 OCResourceInterface *interfacePtr = resource->rsrcInterface;
532 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
533 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
534 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
538 interfacePtr = interfacePtr->next;
541 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
546 * If the filters are null, they will be assumed to NOT be present
547 * and the resource will not be matched against them.
548 * Function will return true if all non null AND non empty filters passed in find a match.
550 static bool includeThisResourceInResponse(OCResource *resource,
551 char *interfaceFilter,
552 char *resourceTypeFilter)
556 OIC_LOG(ERROR, TAG, "Invalid resource");
560 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
563 * At least one valid filter should be available to
564 * include the resource in discovery response
566 if (!(resourceTypeFilter && *resourceTypeFilter))
568 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
569 resource", resource->uri);
573 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
574 !(resource->resourceProperties & OC_DISCOVERABLE))
576 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
580 return resourceMatchesIFFilter(resource, interfaceFilter) &&
581 resourceMatchesRTFilter(resource, resourceTypeFilter);
585 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
586 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
588 OCEntityHandlerResponse response = {0};
590 response.ehResult = ehResult;
591 response.payload = discoveryPayload;
592 response.persistentBufferFlag = 0;
593 response.requestHandle = (OCRequestHandle) request;
594 response.resourceHandle = (OCResourceHandle) resource;
596 return OCDoResponse(&response);
600 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
601 OCResource **payload, OCDevAddr *devAddr)
603 OCResourceCollectionPayload *repPayload;
606 return OC_STACK_ERROR;
608 if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
612 return OC_STACK_ERROR;
614 OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
617 return OC_STACK_NO_MEMORY;
620 ptr->uri = OICStrdup(repPayload->setLinks->href);
623 return OC_STACK_NO_MEMORY;
625 OCStringLL *rt = repPayload->setLinks->rt;
628 OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
632 return OC_STACK_NO_MEMORY;
635 temp->resourcetypename = OICStrdup(rt->value);
638 ptr->rsrcType = temp;
642 OCResourceType *type = ptr->rsrcType;
652 OCStringLL *itf = repPayload->setLinks->itf;
655 OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
660 return OC_STACK_NO_MEMORY;
663 temp->name = OICStrdup(itf->value);
664 if (!ptr->rsrcInterface)
666 ptr->rsrcInterface = temp;
670 OCResourceInterface *type = ptr->rsrcInterface;
680 ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
682 OCFreeCollectionResource(repPayload);
688 OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
689 on the resource directory");
691 return OC_STACK_ERROR;
695 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
697 if (!request || !resource)
699 return OC_STACK_INVALID_PARAM;
702 OCStackResult discoveryResult = OC_STACK_ERROR;
704 bool bMulticast = false; // Was the discovery request a multicast request?
705 OCPayload* payload = NULL;
707 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
709 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
711 // Step 1: Generate the response to discovery request
712 if (virtualUriInRequest == OC_WELL_KNOWN_URI)
714 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
716 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
717 return OC_STACK_UNAUTHORIZED_REQ;
720 char *interfaceQuery = NULL;
721 char *resourceTypeQuery = NULL;
723 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
724 &interfaceQuery, &resourceTypeQuery);
725 bool interfaceQueryAllocated = false;
726 if (!interfaceQuery && !resourceTypeQuery)
728 interfaceQueryAllocated = true;
729 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
732 if (discoveryResult == OC_STACK_OK)
734 payload = (OCPayload *)OCDiscoveryPayloadCreate();
738 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
739 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
740 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
741 memcpy(discPayload->sid, OCGetServerInstanceIDString(), UUID_STRING_SIZE);
742 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
744 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
747 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
749 if (resourceTypeQuery && resourceMatchesRTFilter(resource, resourceTypeQuery))
754 if (resource->resourceProperties & OC_DISCOVERABLE)
761 discoveryResult = BuildVirtualResourceResponse(resource,
762 discPayload, &request->devAddr, false);
768 if ((interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))) ||
771 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
772 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
773 if (savedDeviceInfo.deviceName)
775 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
776 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
778 discPayload->type = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
779 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
780 OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_LL);
781 OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_DEFAULT);
782 VERIFY_NON_NULL(discPayload->interface, ERROR, OC_STACK_NO_MEMORY);
784 bool foundResourceAtRD = false;
785 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
788 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
790 OCResource *resource1 = NULL;
792 discoveryResult = checkResourceExistsAtRD(interfaceQuery,
793 resourceTypeQuery, &resource1, &devAddr);
794 if (discoveryResult != OC_STACK_OK)
798 discoveryResult = BuildVirtualResourceResponse(resource1,
799 discPayload, &devAddr, true);
802 discPayload->baseURI = OICStrdup(devAddr.addr);
804 OICFree(resource1->uri);
805 for (OCResourceType *rsrcRt = resource1->rsrcType, *rsrcRtNext = NULL; rsrcRt; )
807 rsrcRtNext = rsrcRt->next;
808 OICFree(rsrcRt->resourcetypename);
813 for (OCResourceInterface *rsrcPtr = resource1->rsrcInterface, *rsrcNext = NULL; rsrcPtr; )
815 rsrcNext = rsrcPtr->next;
816 OICFree(rsrcPtr->name);
820 foundResourceAtRD = true;
823 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
825 discoveryResult = BuildVirtualResourceResponse(resource,
826 discPayload, &request->devAddr, false);
829 // Set discoveryResult appropriately if no 'valid' resources are available
830 if (discPayload->resources == NULL && !foundResourceAtRD)
832 discoveryResult = OC_STACK_NO_RESOURCE;
838 discoveryResult = OC_STACK_NO_MEMORY;
843 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
845 if (interfaceQueryAllocated)
847 OICFree(interfaceQuery);
850 else if (virtualUriInRequest == OC_DEVICE_URI)
852 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
854 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
855 return OC_STACK_UNAUTHORIZED_REQ;
858 const char* deviceId = OCGetServerInstanceIDString();
861 discoveryResult = OC_STACK_ERROR;
865 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
866 savedDeviceInfo.types, OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
869 discoveryResult = OC_STACK_NO_MEMORY;
873 discoveryResult = OC_STACK_OK;
877 else if (virtualUriInRequest == OC_PLATFORM_URI)
879 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
881 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
882 return OC_STACK_UNAUTHORIZED_REQ;
885 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
888 discoveryResult = OC_STACK_NO_MEMORY;
892 discoveryResult = OC_STACK_OK;
895 #ifdef ROUTING_GATEWAY
896 else if (OC_GATEWAY_URI == virtualUriInRequest)
898 // Received request for a gateway
899 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
900 discoveryResult = RMHandleGatewayRequest(request, resource);
906 * Step 2: Send the discovery response
908 * Iotivity should respond to discovery requests in below manner:
909 * 1)If query filter matching fails and discovery request is multicast,
910 * it should NOT send any response.
911 * 2)If query filter matching fails and discovery request is unicast,
912 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
913 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
914 * request is multicast, it should NOT send any response.
915 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
916 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
920 if ((virtualUriInRequest == OC_PRESENCE) &&
921 (resource->resourceProperties & OC_ACTIVE))
923 // Presence uses observer notification api to respond via SendPresenceNotification.
924 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
928 #ifdef ROUTING_GATEWAY
929 // Gateway uses the RMHandleGatewayRequest to respond to the request.
930 if (OC_GATEWAY_URI != virtualUriInRequest)
933 if(discoveryResult == OC_STACK_OK)
935 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
937 else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
938 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
940 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) \
941 discovery request", discoveryResult, virtualUriInRequest);
942 SendNonPersistantDiscoveryResponse(request, resource, NULL,
943 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
947 // Ignoring the discovery request as per RFC 7252, Section #8.2
948 OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
949 any useful data to send");
953 OCPayloadDestroy(payload);
959 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
963 return OC_STACK_INVALID_PARAM;
966 OCStackResult result = OC_STACK_OK;
967 OCEntityHandlerResult ehResult = OC_EH_ERROR;
968 OCEntityHandlerRequest ehRequest = {0};
970 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
971 result = FormOCEntityHandlerRequest(&ehRequest,
972 (OCRequestHandle) request,
975 (OCResourceHandle) NULL, request->query,
976 PAYLOAD_TYPE_REPRESENTATION,
978 request->payloadSize,
979 request->numRcvdVendorSpecificHeaderOptions,
980 request->rcvdVendorSpecificHeaderOptions,
981 (OCObserveAction)request->observationOption,
983 VERIFY_SUCCESS(result, OC_STACK_OK);
985 // At this point we know for sure that defaultDeviceHandler exists
986 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
987 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
988 if(ehResult == OC_EH_SLOW)
990 OIC_LOG(INFO, TAG, "This is a slow resource");
991 request->slowFlag = 1;
993 else if(ehResult == OC_EH_ERROR)
995 FindAndDeleteServerRequest(request);
997 result = EntityHandlerCodeToOCStackCode(ehResult);
999 OCPayloadDestroy(ehRequest.payload);
1003 static OCStackResult
1004 HandleResourceWithEntityHandler (OCServerRequest *request,
1005 OCResource *resource,
1006 uint8_t collectionResource)
1008 if(!request || ! resource)
1010 return OC_STACK_INVALID_PARAM;
1013 OCStackResult result = OC_STACK_ERROR;
1014 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1015 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1016 ResourceObserver *resObs = NULL;
1018 OCEntityHandlerRequest ehRequest = {0};
1020 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1021 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1022 // check the security resource
1023 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1025 type = PAYLOAD_TYPE_SECURITY;
1029 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
1031 type = PAYLOAD_TYPE_RD;
1034 result = FormOCEntityHandlerRequest(&ehRequest,
1035 (OCRequestHandle)request,
1038 (OCResourceHandle)resource,
1042 request->payloadSize,
1043 request->numRcvdVendorSpecificHeaderOptions,
1044 request->rcvdVendorSpecificHeaderOptions,
1045 (OCObserveAction)request->observationOption,
1047 VERIFY_SUCCESS(result, OC_STACK_OK);
1049 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1051 OIC_LOG(INFO, TAG, "No observation requested");
1052 ehFlag = OC_REQUEST_FLAG;
1054 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
1056 OIC_LOG(INFO, TAG, "Observation registration requested");
1058 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1059 request->tokenLength);
1063 OIC_LOG (INFO, TAG, "Observer with this token already present");
1064 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1065 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1066 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1068 // server requests are usually free'd when the response is sent out
1069 // for the request in ocserverrequest.c : HandleSingleResponse()
1070 // Since we are making an early return and not responding, the server request
1071 // needs to be deleted.
1072 FindAndDeleteServerRequest (request);
1076 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1077 VERIFY_SUCCESS(result, OC_STACK_OK);
1079 result = AddObserver ((const char*)(request->resourceUrl),
1080 (const char *)(request->query),
1081 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1082 resource, request->qos, request->acceptFormat,
1085 if(result == OC_STACK_OK)
1087 OIC_LOG(INFO, TAG, "Added observer successfully");
1088 request->observeResult = OC_STACK_OK;
1089 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1093 result = OC_STACK_OK;
1095 // The error in observeResult for the request will be used when responding to this
1096 // request by omitting the observation option/sequence number.
1097 request->observeResult = OC_STACK_ERROR;
1098 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1099 ehFlag = OC_REQUEST_FLAG;
1103 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1104 !collectionResource)
1106 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1108 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1112 // Stack does not contain this observation request
1113 // Either token is incorrect or observation list is corrupted
1114 result = OC_STACK_ERROR;
1117 ehRequest.obsInfo.obsId = resObs->observeId;
1118 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1120 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1122 if(result == OC_STACK_OK)
1124 OIC_LOG(INFO, TAG, "Removed observer successfully");
1125 request->observeResult = OC_STACK_OK;
1129 result = OC_STACK_OK;
1130 request->observeResult = OC_STACK_ERROR;
1131 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1136 result = OC_STACK_ERROR;
1140 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1141 if(ehResult == OC_EH_SLOW)
1143 OIC_LOG(INFO, TAG, "This is a slow resource");
1144 request->slowFlag = 1;
1146 else if(ehResult == OC_EH_ERROR)
1148 FindAndDeleteServerRequest(request);
1150 result = EntityHandlerCodeToOCStackCode(ehResult);
1152 OCPayloadDestroy(ehRequest.payload);
1156 static OCStackResult
1157 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1158 OCResource *resource)
1160 if(!request || !resource)
1162 return OC_STACK_INVALID_PARAM;
1165 OCStackResult result = OC_STACK_ERROR;
1166 OCEntityHandlerRequest ehRequest = {0};
1168 result = FormOCEntityHandlerRequest(&ehRequest,
1169 (OCRequestHandle)request,
1172 (OCResourceHandle)resource,
1174 PAYLOAD_TYPE_REPRESENTATION,
1176 request->payloadSize,
1177 request->numRcvdVendorSpecificHeaderOptions,
1178 request->rcvdVendorSpecificHeaderOptions,
1179 (OCObserveAction)request->observationOption,
1180 (OCObservationId)0);
1181 if(result == OC_STACK_OK)
1183 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1186 OCPayloadDestroy(ehRequest.payload);
1191 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1193 OCStackResult ret = OC_STACK_OK;
1195 switch (resHandling)
1197 case OC_RESOURCE_VIRTUAL:
1199 ret = HandleVirtualResource (request, resource);
1202 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1204 ret = HandleDefaultDeviceEntityHandler(request);
1207 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1209 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1210 return OC_STACK_ERROR;
1212 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1214 ret = HandleResourceWithEntityHandler (request, resource, 0);
1217 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1219 ret = HandleResourceWithEntityHandler (request, resource, 1);
1222 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1224 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1227 case OC_RESOURCE_NOT_SPECIFIED:
1229 ret = OC_STACK_NO_RESOURCE;
1234 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1235 return OC_STACK_ERROR;
1241 void DeletePlatformInfo()
1243 OIC_LOG(INFO, TAG, "Deleting platform info.");
1245 OICFree(savedPlatformInfo.platformID);
1246 savedPlatformInfo.platformID = NULL;
1248 OICFree(savedPlatformInfo.manufacturerName);
1249 savedPlatformInfo.manufacturerName = NULL;
1251 OICFree(savedPlatformInfo.manufacturerUrl);
1252 savedPlatformInfo.manufacturerUrl = NULL;
1254 OICFree(savedPlatformInfo.modelNumber);
1255 savedPlatformInfo.modelNumber = NULL;
1257 OICFree(savedPlatformInfo.dateOfManufacture);
1258 savedPlatformInfo.dateOfManufacture = NULL;
1260 OICFree(savedPlatformInfo.platformVersion);
1261 savedPlatformInfo.platformVersion = NULL;
1263 OICFree(savedPlatformInfo.operatingSystemVersion);
1264 savedPlatformInfo.operatingSystemVersion = NULL;
1266 OICFree(savedPlatformInfo.hardwareVersion);
1267 savedPlatformInfo.hardwareVersion = NULL;
1269 OICFree(savedPlatformInfo.firmwareVersion);
1270 savedPlatformInfo.firmwareVersion = NULL;
1272 OICFree(savedPlatformInfo.supportUrl);
1273 savedPlatformInfo.supportUrl = NULL;
1275 OICFree(savedPlatformInfo.systemTime);
1276 savedPlatformInfo.systemTime = NULL;
1279 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1281 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1282 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1283 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1284 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1285 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1286 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1287 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1288 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1289 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1290 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1291 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1293 if ((!savedPlatformInfo.platformID && info.platformID)||
1294 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1295 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1296 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1297 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1298 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1299 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1300 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1301 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1302 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1303 (!savedPlatformInfo.systemTime && info.systemTime))
1305 DeletePlatformInfo();
1306 return OC_STACK_INVALID_PARAM;
1313 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1315 DeletePlatformInfo();
1317 OCStackResult res = DeepCopyPlatFormInfo(info);
1319 if (res != OC_STACK_OK)
1321 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1325 OIC_LOG(INFO, TAG, "Platform info saved.");
1331 void DeleteDeviceInfo()
1333 OIC_LOG(INFO, TAG, "Deleting device info.");
1335 OICFree(savedDeviceInfo.deviceName);
1336 OCFreeOCStringLL(savedDeviceInfo.types);
1337 savedDeviceInfo.deviceName = NULL;
1341 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1343 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1345 if(!savedDeviceInfo.deviceName && info.deviceName)
1348 return OC_STACK_NO_MEMORY;
1353 savedDeviceInfo.types = CloneOCStringLL(info.types);
1354 if(!savedDeviceInfo.types && info.types)
1357 return OC_STACK_NO_MEMORY;
1363 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1365 OCStackResult res = OC_STACK_OK;
1369 res = DeepCopyDeviceInfo(info);
1371 VERIFY_SUCCESS(res, OC_STACK_OK);
1373 if (OCGetServerInstanceIDString() == NULL)
1375 OIC_LOG(INFO, TAG, "Device ID generation failed");
1376 res = OC_STACK_ERROR;
1380 OIC_LOG(INFO, TAG, "Device initialized successfully.");