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
39 #include "ocresource.h"
40 #include "ocresourcehandler.h"
41 #include "ocobserve.h"
42 #include "occollection.h"
43 #include "oic_malloc.h"
44 #include "oic_string.h"
47 #include "ocpayload.h"
48 #include "secureresourcemanager.h"
50 #include "cainterface.h"
51 #include "ocpayload.h"
53 #ifdef ROUTING_GATEWAY
54 #include "routingmanager.h"
58 #define TAG "OIC_RI_RESOURCE"
60 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
61 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
63 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
64 TAG, #arg " is NULL"); return (retVal); } }
66 #include "platform_features.h"
68 extern OCResource *headResource;
69 static OCPlatformInfo savedPlatformInfo = {0};
70 static OCDeviceInfo savedDeviceInfo = {0};
73 * Prepares a Payload for response.
75 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
76 OCDiscoveryPayload* payload,
80 //-----------------------------------------------------------------------------
81 // Default resource entity handler function
82 //-----------------------------------------------------------------------------
83 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
84 OCEntityHandlerRequest * request, void* callbackParam)
86 //TODO ("Implement me!!!!");
87 // TODO: remove silence unused param warnings
91 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
94 /* This method will retrieve the port at which the secure resource is hosted */
95 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
99 if (endpoint->adapter == OC_ADAPTER_IP)
101 if (endpoint->flags & OC_IP_USE_V6)
103 p = caglobals.ip.u6s.port;
105 else if (endpoint->flags & OC_IP_USE_V4)
107 p = caglobals.ip.u4s.port;
116 /* This method will retrieve the tcp port */
117 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
121 if (endpoint->adapter == OC_ADAPTER_IP)
123 if (endpoint->flags & OC_IP_USE_V4)
125 p = caglobals.tcp.ipv4.port;
127 else if (endpoint->flags & OC_IP_USE_V6)
129 p = caglobals.tcp.ipv6.port;
139 * Function will extract 0, 1 or 2 filters from query.
140 * More than 2 filters or unsupported filters will result in error.
141 * If both filters are of the same supported type, the 2nd one will be picked.
142 * Resource and device filters in the SAME query are NOT validated
143 * and resources will likely not clear filters.
145 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
150 char *restOfQuery = NULL;
151 int numKeyValuePairsParsed = 0;
156 OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
158 if (strnlen(query, MAX_QUERY_LENGTH) >= MAX_QUERY_LENGTH)
160 OIC_LOG(ERROR, TAG, "Query exceeds maximum length.");
161 return OC_STACK_INVALID_QUERY;
164 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
168 if (numKeyValuePairsParsed >= 2)
170 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
171 return OC_STACK_INVALID_QUERY;
174 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
178 return OC_STACK_INVALID_QUERY;
180 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
182 *filterOne = value; // if
184 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
186 *filterTwo = value; // rt
190 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
191 return OC_STACK_INVALID_QUERY;
193 ++numKeyValuePairsParsed;
195 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
198 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
202 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
204 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
206 return OC_WELL_KNOWN_URI;
208 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
210 return OC_DEVICE_URI;
212 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
214 return OC_PLATFORM_URI;
216 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
218 return OC_RESOURCE_TYPES_URI;
220 #ifdef ROUTING_GATEWAY
221 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
223 return OC_GATEWAY_URI;
227 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
231 #endif //WITH_PRESENCE
234 else if (0 == strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_MQ_URI))
236 return OC_MQ_BROKER_URI;
239 return OC_UNKNOWN_URI;
242 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
243 char **filterOne, char **filterTwo)
245 if(!filterOne || !filterTwo)
247 return OC_STACK_INVALID_PARAM;
254 if (uri == OC_PRESENCE)
256 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
257 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
262 OCStackResult result = OC_STACK_OK;
266 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
272 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
273 OCRepPayload** payload)
275 OCRepPayload *tempPayload = OCRepPayloadCreate();
279 OCRepPayloadDestroy(tempPayload);
280 return OC_STACK_INVALID_PARAM;
285 return OC_STACK_NO_MEMORY;
288 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
290 OCResourceType *resType = resourcePtr->rsrcType;
293 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
294 resType = resType->next;
297 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
300 OCRepPayloadAddInterface(tempPayload, resInterface->name);
301 resInterface = resInterface->next;
304 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
307 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
308 resAttrib->attrValue);
309 resAttrib = resAttrib->next;
314 *payload = tempPayload;
318 OCRepPayloadAppend(*payload, tempPayload);
324 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
325 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
327 if (!resourcePtr || !payload)
329 return OC_STACK_INVALID_PARAM;
331 uint16_t securePort = 0;
332 if (resourcePtr->resourceProperties & OC_SECURE)
334 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
342 securePort = devAddr->port;
345 uint16_t tcpPort = 0;
347 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
351 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
353 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
359 uint8_t IsCollectionResource (OCResource *resource)
366 if(resource->rsrcChildResourcesHead != NULL)
374 OCResource *FindResourceByUri(const char* resourceUri)
381 OCResource * pointer = headResource;
384 if (strcmp(resourceUri, pointer->uri) == 0)
388 pointer = pointer->next;
390 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
395 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
396 ResourceHandling *handling,
397 OCResource **resource)
399 if(!request || !handling || !resource)
401 return OC_STACK_INVALID_PARAM;
404 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
406 // Check if virtual resource
407 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
409 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
410 *handling = OC_RESOURCE_VIRTUAL;
411 *resource = headResource;
414 if (strlen((const char*)(request->resourceUrl)) == 0)
416 // Resource URL not specified
417 *handling = OC_RESOURCE_NOT_SPECIFIED;
418 return OC_STACK_NO_RESOURCE;
422 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
423 *resource = resourcePtr;
426 if(defaultDeviceHandler)
428 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
432 // Resource does not exist
433 // and default device handler does not exist
434 *handling = OC_RESOURCE_NOT_SPECIFIED;
435 return OC_STACK_NO_RESOURCE;
438 if (IsCollectionResource (resourcePtr))
440 // Collection resource
441 if (resourcePtr->entityHandler != defaultResourceEHandler)
443 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
448 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
454 // Resource not a collection
455 if (resourcePtr->entityHandler != defaultResourceEHandler)
457 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
462 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
469 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
471 OCStackResult result;
478 result = OC_STACK_OK;
481 result = OC_STACK_SLOW_RESOURCE;
484 result = OC_STACK_ERROR;
486 case OC_EH_FORBIDDEN:
487 result = OC_STACK_RESOURCE_ERROR;
489 case OC_EH_RESOURCE_CREATED:
490 result = OC_STACK_RESOURCE_CREATED;
492 case OC_EH_RESOURCE_DELETED:
493 result = OC_STACK_RESOURCE_DELETED;
496 result = OC_STACK_RESOURCE_CHANGED;
498 case OC_EH_RESOURCE_NOT_FOUND:
499 result = OC_STACK_NO_RESOURCE;
502 result = OC_STACK_ERROR;
508 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
515 // Null or empty is analogous to no filter.
516 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
521 OCResourceType *resourceTypePtr = resource->rsrcType;
523 while (resourceTypePtr)
525 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
529 resourceTypePtr = resourceTypePtr->next;
532 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
536 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
543 // Null or empty is analogous to no filter.
544 if (interfaceFilter == NULL || *interfaceFilter == 0)
549 OCResourceInterface *interfacePtr = resource->rsrcInterface;
553 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
554 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
555 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
559 interfacePtr = interfacePtr->next;
562 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
567 * If the filters are null, they will be assumed to NOT be present
568 * and the resource will not be matched against them.
569 * Function will return true if all non null AND non empty filters passed in find a match.
571 static bool includeThisResourceInResponse(OCResource *resource,
572 char *interfaceFilter,
573 char *resourceTypeFilter)
577 OIC_LOG(ERROR, TAG, "Invalid resource");
581 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
584 * At least one valid filter should be available to
585 * include the resource in discovery response
587 if (!(resourceTypeFilter && *resourceTypeFilter))
589 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
590 resource", resource->uri);
594 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
595 !(resource->resourceProperties & OC_DISCOVERABLE))
597 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
601 return resourceMatchesIFFilter(resource, interfaceFilter) &&
602 resourceMatchesRTFilter(resource, resourceTypeFilter);
606 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
607 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
609 OCEntityHandlerResponse response = {0};
611 response.ehResult = ehResult;
612 response.payload = discoveryPayload;
613 response.persistentBufferFlag = 0;
614 response.requestHandle = (OCRequestHandle) request;
615 response.resourceHandle = (OCResourceHandle) resource;
617 return OCDoResponse(&response);
620 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
622 if (!request || !resource)
624 return OC_STACK_INVALID_PARAM;
627 OCStackResult discoveryResult = OC_STACK_ERROR;
628 OCPayload* payload = NULL;
630 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
632 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
634 // Step 1: Generate the response to discovery request
635 if (virtualUriInRequest == OC_WELL_KNOWN_URI
637 || virtualUriInRequest == OC_MQ_BROKER_URI
641 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
643 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
644 return OC_STACK_UNAUTHORIZED_REQ;
647 char *interfaceQuery = NULL;
648 char *resourceTypeQuery = NULL;
650 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
651 &interfaceQuery, &resourceTypeQuery);
652 bool interfaceQueryAllocated = false;
653 if (!interfaceQuery && !resourceTypeQuery)
655 interfaceQueryAllocated = true;
656 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
659 if (discoveryResult == OC_STACK_OK)
661 payload = (OCPayload *)OCDiscoveryPayloadCreate();
665 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
666 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
667 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
669 const char* uid = OCGetServerInstanceIDString();
672 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
675 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
677 OCResourceProperty prop = OC_DISCOVERABLE;
679 if (OC_MQ_BROKER_URI == virtualUriInRequest)
685 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
689 if (resource->resourceProperties & prop)
696 discoveryResult = BuildVirtualResourceResponse(resource,
697 discPayload, &request->devAddr, false);
703 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
705 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
706 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
707 if (savedDeviceInfo.deviceName)
709 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
710 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
712 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
713 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
714 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
715 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
716 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
717 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
718 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
720 bool foundResourceAtRD = false;
721 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
723 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
725 discoveryResult = BuildVirtualResourceResponse(resource,
726 discPayload, &request->devAddr, false);
729 // Set discoveryResult appropriately if no 'valid' resources are available
730 if (discPayload->resources == NULL && !foundResourceAtRD)
732 discoveryResult = OC_STACK_NO_RESOURCE;
738 discoveryResult = OC_STACK_NO_MEMORY;
743 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
745 if (interfaceQueryAllocated)
747 OICFree(interfaceQuery);
750 else if (virtualUriInRequest == OC_DEVICE_URI)
752 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
754 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
755 return OC_STACK_UNAUTHORIZED_REQ;
758 const char* deviceId = OCGetServerInstanceIDString();
761 discoveryResult = OC_STACK_ERROR;
765 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
766 if (!dataModelVersions)
768 discoveryResult = OC_STACK_NO_MEMORY;
772 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
773 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
776 discoveryResult = OC_STACK_NO_MEMORY;
780 discoveryResult = OC_STACK_OK;
782 OICFree(dataModelVersions);
786 else if (virtualUriInRequest == OC_PLATFORM_URI)
788 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
790 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
791 return OC_STACK_UNAUTHORIZED_REQ;
794 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
797 discoveryResult = OC_STACK_NO_MEMORY;
801 discoveryResult = OC_STACK_OK;
804 #ifdef ROUTING_GATEWAY
805 else if (OC_GATEWAY_URI == virtualUriInRequest)
807 // Received request for a gateway
808 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
809 discoveryResult = RMHandleGatewayRequest(request, resource);
815 * Step 2: Send the discovery response
817 * Iotivity should respond to discovery requests in below manner:
818 * 1)If query filter matching fails and discovery request is multicast,
819 * it should NOT send any response.
820 * 2)If query filter matching fails and discovery request is unicast,
821 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
822 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
823 * request is multicast, it should NOT send any response.
824 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
825 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
829 if ((virtualUriInRequest == OC_PRESENCE) &&
830 (resource->resourceProperties & OC_ACTIVE))
832 // Need to send ACK when the request is CON.
833 if (request->qos == OC_HIGH_QOS)
835 CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
836 CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
837 SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
838 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
841 // Presence uses observer notification api to respond via SendPresenceNotification.
842 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
846 #ifdef ROUTING_GATEWAY
847 // Gateway uses the RMHandleGatewayRequest to respond to the request.
848 if (OC_GATEWAY_URI != virtualUriInRequest)
851 if(discoveryResult == OC_STACK_OK)
853 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
855 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
856 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
857 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
859 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
860 discoveryResult, virtualUriInRequest);
861 SendNonPersistantDiscoveryResponse(request, resource, NULL,
862 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
866 // Ignoring the discovery request as per RFC 7252, Section #8.2
867 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
871 OCPayloadDestroy(payload);
877 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
881 return OC_STACK_INVALID_PARAM;
884 OCStackResult result = OC_STACK_OK;
885 OCEntityHandlerResult ehResult = OC_EH_ERROR;
886 OCEntityHandlerRequest ehRequest = {0};
888 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
889 result = FormOCEntityHandlerRequest(&ehRequest,
890 (OCRequestHandle) request,
893 (OCResourceHandle) NULL, request->query,
894 PAYLOAD_TYPE_REPRESENTATION,
896 request->payloadSize,
897 request->numRcvdVendorSpecificHeaderOptions,
898 request->rcvdVendorSpecificHeaderOptions,
899 (OCObserveAction)request->observationOption,
902 VERIFY_SUCCESS(result, OC_STACK_OK);
904 // At this point we know for sure that defaultDeviceHandler exists
905 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
906 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
907 if(ehResult == OC_EH_SLOW)
909 OIC_LOG(INFO, TAG, "This is a slow resource");
910 request->slowFlag = 1;
912 else if(ehResult == OC_EH_ERROR)
914 FindAndDeleteServerRequest(request);
916 result = EntityHandlerCodeToOCStackCode(ehResult);
918 OCPayloadDestroy(ehRequest.payload);
923 HandleResourceWithEntityHandler (OCServerRequest *request,
924 OCResource *resource,
925 uint8_t collectionResource)
927 if(!request || ! resource)
929 return OC_STACK_INVALID_PARAM;
932 OCStackResult result = OC_STACK_ERROR;
933 OCEntityHandlerResult ehResult = OC_EH_ERROR;
934 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
935 ResourceObserver *resObs = NULL;
937 OCEntityHandlerRequest ehRequest = {0};
939 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
940 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
941 // check the security resource
942 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
944 type = PAYLOAD_TYPE_SECURITY;
948 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
950 type = PAYLOAD_TYPE_RD;
953 result = FormOCEntityHandlerRequest(&ehRequest,
954 (OCRequestHandle)request,
957 (OCResourceHandle)resource,
961 request->payloadSize,
962 request->numRcvdVendorSpecificHeaderOptions,
963 request->rcvdVendorSpecificHeaderOptions,
964 (OCObserveAction)request->observationOption,
967 VERIFY_SUCCESS(result, OC_STACK_OK);
969 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
971 OIC_LOG(INFO, TAG, "No observation requested");
972 ehFlag = OC_REQUEST_FLAG;
974 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
976 OIC_LOG(INFO, TAG, "Observation registration requested");
978 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
979 request->tokenLength);
983 OIC_LOG (INFO, TAG, "Observer with this token already present");
984 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
985 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
986 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
988 // server requests are usually free'd when the response is sent out
989 // for the request in ocserverrequest.c : HandleSingleResponse()
990 // Since we are making an early return and not responding, the server request
991 // needs to be deleted.
992 FindAndDeleteServerRequest (request);
996 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
997 VERIFY_SUCCESS(result, OC_STACK_OK);
999 result = AddObserver ((const char*)(request->resourceUrl),
1000 (const char *)(request->query),
1001 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1002 resource, request->qos, request->acceptFormat,
1005 if(result == OC_STACK_OK)
1007 OIC_LOG(INFO, TAG, "Added observer successfully");
1008 request->observeResult = OC_STACK_OK;
1009 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1013 // The error in observeResult for the request will be used when responding to this
1014 // request by omitting the observation option/sequence number.
1015 request->observeResult = OC_STACK_ERROR;
1016 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1017 ehFlag = OC_REQUEST_FLAG;
1018 FindAndDeleteServerRequest(request);
1023 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1024 !collectionResource)
1026 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1028 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1032 // Stack does not contain this observation request
1033 // Either token is incorrect or observation list is corrupted
1034 result = OC_STACK_ERROR;
1037 ehRequest.obsInfo.obsId = resObs->observeId;
1038 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1040 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1042 if(result == OC_STACK_OK)
1044 OIC_LOG(INFO, TAG, "Removed observer successfully");
1045 request->observeResult = OC_STACK_OK;
1046 // There should be no observe option header for de-registration response.
1047 // Set as an invalid value here so we can detect it later and remove the field in response.
1048 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1052 request->observeResult = OC_STACK_ERROR;
1053 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1054 FindAndDeleteServerRequest(request);
1060 result = OC_STACK_ERROR;
1064 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1065 if(ehResult == OC_EH_SLOW)
1067 OIC_LOG(INFO, TAG, "This is a slow resource");
1068 request->slowFlag = 1;
1070 else if(ehResult == OC_EH_ERROR)
1072 FindAndDeleteServerRequest(request);
1074 result = EntityHandlerCodeToOCStackCode(ehResult);
1076 OCPayloadDestroy(ehRequest.payload);
1080 static OCStackResult
1081 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1082 OCResource *resource)
1084 if(!request || !resource)
1086 return OC_STACK_INVALID_PARAM;
1089 OCStackResult result = OC_STACK_ERROR;
1090 OCEntityHandlerRequest ehRequest = {0};
1092 result = FormOCEntityHandlerRequest(&ehRequest,
1093 (OCRequestHandle)request,
1096 (OCResourceHandle)resource,
1098 PAYLOAD_TYPE_REPRESENTATION,
1100 request->payloadSize,
1101 request->numRcvdVendorSpecificHeaderOptions,
1102 request->rcvdVendorSpecificHeaderOptions,
1103 (OCObserveAction)request->observationOption,
1106 if(result == OC_STACK_OK)
1108 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1111 OCPayloadDestroy(ehRequest.payload);
1116 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1118 OCStackResult ret = OC_STACK_OK;
1120 switch (resHandling)
1122 case OC_RESOURCE_VIRTUAL:
1124 ret = HandleVirtualResource (request, resource);
1127 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1129 ret = HandleDefaultDeviceEntityHandler(request);
1132 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1134 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1135 return OC_STACK_ERROR;
1137 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1139 ret = HandleResourceWithEntityHandler (request, resource, 0);
1142 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1144 ret = HandleResourceWithEntityHandler (request, resource, 1);
1147 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1149 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1152 case OC_RESOURCE_NOT_SPECIFIED:
1154 ret = OC_STACK_NO_RESOURCE;
1159 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1160 return OC_STACK_ERROR;
1166 void DeletePlatformInfo()
1168 OIC_LOG(INFO, TAG, "Deleting platform info.");
1170 OICFree(savedPlatformInfo.platformID);
1171 savedPlatformInfo.platformID = NULL;
1173 OICFree(savedPlatformInfo.manufacturerName);
1174 savedPlatformInfo.manufacturerName = NULL;
1176 OICFree(savedPlatformInfo.manufacturerUrl);
1177 savedPlatformInfo.manufacturerUrl = NULL;
1179 OICFree(savedPlatformInfo.modelNumber);
1180 savedPlatformInfo.modelNumber = NULL;
1182 OICFree(savedPlatformInfo.dateOfManufacture);
1183 savedPlatformInfo.dateOfManufacture = NULL;
1185 OICFree(savedPlatformInfo.platformVersion);
1186 savedPlatformInfo.platformVersion = NULL;
1188 OICFree(savedPlatformInfo.operatingSystemVersion);
1189 savedPlatformInfo.operatingSystemVersion = NULL;
1191 OICFree(savedPlatformInfo.hardwareVersion);
1192 savedPlatformInfo.hardwareVersion = NULL;
1194 OICFree(savedPlatformInfo.firmwareVersion);
1195 savedPlatformInfo.firmwareVersion = NULL;
1197 OICFree(savedPlatformInfo.supportUrl);
1198 savedPlatformInfo.supportUrl = NULL;
1200 OICFree(savedPlatformInfo.systemTime);
1201 savedPlatformInfo.systemTime = NULL;
1204 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1206 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1207 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1208 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1209 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1210 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1211 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1212 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1213 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1214 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1215 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1216 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1218 if ((!savedPlatformInfo.platformID && info.platformID)||
1219 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1220 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1221 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1222 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1223 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1224 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1225 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1226 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1227 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1228 (!savedPlatformInfo.systemTime && info.systemTime))
1230 DeletePlatformInfo();
1231 return OC_STACK_INVALID_PARAM;
1238 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1240 DeletePlatformInfo();
1242 OCStackResult res = DeepCopyPlatFormInfo(info);
1244 if (res != OC_STACK_OK)
1246 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1250 OIC_LOG(INFO, TAG, "Platform info saved.");
1256 void DeleteDeviceInfo()
1258 OIC_LOG(INFO, TAG, "Deleting device info.");
1260 OICFree(savedDeviceInfo.deviceName);
1261 OCFreeOCStringLL(savedDeviceInfo.types);
1262 OICFree(savedDeviceInfo.specVersion);
1263 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1264 savedDeviceInfo.deviceName = NULL;
1265 savedDeviceInfo.specVersion = NULL;
1266 savedDeviceInfo.dataModelVersions = NULL;
1269 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1271 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1273 if(!savedDeviceInfo.deviceName && info.deviceName)
1276 return OC_STACK_NO_MEMORY;
1281 savedDeviceInfo.types = CloneOCStringLL(info.types);
1282 OCStringLL *type = info.types;
1286 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1294 // Append the oic.wk.d at the start of rt link parameter value.
1295 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1299 return OC_STACK_NO_MEMORY;
1301 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1305 return OC_STACK_NO_MEMORY;
1307 dest->next = savedDeviceInfo.types;
1308 savedDeviceInfo.types = dest;
1310 if(!savedDeviceInfo.types && info.types)
1313 return OC_STACK_NO_MEMORY;
1317 if (info.specVersion)
1319 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1320 if(!savedDeviceInfo.specVersion && info.specVersion)
1323 return OC_STACK_NO_MEMORY;
1328 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1329 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1332 return OC_STACK_NO_MEMORY;
1336 if (info.dataModelVersions)
1338 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1339 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1342 return OC_STACK_NO_MEMORY;
1347 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1348 if (!savedDeviceInfo.dataModelVersions)
1350 return OC_STACK_NO_MEMORY;
1352 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1353 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1356 return OC_STACK_NO_MEMORY;
1363 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1365 OCStackResult res = OC_STACK_OK;
1369 res = DeepCopyDeviceInfo(info);
1371 VERIFY_SUCCESS(res, OC_STACK_OK);
1373 if (OCGetServerInstanceIDString() == NULL)
1375 OIC_LOG(INFO, TAG, "Device ID generation failed");
1376 res = OC_STACK_ERROR;
1380 OIC_LOG(INFO, TAG, "Device initialized successfully.");