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, successCode) { if (op != successCode) \
67 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
69 extern OCResource *headResource;
70 static OCPlatformInfo savedPlatformInfo = {0};
71 static OCDeviceInfo savedDeviceInfo = {0};
74 * Prepares a Payload for response.
76 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
77 OCDiscoveryPayload* payload,
80 //-----------------------------------------------------------------------------
81 // Default resource entity handler function
82 //-----------------------------------------------------------------------------
83 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
84 OCEntityHandlerRequest * request, void* callbackParam)
86 //TODO ("Implement me!!!!");
87 // TODO: remove silence unused param warnings
91 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
94 /* This method will retrieve the port at which the secure resource is hosted */
95 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
99 if (endpoint->adapter == OC_ADAPTER_IP)
101 if (endpoint->flags & OC_IP_USE_V6)
103 p = caglobals.ip.u6s.port;
105 else if (endpoint->flags & OC_IP_USE_V4)
107 p = caglobals.ip.u4s.port;
116 /* This method will retrieve the tcp port */
117 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
121 if (endpoint->adapter == OC_ADAPTER_IP)
123 if (endpoint->flags & OC_IP_USE_V4)
125 p = caglobals.tcp.ipv4.port;
127 else if (endpoint->flags & OC_IP_USE_V6)
129 p = caglobals.tcp.ipv6.port;
139 * Function will extract 0, 1 or 2 filters from query.
140 * More than 2 filters or unsupported filters will result in error.
141 * If both filters are of the same supported type, the 2nd one will be picked.
142 * Resource and device filters in the SAME query are NOT validated
143 * and resources will likely not clear filters.
145 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
149 char *queryDup = NULL;
150 char *restOfQuery = NULL;
151 char *keyValuePair = NULL;
152 int numKeyValuePairsParsed = 0;
157 queryDup = OICStrdup(query);
158 if (NULL == queryDup)
160 OIC_LOG_V(ERROR, TAG, "Creating duplicate string failed!");
161 return OC_STACK_NO_MEMORY;
164 OIC_LOG_V(INFO, TAG, "Extracting params from %s", queryDup);
166 OCStackResult eCode = OC_STACK_INVALID_QUERY;
167 if (strnlen(queryDup, MAX_QUERY_LENGTH) >= MAX_QUERY_LENGTH)
169 OIC_LOG(ERROR, TAG, "Query exceeds maximum length.");
173 keyValuePair = strtok_r (queryDup, OC_QUERY_SEPARATOR, &restOfQuery);
177 if (numKeyValuePairsParsed >= 2)
179 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
183 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
189 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
191 *filterOne = value; // if
193 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
195 *filterTwo = value; // rt
199 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
202 ++numKeyValuePairsParsed;
204 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
209 *filterOne = OICStrdup(*filterOne);
210 if (NULL == *filterOne)
212 OIC_LOG_V(ERROR, TAG, "Creating duplicate string failed!");
213 eCode = OC_STACK_NO_MEMORY;
220 *filterTwo = OICStrdup(*filterTwo);
221 if (NULL == *filterTwo)
223 OIC_LOG_V(ERROR, TAG, "Creating duplicate string failed!");
225 eCode = OC_STACK_NO_MEMORY;
231 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
241 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
243 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
245 return OC_WELL_KNOWN_URI;
247 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
249 return OC_DEVICE_URI;
251 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
253 return OC_PLATFORM_URI;
255 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
257 return OC_RESOURCE_TYPES_URI;
259 #ifdef ROUTING_GATEWAY
260 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
262 return OC_GATEWAY_URI;
266 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
270 #endif //WITH_PRESENCE
273 else if (0 == strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_MQ_URI))
275 return OC_MQ_BROKER_URI;
280 else if (strcmp(uriInRequest, OC_RSRVD_KEEPALIVE_URI) == 0)
282 return OC_KEEPALIVE_RESOURCE_URI;
286 return OC_UNKNOWN_URI;
289 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
290 char **filterOne, char **filterTwo)
292 if(!filterOne || !filterTwo)
294 return OC_STACK_INVALID_PARAM;
301 if (uri == OC_PRESENCE)
303 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
304 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
309 OCStackResult result = OC_STACK_OK;
313 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
319 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
320 OCRepPayload** payload)
322 OCRepPayload *tempPayload = OCRepPayloadCreate();
326 OCRepPayloadDestroy(tempPayload);
327 return OC_STACK_INVALID_PARAM;
332 return OC_STACK_NO_MEMORY;
335 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
337 OCResourceType *resType = resourcePtr->rsrcType;
340 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
341 resType = resType->next;
344 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
347 OCRepPayloadAddInterface(tempPayload, resInterface->name);
348 resInterface = resInterface->next;
351 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
354 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
355 resAttrib->attrValue);
356 resAttrib = resAttrib->next;
361 *payload = tempPayload;
365 OCRepPayloadAppend(*payload, tempPayload);
371 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
372 OCDiscoveryPayload *payload, OCDevAddr *devAddr)
374 if (!resourcePtr || !payload)
376 return OC_STACK_INVALID_PARAM;
378 uint16_t securePort = 0;
379 if (resourcePtr->resourceProperties & OC_SECURE)
381 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
388 uint16_t tcpPort = 0;
389 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
393 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
395 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
401 uint8_t IsCollectionResource (OCResource *resource)
408 if(resource->rsrcChildResourcesHead != NULL)
416 OCResource *FindResourceByUri(const char* resourceUri)
423 OCResource * pointer = headResource;
426 if (strcmp(resourceUri, pointer->uri) == 0)
430 pointer = pointer->next;
432 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
437 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
438 ResourceHandling *handling,
439 OCResource **resource)
441 if(!request || !handling || !resource)
443 return OC_STACK_INVALID_PARAM;
446 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
448 // Check if virtual resource
449 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
451 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
452 *handling = OC_RESOURCE_VIRTUAL;
453 *resource = headResource;
456 if (strlen((const char*)(request->resourceUrl)) == 0)
458 // Resource URL not specified
459 *handling = OC_RESOURCE_NOT_SPECIFIED;
460 return OC_STACK_NO_RESOURCE;
464 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
465 *resource = resourcePtr;
468 if(defaultDeviceHandler)
470 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
474 // Resource does not exist
475 // and default device handler does not exist
476 *handling = OC_RESOURCE_NOT_SPECIFIED;
477 return OC_STACK_NO_RESOURCE;
480 if (IsCollectionResource (resourcePtr))
482 // Collection resource
483 if (resourcePtr->entityHandler != defaultResourceEHandler)
485 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
490 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
496 // Resource not a collection
497 if (resourcePtr->entityHandler != defaultResourceEHandler)
499 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
504 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
511 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
513 OCStackResult result;
520 result = OC_STACK_OK;
523 result = OC_STACK_SLOW_RESOURCE;
526 result = OC_STACK_ERROR;
528 case OC_EH_FORBIDDEN:
529 result = OC_STACK_FORBIDDEN_REQ;
531 case OC_EH_INTERNAL_SERVER_ERROR:
532 result = OC_STACK_INTERNAL_SERVER_ERROR;
534 case OC_EH_RESOURCE_CREATED:
535 result = OC_STACK_RESOURCE_CREATED;
537 case OC_EH_RESOURCE_DELETED:
538 result = OC_STACK_RESOURCE_DELETED;
541 result = OC_STACK_RESOURCE_CHANGED;
543 case OC_EH_RESOURCE_NOT_FOUND:
544 result = OC_STACK_NO_RESOURCE;
547 result = OC_STACK_ERROR;
553 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
560 // Null or empty is analogous to no filter.
561 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
566 OCResourceType *resourceTypePtr = resource->rsrcType;
568 while (resourceTypePtr)
570 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
574 resourceTypePtr = resourceTypePtr->next;
577 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
581 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
588 // Null or empty is analogous to no filter.
589 if (interfaceFilter == NULL || *interfaceFilter == 0)
594 OCResourceInterface *interfacePtr = resource->rsrcInterface;
598 if (strcmp (interfacePtr->name, interfaceFilter) == 0 ||
599 strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
600 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0)
604 interfacePtr = interfacePtr->next;
607 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
612 * If the filters are null, they will be assumed to NOT be present
613 * and the resource will not be matched against them.
614 * Function will return true if all non null AND non empty filters passed in find a match.
616 static bool includeThisResourceInResponse(OCResource *resource,
617 char *interfaceFilter,
618 char *resourceTypeFilter)
622 OIC_LOG(ERROR, TAG, "Invalid resource");
626 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
629 * At least one valid filter should be available to
630 * include the resource in discovery response
632 if (!(resourceTypeFilter && *resourceTypeFilter))
634 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
635 resource", resource->uri);
639 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
640 !(resource->resourceProperties & OC_DISCOVERABLE))
642 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
646 return resourceMatchesIFFilter(resource, interfaceFilter) &&
647 resourceMatchesRTFilter(resource, resourceTypeFilter);
651 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
652 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
654 OCEntityHandlerResponse response = {0};
656 response.ehResult = ehResult;
657 response.payload = discoveryPayload;
658 response.persistentBufferFlag = 0;
659 response.requestHandle = (OCRequestHandle) request;
660 response.resourceHandle = (OCResourceHandle) resource;
662 return OCDoResponse(&response);
666 * Find resource at the resource directory server. This resource is not local resource but a
669 * @param resource The resource to check the matching resource URI.
670 * @param interfaceQuery The interface query parameter.
671 * @param resourceTypeQuery The resourceType query parameter.
672 * @param discPayload The payload that will be added with the resource information if found at RD.
674 * @return ::OC_STACK_OK if the resource is found else ::OC_STACK_NO_RESOURCE.
675 * In case if build is not with flag RD_SERVER, it returns ::OC_STACK_NO_RESOURCE.
677 static OCStackResult findResourceAtRD(const OCResource* resource, const char *interfaceQuery,
678 const char *resourceTypeQuery, OCDiscoveryPayload *discPayload)
680 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
682 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
688 return OC_STACK_NO_RESOURCE;
693 * Creates a discovery payload and add device id information. This information is included in all
696 * @param payload payload that will have memory alllocated and device id information added.
698 * @return ::OC_STACK_OK if successful in allocating memory and adding ID information.
699 * ::OC_STACK_NO_MEMORY if failed allocating the memory.
701 static OCStackResult discoveryPayloadCreateAndAddDeviceId(OCPayload **payload)
705 OIC_LOG_V(DEBUG, TAG, "Payload is already allocated");
709 *payload = (OCPayload *) OCDiscoveryPayloadCreate();
710 VERIFY_PARAM_NON_NULL(TAG, *payload, "Failed adding device id to discovery payload.");
713 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)*payload;
714 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
715 VERIFY_PARAM_NON_NULL(TAG, discPayload->sid, "Failed adding device id to discovery payload.");
717 const char* uid = OCGetServerInstanceIDString();
720 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
726 OCPayloadDestroy(*payload);
727 return OC_STACK_NO_MEMORY;
731 * Add the common properties to the payload, they are only included in case of oic.if.baseline response.
733 * @param discPayload payload that will have the baseline information included.
735 * @return ::OC_STACK_OK if successful in adding all the information. ::OC_STACK_NO_MEMORY if failed
736 * allocating the memory for the baseline information.
738 static OCStackResult addDiscoveryBaselineCommonProperties(OCDiscoveryPayload *discPayload)
740 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
741 VERIFY_PARAM_NON_NULL(TAG, discPayload->uri, "Failed adding href to discovery payload.");
743 if (savedDeviceInfo.deviceName)
745 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
746 VERIFY_PARAM_NON_NULL(TAG, discPayload->name, "Failed adding name to discovery payload.");
749 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
750 VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt to discovery payload.");
751 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
752 VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt value to discovery payload.");
754 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
755 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
756 VERIFY_PARAM_NON_NULL(TAG, discPayload->iface, "Failed adding if to discovery payload.");
761 return OC_STACK_NO_MEMORY;
764 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
766 if (!request || !resource)
768 return OC_STACK_INVALID_PARAM;
771 OCStackResult discoveryResult = OC_STACK_ERROR;
772 OCPayload* payload = NULL;
773 char *interfaceQuery = NULL;
774 char *resourceTypeQuery = NULL;
775 char *dataModelVersions = NULL;
777 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
779 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
781 // Step 1: Generate the response to discovery request
782 if (virtualUriInRequest == OC_WELL_KNOWN_URI
784 || virtualUriInRequest == OC_MQ_BROKER_URI
788 if (request->method == OC_REST_PUT || request->method == OC_REST_POST ||
789 request->method == OC_REST_DELETE)
791 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d",
792 request->resourceUrl, request->method);
793 discoveryResult = OC_STACK_UNAUTHORIZED_REQ;
797 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
798 &interfaceQuery, &resourceTypeQuery);
799 VERIFY_SUCCESS(discoveryResult, OC_STACK_OK);
800 if (!interfaceQuery && !resourceTypeQuery)
802 // If no query is sent, default interface is used i.e. oic.if.ll.
803 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
806 bool baselineQuery = false;
807 if (interfaceQuery && 0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))
809 baselineQuery = true;
812 discoveryResult = discoveryPayloadCreateAndAddDeviceId(&payload);
813 VERIFY_PARAM_NON_NULL(TAG, payload, "Failed creating Discovery Payload.");
814 VERIFY_SUCCESS(discoveryResult, OC_STACK_OK);
816 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
819 discoveryResult = addDiscoveryBaselineCommonProperties(discPayload);
820 VERIFY_SUCCESS(discoveryResult, OC_STACK_OK);
822 OCResourceProperty prop = OC_DISCOVERABLE;
824 prop = (OC_MQ_BROKER_URI == virtualUriInRequest) ? OC_MQ_BROKER : prop;
826 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
828 discoveryResult = OC_STACK_NO_RESOURCE;
830 discoveryResult = findResourceAtRD(resource, interfaceQuery, resourceTypeQuery,
833 if (OC_STACK_NO_RESOURCE == discoveryResult)
835 if ((!baselineQuery && (resource->resourceProperties & prop)) ||
836 (baselineQuery && (includeThisResourceInResponse(resource, interfaceQuery,
837 resourceTypeQuery))))
839 discoveryResult = BuildVirtualResourceResponse(resource, discPayload,
844 discoveryResult = OC_STACK_OK;
848 if (discPayload->resources == NULL)
850 discoveryResult = OC_STACK_NO_RESOURCE;
853 else if (virtualUriInRequest == OC_DEVICE_URI)
855 if (request->method == OC_REST_PUT || request->method == OC_REST_POST ||
856 request->method == OC_REST_DELETE)
858 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d",
859 request->resourceUrl, request->method);
860 discoveryResult = OC_STACK_UNAUTHORIZED_REQ;
864 const char* deviceId = OCGetServerInstanceIDString();
865 VERIFY_PARAM_NON_NULL(TAG, deviceId, "Failed retrieving device id.");
866 discoveryResult = OC_STACK_NO_MEMORY;
867 dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
868 VERIFY_PARAM_NON_NULL(TAG, dataModelVersions, "Failed adding data model version.");
869 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
870 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
871 VERIFY_PARAM_NON_NULL(TAG, payload, "Failed adding device payload.");
873 else if (virtualUriInRequest == OC_PLATFORM_URI)
875 if (request->method == OC_REST_PUT || request->method == OC_REST_POST ||
876 request->method == OC_REST_DELETE)
878 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d",
879 request->resourceUrl, request->method);
880 discoveryResult = OC_STACK_UNAUTHORIZED_REQ;
884 discoveryResult = OC_STACK_NO_MEMORY;
885 payload = (OCPayload *)OCPlatformPayloadCreate(&savedPlatformInfo);
886 VERIFY_PARAM_NON_NULL(TAG, payload, "Failed adding platform payload.");
888 #ifdef ROUTING_GATEWAY
889 else if (OC_GATEWAY_URI == virtualUriInRequest)
891 // Received request for a gateway
892 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
893 discoveryResult = RMHandleGatewayRequest(request, resource);
897 else if (OC_KEEPALIVE_RESOURCE_URI == virtualUriInRequest)
899 // Received request for a keepalive
900 OIC_LOG(INFO, TAG, "Request is for KeepAlive Request");
901 discoveryResult = HandleKeepAliveRequest(request, resource);
905 * Step 2: Send the discovery response
907 * Iotivity should respond to discovery requests in below manner:
908 * 1)If query filter matching fails and discovery request is multicast,
909 * it should NOT send any response.
910 * 2)If query filter matching fails and discovery request is unicast,
911 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
912 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
913 * request is multicast, it should NOT send any response.
914 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
915 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
919 if ((virtualUriInRequest == OC_PRESENCE) &&
920 (resource->resourceProperties & OC_ACTIVE))
922 // Need to send ACK when the request is CON.
923 if (request->qos == OC_HIGH_QOS)
925 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
926 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
927 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
928 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
930 FindAndDeleteServerRequest(request);
932 // Presence uses observer notification api to respond via SendPresenceNotification.
933 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
938 // Gateway uses the RMHandleGatewayRequest to respond to the request.
939 if (OC_GATEWAY_URI != virtualUriInRequest)
943 // KeepAlive uses the HandleKeepAliveRequest to respond to the request.
944 if (OC_KEEPALIVE_RESOURCE_URI != virtualUriInRequest)
947 OIC_LOG_PAYLOAD(DEBUG, payload);
948 if(discoveryResult == OC_STACK_OK)
950 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
952 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
953 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
954 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
956 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
957 discoveryResult, virtualUriInRequest);
958 SendNonPersistantDiscoveryResponse(request, resource, NULL,
959 (discoveryResult == OC_STACK_NO_RESOURCE) ?
960 OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
964 // Ignoring the discovery request as per RFC 7252, Section #8.2
965 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send.");
966 // the request should be removed.
967 // since it never remove and causes a big memory waste.
968 FindAndDeleteServerRequest(request);
976 OICFree(interfaceQuery);
979 if (resourceTypeQuery)
981 OICFree(resourceTypeQuery);
983 OCPayloadDestroy(payload);
984 if (dataModelVersions)
986 OICFree(dataModelVersions);
988 return discoveryResult;
992 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
996 return OC_STACK_INVALID_PARAM;
999 OCStackResult result = OC_STACK_OK;
1000 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1001 OCEntityHandlerRequest ehRequest = {0};
1003 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
1004 result = FormOCEntityHandlerRequest(&ehRequest,
1005 (OCRequestHandle) request,
1008 (OCResourceHandle) NULL, request->query,
1009 PAYLOAD_TYPE_REPRESENTATION,
1011 request->payloadSize,
1012 request->numRcvdVendorSpecificHeaderOptions,
1013 request->rcvdVendorSpecificHeaderOptions,
1014 (OCObserveAction)request->observationOption,
1017 VERIFY_SUCCESS(result, OC_STACK_OK);
1019 // At this point we know for sure that defaultDeviceHandler exists
1020 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
1021 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
1022 if(ehResult == OC_EH_SLOW)
1024 OIC_LOG(INFO, TAG, "This is a slow resource");
1025 request->slowFlag = 1;
1027 else if(ehResult == OC_EH_ERROR)
1029 FindAndDeleteServerRequest(request);
1031 result = EntityHandlerCodeToOCStackCode(ehResult);
1033 OCPayloadDestroy(ehRequest.payload);
1037 static OCStackResult
1038 HandleResourceWithEntityHandler (OCServerRequest *request,
1039 OCResource *resource,
1040 uint8_t collectionResource)
1042 OC_UNUSED(collectionResource);
1044 if(!request || ! resource)
1046 return OC_STACK_INVALID_PARAM;
1049 OCStackResult result = OC_STACK_ERROR;
1050 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1051 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1052 ResourceObserver *resObs = NULL;
1054 OCEntityHandlerRequest ehRequest = {0};
1056 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1057 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1058 // check the security resource
1059 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1061 type = PAYLOAD_TYPE_SECURITY;
1065 result = FormOCEntityHandlerRequest(&ehRequest,
1066 (OCRequestHandle)request,
1069 (OCResourceHandle)resource,
1073 request->payloadSize,
1074 request->numRcvdVendorSpecificHeaderOptions,
1075 request->rcvdVendorSpecificHeaderOptions,
1076 (OCObserveAction)request->observationOption,
1079 VERIFY_SUCCESS(result, OC_STACK_OK);
1081 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1083 OIC_LOG(INFO, TAG, "No observation requested");
1084 ehFlag = OC_REQUEST_FLAG;
1086 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER)
1088 OIC_LOG(INFO, TAG, "Observation registration requested");
1090 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1091 request->tokenLength);
1095 OIC_LOG (INFO, TAG, "Observer with this token already present");
1096 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1097 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1098 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1100 // server requests are usually free'd when the response is sent out
1101 // for the request in ocserverrequest.c : HandleSingleResponse()
1102 // Since we are making an early return and not responding, the server request
1103 // needs to be deleted.
1104 FindAndDeleteServerRequest (request);
1108 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1109 VERIFY_SUCCESS(result, OC_STACK_OK);
1111 result = AddObserver ((const char*)(request->resourceUrl),
1112 (const char *)(request->query),
1113 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1114 resource, request->qos, request->acceptFormat,
1117 if(result == OC_STACK_OK)
1119 OIC_LOG(INFO, TAG, "Added observer successfully");
1120 request->observeResult = OC_STACK_OK;
1121 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1123 else if (result == OC_STACK_RESOURCE_ERROR)
1125 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1126 request->observeResult = OC_STACK_ERROR;
1127 ehFlag = OC_REQUEST_FLAG;
1131 // The error in observeResult for the request will be used when responding to this
1132 // request by omitting the observation option/sequence number.
1133 request->observeResult = OC_STACK_ERROR;
1134 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1135 ehFlag = OC_REQUEST_FLAG;
1136 FindAndDeleteServerRequest(request);
1141 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER)
1143 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1145 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1149 // Stack does not contain this observation request
1150 // Either token is incorrect or observation list is corrupted
1151 result = OC_STACK_ERROR;
1154 ehRequest.obsInfo.obsId = resObs->observeId;
1155 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1157 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1159 if(result == OC_STACK_OK)
1161 OIC_LOG(INFO, TAG, "Removed observer successfully");
1162 request->observeResult = OC_STACK_OK;
1163 // There should be no observe option header for de-registration response.
1164 // Set as an invalid value here so we can detect it later and remove the field in response.
1165 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1169 request->observeResult = OC_STACK_ERROR;
1170 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1171 FindAndDeleteServerRequest(request);
1177 result = OC_STACK_ERROR;
1181 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1182 if(ehResult == OC_EH_SLOW)
1184 OIC_LOG(INFO, TAG, "This is a slow resource");
1185 request->slowFlag = 1;
1187 else if(ehResult == OC_EH_ERROR)
1189 FindAndDeleteServerRequest(request);
1191 result = EntityHandlerCodeToOCStackCode(ehResult);
1193 OCPayloadDestroy(ehRequest.payload);
1197 static OCStackResult
1198 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1199 OCResource *resource)
1201 if(!request || !resource)
1203 return OC_STACK_INVALID_PARAM;
1206 OCStackResult result = OC_STACK_ERROR;
1207 OCEntityHandlerRequest ehRequest = {0};
1209 result = FormOCEntityHandlerRequest(&ehRequest,
1210 (OCRequestHandle)request,
1213 (OCResourceHandle)resource,
1215 PAYLOAD_TYPE_REPRESENTATION,
1217 request->payloadSize,
1218 request->numRcvdVendorSpecificHeaderOptions,
1219 request->rcvdVendorSpecificHeaderOptions,
1220 (OCObserveAction)request->observationOption,
1223 if(result == OC_STACK_OK)
1225 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1228 OCPayloadDestroy(ehRequest.payload);
1233 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1235 OCStackResult ret = OC_STACK_OK;
1237 switch (resHandling)
1239 case OC_RESOURCE_VIRTUAL:
1241 ret = HandleVirtualResource (request, resource);
1244 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1246 ret = HandleDefaultDeviceEntityHandler(request);
1249 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1251 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1252 return OC_STACK_ERROR;
1254 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1256 ret = HandleResourceWithEntityHandler (request, resource, 0);
1259 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1261 ret = HandleResourceWithEntityHandler (request, resource, 1);
1264 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1266 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1269 case OC_RESOURCE_NOT_SPECIFIED:
1271 ret = OC_STACK_NO_RESOURCE;
1276 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1277 return OC_STACK_ERROR;
1283 void DeletePlatformInfo()
1285 OIC_LOG(INFO, TAG, "Deleting platform info.");
1287 OICFree(savedPlatformInfo.platformID);
1288 savedPlatformInfo.platformID = NULL;
1290 OICFree(savedPlatformInfo.manufacturerName);
1291 savedPlatformInfo.manufacturerName = NULL;
1293 OICFree(savedPlatformInfo.manufacturerUrl);
1294 savedPlatformInfo.manufacturerUrl = NULL;
1296 OICFree(savedPlatformInfo.modelNumber);
1297 savedPlatformInfo.modelNumber = NULL;
1299 OICFree(savedPlatformInfo.dateOfManufacture);
1300 savedPlatformInfo.dateOfManufacture = NULL;
1302 OICFree(savedPlatformInfo.platformVersion);
1303 savedPlatformInfo.platformVersion = NULL;
1305 OICFree(savedPlatformInfo.operatingSystemVersion);
1306 savedPlatformInfo.operatingSystemVersion = NULL;
1308 OICFree(savedPlatformInfo.hardwareVersion);
1309 savedPlatformInfo.hardwareVersion = NULL;
1311 OICFree(savedPlatformInfo.firmwareVersion);
1312 savedPlatformInfo.firmwareVersion = NULL;
1314 OICFree(savedPlatformInfo.supportUrl);
1315 savedPlatformInfo.supportUrl = NULL;
1317 OICFree(savedPlatformInfo.systemTime);
1318 savedPlatformInfo.systemTime = NULL;
1321 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1323 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1324 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1325 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1326 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1327 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1328 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1329 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1330 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1331 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1332 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1333 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1335 if ((!savedPlatformInfo.platformID && info.platformID)||
1336 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1337 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1338 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1339 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1340 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1341 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1342 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1343 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1344 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1345 (!savedPlatformInfo.systemTime && info.systemTime))
1347 DeletePlatformInfo();
1348 return OC_STACK_INVALID_PARAM;
1355 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1357 DeletePlatformInfo();
1359 OCStackResult res = DeepCopyPlatFormInfo(info);
1361 if (res != OC_STACK_OK)
1363 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1367 OIC_LOG(INFO, TAG, "Platform info saved.");
1373 void DeleteDeviceInfo()
1375 OIC_LOG(INFO, TAG, "Deleting device info.");
1377 OICFree(savedDeviceInfo.deviceName);
1378 OCFreeOCStringLL(savedDeviceInfo.types);
1379 OICFree(savedDeviceInfo.specVersion);
1380 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1381 savedDeviceInfo.deviceName = NULL;
1382 savedDeviceInfo.specVersion = NULL;
1383 savedDeviceInfo.dataModelVersions = NULL;
1386 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1388 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1390 if(!savedDeviceInfo.deviceName && info.deviceName)
1393 return OC_STACK_NO_MEMORY;
1398 savedDeviceInfo.types = CloneOCStringLL(info.types);
1399 OCStringLL *type = info.types;
1403 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1411 // Append the oic.wk.d at the start of rt link parameter value.
1412 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1416 return OC_STACK_NO_MEMORY;
1418 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1422 return OC_STACK_NO_MEMORY;
1424 dest->next = savedDeviceInfo.types;
1425 savedDeviceInfo.types = dest;
1427 if(!savedDeviceInfo.types && info.types)
1430 return OC_STACK_NO_MEMORY;
1434 if (info.specVersion)
1436 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1437 if(!savedDeviceInfo.specVersion && info.specVersion)
1440 return OC_STACK_NO_MEMORY;
1445 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1446 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1449 return OC_STACK_NO_MEMORY;
1453 if (info.dataModelVersions)
1455 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1456 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1459 return OC_STACK_NO_MEMORY;
1464 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1465 if (!savedDeviceInfo.dataModelVersions)
1467 return OC_STACK_NO_MEMORY;
1469 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1470 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1473 return OC_STACK_NO_MEMORY;
1480 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1482 OCStackResult res = OC_STACK_OK;
1486 res = DeepCopyDeviceInfo(info);
1488 VERIFY_SUCCESS(res, OC_STACK_OK);
1490 if (OCGetServerInstanceIDString() == NULL)
1492 OIC_LOG(INFO, TAG, "Device ID generation failed");
1493 res = OC_STACK_ERROR;
1497 OIC_LOG(INFO, TAG, "Device initialized successfully.");