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;
392 *payload = tempPayload;
396 OCRepPayloadAppend(*payload, tempPayload);
402 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
403 OCDiscoveryPayload *payload, OCDevAddr *devAddr)
405 if (!resourcePtr || !payload)
407 return OC_STACK_INVALID_PARAM;
409 uint16_t securePort = 0;
410 if (resourcePtr->resourceProperties & OC_SECURE)
412 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
419 uint16_t tcpPort = 0;
420 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
424 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
426 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
432 uint8_t IsCollectionResource (OCResource *resource)
439 if(resource->rsrcChildResourcesHead != NULL)
447 OCResource *FindResourceByUri(const char* resourceUri)
454 OCResource * pointer = headResource;
457 if (strcmp(resourceUri, pointer->uri) == 0)
461 pointer = pointer->next;
463 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
468 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
469 ResourceHandling *handling,
470 OCResource **resource)
472 if(!request || !handling || !resource)
474 return OC_STACK_INVALID_PARAM;
477 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
479 // Check if virtual resource
480 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
482 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
483 *handling = OC_RESOURCE_VIRTUAL;
484 *resource = headResource;
487 if (strlen((const char*)(request->resourceUrl)) == 0)
489 // Resource URL not specified
490 *handling = OC_RESOURCE_NOT_SPECIFIED;
491 return OC_STACK_NO_RESOURCE;
495 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
496 *resource = resourcePtr;
499 if(defaultDeviceHandler)
501 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
505 // Resource does not exist
506 // and default device handler does not exist
507 *handling = OC_RESOURCE_NOT_SPECIFIED;
508 return OC_STACK_NO_RESOURCE;
511 if (IsCollectionResource (resourcePtr))
513 // Collection resource
514 if (resourcePtr->entityHandler != defaultResourceEHandler)
516 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
521 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
527 // Resource not a collection
528 if (resourcePtr->entityHandler != defaultResourceEHandler)
530 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
535 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
542 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
544 OCStackResult result;
551 result = OC_STACK_OK;
554 result = OC_STACK_SLOW_RESOURCE;
557 result = OC_STACK_ERROR;
559 case OC_EH_FORBIDDEN:
560 result = OC_STACK_FORBIDDEN_REQ;
562 case OC_EH_INTERNAL_SERVER_ERROR:
563 result = OC_STACK_INTERNAL_SERVER_ERROR;
565 case OC_EH_RESOURCE_CREATED:
566 result = OC_STACK_RESOURCE_CREATED;
568 case OC_EH_RESOURCE_DELETED:
569 result = OC_STACK_RESOURCE_DELETED;
572 result = OC_STACK_RESOURCE_CHANGED;
574 case OC_EH_RESOURCE_NOT_FOUND:
575 result = OC_STACK_NO_RESOURCE;
578 result = OC_STACK_ERROR;
584 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
591 // Null or empty is analogous to no filter.
592 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
597 OCResourceType *resourceTypePtr = resource->rsrcType;
599 while (resourceTypePtr)
601 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
605 resourceTypePtr = resourceTypePtr->next;
608 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
612 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
619 // Null or empty is analogous to no filter.
620 if (interfaceFilter == NULL || *interfaceFilter == 0)
625 OCResourceInterface *interfacePtr = resource->rsrcInterface;
629 if (strcmp (interfacePtr->name, interfaceFilter) == 0 ||
630 strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
631 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0)
635 interfacePtr = interfacePtr->next;
638 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
643 * If the filters are null, they will be assumed to NOT be present
644 * and the resource will not be matched against them.
645 * Function will return true if all non null AND non empty filters passed in find a match.
647 static bool includeThisResourceInResponse(OCResource *resource,
648 char *interfaceFilter,
649 char *resourceTypeFilter)
653 OIC_LOG(ERROR, TAG, "Invalid resource");
657 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
660 * At least one valid filter should be available to
661 * include the resource in discovery response
663 if (!(resourceTypeFilter && *resourceTypeFilter))
665 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
666 resource", resource->uri);
670 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
671 !(resource->resourceProperties & OC_DISCOVERABLE))
673 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
677 return resourceMatchesIFFilter(resource, interfaceFilter) &&
678 resourceMatchesRTFilter(resource, resourceTypeFilter);
682 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
683 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
685 OCEntityHandlerResponse response = {0};
687 response.ehResult = ehResult;
688 response.payload = discoveryPayload;
689 response.persistentBufferFlag = 0;
690 response.requestHandle = (OCRequestHandle) request;
691 response.resourceHandle = (OCResourceHandle) resource;
693 return OCDoResponse(&response);
697 * Find resource at the resource directory server. This resource is not local resource but a
700 * @param resource The resource to check the matching resource URI.
701 * @param interfaceQuery The interface query parameter.
702 * @param resourceTypeQuery The resourceType query parameter.
703 * @param discPayload The payload that will be added with the resource information if found at RD.
705 * @return ::OC_STACK_OK if the resource is found else ::OC_STACK_NO_RESOURCE.
706 * In case if build is not with flag RD_SERVER, it returns ::OC_STACK_NO_RESOURCE.
708 static OCStackResult findResourceAtRD(const OCResource* resource, const char *interfaceQuery,
709 const char *resourceTypeQuery, OCDiscoveryPayload *discPayload)
711 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
713 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
719 return OC_STACK_NO_RESOURCE;
724 * Creates a discovery payload and add device id information. This information is included in all
727 * @param payload payload that will have memory alllocated and device id information added.
729 * @return ::OC_STACK_OK if successful in allocating memory and adding ID information.
730 * ::OC_STACK_NO_MEMORY if failed allocating the memory.
732 static OCStackResult discoveryPayloadCreateAndAddDeviceId(OCPayload **payload)
736 OIC_LOG_V(DEBUG, TAG, "Payload is already allocated");
740 *payload = (OCPayload *) OCDiscoveryPayloadCreate();
741 VERIFY_PARAM_NON_NULL(TAG, *payload, "Failed adding device id to discovery payload.");
744 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)*payload;
745 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
746 VERIFY_PARAM_NON_NULL(TAG, discPayload->sid, "Failed adding device id to discovery payload.");
748 const char* uid = OCGetServerInstanceIDString();
751 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
757 OCPayloadDestroy(*payload);
758 return OC_STACK_NO_MEMORY;
762 * Add the common properties to the payload, they are only included in case of oic.if.baseline response.
764 * @param discPayload payload that will have the baseline information included.
766 * @return ::OC_STACK_OK if successful in adding all the information. ::OC_STACK_NO_MEMORY if failed
767 * allocating the memory for the baseline information.
769 static OCStackResult addDiscoveryBaselineCommonProperties(OCDiscoveryPayload *discPayload)
771 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
772 VERIFY_PARAM_NON_NULL(TAG, discPayload->uri, "Failed adding href to discovery payload.");
774 OCGetPropertyValue(PAYLOAD_TYPE_DEVICE, "deviceName", (void **)&discPayload->name);
775 VERIFY_PARAM_NON_NULL(TAG, discPayload->name, "Failed adding name to discovery payload.");
777 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
778 VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt to discovery payload.");
779 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
780 VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt value to discovery payload.");
782 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
783 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
784 VERIFY_PARAM_NON_NULL(TAG, discPayload->iface, "Failed adding if to discovery payload.");
789 return OC_STACK_NO_MEMORY;
792 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
794 if (!request || !resource)
796 return OC_STACK_INVALID_PARAM;
799 OCStackResult discoveryResult = OC_STACK_ERROR;
800 if (request->method == OC_REST_PUT || request->method == OC_REST_POST ||
801 request->method == OC_REST_DELETE)
803 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d",
804 request->resourceUrl, request->method);
805 return OC_STACK_UNAUTHORIZED_REQ;
808 OCPayload* payload = NULL;
809 char *interfaceQuery = NULL;
810 char *resourceTypeQuery = NULL;
811 char *dataModelVersions = NULL;
813 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
815 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
817 // Step 1: Generate the response to discovery request
818 if (virtualUriInRequest == OC_WELL_KNOWN_URI
820 || virtualUriInRequest == OC_MQ_BROKER_URI
824 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
825 &interfaceQuery, &resourceTypeQuery);
826 VERIFY_SUCCESS(discoveryResult);
827 if (!interfaceQuery && !resourceTypeQuery)
829 // If no query is sent, default interface is used i.e. oic.if.ll.
830 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
833 bool baselineQuery = false;
834 if (interfaceQuery && 0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))
836 baselineQuery = true;
839 discoveryResult = discoveryPayloadCreateAndAddDeviceId(&payload);
840 VERIFY_PARAM_NON_NULL(TAG, payload, "Failed creating Discovery Payload.");
841 VERIFY_SUCCESS(discoveryResult);
843 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
846 discoveryResult = addDiscoveryBaselineCommonProperties(discPayload);
847 VERIFY_SUCCESS(discoveryResult);
849 OCResourceProperty prop = OC_DISCOVERABLE;
851 prop = (OC_MQ_BROKER_URI == virtualUriInRequest) ? OC_MQ_BROKER : prop;
853 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
855 discoveryResult = OC_STACK_NO_RESOURCE;
857 discoveryResult = findResourceAtRD(resource, interfaceQuery, resourceTypeQuery,
860 if (OC_STACK_NO_RESOURCE == discoveryResult)
862 if ((!baselineQuery && (resource->resourceProperties & prop)) ||
863 (baselineQuery && (includeThisResourceInResponse(resource, interfaceQuery,
864 resourceTypeQuery))))
866 discoveryResult = BuildVirtualResourceResponse(resource, discPayload,
871 discoveryResult = OC_STACK_OK;
875 if (discPayload->resources == NULL)
877 discoveryResult = OC_STACK_NO_RESOURCE;
880 else if (virtualUriInRequest == OC_DEVICE_URI)
882 OCResource *resourcePtr = FindResourceByUri(OC_RSRVD_DEVICE_URI);
883 VERIFY_PARAM_NON_NULL(TAG, resourcePtr, "Device URI not found.");
884 discoveryResult = BuildResponseRepresentation(resourcePtr, (OCRepPayload **)&payload);
886 else if (virtualUriInRequest == OC_PLATFORM_URI)
888 OCResource *resourcePtr = FindResourceByUri(OC_RSRVD_PLATFORM_URI);
889 VERIFY_PARAM_NON_NULL(TAG, resourcePtr, "Platform URI not found.");
890 discoveryResult = BuildResponseRepresentation(resourcePtr, (OCRepPayload **)&payload);
892 #ifdef ROUTING_GATEWAY
893 else if (OC_GATEWAY_URI == virtualUriInRequest)
895 // Received request for a gateway
896 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
897 discoveryResult = RMHandleGatewayRequest(request, resource);
901 else if (OC_KEEPALIVE_RESOURCE_URI == virtualUriInRequest)
903 // Received request for a keepalive
904 OIC_LOG(INFO, TAG, "Request is for KeepAlive Request");
905 discoveryResult = HandleKeepAliveRequest(request, resource);
909 * Step 2: Send the discovery response
911 * Iotivity should respond to discovery requests in below manner:
912 * 1)If query filter matching fails and discovery request is multicast,
913 * it should NOT send any response.
914 * 2)If query filter matching fails and discovery request is unicast,
915 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
916 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
917 * request is multicast, it should NOT send any response.
918 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
919 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
923 if ((virtualUriInRequest == OC_PRESENCE) &&
924 (resource->resourceProperties & OC_ACTIVE))
926 // Need to send ACK when the request is CON.
927 if (request->qos == OC_HIGH_QOS)
929 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
930 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
931 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
932 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
934 FindAndDeleteServerRequest(request);
936 // Presence uses observer notification api to respond via SendPresenceNotification.
937 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
942 // Gateway uses the RMHandleGatewayRequest to respond to the request.
943 if (OC_GATEWAY_URI != virtualUriInRequest)
947 // KeepAlive uses the HandleKeepAliveRequest to respond to the request.
948 if (OC_KEEPALIVE_RESOURCE_URI != virtualUriInRequest)
951 OIC_LOG_PAYLOAD(DEBUG, payload);
952 if(discoveryResult == OC_STACK_OK)
954 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
956 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
957 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
958 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
960 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
961 discoveryResult, virtualUriInRequest);
962 SendNonPersistantDiscoveryResponse(request, resource, NULL,
963 (discoveryResult == OC_STACK_NO_RESOURCE) ?
964 OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
968 // Ignoring the discovery request as per RFC 7252, Section #8.2
969 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send.");
970 // the request should be removed.
971 // since it never remove and causes a big memory waste.
972 FindAndDeleteServerRequest(request);
980 OICFree(interfaceQuery);
983 if (resourceTypeQuery)
985 OICFree(resourceTypeQuery);
987 OCPayloadDestroy(payload);
988 if (dataModelVersions)
990 OICFree(dataModelVersions);
992 return discoveryResult;
996 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
1000 return OC_STACK_INVALID_PARAM;
1003 OCStackResult result = OC_STACK_OK;
1004 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1005 OCEntityHandlerRequest ehRequest = {0};
1007 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
1008 result = FormOCEntityHandlerRequest(&ehRequest,
1009 (OCRequestHandle) request,
1012 (OCResourceHandle) NULL, request->query,
1013 PAYLOAD_TYPE_REPRESENTATION,
1015 request->payloadSize,
1016 request->numRcvdVendorSpecificHeaderOptions,
1017 request->rcvdVendorSpecificHeaderOptions,
1018 (OCObserveAction)request->observationOption,
1021 VERIFY_SUCCESS(result);
1023 // At this point we know for sure that defaultDeviceHandler exists
1024 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
1025 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
1026 if(ehResult == OC_EH_SLOW)
1028 OIC_LOG(INFO, TAG, "This is a slow resource");
1029 request->slowFlag = 1;
1031 else if(ehResult == OC_EH_ERROR)
1033 FindAndDeleteServerRequest(request);
1035 result = EntityHandlerCodeToOCStackCode(ehResult);
1037 OCPayloadDestroy(ehRequest.payload);
1041 static OCStackResult
1042 HandleResourceWithEntityHandler (OCServerRequest *request,
1043 OCResource *resource,
1044 uint8_t collectionResource)
1046 OC_UNUSED(collectionResource);
1048 if(!request || ! resource)
1050 return OC_STACK_INVALID_PARAM;
1053 OCStackResult result = OC_STACK_ERROR;
1054 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1055 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1056 ResourceObserver *resObs = NULL;
1058 OCEntityHandlerRequest ehRequest = {0};
1060 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1061 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1062 // check the security resource
1063 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1065 type = PAYLOAD_TYPE_SECURITY;
1069 result = FormOCEntityHandlerRequest(&ehRequest,
1070 (OCRequestHandle)request,
1073 (OCResourceHandle)resource,
1077 request->payloadSize,
1078 request->numRcvdVendorSpecificHeaderOptions,
1079 request->rcvdVendorSpecificHeaderOptions,
1080 (OCObserveAction)request->observationOption,
1083 VERIFY_SUCCESS(result);
1085 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1087 OIC_LOG(INFO, TAG, "No observation requested");
1088 ehFlag = OC_REQUEST_FLAG;
1090 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER)
1092 OIC_LOG(INFO, TAG, "Observation registration requested");
1094 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1095 request->tokenLength);
1099 OIC_LOG (INFO, TAG, "Observer with this token already present");
1100 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1101 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1102 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1104 // server requests are usually free'd when the response is sent out
1105 // for the request in ocserverrequest.c : HandleSingleResponse()
1106 // Since we are making an early return and not responding, the server request
1107 // needs to be deleted.
1108 FindAndDeleteServerRequest (request);
1112 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1113 VERIFY_SUCCESS(result);
1115 result = AddObserver ((const char*)(request->resourceUrl),
1116 (const char *)(request->query),
1117 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1118 resource, request->qos, request->acceptFormat,
1121 if(result == OC_STACK_OK)
1123 OIC_LOG(INFO, TAG, "Added observer successfully");
1124 request->observeResult = OC_STACK_OK;
1125 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1127 else if (result == OC_STACK_RESOURCE_ERROR)
1129 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1130 request->observeResult = OC_STACK_ERROR;
1131 ehFlag = OC_REQUEST_FLAG;
1135 // The error in observeResult for the request will be used when responding to this
1136 // request by omitting the observation option/sequence number.
1137 request->observeResult = OC_STACK_ERROR;
1138 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1139 ehFlag = OC_REQUEST_FLAG;
1140 FindAndDeleteServerRequest(request);
1145 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER)
1147 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1149 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1153 // Stack does not contain this observation request
1154 // Either token is incorrect or observation list is corrupted
1155 result = OC_STACK_ERROR;
1158 ehRequest.obsInfo.obsId = resObs->observeId;
1159 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1161 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1163 if(result == OC_STACK_OK)
1165 OIC_LOG(INFO, TAG, "Removed observer successfully");
1166 request->observeResult = OC_STACK_OK;
1167 // There should be no observe option header for de-registration response.
1168 // Set as an invalid value here so we can detect it later and remove the field in response.
1169 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1173 request->observeResult = OC_STACK_ERROR;
1174 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1175 FindAndDeleteServerRequest(request);
1181 result = OC_STACK_ERROR;
1185 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1186 if(ehResult == OC_EH_SLOW)
1188 OIC_LOG(INFO, TAG, "This is a slow resource");
1189 request->slowFlag = 1;
1191 else if(ehResult == OC_EH_ERROR)
1193 FindAndDeleteServerRequest(request);
1195 result = EntityHandlerCodeToOCStackCode(ehResult);
1197 OCPayloadDestroy(ehRequest.payload);
1201 static OCStackResult
1202 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1203 OCResource *resource)
1205 if(!request || !resource)
1207 return OC_STACK_INVALID_PARAM;
1210 OCStackResult result = OC_STACK_ERROR;
1211 OCEntityHandlerRequest ehRequest = {0};
1213 result = FormOCEntityHandlerRequest(&ehRequest,
1214 (OCRequestHandle)request,
1217 (OCResourceHandle)resource,
1219 PAYLOAD_TYPE_REPRESENTATION,
1221 request->payloadSize,
1222 request->numRcvdVendorSpecificHeaderOptions,
1223 request->rcvdVendorSpecificHeaderOptions,
1224 (OCObserveAction)request->observationOption,
1227 if(result == OC_STACK_OK)
1229 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1232 OCPayloadDestroy(ehRequest.payload);
1237 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1239 OCStackResult ret = OC_STACK_OK;
1241 switch (resHandling)
1243 case OC_RESOURCE_VIRTUAL:
1245 ret = HandleVirtualResource (request, resource);
1248 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1250 ret = HandleDefaultDeviceEntityHandler(request);
1253 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1255 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1256 return OC_STACK_ERROR;
1258 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1260 ret = HandleResourceWithEntityHandler (request, resource, 0);
1263 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1265 ret = HandleResourceWithEntityHandler (request, resource, 1);
1268 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1270 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1273 case OC_RESOURCE_NOT_SPECIFIED:
1275 ret = OC_STACK_NO_RESOURCE;
1280 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1281 return OC_STACK_ERROR;
1287 OCStackResult OCSetPlatformInfo(OCPlatformInfo info)
1289 OCResource *resource = NULL;
1290 if (!info.platformID || !info.manufacturerName)
1292 OIC_LOG(ERROR, TAG, "No value specified.");
1295 if (0 == strlen(info.platformID) || 0 == strlen(info.manufacturerName))
1297 OIC_LOG(ERROR, TAG, "The passed value cannot be empty");
1300 if ((info.manufacturerName && strlen(info.manufacturerName) > MAX_PLATFORM_NAME_LENGTH) ||
1301 (info.manufacturerUrl && strlen(info.manufacturerUrl) > MAX_PLATFORM_URL_LENGTH) ||
1302 (info.modelNumber && strlen(info.modelNumber) > MAX_PLATFORM_NAME_LENGTH) ||
1303 (info.platformVersion && strlen(info.platformVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1304 (info.operatingSystemVersion && strlen(info.operatingSystemVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1305 (info.hardwareVersion && strlen(info.hardwareVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1306 (info.firmwareVersion && strlen(info.firmwareVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1307 (info.supportUrl && strlen(info.supportUrl) > MAX_PLATFORM_URL_LENGTH))
1309 OIC_LOG(ERROR, TAG, "The passed value is bigger than permitted.");
1313 resource = FindResourceByUri(OC_RSRVD_PLATFORM_URI);
1316 OIC_LOG(ERROR, TAG, "Platform Resource does not exist.");
1319 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
1320 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_PLATFORM_ID, info.platformID));
1321 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_NAME, info.manufacturerName));
1322 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_URL, info.manufacturerUrl);
1323 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MODEL_NUM, info.modelNumber);
1324 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_DATE, info.dateOfManufacture);
1325 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_PLATFORM_VERSION, info.platformVersion);
1326 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_OS_VERSION, info.operatingSystemVersion);
1327 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_HARDWARE_VERSION, info.hardwareVersion);
1328 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_FIRMWARE_VERSION, info.firmwareVersion);
1329 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_SUPPORT_URL, info.supportUrl);
1330 OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_SYSTEM_TIME, info.systemTime);
1331 OIC_LOG(INFO, TAG, "Platform parameter initialized successfully.");
1335 return OC_STACK_INVALID_PARAM;
1338 OCStackResult OCSetDeviceInfo(OCDeviceInfo info)
1340 OCStringLL *dataModelVersion = NULL;
1341 OCResource *resource = FindResourceByUri(OC_RSRVD_DEVICE_URI);
1344 OIC_LOG(ERROR, TAG, "Device Resource does not exist.");
1347 if (!info.deviceName || info.deviceName[0] == '\0')
1349 OIC_LOG(ERROR, TAG, "Null or empty device name.");
1350 return OC_STACK_INVALID_PARAM;
1353 if (OCGetServerInstanceIDString() == NULL)
1355 OIC_LOG(INFO, TAG, "Device ID generation failed");
1359 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME, info.deviceName));
1360 for (OCStringLL *temp = info.types; temp; temp = temp->next)
1364 VERIFY_SUCCESS(OCBindResourceTypeToResource(resource, temp->value));
1367 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, info.specVersion ?
1368 info.specVersion: OC_SPEC_VERSION));
1369 if (info.dataModelVersions)
1371 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION, info.dataModelVersions));
1375 dataModelVersion = OCCreateOCStringLL(OC_DATA_MODEL_VERSION);
1376 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION, dataModelVersion));
1378 OIC_LOG(INFO, TAG, "Device parameter initialized successfully.");
1382 if (dataModelVersion)
1384 OCFreeOCStringLL(dataModelVersion);
1386 return OC_STACK_ERROR;
1389 OCStackResult OCGetAttribute(const OCResource *resource, const char *attribute, void **value)
1391 if (!resource || !attribute)
1393 return OC_STACK_INVALID_PARAM;
1395 if (0 == strlen(attribute))
1397 return OC_STACK_INVALID_PARAM;
1399 for (OCAttribute *temp = resource->rsrcAttributes; temp; temp = temp->next)
1401 if (0 == strcmp(attribute, temp->attrName))
1403 // A special case as this type return OCStringLL
1404 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, attribute))
1406 *value = CloneOCStringLL((OCStringLL *)temp->attrValue);
1411 *value = OICStrdup((char *)temp->attrValue);
1416 return OC_STACK_NO_RESOURCE;
1419 OCStackResult OCGetPropertyValue(OCPayloadType type, const char *prop, void **value)
1421 if (!prop || *value)
1423 return OC_STACK_INVALID_PARAM;
1425 if (strlen(prop) == 0)
1427 return OC_STACK_INVALID_PARAM;
1429 OCStackResult res = OC_STACK_NO_RESOURCE;
1430 if (PAYLOAD_TYPE_DEVICE == type || PAYLOAD_TYPE_PLATFORM == type)
1432 const char *pathType = (type == PAYLOAD_TYPE_DEVICE) ? OC_RSRVD_DEVICE_URI : OC_RSRVD_PLATFORM_URI;
1433 OCResource *resource = FindResourceByUri(pathType);
1436 return OC_STACK_NO_RESOURCE;
1439 res = OCGetAttribute(resource, prop, value);
1444 OCStackResult OCSetAttribute(OCResource* resource, const char* attribute, const void* value)
1446 OCAttribute *resAttrib = (OCAttribute *)OICCalloc(1, sizeof(OCAttribute));
1447 VERIFY_PARAM_NON_NULL(TAG, resAttrib, "Failed allocation OCAttribute");
1448 resAttrib->attrName = OICStrdup(attribute);
1449 VERIFY_PARAM_NON_NULL(TAG, resAttrib->attrName, "Failed allocating attribute name");
1450 // A special case when value is of type OCStringLL
1451 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, attribute))
1453 resAttrib->attrValue = CloneOCStringLL((OCStringLL *)value);
1457 resAttrib->attrValue = OICStrdup((char *)value);
1459 VERIFY_PARAM_NON_NULL(TAG, resAttrib->attrValue, "Failed allocating attribute value");
1460 resAttrib->next = NULL;
1462 if (!resource->rsrcAttributes)
1464 resource->rsrcAttributes = resAttrib;
1468 OCAttribute *temp = resource->rsrcAttributes;
1469 for (; temp->next; temp = temp->next)
1471 if (0 == strcmp(attribute, temp->attrName))
1473 if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, temp->attrName))
1475 OCFreeOCStringLL((OCStringLL *)temp->attrValue);
1478 OICFree((char *)temp->attrValue);
1483 temp->next = resAttrib;
1488 OCDeleteResourceAttributes(resAttrib);
1489 return OC_STACK_NO_MEMORY;
1493 OCStackResult OCSetPropertyValue(OCPayloadType type, const char *prop, const void *value)
1497 return OC_STACK_INVALID_PARAM;
1499 if (strlen(prop) == 0)
1501 return OC_STACK_INVALID_PARAM;
1504 OCStackResult res = OC_STACK_ERROR;
1505 if (PAYLOAD_TYPE_DEVICE == type || PAYLOAD_TYPE_PLATFORM == type)
1507 const char *pathType = (type == PAYLOAD_TYPE_DEVICE) ? OC_RSRVD_DEVICE_URI : OC_RSRVD_PLATFORM_URI;
1508 OCResource *resource = FindResourceByUri(pathType);
1511 OIC_LOG(ERROR, TAG, "Resource does not exist.");
1515 res = OCSetAttribute(resource, prop, value);