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
32 #include "iotivity_config.h"
40 #include "ocresource.h"
41 #include "ocresourcehandler.h"
42 #include "ocobserve.h"
43 #include "occollection.h"
44 #include "oic_malloc.h"
45 #include "oic_string.h"
48 #include "ocpayload.h"
49 #include "secureresourcemanager.h"
51 #include "cainterface.h"
52 #include "ocpayload.h"
53 #include "platform_features.h"
54 #include "payload_logging.h"
55 #ifdef ROUTING_GATEWAY
56 #include "routingmanager.h"
60 #include "rd_database.h"
64 #define TAG "OIC_RI_RESOURCE"
66 #define VERIFY_SUCCESS(op) { if (op != (OC_STACK_OK)) \
67 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
69 extern OCResource *headResource;
72 * Prepares a Payload for response.
74 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
75 OCDiscoveryPayload* payload,
78 //-----------------------------------------------------------------------------
79 // Default resource entity handler function
80 //-----------------------------------------------------------------------------
81 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
82 OCEntityHandlerRequest * request, void* callbackParam)
84 //TODO ("Implement me!!!!");
85 // TODO: remove silence unused param warnings
89 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
92 /* This method will retrieve the port at which the secure resource is hosted */
93 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
97 if (endpoint->adapter == OC_ADAPTER_IP)
99 if (endpoint->flags & OC_IP_USE_V6)
101 p = caglobals.ip.u6s.port;
103 else if (endpoint->flags & OC_IP_USE_V4)
105 p = caglobals.ip.u4s.port;
114 /* This method will retrieve the tcp port */
115 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
119 if (endpoint->adapter == OC_ADAPTER_IP)
121 if (endpoint->flags & OC_IP_USE_V4)
123 p = caglobals.tcp.ipv4.port;
125 else if (endpoint->flags & OC_IP_USE_V6)
127 p = caglobals.tcp.ipv6.port;
137 * Function will extract 0, 1 or 2 filters from query.
138 * More than 2 filters or unsupported filters will result in error.
139 * If both filters are of the same supported type, the 2nd one will be picked.
140 * Resource and device filters in the SAME query are NOT validated
141 * and resources will likely not clear filters.
143 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
147 char *queryDup = NULL;
148 char *restOfQuery = NULL;
149 char *keyValuePair = NULL;
150 int numKeyValuePairsParsed = 0;
155 queryDup = OICStrdup(query);
156 if (NULL == queryDup)
158 OIC_LOG_V(ERROR, TAG, "Creating duplicate string failed!");
159 return OC_STACK_NO_MEMORY;
162 OIC_LOG_V(INFO, TAG, "Extracting params from %s", queryDup);
164 OCStackResult eCode = OC_STACK_INVALID_QUERY;
165 if (strnlen(queryDup, MAX_QUERY_LENGTH) >= MAX_QUERY_LENGTH)
167 OIC_LOG(ERROR, TAG, "Query exceeds maximum length.");
171 keyValuePair = strtok_r (queryDup, OC_QUERY_SEPARATOR, &restOfQuery);
175 if (numKeyValuePairsParsed >= 2)
177 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
181 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
187 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
189 *filterOne = value; // if
191 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
193 *filterTwo = value; // rt
197 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
200 ++numKeyValuePairsParsed;
202 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
207 *filterOne = OICStrdup(*filterOne);
208 if (NULL == *filterOne)
210 OIC_LOG_V(ERROR, TAG, "Creating duplicate string failed!");
211 eCode = OC_STACK_NO_MEMORY;
218 *filterTwo = OICStrdup(*filterTwo);
219 if (NULL == *filterTwo)
221 OIC_LOG_V(ERROR, TAG, "Creating duplicate string failed!");
223 eCode = OC_STACK_NO_MEMORY;
229 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
239 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
241 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
243 return OC_WELL_KNOWN_URI;
245 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
247 return OC_DEVICE_URI;
249 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
251 return OC_PLATFORM_URI;
253 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
255 return OC_RESOURCE_TYPES_URI;
257 #ifdef ROUTING_GATEWAY
258 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
260 return OC_GATEWAY_URI;
264 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
268 #endif //WITH_PRESENCE
271 else if (0 == strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_MQ_URI))
273 return OC_MQ_BROKER_URI;
278 else if (strcmp(uriInRequest, OC_RSRVD_KEEPALIVE_URI) == 0)
280 return OC_KEEPALIVE_RESOURCE_URI;
284 return OC_UNKNOWN_URI;
287 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
288 char **filterOne, char **filterTwo)
290 if(!filterOne || !filterTwo)
292 return OC_STACK_INVALID_PARAM;
299 if (uri == OC_PRESENCE)
301 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
302 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
307 OCStackResult result = OC_STACK_OK;
311 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
317 bool appendOCStringLL(OCRepPayload *device, OCStringLL *dmv)
320 for (OCStringLL *ll = dmv; ll; ll = ll->next, size++);
321 size_t dim[MAX_REP_ARRAY_DEPTH] = {size, 0, 0};
322 char **dt = (char **)OICMalloc(sizeof(char *) * size);
324 VERIFY_PARAM_NON_NULL(TAG, dt, "Data Model Version allocation failed.");
325 for (OCStringLL *ll = dmv; ll; ll = ll->next, i++)
327 dt[i] = OICStrdup(ll->value);
328 VERIFY_PARAM_NON_NULL(TAG, dt[i], "Data Model Version adding failed.");
330 if (!OCRepPayloadSetStringArrayAsOwner(device, OC_RSRVD_DATA_MODEL_VERSION, dt, dim))
337 for (int i = 0; i < size; i++)
345 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
346 OCRepPayload** payload, OCDevAddr *devAddr)
348 OCRepPayload *tempPayload = OCRepPayloadCreate();
352 OCRepPayloadDestroy(tempPayload);
353 return OC_STACK_INVALID_PARAM;
358 return OC_STACK_NO_MEMORY;
361 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
363 OCResourceType *resType = resourcePtr->rsrcType;
366 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
367 resType = resType->next;
370 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
373 OCRepPayloadAddInterface(tempPayload, resInterface->name);
374 resInterface = resInterface->next;
377 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
380 if (resAttrib->attrName && resAttrib->attrValue)
382 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, resAttrib->attrName))
384 appendOCStringLL(tempPayload, (OCStringLL *)resAttrib->attrValue);
388 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName, (char *)resAttrib->attrValue);
391 resAttrib = resAttrib->next;
394 OCResourceProperty p = OCGetResourceProperties((OCResourceHandle *)resourcePtr);
395 OCRepPayload *policy = OCRepPayloadCreate();
398 OCPayloadDestroy((OCPayload *)tempPayload);
399 return OC_STACK_NO_MEMORY;
401 OCRepPayloadSetPropInt(policy, OC_RSRVD_BITMAP, ((p & OC_DISCOVERABLE) | (p & OC_OBSERVABLE)));
404 OCRepPayloadSetPropBool(policy, OC_RSRVD_SECURE, p & OC_SECURE);
405 uint16_t securePort = 0;
406 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
410 OCRepPayloadSetPropInt(policy, OC_RSRVD_HOSTING_PORT, securePort);
412 OCRepPayloadSetPropObjectAsOwner(tempPayload, OC_RSRVD_POLICY, policy);
416 *payload = tempPayload;
420 OCRepPayloadAppend(*payload, tempPayload);
426 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
427 OCDiscoveryPayload *payload, OCDevAddr *devAddr)
429 if (!resourcePtr || !payload)
431 return OC_STACK_INVALID_PARAM;
433 uint16_t securePort = 0;
434 if (resourcePtr->resourceProperties & OC_SECURE)
436 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
443 uint16_t tcpPort = 0;
444 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
448 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
450 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
456 uint8_t IsCollectionResource (OCResource *resource)
463 if(resource->rsrcChildResourcesHead != NULL)
471 OCResource *FindResourceByUri(const char* resourceUri)
478 OCResource * pointer = headResource;
481 if (strcmp(resourceUri, pointer->uri) == 0)
485 pointer = pointer->next;
487 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
492 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
493 ResourceHandling *handling,
494 OCResource **resource)
496 if(!request || !handling || !resource)
498 return OC_STACK_INVALID_PARAM;
501 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
503 // Check if virtual resource
504 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
506 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
507 *handling = OC_RESOURCE_VIRTUAL;
508 *resource = headResource;
511 if (strlen((const char*)(request->resourceUrl)) == 0)
513 // Resource URL not specified
514 *handling = OC_RESOURCE_NOT_SPECIFIED;
515 return OC_STACK_NO_RESOURCE;
519 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
520 *resource = resourcePtr;
523 if(defaultDeviceHandler)
525 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
529 // Resource does not exist
530 // and default device handler does not exist
531 *handling = OC_RESOURCE_NOT_SPECIFIED;
532 return OC_STACK_NO_RESOURCE;
535 if (IsCollectionResource (resourcePtr))
537 // Collection resource
538 if (resourcePtr->entityHandler != defaultResourceEHandler)
540 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
545 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
551 // Resource not a collection
552 if (resourcePtr->entityHandler != defaultResourceEHandler)
554 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
559 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
566 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
568 OCStackResult result;
575 result = OC_STACK_OK;
578 result = OC_STACK_SLOW_RESOURCE;
581 result = OC_STACK_ERROR;
583 case OC_EH_FORBIDDEN:
584 result = OC_STACK_FORBIDDEN_REQ;
586 case OC_EH_INTERNAL_SERVER_ERROR:
587 result = OC_STACK_INTERNAL_SERVER_ERROR;
589 case OC_EH_RESOURCE_CREATED:
590 result = OC_STACK_RESOURCE_CREATED;
592 case OC_EH_RESOURCE_DELETED:
593 result = OC_STACK_RESOURCE_DELETED;
596 result = OC_STACK_RESOURCE_CHANGED;
598 case OC_EH_RESOURCE_NOT_FOUND:
599 result = OC_STACK_NO_RESOURCE;
602 result = OC_STACK_ERROR;
608 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
615 // Null or empty is analogous to no filter.
616 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
621 OCResourceType *resourceTypePtr = resource->rsrcType;
623 while (resourceTypePtr)
625 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
629 resourceTypePtr = resourceTypePtr->next;
632 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
636 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
643 // Null or empty is analogous to no filter.
644 if (interfaceFilter == NULL || *interfaceFilter == 0)
649 OCResourceInterface *interfacePtr = resource->rsrcInterface;
653 if (strcmp (interfacePtr->name, interfaceFilter) == 0 ||
654 strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
655 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0)
659 interfacePtr = interfacePtr->next;
662 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
667 * If the filters are null, they will be assumed to NOT be present
668 * and the resource will not be matched against them.
669 * Function will return true if all non null AND non empty filters passed in find a match.
671 static bool includeThisResourceInResponse(OCResource *resource,
672 char *interfaceFilter,
673 char *resourceTypeFilter)
677 OIC_LOG(ERROR, TAG, "Invalid resource");
681 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
684 * At least one valid filter should be available to
685 * include the resource in discovery response
687 if (!(resourceTypeFilter && *resourceTypeFilter))
689 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
690 resource", resource->uri);
694 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
695 !(resource->resourceProperties & OC_DISCOVERABLE))
697 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
701 return resourceMatchesIFFilter(resource, interfaceFilter) &&
702 resourceMatchesRTFilter(resource, resourceTypeFilter);
706 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
707 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
709 OCEntityHandlerResponse response = {0};
711 response.ehResult = ehResult;
712 response.payload = discoveryPayload;
713 response.persistentBufferFlag = 0;
714 response.requestHandle = (OCRequestHandle) request->requestId;
715 response.resourceHandle = (OCResourceHandle) resource;
717 return OCDoResponse(&response);
721 * Find resource at the resource directory server. This resource is not local resource but a
724 * @param resource The resource to check the matching resource URI.
725 * @param interfaceQuery The interface query parameter.
726 * @param resourceTypeQuery The resourceType query parameter.
727 * @param discPayload The payload that will be added with the resource information if found at RD.
729 * @return ::OC_STACK_OK if the resource is found else ::OC_STACK_NO_RESOURCE.
730 * In case if build is not with flag RD_SERVER, it returns ::OC_STACK_NO_RESOURCE.
732 static OCStackResult findResourceAtRD(const OCResource* resource, const char *interfaceQuery,
733 const char *resourceTypeQuery, OCDiscoveryPayload *discPayload)
735 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
737 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
743 return OC_STACK_NO_RESOURCE;
748 * Creates a discovery payload and add device id information. This information is included in all
751 * @param payload payload that will have memory alllocated and device id information added.
753 * @return ::OC_STACK_OK if successful in allocating memory and adding ID information.
754 * ::OC_STACK_NO_MEMORY if failed allocating the memory.
756 static OCStackResult discoveryPayloadCreateAndAddDeviceId(OCPayload **payload)
760 OIC_LOG_V(DEBUG, TAG, "Payload is already allocated");
764 *payload = (OCPayload *) OCDiscoveryPayloadCreate();
765 VERIFY_PARAM_NON_NULL(TAG, *payload, "Failed adding device id to discovery payload.");
768 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)*payload;
769 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
770 VERIFY_PARAM_NON_NULL(TAG, discPayload->sid, "Failed adding device id to discovery payload.");
772 const char* uid = OCGetServerInstanceIDString();
775 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
781 OCPayloadDestroy(*payload);
782 return OC_STACK_NO_MEMORY;
786 * Add the common properties to the payload, they are only included in case of oic.if.baseline response.
788 * @param discPayload payload that will have the baseline information included.
790 * @return ::OC_STACK_OK if successful in adding all the information. ::OC_STACK_NO_MEMORY if failed
791 * allocating the memory for the baseline information.
793 static OCStackResult addDiscoveryBaselineCommonProperties(OCDiscoveryPayload *discPayload)
795 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
796 VERIFY_PARAM_NON_NULL(TAG, discPayload->uri, "Failed adding href to discovery payload.");
798 OCGetPropertyValue(PAYLOAD_TYPE_DEVICE, "deviceName", (void **)&discPayload->name);
800 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
801 VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt to discovery payload.");
802 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
803 VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt value to discovery payload.");
805 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
806 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
807 VERIFY_PARAM_NON_NULL(TAG, discPayload->iface, "Failed adding if to discovery payload.");
812 return OC_STACK_NO_MEMORY;
815 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
817 if (!request || !resource)
819 return OC_STACK_INVALID_PARAM;
822 OCStackResult discoveryResult = OC_STACK_ERROR;
823 if (request->method == OC_REST_PUT || request->method == OC_REST_POST ||
824 request->method == OC_REST_DELETE)
826 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d",
827 request->resourceUrl, request->method);
828 return OC_STACK_UNAUTHORIZED_REQ;
831 OCPayload* payload = NULL;
832 char *interfaceQuery = NULL;
833 char *resourceTypeQuery = NULL;
834 char *dataModelVersions = NULL;
836 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
838 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
840 // Step 1: Generate the response to discovery request
841 if (virtualUriInRequest == OC_WELL_KNOWN_URI
843 || virtualUriInRequest == OC_MQ_BROKER_URI
847 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
848 &interfaceQuery, &resourceTypeQuery);
849 VERIFY_SUCCESS(discoveryResult);
850 if (!interfaceQuery && !resourceTypeQuery)
852 // If no query is sent, default interface is used i.e. oic.if.ll.
853 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
856 bool baselineQuery = false;
857 if (interfaceQuery && 0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_DEFAULT))
859 baselineQuery = true;
862 discoveryResult = discoveryPayloadCreateAndAddDeviceId(&payload);
863 VERIFY_PARAM_NON_NULL(TAG, payload, "Failed creating Discovery Payload.");
864 VERIFY_SUCCESS(discoveryResult);
866 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
869 discoveryResult = addDiscoveryBaselineCommonProperties(discPayload);
870 VERIFY_SUCCESS(discoveryResult);
872 OCResourceProperty prop = OC_DISCOVERABLE;
874 prop = (OC_MQ_BROKER_URI == virtualUriInRequest) ? OC_MQ_BROKER : prop;
876 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
878 discoveryResult = OC_STACK_NO_RESOURCE;
880 discoveryResult = findResourceAtRD(resource, interfaceQuery, resourceTypeQuery,
883 if (OC_STACK_NO_RESOURCE == discoveryResult)
885 // This case will handle when no resource type and it is oic.if.ll.
886 if (!resourceTypeQuery && !baselineQuery && (resource->resourceProperties & prop))
888 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
890 else if (includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
892 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
896 discoveryResult = OC_STACK_OK;
900 if (discPayload->resources == NULL)
902 discoveryResult = OC_STACK_NO_RESOURCE;
905 else if (virtualUriInRequest == OC_DEVICE_URI)
907 OCResource *resourcePtr = FindResourceByUri(OC_RSRVD_DEVICE_URI);
908 VERIFY_PARAM_NON_NULL(TAG, resourcePtr, "Device URI not found.");
909 discoveryResult = BuildResponseRepresentation(resourcePtr, (OCRepPayload **)&payload, &request->devAddr);
911 else if (virtualUriInRequest == OC_PLATFORM_URI)
913 OCResource *resourcePtr = FindResourceByUri(OC_RSRVD_PLATFORM_URI);
914 VERIFY_PARAM_NON_NULL(TAG, resourcePtr, "Platform URI not found.");
915 discoveryResult = BuildResponseRepresentation(resourcePtr, (OCRepPayload **)&payload, &request->devAddr);
917 #ifdef ROUTING_GATEWAY
918 else if (OC_GATEWAY_URI == virtualUriInRequest)
920 // Received request for a gateway
921 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
922 discoveryResult = RMHandleGatewayRequest(request, resource);
926 else if (OC_KEEPALIVE_RESOURCE_URI == virtualUriInRequest)
928 // Received request for a keepalive
929 OIC_LOG(INFO, TAG, "Request is for KeepAlive Request");
930 discoveryResult = HandleKeepAliveRequest(request, resource);
934 * Step 2: Send the discovery response
936 * Iotivity should respond to discovery requests in below manner:
937 * 1)If query filter matching fails and discovery request is multicast,
938 * it should NOT send any response.
939 * 2)If query filter matching fails and discovery request is unicast,
940 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
941 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
942 * request is multicast, it should NOT send any response.
943 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
944 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
948 if ((virtualUriInRequest == OC_PRESENCE) &&
949 (resource->resourceProperties & OC_ACTIVE))
951 // Need to send ACK when the request is CON.
952 if (request->qos == OC_HIGH_QOS)
954 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
955 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
956 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
957 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
959 FindAndDeleteServerRequest(request);
961 // Presence uses observer notification api to respond via SendPresenceNotification.
962 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
967 // Gateway uses the RMHandleGatewayRequest to respond to the request.
968 if (OC_GATEWAY_URI != virtualUriInRequest)
972 // KeepAlive uses the HandleKeepAliveRequest to respond to the request.
973 if (OC_KEEPALIVE_RESOURCE_URI != virtualUriInRequest)
976 OIC_LOG_PAYLOAD(DEBUG, payload);
977 if(discoveryResult == OC_STACK_OK)
979 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
981 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
982 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
983 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
985 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
986 discoveryResult, virtualUriInRequest);
987 SendNonPersistantDiscoveryResponse(request, resource, NULL,
988 (discoveryResult == OC_STACK_NO_RESOURCE) ?
989 OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
993 // Ignoring the discovery request as per RFC 7252, Section #8.2
994 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send.");
995 // the request should be removed.
996 // since it never remove and causes a big memory waste.
997 FindAndDeleteServerRequest(request);
1005 OICFree(interfaceQuery);
1008 if (resourceTypeQuery)
1010 OICFree(resourceTypeQuery);
1012 OCPayloadDestroy(payload);
1013 if (dataModelVersions)
1015 OICFree(dataModelVersions);
1017 return discoveryResult;
1020 static OCStackResult
1021 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
1025 return OC_STACK_INVALID_PARAM;
1028 OCStackResult result = OC_STACK_OK;
1029 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1030 OCEntityHandlerRequest ehRequest = {0};
1032 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
1033 result = FormOCEntityHandlerRequest(&ehRequest,
1034 (OCRequestHandle) request->requestId,
1037 (OCResourceHandle) NULL, request->query,
1038 PAYLOAD_TYPE_REPRESENTATION,
1040 request->payloadSize,
1041 request->numRcvdVendorSpecificHeaderOptions,
1042 request->rcvdVendorSpecificHeaderOptions,
1043 (OCObserveAction)request->observationOption,
1046 VERIFY_SUCCESS(result);
1048 // At this point we know for sure that defaultDeviceHandler exists
1049 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
1050 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
1051 if(ehResult == OC_EH_SLOW)
1053 OIC_LOG(INFO, TAG, "This is a slow resource");
1054 request->slowFlag = 1;
1056 else if(ehResult == OC_EH_ERROR)
1058 FindAndDeleteServerRequest(request);
1060 result = EntityHandlerCodeToOCStackCode(ehResult);
1062 OCPayloadDestroy(ehRequest.payload);
1066 static OCStackResult
1067 HandleResourceWithEntityHandler (OCServerRequest *request,
1068 OCResource *resource,
1069 uint8_t collectionResource)
1071 OC_UNUSED(collectionResource);
1073 if(!request || ! resource)
1075 return OC_STACK_INVALID_PARAM;
1078 OCStackResult result = OC_STACK_ERROR;
1079 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1080 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1081 ResourceObserver *resObs = NULL;
1083 OCEntityHandlerRequest ehRequest = {0};
1085 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1086 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1087 // check the security resource
1088 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1090 type = PAYLOAD_TYPE_SECURITY;
1093 result = FormOCEntityHandlerRequest(&ehRequest,
1094 (OCRequestHandle)request->requestId,
1097 (OCResourceHandle)resource,
1101 request->payloadSize,
1102 request->numRcvdVendorSpecificHeaderOptions,
1103 request->rcvdVendorSpecificHeaderOptions,
1104 (OCObserveAction)request->observationOption,
1107 VERIFY_SUCCESS(result);
1109 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1111 OIC_LOG(INFO, TAG, "No observation requested");
1112 ehFlag = OC_REQUEST_FLAG;
1114 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER)
1116 OIC_LOG(INFO, TAG, "Observation registration requested");
1118 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1119 request->tokenLength);
1123 OIC_LOG (INFO, TAG, "Observer with this token already present");
1124 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1125 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1126 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1128 // server requests are usually free'd when the response is sent out
1129 // for the request in ocserverrequest.c : HandleSingleResponse()
1130 // Since we are making an early return and not responding, the server request
1131 // needs to be deleted.
1132 FindAndDeleteServerRequest (request);
1136 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1137 VERIFY_SUCCESS(result);
1139 result = AddObserver ((const char*)(request->resourceUrl),
1140 (const char *)(request->query),
1141 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1142 resource, request->qos, request->acceptFormat,
1145 if(result == OC_STACK_OK)
1147 OIC_LOG(INFO, TAG, "Added observer successfully");
1148 request->observeResult = OC_STACK_OK;
1149 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1151 else if (result == OC_STACK_RESOURCE_ERROR)
1153 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1154 request->observeResult = OC_STACK_ERROR;
1155 ehFlag = OC_REQUEST_FLAG;
1159 // The error in observeResult for the request will be used when responding to this
1160 // request by omitting the observation option/sequence number.
1161 request->observeResult = OC_STACK_ERROR;
1162 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1163 ehFlag = OC_REQUEST_FLAG;
1164 FindAndDeleteServerRequest(request);
1169 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER)
1171 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1173 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1177 // Stack does not contain this observation request
1178 // Either token is incorrect or observation list is corrupted
1179 result = OC_STACK_ERROR;
1182 ehRequest.obsInfo.obsId = resObs->observeId;
1183 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1185 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1187 if(result == OC_STACK_OK)
1189 OIC_LOG(INFO, TAG, "Removed observer successfully");
1190 request->observeResult = OC_STACK_OK;
1191 // There should be no observe option header for de-registration response.
1192 // Set as an invalid value here so we can detect it later and remove the field in response.
1193 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1197 request->observeResult = OC_STACK_ERROR;
1198 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1199 FindAndDeleteServerRequest(request);
1205 result = OC_STACK_ERROR;
1209 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1210 if(ehResult == OC_EH_SLOW)
1212 OIC_LOG(INFO, TAG, "This is a slow resource");
1213 request->slowFlag = 1;
1215 else if(ehResult == OC_EH_ERROR)
1217 FindAndDeleteServerRequest(request);
1219 result = EntityHandlerCodeToOCStackCode(ehResult);
1221 OCPayloadDestroy(ehRequest.payload);
1225 static OCStackResult
1226 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1227 OCResource *resource)
1229 if(!request || !resource)
1231 return OC_STACK_INVALID_PARAM;
1234 OCStackResult result = OC_STACK_ERROR;
1235 OCEntityHandlerRequest ehRequest = {0};
1237 result = FormOCEntityHandlerRequest(&ehRequest,
1238 (OCRequestHandle)request->requestId,
1241 (OCResourceHandle)resource,
1243 PAYLOAD_TYPE_REPRESENTATION,
1245 request->payloadSize,
1246 request->numRcvdVendorSpecificHeaderOptions,
1247 request->rcvdVendorSpecificHeaderOptions,
1248 (OCObserveAction)request->observationOption,
1251 if(result == OC_STACK_OK)
1253 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1256 OCPayloadDestroy(ehRequest.payload);
1261 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1263 OCStackResult ret = OC_STACK_OK;
1265 switch (resHandling)
1267 case OC_RESOURCE_VIRTUAL:
1269 ret = HandleVirtualResource (request, resource);
1272 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1274 ret = HandleDefaultDeviceEntityHandler(request);
1277 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1279 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1280 return OC_STACK_ERROR;
1282 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1284 ret = HandleResourceWithEntityHandler (request, resource, 0);
1287 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1289 ret = HandleResourceWithEntityHandler (request, resource, 1);
1292 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1294 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1297 case OC_RESOURCE_NOT_SPECIFIED:
1299 ret = OC_STACK_NO_RESOURCE;
1304 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1305 return OC_STACK_ERROR;
1311 OCStackResult OCSetPlatformInfo(OCPlatformInfo info)
1313 OCResource *resource = NULL;
1314 if (!info.platformID || !info.manufacturerName)
1316 OIC_LOG(ERROR, TAG, "No value specified.");
1319 if (0 == strlen(info.platformID) || 0 == strlen(info.manufacturerName))
1321 OIC_LOG(ERROR, TAG, "The passed value cannot be empty");
1324 if ((info.manufacturerName && strlen(info.manufacturerName) > MAX_PLATFORM_NAME_LENGTH) ||
1325 (info.manufacturerUrl && strlen(info.manufacturerUrl) > MAX_PLATFORM_URL_LENGTH) ||
1326 (info.modelNumber && strlen(info.modelNumber) > MAX_PLATFORM_NAME_LENGTH) ||
1327 (info.platformVersion && strlen(info.platformVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1328 (info.operatingSystemVersion && strlen(info.operatingSystemVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1329 (info.hardwareVersion && strlen(info.hardwareVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1330 (info.firmwareVersion && strlen(info.firmwareVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1331 (info.supportUrl && strlen(info.supportUrl) > MAX_PLATFORM_URL_LENGTH))
1333 OIC_LOG(ERROR, TAG, "The passed value is bigger than permitted.");
1337 resource = FindResourceByUri(OC_RSRVD_PLATFORM_URI);
1340 OIC_LOG(ERROR, TAG, "Platform Resource does not exist.");
1343 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
1344 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_PLATFORM_ID, info.platformID));
1345 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_NAME, info.manufacturerName));
1346 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_URL, info.manufacturerUrl);
1347 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MODEL_NUM, info.modelNumber);
1348 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_DATE, info.dateOfManufacture);
1349 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_PLATFORM_VERSION, info.platformVersion);
1350 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_OS_VERSION, info.operatingSystemVersion);
1351 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_HARDWARE_VERSION, info.hardwareVersion);
1352 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_FIRMWARE_VERSION, info.firmwareVersion);
1353 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_SUPPORT_URL, info.supportUrl);
1354 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_SYSTEM_TIME, info.systemTime);
1355 OIC_LOG(INFO, TAG, "Platform parameter initialized successfully.");
1359 return OC_STACK_INVALID_PARAM;
1362 OCStackResult OCSetDeviceInfo(OCDeviceInfo info)
1364 OCStringLL *dataModelVersion = NULL;
1365 OCResource *resource = FindResourceByUri(OC_RSRVD_DEVICE_URI);
1368 OIC_LOG(ERROR, TAG, "Device Resource does not exist.");
1371 if (!info.deviceName || info.deviceName[0] == '\0')
1373 OIC_LOG(ERROR, TAG, "Null or empty device name.");
1374 return OC_STACK_INVALID_PARAM;
1377 if (OCGetServerInstanceIDString() == NULL)
1379 OIC_LOG(INFO, TAG, "Device ID generation failed");
1383 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME, info.deviceName));
1384 for (OCStringLL *temp = info.types; temp; temp = temp->next)
1388 VERIFY_SUCCESS(OCBindResourceTypeToResource(resource, temp->value));
1391 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, info.specVersion ?
1392 info.specVersion: OC_SPEC_VERSION));
1393 if (info.dataModelVersions)
1395 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION, info.dataModelVersions));
1399 dataModelVersion = OCCreateOCStringLL(OC_DATA_MODEL_VERSION);
1400 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION, dataModelVersion));
1402 OIC_LOG(INFO, TAG, "Device parameter initialized successfully.");
1406 if (dataModelVersion)
1408 OCFreeOCStringLL(dataModelVersion);
1410 return OC_STACK_ERROR;
1413 OCStackResult OCGetAttribute(const OCResource *resource, const char *attribute, void **value)
1415 if (!resource || !attribute)
1417 return OC_STACK_INVALID_PARAM;
1419 if (0 == strlen(attribute))
1421 return OC_STACK_INVALID_PARAM;
1423 for (OCAttribute *temp = resource->rsrcAttributes; temp; temp = temp->next)
1425 if (0 == strcmp(attribute, temp->attrName))
1427 // A special case as this type return OCStringLL
1428 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, attribute))
1430 *value = CloneOCStringLL((OCStringLL *)temp->attrValue);
1435 *value = OICStrdup((char *)temp->attrValue);
1440 return OC_STACK_NO_RESOURCE;
1443 OCStackResult OCGetPropertyValue(OCPayloadType type, const char *prop, void **value)
1445 if (!prop || *value)
1447 return OC_STACK_INVALID_PARAM;
1449 if (strlen(prop) == 0)
1451 return OC_STACK_INVALID_PARAM;
1453 OCStackResult res = OC_STACK_NO_RESOURCE;
1454 if (PAYLOAD_TYPE_DEVICE == type || PAYLOAD_TYPE_PLATFORM == type)
1456 const char *pathType = (type == PAYLOAD_TYPE_DEVICE) ? OC_RSRVD_DEVICE_URI : OC_RSRVD_PLATFORM_URI;
1457 OCResource *resource = FindResourceByUri(pathType);
1460 return OC_STACK_NO_RESOURCE;
1463 res = OCGetAttribute(resource, prop, value);
1468 OCStackResult OCSetAttribute(OCResource* resource, const char* attribute, const void* value)
1470 OCAttribute *resAttrib = (OCAttribute *)OICCalloc(1, sizeof(OCAttribute));
1471 VERIFY_PARAM_NON_NULL(TAG, resAttrib, "Failed allocation OCAttribute");
1472 resAttrib->attrName = OICStrdup(attribute);
1473 VERIFY_PARAM_NON_NULL(TAG, resAttrib->attrName, "Failed allocating attribute name");
1474 // A special case when value is of type OCStringLL
1475 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, attribute))
1477 resAttrib->attrValue = CloneOCStringLL((OCStringLL *)value);
1481 resAttrib->attrValue = OICStrdup((char *)value);
1483 VERIFY_PARAM_NON_NULL(TAG, resAttrib->attrValue, "Failed allocating attribute value");
1484 resAttrib->next = NULL;
1486 if (!resource->rsrcAttributes)
1488 resource->rsrcAttributes = resAttrib;
1492 OCAttribute *temp = resource->rsrcAttributes;
1493 for (; temp->next; temp = temp->next)
1495 if (0 == strcmp(attribute, temp->attrName))
1497 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, temp->attrName))
1499 OCFreeOCStringLL((OCStringLL *)temp->attrValue);
1502 OICFree((char *)temp->attrValue);
1507 temp->next = resAttrib;
1512 OCDeleteResourceAttributes(resAttrib);
1513 return OC_STACK_NO_MEMORY;
1517 OCStackResult OCSetPropertyValue(OCPayloadType type, const char *prop, const void *value)
1521 return OC_STACK_INVALID_PARAM;
1523 if (strlen(prop) == 0)
1525 return OC_STACK_INVALID_PARAM;
1528 OCStackResult res = OC_STACK_ERROR;
1529 if (PAYLOAD_TYPE_DEVICE == type || PAYLOAD_TYPE_PLATFORM == type)
1531 const char *pathType = (type == PAYLOAD_TYPE_DEVICE) ? OC_RSRVD_DEVICE_URI : OC_RSRVD_PLATFORM_URI;
1532 OCResource *resource = FindResourceByUri(pathType);
1535 OIC_LOG(ERROR, TAG, "Resource does not exist.");
1539 res = OCSetAttribute(resource, prop, value);