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 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
164 if (numKeyValuePairsParsed >= 2)
166 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
167 return OC_STACK_INVALID_QUERY;
170 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
174 return OC_STACK_INVALID_QUERY;
176 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
178 *filterOne = value; // if
180 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
182 *filterTwo = value; // rt
186 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
187 return OC_STACK_INVALID_QUERY;
189 ++numKeyValuePairsParsed;
191 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
194 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
198 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
200 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
202 return OC_WELL_KNOWN_URI;
204 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
206 return OC_DEVICE_URI;
208 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
210 return OC_PLATFORM_URI;
212 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
214 return OC_RESOURCE_TYPES_URI;
216 #ifdef ROUTING_GATEWAY
217 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
219 return OC_GATEWAY_URI;
223 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
227 #endif //WITH_PRESENCE
228 return OC_UNKNOWN_URI;
231 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
232 char **filterOne, char **filterTwo)
234 if(!filterOne || !filterTwo)
236 return OC_STACK_INVALID_PARAM;
243 if (uri == OC_PRESENCE)
245 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
246 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
251 OCStackResult result = OC_STACK_OK;
255 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
261 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
262 OCRepPayload** payload)
264 OCRepPayload *tempPayload = OCRepPayloadCreate();
268 OCRepPayloadDestroy(tempPayload);
269 return OC_STACK_INVALID_PARAM;
274 return OC_STACK_NO_MEMORY;
277 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
279 OCResourceType *resType = resourcePtr->rsrcType;
282 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
283 resType = resType->next;
286 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
289 OCRepPayloadAddInterface(tempPayload, resInterface->name);
290 resInterface = resInterface->next;
293 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
296 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
297 resAttrib->attrValue);
298 resAttrib = resAttrib->next;
303 *payload = tempPayload;
307 OCRepPayloadAppend(*payload, tempPayload);
313 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
314 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
316 if (!resourcePtr || !payload)
318 return OC_STACK_INVALID_PARAM;
320 uint16_t securePort = 0;
321 if (resourcePtr->resourceProperties & OC_SECURE)
323 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
331 securePort = devAddr->port;
334 uint16_t tcpPort = 0;
336 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
340 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
342 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
348 uint8_t IsCollectionResource (OCResource *resource)
355 if(resource->rsrcChildResourcesHead != NULL)
363 OCResource *FindResourceByUri(const char* resourceUri)
370 OCResource * pointer = headResource;
373 if (strcmp(resourceUri, pointer->uri) == 0)
377 pointer = pointer->next;
379 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
384 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
385 ResourceHandling *handling,
386 OCResource **resource)
388 if(!request || !handling || !resource)
390 return OC_STACK_INVALID_PARAM;
393 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
395 // Check if virtual resource
396 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
398 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
399 *handling = OC_RESOURCE_VIRTUAL;
400 *resource = headResource;
403 if (strlen((const char*)(request->resourceUrl)) == 0)
405 // Resource URL not specified
406 *handling = OC_RESOURCE_NOT_SPECIFIED;
407 return OC_STACK_NO_RESOURCE;
411 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
412 *resource = resourcePtr;
415 if(defaultDeviceHandler)
417 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
421 // Resource does not exist
422 // and default device handler does not exist
423 *handling = OC_RESOURCE_NOT_SPECIFIED;
424 return OC_STACK_NO_RESOURCE;
427 if (IsCollectionResource (resourcePtr))
429 // Collection resource
430 if (resourcePtr->entityHandler != defaultResourceEHandler)
432 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
437 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
443 // Resource not a collection
444 if (resourcePtr->entityHandler != defaultResourceEHandler)
446 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
451 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
458 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
460 OCStackResult result;
465 result = OC_STACK_OK;
468 result = OC_STACK_SLOW_RESOURCE;
471 result = OC_STACK_ERROR;
473 case OC_EH_FORBIDDEN:
474 result = OC_STACK_RESOURCE_ERROR;
476 case OC_EH_RESOURCE_CREATED:
477 result = OC_STACK_RESOURCE_CREATED;
479 case OC_EH_RESOURCE_DELETED:
480 result = OC_STACK_RESOURCE_DELETED;
482 case OC_EH_RESOURCE_NOT_FOUND:
483 result = OC_STACK_NO_RESOURCE;
486 result = OC_STACK_ERROR;
492 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
499 // Null or empty is analogous to no filter.
500 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
505 OCResourceType *resourceTypePtr = resource->rsrcType;
507 while (resourceTypePtr)
509 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
513 resourceTypePtr = resourceTypePtr->next;
516 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
520 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
527 // Null or empty is analogous to no filter.
528 if (interfaceFilter == NULL || *interfaceFilter == 0)
533 OCResourceInterface *interfacePtr = resource->rsrcInterface;
537 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
538 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
539 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
543 interfacePtr = interfacePtr->next;
546 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
551 * If the filters are null, they will be assumed to NOT be present
552 * and the resource will not be matched against them.
553 * Function will return true if all non null AND non empty filters passed in find a match.
555 static bool includeThisResourceInResponse(OCResource *resource,
556 char *interfaceFilter,
557 char *resourceTypeFilter)
561 OIC_LOG(ERROR, TAG, "Invalid resource");
565 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
568 * At least one valid filter should be available to
569 * include the resource in discovery response
571 if (!(resourceTypeFilter && *resourceTypeFilter))
573 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
574 resource", resource->uri);
578 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
579 !(resource->resourceProperties & OC_DISCOVERABLE))
581 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
585 return resourceMatchesIFFilter(resource, interfaceFilter) &&
586 resourceMatchesRTFilter(resource, resourceTypeFilter);
590 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
591 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
593 OCEntityHandlerResponse response = {0};
595 response.ehResult = ehResult;
596 response.payload = discoveryPayload;
597 response.persistentBufferFlag = 0;
598 response.requestHandle = (OCRequestHandle) request;
599 response.resourceHandle = (OCResourceHandle) resource;
601 return OCDoResponse(&response);
605 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
606 OCResource **payload, OCDevAddr *devAddr)
608 OCResourceCollectionPayload *repPayload;
611 return OC_STACK_ERROR;
613 if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
617 return OC_STACK_ERROR;
619 OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
622 return OC_STACK_NO_MEMORY;
625 ptr->uri = OICStrdup(repPayload->setLinks->href);
628 return OC_STACK_NO_MEMORY;
630 OCStringLL *rt = repPayload->setLinks->rt;
633 OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
637 return OC_STACK_NO_MEMORY;
640 temp->resourcetypename = OICStrdup(rt->value);
643 ptr->rsrcType = temp;
647 OCResourceType *type = ptr->rsrcType;
657 OCStringLL *itf = repPayload->setLinks->itf;
660 OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
665 return OC_STACK_NO_MEMORY;
668 temp->name = OICStrdup(itf->value);
669 if (!ptr->rsrcInterface)
671 ptr->rsrcInterface = temp;
675 OCResourceInterface *type = ptr->rsrcInterface;
685 ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
687 OCFreeCollectionResource(repPayload);
693 OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
694 on the resource directory");
696 return OC_STACK_ERROR;
700 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
702 if (!request || !resource)
704 return OC_STACK_INVALID_PARAM;
707 OCStackResult discoveryResult = OC_STACK_ERROR;
708 OCPayload* payload = NULL;
710 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
712 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
714 // Step 1: Generate the response to discovery request
715 if (virtualUriInRequest == OC_WELL_KNOWN_URI)
717 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
719 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
720 return OC_STACK_UNAUTHORIZED_REQ;
723 char *interfaceQuery = NULL;
724 char *resourceTypeQuery = NULL;
726 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
727 &interfaceQuery, &resourceTypeQuery);
728 bool interfaceQueryAllocated = false;
729 if (!interfaceQuery && !resourceTypeQuery)
731 interfaceQueryAllocated = true;
732 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
735 if (discoveryResult == OC_STACK_OK)
737 payload = (OCPayload *)OCDiscoveryPayloadCreate();
741 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
742 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
743 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
745 const char* uid = OCGetServerInstanceIDString();
748 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
751 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
753 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
756 if (resource->resourceProperties & OC_DISCOVERABLE)
763 discoveryResult = BuildVirtualResourceResponse(resource,
764 discPayload, &request->devAddr, false);
770 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
772 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
773 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
774 if (savedDeviceInfo.deviceName)
776 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
777 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
779 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
780 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
781 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
782 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
783 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
784 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
785 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
787 bool foundResourceAtRD = false;
788 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
791 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
793 OCResource *resource1 = NULL;
795 discoveryResult = checkResourceExistsAtRD(interfaceQuery,
796 resourceTypeQuery, &resource1, &devAddr);
797 if (discoveryResult != OC_STACK_OK)
801 discoveryResult = BuildVirtualResourceResponse(resource1,
802 discPayload, &devAddr, true);
805 discPayload->baseURI = OICStrdup(devAddr.addr);
807 OICFree(resource1->uri);
808 for (OCResourceType *rsrcRt = resource1->rsrcType, *rsrcRtNext = NULL; rsrcRt; )
810 rsrcRtNext = rsrcRt->next;
811 OICFree(rsrcRt->resourcetypename);
816 for (OCResourceInterface *rsrcPtr = resource1->rsrcInterface, *rsrcNext = NULL; rsrcPtr; )
818 rsrcNext = rsrcPtr->next;
819 OICFree(rsrcPtr->name);
823 foundResourceAtRD = true;
826 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
828 discoveryResult = BuildVirtualResourceResponse(resource,
829 discPayload, &request->devAddr, false);
832 // Set discoveryResult appropriately if no 'valid' resources are available
833 if (discPayload->resources == NULL && !foundResourceAtRD)
835 discoveryResult = OC_STACK_NO_RESOURCE;
841 discoveryResult = OC_STACK_NO_MEMORY;
846 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
848 if (interfaceQueryAllocated)
850 OICFree(interfaceQuery);
853 else if (virtualUriInRequest == OC_DEVICE_URI)
855 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
857 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
858 return OC_STACK_UNAUTHORIZED_REQ;
861 const char* deviceId = OCGetServerInstanceIDString();
864 discoveryResult = OC_STACK_ERROR;
868 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
869 if (!dataModelVersions)
871 discoveryResult = OC_STACK_NO_MEMORY;
875 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
876 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
879 discoveryResult = OC_STACK_NO_MEMORY;
883 discoveryResult = OC_STACK_OK;
885 OICFree(dataModelVersions);
889 else if (virtualUriInRequest == OC_PLATFORM_URI)
891 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
893 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
894 return OC_STACK_UNAUTHORIZED_REQ;
897 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
900 discoveryResult = OC_STACK_NO_MEMORY;
904 discoveryResult = OC_STACK_OK;
907 #ifdef ROUTING_GATEWAY
908 else if (OC_GATEWAY_URI == virtualUriInRequest)
910 // Received request for a gateway
911 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
912 discoveryResult = RMHandleGatewayRequest(request, resource);
918 * Step 2: Send the discovery response
920 * Iotivity should respond to discovery requests in below manner:
921 * 1)If query filter matching fails and discovery request is multicast,
922 * it should NOT send any response.
923 * 2)If query filter matching fails and discovery request is unicast,
924 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
925 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
926 * request is multicast, it should NOT send any response.
927 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
928 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
932 if ((virtualUriInRequest == OC_PRESENCE) &&
933 (resource->resourceProperties & OC_ACTIVE))
935 // Presence uses observer notification api to respond via SendPresenceNotification.
936 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
940 #ifdef ROUTING_GATEWAY
941 // Gateway uses the RMHandleGatewayRequest to respond to the request.
942 if (OC_GATEWAY_URI != virtualUriInRequest)
945 if(discoveryResult == OC_STACK_OK)
947 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
949 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
950 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
951 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
953 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
954 discoveryResult, virtualUriInRequest);
955 SendNonPersistantDiscoveryResponse(request, resource, NULL,
956 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
960 // Ignoring the discovery request as per RFC 7252, Section #8.2
961 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
965 OCPayloadDestroy(payload);
971 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
975 return OC_STACK_INVALID_PARAM;
978 OCStackResult result = OC_STACK_OK;
979 OCEntityHandlerResult ehResult = OC_EH_ERROR;
980 OCEntityHandlerRequest ehRequest = {0};
982 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
983 result = FormOCEntityHandlerRequest(&ehRequest,
984 (OCRequestHandle) request,
987 (OCResourceHandle) NULL, request->query,
988 PAYLOAD_TYPE_REPRESENTATION,
990 request->payloadSize,
991 request->numRcvdVendorSpecificHeaderOptions,
992 request->rcvdVendorSpecificHeaderOptions,
993 (OCObserveAction)request->observationOption,
996 VERIFY_SUCCESS(result, OC_STACK_OK);
998 // At this point we know for sure that defaultDeviceHandler exists
999 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
1000 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
1001 if(ehResult == OC_EH_SLOW)
1003 OIC_LOG(INFO, TAG, "This is a slow resource");
1004 request->slowFlag = 1;
1006 else if(ehResult == OC_EH_ERROR)
1008 FindAndDeleteServerRequest(request);
1010 result = EntityHandlerCodeToOCStackCode(ehResult);
1012 OCPayloadDestroy(ehRequest.payload);
1016 static OCStackResult
1017 HandleResourceWithEntityHandler (OCServerRequest *request,
1018 OCResource *resource,
1019 uint8_t collectionResource)
1021 if(!request || ! resource)
1023 return OC_STACK_INVALID_PARAM;
1026 OCStackResult result = OC_STACK_ERROR;
1027 OCEntityHandlerResult ehResult = OC_EH_ERROR;
1028 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1029 ResourceObserver *resObs = NULL;
1031 OCEntityHandlerRequest ehRequest = {0};
1033 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1034 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1035 // check the security resource
1036 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1038 type = PAYLOAD_TYPE_SECURITY;
1042 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
1044 type = PAYLOAD_TYPE_RD;
1047 result = FormOCEntityHandlerRequest(&ehRequest,
1048 (OCRequestHandle)request,
1051 (OCResourceHandle)resource,
1055 request->payloadSize,
1056 request->numRcvdVendorSpecificHeaderOptions,
1057 request->rcvdVendorSpecificHeaderOptions,
1058 (OCObserveAction)request->observationOption,
1061 VERIFY_SUCCESS(result, OC_STACK_OK);
1063 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1065 OIC_LOG(INFO, TAG, "No observation requested");
1066 ehFlag = OC_REQUEST_FLAG;
1068 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
1070 OIC_LOG(INFO, TAG, "Observation registration requested");
1072 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1073 request->tokenLength);
1077 OIC_LOG (INFO, TAG, "Observer with this token already present");
1078 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1079 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1080 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1082 // server requests are usually free'd when the response is sent out
1083 // for the request in ocserverrequest.c : HandleSingleResponse()
1084 // Since we are making an early return and not responding, the server request
1085 // needs to be deleted.
1086 FindAndDeleteServerRequest (request);
1090 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1091 VERIFY_SUCCESS(result, OC_STACK_OK);
1093 result = AddObserver ((const char*)(request->resourceUrl),
1094 (const char *)(request->query),
1095 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1096 resource, request->qos, request->acceptFormat,
1099 if(result == OC_STACK_OK)
1101 OIC_LOG(INFO, TAG, "Added observer successfully");
1102 request->observeResult = OC_STACK_OK;
1103 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1107 // The error in observeResult for the request will be used when responding to this
1108 // request by omitting the observation option/sequence number.
1109 request->observeResult = OC_STACK_ERROR;
1110 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1111 ehFlag = OC_REQUEST_FLAG;
1112 FindAndDeleteServerRequest(request);
1117 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1118 !collectionResource)
1120 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1122 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1126 // Stack does not contain this observation request
1127 // Either token is incorrect or observation list is corrupted
1128 result = OC_STACK_ERROR;
1131 ehRequest.obsInfo.obsId = resObs->observeId;
1132 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1134 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1136 if(result == OC_STACK_OK)
1138 OIC_LOG(INFO, TAG, "Removed observer successfully");
1139 request->observeResult = OC_STACK_OK;
1143 request->observeResult = OC_STACK_ERROR;
1144 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1145 FindAndDeleteServerRequest(request);
1151 result = OC_STACK_ERROR;
1155 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1156 if(ehResult == OC_EH_SLOW)
1158 OIC_LOG(INFO, TAG, "This is a slow resource");
1159 request->slowFlag = 1;
1161 else if(ehResult == OC_EH_ERROR)
1163 FindAndDeleteServerRequest(request);
1165 result = EntityHandlerCodeToOCStackCode(ehResult);
1167 OCPayloadDestroy(ehRequest.payload);
1171 static OCStackResult
1172 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1173 OCResource *resource)
1175 if(!request || !resource)
1177 return OC_STACK_INVALID_PARAM;
1180 OCStackResult result = OC_STACK_ERROR;
1181 OCEntityHandlerRequest ehRequest = {0};
1183 result = FormOCEntityHandlerRequest(&ehRequest,
1184 (OCRequestHandle)request,
1187 (OCResourceHandle)resource,
1189 PAYLOAD_TYPE_REPRESENTATION,
1191 request->payloadSize,
1192 request->numRcvdVendorSpecificHeaderOptions,
1193 request->rcvdVendorSpecificHeaderOptions,
1194 (OCObserveAction)request->observationOption,
1197 if(result == OC_STACK_OK)
1199 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1202 OCPayloadDestroy(ehRequest.payload);
1207 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1209 OCStackResult ret = OC_STACK_OK;
1211 switch (resHandling)
1213 case OC_RESOURCE_VIRTUAL:
1215 ret = HandleVirtualResource (request, resource);
1218 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1220 ret = HandleDefaultDeviceEntityHandler(request);
1223 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1225 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1226 return OC_STACK_ERROR;
1228 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1230 ret = HandleResourceWithEntityHandler (request, resource, 0);
1233 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1235 ret = HandleResourceWithEntityHandler (request, resource, 1);
1238 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1240 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1243 case OC_RESOURCE_NOT_SPECIFIED:
1245 ret = OC_STACK_NO_RESOURCE;
1250 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1251 return OC_STACK_ERROR;
1257 void DeletePlatformInfo()
1259 OIC_LOG(INFO, TAG, "Deleting platform info.");
1261 OICFree(savedPlatformInfo.platformID);
1262 savedPlatformInfo.platformID = NULL;
1264 OICFree(savedPlatformInfo.manufacturerName);
1265 savedPlatformInfo.manufacturerName = NULL;
1267 OICFree(savedPlatformInfo.manufacturerUrl);
1268 savedPlatformInfo.manufacturerUrl = NULL;
1270 OICFree(savedPlatformInfo.modelNumber);
1271 savedPlatformInfo.modelNumber = NULL;
1273 OICFree(savedPlatformInfo.dateOfManufacture);
1274 savedPlatformInfo.dateOfManufacture = NULL;
1276 OICFree(savedPlatformInfo.platformVersion);
1277 savedPlatformInfo.platformVersion = NULL;
1279 OICFree(savedPlatformInfo.operatingSystemVersion);
1280 savedPlatformInfo.operatingSystemVersion = NULL;
1282 OICFree(savedPlatformInfo.hardwareVersion);
1283 savedPlatformInfo.hardwareVersion = NULL;
1285 OICFree(savedPlatformInfo.firmwareVersion);
1286 savedPlatformInfo.firmwareVersion = NULL;
1288 OICFree(savedPlatformInfo.supportUrl);
1289 savedPlatformInfo.supportUrl = NULL;
1291 OICFree(savedPlatformInfo.systemTime);
1292 savedPlatformInfo.systemTime = NULL;
1295 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1297 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1298 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1299 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1300 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1301 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1302 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1303 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1304 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1305 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1306 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1307 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1309 if ((!savedPlatformInfo.platformID && info.platformID)||
1310 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1311 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1312 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1313 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1314 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1315 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1316 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1317 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1318 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1319 (!savedPlatformInfo.systemTime && info.systemTime))
1321 DeletePlatformInfo();
1322 return OC_STACK_INVALID_PARAM;
1329 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1331 DeletePlatformInfo();
1333 OCStackResult res = DeepCopyPlatFormInfo(info);
1335 if (res != OC_STACK_OK)
1337 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1341 OIC_LOG(INFO, TAG, "Platform info saved.");
1347 void DeleteDeviceInfo()
1349 OIC_LOG(INFO, TAG, "Deleting device info.");
1351 OICFree(savedDeviceInfo.deviceName);
1352 OCFreeOCStringLL(savedDeviceInfo.types);
1353 OICFree(savedDeviceInfo.specVersion);
1354 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1355 savedDeviceInfo.deviceName = NULL;
1356 savedDeviceInfo.specVersion = NULL;
1357 savedDeviceInfo.dataModelVersions = NULL;
1360 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1362 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1364 if(!savedDeviceInfo.deviceName && info.deviceName)
1367 return OC_STACK_NO_MEMORY;
1372 savedDeviceInfo.types = CloneOCStringLL(info.types);
1373 OCStringLL *type = info.types;
1377 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1385 // Append the oic.wk.d at the start of rt link parameter value.
1386 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1390 return OC_STACK_NO_MEMORY;
1392 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1396 return OC_STACK_NO_MEMORY;
1398 dest->next = savedDeviceInfo.types;
1399 savedDeviceInfo.types = dest;
1401 if(!savedDeviceInfo.types && info.types)
1404 return OC_STACK_NO_MEMORY;
1408 if (info.specVersion)
1410 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1411 if(!savedDeviceInfo.specVersion && info.specVersion)
1414 return OC_STACK_NO_MEMORY;
1419 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1420 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1423 return OC_STACK_NO_MEMORY;
1427 if (info.dataModelVersions)
1429 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1430 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1433 return OC_STACK_NO_MEMORY;
1438 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1439 if (!savedDeviceInfo.dataModelVersions)
1441 return OC_STACK_NO_MEMORY;
1443 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1444 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1447 return OC_STACK_NO_MEMORY;
1454 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1456 OCStackResult res = OC_STACK_OK;
1460 res = DeepCopyDeviceInfo(info);
1462 VERIFY_SUCCESS(res, OC_STACK_OK);
1464 if (OCGetServerInstanceIDString() == NULL)
1466 OIC_LOG(INFO, TAG, "Device ID generation failed");
1467 res = OC_STACK_ERROR;
1471 OIC_LOG(INFO, TAG, "Device initialized successfully.");