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
35 #include "ocresource.h"
36 #include "ocresourcehandler.h"
37 #include "ocobserve.h"
38 #include "occollection.h"
39 #include "oic_malloc.h"
40 #include "oic_string.h"
43 #include "ocpayload.h"
44 #include "secureresourcemanager.h"
46 #include "cainterface.h"
47 #include "rdpayload.h"
48 #include "ocpayload.h"
51 #include "rd_server.h"
54 #ifdef ROUTING_GATEWAY
55 #include "routingmanager.h"
59 #define TAG "OIC_RI_RESOURCE"
61 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
62 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
64 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
65 TAG, #arg " is NULL"); return (retVal); } }
67 extern OCResource *headResource;
68 static OCPlatformInfo savedPlatformInfo = {0};
69 static OCDeviceInfo savedDeviceInfo = {0};
72 * Prepares a Payload for response.
74 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
75 OCDiscoveryPayload* payload,
79 //-----------------------------------------------------------------------------
80 // Default resource entity handler function
81 //-----------------------------------------------------------------------------
82 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
83 OCEntityHandlerRequest * request, void* callbackParam)
85 //TODO ("Implement me!!!!");
86 // TODO: remove silence unused param warnings
90 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
93 /* This method will retrieve the port at which the secure resource is hosted */
94 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
98 if (endpoint->adapter == OC_ADAPTER_IP)
100 if (endpoint->flags & OC_IP_USE_V6)
102 p = caglobals.ip.u6s.port;
104 else if (endpoint->flags & OC_IP_USE_V4)
106 p = caglobals.ip.u4s.port;
115 /* This method will retrieve the tcp port */
116 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
120 if (endpoint->adapter == OC_ADAPTER_IP)
122 if (endpoint->flags & OC_IP_USE_V4)
124 p = caglobals.tcp.ipv4.port;
126 else if (endpoint->flags & OC_IP_USE_V6)
128 p = caglobals.tcp.ipv6.port;
138 * Function will extract 0, 1 or 2 filters from query.
139 * More than 2 filters or unsupported filters will result in error.
140 * If both filters are of the same supported type, the 2nd one will be picked.
141 * Resource and device filters in the SAME query are NOT validated
142 * and resources will likely not clear filters.
144 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
149 char *restOfQuery = NULL;
150 int numKeyValuePairsParsed = 0;
155 OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
157 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
161 if (numKeyValuePairsParsed >= 2)
163 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
164 return OC_STACK_INVALID_QUERY;
167 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
171 return OC_STACK_INVALID_QUERY;
173 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
175 *filterOne = value; // if
177 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
179 *filterTwo = value; // rt
183 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
184 return OC_STACK_INVALID_QUERY;
186 ++numKeyValuePairsParsed;
188 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
191 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
195 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
197 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
199 return OC_WELL_KNOWN_URI;
201 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
203 return OC_DEVICE_URI;
205 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
207 return OC_PLATFORM_URI;
209 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
211 return OC_RESOURCE_TYPES_URI;
213 #ifdef ROUTING_GATEWAY
214 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
216 return OC_GATEWAY_URI;
220 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
224 #endif //WITH_PRESENCE
225 return OC_UNKNOWN_URI;
228 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
229 char **filterOne, char **filterTwo)
231 if(!filterOne || !filterTwo)
233 return OC_STACK_INVALID_PARAM;
240 if (uri == OC_PRESENCE)
242 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
243 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
248 OCStackResult result = OC_STACK_OK;
252 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
258 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
259 OCRepPayload** payload)
261 OCRepPayload *tempPayload = OCRepPayloadCreate();
265 OCRepPayloadDestroy(tempPayload);
266 return OC_STACK_INVALID_PARAM;
271 return OC_STACK_NO_MEMORY;
274 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
276 OCResourceType *resType = resourcePtr->rsrcType;
279 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
280 resType = resType->next;
283 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
286 OCRepPayloadAddInterface(tempPayload, resInterface->name);
287 resInterface = resInterface->next;
290 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
293 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
294 resAttrib->attrValue);
295 resAttrib = resAttrib->next;
300 *payload = tempPayload;
304 OCRepPayloadAppend(*payload, tempPayload);
310 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
311 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
313 if (!resourcePtr || !payload)
315 return OC_STACK_INVALID_PARAM;
317 uint16_t securePort = 0;
318 if (resourcePtr->resourceProperties & OC_SECURE)
320 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
328 securePort = devAddr->port;
331 uint16_t tcpPort = 0;
333 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
337 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
339 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
345 uint8_t IsCollectionResource (OCResource *resource)
352 if(resource->rsrcChildResourcesHead != NULL)
360 OCResource *FindResourceByUri(const char* resourceUri)
367 OCResource * pointer = headResource;
370 if (strcmp(resourceUri, pointer->uri) == 0)
374 pointer = pointer->next;
376 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
381 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
382 ResourceHandling *handling,
383 OCResource **resource)
385 if(!request || !handling || !resource)
387 return OC_STACK_INVALID_PARAM;
390 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
392 // Check if virtual resource
393 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
395 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
396 *handling = OC_RESOURCE_VIRTUAL;
397 *resource = headResource;
400 if (strlen((const char*)(request->resourceUrl)) == 0)
402 // Resource URL not specified
403 *handling = OC_RESOURCE_NOT_SPECIFIED;
404 return OC_STACK_NO_RESOURCE;
408 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
409 *resource = resourcePtr;
412 if(defaultDeviceHandler)
414 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
418 // Resource does not exist
419 // and default device handler does not exist
420 *handling = OC_RESOURCE_NOT_SPECIFIED;
421 return OC_STACK_NO_RESOURCE;
424 if (IsCollectionResource (resourcePtr))
426 // Collection resource
427 if (resourcePtr->entityHandler != defaultResourceEHandler)
429 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
434 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
440 // Resource not a collection
441 if (resourcePtr->entityHandler != defaultResourceEHandler)
443 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
448 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
455 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
457 OCStackResult result;
462 result = OC_STACK_OK;
465 result = OC_STACK_SLOW_RESOURCE;
468 result = OC_STACK_ERROR;
470 case OC_EH_FORBIDDEN:
471 result = OC_STACK_RESOURCE_ERROR;
473 case OC_EH_RESOURCE_CREATED:
474 result = OC_STACK_RESOURCE_CREATED;
476 case OC_EH_RESOURCE_DELETED:
477 result = OC_STACK_RESOURCE_DELETED;
479 case OC_EH_RESOURCE_NOT_FOUND:
480 result = OC_STACK_NO_RESOURCE;
483 result = OC_STACK_ERROR;
489 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
496 // Null or empty is analogous to no filter.
497 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
502 OCResourceType *resourceTypePtr = resource->rsrcType;
504 while (resourceTypePtr)
506 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
510 resourceTypePtr = resourceTypePtr->next;
513 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
517 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
524 // Null or empty is analogous to no filter.
525 if (interfaceFilter == NULL || *interfaceFilter == 0)
530 OCResourceInterface *interfacePtr = resource->rsrcInterface;
534 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
535 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
536 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
540 interfacePtr = interfacePtr->next;
543 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
548 * If the filters are null, they will be assumed to NOT be present
549 * and the resource will not be matched against them.
550 * Function will return true if all non null AND non empty filters passed in find a match.
552 static bool includeThisResourceInResponse(OCResource *resource,
553 char *interfaceFilter,
554 char *resourceTypeFilter)
558 OIC_LOG(ERROR, TAG, "Invalid resource");
562 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
565 * At least one valid filter should be available to
566 * include the resource in discovery response
568 if (!(resourceTypeFilter && *resourceTypeFilter))
570 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
571 resource", resource->uri);
575 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
576 !(resource->resourceProperties & OC_DISCOVERABLE))
578 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
582 return resourceMatchesIFFilter(resource, interfaceFilter) &&
583 resourceMatchesRTFilter(resource, resourceTypeFilter);
587 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
588 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
590 OCEntityHandlerResponse response = {0};
592 response.ehResult = ehResult;
593 response.payload = discoveryPayload;
594 response.persistentBufferFlag = 0;
595 response.requestHandle = (OCRequestHandle) request;
596 response.resourceHandle = (OCResourceHandle) resource;
598 return OCDoResponse(&response);
602 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
603 OCResource **payload, OCDevAddr *devAddr)
605 OCResourceCollectionPayload *repPayload;
608 return OC_STACK_ERROR;
610 if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
614 return OC_STACK_ERROR;
616 OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
619 return OC_STACK_NO_MEMORY;
622 ptr->uri = OICStrdup(repPayload->setLinks->href);
625 return OC_STACK_NO_MEMORY;
627 OCStringLL *rt = repPayload->setLinks->rt;
630 OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
634 return OC_STACK_NO_MEMORY;
637 temp->resourcetypename = OICStrdup(rt->value);
640 ptr->rsrcType = temp;
644 OCResourceType *type = ptr->rsrcType;
654 OCStringLL *itf = repPayload->setLinks->itf;
657 OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
662 return OC_STACK_NO_MEMORY;
665 temp->name = OICStrdup(itf->value);
666 if (!ptr->rsrcInterface)
668 ptr->rsrcInterface = temp;
672 OCResourceInterface *type = ptr->rsrcInterface;
682 ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
684 OCFreeCollectionResource(repPayload);
690 OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
691 on the resource directory");
693 return OC_STACK_ERROR;
697 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
699 if (!request || !resource)
701 return OC_STACK_INVALID_PARAM;
704 OCStackResult discoveryResult = OC_STACK_ERROR;
706 bool bMulticast = false; // Was the discovery request a multicast request?
707 OCPayload* payload = NULL;
709 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
711 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
713 // Step 1: Generate the response to discovery request
714 if (virtualUriInRequest == OC_WELL_KNOWN_URI)
716 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
718 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
719 return OC_STACK_UNAUTHORIZED_REQ;
722 char *interfaceQuery = NULL;
723 char *resourceTypeQuery = NULL;
725 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
726 &interfaceQuery, &resourceTypeQuery);
727 bool interfaceQueryAllocated = false;
728 if (!interfaceQuery && !resourceTypeQuery)
730 interfaceQueryAllocated = true;
731 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
734 if (discoveryResult == OC_STACK_OK)
736 payload = (OCPayload *)OCDiscoveryPayloadCreate();
740 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
741 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
742 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
744 const char* uid = OCGetServerInstanceIDString();
747 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
750 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
752 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
755 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
757 if (resourceTypeQuery && resourceMatchesRTFilter(resource, resourceTypeQuery))
762 if (resource->resourceProperties & OC_DISCOVERABLE)
769 discoveryResult = BuildVirtualResourceResponse(resource,
770 discPayload, &request->devAddr, false);
776 if ((interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))) ||
779 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
780 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
781 if (savedDeviceInfo.deviceName)
783 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
784 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
786 discPayload->type = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
787 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
788 OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_LL);
789 OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_DEFAULT);
790 VERIFY_NON_NULL(discPayload->interface, ERROR, OC_STACK_NO_MEMORY);
792 bool foundResourceAtRD = false;
793 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
796 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
798 OCResource *resource1 = NULL;
800 discoveryResult = checkResourceExistsAtRD(interfaceQuery,
801 resourceTypeQuery, &resource1, &devAddr);
802 if (discoveryResult != OC_STACK_OK)
806 discoveryResult = BuildVirtualResourceResponse(resource1,
807 discPayload, &devAddr, true);
810 discPayload->baseURI = OICStrdup(devAddr.addr);
812 OICFree(resource1->uri);
813 for (OCResourceType *rsrcRt = resource1->rsrcType, *rsrcRtNext = NULL; rsrcRt; )
815 rsrcRtNext = rsrcRt->next;
816 OICFree(rsrcRt->resourcetypename);
821 for (OCResourceInterface *rsrcPtr = resource1->rsrcInterface, *rsrcNext = NULL; rsrcPtr; )
823 rsrcNext = rsrcPtr->next;
824 OICFree(rsrcPtr->name);
828 foundResourceAtRD = true;
831 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
833 discoveryResult = BuildVirtualResourceResponse(resource,
834 discPayload, &request->devAddr, false);
837 // Set discoveryResult appropriately if no 'valid' resources are available
838 if (discPayload->resources == NULL && !foundResourceAtRD)
840 discoveryResult = OC_STACK_NO_RESOURCE;
846 discoveryResult = OC_STACK_NO_MEMORY;
851 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
853 if (interfaceQueryAllocated)
855 OICFree(interfaceQuery);
858 else if (virtualUriInRequest == OC_DEVICE_URI)
860 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
862 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
863 return OC_STACK_UNAUTHORIZED_REQ;
866 const char* deviceId = OCGetServerInstanceIDString();
869 discoveryResult = OC_STACK_ERROR;
873 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
874 savedDeviceInfo.types, savedDeviceInfo.specVersion, savedDeviceInfo.dataModelVersion);
877 discoveryResult = OC_STACK_NO_MEMORY;
881 discoveryResult = OC_STACK_OK;
885 else if (virtualUriInRequest == OC_PLATFORM_URI)
887 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
889 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
890 return OC_STACK_UNAUTHORIZED_REQ;
893 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
896 discoveryResult = OC_STACK_NO_MEMORY;
900 discoveryResult = OC_STACK_OK;
903 #ifdef ROUTING_GATEWAY
904 else if (OC_GATEWAY_URI == virtualUriInRequest)
906 // Received request for a gateway
907 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
908 discoveryResult = RMHandleGatewayRequest(request, resource);
914 * Step 2: Send the discovery response
916 * Iotivity should respond to discovery requests in below manner:
917 * 1)If query filter matching fails and discovery request is multicast,
918 * it should NOT send any response.
919 * 2)If query filter matching fails and discovery request is unicast,
920 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
921 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
922 * request is multicast, it should NOT send any response.
923 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
924 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
928 if ((virtualUriInRequest == OC_PRESENCE) &&
929 (resource->resourceProperties & OC_ACTIVE))
931 // Presence uses observer notification api to respond via SendPresenceNotification.
932 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
936 #ifdef ROUTING_GATEWAY
937 // Gateway uses the RMHandleGatewayRequest to respond to the request.
938 if (OC_GATEWAY_URI != virtualUriInRequest)
941 if(discoveryResult == OC_STACK_OK)
943 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
945 else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
946 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
948 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) \
949 discovery request", discoveryResult, virtualUriInRequest);
950 SendNonPersistantDiscoveryResponse(request, resource, NULL,
951 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
955 // Ignoring the discovery request as per RFC 7252, Section #8.2
956 OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
957 any useful data to send");
961 OCPayloadDestroy(payload);
967 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
971 return OC_STACK_INVALID_PARAM;
974 OCStackResult result = OC_STACK_OK;
975 OCEntityHandlerResult ehResult = OC_EH_ERROR;
976 OCEntityHandlerRequest ehRequest = {0};
978 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
979 result = FormOCEntityHandlerRequest(&ehRequest,
980 (OCRequestHandle) request,
983 (OCResourceHandle) NULL, request->query,
984 PAYLOAD_TYPE_REPRESENTATION,
986 request->payloadSize,
987 request->numRcvdVendorSpecificHeaderOptions,
988 request->rcvdVendorSpecificHeaderOptions,
989 (OCObserveAction)request->observationOption,
991 VERIFY_SUCCESS(result, OC_STACK_OK);
993 // At this point we know for sure that defaultDeviceHandler exists
994 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
995 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
996 if(ehResult == OC_EH_SLOW)
998 OIC_LOG(INFO, TAG, "This is a slow resource");
999 request->slowFlag = 1;
1001 else if(ehResult == OC_EH_ERROR)
1003 FindAndDeleteServerRequest(request);
1005 result = EntityHandlerCodeToOCStackCode(ehResult);
1007 OCPayloadDestroy(ehRequest.payload);
1011 static OCStackResult
1012 HandleResourceWithEntityHandler (OCServerRequest *request,
1013 OCResource *resource,
1014 uint8_t collectionResource)
1016 if(!request || ! resource)
1018 return OC_STACK_INVALID_PARAM;
1021 OCStackResult result = OC_STACK_ERROR;
1022 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1023 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1024 ResourceObserver *resObs = NULL;
1026 OCEntityHandlerRequest ehRequest = {0};
1028 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1029 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1030 // check the security resource
1031 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1033 type = PAYLOAD_TYPE_SECURITY;
1037 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
1039 type = PAYLOAD_TYPE_RD;
1042 result = FormOCEntityHandlerRequest(&ehRequest,
1043 (OCRequestHandle)request,
1046 (OCResourceHandle)resource,
1050 request->payloadSize,
1051 request->numRcvdVendorSpecificHeaderOptions,
1052 request->rcvdVendorSpecificHeaderOptions,
1053 (OCObserveAction)request->observationOption,
1055 VERIFY_SUCCESS(result, OC_STACK_OK);
1057 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1059 OIC_LOG(INFO, TAG, "No observation requested");
1060 ehFlag = OC_REQUEST_FLAG;
1062 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
1064 OIC_LOG(INFO, TAG, "Observation registration requested");
1066 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1067 request->tokenLength);
1071 OIC_LOG (INFO, TAG, "Observer with this token already present");
1072 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1073 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1074 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1076 // server requests are usually free'd when the response is sent out
1077 // for the request in ocserverrequest.c : HandleSingleResponse()
1078 // Since we are making an early return and not responding, the server request
1079 // needs to be deleted.
1080 FindAndDeleteServerRequest (request);
1084 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1085 VERIFY_SUCCESS(result, OC_STACK_OK);
1087 result = AddObserver ((const char*)(request->resourceUrl),
1088 (const char *)(request->query),
1089 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1090 resource, request->qos, request->acceptFormat,
1093 if(result == OC_STACK_OK)
1095 OIC_LOG(INFO, TAG, "Added observer successfully");
1096 request->observeResult = OC_STACK_OK;
1097 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1101 // The error in observeResult for the request will be used when responding to this
1102 // request by omitting the observation option/sequence number.
1103 request->observeResult = OC_STACK_ERROR;
1104 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1105 ehFlag = OC_REQUEST_FLAG;
1106 FindAndDeleteServerRequest(request);
1111 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1112 !collectionResource)
1114 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1116 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1120 // Stack does not contain this observation request
1121 // Either token is incorrect or observation list is corrupted
1122 result = OC_STACK_ERROR;
1125 ehRequest.obsInfo.obsId = resObs->observeId;
1126 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1128 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1130 if(result == OC_STACK_OK)
1132 OIC_LOG(INFO, TAG, "Removed observer successfully");
1133 request->observeResult = OC_STACK_OK;
1137 request->observeResult = OC_STACK_ERROR;
1138 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1139 FindAndDeleteServerRequest(request);
1145 result = OC_STACK_ERROR;
1149 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1150 if(ehResult == OC_EH_SLOW)
1152 OIC_LOG(INFO, TAG, "This is a slow resource");
1153 request->slowFlag = 1;
1155 else if(ehResult == OC_EH_ERROR)
1157 FindAndDeleteServerRequest(request);
1159 result = EntityHandlerCodeToOCStackCode(ehResult);
1161 OCPayloadDestroy(ehRequest.payload);
1165 static OCStackResult
1166 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1167 OCResource *resource)
1169 if(!request || !resource)
1171 return OC_STACK_INVALID_PARAM;
1174 OCStackResult result = OC_STACK_ERROR;
1175 OCEntityHandlerRequest ehRequest = {0};
1177 result = FormOCEntityHandlerRequest(&ehRequest,
1178 (OCRequestHandle)request,
1181 (OCResourceHandle)resource,
1183 PAYLOAD_TYPE_REPRESENTATION,
1185 request->payloadSize,
1186 request->numRcvdVendorSpecificHeaderOptions,
1187 request->rcvdVendorSpecificHeaderOptions,
1188 (OCObserveAction)request->observationOption,
1189 (OCObservationId)0);
1190 if(result == OC_STACK_OK)
1192 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1195 OCPayloadDestroy(ehRequest.payload);
1200 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1202 OCStackResult ret = OC_STACK_OK;
1204 switch (resHandling)
1206 case OC_RESOURCE_VIRTUAL:
1208 ret = HandleVirtualResource (request, resource);
1211 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1213 ret = HandleDefaultDeviceEntityHandler(request);
1216 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1218 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1219 return OC_STACK_ERROR;
1221 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1223 ret = HandleResourceWithEntityHandler (request, resource, 0);
1226 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1228 ret = HandleResourceWithEntityHandler (request, resource, 1);
1231 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1233 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1236 case OC_RESOURCE_NOT_SPECIFIED:
1238 ret = OC_STACK_NO_RESOURCE;
1243 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1244 return OC_STACK_ERROR;
1250 void DeletePlatformInfo()
1252 OIC_LOG(INFO, TAG, "Deleting platform info.");
1254 OICFree(savedPlatformInfo.platformID);
1255 savedPlatformInfo.platformID = NULL;
1257 OICFree(savedPlatformInfo.manufacturerName);
1258 savedPlatformInfo.manufacturerName = NULL;
1260 OICFree(savedPlatformInfo.manufacturerUrl);
1261 savedPlatformInfo.manufacturerUrl = NULL;
1263 OICFree(savedPlatformInfo.modelNumber);
1264 savedPlatformInfo.modelNumber = NULL;
1266 OICFree(savedPlatformInfo.dateOfManufacture);
1267 savedPlatformInfo.dateOfManufacture = NULL;
1269 OICFree(savedPlatformInfo.platformVersion);
1270 savedPlatformInfo.platformVersion = NULL;
1272 OICFree(savedPlatformInfo.operatingSystemVersion);
1273 savedPlatformInfo.operatingSystemVersion = NULL;
1275 OICFree(savedPlatformInfo.hardwareVersion);
1276 savedPlatformInfo.hardwareVersion = NULL;
1278 OICFree(savedPlatformInfo.firmwareVersion);
1279 savedPlatformInfo.firmwareVersion = NULL;
1281 OICFree(savedPlatformInfo.supportUrl);
1282 savedPlatformInfo.supportUrl = NULL;
1284 OICFree(savedPlatformInfo.systemTime);
1285 savedPlatformInfo.systemTime = NULL;
1288 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1290 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1291 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1292 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1293 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1294 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1295 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1296 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1297 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1298 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1299 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1300 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1302 if ((!savedPlatformInfo.platformID && info.platformID)||
1303 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1304 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1305 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1306 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1307 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1308 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1309 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1310 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1311 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1312 (!savedPlatformInfo.systemTime && info.systemTime))
1314 DeletePlatformInfo();
1315 return OC_STACK_INVALID_PARAM;
1322 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1324 DeletePlatformInfo();
1326 OCStackResult res = DeepCopyPlatFormInfo(info);
1328 if (res != OC_STACK_OK)
1330 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1334 OIC_LOG(INFO, TAG, "Platform info saved.");
1340 void DeleteDeviceInfo()
1342 OIC_LOG(INFO, TAG, "Deleting device info.");
1344 OICFree(savedDeviceInfo.deviceName);
1345 OCFreeOCStringLL(savedDeviceInfo.types);
1346 OICFree(savedDeviceInfo.specVersion);
1347 OICFree(savedDeviceInfo.dataModelVersion);
1348 savedDeviceInfo.deviceName = NULL;
1349 savedDeviceInfo.specVersion = NULL;
1350 savedDeviceInfo.dataModelVersion = NULL;
1353 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1355 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1357 if(!savedDeviceInfo.deviceName && info.deviceName)
1360 return OC_STACK_NO_MEMORY;
1365 savedDeviceInfo.types = CloneOCStringLL(info.types);
1366 if(!savedDeviceInfo.types && info.types)
1369 return OC_STACK_NO_MEMORY;
1373 if (info.specVersion)
1375 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1376 if(!savedDeviceInfo.specVersion && info.specVersion)
1379 return OC_STACK_NO_MEMORY;
1384 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1385 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1388 return OC_STACK_NO_MEMORY;
1392 if (info.dataModelVersion)
1394 savedDeviceInfo.dataModelVersion = OICStrdup(info.dataModelVersion);
1395 if(!savedDeviceInfo.dataModelVersion && info.dataModelVersion)
1398 return OC_STACK_NO_MEMORY;
1403 savedDeviceInfo.dataModelVersion = OICStrdup(OC_DATA_MODEL_VERSION);
1404 if(!savedDeviceInfo.dataModelVersion && OC_DATA_MODEL_VERSION)
1407 return OC_STACK_NO_MEMORY;
1414 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1416 OCStackResult res = OC_STACK_OK;
1420 res = DeepCopyDeviceInfo(info);
1422 VERIFY_SUCCESS(res, OC_STACK_OK);
1424 if (OCGetServerInstanceIDString() == NULL)
1426 OIC_LOG(INFO, TAG, "Device ID generation failed");
1427 res = OC_STACK_ERROR;
1431 OIC_LOG(INFO, TAG, "Device initialized successfully.");