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
36 #include "ocresource.h"
37 #include "ocresourcehandler.h"
38 #include "ocobserve.h"
39 #include "occollection.h"
40 #include "oic_malloc.h"
41 #include "oic_string.h"
44 #include "ocpayload.h"
45 #include "secureresourcemanager.h"
47 #include "cainterface.h"
48 #include "rdpayload.h"
49 #include "ocpayload.h"
52 #include "rd_server.h"
55 #ifdef ROUTING_GATEWAY
56 #include "routingmanager.h"
60 #define TAG "OIC_RI_RESOURCE"
62 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
63 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
65 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
66 TAG, #arg " is NULL"); return (retVal); } }
68 #include "platform_features.h"
70 extern OCResource *headResource;
71 static OCPlatformInfo savedPlatformInfo = {0};
72 static OCDeviceInfo savedDeviceInfo = {0};
75 * Prepares a Payload for response.
77 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
78 OCDiscoveryPayload* payload,
82 //-----------------------------------------------------------------------------
83 // Default resource entity handler function
84 //-----------------------------------------------------------------------------
85 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
86 OCEntityHandlerRequest * request, void* callbackParam)
88 //TODO ("Implement me!!!!");
89 // TODO: remove silence unused param warnings
93 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
96 /* This method will retrieve the port at which the secure resource is hosted */
97 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
101 if (endpoint->adapter == OC_ADAPTER_IP)
103 if (endpoint->flags & OC_IP_USE_V6)
105 p = caglobals.ip.u6s.port;
107 else if (endpoint->flags & OC_IP_USE_V4)
109 p = caglobals.ip.u4s.port;
118 /* This method will retrieve the tcp port */
119 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
123 if (endpoint->adapter == OC_ADAPTER_IP)
125 if (endpoint->flags & OC_IP_USE_V4)
127 p = caglobals.tcp.ipv4.port;
129 else if (endpoint->flags & OC_IP_USE_V6)
131 p = caglobals.tcp.ipv6.port;
141 * Function will extract 0, 1 or 2 filters from query.
142 * More than 2 filters or unsupported filters will result in error.
143 * If both filters are of the same supported type, the 2nd one will be picked.
144 * Resource and device filters in the SAME query are NOT validated
145 * and resources will likely not clear filters.
147 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
152 char *restOfQuery = NULL;
153 int numKeyValuePairsParsed = 0;
158 OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
160 if (strnlen(query, MAX_QUERY_LENGTH) >= MAX_QUERY_LENGTH)
162 OIC_LOG(ERROR, TAG, "Query exceeds maximum length.");
163 return OC_STACK_INVALID_QUERY;
166 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
170 if (numKeyValuePairsParsed >= 2)
172 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
173 return OC_STACK_INVALID_QUERY;
176 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
180 return OC_STACK_INVALID_QUERY;
182 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
184 *filterOne = value; // if
186 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
188 *filterTwo = value; // rt
192 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
193 return OC_STACK_INVALID_QUERY;
195 ++numKeyValuePairsParsed;
197 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
200 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
204 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
206 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
208 return OC_WELL_KNOWN_URI;
210 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
212 return OC_DEVICE_URI;
214 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
216 return OC_PLATFORM_URI;
218 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
220 return OC_RESOURCE_TYPES_URI;
222 #ifdef ROUTING_GATEWAY
223 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
225 return OC_GATEWAY_URI;
229 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
233 #endif //WITH_PRESENCE
236 else if (0 == strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_MQ_URI))
238 return OC_MQ_BROKER_URI;
241 return OC_UNKNOWN_URI;
244 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
245 char **filterOne, char **filterTwo)
247 if(!filterOne || !filterTwo)
249 return OC_STACK_INVALID_PARAM;
256 if (uri == OC_PRESENCE)
258 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
259 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
264 OCStackResult result = OC_STACK_OK;
268 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
274 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
275 OCRepPayload** payload)
277 OCRepPayload *tempPayload = OCRepPayloadCreate();
281 OCRepPayloadDestroy(tempPayload);
282 return OC_STACK_INVALID_PARAM;
287 return OC_STACK_NO_MEMORY;
290 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
292 OCResourceType *resType = resourcePtr->rsrcType;
295 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
296 resType = resType->next;
299 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
302 OCRepPayloadAddInterface(tempPayload, resInterface->name);
303 resInterface = resInterface->next;
306 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
309 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
310 resAttrib->attrValue);
311 resAttrib = resAttrib->next;
316 *payload = tempPayload;
320 OCRepPayloadAppend(*payload, tempPayload);
326 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
327 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
329 if (!resourcePtr || !payload)
331 return OC_STACK_INVALID_PARAM;
333 uint16_t securePort = 0;
334 if (resourcePtr->resourceProperties & OC_SECURE)
336 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
344 securePort = devAddr->port;
347 uint16_t tcpPort = 0;
349 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
353 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
355 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
361 uint8_t IsCollectionResource (OCResource *resource)
368 if(resource->rsrcChildResourcesHead != NULL)
376 OCResource *FindResourceByUri(const char* resourceUri)
383 OCResource * pointer = headResource;
386 if (strcmp(resourceUri, pointer->uri) == 0)
390 pointer = pointer->next;
392 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
397 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
398 ResourceHandling *handling,
399 OCResource **resource)
401 if(!request || !handling || !resource)
403 return OC_STACK_INVALID_PARAM;
406 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
408 // Check if virtual resource
409 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
411 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
412 *handling = OC_RESOURCE_VIRTUAL;
413 *resource = headResource;
416 if (strlen((const char*)(request->resourceUrl)) == 0)
418 // Resource URL not specified
419 *handling = OC_RESOURCE_NOT_SPECIFIED;
420 return OC_STACK_NO_RESOURCE;
424 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
425 *resource = resourcePtr;
428 if(defaultDeviceHandler)
430 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
434 // Resource does not exist
435 // and default device handler does not exist
436 *handling = OC_RESOURCE_NOT_SPECIFIED;
437 return OC_STACK_NO_RESOURCE;
440 if (IsCollectionResource (resourcePtr))
442 // Collection resource
443 if (resourcePtr->entityHandler != defaultResourceEHandler)
445 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
450 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
456 // Resource not a collection
457 if (resourcePtr->entityHandler != defaultResourceEHandler)
459 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
464 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
471 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
473 OCStackResult result;
478 result = OC_STACK_OK;
481 result = OC_STACK_SLOW_RESOURCE;
484 result = OC_STACK_ERROR;
486 case OC_EH_FORBIDDEN:
487 result = OC_STACK_RESOURCE_ERROR;
489 case OC_EH_RESOURCE_CREATED:
490 result = OC_STACK_RESOURCE_CREATED;
492 case OC_EH_RESOURCE_DELETED:
493 result = OC_STACK_RESOURCE_DELETED;
496 result = OC_STACK_RESOURCE_CHANGED;
498 case OC_EH_RESOURCE_NOT_FOUND:
499 result = OC_STACK_NO_RESOURCE;
502 result = OC_STACK_ERROR;
508 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
515 // Null or empty is analogous to no filter.
516 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
521 OCResourceType *resourceTypePtr = resource->rsrcType;
523 while (resourceTypePtr)
525 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
529 resourceTypePtr = resourceTypePtr->next;
532 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
536 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
543 // Null or empty is analogous to no filter.
544 if (interfaceFilter == NULL || *interfaceFilter == 0)
549 OCResourceInterface *interfacePtr = resource->rsrcInterface;
553 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
554 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
555 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
559 interfacePtr = interfacePtr->next;
562 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
567 * If the filters are null, they will be assumed to NOT be present
568 * and the resource will not be matched against them.
569 * Function will return true if all non null AND non empty filters passed in find a match.
571 static bool includeThisResourceInResponse(OCResource *resource,
572 char *interfaceFilter,
573 char *resourceTypeFilter)
577 OIC_LOG(ERROR, TAG, "Invalid resource");
581 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
584 * At least one valid filter should be available to
585 * include the resource in discovery response
587 if (!(resourceTypeFilter && *resourceTypeFilter))
589 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
590 resource", resource->uri);
594 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
595 !(resource->resourceProperties & OC_DISCOVERABLE))
597 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
601 return resourceMatchesIFFilter(resource, interfaceFilter) &&
602 resourceMatchesRTFilter(resource, resourceTypeFilter);
606 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
607 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
609 OCEntityHandlerResponse response = {0};
611 response.ehResult = ehResult;
612 response.payload = discoveryPayload;
613 response.persistentBufferFlag = 0;
614 response.requestHandle = (OCRequestHandle) request;
615 response.resourceHandle = (OCResourceHandle) resource;
617 return OCDoResponse(&response);
621 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
622 OCResource **payload, OCDevAddr *devAddr)
624 OCResourceCollectionPayload *repPayload;
627 return OC_STACK_ERROR;
629 if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
633 return OC_STACK_ERROR;
635 OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
638 return OC_STACK_NO_MEMORY;
641 ptr->uri = OICStrdup(repPayload->setLinks->href);
644 return OC_STACK_NO_MEMORY;
646 OCStringLL *rt = repPayload->setLinks->rt;
649 OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
653 return OC_STACK_NO_MEMORY;
656 temp->resourcetypename = OICStrdup(rt->value);
659 ptr->rsrcType = temp;
663 OCResourceType *type = ptr->rsrcType;
673 OCStringLL *itf = repPayload->setLinks->itf;
676 OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
681 return OC_STACK_NO_MEMORY;
684 temp->name = OICStrdup(itf->value);
685 if (!ptr->rsrcInterface)
687 ptr->rsrcInterface = temp;
691 OCResourceInterface *type = ptr->rsrcInterface;
701 ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
703 OCFreeCollectionResource(repPayload);
709 OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
710 on the resource directory");
712 return OC_STACK_ERROR;
716 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
718 if (!request || !resource)
720 return OC_STACK_INVALID_PARAM;
723 OCStackResult discoveryResult = OC_STACK_ERROR;
724 OCPayload* payload = NULL;
726 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
728 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
730 // Step 1: Generate the response to discovery request
731 if (virtualUriInRequest == OC_WELL_KNOWN_URI
733 || virtualUriInRequest == OC_MQ_BROKER_URI
737 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
739 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
740 return OC_STACK_UNAUTHORIZED_REQ;
743 char *interfaceQuery = NULL;
744 char *resourceTypeQuery = NULL;
746 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
747 &interfaceQuery, &resourceTypeQuery);
748 bool interfaceQueryAllocated = false;
749 if (!interfaceQuery && !resourceTypeQuery)
751 interfaceQueryAllocated = true;
752 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
755 if (discoveryResult == OC_STACK_OK)
757 payload = (OCPayload *)OCDiscoveryPayloadCreate();
761 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
762 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
763 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
765 const char* uid = OCGetServerInstanceIDString();
768 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
771 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
773 OCResourceProperty prop = OC_DISCOVERABLE;
775 if (OC_MQ_BROKER_URI == virtualUriInRequest)
781 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
785 if (resource->resourceProperties & prop)
792 discoveryResult = BuildVirtualResourceResponse(resource,
793 discPayload, &request->devAddr, false);
799 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
801 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
802 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
803 if (savedDeviceInfo.deviceName)
805 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
806 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
808 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
809 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
810 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
811 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
812 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
813 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
814 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
816 bool foundResourceAtRD = false;
817 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
820 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
822 OCResource *resource1 = NULL;
824 discoveryResult = checkResourceExistsAtRD(interfaceQuery,
825 resourceTypeQuery, &resource1, &devAddr);
826 if (discoveryResult != OC_STACK_OK)
830 discoveryResult = BuildVirtualResourceResponse(resource1,
831 discPayload, &devAddr, true);
834 discPayload->baseURI = OICStrdup(devAddr.addr);
836 OICFree(resource1->uri);
837 for (OCResourceType *rsrcRt = resource1->rsrcType, *rsrcRtNext = NULL; rsrcRt; )
839 rsrcRtNext = rsrcRt->next;
840 OICFree(rsrcRt->resourcetypename);
845 for (OCResourceInterface *rsrcPtr = resource1->rsrcInterface, *rsrcNext = NULL; rsrcPtr; )
847 rsrcNext = rsrcPtr->next;
848 OICFree(rsrcPtr->name);
852 foundResourceAtRD = true;
855 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
857 discoveryResult = BuildVirtualResourceResponse(resource,
858 discPayload, &request->devAddr, false);
861 // Set discoveryResult appropriately if no 'valid' resources are available
862 if (discPayload->resources == NULL && !foundResourceAtRD)
864 discoveryResult = OC_STACK_NO_RESOURCE;
870 discoveryResult = OC_STACK_NO_MEMORY;
875 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
877 if (interfaceQueryAllocated)
879 OICFree(interfaceQuery);
882 else if (virtualUriInRequest == OC_DEVICE_URI)
884 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
886 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
887 return OC_STACK_UNAUTHORIZED_REQ;
890 const char* deviceId = OCGetServerInstanceIDString();
893 discoveryResult = OC_STACK_ERROR;
897 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
898 if (!dataModelVersions)
900 discoveryResult = OC_STACK_NO_MEMORY;
904 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
905 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
908 discoveryResult = OC_STACK_NO_MEMORY;
912 discoveryResult = OC_STACK_OK;
914 OICFree(dataModelVersions);
918 else if (virtualUriInRequest == OC_PLATFORM_URI)
920 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
922 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
923 return OC_STACK_UNAUTHORIZED_REQ;
926 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
929 discoveryResult = OC_STACK_NO_MEMORY;
933 discoveryResult = OC_STACK_OK;
936 #ifdef ROUTING_GATEWAY
937 else if (OC_GATEWAY_URI == virtualUriInRequest)
939 // Received request for a gateway
940 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
941 discoveryResult = RMHandleGatewayRequest(request, resource);
947 * Step 2: Send the discovery response
949 * Iotivity should respond to discovery requests in below manner:
950 * 1)If query filter matching fails and discovery request is multicast,
951 * it should NOT send any response.
952 * 2)If query filter matching fails and discovery request is unicast,
953 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
954 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
955 * request is multicast, it should NOT send any response.
956 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
957 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
961 if ((virtualUriInRequest == OC_PRESENCE) &&
962 (resource->resourceProperties & OC_ACTIVE))
964 // Presence uses observer notification api to respond via SendPresenceNotification.
965 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
969 #ifdef ROUTING_GATEWAY
970 // Gateway uses the RMHandleGatewayRequest to respond to the request.
971 if (OC_GATEWAY_URI != virtualUriInRequest)
974 if(discoveryResult == OC_STACK_OK)
976 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
978 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
979 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
980 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
982 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
983 discoveryResult, virtualUriInRequest);
984 SendNonPersistantDiscoveryResponse(request, resource, NULL,
985 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
989 // Ignoring the discovery request as per RFC 7252, Section #8.2
990 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
994 OCPayloadDestroy(payload);
1000 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
1004 return OC_STACK_INVALID_PARAM;
1007 OCStackResult result = OC_STACK_OK;
1008 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1009 OCEntityHandlerRequest ehRequest = {0};
1011 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
1012 result = FormOCEntityHandlerRequest(&ehRequest,
1013 (OCRequestHandle) request,
1016 (OCResourceHandle) NULL, request->query,
1017 PAYLOAD_TYPE_REPRESENTATION,
1019 request->payloadSize,
1020 request->numRcvdVendorSpecificHeaderOptions,
1021 request->rcvdVendorSpecificHeaderOptions,
1022 (OCObserveAction)request->observationOption,
1025 VERIFY_SUCCESS(result, OC_STACK_OK);
1027 // At this point we know for sure that defaultDeviceHandler exists
1028 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
1029 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
1030 if(ehResult == OC_EH_SLOW)
1032 OIC_LOG(INFO, TAG, "This is a slow resource");
1033 request->slowFlag = 1;
1035 else if(ehResult == OC_EH_ERROR)
1037 FindAndDeleteServerRequest(request);
1039 result = EntityHandlerCodeToOCStackCode(ehResult);
1041 OCPayloadDestroy(ehRequest.payload);
1045 static OCStackResult
1046 HandleResourceWithEntityHandler (OCServerRequest *request,
1047 OCResource *resource,
1048 uint8_t collectionResource)
1050 if(!request || ! resource)
1052 return OC_STACK_INVALID_PARAM;
1055 OCStackResult result = OC_STACK_ERROR;
1056 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1057 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1058 ResourceObserver *resObs = NULL;
1060 OCEntityHandlerRequest ehRequest = {0};
1062 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1063 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1064 // check the security resource
1065 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1067 type = PAYLOAD_TYPE_SECURITY;
1071 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
1073 type = PAYLOAD_TYPE_RD;
1076 result = FormOCEntityHandlerRequest(&ehRequest,
1077 (OCRequestHandle)request,
1080 (OCResourceHandle)resource,
1084 request->payloadSize,
1085 request->numRcvdVendorSpecificHeaderOptions,
1086 request->rcvdVendorSpecificHeaderOptions,
1087 (OCObserveAction)request->observationOption,
1090 VERIFY_SUCCESS(result, OC_STACK_OK);
1092 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1094 OIC_LOG(INFO, TAG, "No observation requested");
1095 ehFlag = OC_REQUEST_FLAG;
1097 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
1099 OIC_LOG(INFO, TAG, "Observation registration requested");
1101 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1102 request->tokenLength);
1106 OIC_LOG (INFO, TAG, "Observer with this token already present");
1107 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1108 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1109 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1111 // server requests are usually free'd when the response is sent out
1112 // for the request in ocserverrequest.c : HandleSingleResponse()
1113 // Since we are making an early return and not responding, the server request
1114 // needs to be deleted.
1115 FindAndDeleteServerRequest (request);
1119 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1120 VERIFY_SUCCESS(result, OC_STACK_OK);
1122 result = AddObserver ((const char*)(request->resourceUrl),
1123 (const char *)(request->query),
1124 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1125 resource, request->qos, request->acceptFormat,
1128 if(result == OC_STACK_OK)
1130 OIC_LOG(INFO, TAG, "Added observer successfully");
1131 request->observeResult = OC_STACK_OK;
1132 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1136 // The error in observeResult for the request will be used when responding to this
1137 // request by omitting the observation option/sequence number.
1138 request->observeResult = OC_STACK_ERROR;
1139 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1140 ehFlag = OC_REQUEST_FLAG;
1141 FindAndDeleteServerRequest(request);
1146 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1147 !collectionResource)
1149 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1151 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1155 // Stack does not contain this observation request
1156 // Either token is incorrect or observation list is corrupted
1157 result = OC_STACK_ERROR;
1160 ehRequest.obsInfo.obsId = resObs->observeId;
1161 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1163 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1165 if(result == OC_STACK_OK)
1167 OIC_LOG(INFO, TAG, "Removed observer successfully");
1168 request->observeResult = OC_STACK_OK;
1172 request->observeResult = OC_STACK_ERROR;
1173 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1174 FindAndDeleteServerRequest(request);
1180 result = OC_STACK_ERROR;
1184 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1185 if(ehResult == OC_EH_SLOW)
1187 OIC_LOG(INFO, TAG, "This is a slow resource");
1188 request->slowFlag = 1;
1190 else if(ehResult == OC_EH_ERROR)
1192 FindAndDeleteServerRequest(request);
1194 result = EntityHandlerCodeToOCStackCode(ehResult);
1196 OCPayloadDestroy(ehRequest.payload);
1200 static OCStackResult
1201 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1202 OCResource *resource)
1204 if(!request || !resource)
1206 return OC_STACK_INVALID_PARAM;
1209 OCStackResult result = OC_STACK_ERROR;
1210 OCEntityHandlerRequest ehRequest = {0};
1212 result = FormOCEntityHandlerRequest(&ehRequest,
1213 (OCRequestHandle)request,
1216 (OCResourceHandle)resource,
1218 PAYLOAD_TYPE_REPRESENTATION,
1220 request->payloadSize,
1221 request->numRcvdVendorSpecificHeaderOptions,
1222 request->rcvdVendorSpecificHeaderOptions,
1223 (OCObserveAction)request->observationOption,
1226 if(result == OC_STACK_OK)
1228 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1231 OCPayloadDestroy(ehRequest.payload);
1236 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1238 OCStackResult ret = OC_STACK_OK;
1240 switch (resHandling)
1242 case OC_RESOURCE_VIRTUAL:
1244 ret = HandleVirtualResource (request, resource);
1247 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1249 ret = HandleDefaultDeviceEntityHandler(request);
1252 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1254 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1255 return OC_STACK_ERROR;
1257 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1259 ret = HandleResourceWithEntityHandler (request, resource, 0);
1262 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1264 ret = HandleResourceWithEntityHandler (request, resource, 1);
1267 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1269 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1272 case OC_RESOURCE_NOT_SPECIFIED:
1274 ret = OC_STACK_NO_RESOURCE;
1279 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1280 return OC_STACK_ERROR;
1286 void DeletePlatformInfo()
1288 OIC_LOG(INFO, TAG, "Deleting platform info.");
1290 OICFree(savedPlatformInfo.platformID);
1291 savedPlatformInfo.platformID = NULL;
1293 OICFree(savedPlatformInfo.manufacturerName);
1294 savedPlatformInfo.manufacturerName = NULL;
1296 OICFree(savedPlatformInfo.manufacturerUrl);
1297 savedPlatformInfo.manufacturerUrl = NULL;
1299 OICFree(savedPlatformInfo.modelNumber);
1300 savedPlatformInfo.modelNumber = NULL;
1302 OICFree(savedPlatformInfo.dateOfManufacture);
1303 savedPlatformInfo.dateOfManufacture = NULL;
1305 OICFree(savedPlatformInfo.platformVersion);
1306 savedPlatformInfo.platformVersion = NULL;
1308 OICFree(savedPlatformInfo.operatingSystemVersion);
1309 savedPlatformInfo.operatingSystemVersion = NULL;
1311 OICFree(savedPlatformInfo.hardwareVersion);
1312 savedPlatformInfo.hardwareVersion = NULL;
1314 OICFree(savedPlatformInfo.firmwareVersion);
1315 savedPlatformInfo.firmwareVersion = NULL;
1317 OICFree(savedPlatformInfo.supportUrl);
1318 savedPlatformInfo.supportUrl = NULL;
1320 OICFree(savedPlatformInfo.systemTime);
1321 savedPlatformInfo.systemTime = NULL;
1324 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1326 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1327 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1328 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1329 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1330 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1331 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1332 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1333 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1334 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1335 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1336 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1338 if ((!savedPlatformInfo.platformID && info.platformID)||
1339 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1340 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1341 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1342 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1343 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1344 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1345 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1346 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1347 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1348 (!savedPlatformInfo.systemTime && info.systemTime))
1350 DeletePlatformInfo();
1351 return OC_STACK_INVALID_PARAM;
1358 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1360 DeletePlatformInfo();
1362 OCStackResult res = DeepCopyPlatFormInfo(info);
1364 if (res != OC_STACK_OK)
1366 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1370 OIC_LOG(INFO, TAG, "Platform info saved.");
1376 void DeleteDeviceInfo()
1378 OIC_LOG(INFO, TAG, "Deleting device info.");
1380 OICFree(savedDeviceInfo.deviceName);
1381 OCFreeOCStringLL(savedDeviceInfo.types);
1382 OICFree(savedDeviceInfo.specVersion);
1383 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1384 savedDeviceInfo.deviceName = NULL;
1385 savedDeviceInfo.specVersion = NULL;
1386 savedDeviceInfo.dataModelVersions = NULL;
1389 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1391 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1393 if(!savedDeviceInfo.deviceName && info.deviceName)
1396 return OC_STACK_NO_MEMORY;
1401 savedDeviceInfo.types = CloneOCStringLL(info.types);
1402 OCStringLL *type = info.types;
1406 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1414 // Append the oic.wk.d at the start of rt link parameter value.
1415 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1419 return OC_STACK_NO_MEMORY;
1421 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1425 return OC_STACK_NO_MEMORY;
1427 dest->next = savedDeviceInfo.types;
1428 savedDeviceInfo.types = dest;
1430 if(!savedDeviceInfo.types && info.types)
1433 return OC_STACK_NO_MEMORY;
1437 if (info.specVersion)
1439 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1440 if(!savedDeviceInfo.specVersion && info.specVersion)
1443 return OC_STACK_NO_MEMORY;
1448 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1449 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1452 return OC_STACK_NO_MEMORY;
1456 if (info.dataModelVersions)
1458 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1459 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1462 return OC_STACK_NO_MEMORY;
1467 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1468 if (!savedDeviceInfo.dataModelVersions)
1470 return OC_STACK_NO_MEMORY;
1472 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1473 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1476 return OC_STACK_NO_MEMORY;
1483 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1485 OCStackResult res = OC_STACK_OK;
1489 res = DeepCopyDeviceInfo(info);
1491 VERIFY_SUCCESS(res, OC_STACK_OK);
1493 if (OCGetServerInstanceIDString() == NULL)
1495 OIC_LOG(INFO, TAG, "Device ID generation failed");
1496 res = OC_STACK_ERROR;
1500 OIC_LOG(INFO, TAG, "Device initialized successfully.");