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_FORBIDDEN_REQ;
496 case OC_EH_INTERNAL_SERVER_ERROR:
497 result = OC_STACK_INTERNAL_SERVER_ERROR;
499 case OC_EH_RESOURCE_CREATED:
500 result = OC_STACK_RESOURCE_CREATED;
502 case OC_EH_RESOURCE_DELETED:
503 result = OC_STACK_RESOURCE_DELETED;
506 result = OC_STACK_RESOURCE_CHANGED;
508 case OC_EH_RESOURCE_NOT_FOUND:
509 result = OC_STACK_NO_RESOURCE;
512 result = OC_STACK_ERROR;
518 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
525 // Null or empty is analogous to no filter.
526 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
531 OCResourceType *resourceTypePtr = resource->rsrcType;
533 while (resourceTypePtr)
535 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
539 resourceTypePtr = resourceTypePtr->next;
542 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
546 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
553 // Null or empty is analogous to no filter.
554 if (interfaceFilter == NULL || *interfaceFilter == 0)
559 OCResourceInterface *interfacePtr = resource->rsrcInterface;
563 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
564 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
565 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
569 interfacePtr = interfacePtr->next;
572 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
577 * If the filters are null, they will be assumed to NOT be present
578 * and the resource will not be matched against them.
579 * Function will return true if all non null AND non empty filters passed in find a match.
581 static bool includeThisResourceInResponse(OCResource *resource,
582 char *interfaceFilter,
583 char *resourceTypeFilter)
587 OIC_LOG(ERROR, TAG, "Invalid resource");
591 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
594 * At least one valid filter should be available to
595 * include the resource in discovery response
597 if (!(resourceTypeFilter && *resourceTypeFilter))
599 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
600 resource", resource->uri);
604 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
605 !(resource->resourceProperties & OC_DISCOVERABLE))
607 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
611 return resourceMatchesIFFilter(resource, interfaceFilter) &&
612 resourceMatchesRTFilter(resource, resourceTypeFilter);
616 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
617 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
619 OCEntityHandlerResponse response = {0};
621 response.ehResult = ehResult;
622 response.payload = discoveryPayload;
623 response.persistentBufferFlag = 0;
624 response.requestHandle = (OCRequestHandle) request;
625 response.resourceHandle = (OCResourceHandle) resource;
627 return OCDoResponse(&response);
630 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
632 if (!request || !resource)
634 return OC_STACK_INVALID_PARAM;
637 OCStackResult discoveryResult = OC_STACK_ERROR;
638 OCPayload* payload = NULL;
640 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
642 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
644 // Step 1: Generate the response to discovery request
645 if (virtualUriInRequest == OC_WELL_KNOWN_URI
647 || virtualUriInRequest == OC_MQ_BROKER_URI
651 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
653 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
654 return OC_STACK_UNAUTHORIZED_REQ;
657 char *interfaceQuery = NULL;
658 char *resourceTypeQuery = NULL;
660 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
661 &interfaceQuery, &resourceTypeQuery);
662 bool interfaceQueryAllocated = false;
663 if (!interfaceQuery && !resourceTypeQuery)
665 interfaceQueryAllocated = true;
666 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
669 if (discoveryResult == OC_STACK_OK)
671 payload = (OCPayload *)OCDiscoveryPayloadCreate();
675 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
676 bool foundResourceAtRD = false;
678 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
680 OCResourceProperty prop = OC_DISCOVERABLE;
682 if (OC_MQ_BROKER_URI == virtualUriInRequest)
688 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
690 foundResourceAtRD = false;
692 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
694 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
696 foundResourceAtRD = true;
697 discoveryResult = OC_STACK_OK;
701 if (!foundResourceAtRD && (resource->resourceProperties & prop))
703 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
709 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
711 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
712 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
713 if (savedDeviceInfo.deviceName)
715 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
716 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
718 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
719 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
720 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
721 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
722 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
723 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
724 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
726 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
729 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
731 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
733 foundResourceAtRD = true;
734 discoveryResult = OC_STACK_OK;
738 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
740 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
743 // Set discoveryResult appropriately if no 'valid' resources are available
744 if (discPayload->resources == NULL && !foundResourceAtRD)
746 discoveryResult = OC_STACK_NO_RESOURCE;
749 if (discoveryResult == OC_STACK_OK && foundResourceAtRD == false)
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);
763 discoveryResult = OC_STACK_NO_MEMORY;
769 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
771 if (interfaceQueryAllocated)
773 OICFree(interfaceQuery);
776 else if (virtualUriInRequest == OC_DEVICE_URI)
778 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
780 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
781 return OC_STACK_UNAUTHORIZED_REQ;
784 const char* deviceId = OCGetServerInstanceIDString();
787 discoveryResult = OC_STACK_ERROR;
791 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
792 if (!dataModelVersions)
794 discoveryResult = OC_STACK_NO_MEMORY;
798 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
799 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
802 discoveryResult = OC_STACK_NO_MEMORY;
806 discoveryResult = OC_STACK_OK;
808 OICFree(dataModelVersions);
812 else if (virtualUriInRequest == OC_PLATFORM_URI)
814 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
816 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
817 return OC_STACK_UNAUTHORIZED_REQ;
820 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
823 discoveryResult = OC_STACK_NO_MEMORY;
827 discoveryResult = OC_STACK_OK;
830 #ifdef ROUTING_GATEWAY
831 else if (OC_GATEWAY_URI == virtualUriInRequest)
833 // Received request for a gateway
834 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
835 discoveryResult = RMHandleGatewayRequest(request, resource);
840 else if (OC_KEEPALIVE_RESOURCE_URI == virtualUriInRequest)
842 // Received request for a keepalive
843 OIC_LOG(INFO, TAG, "Request is for KeepAlive Request");
844 discoveryResult = HandleKeepAliveRequest(request, resource);
848 * Step 2: Send the discovery response
850 * Iotivity should respond to discovery requests in below manner:
851 * 1)If query filter matching fails and discovery request is multicast,
852 * it should NOT send any response.
853 * 2)If query filter matching fails and discovery request is unicast,
854 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
855 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
856 * request is multicast, it should NOT send any response.
857 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
858 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
862 if ((virtualUriInRequest == OC_PRESENCE) &&
863 (resource->resourceProperties & OC_ACTIVE))
865 // Need to send ACK when the request is CON.
866 if (request->qos == OC_HIGH_QOS)
868 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
869 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
870 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
871 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
873 FindAndDeleteServerRequest(request);
875 // Presence uses observer notification api to respond via SendPresenceNotification.
876 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
881 // Gateway uses the RMHandleGatewayRequest to respond to the request.
882 if (OC_GATEWAY_URI != virtualUriInRequest)
886 // KeepAlive uses the HandleKeepAliveRequest to respond to the request.
887 if (OC_KEEPALIVE_RESOURCE_URI != virtualUriInRequest)
890 if(discoveryResult == OC_STACK_OK)
892 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
894 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
895 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
896 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
898 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
899 discoveryResult, virtualUriInRequest);
900 SendNonPersistantDiscoveryResponse(request, resource, NULL,
901 (discoveryResult == OC_STACK_NO_RESOURCE) ?
902 OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
906 // Ignoring the discovery request as per RFC 7252, Section #8.2
907 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send.");
908 // the request should be removed.
909 // since it never remove and causes a big memory waste.
910 FindAndDeleteServerRequest(request);
915 OCPayloadDestroy(payload);
921 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
925 return OC_STACK_INVALID_PARAM;
928 OCStackResult result = OC_STACK_OK;
929 OCEntityHandlerResult ehResult = OC_EH_ERROR;
930 OCEntityHandlerRequest ehRequest = {0};
932 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
933 result = FormOCEntityHandlerRequest(&ehRequest,
934 (OCRequestHandle) request,
937 (OCResourceHandle) NULL, request->query,
938 PAYLOAD_TYPE_REPRESENTATION,
940 request->payloadSize,
941 request->numRcvdVendorSpecificHeaderOptions,
942 request->rcvdVendorSpecificHeaderOptions,
943 (OCObserveAction)request->observationOption,
946 VERIFY_SUCCESS(result, OC_STACK_OK);
948 // At this point we know for sure that defaultDeviceHandler exists
949 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
950 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
951 if(ehResult == OC_EH_SLOW)
953 OIC_LOG(INFO, TAG, "This is a slow resource");
954 request->slowFlag = 1;
956 else if(ehResult == OC_EH_ERROR)
958 FindAndDeleteServerRequest(request);
960 result = EntityHandlerCodeToOCStackCode(ehResult);
962 OCPayloadDestroy(ehRequest.payload);
967 HandleResourceWithEntityHandler (OCServerRequest *request,
968 OCResource *resource,
969 uint8_t collectionResource)
971 if(!request || ! resource)
973 return OC_STACK_INVALID_PARAM;
976 OCStackResult result = OC_STACK_ERROR;
977 OCEntityHandlerResult ehResult = OC_EH_ERROR;
978 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
979 ResourceObserver *resObs = NULL;
981 OCEntityHandlerRequest ehRequest = {0};
983 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
984 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
985 // check the security resource
986 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
988 type = PAYLOAD_TYPE_SECURITY;
992 result = FormOCEntityHandlerRequest(&ehRequest,
993 (OCRequestHandle)request,
996 (OCResourceHandle)resource,
1000 request->payloadSize,
1001 request->numRcvdVendorSpecificHeaderOptions,
1002 request->rcvdVendorSpecificHeaderOptions,
1003 (OCObserveAction)request->observationOption,
1006 VERIFY_SUCCESS(result, OC_STACK_OK);
1008 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1010 OIC_LOG(INFO, TAG, "No observation requested");
1011 ehFlag = OC_REQUEST_FLAG;
1013 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER)
1015 OIC_LOG(INFO, TAG, "Observation registration requested");
1017 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1018 request->tokenLength);
1022 OIC_LOG (INFO, TAG, "Observer with this token already present");
1023 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1024 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1025 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1027 // server requests are usually free'd when the response is sent out
1028 // for the request in ocserverrequest.c : HandleSingleResponse()
1029 // Since we are making an early return and not responding, the server request
1030 // needs to be deleted.
1031 FindAndDeleteServerRequest (request);
1035 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1036 VERIFY_SUCCESS(result, OC_STACK_OK);
1038 result = AddObserver ((const char*)(request->resourceUrl),
1039 (const char *)(request->query),
1040 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1041 resource, request->qos, request->acceptFormat,
1044 if(result == OC_STACK_OK)
1046 OIC_LOG(INFO, TAG, "Added observer successfully");
1047 request->observeResult = OC_STACK_OK;
1048 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1050 else if (result == OC_STACK_RESOURCE_ERROR)
1052 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1053 request->observeResult = OC_STACK_ERROR;
1054 ehFlag = OC_REQUEST_FLAG;
1058 // The error in observeResult for the request will be used when responding to this
1059 // request by omitting the observation option/sequence number.
1060 request->observeResult = OC_STACK_ERROR;
1061 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1062 ehFlag = OC_REQUEST_FLAG;
1063 FindAndDeleteServerRequest(request);
1068 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER)
1070 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1072 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1076 // Stack does not contain this observation request
1077 // Either token is incorrect or observation list is corrupted
1078 result = OC_STACK_ERROR;
1081 ehRequest.obsInfo.obsId = resObs->observeId;
1082 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1084 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1086 if(result == OC_STACK_OK)
1088 OIC_LOG(INFO, TAG, "Removed observer successfully");
1089 request->observeResult = OC_STACK_OK;
1090 // There should be no observe option header for de-registration response.
1091 // Set as an invalid value here so we can detect it later and remove the field in response.
1092 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1096 request->observeResult = OC_STACK_ERROR;
1097 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1098 FindAndDeleteServerRequest(request);
1104 result = OC_STACK_ERROR;
1108 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1109 if(ehResult == OC_EH_SLOW)
1111 OIC_LOG(INFO, TAG, "This is a slow resource");
1112 request->slowFlag = 1;
1114 else if(ehResult == OC_EH_ERROR)
1116 FindAndDeleteServerRequest(request);
1118 result = EntityHandlerCodeToOCStackCode(ehResult);
1120 OCPayloadDestroy(ehRequest.payload);
1124 static OCStackResult
1125 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1126 OCResource *resource)
1128 if(!request || !resource)
1130 return OC_STACK_INVALID_PARAM;
1133 OCStackResult result = OC_STACK_ERROR;
1134 OCEntityHandlerRequest ehRequest = {0};
1136 result = FormOCEntityHandlerRequest(&ehRequest,
1137 (OCRequestHandle)request,
1140 (OCResourceHandle)resource,
1142 PAYLOAD_TYPE_REPRESENTATION,
1144 request->payloadSize,
1145 request->numRcvdVendorSpecificHeaderOptions,
1146 request->rcvdVendorSpecificHeaderOptions,
1147 (OCObserveAction)request->observationOption,
1150 if(result == OC_STACK_OK)
1152 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1155 OCPayloadDestroy(ehRequest.payload);
1160 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1162 OCStackResult ret = OC_STACK_OK;
1164 switch (resHandling)
1166 case OC_RESOURCE_VIRTUAL:
1168 ret = HandleVirtualResource (request, resource);
1171 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1173 ret = HandleDefaultDeviceEntityHandler(request);
1176 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1178 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1179 return OC_STACK_ERROR;
1181 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1183 ret = HandleResourceWithEntityHandler (request, resource, 0);
1186 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1188 ret = HandleResourceWithEntityHandler (request, resource, 1);
1191 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1193 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1196 case OC_RESOURCE_NOT_SPECIFIED:
1198 ret = OC_STACK_NO_RESOURCE;
1203 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1204 return OC_STACK_ERROR;
1210 void DeletePlatformInfo()
1212 OIC_LOG(INFO, TAG, "Deleting platform info.");
1214 OICFree(savedPlatformInfo.platformID);
1215 savedPlatformInfo.platformID = NULL;
1217 OICFree(savedPlatformInfo.manufacturerName);
1218 savedPlatformInfo.manufacturerName = NULL;
1220 OICFree(savedPlatformInfo.manufacturerUrl);
1221 savedPlatformInfo.manufacturerUrl = NULL;
1223 OICFree(savedPlatformInfo.modelNumber);
1224 savedPlatformInfo.modelNumber = NULL;
1226 OICFree(savedPlatformInfo.dateOfManufacture);
1227 savedPlatformInfo.dateOfManufacture = NULL;
1229 OICFree(savedPlatformInfo.platformVersion);
1230 savedPlatformInfo.platformVersion = NULL;
1232 OICFree(savedPlatformInfo.operatingSystemVersion);
1233 savedPlatformInfo.operatingSystemVersion = NULL;
1235 OICFree(savedPlatformInfo.hardwareVersion);
1236 savedPlatformInfo.hardwareVersion = NULL;
1238 OICFree(savedPlatformInfo.firmwareVersion);
1239 savedPlatformInfo.firmwareVersion = NULL;
1241 OICFree(savedPlatformInfo.supportUrl);
1242 savedPlatformInfo.supportUrl = NULL;
1244 OICFree(savedPlatformInfo.systemTime);
1245 savedPlatformInfo.systemTime = NULL;
1248 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1250 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1251 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1252 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1253 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1254 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1255 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1256 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1257 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1258 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1259 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1260 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1262 if ((!savedPlatformInfo.platformID && info.platformID)||
1263 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1264 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1265 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1266 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1267 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1268 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1269 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1270 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1271 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1272 (!savedPlatformInfo.systemTime && info.systemTime))
1274 DeletePlatformInfo();
1275 return OC_STACK_INVALID_PARAM;
1282 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1284 DeletePlatformInfo();
1286 OCStackResult res = DeepCopyPlatFormInfo(info);
1288 if (res != OC_STACK_OK)
1290 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1294 OIC_LOG(INFO, TAG, "Platform info saved.");
1300 void DeleteDeviceInfo()
1302 OIC_LOG(INFO, TAG, "Deleting device info.");
1304 OICFree(savedDeviceInfo.deviceName);
1305 OCFreeOCStringLL(savedDeviceInfo.types);
1306 OICFree(savedDeviceInfo.specVersion);
1307 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1308 savedDeviceInfo.deviceName = NULL;
1309 savedDeviceInfo.specVersion = NULL;
1310 savedDeviceInfo.dataModelVersions = NULL;
1313 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1315 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1317 if(!savedDeviceInfo.deviceName && info.deviceName)
1320 return OC_STACK_NO_MEMORY;
1325 savedDeviceInfo.types = CloneOCStringLL(info.types);
1326 OCStringLL *type = info.types;
1330 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1338 // Append the oic.wk.d at the start of rt link parameter value.
1339 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1343 return OC_STACK_NO_MEMORY;
1345 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1349 return OC_STACK_NO_MEMORY;
1351 dest->next = savedDeviceInfo.types;
1352 savedDeviceInfo.types = dest;
1354 if(!savedDeviceInfo.types && info.types)
1357 return OC_STACK_NO_MEMORY;
1361 if (info.specVersion)
1363 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1364 if(!savedDeviceInfo.specVersion && info.specVersion)
1367 return OC_STACK_NO_MEMORY;
1372 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1373 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1376 return OC_STACK_NO_MEMORY;
1380 if (info.dataModelVersions)
1382 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1383 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1386 return OC_STACK_NO_MEMORY;
1391 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1392 if (!savedDeviceInfo.dataModelVersions)
1394 return OC_STACK_NO_MEMORY;
1396 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1397 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1400 return OC_STACK_NO_MEMORY;
1407 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1409 OCStackResult res = OC_STACK_OK;
1413 res = DeepCopyDeviceInfo(info);
1415 VERIFY_SUCCESS(res, OC_STACK_OK);
1417 if (OCGetServerInstanceIDString() == NULL)
1419 OIC_LOG(INFO, TAG, "Device ID generation failed");
1420 res = OC_STACK_ERROR;
1424 OIC_LOG(INFO, TAG, "Device initialized successfully.");