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;
476 result = OC_STACK_OK;
479 result = OC_STACK_SLOW_RESOURCE;
482 result = OC_STACK_ERROR;
484 case OC_EH_FORBIDDEN:
485 result = OC_STACK_RESOURCE_ERROR;
487 case OC_EH_RESOURCE_CREATED:
488 result = OC_STACK_RESOURCE_CREATED;
490 case OC_EH_RESOURCE_DELETED:
491 result = OC_STACK_RESOURCE_DELETED;
494 result = OC_STACK_RESOURCE_CHANGED;
496 case OC_EH_RESOURCE_NOT_FOUND:
497 result = OC_STACK_NO_RESOURCE;
500 result = OC_STACK_ERROR;
506 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
513 // Null or empty is analogous to no filter.
514 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
519 OCResourceType *resourceTypePtr = resource->rsrcType;
521 while (resourceTypePtr)
523 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
527 resourceTypePtr = resourceTypePtr->next;
530 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
534 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
541 // Null or empty is analogous to no filter.
542 if (interfaceFilter == NULL || *interfaceFilter == 0)
547 OCResourceInterface *interfacePtr = resource->rsrcInterface;
551 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
552 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
553 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
557 interfacePtr = interfacePtr->next;
560 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
565 * If the filters are null, they will be assumed to NOT be present
566 * and the resource will not be matched against them.
567 * Function will return true if all non null AND non empty filters passed in find a match.
569 static bool includeThisResourceInResponse(OCResource *resource,
570 char *interfaceFilter,
571 char *resourceTypeFilter)
575 OIC_LOG(ERROR, TAG, "Invalid resource");
579 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
582 * At least one valid filter should be available to
583 * include the resource in discovery response
585 if (!(resourceTypeFilter && *resourceTypeFilter))
587 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
588 resource", resource->uri);
592 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
593 !(resource->resourceProperties & OC_DISCOVERABLE))
595 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
599 return resourceMatchesIFFilter(resource, interfaceFilter) &&
600 resourceMatchesRTFilter(resource, resourceTypeFilter);
604 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
605 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
607 OCEntityHandlerResponse response = {0};
609 response.ehResult = ehResult;
610 response.payload = discoveryPayload;
611 response.persistentBufferFlag = 0;
612 response.requestHandle = (OCRequestHandle) request;
613 response.resourceHandle = (OCResourceHandle) resource;
615 return OCDoResponse(&response);
618 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
620 if (!request || !resource)
622 return OC_STACK_INVALID_PARAM;
625 OCStackResult discoveryResult = OC_STACK_ERROR;
626 OCPayload* payload = NULL;
628 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
630 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
632 // Step 1: Generate the response to discovery request
633 if (virtualUriInRequest == OC_WELL_KNOWN_URI
635 || virtualUriInRequest == OC_MQ_BROKER_URI
639 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
641 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
642 return OC_STACK_UNAUTHORIZED_REQ;
645 char *interfaceQuery = NULL;
646 char *resourceTypeQuery = NULL;
648 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
649 &interfaceQuery, &resourceTypeQuery);
650 bool interfaceQueryAllocated = false;
651 if (!interfaceQuery && !resourceTypeQuery)
653 interfaceQueryAllocated = true;
654 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
657 if (discoveryResult == OC_STACK_OK)
659 payload = (OCPayload *)OCDiscoveryPayloadCreate();
663 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
664 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
665 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
667 const char* uid = OCGetServerInstanceIDString();
670 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
673 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
675 OCResourceProperty prop = OC_DISCOVERABLE;
677 if (OC_MQ_BROKER_URI == virtualUriInRequest)
683 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
687 if (resource->resourceProperties & prop)
694 discoveryResult = BuildVirtualResourceResponse(resource,
695 discPayload, &request->devAddr, false);
701 if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
703 discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
704 VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
705 if (savedDeviceInfo.deviceName)
707 discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
708 VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
710 discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
711 VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
712 discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
713 VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
714 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
715 OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
716 VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
718 bool foundResourceAtRD = false;
719 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
721 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
723 discoveryResult = BuildVirtualResourceResponse(resource,
724 discPayload, &request->devAddr, false);
727 // Set discoveryResult appropriately if no 'valid' resources are available
728 if (discPayload->resources == NULL && !foundResourceAtRD)
730 discoveryResult = OC_STACK_NO_RESOURCE;
736 discoveryResult = OC_STACK_NO_MEMORY;
741 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
743 if (interfaceQueryAllocated)
745 OICFree(interfaceQuery);
748 else if (virtualUriInRequest == OC_DEVICE_URI)
750 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
752 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
753 return OC_STACK_UNAUTHORIZED_REQ;
756 const char* deviceId = OCGetServerInstanceIDString();
759 discoveryResult = OC_STACK_ERROR;
763 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
764 if (!dataModelVersions)
766 discoveryResult = OC_STACK_NO_MEMORY;
770 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
771 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
774 discoveryResult = OC_STACK_NO_MEMORY;
778 discoveryResult = OC_STACK_OK;
780 OICFree(dataModelVersions);
784 else if (virtualUriInRequest == OC_PLATFORM_URI)
786 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
788 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
789 return OC_STACK_UNAUTHORIZED_REQ;
792 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
795 discoveryResult = OC_STACK_NO_MEMORY;
799 discoveryResult = OC_STACK_OK;
802 #ifdef ROUTING_GATEWAY
803 else if (OC_GATEWAY_URI == virtualUriInRequest)
805 // Received request for a gateway
806 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
807 discoveryResult = RMHandleGatewayRequest(request, resource);
813 * Step 2: Send the discovery response
815 * Iotivity should respond to discovery requests in below manner:
816 * 1)If query filter matching fails and discovery request is multicast,
817 * it should NOT send any response.
818 * 2)If query filter matching fails and discovery request is unicast,
819 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
820 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
821 * request is multicast, it should NOT send any response.
822 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
823 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
827 if ((virtualUriInRequest == OC_PRESENCE) &&
828 (resource->resourceProperties & OC_ACTIVE))
830 // Presence uses observer notification api to respond via SendPresenceNotification.
831 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
835 #ifdef ROUTING_GATEWAY
836 // Gateway uses the RMHandleGatewayRequest to respond to the request.
837 if (OC_GATEWAY_URI != virtualUriInRequest)
840 if(discoveryResult == OC_STACK_OK)
842 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
844 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
845 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
846 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
848 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
849 discoveryResult, virtualUriInRequest);
850 SendNonPersistantDiscoveryResponse(request, resource, NULL,
851 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
855 // Ignoring the discovery request as per RFC 7252, Section #8.2
856 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
860 OCPayloadDestroy(payload);
866 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
870 return OC_STACK_INVALID_PARAM;
873 OCStackResult result = OC_STACK_OK;
874 OCEntityHandlerResult ehResult = OC_EH_ERROR;
875 OCEntityHandlerRequest ehRequest = {0};
877 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
878 result = FormOCEntityHandlerRequest(&ehRequest,
879 (OCRequestHandle) request,
882 (OCResourceHandle) NULL, request->query,
883 PAYLOAD_TYPE_REPRESENTATION,
885 request->payloadSize,
886 request->numRcvdVendorSpecificHeaderOptions,
887 request->rcvdVendorSpecificHeaderOptions,
888 (OCObserveAction)request->observationOption,
891 VERIFY_SUCCESS(result, OC_STACK_OK);
893 // At this point we know for sure that defaultDeviceHandler exists
894 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
895 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
896 if(ehResult == OC_EH_SLOW)
898 OIC_LOG(INFO, TAG, "This is a slow resource");
899 request->slowFlag = 1;
901 else if(ehResult == OC_EH_ERROR)
903 FindAndDeleteServerRequest(request);
905 result = EntityHandlerCodeToOCStackCode(ehResult);
907 OCPayloadDestroy(ehRequest.payload);
912 HandleResourceWithEntityHandler (OCServerRequest *request,
913 OCResource *resource,
914 uint8_t collectionResource)
916 if(!request || ! resource)
918 return OC_STACK_INVALID_PARAM;
921 OCStackResult result = OC_STACK_ERROR;
922 OCEntityHandlerResult ehResult = OC_EH_ERROR;
923 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
924 ResourceObserver *resObs = NULL;
926 OCEntityHandlerRequest ehRequest = {0};
928 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
929 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
930 // check the security resource
931 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
933 type = PAYLOAD_TYPE_SECURITY;
937 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
939 type = PAYLOAD_TYPE_RD;
942 result = FormOCEntityHandlerRequest(&ehRequest,
943 (OCRequestHandle)request,
946 (OCResourceHandle)resource,
950 request->payloadSize,
951 request->numRcvdVendorSpecificHeaderOptions,
952 request->rcvdVendorSpecificHeaderOptions,
953 (OCObserveAction)request->observationOption,
956 VERIFY_SUCCESS(result, OC_STACK_OK);
958 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
960 OIC_LOG(INFO, TAG, "No observation requested");
961 ehFlag = OC_REQUEST_FLAG;
963 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
965 OIC_LOG(INFO, TAG, "Observation registration requested");
967 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
968 request->tokenLength);
972 OIC_LOG (INFO, TAG, "Observer with this token already present");
973 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
974 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
975 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
977 // server requests are usually free'd when the response is sent out
978 // for the request in ocserverrequest.c : HandleSingleResponse()
979 // Since we are making an early return and not responding, the server request
980 // needs to be deleted.
981 FindAndDeleteServerRequest (request);
985 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
986 VERIFY_SUCCESS(result, OC_STACK_OK);
988 result = AddObserver ((const char*)(request->resourceUrl),
989 (const char *)(request->query),
990 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
991 resource, request->qos, request->acceptFormat,
994 if(result == OC_STACK_OK)
996 OIC_LOG(INFO, TAG, "Added observer successfully");
997 request->observeResult = OC_STACK_OK;
998 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1002 // The error in observeResult for the request will be used when responding to this
1003 // request by omitting the observation option/sequence number.
1004 request->observeResult = OC_STACK_ERROR;
1005 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1006 ehFlag = OC_REQUEST_FLAG;
1007 FindAndDeleteServerRequest(request);
1012 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1013 !collectionResource)
1015 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1017 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1021 // Stack does not contain this observation request
1022 // Either token is incorrect or observation list is corrupted
1023 result = OC_STACK_ERROR;
1026 ehRequest.obsInfo.obsId = resObs->observeId;
1027 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1029 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1031 if(result == OC_STACK_OK)
1033 OIC_LOG(INFO, TAG, "Removed observer successfully");
1034 request->observeResult = OC_STACK_OK;
1035 // There should be no observe option header for de-registration response.
1036 // Set as an invalid value here so we can detect it later and remove the field in response.
1037 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1041 request->observeResult = OC_STACK_ERROR;
1042 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1043 FindAndDeleteServerRequest(request);
1049 result = OC_STACK_ERROR;
1053 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1054 if(ehResult == OC_EH_SLOW)
1056 OIC_LOG(INFO, TAG, "This is a slow resource");
1057 request->slowFlag = 1;
1059 else if(ehResult == OC_EH_ERROR)
1061 FindAndDeleteServerRequest(request);
1063 result = EntityHandlerCodeToOCStackCode(ehResult);
1065 OCPayloadDestroy(ehRequest.payload);
1069 static OCStackResult
1070 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1071 OCResource *resource)
1073 if(!request || !resource)
1075 return OC_STACK_INVALID_PARAM;
1078 OCStackResult result = OC_STACK_ERROR;
1079 OCEntityHandlerRequest ehRequest = {0};
1081 result = FormOCEntityHandlerRequest(&ehRequest,
1082 (OCRequestHandle)request,
1085 (OCResourceHandle)resource,
1087 PAYLOAD_TYPE_REPRESENTATION,
1089 request->payloadSize,
1090 request->numRcvdVendorSpecificHeaderOptions,
1091 request->rcvdVendorSpecificHeaderOptions,
1092 (OCObserveAction)request->observationOption,
1095 if(result == OC_STACK_OK)
1097 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1100 OCPayloadDestroy(ehRequest.payload);
1105 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1107 OCStackResult ret = OC_STACK_OK;
1109 switch (resHandling)
1111 case OC_RESOURCE_VIRTUAL:
1113 ret = HandleVirtualResource (request, resource);
1116 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1118 ret = HandleDefaultDeviceEntityHandler(request);
1121 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1123 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1124 return OC_STACK_ERROR;
1126 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1128 ret = HandleResourceWithEntityHandler (request, resource, 0);
1131 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1133 ret = HandleResourceWithEntityHandler (request, resource, 1);
1136 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1138 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1141 case OC_RESOURCE_NOT_SPECIFIED:
1143 ret = OC_STACK_NO_RESOURCE;
1148 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1149 return OC_STACK_ERROR;
1155 void DeletePlatformInfo()
1157 OIC_LOG(INFO, TAG, "Deleting platform info.");
1159 OICFree(savedPlatformInfo.platformID);
1160 savedPlatformInfo.platformID = NULL;
1162 OICFree(savedPlatformInfo.manufacturerName);
1163 savedPlatformInfo.manufacturerName = NULL;
1165 OICFree(savedPlatformInfo.manufacturerUrl);
1166 savedPlatformInfo.manufacturerUrl = NULL;
1168 OICFree(savedPlatformInfo.modelNumber);
1169 savedPlatformInfo.modelNumber = NULL;
1171 OICFree(savedPlatformInfo.dateOfManufacture);
1172 savedPlatformInfo.dateOfManufacture = NULL;
1174 OICFree(savedPlatformInfo.platformVersion);
1175 savedPlatformInfo.platformVersion = NULL;
1177 OICFree(savedPlatformInfo.operatingSystemVersion);
1178 savedPlatformInfo.operatingSystemVersion = NULL;
1180 OICFree(savedPlatformInfo.hardwareVersion);
1181 savedPlatformInfo.hardwareVersion = NULL;
1183 OICFree(savedPlatformInfo.firmwareVersion);
1184 savedPlatformInfo.firmwareVersion = NULL;
1186 OICFree(savedPlatformInfo.supportUrl);
1187 savedPlatformInfo.supportUrl = NULL;
1189 OICFree(savedPlatformInfo.systemTime);
1190 savedPlatformInfo.systemTime = NULL;
1193 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1195 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1196 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1197 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1198 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1199 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1200 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1201 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1202 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1203 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1204 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1205 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1207 if ((!savedPlatformInfo.platformID && info.platformID)||
1208 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1209 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1210 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1211 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1212 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1213 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1214 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1215 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1216 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1217 (!savedPlatformInfo.systemTime && info.systemTime))
1219 DeletePlatformInfo();
1220 return OC_STACK_INVALID_PARAM;
1227 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1229 DeletePlatformInfo();
1231 OCStackResult res = DeepCopyPlatFormInfo(info);
1233 if (res != OC_STACK_OK)
1235 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1239 OIC_LOG(INFO, TAG, "Platform info saved.");
1245 void DeleteDeviceInfo()
1247 OIC_LOG(INFO, TAG, "Deleting device info.");
1249 OICFree(savedDeviceInfo.deviceName);
1250 OCFreeOCStringLL(savedDeviceInfo.types);
1251 OICFree(savedDeviceInfo.specVersion);
1252 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1253 savedDeviceInfo.deviceName = NULL;
1254 savedDeviceInfo.specVersion = NULL;
1255 savedDeviceInfo.dataModelVersions = NULL;
1258 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1260 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1262 if(!savedDeviceInfo.deviceName && info.deviceName)
1265 return OC_STACK_NO_MEMORY;
1270 savedDeviceInfo.types = CloneOCStringLL(info.types);
1271 OCStringLL *type = info.types;
1275 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1283 // Append the oic.wk.d at the start of rt link parameter value.
1284 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1288 return OC_STACK_NO_MEMORY;
1290 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1294 return OC_STACK_NO_MEMORY;
1296 dest->next = savedDeviceInfo.types;
1297 savedDeviceInfo.types = dest;
1299 if(!savedDeviceInfo.types && info.types)
1302 return OC_STACK_NO_MEMORY;
1306 if (info.specVersion)
1308 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1309 if(!savedDeviceInfo.specVersion && info.specVersion)
1312 return OC_STACK_NO_MEMORY;
1317 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1318 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1321 return OC_STACK_NO_MEMORY;
1325 if (info.dataModelVersions)
1327 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1328 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1331 return OC_STACK_NO_MEMORY;
1336 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1337 if (!savedDeviceInfo.dataModelVersions)
1339 return OC_STACK_NO_MEMORY;
1341 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1342 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1345 return OC_STACK_NO_MEMORY;
1352 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1354 OCStackResult res = OC_STACK_OK;
1358 res = DeepCopyDeviceInfo(info);
1360 VERIFY_SUCCESS(res, OC_STACK_OK);
1362 if (OCGetServerInstanceIDString() == NULL)
1364 OIC_LOG(INFO, TAG, "Device ID generation failed");
1365 res = OC_STACK_ERROR;
1369 OIC_LOG(INFO, TAG, "Device initialized successfully.");