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
234 return OC_UNKNOWN_URI;
237 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
238 char **filterOne, char **filterTwo)
240 if(!filterOne || !filterTwo)
242 return OC_STACK_INVALID_PARAM;
249 if (uri == OC_PRESENCE)
251 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
252 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
257 OCStackResult result = OC_STACK_OK;
261 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
267 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
268 OCRepPayload** payload)
270 OCRepPayload *tempPayload = OCRepPayloadCreate();
274 OCRepPayloadDestroy(tempPayload);
275 return OC_STACK_INVALID_PARAM;
280 return OC_STACK_NO_MEMORY;
283 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
285 OCResourceType *resType = resourcePtr->rsrcType;
288 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
289 resType = resType->next;
292 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
295 OCRepPayloadAddInterface(tempPayload, resInterface->name);
296 resInterface = resInterface->next;
299 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
302 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
303 resAttrib->attrValue);
304 resAttrib = resAttrib->next;
309 *payload = tempPayload;
313 OCRepPayloadAppend(*payload, tempPayload);
319 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
320 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
322 if (!resourcePtr || !payload)
324 return OC_STACK_INVALID_PARAM;
326 uint16_t securePort = 0;
327 if (resourcePtr->resourceProperties & OC_SECURE)
329 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
337 securePort = devAddr->port;
340 uint16_t tcpPort = 0;
342 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
346 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
348 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
354 uint8_t IsCollectionResource (OCResource *resource)
361 if(resource->rsrcChildResourcesHead != NULL)
369 OCResource *FindResourceByUri(const char* resourceUri)
376 OCResource * pointer = headResource;
379 if (strcmp(resourceUri, pointer->uri) == 0)
383 pointer = pointer->next;
385 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
390 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
391 ResourceHandling *handling,
392 OCResource **resource)
394 if(!request || !handling || !resource)
396 return OC_STACK_INVALID_PARAM;
399 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
401 // Check if virtual resource
402 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
404 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
405 *handling = OC_RESOURCE_VIRTUAL;
406 *resource = headResource;
409 if (strlen((const char*)(request->resourceUrl)) == 0)
411 // Resource URL not specified
412 *handling = OC_RESOURCE_NOT_SPECIFIED;
413 return OC_STACK_NO_RESOURCE;
417 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
418 *resource = resourcePtr;
421 if(defaultDeviceHandler)
423 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
427 // Resource does not exist
428 // and default device handler does not exist
429 *handling = OC_RESOURCE_NOT_SPECIFIED;
430 return OC_STACK_NO_RESOURCE;
433 if (IsCollectionResource (resourcePtr))
435 // Collection resource
436 if (resourcePtr->entityHandler != defaultResourceEHandler)
438 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
443 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
449 // Resource not a collection
450 if (resourcePtr->entityHandler != defaultResourceEHandler)
452 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
457 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
464 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
466 OCStackResult result;
471 result = OC_STACK_OK;
474 result = OC_STACK_SLOW_RESOURCE;
477 result = OC_STACK_ERROR;
479 case OC_EH_FORBIDDEN:
480 result = OC_STACK_RESOURCE_ERROR;
482 case OC_EH_RESOURCE_CREATED:
483 result = OC_STACK_RESOURCE_CREATED;
485 case OC_EH_RESOURCE_DELETED:
486 result = OC_STACK_RESOURCE_DELETED;
489 result = OC_STACK_RESOURCE_CHANGED;
491 case OC_EH_RESOURCE_NOT_FOUND:
492 result = OC_STACK_NO_RESOURCE;
495 result = OC_STACK_ERROR;
501 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
508 // Null or empty is analogous to no filter.
509 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
514 OCResourceType *resourceTypePtr = resource->rsrcType;
516 while (resourceTypePtr)
518 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
522 resourceTypePtr = resourceTypePtr->next;
525 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
529 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
536 // Null or empty is analogous to no filter.
537 if (interfaceFilter == NULL || *interfaceFilter == 0)
542 OCResourceInterface *interfacePtr = resource->rsrcInterface;
546 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
547 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
548 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
552 interfacePtr = interfacePtr->next;
555 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
560 * If the filters are null, they will be assumed to NOT be present
561 * and the resource will not be matched against them.
562 * Function will return true if all non null AND non empty filters passed in find a match.
564 static bool includeThisResourceInResponse(OCResource *resource,
565 char *interfaceFilter,
566 char *resourceTypeFilter)
570 OIC_LOG(ERROR, TAG, "Invalid resource");
574 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
577 * At least one valid filter should be available to
578 * include the resource in discovery response
580 if (!(resourceTypeFilter && *resourceTypeFilter))
582 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
583 resource", resource->uri);
587 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
588 !(resource->resourceProperties & OC_DISCOVERABLE))
590 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
594 return resourceMatchesIFFilter(resource, interfaceFilter) &&
595 resourceMatchesRTFilter(resource, resourceTypeFilter);
599 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
600 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
602 OCEntityHandlerResponse response = {0};
604 response.ehResult = ehResult;
605 response.payload = discoveryPayload;
606 response.persistentBufferFlag = 0;
607 response.requestHandle = (OCRequestHandle) request;
608 response.resourceHandle = (OCResourceHandle) resource;
610 return OCDoResponse(&response);
614 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
615 OCResource **payload, OCDevAddr *devAddr)
617 OCResourceCollectionPayload *repPayload;
620 return OC_STACK_ERROR;
622 if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
626 return OC_STACK_ERROR;
628 OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
631 return OC_STACK_NO_MEMORY;
634 ptr->uri = OICStrdup(repPayload->setLinks->href);
637 return OC_STACK_NO_MEMORY;
639 OCStringLL *rt = repPayload->setLinks->rt;
642 OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
646 return OC_STACK_NO_MEMORY;
649 temp->resourcetypename = OICStrdup(rt->value);
652 ptr->rsrcType = temp;
656 OCResourceType *type = ptr->rsrcType;
666 OCStringLL *itf = repPayload->setLinks->itf;
669 OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
674 return OC_STACK_NO_MEMORY;
677 temp->name = OICStrdup(itf->value);
678 if (!ptr->rsrcInterface)
680 ptr->rsrcInterface = temp;
684 OCResourceInterface *type = ptr->rsrcInterface;
694 ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
696 OCFreeCollectionResource(repPayload);
702 OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
703 on the resource directory");
705 return OC_STACK_ERROR;
709 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
711 if (!request || !resource)
713 return OC_STACK_INVALID_PARAM;
716 OCStackResult discoveryResult = OC_STACK_ERROR;
717 OCPayload* payload = NULL;
719 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
721 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
723 // Step 1: Generate the response to discovery request
724 if (virtualUriInRequest == OC_WELL_KNOWN_URI)
726 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
728 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
729 return OC_STACK_UNAUTHORIZED_REQ;
732 char *interfaceQuery = NULL;
733 char *resourceTypeQuery = NULL;
735 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
736 &interfaceQuery, &resourceTypeQuery);
737 bool interfaceQueryAllocated = false;
738 if (!interfaceQuery && !resourceTypeQuery)
740 interfaceQueryAllocated = true;
741 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
744 if (discoveryResult == OC_STACK_OK)
746 payload = (OCPayload *)OCDiscoveryPayloadCreate();
750 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
751 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
752 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
754 const char* uid = OCGetServerInstanceIDString();
757 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
760 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
762 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
765 if (resource->resourceProperties & OC_DISCOVERABLE)
772 discoveryResult = BuildVirtualResourceResponse(resource,
773 discPayload, &request->devAddr, false);
779 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
781 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
782 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
783 if (savedDeviceInfo.deviceName)
785 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
786 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
788 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
789 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
790 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
791 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
792 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
793 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
794 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
796 bool foundResourceAtRD = false;
797 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
800 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
802 OCResource *resource1 = NULL;
804 discoveryResult = checkResourceExistsAtRD(interfaceQuery,
805 resourceTypeQuery, &resource1, &devAddr);
806 if (discoveryResult != OC_STACK_OK)
810 discoveryResult = BuildVirtualResourceResponse(resource1,
811 discPayload, &devAddr, true);
814 discPayload->baseURI = OICStrdup(devAddr.addr);
816 OICFree(resource1->uri);
817 for (OCResourceType *rsrcRt = resource1->rsrcType, *rsrcRtNext = NULL; rsrcRt; )
819 rsrcRtNext = rsrcRt->next;
820 OICFree(rsrcRt->resourcetypename);
825 for (OCResourceInterface *rsrcPtr = resource1->rsrcInterface, *rsrcNext = NULL; rsrcPtr; )
827 rsrcNext = rsrcPtr->next;
828 OICFree(rsrcPtr->name);
832 foundResourceAtRD = true;
835 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
837 discoveryResult = BuildVirtualResourceResponse(resource,
838 discPayload, &request->devAddr, false);
841 // Set discoveryResult appropriately if no 'valid' resources are available
842 if (discPayload->resources == NULL && !foundResourceAtRD)
844 discoveryResult = OC_STACK_NO_RESOURCE;
850 discoveryResult = OC_STACK_NO_MEMORY;
855 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
857 if (interfaceQueryAllocated)
859 OICFree(interfaceQuery);
862 else if (virtualUriInRequest == OC_DEVICE_URI)
864 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
866 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
867 return OC_STACK_UNAUTHORIZED_REQ;
870 const char* deviceId = OCGetServerInstanceIDString();
873 discoveryResult = OC_STACK_ERROR;
877 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
878 if (!dataModelVersions)
880 discoveryResult = OC_STACK_NO_MEMORY;
884 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
885 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
888 discoveryResult = OC_STACK_NO_MEMORY;
892 discoveryResult = OC_STACK_OK;
894 OICFree(dataModelVersions);
898 else if (virtualUriInRequest == OC_PLATFORM_URI)
900 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
902 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
903 return OC_STACK_UNAUTHORIZED_REQ;
906 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
909 discoveryResult = OC_STACK_NO_MEMORY;
913 discoveryResult = OC_STACK_OK;
916 #ifdef ROUTING_GATEWAY
917 else if (OC_GATEWAY_URI == virtualUriInRequest)
919 // Received request for a gateway
920 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
921 discoveryResult = RMHandleGatewayRequest(request, resource);
927 * Step 2: Send the discovery response
929 * Iotivity should respond to discovery requests in below manner:
930 * 1)If query filter matching fails and discovery request is multicast,
931 * it should NOT send any response.
932 * 2)If query filter matching fails and discovery request is unicast,
933 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
934 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
935 * request is multicast, it should NOT send any response.
936 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
937 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
941 if ((virtualUriInRequest == OC_PRESENCE) &&
942 (resource->resourceProperties & OC_ACTIVE))
944 // Presence uses observer notification api to respond via SendPresenceNotification.
945 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
949 #ifdef ROUTING_GATEWAY
950 // Gateway uses the RMHandleGatewayRequest to respond to the request.
951 if (OC_GATEWAY_URI != virtualUriInRequest)
954 if(discoveryResult == OC_STACK_OK)
956 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
958 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
959 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
960 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
962 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
963 discoveryResult, virtualUriInRequest);
964 SendNonPersistantDiscoveryResponse(request, resource, NULL,
965 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
969 // Ignoring the discovery request as per RFC 7252, Section #8.2
970 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
974 OCPayloadDestroy(payload);
980 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
984 return OC_STACK_INVALID_PARAM;
987 OCStackResult result = OC_STACK_OK;
988 OCEntityHandlerResult ehResult = OC_EH_ERROR;
989 OCEntityHandlerRequest ehRequest = {0};
991 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
992 result = FormOCEntityHandlerRequest(&ehRequest,
993 (OCRequestHandle) request,
996 (OCResourceHandle) NULL, request->query,
997 PAYLOAD_TYPE_REPRESENTATION,
999 request->payloadSize,
1000 request->numRcvdVendorSpecificHeaderOptions,
1001 request->rcvdVendorSpecificHeaderOptions,
1002 (OCObserveAction)request->observationOption,
1005 VERIFY_SUCCESS(result, OC_STACK_OK);
1007 // At this point we know for sure that defaultDeviceHandler exists
1008 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
1009 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
1010 if(ehResult == OC_EH_SLOW)
1012 OIC_LOG(INFO, TAG, "This is a slow resource");
1013 request->slowFlag = 1;
1015 else if(ehResult == OC_EH_ERROR)
1017 FindAndDeleteServerRequest(request);
1019 result = EntityHandlerCodeToOCStackCode(ehResult);
1021 OCPayloadDestroy(ehRequest.payload);
1025 static OCStackResult
1026 HandleResourceWithEntityHandler (OCServerRequest *request,
1027 OCResource *resource,
1028 uint8_t collectionResource)
1030 if(!request || ! resource)
1032 return OC_STACK_INVALID_PARAM;
1035 OCStackResult result = OC_STACK_ERROR;
1036 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1037 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1038 ResourceObserver *resObs = NULL;
1040 OCEntityHandlerRequest ehRequest = {0};
1042 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1043 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1044 // check the security resource
1045 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1047 type = PAYLOAD_TYPE_SECURITY;
1051 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
1053 type = PAYLOAD_TYPE_RD;
1056 result = FormOCEntityHandlerRequest(&ehRequest,
1057 (OCRequestHandle)request,
1060 (OCResourceHandle)resource,
1064 request->payloadSize,
1065 request->numRcvdVendorSpecificHeaderOptions,
1066 request->rcvdVendorSpecificHeaderOptions,
1067 (OCObserveAction)request->observationOption,
1070 VERIFY_SUCCESS(result, OC_STACK_OK);
1072 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1074 OIC_LOG(INFO, TAG, "No observation requested");
1075 ehFlag = OC_REQUEST_FLAG;
1077 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
1079 OIC_LOG(INFO, TAG, "Observation registration requested");
1081 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1082 request->tokenLength);
1086 OIC_LOG (INFO, TAG, "Observer with this token already present");
1087 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1088 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1089 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1091 // server requests are usually free'd when the response is sent out
1092 // for the request in ocserverrequest.c : HandleSingleResponse()
1093 // Since we are making an early return and not responding, the server request
1094 // needs to be deleted.
1095 FindAndDeleteServerRequest (request);
1099 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1100 VERIFY_SUCCESS(result, OC_STACK_OK);
1102 result = AddObserver ((const char*)(request->resourceUrl),
1103 (const char *)(request->query),
1104 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1105 resource, request->qos, request->acceptFormat,
1108 if(result == OC_STACK_OK)
1110 OIC_LOG(INFO, TAG, "Added observer successfully");
1111 request->observeResult = OC_STACK_OK;
1112 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1116 // The error in observeResult for the request will be used when responding to this
1117 // request by omitting the observation option/sequence number.
1118 request->observeResult = OC_STACK_ERROR;
1119 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1120 ehFlag = OC_REQUEST_FLAG;
1121 FindAndDeleteServerRequest(request);
1126 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1127 !collectionResource)
1129 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1131 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1135 // Stack does not contain this observation request
1136 // Either token is incorrect or observation list is corrupted
1137 result = OC_STACK_ERROR;
1140 ehRequest.obsInfo.obsId = resObs->observeId;
1141 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1143 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1145 if(result == OC_STACK_OK)
1147 OIC_LOG(INFO, TAG, "Removed observer successfully");
1148 request->observeResult = OC_STACK_OK;
1152 request->observeResult = OC_STACK_ERROR;
1153 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1154 FindAndDeleteServerRequest(request);
1160 result = OC_STACK_ERROR;
1164 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1165 if(ehResult == OC_EH_SLOW)
1167 OIC_LOG(INFO, TAG, "This is a slow resource");
1168 request->slowFlag = 1;
1170 else if(ehResult == OC_EH_ERROR)
1172 FindAndDeleteServerRequest(request);
1174 result = EntityHandlerCodeToOCStackCode(ehResult);
1176 OCPayloadDestroy(ehRequest.payload);
1180 static OCStackResult
1181 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1182 OCResource *resource)
1184 if(!request || !resource)
1186 return OC_STACK_INVALID_PARAM;
1189 OCStackResult result = OC_STACK_ERROR;
1190 OCEntityHandlerRequest ehRequest = {0};
1192 result = FormOCEntityHandlerRequest(&ehRequest,
1193 (OCRequestHandle)request,
1196 (OCResourceHandle)resource,
1198 PAYLOAD_TYPE_REPRESENTATION,
1200 request->payloadSize,
1201 request->numRcvdVendorSpecificHeaderOptions,
1202 request->rcvdVendorSpecificHeaderOptions,
1203 (OCObserveAction)request->observationOption,
1206 if(result == OC_STACK_OK)
1208 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1211 OCPayloadDestroy(ehRequest.payload);
1216 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1218 OCStackResult ret = OC_STACK_OK;
1220 switch (resHandling)
1222 case OC_RESOURCE_VIRTUAL:
1224 ret = HandleVirtualResource (request, resource);
1227 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1229 ret = HandleDefaultDeviceEntityHandler(request);
1232 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1234 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1235 return OC_STACK_ERROR;
1237 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1239 ret = HandleResourceWithEntityHandler (request, resource, 0);
1242 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1244 ret = HandleResourceWithEntityHandler (request, resource, 1);
1247 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1249 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1252 case OC_RESOURCE_NOT_SPECIFIED:
1254 ret = OC_STACK_NO_RESOURCE;
1259 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1260 return OC_STACK_ERROR;
1266 void DeletePlatformInfo()
1268 OIC_LOG(INFO, TAG, "Deleting platform info.");
1270 OICFree(savedPlatformInfo.platformID);
1271 savedPlatformInfo.platformID = NULL;
1273 OICFree(savedPlatformInfo.manufacturerName);
1274 savedPlatformInfo.manufacturerName = NULL;
1276 OICFree(savedPlatformInfo.manufacturerUrl);
1277 savedPlatformInfo.manufacturerUrl = NULL;
1279 OICFree(savedPlatformInfo.modelNumber);
1280 savedPlatformInfo.modelNumber = NULL;
1282 OICFree(savedPlatformInfo.dateOfManufacture);
1283 savedPlatformInfo.dateOfManufacture = NULL;
1285 OICFree(savedPlatformInfo.platformVersion);
1286 savedPlatformInfo.platformVersion = NULL;
1288 OICFree(savedPlatformInfo.operatingSystemVersion);
1289 savedPlatformInfo.operatingSystemVersion = NULL;
1291 OICFree(savedPlatformInfo.hardwareVersion);
1292 savedPlatformInfo.hardwareVersion = NULL;
1294 OICFree(savedPlatformInfo.firmwareVersion);
1295 savedPlatformInfo.firmwareVersion = NULL;
1297 OICFree(savedPlatformInfo.supportUrl);
1298 savedPlatformInfo.supportUrl = NULL;
1300 OICFree(savedPlatformInfo.systemTime);
1301 savedPlatformInfo.systemTime = NULL;
1304 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1306 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1307 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1308 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1309 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1310 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1311 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1312 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1313 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1314 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1315 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1316 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1318 if ((!savedPlatformInfo.platformID && info.platformID)||
1319 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1320 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1321 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1322 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1323 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1324 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1325 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1326 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1327 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1328 (!savedPlatformInfo.systemTime && info.systemTime))
1330 DeletePlatformInfo();
1331 return OC_STACK_INVALID_PARAM;
1338 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1340 DeletePlatformInfo();
1342 OCStackResult res = DeepCopyPlatFormInfo(info);
1344 if (res != OC_STACK_OK)
1346 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1350 OIC_LOG(INFO, TAG, "Platform info saved.");
1356 void DeleteDeviceInfo()
1358 OIC_LOG(INFO, TAG, "Deleting device info.");
1360 OICFree(savedDeviceInfo.deviceName);
1361 OCFreeOCStringLL(savedDeviceInfo.types);
1362 OICFree(savedDeviceInfo.specVersion);
1363 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1364 savedDeviceInfo.deviceName = NULL;
1365 savedDeviceInfo.specVersion = NULL;
1366 savedDeviceInfo.dataModelVersions = NULL;
1369 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1371 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1373 if(!savedDeviceInfo.deviceName && info.deviceName)
1376 return OC_STACK_NO_MEMORY;
1381 savedDeviceInfo.types = CloneOCStringLL(info.types);
1382 OCStringLL *type = info.types;
1386 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1394 // Append the oic.wk.d at the start of rt link parameter value.
1395 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1399 return OC_STACK_NO_MEMORY;
1401 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1405 return OC_STACK_NO_MEMORY;
1407 dest->next = savedDeviceInfo.types;
1408 savedDeviceInfo.types = dest;
1410 if(!savedDeviceInfo.types && info.types)
1413 return OC_STACK_NO_MEMORY;
1417 if (info.specVersion)
1419 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1420 if(!savedDeviceInfo.specVersion && info.specVersion)
1423 return OC_STACK_NO_MEMORY;
1428 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1429 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1432 return OC_STACK_NO_MEMORY;
1436 if (info.dataModelVersions)
1438 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1439 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1442 return OC_STACK_NO_MEMORY;
1447 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1448 if (!savedDeviceInfo.dataModelVersions)
1450 return OC_STACK_NO_MEMORY;
1452 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1453 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1456 return OC_STACK_NO_MEMORY;
1463 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1465 OCStackResult res = OC_STACK_OK;
1469 res = DeepCopyDeviceInfo(info);
1471 VERIFY_SUCCESS(res, OC_STACK_OK);
1473 if (OCGetServerInstanceIDString() == NULL)
1475 OIC_LOG(INFO, TAG, "Device ID generation failed");
1476 res = OC_STACK_ERROR;
1480 OIC_LOG(INFO, TAG, "Device initialized successfully.");