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);
855 FindAndDeleteServerRequest(request);
857 // Presence uses observer notification api to respond via SendPresenceNotification.
858 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
862 #ifdef ROUTING_GATEWAY
863 // Gateway uses the RMHandleGatewayRequest to respond to the request.
864 if (OC_GATEWAY_URI != virtualUriInRequest)
867 if(discoveryResult == OC_STACK_OK)
869 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
871 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
872 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
873 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
875 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
876 discoveryResult, virtualUriInRequest);
877 SendNonPersistantDiscoveryResponse(request, resource, NULL,
878 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
882 // Ignoring the discovery request as per RFC 7252, Section #8.2
883 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
884 // the request should be removed. since it never remove and causes a big memory waste.
885 FindAndDeleteServerRequest(request);
889 OCPayloadDestroy(payload);
895 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
899 return OC_STACK_INVALID_PARAM;
902 OCStackResult result = OC_STACK_OK;
903 OCEntityHandlerResult ehResult = OC_EH_ERROR;
904 OCEntityHandlerRequest ehRequest = {0};
906 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
907 result = FormOCEntityHandlerRequest(&ehRequest,
908 (OCRequestHandle) request,
911 (OCResourceHandle) NULL, request->query,
912 PAYLOAD_TYPE_REPRESENTATION,
914 request->payloadSize,
915 request->numRcvdVendorSpecificHeaderOptions,
916 request->rcvdVendorSpecificHeaderOptions,
917 (OCObserveAction)request->observationOption,
920 VERIFY_SUCCESS(result, OC_STACK_OK);
922 // At this point we know for sure that defaultDeviceHandler exists
923 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
924 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
925 if(ehResult == OC_EH_SLOW)
927 OIC_LOG(INFO, TAG, "This is a slow resource");
928 request->slowFlag = 1;
930 else if(ehResult == OC_EH_ERROR)
932 FindAndDeleteServerRequest(request);
934 result = EntityHandlerCodeToOCStackCode(ehResult);
936 OCPayloadDestroy(ehRequest.payload);
941 HandleResourceWithEntityHandler (OCServerRequest *request,
942 OCResource *resource,
943 uint8_t collectionResource)
945 if(!request || ! resource)
947 return OC_STACK_INVALID_PARAM;
950 OCStackResult result = OC_STACK_ERROR;
951 OCEntityHandlerResult ehResult = OC_EH_ERROR;
952 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
953 ResourceObserver *resObs = NULL;
955 OCEntityHandlerRequest ehRequest = {0};
957 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
958 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
959 // check the security resource
960 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
962 type = PAYLOAD_TYPE_SECURITY;
966 result = FormOCEntityHandlerRequest(&ehRequest,
967 (OCRequestHandle)request,
970 (OCResourceHandle)resource,
974 request->payloadSize,
975 request->numRcvdVendorSpecificHeaderOptions,
976 request->rcvdVendorSpecificHeaderOptions,
977 (OCObserveAction)request->observationOption,
980 VERIFY_SUCCESS(result, OC_STACK_OK);
982 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
984 OIC_LOG(INFO, TAG, "No observation requested");
985 ehFlag = OC_REQUEST_FLAG;
987 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
989 OIC_LOG(INFO, TAG, "Observation registration requested");
991 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
992 request->tokenLength);
996 OIC_LOG (INFO, TAG, "Observer with this token already present");
997 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
998 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
999 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1001 // server requests are usually free'd when the response is sent out
1002 // for the request in ocserverrequest.c : HandleSingleResponse()
1003 // Since we are making an early return and not responding, the server request
1004 // needs to be deleted.
1005 FindAndDeleteServerRequest (request);
1009 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1010 VERIFY_SUCCESS(result, OC_STACK_OK);
1012 result = AddObserver ((const char*)(request->resourceUrl),
1013 (const char *)(request->query),
1014 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1015 resource, request->qos, request->acceptFormat,
1018 if(result == OC_STACK_OK)
1020 OIC_LOG(INFO, TAG, "Added observer successfully");
1021 request->observeResult = OC_STACK_OK;
1022 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1024 else if (result == OC_STACK_RESOURCE_ERROR)
1026 OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1027 request->observeResult = OC_STACK_ERROR;
1028 ehFlag = OC_REQUEST_FLAG;
1032 // The error in observeResult for the request will be used when responding to this
1033 // request by omitting the observation option/sequence number.
1034 request->observeResult = OC_STACK_ERROR;
1035 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1036 ehFlag = OC_REQUEST_FLAG;
1037 FindAndDeleteServerRequest(request);
1042 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1043 !collectionResource)
1045 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1047 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1051 // Stack does not contain this observation request
1052 // Either token is incorrect or observation list is corrupted
1053 result = OC_STACK_ERROR;
1056 ehRequest.obsInfo.obsId = resObs->observeId;
1057 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1059 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1061 if(result == OC_STACK_OK)
1063 OIC_LOG(INFO, TAG, "Removed observer successfully");
1064 request->observeResult = OC_STACK_OK;
1065 // There should be no observe option header for de-registration response.
1066 // Set as an invalid value here so we can detect it later and remove the field in response.
1067 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1071 request->observeResult = OC_STACK_ERROR;
1072 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1073 FindAndDeleteServerRequest(request);
1079 result = OC_STACK_ERROR;
1083 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1084 if(ehResult == OC_EH_SLOW)
1086 OIC_LOG(INFO, TAG, "This is a slow resource");
1087 request->slowFlag = 1;
1089 else if(ehResult == OC_EH_ERROR)
1091 FindAndDeleteServerRequest(request);
1093 result = EntityHandlerCodeToOCStackCode(ehResult);
1095 OCPayloadDestroy(ehRequest.payload);
1099 static OCStackResult
1100 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1101 OCResource *resource)
1103 if(!request || !resource)
1105 return OC_STACK_INVALID_PARAM;
1108 OCStackResult result = OC_STACK_ERROR;
1109 OCEntityHandlerRequest ehRequest = {0};
1111 result = FormOCEntityHandlerRequest(&ehRequest,
1112 (OCRequestHandle)request,
1115 (OCResourceHandle)resource,
1117 PAYLOAD_TYPE_REPRESENTATION,
1119 request->payloadSize,
1120 request->numRcvdVendorSpecificHeaderOptions,
1121 request->rcvdVendorSpecificHeaderOptions,
1122 (OCObserveAction)request->observationOption,
1125 if(result == OC_STACK_OK)
1127 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1130 OCPayloadDestroy(ehRequest.payload);
1135 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1137 OCStackResult ret = OC_STACK_OK;
1139 switch (resHandling)
1141 case OC_RESOURCE_VIRTUAL:
1143 ret = HandleVirtualResource (request, resource);
1146 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1148 ret = HandleDefaultDeviceEntityHandler(request);
1151 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1153 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1154 return OC_STACK_ERROR;
1156 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1158 ret = HandleResourceWithEntityHandler (request, resource, 0);
1161 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1163 ret = HandleResourceWithEntityHandler (request, resource, 1);
1166 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1168 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1171 case OC_RESOURCE_NOT_SPECIFIED:
1173 ret = OC_STACK_NO_RESOURCE;
1178 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1179 return OC_STACK_ERROR;
1185 void DeletePlatformInfo()
1187 OIC_LOG(INFO, TAG, "Deleting platform info.");
1189 OICFree(savedPlatformInfo.platformID);
1190 savedPlatformInfo.platformID = NULL;
1192 OICFree(savedPlatformInfo.manufacturerName);
1193 savedPlatformInfo.manufacturerName = NULL;
1195 OICFree(savedPlatformInfo.manufacturerUrl);
1196 savedPlatformInfo.manufacturerUrl = NULL;
1198 OICFree(savedPlatformInfo.modelNumber);
1199 savedPlatformInfo.modelNumber = NULL;
1201 OICFree(savedPlatformInfo.dateOfManufacture);
1202 savedPlatformInfo.dateOfManufacture = NULL;
1204 OICFree(savedPlatformInfo.platformVersion);
1205 savedPlatformInfo.platformVersion = NULL;
1207 OICFree(savedPlatformInfo.operatingSystemVersion);
1208 savedPlatformInfo.operatingSystemVersion = NULL;
1210 OICFree(savedPlatformInfo.hardwareVersion);
1211 savedPlatformInfo.hardwareVersion = NULL;
1213 OICFree(savedPlatformInfo.firmwareVersion);
1214 savedPlatformInfo.firmwareVersion = NULL;
1216 OICFree(savedPlatformInfo.supportUrl);
1217 savedPlatformInfo.supportUrl = NULL;
1219 OICFree(savedPlatformInfo.systemTime);
1220 savedPlatformInfo.systemTime = NULL;
1223 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1225 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1226 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1227 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1228 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1229 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1230 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1231 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1232 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1233 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1234 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1235 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1237 if ((!savedPlatformInfo.platformID && info.platformID)||
1238 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1239 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1240 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1241 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1242 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1243 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1244 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1245 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1246 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1247 (!savedPlatformInfo.systemTime && info.systemTime))
1249 DeletePlatformInfo();
1250 return OC_STACK_INVALID_PARAM;
1257 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1259 DeletePlatformInfo();
1261 OCStackResult res = DeepCopyPlatFormInfo(info);
1263 if (res != OC_STACK_OK)
1265 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1269 OIC_LOG(INFO, TAG, "Platform info saved.");
1275 void DeleteDeviceInfo()
1277 OIC_LOG(INFO, TAG, "Deleting device info.");
1279 OICFree(savedDeviceInfo.deviceName);
1280 OCFreeOCStringLL(savedDeviceInfo.types);
1281 OICFree(savedDeviceInfo.specVersion);
1282 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1283 savedDeviceInfo.deviceName = NULL;
1284 savedDeviceInfo.specVersion = NULL;
1285 savedDeviceInfo.dataModelVersions = NULL;
1288 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1290 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1292 if(!savedDeviceInfo.deviceName && info.deviceName)
1295 return OC_STACK_NO_MEMORY;
1300 savedDeviceInfo.types = CloneOCStringLL(info.types);
1301 OCStringLL *type = info.types;
1305 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1313 // Append the oic.wk.d at the start of rt link parameter value.
1314 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1318 return OC_STACK_NO_MEMORY;
1320 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1324 return OC_STACK_NO_MEMORY;
1326 dest->next = savedDeviceInfo.types;
1327 savedDeviceInfo.types = dest;
1329 if(!savedDeviceInfo.types && info.types)
1332 return OC_STACK_NO_MEMORY;
1336 if (info.specVersion)
1338 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1339 if(!savedDeviceInfo.specVersion && info.specVersion)
1342 return OC_STACK_NO_MEMORY;
1347 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1348 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1351 return OC_STACK_NO_MEMORY;
1355 if (info.dataModelVersions)
1357 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1358 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1361 return OC_STACK_NO_MEMORY;
1366 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1367 if (!savedDeviceInfo.dataModelVersions)
1369 return OC_STACK_NO_MEMORY;
1371 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1372 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1375 return OC_STACK_NO_MEMORY;
1382 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1384 OCStackResult res = OC_STACK_OK;
1388 res = DeepCopyDeviceInfo(info);
1390 VERIFY_SUCCESS(res, OC_STACK_OK);
1392 if (OCGetServerInstanceIDString() == NULL)
1394 OIC_LOG(INFO, TAG, "Device ID generation failed");
1395 res = OC_STACK_ERROR;
1399 OIC_LOG(INFO, TAG, "Device initialized successfully.");