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 #define TAG "OIC_RI_RESOURCE"
62 #define VERIFY_SUCCESS(op) { if (op != (OC_STACK_OK)) \
63 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
65 extern OCResource *headResource;
68 * Prepares a Payload for response.
70 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
71 OCDiscoveryPayload* payload,
74 //-----------------------------------------------------------------------------
75 // Default resource entity handler function
76 //-----------------------------------------------------------------------------
77 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
78 OCEntityHandlerRequest * request, void* callbackParam)
80 //TODO ("Implement me!!!!");
81 // TODO: remove silence unused param warnings
85 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
88 /* This method will retrieve the port at which the secure resource is hosted */
89 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
93 if (endpoint->adapter == OC_ADAPTER_IP)
95 if (endpoint->flags & OC_IP_USE_V6)
97 p = caglobals.ip.u6s.port;
99 else if (endpoint->flags & OC_IP_USE_V4)
101 p = caglobals.ip.u4s.port;
110 /* This method will retrieve the tcp port */
111 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
115 if (endpoint->adapter == OC_ADAPTER_IP)
117 if (endpoint->flags & OC_IP_USE_V4)
119 p = caglobals.tcp.ipv4.port;
121 else if (endpoint->flags & OC_IP_USE_V6)
123 p = caglobals.tcp.ipv6.port;
133 * Function will extract 0, 1 or 2 filters from query.
134 * More than 2 filters or unsupported filters will result in error.
135 * If both filters are of the same supported type, the 2nd one will be picked.
136 * Resource and device filters in the SAME query are NOT validated
137 * and resources will likely not clear filters.
139 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
143 char *queryDup = NULL;
144 char *restOfQuery = NULL;
145 char *keyValuePair = NULL;
146 int numKeyValuePairsParsed = 0;
151 queryDup = OICStrdup(query);
152 if (NULL == queryDup)
154 OIC_LOG_V(ERROR, TAG, "Creating duplicate string failed!");
155 return OC_STACK_NO_MEMORY;
158 OIC_LOG_V(INFO, TAG, "Extracting params from %s", queryDup);
160 OCStackResult eCode = OC_STACK_INVALID_QUERY;
161 if (strnlen(queryDup, MAX_QUERY_LENGTH) >= MAX_QUERY_LENGTH)
163 OIC_LOG(ERROR, TAG, "Query exceeds maximum length.");
167 keyValuePair = strtok_r (queryDup, OC_QUERY_SEPARATOR, &restOfQuery);
171 if (numKeyValuePairsParsed >= 2)
173 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
177 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
183 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
185 *filterOne = value; // if
187 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
189 *filterTwo = value; // rt
193 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
196 ++numKeyValuePairsParsed;
198 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
203 *filterOne = OICStrdup(*filterOne);
204 if (NULL == *filterOne)
206 OIC_LOG_V(ERROR, TAG, "Creating duplicate string failed!");
207 eCode = OC_STACK_NO_MEMORY;
214 *filterTwo = OICStrdup(*filterTwo);
215 if (NULL == *filterTwo)
217 OIC_LOG_V(ERROR, TAG, "Creating duplicate string failed!");
219 eCode = OC_STACK_NO_MEMORY;
225 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
235 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
237 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
239 return OC_WELL_KNOWN_URI;
241 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
243 return OC_DEVICE_URI;
245 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
247 return OC_PLATFORM_URI;
249 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
251 return OC_RESOURCE_TYPES_URI;
253 #ifdef ROUTING_GATEWAY
254 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
256 return OC_GATEWAY_URI;
260 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
264 #endif //WITH_PRESENCE
267 else if (0 == strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_MQ_URI))
269 return OC_MQ_BROKER_URI;
274 else if (strcmp(uriInRequest, OC_RSRVD_KEEPALIVE_URI) == 0)
276 return OC_KEEPALIVE_RESOURCE_URI;
280 return OC_UNKNOWN_URI;
283 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
284 char **filterOne, char **filterTwo)
286 if(!filterOne || !filterTwo)
288 return OC_STACK_INVALID_PARAM;
295 if (uri == OC_PRESENCE)
297 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
298 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
303 OCStackResult result = OC_STACK_OK;
307 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
313 bool appendOCStringLL(OCRepPayload *device, OCStringLL *dmv)
316 for (OCStringLL *ll = dmv; ll; ll = ll->next, size++);
317 size_t dim[MAX_REP_ARRAY_DEPTH] = {size, 0, 0};
318 char **dt = (char **)OICMalloc(sizeof(char *) * size);
320 VERIFY_PARAM_NON_NULL(TAG, dt, "Data Model Version allocation failed.");
321 for (OCStringLL *ll = dmv; ll; ll = ll->next, i++)
323 dt[i] = OICStrdup(ll->value);
324 VERIFY_PARAM_NON_NULL(TAG, dt[i], "Data Model Version adding failed.");
326 if (!OCRepPayloadSetStringArrayAsOwner(device, OC_RSRVD_DATA_MODEL_VERSION, dt, dim))
333 for (int i = 0; i < size; i++)
341 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
342 OCRepPayload** payload)
344 OCRepPayload *tempPayload = OCRepPayloadCreate();
348 OCRepPayloadDestroy(tempPayload);
349 return OC_STACK_INVALID_PARAM;
354 return OC_STACK_NO_MEMORY;
357 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
359 OCResourceType *resType = resourcePtr->rsrcType;
362 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
363 resType = resType->next;
366 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
369 OCRepPayloadAddInterface(tempPayload, resInterface->name);
370 resInterface = resInterface->next;
373 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
376 if (resAttrib->attrName && resAttrib->attrValue)
378 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, resAttrib->attrName))
380 appendOCStringLL(tempPayload, (OCStringLL *)resAttrib->attrValue);
384 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName, (char *)resAttrib->attrValue);
387 resAttrib = resAttrib->next;
390 OCResourceProperty p = OCGetResourceProperties((OCResourceHandle *)resourcePtr);
391 p = (OCResourceProperty) ((p & OC_DISCOVERABLE) | (p & OC_OBSERVABLE));
392 OCRepPayload *policy = OCRepPayloadCreate();
393 OCRepPayloadSetPropInt(policy, OC_RSRVD_BITMAP, p);
394 OCRepPayloadSetPropObjectAsOwner(tempPayload, OC_RSRVD_POLICY, policy);
398 *payload = tempPayload;
402 OCRepPayloadAppend(*payload, tempPayload);
408 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
409 OCDiscoveryPayload *payload, OCDevAddr *devAddr)
411 if (!resourcePtr || !payload)
413 return OC_STACK_INVALID_PARAM;
415 uint16_t securePort = 0;
416 if (resourcePtr->resourceProperties & OC_SECURE)
418 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
425 uint16_t tcpPort = 0;
426 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
430 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
432 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
438 uint8_t IsCollectionResource (OCResource *resource)
445 if(resource->rsrcChildResourcesHead != NULL)
453 OCResource *FindResourceByUri(const char* resourceUri)
460 OCResource * pointer = headResource;
463 if (strcmp(resourceUri, pointer->uri) == 0)
467 pointer = pointer->next;
469 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
474 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
475 ResourceHandling *handling,
476 OCResource **resource)
478 if(!request || !handling || !resource)
480 return OC_STACK_INVALID_PARAM;
483 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
485 // Check if virtual resource
486 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
488 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
489 *handling = OC_RESOURCE_VIRTUAL;
490 *resource = headResource;
493 if (strlen((const char*)(request->resourceUrl)) == 0)
495 // Resource URL not specified
496 *handling = OC_RESOURCE_NOT_SPECIFIED;
497 return OC_STACK_NO_RESOURCE;
501 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
502 *resource = resourcePtr;
505 if(defaultDeviceHandler)
507 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
511 // Resource does not exist
512 // and default device handler does not exist
513 *handling = OC_RESOURCE_NOT_SPECIFIED;
514 return OC_STACK_NO_RESOURCE;
517 if (IsCollectionResource (resourcePtr))
519 // Collection resource
520 if (resourcePtr->entityHandler != defaultResourceEHandler)
522 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
527 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
533 // Resource not a collection
534 if (resourcePtr->entityHandler != defaultResourceEHandler)
536 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
541 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
548 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
550 OCStackResult result;
557 result = OC_STACK_OK;
560 result = OC_STACK_SLOW_RESOURCE;
563 result = OC_STACK_ERROR;
565 case OC_EH_FORBIDDEN:
566 result = OC_STACK_FORBIDDEN_REQ;
568 case OC_EH_INTERNAL_SERVER_ERROR:
569 result = OC_STACK_INTERNAL_SERVER_ERROR;
571 case OC_EH_RESOURCE_CREATED:
572 result = OC_STACK_RESOURCE_CREATED;
574 case OC_EH_RESOURCE_DELETED:
575 result = OC_STACK_RESOURCE_DELETED;
578 result = OC_STACK_RESOURCE_CHANGED;
580 case OC_EH_RESOURCE_NOT_FOUND:
581 result = OC_STACK_NO_RESOURCE;
584 result = OC_STACK_ERROR;
590 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
597 // Null or empty is analogous to no filter.
598 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
603 OCResourceType *resourceTypePtr = resource->rsrcType;
605 while (resourceTypePtr)
607 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
611 resourceTypePtr = resourceTypePtr->next;
614 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
618 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
625 // Null or empty is analogous to no filter.
626 if (interfaceFilter == NULL || *interfaceFilter == 0)
631 OCResourceInterface *interfacePtr = resource->rsrcInterface;
635 if (strcmp (interfacePtr->name, interfaceFilter) == 0 ||
636 strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
637 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0)
641 interfacePtr = interfacePtr->next;
644 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
649 * If the filters are null, they will be assumed to NOT be present
650 * and the resource will not be matched against them.
651 * Function will return true if all non null AND non empty filters passed in find a match.
653 static bool includeThisResourceInResponse(OCResource *resource,
654 char *interfaceFilter,
655 char *resourceTypeFilter)
659 OIC_LOG(ERROR, TAG, "Invalid resource");
663 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
666 * At least one valid filter should be available to
667 * include the resource in discovery response
669 if (!(resourceTypeFilter && *resourceTypeFilter))
671 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
672 resource", resource->uri);
676 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
677 !(resource->resourceProperties & OC_DISCOVERABLE))
679 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
683 return resourceMatchesIFFilter(resource, interfaceFilter) &&
684 resourceMatchesRTFilter(resource, resourceTypeFilter);
688 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
689 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
691 OCEntityHandlerResponse response = {0};
693 response.ehResult = ehResult;
694 response.payload = discoveryPayload;
695 response.persistentBufferFlag = 0;
696 response.requestHandle = (OCRequestHandle) request;
697 response.resourceHandle = (OCResourceHandle) resource;
699 return OCDoResponse(&response);
703 * Find resource at the resource directory server. This resource is not local resource but a
706 * @param resource The resource to check the matching resource URI.
707 * @param interfaceQuery The interface query parameter.
708 * @param resourceTypeQuery The resourceType query parameter.
709 * @param discPayload The payload that will be added with the resource information if found at RD.
711 * @return ::OC_STACK_OK if the resource is found else ::OC_STACK_NO_RESOURCE.
712 * In case if build is not with flag RD_SERVER, it returns ::OC_STACK_NO_RESOURCE.
714 static OCStackResult findResourceAtRD(const OCResource* resource, const char *interfaceQuery,
715 const char *resourceTypeQuery, OCDiscoveryPayload *discPayload)
717 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
719 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
725 return OC_STACK_NO_RESOURCE;
730 * Creates a discovery payload and add device id information. This information is included in all
733 * @param payload payload that will have memory alllocated and device id information added.
735 * @return ::OC_STACK_OK if successful in allocating memory and adding ID information.
736 * ::OC_STACK_NO_MEMORY if failed allocating the memory.
738 static OCStackResult discoveryPayloadCreateAndAddDeviceId(OCPayload **payload)
742 OIC_LOG_V(DEBUG, TAG, "Payload is already allocated");
746 *payload = (OCPayload *) OCDiscoveryPayloadCreate();
747 VERIFY_PARAM_NON_NULL(TAG, *payload, "Failed adding device id to discovery payload.");
750 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)*payload;
751 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
752 VERIFY_PARAM_NON_NULL(TAG, discPayload->sid, "Failed adding device id to discovery payload.");
754 const char* uid = OCGetServerInstanceIDString();
757 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
763 OCPayloadDestroy(*payload);
764 return OC_STACK_NO_MEMORY;
768 * Add the common properties to the payload, they are only included in case of oic.if.baseline response.
770 * @param discPayload payload that will have the baseline information included.
772 * @return ::OC_STACK_OK if successful in adding all the information. ::OC_STACK_NO_MEMORY if failed
773 * allocating the memory for the baseline information.
775 static OCStackResult addDiscoveryBaselineCommonProperties(OCDiscoveryPayload *discPayload)
777 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
778 VERIFY_PARAM_NON_NULL(TAG, discPayload->uri, "Failed adding href to discovery payload.");
780 OCGetPropertyValue(PAYLOAD_TYPE_DEVICE, "deviceName", (void **)&discPayload->name);
781 VERIFY_PARAM_NON_NULL(TAG, discPayload->name, "Failed adding name to discovery payload.");
783 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
784 VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt to discovery payload.");
785 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
786 VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt value to discovery payload.");
788 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
789 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
790 VERIFY_PARAM_NON_NULL(TAG, discPayload->iface, "Failed adding if to discovery payload.");
795 return OC_STACK_NO_MEMORY;
798 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
800 if (!request || !resource)
802 return OC_STACK_INVALID_PARAM;
805 OCStackResult discoveryResult = OC_STACK_ERROR;
806 if (request->method == OC_REST_PUT || request->method == OC_REST_POST ||
807 request->method == OC_REST_DELETE)
809 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d",
810 request->resourceUrl, request->method);
811 return OC_STACK_UNAUTHORIZED_REQ;
814 OCPayload* payload = NULL;
815 char *interfaceQuery = NULL;
816 char *resourceTypeQuery = NULL;
817 char *dataModelVersions = NULL;
819 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
821 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
823 // Step 1: Generate the response to discovery request
824 if (virtualUriInRequest == OC_WELL_KNOWN_URI
826 || virtualUriInRequest == OC_MQ_BROKER_URI
830 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
831 &interfaceQuery, &resourceTypeQuery);
832 VERIFY_SUCCESS(discoveryResult);
833 if (!interfaceQuery && !resourceTypeQuery)
835 // If no query is sent, default interface is used i.e. oic.if.ll.
836 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
839 bool baselineQuery = false;
840 if (interfaceQuery && 0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))
842 baselineQuery = true;
845 discoveryResult = discoveryPayloadCreateAndAddDeviceId(&payload);
846 VERIFY_PARAM_NON_NULL(TAG, payload, "Failed creating Discovery Payload.");
847 VERIFY_SUCCESS(discoveryResult);
849 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
852 discoveryResult = addDiscoveryBaselineCommonProperties(discPayload);
853 VERIFY_SUCCESS(discoveryResult);
855 OCResourceProperty prop = OC_DISCOVERABLE;
857 prop = (OC_MQ_BROKER_URI == virtualUriInRequest) ? OC_MQ_BROKER : prop;
859 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
861 discoveryResult = OC_STACK_NO_RESOURCE;
863 discoveryResult = findResourceAtRD(resource, interfaceQuery, resourceTypeQuery,
866 if (OC_STACK_NO_RESOURCE == discoveryResult)
868 if ((!baselineQuery && (resource->resourceProperties & prop)) ||
869 (baselineQuery && (includeThisResourceInResponse(resource, interfaceQuery,
870 resourceTypeQuery))))
872 discoveryResult = BuildVirtualResourceResponse(resource, discPayload,
877 discoveryResult = OC_STACK_OK;
881 if (discPayload->resources == NULL)
883 discoveryResult = OC_STACK_NO_RESOURCE;
886 else if (virtualUriInRequest == OC_DEVICE_URI)
888 OCResource *resourcePtr = FindResourceByUri(OC_RSRVD_DEVICE_URI);
889 VERIFY_PARAM_NON_NULL(TAG, resourcePtr, "Device URI not found.");
890 discoveryResult = BuildResponseRepresentation(resourcePtr, (OCRepPayload **)&payload);
892 else if (virtualUriInRequest == OC_PLATFORM_URI)
894 OCResource *resourcePtr = FindResourceByUri(OC_RSRVD_PLATFORM_URI);
895 VERIFY_PARAM_NON_NULL(TAG, resourcePtr, "Platform URI not found.");
896 discoveryResult = BuildResponseRepresentation(resourcePtr, (OCRepPayload **)&payload);
898 #ifdef ROUTING_GATEWAY
899 else if (OC_GATEWAY_URI == virtualUriInRequest)
901 // Received request for a gateway
902 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
903 discoveryResult = RMHandleGatewayRequest(request, resource);
907 else if (OC_KEEPALIVE_RESOURCE_URI == virtualUriInRequest)
909 // Received request for a keepalive
910 OIC_LOG(INFO, TAG, "Request is for KeepAlive Request");
911 discoveryResult = HandleKeepAliveRequest(request, resource);
915 * Step 2: Send the discovery response
917 * Iotivity should respond to discovery requests in below manner:
918 * 1)If query filter matching fails and discovery request is multicast,
919 * it should NOT send any response.
920 * 2)If query filter matching fails and discovery request is unicast,
921 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
922 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
923 * request is multicast, it should NOT send any response.
924 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
925 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
929 if ((virtualUriInRequest == OC_PRESENCE) &&
930 (resource->resourceProperties & OC_ACTIVE))
932 // Need to send ACK when the request is CON.
933 if (request->qos == OC_HIGH_QOS)
935 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
936 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
937 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
938 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
940 FindAndDeleteServerRequest(request);
942 // Presence uses observer notification api to respond via SendPresenceNotification.
943 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
948 // Gateway uses the RMHandleGatewayRequest to respond to the request.
949 if (OC_GATEWAY_URI != virtualUriInRequest)
953 // KeepAlive uses the HandleKeepAliveRequest to respond to the request.
954 if (OC_KEEPALIVE_RESOURCE_URI != virtualUriInRequest)
957 OIC_LOG_PAYLOAD(DEBUG, payload);
958 if(discoveryResult == OC_STACK_OK)
960 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
962 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
963 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
964 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
966 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
967 discoveryResult, virtualUriInRequest);
968 SendNonPersistantDiscoveryResponse(request, resource, NULL,
969 (discoveryResult == OC_STACK_NO_RESOURCE) ?
970 OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
974 // Ignoring the discovery request as per RFC 7252, Section #8.2
975 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send.");
976 // the request should be removed.
977 // since it never remove and causes a big memory waste.
978 FindAndDeleteServerRequest(request);
986 OICFree(interfaceQuery);
989 if (resourceTypeQuery)
991 OICFree(resourceTypeQuery);
993 OCPayloadDestroy(payload);
994 if (dataModelVersions)
996 OICFree(dataModelVersions);
998 return discoveryResult;
1001 static OCStackResult
1002 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
1006 return OC_STACK_INVALID_PARAM;
1009 OCStackResult result = OC_STACK_OK;
1010 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1011 OCEntityHandlerRequest ehRequest = {0};
1013 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
1014 result = FormOCEntityHandlerRequest(&ehRequest,
1015 (OCRequestHandle) request,
1018 (OCResourceHandle) NULL, request->query,
1019 PAYLOAD_TYPE_REPRESENTATION,
1021 request->payloadSize,
1022 request->numRcvdVendorSpecificHeaderOptions,
1023 request->rcvdVendorSpecificHeaderOptions,
1024 (OCObserveAction)request->observationOption,
1027 VERIFY_SUCCESS(result);
1029 // At this point we know for sure that defaultDeviceHandler exists
1030 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
1031 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
1032 if(ehResult == OC_EH_SLOW)
1034 OIC_LOG(INFO, TAG, "This is a slow resource");
1035 request->slowFlag = 1;
1037 else if(ehResult == OC_EH_ERROR)
1039 FindAndDeleteServerRequest(request);
1041 result = EntityHandlerCodeToOCStackCode(ehResult);
1043 OCPayloadDestroy(ehRequest.payload);
1047 static OCStackResult
1048 HandleResourceWithEntityHandler (OCServerRequest *request,
1049 OCResource *resource,
1050 uint8_t collectionResource)
1052 OC_UNUSED(collectionResource);
1054 if(!request || ! resource)
1056 return OC_STACK_INVALID_PARAM;
1059 OCStackResult result = OC_STACK_ERROR;
1060 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1061 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1062 ResourceObserver *resObs = NULL;
1064 OCEntityHandlerRequest ehRequest = {0};
1066 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1067 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1068 // check the security resource
1069 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1071 type = PAYLOAD_TYPE_SECURITY;
1075 result = FormOCEntityHandlerRequest(&ehRequest,
1076 (OCRequestHandle)request,
1079 (OCResourceHandle)resource,
1083 request->payloadSize,
1084 request->numRcvdVendorSpecificHeaderOptions,
1085 request->rcvdVendorSpecificHeaderOptions,
1086 (OCObserveAction)request->observationOption,
1089 VERIFY_SUCCESS(result);
1091 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1093 OIC_LOG(INFO, TAG, "No observation requested");
1094 ehFlag = OC_REQUEST_FLAG;
1096 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER)
1098 OIC_LOG(INFO, TAG, "Observation registration requested");
1100 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1101 request->tokenLength);
1105 OIC_LOG (INFO, TAG, "Observer with this token already present");
1106 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1107 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1108 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1110 // server requests are usually free'd when the response is sent out
1111 // for the request in ocserverrequest.c : HandleSingleResponse()
1112 // Since we are making an early return and not responding, the server request
1113 // needs to be deleted.
1114 FindAndDeleteServerRequest (request);
1118 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1119 VERIFY_SUCCESS(result);
1121 result = AddObserver ((const char*)(request->resourceUrl),
1122 (const char *)(request->query),
1123 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1124 resource, request->qos, request->acceptFormat,
1127 if(result == OC_STACK_OK)
1129 OIC_LOG(INFO, TAG, "Added observer successfully");
1130 request->observeResult = OC_STACK_OK;
1131 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1133 else if (result == OC_STACK_RESOURCE_ERROR)
1135 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1136 request->observeResult = OC_STACK_ERROR;
1137 ehFlag = OC_REQUEST_FLAG;
1141 // The error in observeResult for the request will be used when responding to this
1142 // request by omitting the observation option/sequence number.
1143 request->observeResult = OC_STACK_ERROR;
1144 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1145 ehFlag = OC_REQUEST_FLAG;
1146 FindAndDeleteServerRequest(request);
1151 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER)
1153 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1155 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1159 // Stack does not contain this observation request
1160 // Either token is incorrect or observation list is corrupted
1161 result = OC_STACK_ERROR;
1164 ehRequest.obsInfo.obsId = resObs->observeId;
1165 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1167 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1169 if(result == OC_STACK_OK)
1171 OIC_LOG(INFO, TAG, "Removed observer successfully");
1172 request->observeResult = OC_STACK_OK;
1173 // There should be no observe option header for de-registration response.
1174 // Set as an invalid value here so we can detect it later and remove the field in response.
1175 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1179 request->observeResult = OC_STACK_ERROR;
1180 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1181 FindAndDeleteServerRequest(request);
1187 result = OC_STACK_ERROR;
1191 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1192 if(ehResult == OC_EH_SLOW)
1194 OIC_LOG(INFO, TAG, "This is a slow resource");
1195 request->slowFlag = 1;
1197 else if(ehResult == OC_EH_ERROR)
1199 FindAndDeleteServerRequest(request);
1201 result = EntityHandlerCodeToOCStackCode(ehResult);
1203 OCPayloadDestroy(ehRequest.payload);
1207 static OCStackResult
1208 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1209 OCResource *resource)
1211 if(!request || !resource)
1213 return OC_STACK_INVALID_PARAM;
1216 OCStackResult result = OC_STACK_ERROR;
1217 OCEntityHandlerRequest ehRequest = {0};
1219 result = FormOCEntityHandlerRequest(&ehRequest,
1220 (OCRequestHandle)request,
1223 (OCResourceHandle)resource,
1225 PAYLOAD_TYPE_REPRESENTATION,
1227 request->payloadSize,
1228 request->numRcvdVendorSpecificHeaderOptions,
1229 request->rcvdVendorSpecificHeaderOptions,
1230 (OCObserveAction)request->observationOption,
1233 if(result == OC_STACK_OK)
1235 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1238 OCPayloadDestroy(ehRequest.payload);
1243 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1245 OCStackResult ret = OC_STACK_OK;
1247 switch (resHandling)
1249 case OC_RESOURCE_VIRTUAL:
1251 ret = HandleVirtualResource (request, resource);
1254 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1256 ret = HandleDefaultDeviceEntityHandler(request);
1259 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1261 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1262 return OC_STACK_ERROR;
1264 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1266 ret = HandleResourceWithEntityHandler (request, resource, 0);
1269 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1271 ret = HandleResourceWithEntityHandler (request, resource, 1);
1274 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1276 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1279 case OC_RESOURCE_NOT_SPECIFIED:
1281 ret = OC_STACK_NO_RESOURCE;
1286 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1287 return OC_STACK_ERROR;
1293 OCStackResult OCSetPlatformInfo(OCPlatformInfo info)
1295 OCResource *resource = NULL;
1296 if (!info.platformID || !info.manufacturerName)
1298 OIC_LOG(ERROR, TAG, "No value specified.");
1301 if (0 == strlen(info.platformID) || 0 == strlen(info.manufacturerName))
1303 OIC_LOG(ERROR, TAG, "The passed value cannot be empty");
1306 if ((info.manufacturerName && strlen(info.manufacturerName) > MAX_PLATFORM_NAME_LENGTH) ||
1307 (info.manufacturerUrl && strlen(info.manufacturerUrl) > MAX_PLATFORM_URL_LENGTH) ||
1308 (info.modelNumber && strlen(info.modelNumber) > MAX_PLATFORM_NAME_LENGTH) ||
1309 (info.platformVersion && strlen(info.platformVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1310 (info.operatingSystemVersion && strlen(info.operatingSystemVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1311 (info.hardwareVersion && strlen(info.hardwareVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1312 (info.firmwareVersion && strlen(info.firmwareVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1313 (info.supportUrl && strlen(info.supportUrl) > MAX_PLATFORM_URL_LENGTH))
1315 OIC_LOG(ERROR, TAG, "The passed value is bigger than permitted.");
1319 resource = FindResourceByUri(OC_RSRVD_PLATFORM_URI);
1322 OIC_LOG(ERROR, TAG, "Platform Resource does not exist.");
1325 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
1326 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_PLATFORM_ID, info.platformID));
1327 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_NAME, info.manufacturerName));
1328 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_URL, info.manufacturerUrl);
1329 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MODEL_NUM, info.modelNumber);
1330 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_DATE, info.dateOfManufacture);
1331 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_PLATFORM_VERSION, info.platformVersion);
1332 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_OS_VERSION, info.operatingSystemVersion);
1333 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_HARDWARE_VERSION, info.hardwareVersion);
1334 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_FIRMWARE_VERSION, info.firmwareVersion);
1335 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_SUPPORT_URL, info.supportUrl);
1336 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_SYSTEM_TIME, info.systemTime);
1337 OIC_LOG(INFO, TAG, "Platform parameter initialized successfully.");
1341 return OC_STACK_INVALID_PARAM;
1344 OCStackResult OCSetDeviceInfo(OCDeviceInfo info)
1346 OCStringLL *dataModelVersion = NULL;
1347 OCResource *resource = FindResourceByUri(OC_RSRVD_DEVICE_URI);
1350 OIC_LOG(ERROR, TAG, "Device Resource does not exist.");
1353 if (!info.deviceName || info.deviceName[0] == '\0')
1355 OIC_LOG(ERROR, TAG, "Null or empty device name.");
1356 return OC_STACK_INVALID_PARAM;
1359 if (OCGetServerInstanceIDString() == NULL)
1361 OIC_LOG(INFO, TAG, "Device ID generation failed");
1365 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME, info.deviceName));
1366 for (OCStringLL *temp = info.types; temp; temp = temp->next)
1370 VERIFY_SUCCESS(OCBindResourceTypeToResource(resource, temp->value));
1373 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, info.specVersion ?
1374 info.specVersion: OC_SPEC_VERSION));
1375 if (info.dataModelVersions)
1377 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION, info.dataModelVersions));
1381 dataModelVersion = OCCreateOCStringLL(OC_DATA_MODEL_VERSION);
1382 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION, dataModelVersion));
1384 OIC_LOG(INFO, TAG, "Device parameter initialized successfully.");
1388 if (dataModelVersion)
1390 OCFreeOCStringLL(dataModelVersion);
1392 return OC_STACK_ERROR;
1395 OCStackResult OCGetAttribute(const OCResource *resource, const char *attribute, void **value)
1397 if (!resource || !attribute)
1399 return OC_STACK_INVALID_PARAM;
1401 if (0 == strlen(attribute))
1403 return OC_STACK_INVALID_PARAM;
1405 for (OCAttribute *temp = resource->rsrcAttributes; temp; temp = temp->next)
1407 if (0 == strcmp(attribute, temp->attrName))
1409 // A special case as this type return OCStringLL
1410 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, attribute))
1412 *value = CloneOCStringLL((OCStringLL *)temp->attrValue);
1417 *value = OICStrdup((char *)temp->attrValue);
1422 return OC_STACK_NO_RESOURCE;
1425 OCStackResult OCGetPropertyValue(OCPayloadType type, const char *prop, void **value)
1427 if (!prop || *value)
1429 return OC_STACK_INVALID_PARAM;
1431 if (strlen(prop) == 0)
1433 return OC_STACK_INVALID_PARAM;
1435 OCStackResult res = OC_STACK_NO_RESOURCE;
1436 if (PAYLOAD_TYPE_DEVICE == type || PAYLOAD_TYPE_PLATFORM == type)
1438 const char *pathType = (type == PAYLOAD_TYPE_DEVICE) ? OC_RSRVD_DEVICE_URI : OC_RSRVD_PLATFORM_URI;
1439 OCResource *resource = FindResourceByUri(pathType);
1442 return OC_STACK_NO_RESOURCE;
1445 res = OCGetAttribute(resource, prop, value);
1450 OCStackResult OCSetAttribute(OCResource* resource, const char* attribute, const void* value)
1452 OCAttribute *resAttrib = (OCAttribute *)OICCalloc(1, sizeof(OCAttribute));
1453 VERIFY_PARAM_NON_NULL(TAG, resAttrib, "Failed allocation OCAttribute");
1454 resAttrib->attrName = OICStrdup(attribute);
1455 VERIFY_PARAM_NON_NULL(TAG, resAttrib->attrName, "Failed allocating attribute name");
1456 // A special case when value is of type OCStringLL
1457 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, attribute))
1459 resAttrib->attrValue = CloneOCStringLL((OCStringLL *)value);
1463 resAttrib->attrValue = OICStrdup((char *)value);
1465 VERIFY_PARAM_NON_NULL(TAG, resAttrib->attrValue, "Failed allocating attribute value");
1466 resAttrib->next = NULL;
1468 if (!resource->rsrcAttributes)
1470 resource->rsrcAttributes = resAttrib;
1474 OCAttribute *temp = resource->rsrcAttributes;
1475 for (; temp->next; temp = temp->next)
1477 if (0 == strcmp(attribute, temp->attrName))
1479 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, temp->attrName))
1481 OCFreeOCStringLL((OCStringLL *)temp->attrValue);
1484 OICFree((char *)temp->attrValue);
1489 temp->next = resAttrib;
1494 OCDeleteResourceAttributes(resAttrib);
1495 return OC_STACK_NO_MEMORY;
1499 OCStackResult OCSetPropertyValue(OCPayloadType type, const char *prop, const void *value)
1503 return OC_STACK_INVALID_PARAM;
1505 if (strlen(prop) == 0)
1507 return OC_STACK_INVALID_PARAM;
1510 OCStackResult res = OC_STACK_ERROR;
1511 if (PAYLOAD_TYPE_DEVICE == type || PAYLOAD_TYPE_PLATFORM == type)
1513 const char *pathType = (type == PAYLOAD_TYPE_DEVICE) ? OC_RSRVD_DEVICE_URI : OC_RSRVD_PLATFORM_URI;
1514 OCResource *resource = FindResourceByUri(pathType);
1517 OIC_LOG(ERROR, TAG, "Resource does not exist.");
1521 res = OCSetAttribute(resource, prop, value);