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
36 #include "ocresource.h"
37 #include "ocresourcehandler.h"
38 #include "ocobserve.h"
39 #include "occollection.h"
40 #include "oic_malloc.h"
41 #include "oic_string.h"
44 #include "ocpayload.h"
45 #include "secureresourcemanager.h"
47 #include "cainterface.h"
48 #include "ocpayload.h"
50 #ifdef ROUTING_GATEWAY
51 #include "routingmanager.h"
55 #define TAG "OIC_RI_RESOURCE"
57 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
58 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
60 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
61 TAG, #arg " is NULL"); return (retVal); } }
63 #include "platform_features.h"
65 extern OCResource *headResource;
66 static OCPlatformInfo savedPlatformInfo = {0};
67 static OCDeviceInfo savedDeviceInfo = {0};
70 * Prepares a Payload for response.
72 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
73 OCDiscoveryPayload* payload,
77 //-----------------------------------------------------------------------------
78 // Default resource entity handler function
79 //-----------------------------------------------------------------------------
80 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
81 OCEntityHandlerRequest * request, void* callbackParam)
83 //TODO ("Implement me!!!!");
84 // TODO: remove silence unused param warnings
88 return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
91 /* This method will retrieve the port at which the secure resource is hosted */
92 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
96 if (endpoint->adapter == OC_ADAPTER_IP)
98 if (endpoint->flags & OC_IP_USE_V6)
100 p = caglobals.ip.u6s.port;
102 else if (endpoint->flags & OC_IP_USE_V4)
104 p = caglobals.ip.u4s.port;
113 /* This method will retrieve the tcp port */
114 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
118 if (endpoint->adapter == OC_ADAPTER_IP)
120 if (endpoint->flags & OC_IP_USE_V4)
122 p = caglobals.tcp.ipv4.port;
124 else if (endpoint->flags & OC_IP_USE_V6)
126 p = caglobals.tcp.ipv6.port;
136 * Function will extract 0, 1 or 2 filters from query.
137 * More than 2 filters or unsupported filters will result in error.
138 * If both filters are of the same supported type, the 2nd one will be picked.
139 * Resource and device filters in the SAME query are NOT validated
140 * and resources will likely not clear filters.
142 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
147 char *restOfQuery = NULL;
148 int numKeyValuePairsParsed = 0;
153 OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
155 if (strnlen(query, MAX_QUERY_LENGTH) >= MAX_QUERY_LENGTH)
157 OIC_LOG(ERROR, TAG, "Query exceeds maximum length.");
158 return OC_STACK_INVALID_QUERY;
161 char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
165 if (numKeyValuePairsParsed >= 2)
167 OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
168 return OC_STACK_INVALID_QUERY;
171 key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
175 return OC_STACK_INVALID_QUERY;
177 else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
179 *filterOne = value; // if
181 else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
183 *filterTwo = value; // rt
187 OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
188 return OC_STACK_INVALID_QUERY;
190 ++numKeyValuePairsParsed;
192 keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
195 OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
199 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
201 if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
203 return OC_WELL_KNOWN_URI;
205 else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
207 return OC_DEVICE_URI;
209 else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
211 return OC_PLATFORM_URI;
213 else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
215 return OC_RESOURCE_TYPES_URI;
217 #ifdef ROUTING_GATEWAY
218 else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
220 return OC_GATEWAY_URI;
224 else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
228 #endif //WITH_PRESENCE
231 else if (0 == strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_MQ_URI))
233 return OC_MQ_BROKER_URI;
236 return OC_UNKNOWN_URI;
239 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
240 char **filterOne, char **filterTwo)
242 if(!filterOne || !filterTwo)
244 return OC_STACK_INVALID_PARAM;
251 if (uri == OC_PRESENCE)
253 //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
254 OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
259 OCStackResult result = OC_STACK_OK;
263 result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
269 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
270 OCRepPayload** payload)
272 OCRepPayload *tempPayload = OCRepPayloadCreate();
276 OCRepPayloadDestroy(tempPayload);
277 return OC_STACK_INVALID_PARAM;
282 return OC_STACK_NO_MEMORY;
285 OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
287 OCResourceType *resType = resourcePtr->rsrcType;
290 OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
291 resType = resType->next;
294 OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
297 OCRepPayloadAddInterface(tempPayload, resInterface->name);
298 resInterface = resInterface->next;
301 OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
304 OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
305 resAttrib->attrValue);
306 resAttrib = resAttrib->next;
311 *payload = tempPayload;
315 OCRepPayloadAppend(*payload, tempPayload);
321 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
322 OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
324 if (!resourcePtr || !payload)
326 return OC_STACK_INVALID_PARAM;
328 uint16_t securePort = 0;
329 if (resourcePtr->resourceProperties & OC_SECURE)
331 if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
339 securePort = devAddr->port;
342 uint16_t tcpPort = 0;
344 if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
348 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
350 OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
356 uint8_t IsCollectionResource (OCResource *resource)
363 if(resource->rsrcChildResourcesHead != NULL)
371 OCResource *FindResourceByUri(const char* resourceUri)
378 OCResource * pointer = headResource;
381 if (strcmp(resourceUri, pointer->uri) == 0)
385 pointer = pointer->next;
387 OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
392 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
393 ResourceHandling *handling,
394 OCResource **resource)
396 if(!request || !handling || !resource)
398 return OC_STACK_INVALID_PARAM;
401 OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
403 // Check if virtual resource
404 if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
406 OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
407 *handling = OC_RESOURCE_VIRTUAL;
408 *resource = headResource;
411 if (strlen((const char*)(request->resourceUrl)) == 0)
413 // Resource URL not specified
414 *handling = OC_RESOURCE_NOT_SPECIFIED;
415 return OC_STACK_NO_RESOURCE;
419 OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
420 *resource = resourcePtr;
423 if(defaultDeviceHandler)
425 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
429 // Resource does not exist
430 // and default device handler does not exist
431 *handling = OC_RESOURCE_NOT_SPECIFIED;
432 return OC_STACK_NO_RESOURCE;
435 if (IsCollectionResource (resourcePtr))
437 // Collection resource
438 if (resourcePtr->entityHandler != defaultResourceEHandler)
440 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
445 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
451 // Resource not a collection
452 if (resourcePtr->entityHandler != defaultResourceEHandler)
454 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
459 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
466 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
468 OCStackResult result;
473 result = OC_STACK_OK;
476 result = OC_STACK_SLOW_RESOURCE;
479 result = OC_STACK_ERROR;
481 case OC_EH_FORBIDDEN:
482 result = OC_STACK_RESOURCE_ERROR;
484 case OC_EH_RESOURCE_CREATED:
485 result = OC_STACK_RESOURCE_CREATED;
487 case OC_EH_RESOURCE_DELETED:
488 result = OC_STACK_RESOURCE_DELETED;
491 result = OC_STACK_RESOURCE_CHANGED;
493 case OC_EH_RESOURCE_NOT_FOUND:
494 result = OC_STACK_NO_RESOURCE;
497 result = OC_STACK_ERROR;
503 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
510 // Null or empty is analogous to no filter.
511 if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
516 OCResourceType *resourceTypePtr = resource->rsrcType;
518 while (resourceTypePtr)
520 if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
524 resourceTypePtr = resourceTypePtr->next;
527 OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
531 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
538 // Null or empty is analogous to no filter.
539 if (interfaceFilter == NULL || *interfaceFilter == 0)
544 OCResourceInterface *interfacePtr = resource->rsrcInterface;
548 if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
549 (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
550 strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
554 interfacePtr = interfacePtr->next;
557 OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
562 * If the filters are null, they will be assumed to NOT be present
563 * and the resource will not be matched against them.
564 * Function will return true if all non null AND non empty filters passed in find a match.
566 static bool includeThisResourceInResponse(OCResource *resource,
567 char *interfaceFilter,
568 char *resourceTypeFilter)
572 OIC_LOG(ERROR, TAG, "Invalid resource");
576 if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
579 * At least one valid filter should be available to
580 * include the resource in discovery response
582 if (!(resourceTypeFilter && *resourceTypeFilter))
584 OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
585 resource", resource->uri);
589 else if ( !(resource->resourceProperties & OC_ACTIVE) ||
590 !(resource->resourceProperties & OC_DISCOVERABLE))
592 OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
596 return resourceMatchesIFFilter(resource, interfaceFilter) &&
597 resourceMatchesRTFilter(resource, resourceTypeFilter);
601 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
602 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
604 OCEntityHandlerResponse response = {0};
606 response.ehResult = ehResult;
607 response.payload = discoveryPayload;
608 response.persistentBufferFlag = 0;
609 response.requestHandle = (OCRequestHandle) request;
610 response.resourceHandle = (OCResourceHandle) resource;
612 return OCDoResponse(&response);
615 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
617 if (!request || !resource)
619 return OC_STACK_INVALID_PARAM;
622 OCStackResult discoveryResult = OC_STACK_ERROR;
623 OCPayload* payload = NULL;
625 OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
627 OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
629 // Step 1: Generate the response to discovery request
630 if (virtualUriInRequest == OC_WELL_KNOWN_URI
632 || virtualUriInRequest == OC_MQ_BROKER_URI
636 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
638 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
639 return OC_STACK_UNAUTHORIZED_REQ;
642 char *interfaceQuery = NULL;
643 char *resourceTypeQuery = NULL;
645 discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
646 &interfaceQuery, &resourceTypeQuery);
647 bool interfaceQueryAllocated = false;
648 if (!interfaceQuery && !resourceTypeQuery)
650 interfaceQueryAllocated = true;
651 interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
654 if (discoveryResult == OC_STACK_OK)
656 payload = (OCPayload *)OCDiscoveryPayloadCreate();
660 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
661 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
662 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
664 const char* uid = OCGetServerInstanceIDString();
667 memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
670 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
672 OCResourceProperty prop = OC_DISCOVERABLE;
674 if (OC_MQ_BROKER_URI == virtualUriInRequest)
680 for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
684 if (resource->resourceProperties & prop)
691 discoveryResult = BuildVirtualResourceResponse(resource,
692 discPayload, &request->devAddr, false);
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 bool foundResourceAtRD = false;
716 for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
718 if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
720 discoveryResult = BuildVirtualResourceResponse(resource,
721 discPayload, &request->devAddr, false);
724 // Set discoveryResult appropriately if no 'valid' resources are available
725 if (discPayload->resources == NULL && !foundResourceAtRD)
727 discoveryResult = OC_STACK_NO_RESOURCE;
733 discoveryResult = OC_STACK_NO_MEMORY;
738 OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
740 if (interfaceQueryAllocated)
742 OICFree(interfaceQuery);
745 else if (virtualUriInRequest == OC_DEVICE_URI)
747 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
749 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
750 return OC_STACK_UNAUTHORIZED_REQ;
753 const char* deviceId = OCGetServerInstanceIDString();
756 discoveryResult = OC_STACK_ERROR;
760 char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
761 if (!dataModelVersions)
763 discoveryResult = OC_STACK_NO_MEMORY;
767 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
768 savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
771 discoveryResult = OC_STACK_NO_MEMORY;
775 discoveryResult = OC_STACK_OK;
777 OICFree(dataModelVersions);
781 else if (virtualUriInRequest == OC_PLATFORM_URI)
783 if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
785 OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
786 return OC_STACK_UNAUTHORIZED_REQ;
789 payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
792 discoveryResult = OC_STACK_NO_MEMORY;
796 discoveryResult = OC_STACK_OK;
799 #ifdef ROUTING_GATEWAY
800 else if (OC_GATEWAY_URI == virtualUriInRequest)
802 // Received request for a gateway
803 OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
804 discoveryResult = RMHandleGatewayRequest(request, resource);
810 * Step 2: Send the discovery response
812 * Iotivity should respond to discovery requests in below manner:
813 * 1)If query filter matching fails and discovery request is multicast,
814 * it should NOT send any response.
815 * 2)If query filter matching fails and discovery request is unicast,
816 * it should send an error(RESOURCE_NOT_FOUND - 404) response.
817 * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
818 * request is multicast, it should NOT send any response.
819 * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
820 * request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
824 if ((virtualUriInRequest == OC_PRESENCE) &&
825 (resource->resourceProperties & OC_ACTIVE))
827 // Presence uses observer notification api to respond via SendPresenceNotification.
828 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
832 #ifdef ROUTING_GATEWAY
833 // Gateway uses the RMHandleGatewayRequest to respond to the request.
834 if (OC_GATEWAY_URI != virtualUriInRequest)
837 if(discoveryResult == OC_STACK_OK)
839 SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
841 else if(((request->devAddr.flags & OC_MULTICAST) == false) &&
842 (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
843 (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
845 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
846 discoveryResult, virtualUriInRequest);
847 SendNonPersistantDiscoveryResponse(request, resource, NULL,
848 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
852 // Ignoring the discovery request as per RFC 7252, Section #8.2
853 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
857 OCPayloadDestroy(payload);
863 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
867 return OC_STACK_INVALID_PARAM;
870 OCStackResult result = OC_STACK_OK;
871 OCEntityHandlerResult ehResult = OC_EH_ERROR;
872 OCEntityHandlerRequest ehRequest = {0};
874 OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
875 result = FormOCEntityHandlerRequest(&ehRequest,
876 (OCRequestHandle) request,
879 (OCResourceHandle) NULL, request->query,
880 PAYLOAD_TYPE_REPRESENTATION,
882 request->payloadSize,
883 request->numRcvdVendorSpecificHeaderOptions,
884 request->rcvdVendorSpecificHeaderOptions,
885 (OCObserveAction)request->observationOption,
888 VERIFY_SUCCESS(result, OC_STACK_OK);
890 // At this point we know for sure that defaultDeviceHandler exists
891 ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
892 (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
893 if(ehResult == OC_EH_SLOW)
895 OIC_LOG(INFO, TAG, "This is a slow resource");
896 request->slowFlag = 1;
898 else if(ehResult == OC_EH_ERROR)
900 FindAndDeleteServerRequest(request);
902 result = EntityHandlerCodeToOCStackCode(ehResult);
904 OCPayloadDestroy(ehRequest.payload);
909 HandleResourceWithEntityHandler (OCServerRequest *request,
910 OCResource *resource,
911 uint8_t collectionResource)
913 if(!request || ! resource)
915 return OC_STACK_INVALID_PARAM;
918 OCStackResult result = OC_STACK_ERROR;
919 OCEntityHandlerResult ehResult = OC_EH_ERROR;
920 OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
921 ResourceObserver *resObs = NULL;
923 OCEntityHandlerRequest ehRequest = {0};
925 OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
926 OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
927 // check the security resource
928 if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
930 type = PAYLOAD_TYPE_SECURITY;
934 if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
936 type = PAYLOAD_TYPE_RD;
939 result = FormOCEntityHandlerRequest(&ehRequest,
940 (OCRequestHandle)request,
943 (OCResourceHandle)resource,
947 request->payloadSize,
948 request->numRcvdVendorSpecificHeaderOptions,
949 request->rcvdVendorSpecificHeaderOptions,
950 (OCObserveAction)request->observationOption,
953 VERIFY_SUCCESS(result, OC_STACK_OK);
955 if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
957 OIC_LOG(INFO, TAG, "No observation requested");
958 ehFlag = OC_REQUEST_FLAG;
960 else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
962 OIC_LOG(INFO, TAG, "Observation registration requested");
964 ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
965 request->tokenLength);
969 OIC_LOG (INFO, TAG, "Observer with this token already present");
970 OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
971 OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
972 OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
974 // server requests are usually free'd when the response is sent out
975 // for the request in ocserverrequest.c : HandleSingleResponse()
976 // Since we are making an early return and not responding, the server request
977 // needs to be deleted.
978 FindAndDeleteServerRequest (request);
982 result = GenerateObserverId(&ehRequest.obsInfo.obsId);
983 VERIFY_SUCCESS(result, OC_STACK_OK);
985 result = AddObserver ((const char*)(request->resourceUrl),
986 (const char *)(request->query),
987 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
988 resource, request->qos, request->acceptFormat,
991 if(result == OC_STACK_OK)
993 OIC_LOG(INFO, TAG, "Added observer successfully");
994 request->observeResult = OC_STACK_OK;
995 ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
999 // The error in observeResult for the request will be used when responding to this
1000 // request by omitting the observation option/sequence number.
1001 request->observeResult = OC_STACK_ERROR;
1002 OIC_LOG(ERROR, TAG, "Observer Addition failed");
1003 ehFlag = OC_REQUEST_FLAG;
1004 FindAndDeleteServerRequest(request);
1009 else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1010 !collectionResource)
1012 OIC_LOG(INFO, TAG, "Deregistering observation requested");
1014 resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1018 // Stack does not contain this observation request
1019 // Either token is incorrect or observation list is corrupted
1020 result = OC_STACK_ERROR;
1023 ehRequest.obsInfo.obsId = resObs->observeId;
1024 ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1026 result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1028 if(result == OC_STACK_OK)
1030 OIC_LOG(INFO, TAG, "Removed observer successfully");
1031 request->observeResult = OC_STACK_OK;
1032 // There should be no observe option header for de-registration response.
1033 // Set as an invalid value here so we can detect it later and remove the field in response.
1034 request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1038 request->observeResult = OC_STACK_ERROR;
1039 OIC_LOG(ERROR, TAG, "Observer Removal failed");
1040 FindAndDeleteServerRequest(request);
1046 result = OC_STACK_ERROR;
1050 ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1051 if(ehResult == OC_EH_SLOW)
1053 OIC_LOG(INFO, TAG, "This is a slow resource");
1054 request->slowFlag = 1;
1056 else if(ehResult == OC_EH_ERROR)
1058 FindAndDeleteServerRequest(request);
1060 result = EntityHandlerCodeToOCStackCode(ehResult);
1062 OCPayloadDestroy(ehRequest.payload);
1066 static OCStackResult
1067 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1068 OCResource *resource)
1070 if(!request || !resource)
1072 return OC_STACK_INVALID_PARAM;
1075 OCStackResult result = OC_STACK_ERROR;
1076 OCEntityHandlerRequest ehRequest = {0};
1078 result = FormOCEntityHandlerRequest(&ehRequest,
1079 (OCRequestHandle)request,
1082 (OCResourceHandle)resource,
1084 PAYLOAD_TYPE_REPRESENTATION,
1086 request->payloadSize,
1087 request->numRcvdVendorSpecificHeaderOptions,
1088 request->rcvdVendorSpecificHeaderOptions,
1089 (OCObserveAction)request->observationOption,
1092 if(result == OC_STACK_OK)
1094 result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1097 OCPayloadDestroy(ehRequest.payload);
1102 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1104 OCStackResult ret = OC_STACK_OK;
1106 switch (resHandling)
1108 case OC_RESOURCE_VIRTUAL:
1110 ret = HandleVirtualResource (request, resource);
1113 case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1115 ret = HandleDefaultDeviceEntityHandler(request);
1118 case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1120 OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1121 return OC_STACK_ERROR;
1123 case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1125 ret = HandleResourceWithEntityHandler (request, resource, 0);
1128 case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1130 ret = HandleResourceWithEntityHandler (request, resource, 1);
1133 case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1135 ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1138 case OC_RESOURCE_NOT_SPECIFIED:
1140 ret = OC_STACK_NO_RESOURCE;
1145 OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1146 return OC_STACK_ERROR;
1152 void DeletePlatformInfo()
1154 OIC_LOG(INFO, TAG, "Deleting platform info.");
1156 OICFree(savedPlatformInfo.platformID);
1157 savedPlatformInfo.platformID = NULL;
1159 OICFree(savedPlatformInfo.manufacturerName);
1160 savedPlatformInfo.manufacturerName = NULL;
1162 OICFree(savedPlatformInfo.manufacturerUrl);
1163 savedPlatformInfo.manufacturerUrl = NULL;
1165 OICFree(savedPlatformInfo.modelNumber);
1166 savedPlatformInfo.modelNumber = NULL;
1168 OICFree(savedPlatformInfo.dateOfManufacture);
1169 savedPlatformInfo.dateOfManufacture = NULL;
1171 OICFree(savedPlatformInfo.platformVersion);
1172 savedPlatformInfo.platformVersion = NULL;
1174 OICFree(savedPlatformInfo.operatingSystemVersion);
1175 savedPlatformInfo.operatingSystemVersion = NULL;
1177 OICFree(savedPlatformInfo.hardwareVersion);
1178 savedPlatformInfo.hardwareVersion = NULL;
1180 OICFree(savedPlatformInfo.firmwareVersion);
1181 savedPlatformInfo.firmwareVersion = NULL;
1183 OICFree(savedPlatformInfo.supportUrl);
1184 savedPlatformInfo.supportUrl = NULL;
1186 OICFree(savedPlatformInfo.systemTime);
1187 savedPlatformInfo.systemTime = NULL;
1190 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1192 savedPlatformInfo.platformID = OICStrdup(info.platformID);
1193 savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1194 savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1195 savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1196 savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1197 savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1198 savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1199 savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1200 savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1201 savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1202 savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1204 if ((!savedPlatformInfo.platformID && info.platformID)||
1205 (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1206 (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1207 (!savedPlatformInfo.modelNumber && info.modelNumber)||
1208 (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1209 (!savedPlatformInfo.platformVersion && info.platformVersion)||
1210 (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1211 (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1212 (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1213 (!savedPlatformInfo.supportUrl && info.supportUrl)||
1214 (!savedPlatformInfo.systemTime && info.systemTime))
1216 DeletePlatformInfo();
1217 return OC_STACK_INVALID_PARAM;
1224 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1226 DeletePlatformInfo();
1228 OCStackResult res = DeepCopyPlatFormInfo(info);
1230 if (res != OC_STACK_OK)
1232 OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1236 OIC_LOG(INFO, TAG, "Platform info saved.");
1242 void DeleteDeviceInfo()
1244 OIC_LOG(INFO, TAG, "Deleting device info.");
1246 OICFree(savedDeviceInfo.deviceName);
1247 OCFreeOCStringLL(savedDeviceInfo.types);
1248 OICFree(savedDeviceInfo.specVersion);
1249 OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1250 savedDeviceInfo.deviceName = NULL;
1251 savedDeviceInfo.specVersion = NULL;
1252 savedDeviceInfo.dataModelVersions = NULL;
1255 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1257 savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1259 if(!savedDeviceInfo.deviceName && info.deviceName)
1262 return OC_STACK_NO_MEMORY;
1267 savedDeviceInfo.types = CloneOCStringLL(info.types);
1268 OCStringLL *type = info.types;
1272 if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1280 // Append the oic.wk.d at the start of rt link parameter value.
1281 OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1285 return OC_STACK_NO_MEMORY;
1287 dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1291 return OC_STACK_NO_MEMORY;
1293 dest->next = savedDeviceInfo.types;
1294 savedDeviceInfo.types = dest;
1296 if(!savedDeviceInfo.types && info.types)
1299 return OC_STACK_NO_MEMORY;
1303 if (info.specVersion)
1305 savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1306 if(!savedDeviceInfo.specVersion && info.specVersion)
1309 return OC_STACK_NO_MEMORY;
1314 savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1315 if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1318 return OC_STACK_NO_MEMORY;
1322 if (info.dataModelVersions)
1324 savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1325 if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1328 return OC_STACK_NO_MEMORY;
1333 savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1334 if (!savedDeviceInfo.dataModelVersions)
1336 return OC_STACK_NO_MEMORY;
1338 savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1339 if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1342 return OC_STACK_NO_MEMORY;
1349 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1351 OCStackResult res = OC_STACK_OK;
1355 res = DeepCopyDeviceInfo(info);
1357 VERIFY_SUCCESS(res, OC_STACK_OK);
1359 if (OCGetServerInstanceIDString() == NULL)
1361 OIC_LOG(INFO, TAG, "Device ID generation failed");
1362 res = OC_STACK_ERROR;
1366 OIC_LOG(INFO, TAG, "Device initialized successfully.");