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;
243 return OC_UNKNOWN_URI;
246 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
247 char **filterOne, char **filterTwo)
249 if(!filterOne || !filterTwo)
251 return OC_STACK_INVALID_PARAM;
258 if (uri == OC_PRESENCE)
260 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
261 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
266 OCStackResult result = OC_STACK_OK;
270 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
276 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
277 OCRepPayload** payload)
279 OCRepPayload *tempPayload = OCRepPayloadCreate();
283 OCRepPayloadDestroy(tempPayload);
284 return OC_STACK_INVALID_PARAM;
289 return OC_STACK_NO_MEMORY;
292 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
294 OCResourceType *resType = resourcePtr->rsrcType;
297 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
298 resType = resType->next;
301 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
304 OCRepPayloadAddInterface(tempPayload, resInterface->name);
305 resInterface = resInterface->next;
308 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
311 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
312 resAttrib->attrValue);
313 resAttrib = resAttrib->next;
318 *payload = tempPayload;
322 OCRepPayloadAppend(*payload, tempPayload);
328 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
329 OCDiscoveryPayload *payload, OCDevAddr *devAddr)
331 if (!resourcePtr || !payload)
333 return OC_STACK_INVALID_PARAM;
335 uint16_t securePort = 0;
336 if (resourcePtr->resourceProperties & OC_SECURE)
338 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
345 uint16_t tcpPort = 0;
346 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
350 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
352 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
358 uint8_t IsCollectionResource (OCResource *resource)
365 if(resource->rsrcChildResourcesHead != NULL)
373 OCResource *FindResourceByUri(const char* resourceUri)
380 OCResource * pointer = headResource;
383 if (strcmp(resourceUri, pointer->uri) == 0)
387 pointer = pointer->next;
389 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
394 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
395 ResourceHandling *handling,
396 OCResource **resource)
398 if(!request || !handling || !resource)
400 return OC_STACK_INVALID_PARAM;
403 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
405 // Check if virtual resource
406 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
408 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
409 *handling = OC_RESOURCE_VIRTUAL;
410 *resource = headResource;
413 if (strlen((const char*)(request->resourceUrl)) == 0)
415 // Resource URL not specified
416 *handling = OC_RESOURCE_NOT_SPECIFIED;
417 return OC_STACK_NO_RESOURCE;
421 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
422 *resource = resourcePtr;
425 if(defaultDeviceHandler)
427 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
431 // Resource does not exist
432 // and default device handler does not exist
433 *handling = OC_RESOURCE_NOT_SPECIFIED;
434 return OC_STACK_NO_RESOURCE;
437 if (IsCollectionResource (resourcePtr))
439 // Collection resource
440 if (resourcePtr->entityHandler != defaultResourceEHandler)
442 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
447 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
453 // Resource not a collection
454 if (resourcePtr->entityHandler != defaultResourceEHandler)
456 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
461 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
468 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
470 OCStackResult result;
477 result = OC_STACK_OK;
480 result = OC_STACK_SLOW_RESOURCE;
483 result = OC_STACK_ERROR;
485 case OC_EH_FORBIDDEN:
486 result = OC_STACK_FORBIDDEN_REQ;
488 case OC_EH_INTERNAL_SERVER_ERROR:
489 result = OC_STACK_INTERNAL_SERVER_ERROR;
491 case OC_EH_RESOURCE_CREATED:
492 result = OC_STACK_RESOURCE_CREATED;
494 case OC_EH_RESOURCE_DELETED:
495 result = OC_STACK_RESOURCE_DELETED;
498 result = OC_STACK_RESOURCE_CHANGED;
500 case OC_EH_RESOURCE_NOT_FOUND:
501 result = OC_STACK_NO_RESOURCE;
504 result = OC_STACK_ERROR;
510 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
517 // Null or empty is analogous to no filter.
518 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
523 OCResourceType *resourceTypePtr = resource->rsrcType;
525 while (resourceTypePtr)
527 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
531 resourceTypePtr = resourceTypePtr->next;
534 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
538 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
545 // Null or empty is analogous to no filter.
546 if (interfaceFilter == NULL || *interfaceFilter == 0)
551 OCResourceInterface *interfacePtr = resource->rsrcInterface;
555 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
556 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
557 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
561 interfacePtr = interfacePtr->next;
564 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
569 * If the filters are null, they will be assumed to NOT be present
570 * and the resource will not be matched against them.
571 * Function will return true if all non null AND non empty filters passed in find a match.
573 static bool includeThisResourceInResponse(OCResource *resource,
574 char *interfaceFilter,
575 char *resourceTypeFilter)
579 OIC_LOG(ERROR, TAG, "Invalid resource");
583 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
586 * At least one valid filter should be available to
587 * include the resource in discovery response
589 if (!(resourceTypeFilter && *resourceTypeFilter))
591 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
592 resource", resource->uri);
596 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
597 !(resource->resourceProperties & OC_DISCOVERABLE))
599 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
603 return resourceMatchesIFFilter(resource, interfaceFilter) &&
604 resourceMatchesRTFilter(resource, resourceTypeFilter);
608 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
609 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
611 OCEntityHandlerResponse response = {0};
613 response.ehResult = ehResult;
614 response.payload = discoveryPayload;
615 response.persistentBufferFlag = 0;
616 response.requestHandle = (OCRequestHandle) request;
617 response.resourceHandle = (OCResourceHandle) resource;
619 return OCDoResponse(&response);
622 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
624 if (!request || !resource)
626 return OC_STACK_INVALID_PARAM;
629 OCStackResult discoveryResult = OC_STACK_ERROR;
630 OCPayload* payload = NULL;
632 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
634 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
636 // Step 1: Generate the response to discovery request
637 if (virtualUriInRequest == OC_WELL_KNOWN_URI
639 || virtualUriInRequest == OC_MQ_BROKER_URI
643 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
645 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
646 return OC_STACK_UNAUTHORIZED_REQ;
649 char *interfaceQuery = NULL;
650 char *resourceTypeQuery = NULL;
652 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
653 &interfaceQuery, &resourceTypeQuery);
654 bool interfaceQueryAllocated = false;
655 if (!interfaceQuery && !resourceTypeQuery)
657 interfaceQueryAllocated = true;
658 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
661 if (discoveryResult == OC_STACK_OK)
663 payload = (OCPayload *)OCDiscoveryPayloadCreate();
667 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
668 bool foundResourceAtRD = false;
670 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
672 OCResourceProperty prop = OC_DISCOVERABLE;
674 if (OC_MQ_BROKER_URI == virtualUriInRequest)
680 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
682 foundResourceAtRD = false;
684 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
686 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
688 foundResourceAtRD = true;
689 discoveryResult = OC_STACK_OK;
693 if (!foundResourceAtRD && (resource->resourceProperties & prop))
695 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
701 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
703 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
704 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
705 if (savedDeviceInfo.deviceName)
707 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
708 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
710 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
711 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
712 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
713 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
714 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
715 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
716 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
718 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
721 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
723 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
725 foundResourceAtRD = true;
726 discoveryResult = OC_STACK_OK;
730 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
732 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
735 // Set discoveryResult appropriately if no 'valid' resources are available
736 if (discPayload->resources == NULL && !foundResourceAtRD)
738 discoveryResult = OC_STACK_NO_RESOURCE;
741 if (discoveryResult == OC_STACK_OK && foundResourceAtRD == false)
743 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
744 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
746 const char* uid = OCGetServerInstanceIDString();
749 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
755 discoveryResult = OC_STACK_NO_MEMORY;
761 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
763 if (interfaceQueryAllocated)
765 OICFree(interfaceQuery);
768 else if (virtualUriInRequest == OC_DEVICE_URI)
770 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
772 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
773 return OC_STACK_UNAUTHORIZED_REQ;
776 const char* deviceId = OCGetServerInstanceIDString();
779 discoveryResult = OC_STACK_ERROR;
783 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
784 if (!dataModelVersions)
786 discoveryResult = OC_STACK_NO_MEMORY;
790 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
791 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
794 discoveryResult = OC_STACK_NO_MEMORY;
798 discoveryResult = OC_STACK_OK;
800 OICFree(dataModelVersions);
804 else if (virtualUriInRequest == OC_PLATFORM_URI)
806 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
808 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
809 return OC_STACK_UNAUTHORIZED_REQ;
812 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
815 discoveryResult = OC_STACK_NO_MEMORY;
819 discoveryResult = OC_STACK_OK;
822 #ifdef ROUTING_GATEWAY
823 else if (OC_GATEWAY_URI == virtualUriInRequest)
825 // Received request for a gateway
826 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
827 discoveryResult = RMHandleGatewayRequest(request, resource);
833 * Step 2: Send the discovery response
835 * Iotivity should respond to discovery requests in below manner:
836 * 1)If query filter matching fails and discovery request is multicast,
837 * it should NOT send any response.
838 * 2)If query filter matching fails and discovery request is unicast,
839 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
840 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
841 * request is multicast, it should NOT send any response.
842 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
843 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
847 if ((virtualUriInRequest == OC_PRESENCE) &&
848 (resource->resourceProperties & OC_ACTIVE))
850 // Need to send ACK when the request is CON.
851 if (request->qos == OC_HIGH_QOS)
853 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
854 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
855 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
856 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
858 FindAndDeleteServerRequest(request);
860 // Presence uses observer notification api to respond via SendPresenceNotification.
861 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
865 #ifdef ROUTING_GATEWAY
866 // Gateway uses the RMHandleGatewayRequest to respond to the request.
867 if (OC_GATEWAY_URI != virtualUriInRequest)
870 if(discoveryResult == OC_STACK_OK)
872 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
874 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
875 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
876 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
878 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
879 discoveryResult, virtualUriInRequest);
880 SendNonPersistantDiscoveryResponse(request, resource, NULL,
881 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
885 // Ignoring the discovery request as per RFC 7252, Section #8.2
886 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
887 // the request should be removed. since it never remove and causes a big memory waste.
888 FindAndDeleteServerRequest(request);
892 OCPayloadDestroy(payload);
898 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
902 return OC_STACK_INVALID_PARAM;
905 OCStackResult result = OC_STACK_OK;
906 OCEntityHandlerResult ehResult = OC_EH_ERROR;
907 OCEntityHandlerRequest ehRequest = {0};
909 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
910 result = FormOCEntityHandlerRequest(&ehRequest,
911 (OCRequestHandle) request,
914 (OCResourceHandle) NULL, request->query,
915 PAYLOAD_TYPE_REPRESENTATION,
917 request->payloadSize,
918 request->numRcvdVendorSpecificHeaderOptions,
919 request->rcvdVendorSpecificHeaderOptions,
920 (OCObserveAction)request->observationOption,
923 VERIFY_SUCCESS(result, OC_STACK_OK);
925 // At this point we know for sure that defaultDeviceHandler exists
926 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
927 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
928 if(ehResult == OC_EH_SLOW)
930 OIC_LOG(INFO, TAG, "This is a slow resource");
931 request->slowFlag = 1;
933 else if(ehResult == OC_EH_ERROR)
935 FindAndDeleteServerRequest(request);
937 result = EntityHandlerCodeToOCStackCode(ehResult);
939 OCPayloadDestroy(ehRequest.payload);
944 HandleResourceWithEntityHandler (OCServerRequest *request,
945 OCResource *resource,
946 uint8_t collectionResource)
948 if(!request || ! resource)
950 return OC_STACK_INVALID_PARAM;
953 OCStackResult result = OC_STACK_ERROR;
954 OCEntityHandlerResult ehResult = OC_EH_ERROR;
955 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
956 ResourceObserver *resObs = NULL;
958 OCEntityHandlerRequest ehRequest = {0};
960 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
961 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
962 // check the security resource
963 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
965 type = PAYLOAD_TYPE_SECURITY;
969 result = FormOCEntityHandlerRequest(&ehRequest,
970 (OCRequestHandle)request,
973 (OCResourceHandle)resource,
977 request->payloadSize,
978 request->numRcvdVendorSpecificHeaderOptions,
979 request->rcvdVendorSpecificHeaderOptions,
980 (OCObserveAction)request->observationOption,
983 VERIFY_SUCCESS(result, OC_STACK_OK);
985 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
987 OIC_LOG(INFO, TAG, "No observation requested");
988 ehFlag = OC_REQUEST_FLAG;
990 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER)
992 OIC_LOG(INFO, TAG, "Observation registration requested");
994 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
995 request->tokenLength);
999 OIC_LOG (INFO, TAG, "Observer with this token already present");
1000 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1001 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1002 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1004 // server requests are usually free'd when the response is sent out
1005 // for the request in ocserverrequest.c : HandleSingleResponse()
1006 // Since we are making an early return and not responding, the server request
1007 // needs to be deleted.
1008 FindAndDeleteServerRequest (request);
1012 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1013 VERIFY_SUCCESS(result, OC_STACK_OK);
1015 result = AddObserver ((const char*)(request->resourceUrl),
1016 (const char *)(request->query),
1017 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1018 resource, request->qos, request->acceptFormat,
1021 if(result == OC_STACK_OK)
1023 OIC_LOG(INFO, TAG, "Added observer successfully");
1024 request->observeResult = OC_STACK_OK;
1025 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1027 else if (result == OC_STACK_RESOURCE_ERROR)
1029 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1030 request->observeResult = OC_STACK_ERROR;
1031 ehFlag = OC_REQUEST_FLAG;
1035 // The error in observeResult for the request will be used when responding to this
1036 // request by omitting the observation option/sequence number.
1037 request->observeResult = OC_STACK_ERROR;
1038 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1039 ehFlag = OC_REQUEST_FLAG;
1040 FindAndDeleteServerRequest(request);
1045 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER)
1047 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1049 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1053 // Stack does not contain this observation request
1054 // Either token is incorrect or observation list is corrupted
1055 result = OC_STACK_ERROR;
1058 ehRequest.obsInfo.obsId = resObs->observeId;
1059 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1061 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1063 if(result == OC_STACK_OK)
1065 OIC_LOG(INFO, TAG, "Removed observer successfully");
1066 request->observeResult = OC_STACK_OK;
1067 // There should be no observe option header for de-registration response.
1068 // Set as an invalid value here so we can detect it later and remove the field in response.
1069 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1073 request->observeResult = OC_STACK_ERROR;
1074 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1075 FindAndDeleteServerRequest(request);
1081 result = OC_STACK_ERROR;
1085 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1086 if(ehResult == OC_EH_SLOW)
1088 OIC_LOG(INFO, TAG, "This is a slow resource");
1089 request->slowFlag = 1;
1091 else if(ehResult == OC_EH_ERROR)
1093 FindAndDeleteServerRequest(request);
1095 result = EntityHandlerCodeToOCStackCode(ehResult);
1097 OCPayloadDestroy(ehRequest.payload);
1101 static OCStackResult
1102 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1103 OCResource *resource)
1105 if(!request || !resource)
1107 return OC_STACK_INVALID_PARAM;
1110 OCStackResult result = OC_STACK_ERROR;
1111 OCEntityHandlerRequest ehRequest = {0};
1113 result = FormOCEntityHandlerRequest(&ehRequest,
1114 (OCRequestHandle)request,
1117 (OCResourceHandle)resource,
1119 PAYLOAD_TYPE_REPRESENTATION,
1121 request->payloadSize,
1122 request->numRcvdVendorSpecificHeaderOptions,
1123 request->rcvdVendorSpecificHeaderOptions,
1124 (OCObserveAction)request->observationOption,
1127 if(result == OC_STACK_OK)
1129 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1132 OCPayloadDestroy(ehRequest.payload);
1137 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1139 OCStackResult ret = OC_STACK_OK;
1141 switch (resHandling)
1143 case OC_RESOURCE_VIRTUAL:
1145 ret = HandleVirtualResource (request, resource);
1148 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1150 ret = HandleDefaultDeviceEntityHandler(request);
1153 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1155 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1156 return OC_STACK_ERROR;
1158 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1160 ret = HandleResourceWithEntityHandler (request, resource, 0);
1163 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1165 ret = HandleResourceWithEntityHandler (request, resource, 1);
1168 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1170 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1173 case OC_RESOURCE_NOT_SPECIFIED:
1175 ret = OC_STACK_NO_RESOURCE;
1180 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1181 return OC_STACK_ERROR;
1187 void DeletePlatformInfo()
1189 OIC_LOG(INFO, TAG, "Deleting platform info.");
1191 OICFree(savedPlatformInfo.platformID);
1192 savedPlatformInfo.platformID = NULL;
1194 OICFree(savedPlatformInfo.manufacturerName);
1195 savedPlatformInfo.manufacturerName = NULL;
1197 OICFree(savedPlatformInfo.manufacturerUrl);
1198 savedPlatformInfo.manufacturerUrl = NULL;
1200 OICFree(savedPlatformInfo.modelNumber);
1201 savedPlatformInfo.modelNumber = NULL;
1203 OICFree(savedPlatformInfo.dateOfManufacture);
1204 savedPlatformInfo.dateOfManufacture = NULL;
1206 OICFree(savedPlatformInfo.platformVersion);
1207 savedPlatformInfo.platformVersion = NULL;
1209 OICFree(savedPlatformInfo.operatingSystemVersion);
1210 savedPlatformInfo.operatingSystemVersion = NULL;
1212 OICFree(savedPlatformInfo.hardwareVersion);
1213 savedPlatformInfo.hardwareVersion = NULL;
1215 OICFree(savedPlatformInfo.firmwareVersion);
1216 savedPlatformInfo.firmwareVersion = NULL;
1218 OICFree(savedPlatformInfo.supportUrl);
1219 savedPlatformInfo.supportUrl = NULL;
1221 OICFree(savedPlatformInfo.systemTime);
1222 savedPlatformInfo.systemTime = NULL;
1225 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1227 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1228 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1229 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1230 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1231 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1232 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1233 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1234 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1235 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1236 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1237 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1239 if ((!savedPlatformInfo.platformID && info.platformID)||
1240 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1241 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1242 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1243 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1244 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1245 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1246 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1247 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1248 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1249 (!savedPlatformInfo.systemTime && info.systemTime))
1251 DeletePlatformInfo();
1252 return OC_STACK_INVALID_PARAM;
1259 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1261 DeletePlatformInfo();
1263 OCStackResult res = DeepCopyPlatFormInfo(info);
1265 if (res != OC_STACK_OK)
1267 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1271 OIC_LOG(INFO, TAG, "Platform info saved.");
1277 void DeleteDeviceInfo()
1279 OIC_LOG(INFO, TAG, "Deleting device info.");
1281 OICFree(savedDeviceInfo.deviceName);
1282 OCFreeOCStringLL(savedDeviceInfo.types);
1283 OICFree(savedDeviceInfo.specVersion);
1284 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1285 savedDeviceInfo.deviceName = NULL;
1286 savedDeviceInfo.specVersion = NULL;
1287 savedDeviceInfo.dataModelVersions = NULL;
1290 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1292 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1294 if(!savedDeviceInfo.deviceName && info.deviceName)
1297 return OC_STACK_NO_MEMORY;
1302 savedDeviceInfo.types = CloneOCStringLL(info.types);
1303 OCStringLL *type = info.types;
1307 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1315 // Append the oic.wk.d at the start of rt link parameter value.
1316 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1320 return OC_STACK_NO_MEMORY;
1322 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1326 return OC_STACK_NO_MEMORY;
1328 dest->next = savedDeviceInfo.types;
1329 savedDeviceInfo.types = dest;
1331 if(!savedDeviceInfo.types && info.types)
1334 return OC_STACK_NO_MEMORY;
1338 if (info.specVersion)
1340 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1341 if(!savedDeviceInfo.specVersion && info.specVersion)
1344 return OC_STACK_NO_MEMORY;
1349 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1350 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1353 return OC_STACK_NO_MEMORY;
1357 if (info.dataModelVersions)
1359 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1360 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1363 return OC_STACK_NO_MEMORY;
1368 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1369 if (!savedDeviceInfo.dataModelVersions)
1371 return OC_STACK_NO_MEMORY;
1373 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1374 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1377 return OC_STACK_NO_MEMORY;
1384 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1386 OCStackResult res = OC_STACK_OK;
1390 res = DeepCopyDeviceInfo(info);
1392 VERIFY_SUCCESS(res, OC_STACK_OK);
1394 if (OCGetServerInstanceIDString() == NULL)
1396 OIC_LOG(INFO, TAG, "Device ID generation failed");
1397 res = OC_STACK_ERROR;
1401 OIC_LOG(INFO, TAG, "Device initialized successfully.");