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 #define TAG "OIC_RI_RESOURCE"
61 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
62 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
64 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
65 TAG, #arg " is NULL"); return (retVal); } }
67 #include "platform_features.h"
69 extern OCResource *headResource;
70 static OCPlatformInfo savedPlatformInfo = {0};
71 static OCDeviceInfo savedDeviceInfo = {0};
74 * Prepares a Payload for response.
76 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
77 OCDiscoveryPayload* payload,
81 //-----------------------------------------------------------------------------
82 // Default resource entity handler function
83 //-----------------------------------------------------------------------------
84 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
85 OCEntityHandlerRequest * request, void* callbackParam)
87 //TODO ("Implement me!!!!");
88 // TODO: remove silence unused param warnings
92 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
95 /* This method will retrieve the port at which the secure resource is hosted */
96 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
100 if (endpoint->adapter == OC_ADAPTER_IP)
102 if (endpoint->flags & OC_IP_USE_V6)
104 p = caglobals.ip.u6s.port;
106 else if (endpoint->flags & OC_IP_USE_V4)
108 p = caglobals.ip.u4s.port;
117 /* This method will retrieve the tcp port */
118 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
122 if (endpoint->adapter == OC_ADAPTER_IP)
124 if (endpoint->flags & OC_IP_USE_V4)
126 p = caglobals.tcp.ipv4.port;
128 else if (endpoint->flags & OC_IP_USE_V6)
130 p = caglobals.tcp.ipv6.port;
140 * Function will extract 0, 1 or 2 filters from query.
141 * More than 2 filters or unsupported filters will result in error.
142 * If both filters are of the same supported type, the 2nd one will be picked.
143 * Resource and device filters in the SAME query are NOT validated
144 * and resources will likely not clear filters.
146 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
151 char *restOfQuery = NULL;
152 int numKeyValuePairsParsed = 0;
157 OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
159 if (strnlen(query, MAX_QUERY_LENGTH) >= MAX_QUERY_LENGTH)
161 OIC_LOG(ERROR, TAG, "Query exceeds maximum length.");
162 return OC_STACK_INVALID_QUERY;
165 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
169 if (numKeyValuePairsParsed >= 2)
171 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
172 return OC_STACK_INVALID_QUERY;
175 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
179 return OC_STACK_INVALID_QUERY;
181 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
183 *filterOne = value; // if
185 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
187 *filterTwo = value; // rt
191 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
192 return OC_STACK_INVALID_QUERY;
194 ++numKeyValuePairsParsed;
196 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
199 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
203 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
205 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
207 return OC_WELL_KNOWN_URI;
209 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
211 return OC_DEVICE_URI;
213 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
215 return OC_PLATFORM_URI;
217 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
219 return OC_RESOURCE_TYPES_URI;
221 #ifdef ROUTING_GATEWAY
222 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
224 return OC_GATEWAY_URI;
228 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
232 #endif //WITH_PRESENCE
235 else if (0 == strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_MQ_URI))
237 return OC_MQ_BROKER_URI;
240 return OC_UNKNOWN_URI;
243 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
244 char **filterOne, char **filterTwo)
246 if(!filterOne || !filterTwo)
248 return OC_STACK_INVALID_PARAM;
255 if (uri == OC_PRESENCE)
257 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
258 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
263 OCStackResult result = OC_STACK_OK;
267 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
273 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
274 OCRepPayload** payload)
276 OCRepPayload *tempPayload = OCRepPayloadCreate();
280 OCRepPayloadDestroy(tempPayload);
281 return OC_STACK_INVALID_PARAM;
286 return OC_STACK_NO_MEMORY;
289 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
291 OCResourceType *resType = resourcePtr->rsrcType;
294 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
295 resType = resType->next;
298 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
301 OCRepPayloadAddInterface(tempPayload, resInterface->name);
302 resInterface = resInterface->next;
305 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
308 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
309 resAttrib->attrValue);
310 resAttrib = resAttrib->next;
315 *payload = tempPayload;
319 OCRepPayloadAppend(*payload, tempPayload);
325 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
326 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
328 if (!resourcePtr || !payload)
330 return OC_STACK_INVALID_PARAM;
332 uint16_t securePort = 0;
333 if (resourcePtr->resourceProperties & OC_SECURE)
335 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
343 securePort = devAddr->port;
347 uint16_t tcpPort = 0;
348 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
352 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
354 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
360 uint8_t IsCollectionResource (OCResource *resource)
367 if(resource->rsrcChildResourcesHead != NULL)
375 OCResource *FindResourceByUri(const char* resourceUri)
382 OCResource * pointer = headResource;
385 if (strcmp(resourceUri, pointer->uri) == 0)
389 pointer = pointer->next;
391 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
396 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
397 ResourceHandling *handling,
398 OCResource **resource)
400 if(!request || !handling || !resource)
402 return OC_STACK_INVALID_PARAM;
405 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
407 // Check if virtual resource
408 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
410 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
411 *handling = OC_RESOURCE_VIRTUAL;
412 *resource = headResource;
415 if (strlen((const char*)(request->resourceUrl)) == 0)
417 // Resource URL not specified
418 *handling = OC_RESOURCE_NOT_SPECIFIED;
419 return OC_STACK_NO_RESOURCE;
423 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
424 *resource = resourcePtr;
427 if(defaultDeviceHandler)
429 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
433 // Resource does not exist
434 // and default device handler does not exist
435 *handling = OC_RESOURCE_NOT_SPECIFIED;
436 return OC_STACK_NO_RESOURCE;
439 if (IsCollectionResource (resourcePtr))
441 // Collection resource
442 if (resourcePtr->entityHandler != defaultResourceEHandler)
444 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
449 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
455 // Resource not a collection
456 if (resourcePtr->entityHandler != defaultResourceEHandler)
458 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
463 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
470 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
472 OCStackResult result;
479 result = OC_STACK_OK;
482 result = OC_STACK_SLOW_RESOURCE;
485 result = OC_STACK_ERROR;
487 case OC_EH_FORBIDDEN:
488 result = OC_STACK_RESOURCE_ERROR;
490 case OC_EH_RESOURCE_CREATED:
491 result = OC_STACK_RESOURCE_CREATED;
493 case OC_EH_RESOURCE_DELETED:
494 result = OC_STACK_RESOURCE_DELETED;
497 result = OC_STACK_RESOURCE_CHANGED;
499 case OC_EH_RESOURCE_NOT_FOUND:
500 result = OC_STACK_NO_RESOURCE;
503 result = OC_STACK_ERROR;
509 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
516 // Null or empty is analogous to no filter.
517 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
522 OCResourceType *resourceTypePtr = resource->rsrcType;
524 while (resourceTypePtr)
526 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
530 resourceTypePtr = resourceTypePtr->next;
533 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
537 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
544 // Null or empty is analogous to no filter.
545 if (interfaceFilter == NULL || *interfaceFilter == 0)
550 OCResourceInterface *interfacePtr = resource->rsrcInterface;
554 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
555 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
556 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
560 interfacePtr = interfacePtr->next;
563 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
568 * If the filters are null, they will be assumed to NOT be present
569 * and the resource will not be matched against them.
570 * Function will return true if all non null AND non empty filters passed in find a match.
572 static bool includeThisResourceInResponse(OCResource *resource,
573 char *interfaceFilter,
574 char *resourceTypeFilter)
578 OIC_LOG(ERROR, TAG, "Invalid resource");
582 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
585 * At least one valid filter should be available to
586 * include the resource in discovery response
588 if (!(resourceTypeFilter && *resourceTypeFilter))
590 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
591 resource", resource->uri);
595 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
596 !(resource->resourceProperties & OC_DISCOVERABLE))
598 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
602 return resourceMatchesIFFilter(resource, interfaceFilter) &&
603 resourceMatchesRTFilter(resource, resourceTypeFilter);
607 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
608 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
610 OCEntityHandlerResponse response = {0};
612 response.ehResult = ehResult;
613 response.payload = discoveryPayload;
614 response.persistentBufferFlag = 0;
615 response.requestHandle = (OCRequestHandle) request;
616 response.resourceHandle = (OCResourceHandle) resource;
618 return OCDoResponse(&response);
621 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
623 if (!request || !resource)
625 return OC_STACK_INVALID_PARAM;
628 OCStackResult discoveryResult = OC_STACK_ERROR;
629 OCPayload* payload = NULL;
631 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
633 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
635 // Step 1: Generate the response to discovery request
636 if (virtualUriInRequest == OC_WELL_KNOWN_URI
638 || virtualUriInRequest == OC_MQ_BROKER_URI
642 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
644 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
645 return OC_STACK_UNAUTHORIZED_REQ;
648 char *interfaceQuery = NULL;
649 char *resourceTypeQuery = NULL;
651 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
652 &interfaceQuery, &resourceTypeQuery);
653 bool interfaceQueryAllocated = false;
654 if (!interfaceQuery && !resourceTypeQuery)
656 interfaceQueryAllocated = true;
657 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
660 if (discoveryResult == OC_STACK_OK)
662 payload = (OCPayload *)OCDiscoveryPayloadCreate();
666 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
667 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
668 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
670 const char* uid = OCGetServerInstanceIDString();
673 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
676 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
678 OCResourceProperty prop = OC_DISCOVERABLE;
680 if (OC_MQ_BROKER_URI == virtualUriInRequest)
686 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
690 if (resource->resourceProperties & prop)
697 discoveryResult = BuildVirtualResourceResponse(resource,
698 discPayload, &request->devAddr, false);
704 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
706 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
707 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
708 if (savedDeviceInfo.deviceName)
710 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
711 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
713 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
714 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
715 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
716 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
717 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
718 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
719 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
721 bool foundResourceAtRD = false;
722 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
724 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
726 discoveryResult = BuildVirtualResourceResponse(resource,
727 discPayload, &request->devAddr, false);
730 // Set discoveryResult appropriately if no 'valid' resources are available
731 if (discPayload->resources == NULL && !foundResourceAtRD)
733 discoveryResult = OC_STACK_NO_RESOURCE;
739 discoveryResult = OC_STACK_NO_MEMORY;
744 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
746 if (interfaceQueryAllocated)
748 OICFree(interfaceQuery);
751 else if (virtualUriInRequest == OC_DEVICE_URI)
753 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
755 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
756 return OC_STACK_UNAUTHORIZED_REQ;
759 const char* deviceId = OCGetServerInstanceIDString();
762 discoveryResult = OC_STACK_ERROR;
766 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
767 if (!dataModelVersions)
769 discoveryResult = OC_STACK_NO_MEMORY;
773 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
774 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
777 discoveryResult = OC_STACK_NO_MEMORY;
781 discoveryResult = OC_STACK_OK;
783 OICFree(dataModelVersions);
787 else if (virtualUriInRequest == OC_PLATFORM_URI)
789 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
791 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
792 return OC_STACK_UNAUTHORIZED_REQ;
795 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
798 discoveryResult = OC_STACK_NO_MEMORY;
802 discoveryResult = OC_STACK_OK;
805 #ifdef ROUTING_GATEWAY
806 else if (OC_GATEWAY_URI == virtualUriInRequest)
808 // Received request for a gateway
809 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
810 discoveryResult = RMHandleGatewayRequest(request, resource);
816 * Step 2: Send the discovery response
818 * Iotivity should respond to discovery requests in below manner:
819 * 1)If query filter matching fails and discovery request is multicast,
820 * it should NOT send any response.
821 * 2)If query filter matching fails and discovery request is unicast,
822 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
823 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
824 * request is multicast, it should NOT send any response.
825 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
826 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
830 if ((virtualUriInRequest == OC_PRESENCE) &&
831 (resource->resourceProperties & OC_ACTIVE))
833 // Need to send ACK when the request is CON.
834 if (request->qos == OC_HIGH_QOS)
836 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
837 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
838 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
839 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
842 // Presence uses observer notification api to respond via SendPresenceNotification.
843 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
847 #ifdef ROUTING_GATEWAY
848 // Gateway uses the RMHandleGatewayRequest to respond to the request.
849 if (OC_GATEWAY_URI != virtualUriInRequest)
852 if(discoveryResult == OC_STACK_OK)
854 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
856 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
857 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
858 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
860 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
861 discoveryResult, virtualUriInRequest);
862 SendNonPersistantDiscoveryResponse(request, resource, NULL,
863 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
867 // Ignoring the discovery request as per RFC 7252, Section #8.2
868 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
872 OCPayloadDestroy(payload);
878 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
882 return OC_STACK_INVALID_PARAM;
885 OCStackResult result = OC_STACK_OK;
886 OCEntityHandlerResult ehResult = OC_EH_ERROR;
887 OCEntityHandlerRequest ehRequest = {0};
889 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
890 result = FormOCEntityHandlerRequest(&ehRequest,
891 (OCRequestHandle) request,
894 (OCResourceHandle) NULL, request->query,
895 PAYLOAD_TYPE_REPRESENTATION,
897 request->payloadSize,
898 request->numRcvdVendorSpecificHeaderOptions,
899 request->rcvdVendorSpecificHeaderOptions,
900 (OCObserveAction)request->observationOption,
903 VERIFY_SUCCESS(result, OC_STACK_OK);
905 // At this point we know for sure that defaultDeviceHandler exists
906 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
907 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
908 if(ehResult == OC_EH_SLOW)
910 OIC_LOG(INFO, TAG, "This is a slow resource");
911 request->slowFlag = 1;
913 else if(ehResult == OC_EH_ERROR)
915 FindAndDeleteServerRequest(request);
917 result = EntityHandlerCodeToOCStackCode(ehResult);
919 OCPayloadDestroy(ehRequest.payload);
924 HandleResourceWithEntityHandler (OCServerRequest *request,
925 OCResource *resource,
926 uint8_t collectionResource)
928 if(!request || ! resource)
930 return OC_STACK_INVALID_PARAM;
933 OCStackResult result = OC_STACK_ERROR;
934 OCEntityHandlerResult ehResult = OC_EH_ERROR;
935 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
936 ResourceObserver *resObs = NULL;
938 OCEntityHandlerRequest ehRequest = {0};
940 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
941 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
942 // check the security resource
943 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
945 type = PAYLOAD_TYPE_SECURITY;
949 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
951 type = PAYLOAD_TYPE_RD;
954 result = FormOCEntityHandlerRequest(&ehRequest,
955 (OCRequestHandle)request,
958 (OCResourceHandle)resource,
962 request->payloadSize,
963 request->numRcvdVendorSpecificHeaderOptions,
964 request->rcvdVendorSpecificHeaderOptions,
965 (OCObserveAction)request->observationOption,
968 VERIFY_SUCCESS(result, OC_STACK_OK);
970 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
972 OIC_LOG(INFO, TAG, "No observation requested");
973 ehFlag = OC_REQUEST_FLAG;
975 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
977 OIC_LOG(INFO, TAG, "Observation registration requested");
979 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
980 request->tokenLength);
984 OIC_LOG (INFO, TAG, "Observer with this token already present");
985 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
986 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
987 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
989 // server requests are usually free'd when the response is sent out
990 // for the request in ocserverrequest.c : HandleSingleResponse()
991 // Since we are making an early return and not responding, the server request
992 // needs to be deleted.
993 FindAndDeleteServerRequest (request);
997 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
998 VERIFY_SUCCESS(result, OC_STACK_OK);
1000 result = AddObserver ((const char*)(request->resourceUrl),
1001 (const char *)(request->query),
1002 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1003 resource, request->qos, request->acceptFormat,
1006 if(result == OC_STACK_OK)
1008 OIC_LOG(INFO, TAG, "Added observer successfully");
1009 request->observeResult = OC_STACK_OK;
1010 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1012 else if (result == OC_STACK_RESOURCE_ERROR)
1014 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1015 request->observeResult = OC_STACK_ERROR;
1016 ehFlag = OC_REQUEST_FLAG;
1020 // The error in observeResult for the request will be used when responding to this
1021 // request by omitting the observation option/sequence number.
1022 request->observeResult = OC_STACK_ERROR;
1023 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1024 ehFlag = OC_REQUEST_FLAG;
1025 FindAndDeleteServerRequest(request);
1030 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1031 !collectionResource)
1033 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1035 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1039 // Stack does not contain this observation request
1040 // Either token is incorrect or observation list is corrupted
1041 result = OC_STACK_ERROR;
1044 ehRequest.obsInfo.obsId = resObs->observeId;
1045 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1047 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1049 if(result == OC_STACK_OK)
1051 OIC_LOG(INFO, TAG, "Removed observer successfully");
1052 request->observeResult = OC_STACK_OK;
1053 // There should be no observe option header for de-registration response.
1054 // Set as an invalid value here so we can detect it later and remove the field in response.
1055 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1059 request->observeResult = OC_STACK_ERROR;
1060 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1061 FindAndDeleteServerRequest(request);
1067 result = OC_STACK_ERROR;
1071 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1072 if(ehResult == OC_EH_SLOW)
1074 OIC_LOG(INFO, TAG, "This is a slow resource");
1075 request->slowFlag = 1;
1077 else if(ehResult == OC_EH_ERROR)
1079 FindAndDeleteServerRequest(request);
1081 result = EntityHandlerCodeToOCStackCode(ehResult);
1083 OCPayloadDestroy(ehRequest.payload);
1087 static OCStackResult
1088 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1089 OCResource *resource)
1091 if(!request || !resource)
1093 return OC_STACK_INVALID_PARAM;
1096 OCStackResult result = OC_STACK_ERROR;
1097 OCEntityHandlerRequest ehRequest = {0};
1099 result = FormOCEntityHandlerRequest(&ehRequest,
1100 (OCRequestHandle)request,
1103 (OCResourceHandle)resource,
1105 PAYLOAD_TYPE_REPRESENTATION,
1107 request->payloadSize,
1108 request->numRcvdVendorSpecificHeaderOptions,
1109 request->rcvdVendorSpecificHeaderOptions,
1110 (OCObserveAction)request->observationOption,
1113 if(result == OC_STACK_OK)
1115 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1118 OCPayloadDestroy(ehRequest.payload);
1123 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1125 OCStackResult ret = OC_STACK_OK;
1127 switch (resHandling)
1129 case OC_RESOURCE_VIRTUAL:
1131 ret = HandleVirtualResource (request, resource);
1134 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1136 ret = HandleDefaultDeviceEntityHandler(request);
1139 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1141 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1142 return OC_STACK_ERROR;
1144 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1146 ret = HandleResourceWithEntityHandler (request, resource, 0);
1149 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1151 ret = HandleResourceWithEntityHandler (request, resource, 1);
1154 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1156 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1159 case OC_RESOURCE_NOT_SPECIFIED:
1161 ret = OC_STACK_NO_RESOURCE;
1166 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1167 return OC_STACK_ERROR;
1173 void DeletePlatformInfo()
1175 OIC_LOG(INFO, TAG, "Deleting platform info.");
1177 OICFree(savedPlatformInfo.platformID);
1178 savedPlatformInfo.platformID = NULL;
1180 OICFree(savedPlatformInfo.manufacturerName);
1181 savedPlatformInfo.manufacturerName = NULL;
1183 OICFree(savedPlatformInfo.manufacturerUrl);
1184 savedPlatformInfo.manufacturerUrl = NULL;
1186 OICFree(savedPlatformInfo.modelNumber);
1187 savedPlatformInfo.modelNumber = NULL;
1189 OICFree(savedPlatformInfo.dateOfManufacture);
1190 savedPlatformInfo.dateOfManufacture = NULL;
1192 OICFree(savedPlatformInfo.platformVersion);
1193 savedPlatformInfo.platformVersion = NULL;
1195 OICFree(savedPlatformInfo.operatingSystemVersion);
1196 savedPlatformInfo.operatingSystemVersion = NULL;
1198 OICFree(savedPlatformInfo.hardwareVersion);
1199 savedPlatformInfo.hardwareVersion = NULL;
1201 OICFree(savedPlatformInfo.firmwareVersion);
1202 savedPlatformInfo.firmwareVersion = NULL;
1204 OICFree(savedPlatformInfo.supportUrl);
1205 savedPlatformInfo.supportUrl = NULL;
1207 OICFree(savedPlatformInfo.systemTime);
1208 savedPlatformInfo.systemTime = NULL;
1211 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1213 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1214 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1215 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1216 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1217 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1218 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1219 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1220 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1221 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1222 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1223 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1225 if ((!savedPlatformInfo.platformID && info.platformID)||
1226 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1227 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1228 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1229 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1230 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1231 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1232 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1233 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1234 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1235 (!savedPlatformInfo.systemTime && info.systemTime))
1237 DeletePlatformInfo();
1238 return OC_STACK_INVALID_PARAM;
1245 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1247 DeletePlatformInfo();
1249 OCStackResult res = DeepCopyPlatFormInfo(info);
1251 if (res != OC_STACK_OK)
1253 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1257 OIC_LOG(INFO, TAG, "Platform info saved.");
1263 void DeleteDeviceInfo()
1265 OIC_LOG(INFO, TAG, "Deleting device info.");
1267 OICFree(savedDeviceInfo.deviceName);
1268 OCFreeOCStringLL(savedDeviceInfo.types);
1269 OICFree(savedDeviceInfo.specVersion);
1270 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1271 savedDeviceInfo.deviceName = NULL;
1272 savedDeviceInfo.specVersion = NULL;
1273 savedDeviceInfo.dataModelVersions = NULL;
1276 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1278 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1280 if(!savedDeviceInfo.deviceName && info.deviceName)
1283 return OC_STACK_NO_MEMORY;
1288 savedDeviceInfo.types = CloneOCStringLL(info.types);
1289 OCStringLL *type = info.types;
1293 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1301 // Append the oic.wk.d at the start of rt link parameter value.
1302 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1306 return OC_STACK_NO_MEMORY;
1308 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1312 return OC_STACK_NO_MEMORY;
1314 dest->next = savedDeviceInfo.types;
1315 savedDeviceInfo.types = dest;
1317 if(!savedDeviceInfo.types && info.types)
1320 return OC_STACK_NO_MEMORY;
1324 if (info.specVersion)
1326 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1327 if(!savedDeviceInfo.specVersion && info.specVersion)
1330 return OC_STACK_NO_MEMORY;
1335 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1336 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1339 return OC_STACK_NO_MEMORY;
1343 if (info.dataModelVersions)
1345 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1346 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1349 return OC_STACK_NO_MEMORY;
1354 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1355 if (!savedDeviceInfo.dataModelVersions)
1357 return OC_STACK_NO_MEMORY;
1359 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1360 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1363 return OC_STACK_NO_MEMORY;
1370 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1372 OCStackResult res = OC_STACK_OK;
1376 res = DeepCopyDeviceInfo(info);
1378 VERIFY_SUCCESS(res, OC_STACK_OK);
1380 if (OCGetServerInstanceIDString() == NULL)
1382 OIC_LOG(INFO, TAG, "Device ID generation failed");
1383 res = OC_STACK_ERROR;
1387 OIC_LOG(INFO, TAG, "Device initialized successfully.");