Updated discovery response when filter query does not match.
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocresource.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
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
28 #include "ocresource.h"
29 #include <string.h>
30 #include "ocresourcehandler.h"
31 #include "ocobserve.h"
32 #include "occollection.h"
33 #include "oic_malloc.h"
34 #include "oic_string.h"
35 #include "logger.h"
36 #include "cJSON.h"
37 #include "ocpayload.h"
38
39 #include "cacommon.h"
40 #include "cainterface.h"
41
42
43 /// Module Name
44 #define TAG PCF("ocresource")
45 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
46             {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
47
48 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
49              TAG, PCF(#arg " is NULL")); return (retVal); } }
50
51 extern OCResource *headResource;
52 static OCPlatformInfo savedPlatformInfo = {};
53 static OCDeviceInfo savedDeviceInfo = {};
54
55 //-----------------------------------------------------------------------------
56 // Default resource entity handler function
57 //-----------------------------------------------------------------------------
58 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
59         OCEntityHandlerRequest * request, void* callbackParam)
60 {
61     //TODO ("Implement me!!!!");
62     // TODO:  remove silence unused param warnings
63     (void) flag;
64     (void) request;
65     (void) callbackParam;
66     return  OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
67 }
68
69 /* This method will retrieve the port at which the secure resource is hosted */
70 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
71 {
72     uint16_t p = 0;
73
74     if (endpoint->adapter == OC_ADAPTER_IP)
75     {
76         if (endpoint->flags & OC_IP_USE_V6)
77         {
78             p = caglobals.ip.u6s.port;
79         }
80         else if (endpoint->flags & OC_IP_USE_V4)
81         {
82             p = caglobals.ip.u4s.port;
83         }
84     }
85
86     *port = p;
87     return OC_STACK_OK;
88 }
89
90 /*
91  * Function will extract 0, 1 or 2 filters from query.
92  * More than 2 filters or unsupported filters will result in error.
93  * If both filters are of the same supported type, the 2nd one will be picked.
94  * Resource and device filters in the SAME query are NOT validated
95  * and resources will likely not clear filters.
96  */
97 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
98 {
99
100     char *key = NULL;
101     char *value = NULL;
102     char *restOfQuery = NULL;
103     int numKeyValuePairsParsed = 0;
104
105     *filterOne = NULL;
106     *filterTwo = NULL;
107
108     OC_LOG_V(INFO, TAG, "Extracting params from %s", query);
109
110     char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
111
112     while(keyValuePair)
113     {
114         if (numKeyValuePairsParsed >= 2)
115         {
116             OC_LOG(ERROR, TAG, PCF("More than 2 queries params in URI."));
117             return OC_STACK_INVALID_QUERY;
118         }
119
120         key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
121
122         if (!key || !value)
123         {
124             return OC_STACK_INVALID_QUERY;
125         }
126         else if (strcmp (key, OC_RSRVD_INTERFACE) == 0)
127         {
128             *filterOne = value;     // if
129         }
130         else if (strcmp (key, OC_RSRVD_RESOURCE_TYPE) == 0)
131         {
132             *filterTwo = value;     // rt
133         }
134         else
135         {
136             OC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
137             return OC_STACK_INVALID_QUERY;
138         }
139         ++numKeyValuePairsParsed;
140
141         keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
142     }
143
144     OC_LOG_V(INFO, TAG, "Extracted params %s and %s.", *filterOne, *filterTwo);
145     return OC_STACK_OK;
146 }
147
148 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
149 {
150     if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
151     {
152         return OC_WELL_KNOWN_URI;
153     }
154     else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
155     {
156         return OC_DEVICE_URI;
157     }
158     else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
159     {
160         return OC_PLATFORM_URI;
161     }
162     else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
163     {
164         return OC_RESOURCE_TYPES_URI;
165     }
166 #ifdef WITH_PRESENCE
167     else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
168     {
169         return OC_PRESENCE;
170     }
171 #endif //WITH_PRESENCE
172     return OC_UNKNOWN_URI;
173 }
174
175 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
176                                             char **filterOne, char **filterTwo)
177 {
178     if(!filterOne || !filterTwo)
179     {
180         return OC_STACK_INVALID_PARAM;
181     }
182
183     *filterOne = NULL;
184     *filterTwo = NULL;
185
186     #ifdef WITH_PRESENCE
187     if (uri == OC_PRESENCE)
188     {
189         //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
190         OC_LOG(INFO, TAG, PCF("OC_PRESENCE Request for virtual resource."));
191         return OC_STACK_OK;
192     }
193     #endif
194
195     OCStackResult result = OC_STACK_OK;
196
197     if (query && *query)
198     {
199         result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
200     }
201
202     return result;
203 }
204
205 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
206                     OCRepPayload** payload)
207 {
208     OCRepPayload *tempPayload = OCRepPayloadCreate();
209
210     if (!resourcePtr)
211     {
212         OCRepPayloadDestroy(tempPayload);
213         return OC_STACK_INVALID_PARAM;
214     }
215
216     if(!tempPayload)
217     {
218         return OC_STACK_NO_MEMORY;
219     }
220
221     OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
222
223     OCResourceType *resType = resourcePtr->rsrcType;
224     while(resType)
225     {
226         OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
227         resType = resType->next;
228     }
229
230     OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
231     while(resInterface)
232     {
233         OCRepPayloadAddInterface(tempPayload, resInterface->name);
234         resInterface = resInterface->next;
235     }
236
237     OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
238     while(resAttrib)
239     {
240         OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
241                                 resAttrib->attrValue);
242         resAttrib = resAttrib->next;
243     }
244
245     if(!*payload)
246     {
247         *payload = tempPayload;
248     }
249     else
250     {
251         OCRepPayloadAppend(*payload, tempPayload);
252     }
253
254     return OC_STACK_OK;
255 }
256
257 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
258                         OCDiscoveryPayload *payload, OCDevAddr *devAddr)
259 {
260     if (!resourcePtr || !payload)
261     {
262         return OC_STACK_INVALID_PARAM;
263     }
264     uint16_t port = 0;
265     if (resourcePtr->resourceProperties & OC_SECURE)
266     {
267        if (GetSecurePortInfo(devAddr, &port) != OC_STACK_OK)
268        {
269            port = 0;
270        }
271     }
272
273     OCDiscoveryPayloadAddResource(payload, resourcePtr, port);
274     return OC_STACK_OK;
275 }
276
277
278 uint8_t IsCollectionResource (OCResource *resource)
279 {
280     if(!resource)
281     {
282         return 0;
283     }
284
285     for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
286     {
287         if (resource->rsrcResources[i])
288         {
289             return 1;
290         }
291     }
292     return 0;
293 }
294
295 OCResource *FindResourceByUri(const char* resourceUri)
296 {
297     if(!resourceUri)
298     {
299         return NULL;
300     }
301
302     OCResource * pointer = headResource;
303     while (pointer)
304     {
305         if (strcmp(resourceUri, pointer->uri) == 0)
306         {
307             return pointer;
308         }
309         pointer = pointer->next;
310     }
311     OC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
312     return NULL;
313 }
314
315
316 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
317                                          ResourceHandling *handling,
318                                          OCResource **resource)
319 {
320     if(!request || !handling || !resource)
321     {
322         return OC_STACK_INVALID_PARAM;
323     }
324
325     OC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
326
327     const OCDevAddr *devAddr = &request->devAddr;
328
329     // Check if virtual resource
330     if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
331     {
332         OC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
333         *handling = OC_RESOURCE_VIRTUAL;
334         *resource = headResource;
335         return OC_STACK_OK;
336     }
337     if (strlen((const char*)(request->resourceUrl)) == 0)
338     {
339         // Resource URL not specified
340         *handling = OC_RESOURCE_NOT_SPECIFIED;
341         return OC_STACK_NO_RESOURCE;
342     }
343     else
344     {
345         OCResource *resourcePtr = NULL;
346         resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
347         *resource = resourcePtr;
348         if (!resourcePtr)
349         {
350             if(defaultDeviceHandler)
351             {
352                 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
353                 return OC_STACK_OK;
354             }
355
356             // Resource does not exist
357             // and default device handler does not exist
358             *handling = OC_RESOURCE_NOT_SPECIFIED;
359             return OC_STACK_NO_RESOURCE;
360         }
361
362         // secure resource will entertain only authorized requests
363         if ((resourcePtr->resourceProperties & OC_SECURE) && ((devAddr->flags & OC_FLAG_SECURE) == 0))
364         {
365             OC_LOG(ERROR, TAG, PCF("Un-authorized request. Ignoring"));
366             return OC_STACK_RESOURCE_ERROR;
367         }
368
369         if (IsCollectionResource (resourcePtr))
370         {
371             // Collection resource
372             if (resourcePtr->entityHandler != defaultResourceEHandler)
373             {
374                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
375                 return OC_STACK_OK;
376             }
377             else
378             {
379                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
380                 return OC_STACK_OK;
381             }
382         }
383         else
384         {
385             // Resource not a collection
386             if (resourcePtr->entityHandler != defaultResourceEHandler)
387             {
388                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
389                 return OC_STACK_OK;
390             }
391             else
392             {
393                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
394                 return OC_STACK_OK;
395             }
396         }
397     }
398 }
399
400 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
401 {
402     OCStackResult result;
403
404     switch (ehResult)
405     {
406         case OC_EH_OK:
407             result = OC_STACK_OK;
408             break;
409         case OC_EH_SLOW:
410             result = OC_STACK_SLOW_RESOURCE;
411             break;
412         case OC_EH_ERROR:
413             result = OC_STACK_ERROR;
414             break;
415         case OC_EH_FORBIDDEN:
416             result = OC_STACK_RESOURCE_ERROR;
417             break;
418         case OC_EH_RESOURCE_CREATED:
419             result = OC_STACK_RESOURCE_CREATED;
420             break;
421         case OC_EH_RESOURCE_DELETED:
422             result = OC_STACK_RESOURCE_DELETED;
423             break;
424         case OC_EH_RESOURCE_NOT_FOUND:
425             result = OC_STACK_NO_RESOURCE;
426             break;
427         default:
428             result = OC_STACK_ERROR;
429     }
430
431     return result;
432 }
433
434 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
435 {
436     if (!resource)
437     {
438         return false;
439     }
440
441     // Null or empty is analogous to no filter.
442     if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
443     {
444         return true;
445     }
446
447     OCResourceType *resourceTypePtr = resource->rsrcType;
448
449     while (resourceTypePtr)
450     {
451         if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
452         {
453             return true;
454         }
455         resourceTypePtr = resourceTypePtr->next;
456     }
457
458     OC_LOG_V(INFO, TAG, PCF("%s does not contain rt=%s."), resource->uri, resourceTypeFilter);
459     return false;
460 }
461
462 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
463 {
464     if (!resource)
465     {
466         return false;
467     }
468
469     // Null or empty is analogous to no filter.
470     if (interfaceFilter == NULL || *interfaceFilter == 0)
471     {
472         return true;
473     }
474
475     OCResourceInterface *interfacePtr = resource->rsrcInterface;
476
477     while (interfacePtr)
478     {
479         if (strcmp (interfacePtr->name, interfaceFilter) == 0)
480         {
481             return true;
482         }
483         interfacePtr = interfacePtr->next;
484     }
485
486     OC_LOG_V(INFO, TAG, PCF("%s does not contain if=%s."), resource->uri, interfaceFilter);
487     return false;
488 }
489
490 /*
491  * If the filters are null, they will be assumed to NOT be present
492  * and the resource will not be matched against them.
493  * Function will return true if all non null AND non empty filters passed in find a match.
494  */
495 static bool includeThisResourceInResponse(OCResource *resource,
496                                                  char *interfaceFilter,
497                                                  char *resourceTypeFilter)
498 {
499     if (!resource)
500     {
501         OC_LOG(ERROR, TAG, PCF("Invalid resource"));
502         return false;
503     }
504
505     if ( !(resource->resourceProperties & OC_ACTIVE) ||
506          !(resource->resourceProperties & OC_DISCOVERABLE))
507     {
508         OC_LOG_V(INFO, TAG, PCF("%s not ACTIVE or DISCOVERABLE"), resource->uri);
509         return false;
510     }
511
512     return resourceMatchesIFFilter(resource, interfaceFilter) &&
513            resourceMatchesRTFilter(resource, resourceTypeFilter);
514
515 }
516
517 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
518                                 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
519 {
520     OCEntityHandlerResponse response = {};
521
522     response.ehResult = ehResult;
523     response.payload = discoveryPayload;
524     response.persistentBufferFlag = 0;
525     response.requestHandle = (OCRequestHandle) request;
526     response.resourceHandle = (OCResourceHandle) resource;
527
528     return OCDoResponse(&response);
529 }
530
531 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
532 {
533     if (!request || !resource)
534     {
535         return OC_STACK_INVALID_PARAM;
536     }
537
538     OCStackResult discoveryResult = OC_STACK_ERROR;
539
540     bool bMulticast    = false;     // Was the discovery request a multicast request?
541     OCPayload* payload = NULL;
542
543     OC_LOG(INFO, TAG, PCF("Entering HandleVirtualResource"));
544
545     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
546
547     // Step 1: Generate the response to discovery request
548     if (virtualUriInRequest == OC_WELL_KNOWN_URI)
549     {
550         char *filterOne = NULL;
551         char *filterTwo = NULL;
552
553         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
554                 &filterOne, &filterTwo);
555
556         if (discoveryResult == OC_STACK_OK)
557         {
558             payload = (OCPayload*)OCDiscoveryPayloadCreate();
559
560             if(payload)
561             {
562                 for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
563                 {
564                     if(includeThisResourceInResponse(resource, filterOne, filterTwo))
565                     {
566                         discoveryResult = BuildVirtualResourceResponse(resource,
567                                 (OCDiscoveryPayload*)payload,
568                                 &request->devAddr);
569                     }
570                 }
571                 // Set discoveryResult appropriately if no 'valid' resources are available.
572                 if (((OCDiscoveryPayload*)payload)->resources == NULL)
573                 {
574                     discoveryResult = OC_STACK_NO_RESOURCE;
575                 }
576             }
577             else
578             {
579                 discoveryResult = OC_STACK_NO_MEMORY;
580             }
581         }
582         else
583         {
584             OC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
585         }
586     }
587     else if (virtualUriInRequest == OC_DEVICE_URI)
588     {
589         payload = (OCPayload*)OCDevicePayloadCreate(OC_RSRVD_DEVICE_URI,
590                 OCGetServerInstanceID(), savedDeviceInfo.deviceName,
591                 OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
592         if (!payload)
593         {
594             discoveryResult = OC_STACK_NO_MEMORY;
595         }
596         else
597         {
598             discoveryResult = OC_STACK_OK;
599         }
600     }
601     else if (virtualUriInRequest == OC_PLATFORM_URI)
602     {
603         payload = (OCPayload*)OCPlatformPayloadCreate(
604                 OC_RSRVD_PLATFORM_URI,
605                 &savedPlatformInfo);
606         if (!payload)
607         {
608             discoveryResult = OC_STACK_NO_MEMORY;
609         }
610         else
611         {
612             discoveryResult = OC_STACK_OK;
613         }
614     }
615
616     /**
617      * Step 2: Send the discovery response
618      *
619      * Iotivity should respond to discovery requests in below manner:
620      * 1)If query filter matching fails and discovery request is multicast,
621      *   it should NOT send any response.
622      * 2)If query filter matching fails and discovery request is unicast,
623      *   it should send an error(RESOURCE_NOT_FOUND - 404) response.
624      * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
625      *   request is multicast, it should NOT send any response.
626      * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
627      *   request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
628      */
629
630     #ifdef WITH_PRESENCE
631     if ((virtualUriInRequest == OC_PRESENCE) &&
632         (resource->resourceProperties & OC_ACTIVE))
633     {
634         // Presence uses observer notification api to respond via SendPresenceNotification.
635         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
636     }
637     else
638     #endif
639     {
640         if(discoveryResult == OC_STACK_OK)
641         {
642             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
643         }
644         else if(bMulticast == false)
645         {
646             OC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d)  \
647                 discovery request", discoveryResult, virtualUriInRequest);
648             SendNonPersistantDiscoveryResponse(request, resource, NULL,
649                 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
650         }
651         else
652         {
653             // Ignoring the discovery request as per RFC 7252, Section #8.2
654             OC_LOG_V(INFO, TAG, "Silently ignoring the request since device does not have \
655                 any useful data to send");
656         }
657     }
658
659     OCPayloadDestroy(payload);
660
661     return OC_STACK_OK;
662 }
663
664 static OCStackResult
665 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
666 {
667     if(!request)
668     {
669         return OC_STACK_INVALID_PARAM;
670     }
671
672     OCStackResult result = OC_STACK_OK;
673     OCEntityHandlerResult ehResult = OC_EH_ERROR;
674     OCEntityHandlerRequest ehRequest = {};
675
676     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithDefaultDeviceEntityHandler"));
677     result = FormOCEntityHandlerRequest(&ehRequest,
678                                         (OCRequestHandle) request,
679                                         request->method,
680                                         &request->devAddr,
681                                         (OCResourceHandle) NULL, request->query,
682                                         request->payload,
683                                         request->payloadSize,
684                                         request->numRcvdVendorSpecificHeaderOptions,
685                                         request->rcvdVendorSpecificHeaderOptions,
686                                         (OCObserveAction)request->observationOption,
687                                         (OCObservationId)0);
688     VERIFY_SUCCESS(result, OC_STACK_OK);
689
690     // At this point we know for sure that defaultDeviceHandler exists
691     ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
692                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
693     if(ehResult == OC_EH_SLOW)
694     {
695         OC_LOG(INFO, TAG, PCF("This is a slow resource"));
696         request->slowFlag = 1;
697     }
698     else if(ehResult == OC_EH_ERROR)
699     {
700         FindAndDeleteServerRequest(request);
701     }
702     result = EntityHandlerCodeToOCStackCode(ehResult);
703 exit:
704     return result;
705 }
706
707 static OCStackResult
708 HandleResourceWithEntityHandler (OCServerRequest *request,
709                                  OCResource *resource,
710                                  uint8_t collectionResource)
711 {
712     if(!request || ! resource)
713     {
714         return OC_STACK_INVALID_PARAM;
715     }
716
717     OCStackResult result = OC_STACK_ERROR;
718     OCEntityHandlerResult ehResult = OC_EH_ERROR;
719     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
720     ResourceObserver *resObs = NULL;
721
722     OCEntityHandlerRequest ehRequest = {};
723
724     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithEntityHandler"));
725
726     result = FormOCEntityHandlerRequest(&ehRequest,
727                                         (OCRequestHandle)request,
728                                         request->method,
729                                         &request->devAddr,
730                                         (OCResourceHandle)resource,
731                                         request->query,
732                                         request->payload,
733                                         request->payloadSize,
734                                         request->numRcvdVendorSpecificHeaderOptions,
735                                         request->rcvdVendorSpecificHeaderOptions,
736                                         (OCObserveAction)request->observationOption,
737                                         0);
738     VERIFY_SUCCESS(result, OC_STACK_OK);
739
740     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
741     {
742         OC_LOG(INFO, TAG, PCF("No observation requested"));
743         ehFlag = OC_REQUEST_FLAG;
744     }
745     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
746     {
747         OC_LOG(INFO, TAG, PCF("Observation registration requested"));
748
749         result = GenerateObserverId(&ehRequest.obsInfo.obsId);
750         VERIFY_SUCCESS(result, OC_STACK_OK);
751
752         result = AddObserver ((const char*)(request->resourceUrl),
753                 (const char *)(request->query),
754                 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
755                 resource, request->qos,
756                 &request->devAddr);
757
758         if(result == OC_STACK_OK)
759         {
760             OC_LOG(INFO, TAG, PCF("Added observer successfully"));
761             request->observeResult = OC_STACK_OK;
762             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
763         }
764         else
765         {
766             result = OC_STACK_OK;
767
768             // The error in observeResult for the request will be used when responding to this
769             // request by omitting the observation option/sequence number.
770             request->observeResult = OC_STACK_ERROR;
771             OC_LOG(ERROR, TAG, PCF("Observer Addition failed"));
772             ehFlag = OC_REQUEST_FLAG;
773         }
774
775     }
776     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
777             !collectionResource)
778     {
779         OC_LOG(INFO, TAG, PCF("Deregistering observation requested"));
780
781         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
782
783         if (NULL == resObs)
784         {
785             // Stack does not contain this observation request
786             // Either token is incorrect or observation list is corrupted
787             result = OC_STACK_ERROR;
788             goto exit;
789         }
790         ehRequest.obsInfo.obsId = resObs->observeId;
791         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
792
793         result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
794
795         if(result == OC_STACK_OK)
796         {
797             OC_LOG(INFO, TAG, PCF("Removed observer successfully"));
798             request->observeResult = OC_STACK_OK;
799         }
800         else
801         {
802             result = OC_STACK_OK;
803             request->observeResult = OC_STACK_ERROR;
804             OC_LOG(ERROR, TAG, PCF("Observer Removal failed"));
805         }
806     }
807     else
808     {
809         result = OC_STACK_ERROR;
810         goto exit;
811     }
812
813     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
814     if(ehResult == OC_EH_SLOW)
815     {
816         OC_LOG(INFO, TAG, PCF("This is a slow resource"));
817         request->slowFlag = 1;
818     }
819     else if(ehResult == OC_EH_ERROR)
820     {
821         FindAndDeleteServerRequest(request);
822     }
823     result = EntityHandlerCodeToOCStackCode(ehResult);
824 exit:
825     return result;
826 }
827
828 static OCStackResult
829 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
830                                               OCResource *resource)
831 {
832     if(!request || !resource)
833     {
834         return OC_STACK_INVALID_PARAM;
835     }
836
837     OCStackResult result = OC_STACK_ERROR;
838     OCEntityHandlerRequest ehRequest = {};
839
840     result = FormOCEntityHandlerRequest(&ehRequest,
841                                         (OCRequestHandle)request,
842                                         request->method,
843                                         &request->devAddr,
844                                         (OCResourceHandle)resource,
845                                         request->query,
846                                         request->payload,
847                                         request->payloadSize,
848                                         request->numRcvdVendorSpecificHeaderOptions,
849                                         request->rcvdVendorSpecificHeaderOptions,
850                                         (OCObserveAction)request->observationOption,
851                                         (OCObservationId)0);
852     if(result != OC_STACK_OK)
853     {
854         return result;
855     }
856
857     return (DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest));
858 }
859
860 OCStackResult
861 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
862 {
863     OCStackResult ret = OC_STACK_OK;
864
865     switch (resHandling)
866     {
867         case OC_RESOURCE_VIRTUAL:
868         {
869             ret = HandleVirtualResource (request, resource);
870             break;
871         }
872         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
873         {
874             ret = HandleDefaultDeviceEntityHandler(request);
875             break;
876         }
877         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
878         {
879             OC_LOG(INFO, TAG, PCF("OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER"));
880             return OC_STACK_ERROR;
881         }
882         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
883         {
884             ret = HandleResourceWithEntityHandler (request, resource, 0);
885             break;
886         }
887         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
888         {
889             ret = HandleResourceWithEntityHandler (request, resource, 1);
890             break;
891         }
892         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
893         {
894             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
895             break;
896         }
897         case OC_RESOURCE_NOT_SPECIFIED:
898         {
899             ret = OC_STACK_NO_RESOURCE;
900             break;
901         }
902         default:
903         {
904             OC_LOG(INFO, TAG, PCF("Invalid Resource Determination"));
905             return OC_STACK_ERROR;
906         }
907     }
908     return ret;
909 }
910
911 void DeletePlatformInfo()
912 {
913     OC_LOG(INFO, TAG, PCF("Deleting platform info."));
914
915     OICFree(savedPlatformInfo.platformID);
916     savedPlatformInfo.platformID = NULL;
917
918     OICFree(savedPlatformInfo.manufacturerName);
919     savedPlatformInfo.manufacturerName = NULL;
920
921     OICFree(savedPlatformInfo.manufacturerUrl);
922     savedPlatformInfo.manufacturerUrl = NULL;
923
924     OICFree(savedPlatformInfo.modelNumber);
925     savedPlatformInfo.modelNumber = NULL;
926
927     OICFree(savedPlatformInfo.dateOfManufacture);
928     savedPlatformInfo.dateOfManufacture = NULL;
929
930     OICFree(savedPlatformInfo.platformVersion);
931     savedPlatformInfo.platformVersion = NULL;
932
933     OICFree(savedPlatformInfo.operatingSystemVersion);
934     savedPlatformInfo.operatingSystemVersion = NULL;
935
936     OICFree(savedPlatformInfo.hardwareVersion);
937     savedPlatformInfo.hardwareVersion = NULL;
938
939     OICFree(savedPlatformInfo.firmwareVersion);
940     savedPlatformInfo.firmwareVersion = NULL;
941
942     OICFree(savedPlatformInfo.supportUrl);
943     savedPlatformInfo.supportUrl = NULL;
944
945     OICFree(savedPlatformInfo.systemTime);
946     savedPlatformInfo.systemTime = NULL;
947 }
948
949 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
950 {
951     savedPlatformInfo.platformID = OICStrdup(info.platformID);
952     savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
953     savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
954     savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
955     savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
956     savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
957     savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
958     savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
959     savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
960     savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
961     savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
962
963     if ((!savedPlatformInfo.platformID && info.platformID)||
964         (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
965         (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
966         (!savedPlatformInfo.modelNumber && info.modelNumber)||
967         (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
968         (!savedPlatformInfo.platformVersion && info.platformVersion)||
969         (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
970         (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
971         (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
972         (!savedPlatformInfo.supportUrl && info.supportUrl)||
973         (!savedPlatformInfo.systemTime && info.systemTime))
974     {
975         DeletePlatformInfo();
976         return OC_STACK_INVALID_PARAM;
977     }
978
979     return OC_STACK_OK;
980
981 }
982
983 OCStackResult SavePlatformInfo(OCPlatformInfo info)
984 {
985     DeletePlatformInfo();
986
987     OCStackResult res = DeepCopyPlatFormInfo(info);
988
989     if (res != OC_STACK_OK)
990     {
991         OC_LOG_V(ERROR, TAG, PCF("Failed to save platform info. errno(%d)"), res);
992     }
993     else
994     {
995         OC_LOG(ERROR, TAG, PCF("Platform info saved."));
996     }
997
998     return res;
999 }
1000
1001 void DeleteDeviceInfo()
1002 {
1003     OC_LOG(INFO, TAG, PCF("Deleting device info."));
1004
1005     OICFree(savedDeviceInfo.deviceName);
1006     savedDeviceInfo.deviceName = NULL;
1007 }
1008
1009 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1010 {
1011     savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1012
1013     if(!savedDeviceInfo.deviceName && info.deviceName)
1014     {
1015         DeleteDeviceInfo();
1016         return OC_STACK_NO_MEMORY;
1017     }
1018
1019     return OC_STACK_OK;
1020 }
1021
1022 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1023 {
1024     OCStackResult res = OC_STACK_OK;
1025
1026     DeleteDeviceInfo();
1027
1028     res = DeepCopyDeviceInfo(info);
1029
1030     VERIFY_SUCCESS(res, OC_STACK_OK);
1031
1032     if(OCGetServerInstanceID() == NULL)
1033     {
1034         OC_LOG(INFO, TAG, PCF("Device ID generation failed"));
1035         res =  OC_STACK_ERROR;
1036         goto exit;
1037     }
1038
1039     OC_LOG(INFO, TAG, PCF("Device initialized successfully."));
1040     return OC_STACK_OK;
1041
1042     exit:
1043         DeleteDeviceInfo();
1044         return res;
1045
1046 }