1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1-2001 base
24 // specification (excluding the XSI extension).
25 // For POSIX.1-2001 base specification,
26 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
27 #define _POSIX_C_SOURCE 200112L
32 #include "iotivity_config.h"
40 #include "ocresource.h"
41 #include "ocresourcehandler.h"
42 #include "ocobserve.h"
43 #include "occollection.h"
44 #include "oic_malloc.h"
45 #include "oic_string.h"
48 #include "ocpayload.h"
49 #include "secureresourcemanager.h"
51 #include "cainterface.h"
52 #include "ocpayload.h"
54 #ifdef ROUTING_GATEWAY
55 #include "routingmanager.h"
59 #include "rd_database.h"
63 #define TAG "OIC_RI_RESOURCE"
65 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
66 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
68 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
69 TAG, #arg " is NULL"); return (retVal); } }
71 #include "platform_features.h"
73 extern OCResource *headResource;
74 static OCPlatformInfo savedPlatformInfo = {0};
75 static OCDeviceInfo savedDeviceInfo = {0};
78 * Prepares a Payload for response.
80 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
81 OCDiscoveryPayload* payload,
84 //-----------------------------------------------------------------------------
85 // Default resource entity handler function
86 //-----------------------------------------------------------------------------
87 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
88 OCEntityHandlerRequest * request, void* callbackParam)
90 //TODO ("Implement me!!!!");
91 // TODO: remove silence unused param warnings
95 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
98 /* This method will retrieve the port at which the secure resource is hosted */
99 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
103 if (endpoint->adapter == OC_ADAPTER_IP)
105 if (endpoint->flags & OC_IP_USE_V6)
107 p = caglobals.ip.u6s.port;
109 else if (endpoint->flags & OC_IP_USE_V4)
111 p = caglobals.ip.u4s.port;
120 /* This method will retrieve the tcp port */
121 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
125 if (endpoint->adapter == OC_ADAPTER_IP)
127 if (endpoint->flags & OC_IP_USE_V4)
129 p = caglobals.tcp.ipv4.port;
131 else if (endpoint->flags & OC_IP_USE_V6)
133 p = caglobals.tcp.ipv6.port;
143 * Function will extract 0, 1 or 2 filters from query.
144 * More than 2 filters or unsupported filters will result in error.
145 * If both filters are of the same supported type, the 2nd one will be picked.
146 * Resource and device filters in the SAME query are NOT validated
147 * and resources will likely not clear filters.
149 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
154 char *restOfQuery = NULL;
155 int numKeyValuePairsParsed = 0;
160 OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
162 if (strnlen(query, MAX_QUERY_LENGTH) >= MAX_QUERY_LENGTH)
164 OIC_LOG(ERROR, TAG, "Query exceeds maximum length.");
165 return OC_STACK_INVALID_QUERY;
168 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
172 if (numKeyValuePairsParsed >= 2)
174 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
175 return OC_STACK_INVALID_QUERY;
178 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
182 return OC_STACK_INVALID_QUERY;
184 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
186 *filterOne = value; // if
188 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
190 *filterTwo = value; // rt
194 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
195 return OC_STACK_INVALID_QUERY;
197 ++numKeyValuePairsParsed;
199 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
202 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
206 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
208 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
210 return OC_WELL_KNOWN_URI;
212 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
214 return OC_DEVICE_URI;
216 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
218 return OC_PLATFORM_URI;
220 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
222 return OC_RESOURCE_TYPES_URI;
224 #ifdef ROUTING_GATEWAY
225 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
227 return OC_GATEWAY_URI;
231 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
235 #endif //WITH_PRESENCE
238 else if (0 == strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_MQ_URI))
240 return OC_MQ_BROKER_URI;
245 else if (strcmp(uriInRequest, OC_RSRVD_KEEPALIVE_URI) == 0)
247 return OC_KEEPALIVE_RESOURCE_URI;
251 return OC_UNKNOWN_URI;
254 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
255 char **filterOne, char **filterTwo)
257 if(!filterOne || !filterTwo)
259 return OC_STACK_INVALID_PARAM;
266 if (uri == OC_PRESENCE)
268 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
269 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
274 OCStackResult result = OC_STACK_OK;
278 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
284 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
285 OCRepPayload** payload)
287 OCRepPayload *tempPayload = OCRepPayloadCreate();
291 OCRepPayloadDestroy(tempPayload);
292 return OC_STACK_INVALID_PARAM;
297 return OC_STACK_NO_MEMORY;
300 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
302 OCResourceType *resType = resourcePtr->rsrcType;
305 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
306 resType = resType->next;
309 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
312 OCRepPayloadAddInterface(tempPayload, resInterface->name);
313 resInterface = resInterface->next;
316 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
319 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
320 resAttrib->attrValue);
321 resAttrib = resAttrib->next;
326 *payload = tempPayload;
330 OCRepPayloadAppend(*payload, tempPayload);
336 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
337 OCDiscoveryPayload *payload, OCDevAddr *devAddr)
339 if (!resourcePtr || !payload)
341 return OC_STACK_INVALID_PARAM;
343 uint16_t securePort = 0;
344 if (resourcePtr->resourceProperties & OC_SECURE)
346 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
353 uint16_t tcpPort = 0;
354 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
358 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
360 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
366 uint8_t IsCollectionResource (OCResource *resource)
373 if(resource->rsrcChildResourcesHead != NULL)
381 OCResource *FindResourceByUri(const char* resourceUri)
388 OCResource * pointer = headResource;
391 if (strcmp(resourceUri, pointer->uri) == 0)
395 pointer = pointer->next;
397 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
402 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
403 ResourceHandling *handling,
404 OCResource **resource)
406 if(!request || !handling || !resource)
408 return OC_STACK_INVALID_PARAM;
411 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
413 // Check if virtual resource
414 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
416 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
417 *handling = OC_RESOURCE_VIRTUAL;
418 *resource = headResource;
421 if (strlen((const char*)(request->resourceUrl)) == 0)
423 // Resource URL not specified
424 *handling = OC_RESOURCE_NOT_SPECIFIED;
425 return OC_STACK_NO_RESOURCE;
429 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
430 *resource = resourcePtr;
433 if(defaultDeviceHandler)
435 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
439 // Resource does not exist
440 // and default device handler does not exist
441 *handling = OC_RESOURCE_NOT_SPECIFIED;
442 return OC_STACK_NO_RESOURCE;
445 if (IsCollectionResource (resourcePtr))
447 // Collection resource
448 if (resourcePtr->entityHandler != defaultResourceEHandler)
450 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
455 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
461 // Resource not a collection
462 if (resourcePtr->entityHandler != defaultResourceEHandler)
464 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
469 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
476 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
478 OCStackResult result;
485 result = OC_STACK_OK;
488 result = OC_STACK_SLOW_RESOURCE;
491 result = OC_STACK_ERROR;
493 case OC_EH_FORBIDDEN:
494 result = OC_STACK_RESOURCE_ERROR;
496 case OC_EH_RESOURCE_CREATED:
497 result = OC_STACK_RESOURCE_CREATED;
499 case OC_EH_RESOURCE_DELETED:
500 result = OC_STACK_RESOURCE_DELETED;
503 result = OC_STACK_RESOURCE_CHANGED;
505 case OC_EH_RESOURCE_NOT_FOUND:
506 result = OC_STACK_NO_RESOURCE;
509 result = OC_STACK_ERROR;
515 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
522 // Null or empty is analogous to no filter.
523 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
528 OCResourceType *resourceTypePtr = resource->rsrcType;
530 while (resourceTypePtr)
532 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
536 resourceTypePtr = resourceTypePtr->next;
539 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
543 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
550 // Null or empty is analogous to no filter.
551 if (interfaceFilter == NULL || *interfaceFilter == 0)
556 OCResourceInterface *interfacePtr = resource->rsrcInterface;
560 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
561 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
562 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
566 interfacePtr = interfacePtr->next;
569 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
574 * If the filters are null, they will be assumed to NOT be present
575 * and the resource will not be matched against them.
576 * Function will return true if all non null AND non empty filters passed in find a match.
578 static bool includeThisResourceInResponse(OCResource *resource,
579 char *interfaceFilter,
580 char *resourceTypeFilter)
584 OIC_LOG(ERROR, TAG, "Invalid resource");
588 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
591 * At least one valid filter should be available to
592 * include the resource in discovery response
594 if (!(resourceTypeFilter && *resourceTypeFilter))
596 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
597 resource", resource->uri);
601 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
602 !(resource->resourceProperties & OC_DISCOVERABLE))
604 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
608 return resourceMatchesIFFilter(resource, interfaceFilter) &&
609 resourceMatchesRTFilter(resource, resourceTypeFilter);
613 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
614 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
616 OCEntityHandlerResponse response = {0};
618 response.ehResult = ehResult;
619 response.payload = discoveryPayload;
620 response.persistentBufferFlag = 0;
621 response.requestHandle = (OCRequestHandle) request;
622 response.resourceHandle = (OCResourceHandle) resource;
624 return OCDoResponse(&response);
627 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
629 if (!request || !resource)
631 return OC_STACK_INVALID_PARAM;
634 OCStackResult discoveryResult = OC_STACK_ERROR;
635 OCPayload* payload = NULL;
637 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
639 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
641 // Step 1: Generate the response to discovery request
642 if (virtualUriInRequest == OC_WELL_KNOWN_URI
644 || virtualUriInRequest == OC_MQ_BROKER_URI
648 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
650 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
651 return OC_STACK_UNAUTHORIZED_REQ;
654 char *interfaceQuery = NULL;
655 char *resourceTypeQuery = NULL;
657 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
658 &interfaceQuery, &resourceTypeQuery);
659 bool interfaceQueryAllocated = false;
660 if (!interfaceQuery && !resourceTypeQuery)
662 interfaceQueryAllocated = true;
663 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
666 if (discoveryResult == OC_STACK_OK)
668 payload = (OCPayload *)OCDiscoveryPayloadCreate();
672 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
673 bool foundResourceAtRD = false;
675 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
677 OCResourceProperty prop = OC_DISCOVERABLE;
679 if (OC_MQ_BROKER_URI == virtualUriInRequest)
685 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
687 foundResourceAtRD = false;
689 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
691 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
693 foundResourceAtRD = true;
694 discoveryResult = OC_STACK_OK;
698 if (!foundResourceAtRD && (resource->resourceProperties & prop))
700 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
706 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
708 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
709 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
710 if (savedDeviceInfo.deviceName)
712 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
713 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
715 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
716 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
717 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
718 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
719 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
720 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
721 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
723 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
726 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
728 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
730 foundResourceAtRD = true;
731 discoveryResult = OC_STACK_OK;
735 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
737 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
740 // Set discoveryResult appropriately if no 'valid' resources are available
741 if (discPayload->resources == NULL && !foundResourceAtRD)
743 discoveryResult = OC_STACK_NO_RESOURCE;
746 if (discoveryResult == OC_STACK_OK && foundResourceAtRD == false)
748 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
749 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
751 const char* uid = OCGetServerInstanceIDString();
754 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
760 discoveryResult = OC_STACK_NO_MEMORY;
766 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
768 if (interfaceQueryAllocated)
770 OICFree(interfaceQuery);
773 else if (virtualUriInRequest == OC_DEVICE_URI)
775 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
777 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
778 return OC_STACK_UNAUTHORIZED_REQ;
781 const char* deviceId = OCGetServerInstanceIDString();
784 discoveryResult = OC_STACK_ERROR;
788 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
789 if (!dataModelVersions)
791 discoveryResult = OC_STACK_NO_MEMORY;
795 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
796 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
799 discoveryResult = OC_STACK_NO_MEMORY;
803 discoveryResult = OC_STACK_OK;
805 OICFree(dataModelVersions);
809 else if (virtualUriInRequest == OC_PLATFORM_URI)
811 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
813 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
814 return OC_STACK_UNAUTHORIZED_REQ;
817 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
820 discoveryResult = OC_STACK_NO_MEMORY;
824 discoveryResult = OC_STACK_OK;
827 #ifdef ROUTING_GATEWAY
828 else if (OC_GATEWAY_URI == virtualUriInRequest)
830 // Received request for a gateway
831 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
832 discoveryResult = RMHandleGatewayRequest(request, resource);
837 else if (OC_KEEPALIVE_RESOURCE_URI == virtualUriInRequest)
839 // Received request for a keepalive
840 OIC_LOG(INFO, TAG, "Request is for KeepAlive Request");
841 discoveryResult = HandleKeepAliveRequest(request, resource);
845 * Step 2: Send the discovery response
847 * Iotivity should respond to discovery requests in below manner:
848 * 1)If query filter matching fails and discovery request is multicast,
849 * it should NOT send any response.
850 * 2)If query filter matching fails and discovery request is unicast,
851 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
852 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
853 * request is multicast, it should NOT send any response.
854 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
855 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
859 if ((virtualUriInRequest == OC_PRESENCE) &&
860 (resource->resourceProperties & OC_ACTIVE))
862 // Need to send ACK when the request is CON.
863 if (request->qos == OC_HIGH_QOS)
865 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
866 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
867 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
868 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
870 FindAndDeleteServerRequest(request);
872 // Presence uses observer notification api to respond via SendPresenceNotification.
873 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
878 // Gateway uses the RMHandleGatewayRequest to respond to the request.
879 if (OC_GATEWAY_URI != virtualUriInRequest)
883 // KeepAlive uses the HandleKeepAliveRequest to respond to the request.
884 if (OC_KEEPALIVE_RESOURCE_URI != virtualUriInRequest)
887 if(discoveryResult == OC_STACK_OK)
889 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
891 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
892 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
893 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
895 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
896 discoveryResult, virtualUriInRequest);
897 SendNonPersistantDiscoveryResponse(request, resource, NULL,
898 (discoveryResult == OC_STACK_NO_RESOURCE) ?
899 OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
903 // Ignoring the discovery request as per RFC 7252, Section #8.2
904 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send.");
905 // the request should be removed.
906 // since it never remove and causes a big memory waste.
907 FindAndDeleteServerRequest(request);
912 OCPayloadDestroy(payload);
918 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
922 return OC_STACK_INVALID_PARAM;
925 OCStackResult result = OC_STACK_OK;
926 OCEntityHandlerResult ehResult = OC_EH_ERROR;
927 OCEntityHandlerRequest ehRequest = {0};
929 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
930 result = FormOCEntityHandlerRequest(&ehRequest,
931 (OCRequestHandle) request,
934 (OCResourceHandle) NULL, request->query,
935 PAYLOAD_TYPE_REPRESENTATION,
937 request->payloadSize,
938 request->numRcvdVendorSpecificHeaderOptions,
939 request->rcvdVendorSpecificHeaderOptions,
940 (OCObserveAction)request->observationOption,
943 VERIFY_SUCCESS(result, OC_STACK_OK);
945 // At this point we know for sure that defaultDeviceHandler exists
946 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
947 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
948 if(ehResult == OC_EH_SLOW)
950 OIC_LOG(INFO, TAG, "This is a slow resource");
951 request->slowFlag = 1;
953 else if(ehResult == OC_EH_ERROR)
955 FindAndDeleteServerRequest(request);
957 result = EntityHandlerCodeToOCStackCode(ehResult);
959 OCPayloadDestroy(ehRequest.payload);
964 HandleResourceWithEntityHandler (OCServerRequest *request,
965 OCResource *resource,
966 uint8_t collectionResource)
968 if(!request || ! resource)
970 return OC_STACK_INVALID_PARAM;
973 OCStackResult result = OC_STACK_ERROR;
974 OCEntityHandlerResult ehResult = OC_EH_ERROR;
975 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
976 ResourceObserver *resObs = NULL;
978 OCEntityHandlerRequest ehRequest = {0};
980 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
981 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
982 // check the security resource
983 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
985 type = PAYLOAD_TYPE_SECURITY;
989 result = FormOCEntityHandlerRequest(&ehRequest,
990 (OCRequestHandle)request,
993 (OCResourceHandle)resource,
997 request->payloadSize,
998 request->numRcvdVendorSpecificHeaderOptions,
999 request->rcvdVendorSpecificHeaderOptions,
1000 (OCObserveAction)request->observationOption,
1003 VERIFY_SUCCESS(result, OC_STACK_OK);
1005 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1007 OIC_LOG(INFO, TAG, "No observation requested");
1008 ehFlag = OC_REQUEST_FLAG;
1010 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
1012 OIC_LOG(INFO, TAG, "Observation registration requested");
1014 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1015 request->tokenLength);
1019 OIC_LOG (INFO, TAG, "Observer with this token already present");
1020 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1021 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1022 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1024 // server requests are usually free'd when the response is sent out
1025 // for the request in ocserverrequest.c : HandleSingleResponse()
1026 // Since we are making an early return and not responding, the server request
1027 // needs to be deleted.
1028 FindAndDeleteServerRequest (request);
1032 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1033 VERIFY_SUCCESS(result, OC_STACK_OK);
1035 result = AddObserver ((const char*)(request->resourceUrl),
1036 (const char *)(request->query),
1037 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1038 resource, request->qos, request->acceptFormat,
1041 if(result == OC_STACK_OK)
1043 OIC_LOG(INFO, TAG, "Added observer successfully");
1044 request->observeResult = OC_STACK_OK;
1045 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1047 else if (result == OC_STACK_RESOURCE_ERROR)
1049 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1050 request->observeResult = OC_STACK_ERROR;
1051 ehFlag = OC_REQUEST_FLAG;
1055 // The error in observeResult for the request will be used when responding to this
1056 // request by omitting the observation option/sequence number.
1057 request->observeResult = OC_STACK_ERROR;
1058 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1059 ehFlag = OC_REQUEST_FLAG;
1060 FindAndDeleteServerRequest(request);
1065 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1066 !collectionResource)
1068 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1070 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1074 // Stack does not contain this observation request
1075 // Either token is incorrect or observation list is corrupted
1076 result = OC_STACK_ERROR;
1079 ehRequest.obsInfo.obsId = resObs->observeId;
1080 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1082 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1084 if(result == OC_STACK_OK)
1086 OIC_LOG(INFO, TAG, "Removed observer successfully");
1087 request->observeResult = OC_STACK_OK;
1088 // There should be no observe option header for de-registration response.
1089 // Set as an invalid value here so we can detect it later and remove the field in response.
1090 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1094 request->observeResult = OC_STACK_ERROR;
1095 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1096 FindAndDeleteServerRequest(request);
1102 result = OC_STACK_ERROR;
1106 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1107 if(ehResult == OC_EH_SLOW)
1109 OIC_LOG(INFO, TAG, "This is a slow resource");
1110 request->slowFlag = 1;
1112 else if(ehResult == OC_EH_ERROR)
1114 FindAndDeleteServerRequest(request);
1116 result = EntityHandlerCodeToOCStackCode(ehResult);
1118 OCPayloadDestroy(ehRequest.payload);
1122 static OCStackResult
1123 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1124 OCResource *resource)
1126 if(!request || !resource)
1128 return OC_STACK_INVALID_PARAM;
1131 OCStackResult result = OC_STACK_ERROR;
1132 OCEntityHandlerRequest ehRequest = {0};
1134 result = FormOCEntityHandlerRequest(&ehRequest,
1135 (OCRequestHandle)request,
1138 (OCResourceHandle)resource,
1140 PAYLOAD_TYPE_REPRESENTATION,
1142 request->payloadSize,
1143 request->numRcvdVendorSpecificHeaderOptions,
1144 request->rcvdVendorSpecificHeaderOptions,
1145 (OCObserveAction)request->observationOption,
1148 if(result == OC_STACK_OK)
1150 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1153 OCPayloadDestroy(ehRequest.payload);
1158 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1160 OCStackResult ret = OC_STACK_OK;
1162 switch (resHandling)
1164 case OC_RESOURCE_VIRTUAL:
1166 ret = HandleVirtualResource (request, resource);
1169 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1171 ret = HandleDefaultDeviceEntityHandler(request);
1174 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1176 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1177 return OC_STACK_ERROR;
1179 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1181 ret = HandleResourceWithEntityHandler (request, resource, 0);
1184 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1186 ret = HandleResourceWithEntityHandler (request, resource, 1);
1189 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1191 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1194 case OC_RESOURCE_NOT_SPECIFIED:
1196 ret = OC_STACK_NO_RESOURCE;
1201 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1202 return OC_STACK_ERROR;
1208 void DeletePlatformInfo()
1210 OIC_LOG(INFO, TAG, "Deleting platform info.");
1212 OICFree(savedPlatformInfo.platformID);
1213 savedPlatformInfo.platformID = NULL;
1215 OICFree(savedPlatformInfo.manufacturerName);
1216 savedPlatformInfo.manufacturerName = NULL;
1218 OICFree(savedPlatformInfo.manufacturerUrl);
1219 savedPlatformInfo.manufacturerUrl = NULL;
1221 OICFree(savedPlatformInfo.modelNumber);
1222 savedPlatformInfo.modelNumber = NULL;
1224 OICFree(savedPlatformInfo.dateOfManufacture);
1225 savedPlatformInfo.dateOfManufacture = NULL;
1227 OICFree(savedPlatformInfo.platformVersion);
1228 savedPlatformInfo.platformVersion = NULL;
1230 OICFree(savedPlatformInfo.operatingSystemVersion);
1231 savedPlatformInfo.operatingSystemVersion = NULL;
1233 OICFree(savedPlatformInfo.hardwareVersion);
1234 savedPlatformInfo.hardwareVersion = NULL;
1236 OICFree(savedPlatformInfo.firmwareVersion);
1237 savedPlatformInfo.firmwareVersion = NULL;
1239 OICFree(savedPlatformInfo.supportUrl);
1240 savedPlatformInfo.supportUrl = NULL;
1242 OICFree(savedPlatformInfo.systemTime);
1243 savedPlatformInfo.systemTime = NULL;
1246 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1248 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1249 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1250 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1251 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1252 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1253 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1254 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1255 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1256 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1257 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1258 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1260 if ((!savedPlatformInfo.platformID && info.platformID)||
1261 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1262 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1263 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1264 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1265 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1266 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1267 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1268 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1269 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1270 (!savedPlatformInfo.systemTime && info.systemTime))
1272 DeletePlatformInfo();
1273 return OC_STACK_INVALID_PARAM;
1280 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1282 DeletePlatformInfo();
1284 OCStackResult res = DeepCopyPlatFormInfo(info);
1286 if (res != OC_STACK_OK)
1288 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1292 OIC_LOG(INFO, TAG, "Platform info saved.");
1298 void DeleteDeviceInfo()
1300 OIC_LOG(INFO, TAG, "Deleting device info.");
1302 OICFree(savedDeviceInfo.deviceName);
1303 OCFreeOCStringLL(savedDeviceInfo.types);
1304 OICFree(savedDeviceInfo.specVersion);
1305 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1306 savedDeviceInfo.deviceName = NULL;
1307 savedDeviceInfo.specVersion = NULL;
1308 savedDeviceInfo.dataModelVersions = NULL;
1311 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1313 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1315 if(!savedDeviceInfo.deviceName && info.deviceName)
1318 return OC_STACK_NO_MEMORY;
1323 savedDeviceInfo.types = CloneOCStringLL(info.types);
1324 OCStringLL *type = info.types;
1328 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1336 // Append the oic.wk.d at the start of rt link parameter value.
1337 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1341 return OC_STACK_NO_MEMORY;
1343 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1347 return OC_STACK_NO_MEMORY;
1349 dest->next = savedDeviceInfo.types;
1350 savedDeviceInfo.types = dest;
1352 if(!savedDeviceInfo.types && info.types)
1355 return OC_STACK_NO_MEMORY;
1359 if (info.specVersion)
1361 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1362 if(!savedDeviceInfo.specVersion && info.specVersion)
1365 return OC_STACK_NO_MEMORY;
1370 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1371 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1374 return OC_STACK_NO_MEMORY;
1378 if (info.dataModelVersions)
1380 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1381 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1384 return OC_STACK_NO_MEMORY;
1389 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1390 if (!savedDeviceInfo.dataModelVersions)
1392 return OC_STACK_NO_MEMORY;
1394 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1395 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1398 return OC_STACK_NO_MEMORY;
1405 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1407 OCStackResult res = OC_STACK_OK;
1411 res = DeepCopyDeviceInfo(info);
1413 VERIFY_SUCCESS(res, OC_STACK_OK);
1415 if (OCGetServerInstanceIDString() == NULL)
1417 OIC_LOG(INFO, TAG, "Device ID generation failed");
1418 res = OC_STACK_ERROR;
1422 OIC_LOG(INFO, TAG, "Device initialized successfully.");