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_RESOURCE_ERROR;
488 case OC_EH_RESOURCE_CREATED:
489 result = OC_STACK_RESOURCE_CREATED;
491 case OC_EH_RESOURCE_DELETED:
492 result = OC_STACK_RESOURCE_DELETED;
495 result = OC_STACK_RESOURCE_CHANGED;
497 case OC_EH_RESOURCE_NOT_FOUND:
498 result = OC_STACK_NO_RESOURCE;
501 result = OC_STACK_ERROR;
507 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
514 // Null or empty is analogous to no filter.
515 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
520 OCResourceType *resourceTypePtr = resource->rsrcType;
522 while (resourceTypePtr)
524 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
528 resourceTypePtr = resourceTypePtr->next;
531 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
535 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
542 // Null or empty is analogous to no filter.
543 if (interfaceFilter == NULL || *interfaceFilter == 0)
548 OCResourceInterface *interfacePtr = resource->rsrcInterface;
552 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
553 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
554 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
558 interfacePtr = interfacePtr->next;
561 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
566 * If the filters are null, they will be assumed to NOT be present
567 * and the resource will not be matched against them.
568 * Function will return true if all non null AND non empty filters passed in find a match.
570 static bool includeThisResourceInResponse(OCResource *resource,
571 char *interfaceFilter,
572 char *resourceTypeFilter)
576 OIC_LOG(ERROR, TAG, "Invalid resource");
580 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
583 * At least one valid filter should be available to
584 * include the resource in discovery response
586 if (!(resourceTypeFilter && *resourceTypeFilter))
588 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
589 resource", resource->uri);
593 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
594 !(resource->resourceProperties & OC_DISCOVERABLE))
596 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
600 return resourceMatchesIFFilter(resource, interfaceFilter) &&
601 resourceMatchesRTFilter(resource, resourceTypeFilter);
605 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
606 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
608 OCEntityHandlerResponse response = {0};
610 response.ehResult = ehResult;
611 response.payload = discoveryPayload;
612 response.persistentBufferFlag = 0;
613 response.requestHandle = (OCRequestHandle) request;
614 response.resourceHandle = (OCResourceHandle) resource;
616 return OCDoResponse(&response);
619 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
621 if (!request || !resource)
623 return OC_STACK_INVALID_PARAM;
626 OCStackResult discoveryResult = OC_STACK_ERROR;
627 OCPayload* payload = NULL;
629 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
631 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
633 // Step 1: Generate the response to discovery request
634 if (virtualUriInRequest == OC_WELL_KNOWN_URI
636 || virtualUriInRequest == OC_MQ_BROKER_URI
640 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
642 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
643 return OC_STACK_UNAUTHORIZED_REQ;
646 char *interfaceQuery = NULL;
647 char *resourceTypeQuery = NULL;
649 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
650 &interfaceQuery, &resourceTypeQuery);
651 bool interfaceQueryAllocated = false;
652 if (!interfaceQuery && !resourceTypeQuery)
654 interfaceQueryAllocated = true;
655 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
658 if (discoveryResult == OC_STACK_OK)
660 payload = (OCPayload *)OCDiscoveryPayloadCreate();
664 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
665 bool foundResourceAtRD = false;
667 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
669 OCResourceProperty prop = OC_DISCOVERABLE;
671 if (OC_MQ_BROKER_URI == virtualUriInRequest)
677 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
679 foundResourceAtRD = false;
681 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
683 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
685 foundResourceAtRD = true;
686 discoveryResult = OC_STACK_OK;
690 if (!foundResourceAtRD && (resource->resourceProperties & prop))
692 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
698 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
700 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
701 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
702 if (savedDeviceInfo.deviceName)
704 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
705 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
707 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
708 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
709 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
710 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
711 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
712 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
713 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
715 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
718 if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
720 if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
722 foundResourceAtRD = true;
723 discoveryResult = OC_STACK_OK;
727 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
729 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
732 // Set discoveryResult appropriately if no 'valid' resources are available
733 if (discPayload->resources == NULL && !foundResourceAtRD)
735 discoveryResult = OC_STACK_NO_RESOURCE;
738 if (discoveryResult == OC_STACK_OK && foundResourceAtRD == false)
740 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
741 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
743 const char* uid = OCGetServerInstanceIDString();
746 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
752 discoveryResult = OC_STACK_NO_MEMORY;
758 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
760 if (interfaceQueryAllocated)
762 OICFree(interfaceQuery);
765 else if (virtualUriInRequest == OC_DEVICE_URI)
767 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
769 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
770 return OC_STACK_UNAUTHORIZED_REQ;
773 const char* deviceId = OCGetServerInstanceIDString();
776 discoveryResult = OC_STACK_ERROR;
780 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
781 if (!dataModelVersions)
783 discoveryResult = OC_STACK_NO_MEMORY;
787 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
788 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
791 discoveryResult = OC_STACK_NO_MEMORY;
795 discoveryResult = OC_STACK_OK;
797 OICFree(dataModelVersions);
801 else if (virtualUriInRequest == OC_PLATFORM_URI)
803 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
805 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
806 return OC_STACK_UNAUTHORIZED_REQ;
809 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
812 discoveryResult = OC_STACK_NO_MEMORY;
816 discoveryResult = OC_STACK_OK;
819 #ifdef ROUTING_GATEWAY
820 else if (OC_GATEWAY_URI == virtualUriInRequest)
822 // Received request for a gateway
823 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
824 discoveryResult = RMHandleGatewayRequest(request, resource);
830 * Step 2: Send the discovery response
832 * Iotivity should respond to discovery requests in below manner:
833 * 1)If query filter matching fails and discovery request is multicast,
834 * it should NOT send any response.
835 * 2)If query filter matching fails and discovery request is unicast,
836 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
837 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
838 * request is multicast, it should NOT send any response.
839 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
840 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
844 if ((virtualUriInRequest == OC_PRESENCE) &&
845 (resource->resourceProperties & OC_ACTIVE))
847 // Need to send ACK when the request is CON.
848 if (request->qos == OC_HIGH_QOS)
850 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
851 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
852 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
853 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
856 // Presence uses observer notification api to respond via SendPresenceNotification.
857 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
861 #ifdef ROUTING_GATEWAY
862 // Gateway uses the RMHandleGatewayRequest to respond to the request.
863 if (OC_GATEWAY_URI != virtualUriInRequest)
866 if(discoveryResult == OC_STACK_OK)
868 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
870 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
871 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
872 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
874 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
875 discoveryResult, virtualUriInRequest);
876 SendNonPersistantDiscoveryResponse(request, resource, NULL,
877 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
881 // Ignoring the discovery request as per RFC 7252, Section #8.2
882 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
886 OCPayloadDestroy(payload);
892 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
896 return OC_STACK_INVALID_PARAM;
899 OCStackResult result = OC_STACK_OK;
900 OCEntityHandlerResult ehResult = OC_EH_ERROR;
901 OCEntityHandlerRequest ehRequest = {0};
903 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
904 result = FormOCEntityHandlerRequest(&ehRequest,
905 (OCRequestHandle) request,
908 (OCResourceHandle) NULL, request->query,
909 PAYLOAD_TYPE_REPRESENTATION,
911 request->payloadSize,
912 request->numRcvdVendorSpecificHeaderOptions,
913 request->rcvdVendorSpecificHeaderOptions,
914 (OCObserveAction)request->observationOption,
917 VERIFY_SUCCESS(result, OC_STACK_OK);
919 // At this point we know for sure that defaultDeviceHandler exists
920 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
921 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
922 if(ehResult == OC_EH_SLOW)
924 OIC_LOG(INFO, TAG, "This is a slow resource");
925 request->slowFlag = 1;
927 else if(ehResult == OC_EH_ERROR)
929 FindAndDeleteServerRequest(request);
931 result = EntityHandlerCodeToOCStackCode(ehResult);
933 OCPayloadDestroy(ehRequest.payload);
938 HandleResourceWithEntityHandler (OCServerRequest *request,
939 OCResource *resource,
940 uint8_t collectionResource)
942 if(!request || ! resource)
944 return OC_STACK_INVALID_PARAM;
947 OCStackResult result = OC_STACK_ERROR;
948 OCEntityHandlerResult ehResult = OC_EH_ERROR;
949 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
950 ResourceObserver *resObs = NULL;
952 OCEntityHandlerRequest ehRequest = {0};
954 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
955 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
956 // check the security resource
957 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
959 type = PAYLOAD_TYPE_SECURITY;
963 result = FormOCEntityHandlerRequest(&ehRequest,
964 (OCRequestHandle)request,
967 (OCResourceHandle)resource,
971 request->payloadSize,
972 request->numRcvdVendorSpecificHeaderOptions,
973 request->rcvdVendorSpecificHeaderOptions,
974 (OCObserveAction)request->observationOption,
977 VERIFY_SUCCESS(result, OC_STACK_OK);
979 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
981 OIC_LOG(INFO, TAG, "No observation requested");
982 ehFlag = OC_REQUEST_FLAG;
984 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
986 OIC_LOG(INFO, TAG, "Observation registration requested");
988 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
989 request->tokenLength);
993 OIC_LOG (INFO, TAG, "Observer with this token already present");
994 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
995 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
996 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
998 // server requests are usually free'd when the response is sent out
999 // for the request in ocserverrequest.c : HandleSingleResponse()
1000 // Since we are making an early return and not responding, the server request
1001 // needs to be deleted.
1002 FindAndDeleteServerRequest (request);
1006 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1007 VERIFY_SUCCESS(result, OC_STACK_OK);
1009 result = AddObserver ((const char*)(request->resourceUrl),
1010 (const char *)(request->query),
1011 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1012 resource, request->qos, request->acceptFormat,
1015 if(result == OC_STACK_OK)
1017 OIC_LOG(INFO, TAG, "Added observer successfully");
1018 request->observeResult = OC_STACK_OK;
1019 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1021 else if (result == OC_STACK_RESOURCE_ERROR)
1023 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1024 request->observeResult = OC_STACK_ERROR;
1025 ehFlag = OC_REQUEST_FLAG;
1029 // The error in observeResult for the request will be used when responding to this
1030 // request by omitting the observation option/sequence number.
1031 request->observeResult = OC_STACK_ERROR;
1032 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1033 ehFlag = OC_REQUEST_FLAG;
1034 FindAndDeleteServerRequest(request);
1039 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1040 !collectionResource)
1042 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1044 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1048 // Stack does not contain this observation request
1049 // Either token is incorrect or observation list is corrupted
1050 result = OC_STACK_ERROR;
1053 ehRequest.obsInfo.obsId = resObs->observeId;
1054 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1056 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1058 if(result == OC_STACK_OK)
1060 OIC_LOG(INFO, TAG, "Removed observer successfully");
1061 request->observeResult = OC_STACK_OK;
1062 // There should be no observe option header for de-registration response.
1063 // Set as an invalid value here so we can detect it later and remove the field in response.
1064 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1068 request->observeResult = OC_STACK_ERROR;
1069 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1070 FindAndDeleteServerRequest(request);
1076 result = OC_STACK_ERROR;
1080 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1081 if(ehResult == OC_EH_SLOW)
1083 OIC_LOG(INFO, TAG, "This is a slow resource");
1084 request->slowFlag = 1;
1086 else if(ehResult == OC_EH_ERROR)
1088 FindAndDeleteServerRequest(request);
1090 result = EntityHandlerCodeToOCStackCode(ehResult);
1092 OCPayloadDestroy(ehRequest.payload);
1096 static OCStackResult
1097 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1098 OCResource *resource)
1100 if(!request || !resource)
1102 return OC_STACK_INVALID_PARAM;
1105 OCStackResult result = OC_STACK_ERROR;
1106 OCEntityHandlerRequest ehRequest = {0};
1108 result = FormOCEntityHandlerRequest(&ehRequest,
1109 (OCRequestHandle)request,
1112 (OCResourceHandle)resource,
1114 PAYLOAD_TYPE_REPRESENTATION,
1116 request->payloadSize,
1117 request->numRcvdVendorSpecificHeaderOptions,
1118 request->rcvdVendorSpecificHeaderOptions,
1119 (OCObserveAction)request->observationOption,
1122 if(result == OC_STACK_OK)
1124 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1127 OCPayloadDestroy(ehRequest.payload);
1132 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1134 OCStackResult ret = OC_STACK_OK;
1136 switch (resHandling)
1138 case OC_RESOURCE_VIRTUAL:
1140 ret = HandleVirtualResource (request, resource);
1143 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1145 ret = HandleDefaultDeviceEntityHandler(request);
1148 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1150 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1151 return OC_STACK_ERROR;
1153 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1155 ret = HandleResourceWithEntityHandler (request, resource, 0);
1158 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1160 ret = HandleResourceWithEntityHandler (request, resource, 1);
1163 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1165 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1168 case OC_RESOURCE_NOT_SPECIFIED:
1170 ret = OC_STACK_NO_RESOURCE;
1175 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1176 return OC_STACK_ERROR;
1182 void DeletePlatformInfo()
1184 OIC_LOG(INFO, TAG, "Deleting platform info.");
1186 OICFree(savedPlatformInfo.platformID);
1187 savedPlatformInfo.platformID = NULL;
1189 OICFree(savedPlatformInfo.manufacturerName);
1190 savedPlatformInfo.manufacturerName = NULL;
1192 OICFree(savedPlatformInfo.manufacturerUrl);
1193 savedPlatformInfo.manufacturerUrl = NULL;
1195 OICFree(savedPlatformInfo.modelNumber);
1196 savedPlatformInfo.modelNumber = NULL;
1198 OICFree(savedPlatformInfo.dateOfManufacture);
1199 savedPlatformInfo.dateOfManufacture = NULL;
1201 OICFree(savedPlatformInfo.platformVersion);
1202 savedPlatformInfo.platformVersion = NULL;
1204 OICFree(savedPlatformInfo.operatingSystemVersion);
1205 savedPlatformInfo.operatingSystemVersion = NULL;
1207 OICFree(savedPlatformInfo.hardwareVersion);
1208 savedPlatformInfo.hardwareVersion = NULL;
1210 OICFree(savedPlatformInfo.firmwareVersion);
1211 savedPlatformInfo.firmwareVersion = NULL;
1213 OICFree(savedPlatformInfo.supportUrl);
1214 savedPlatformInfo.supportUrl = NULL;
1216 OICFree(savedPlatformInfo.systemTime);
1217 savedPlatformInfo.systemTime = NULL;
1220 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1222 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1223 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1224 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1225 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1226 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1227 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1228 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1229 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1230 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1231 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1232 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1234 if ((!savedPlatformInfo.platformID && info.platformID)||
1235 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1236 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1237 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1238 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1239 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1240 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1241 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1242 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1243 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1244 (!savedPlatformInfo.systemTime && info.systemTime))
1246 DeletePlatformInfo();
1247 return OC_STACK_INVALID_PARAM;
1254 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1256 DeletePlatformInfo();
1258 OCStackResult res = DeepCopyPlatFormInfo(info);
1260 if (res != OC_STACK_OK)
1262 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1266 OIC_LOG(INFO, TAG, "Platform info saved.");
1272 void DeleteDeviceInfo()
1274 OIC_LOG(INFO, TAG, "Deleting device info.");
1276 OICFree(savedDeviceInfo.deviceName);
1277 OCFreeOCStringLL(savedDeviceInfo.types);
1278 OICFree(savedDeviceInfo.specVersion);
1279 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1280 savedDeviceInfo.deviceName = NULL;
1281 savedDeviceInfo.specVersion = NULL;
1282 savedDeviceInfo.dataModelVersions = NULL;
1285 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1287 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1289 if(!savedDeviceInfo.deviceName && info.deviceName)
1292 return OC_STACK_NO_MEMORY;
1297 savedDeviceInfo.types = CloneOCStringLL(info.types);
1298 OCStringLL *type = info.types;
1302 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1310 // Append the oic.wk.d at the start of rt link parameter value.
1311 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1315 return OC_STACK_NO_MEMORY;
1317 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1321 return OC_STACK_NO_MEMORY;
1323 dest->next = savedDeviceInfo.types;
1324 savedDeviceInfo.types = dest;
1326 if(!savedDeviceInfo.types && info.types)
1329 return OC_STACK_NO_MEMORY;
1333 if (info.specVersion)
1335 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1336 if(!savedDeviceInfo.specVersion && info.specVersion)
1339 return OC_STACK_NO_MEMORY;
1344 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1345 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1348 return OC_STACK_NO_MEMORY;
1352 if (info.dataModelVersions)
1354 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1355 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1358 return OC_STACK_NO_MEMORY;
1363 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1364 if (!savedDeviceInfo.dataModelVersions)
1366 return OC_STACK_NO_MEMORY;
1368 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1369 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1372 return OC_STACK_NO_MEMORY;
1379 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1381 OCStackResult res = OC_STACK_OK;
1385 res = DeepCopyDeviceInfo(info);
1387 VERIFY_SUCCESS(res, OC_STACK_OK);
1389 if (OCGetServerInstanceIDString() == NULL)
1391 OIC_LOG(INFO, TAG, "Device ID generation failed");
1392 res = OC_STACK_ERROR;
1396 OIC_LOG(INFO, TAG, "Device initialized successfully.");