8a1d744f1eef8cb88663f70fea34fc15a2e3ce72
[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)
519 {
520     OCEntityHandlerResponse response = {};
521
522     response.ehResult = OC_EH_OK;
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     OCPayload* payload = NULL;
540     char *filterOne = NULL;
541     char *filterTwo = NULL;
542
543     OC_LOG(INFO, TAG, PCF("Entering HandleVirtualResource"));
544
545     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
546
547
548     if (virtualUriInRequest == OC_WELL_KNOWN_URI)
549     {
550         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
551                                                             &filterOne, &filterTwo);
552         if (discoveryResult != OC_STACK_OK)
553         {
554             OC_LOG_V(ERROR, TAG, "Error (%d) validating query.\n", discoveryResult);
555             return discoveryResult;
556         }
557         payload = (OCPayload*)OCDiscoveryPayloadCreate();
558
559         if(!payload)
560         {
561             return OC_STACK_NO_MEMORY;
562         }
563
564
565         for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
566         {
567             if(includeThisResourceInResponse(resource, filterOne, filterTwo))
568             {
569                 discoveryResult = BuildVirtualResourceResponse(resource,
570                     (OCDiscoveryPayload*)payload,
571                     &request->devAddr);
572             }
573         }
574     }
575     else if (virtualUriInRequest == OC_DEVICE_URI)
576     {
577             payload = (OCPayload*)OCDevicePayloadCreate(OC_RSRVD_DEVICE_URI,
578                         OCGetServerInstanceID(), savedDeviceInfo.deviceName,
579                         OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
580             if (!payload)
581             {
582                 discoveryResult = OC_STACK_NO_MEMORY;
583             }
584             else
585             {
586                 discoveryResult = OC_STACK_OK;
587             }
588     }
589     else if (virtualUriInRequest == OC_PLATFORM_URI)
590     {
591             payload = (OCPayload*)OCPlatformPayloadCreate(
592                     OC_RSRVD_PLATFORM_URI,
593                     &savedPlatformInfo);
594             if (!payload)
595             {
596                 discoveryResult = OC_STACK_NO_MEMORY;
597             }
598             else
599             {
600                 discoveryResult = OC_STACK_OK;
601             }
602     }
603
604     #ifdef WITH_PRESENCE
605     else
606     {
607         if(resource->resourceProperties & OC_ACTIVE)
608         {
609             discoveryResult = SendPresenceNotification(resource->rsrcType,
610                                                 OC_PRESENCE_TRIGGER_CHANGE);
611         }
612     }
613     #endif
614
615     // Presence uses observer notification api to respond via SendPresenceNotification.
616     if (virtualUriInRequest != OC_PRESENCE)
617     {
618         if(discoveryResult == OC_STACK_OK)
619         {
620             discoveryResult = SendNonPersistantDiscoveryResponse(request, resource,
621                                                         payload);
622             OCPayloadDestroy(payload);
623         }
624         else
625         {
626             OC_LOG_V(ERROR, TAG, "Error (%d) building (%d)  discovery response. "\
627                         "Not responding to request.", discoveryResult, virtualUriInRequest);
628         }
629     }
630
631     return discoveryResult;
632 }
633
634 static OCStackResult
635 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
636 {
637     if(!request)
638     {
639         return OC_STACK_INVALID_PARAM;
640     }
641
642     OCStackResult result = OC_STACK_OK;
643     OCEntityHandlerResult ehResult = OC_EH_ERROR;
644     OCEntityHandlerRequest ehRequest = {};
645
646     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithDefaultDeviceEntityHandler"));
647     result = FormOCEntityHandlerRequest(&ehRequest,
648                                         (OCRequestHandle) request,
649                                         request->method,
650                                         &request->devAddr,
651                                         (OCResourceHandle) NULL, request->query,
652                                         request->payload,
653                                         request->payloadSize,
654                                         request->numRcvdVendorSpecificHeaderOptions,
655                                         request->rcvdVendorSpecificHeaderOptions,
656                                         (OCObserveAction)request->observationOption,
657                                         (OCObservationId)0);
658     VERIFY_SUCCESS(result, OC_STACK_OK);
659
660     // At this point we know for sure that defaultDeviceHandler exists
661     ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
662                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
663     if(ehResult == OC_EH_SLOW)
664     {
665         OC_LOG(INFO, TAG, PCF("This is a slow resource"));
666         request->slowFlag = 1;
667     }
668     else if(ehResult == OC_EH_ERROR)
669     {
670         FindAndDeleteServerRequest(request);
671     }
672     result = EntityHandlerCodeToOCStackCode(ehResult);
673 exit:
674     return result;
675 }
676
677 static OCStackResult
678 HandleResourceWithEntityHandler (OCServerRequest *request,
679                                  OCResource *resource,
680                                  uint8_t collectionResource)
681 {
682     if(!request || ! resource)
683     {
684         return OC_STACK_INVALID_PARAM;
685     }
686
687     OCStackResult result = OC_STACK_ERROR;
688     OCEntityHandlerResult ehResult = OC_EH_ERROR;
689     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
690     ResourceObserver *resObs = NULL;
691
692     OCEntityHandlerRequest ehRequest = {};
693
694     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithEntityHandler"));
695
696     result = FormOCEntityHandlerRequest(&ehRequest,
697                                         (OCRequestHandle)request,
698                                         request->method,
699                                         &request->devAddr,
700                                         (OCResourceHandle)resource,
701                                         request->query,
702                                         request->payload,
703                                         request->payloadSize,
704                                         request->numRcvdVendorSpecificHeaderOptions,
705                                         request->rcvdVendorSpecificHeaderOptions,
706                                         (OCObserveAction)request->observationOption,
707                                         0);
708     VERIFY_SUCCESS(result, OC_STACK_OK);
709
710     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
711     {
712         OC_LOG(INFO, TAG, PCF("No observation requested"));
713         ehFlag = OC_REQUEST_FLAG;
714     }
715     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
716     {
717         OC_LOG(INFO, TAG, PCF("Observation registration requested"));
718
719         result = GenerateObserverId(&ehRequest.obsInfo.obsId);
720         VERIFY_SUCCESS(result, OC_STACK_OK);
721
722         result = AddObserver ((const char*)(request->resourceUrl),
723                 (const char *)(request->query),
724                 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
725                 resource, request->qos,
726                 &request->devAddr);
727
728         if(result == OC_STACK_OK)
729         {
730             OC_LOG(INFO, TAG, PCF("Added observer successfully"));
731             request->observeResult = OC_STACK_OK;
732             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
733         }
734         else
735         {
736             result = OC_STACK_OK;
737
738             // The error in observeResult for the request will be used when responding to this
739             // request by omitting the observation option/sequence number.
740             request->observeResult = OC_STACK_ERROR;
741             OC_LOG(ERROR, TAG, PCF("Observer Addition failed"));
742             ehFlag = OC_REQUEST_FLAG;
743         }
744
745     }
746     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
747             !collectionResource)
748     {
749         OC_LOG(INFO, TAG, PCF("Deregistering observation requested"));
750
751         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
752
753         if (NULL == resObs)
754         {
755             // Stack does not contain this observation request
756             // Either token is incorrect or observation list is corrupted
757             result = OC_STACK_ERROR;
758             goto exit;
759         }
760         ehRequest.obsInfo.obsId = resObs->observeId;
761         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
762
763         result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
764
765         if(result == OC_STACK_OK)
766         {
767             OC_LOG(INFO, TAG, PCF("Removed observer successfully"));
768             request->observeResult = OC_STACK_OK;
769         }
770         else
771         {
772             result = OC_STACK_OK;
773             request->observeResult = OC_STACK_ERROR;
774             OC_LOG(ERROR, TAG, PCF("Observer Removal failed"));
775         }
776     }
777     else
778     {
779         result = OC_STACK_ERROR;
780         goto exit;
781     }
782
783     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
784     if(ehResult == OC_EH_SLOW)
785     {
786         OC_LOG(INFO, TAG, PCF("This is a slow resource"));
787         request->slowFlag = 1;
788     }
789     else if(ehResult == OC_EH_ERROR)
790     {
791         FindAndDeleteServerRequest(request);
792     }
793     result = EntityHandlerCodeToOCStackCode(ehResult);
794 exit:
795     return result;
796 }
797
798 static OCStackResult
799 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
800                                               OCResource *resource)
801 {
802     if(!request || !resource)
803     {
804         return OC_STACK_INVALID_PARAM;
805     }
806
807     OCStackResult result = OC_STACK_ERROR;
808     OCEntityHandlerRequest ehRequest = {};
809
810     result = FormOCEntityHandlerRequest(&ehRequest,
811                                         (OCRequestHandle)request,
812                                         request->method,
813                                         &request->devAddr,
814                                         (OCResourceHandle)resource,
815                                         request->query,
816                                         request->payload,
817                                         request->payloadSize,
818                                         request->numRcvdVendorSpecificHeaderOptions,
819                                         request->rcvdVendorSpecificHeaderOptions,
820                                         (OCObserveAction)request->observationOption,
821                                         (OCObservationId)0);
822     if(result != OC_STACK_OK)
823     {
824         return result;
825     }
826
827     return (DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest));
828 }
829
830 OCStackResult
831 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
832 {
833     OCStackResult ret = OC_STACK_OK;
834
835     switch (resHandling)
836     {
837         case OC_RESOURCE_VIRTUAL:
838         {
839             ret = HandleVirtualResource (request, resource);
840             break;
841         }
842         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
843         {
844             ret = HandleDefaultDeviceEntityHandler(request);
845             break;
846         }
847         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
848         {
849             OC_LOG(INFO, TAG, PCF("OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER"));
850             return OC_STACK_ERROR;
851         }
852         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
853         {
854             ret = HandleResourceWithEntityHandler (request, resource, 0);
855             break;
856         }
857         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
858         {
859             ret = HandleResourceWithEntityHandler (request, resource, 1);
860             break;
861         }
862         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
863         {
864             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
865             break;
866         }
867         case OC_RESOURCE_NOT_SPECIFIED:
868         {
869             ret = OC_STACK_NO_RESOURCE;
870             break;
871         }
872         default:
873         {
874             OC_LOG(INFO, TAG, PCF("Invalid Resource Determination"));
875             return OC_STACK_ERROR;
876         }
877     }
878     return ret;
879 }
880
881 void DeletePlatformInfo()
882 {
883     OC_LOG(INFO, TAG, PCF("Deleting platform info."));
884
885     OICFree(savedPlatformInfo.platformID);
886     savedPlatformInfo.platformID = NULL;
887
888     OICFree(savedPlatformInfo.manufacturerName);
889     savedPlatformInfo.manufacturerName = NULL;
890
891     OICFree(savedPlatformInfo.manufacturerUrl);
892     savedPlatformInfo.manufacturerUrl = NULL;
893
894     OICFree(savedPlatformInfo.modelNumber);
895     savedPlatformInfo.modelNumber = NULL;
896
897     OICFree(savedPlatformInfo.dateOfManufacture);
898     savedPlatformInfo.dateOfManufacture = NULL;
899
900     OICFree(savedPlatformInfo.platformVersion);
901     savedPlatformInfo.platformVersion = NULL;
902
903     OICFree(savedPlatformInfo.operatingSystemVersion);
904     savedPlatformInfo.operatingSystemVersion = NULL;
905
906     OICFree(savedPlatformInfo.hardwareVersion);
907     savedPlatformInfo.hardwareVersion = NULL;
908
909     OICFree(savedPlatformInfo.firmwareVersion);
910     savedPlatformInfo.firmwareVersion = NULL;
911
912     OICFree(savedPlatformInfo.supportUrl);
913     savedPlatformInfo.supportUrl = NULL;
914
915     OICFree(savedPlatformInfo.systemTime);
916     savedPlatformInfo.systemTime = NULL;
917 }
918
919 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
920 {
921     savedPlatformInfo.platformID = OICStrdup(info.platformID);
922     savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
923     savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
924     savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
925     savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
926     savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
927     savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
928     savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
929     savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
930     savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
931     savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
932
933     if ((!savedPlatformInfo.platformID && info.platformID)||
934         (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
935         (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
936         (!savedPlatformInfo.modelNumber && info.modelNumber)||
937         (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
938         (!savedPlatformInfo.platformVersion && info.platformVersion)||
939         (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
940         (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
941         (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
942         (!savedPlatformInfo.supportUrl && info.supportUrl)||
943         (!savedPlatformInfo.systemTime && info.systemTime))
944     {
945         DeletePlatformInfo();
946         return OC_STACK_INVALID_PARAM;
947     }
948
949     return OC_STACK_OK;
950
951 }
952
953 OCStackResult SavePlatformInfo(OCPlatformInfo info)
954 {
955     DeletePlatformInfo();
956
957     OCStackResult res = DeepCopyPlatFormInfo(info);
958
959     if (res != OC_STACK_OK)
960     {
961         OC_LOG_V(ERROR, TAG, PCF("Failed to save platform info. errno(%d)"), res);
962     }
963     else
964     {
965         OC_LOG(ERROR, TAG, PCF("Platform info saved."));
966     }
967
968     return res;
969 }
970
971 void DeleteDeviceInfo()
972 {
973     OC_LOG(INFO, TAG, PCF("Deleting device info."));
974
975     OICFree(savedDeviceInfo.deviceName);
976     savedDeviceInfo.deviceName = NULL;
977 }
978
979 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
980 {
981     savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
982
983     if(!savedDeviceInfo.deviceName && info.deviceName)
984     {
985         DeleteDeviceInfo();
986         return OC_STACK_NO_MEMORY;
987     }
988
989     return OC_STACK_OK;
990 }
991
992 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
993 {
994     OCStackResult res = OC_STACK_OK;
995
996     DeleteDeviceInfo();
997
998     res = DeepCopyDeviceInfo(info);
999
1000     VERIFY_SUCCESS(res, OC_STACK_OK);
1001
1002     if(OCGetServerInstanceID() == NULL)
1003     {
1004         OC_LOG(INFO, TAG, PCF("Device ID generation failed"));
1005         res =  OC_STACK_ERROR;
1006         goto exit;
1007     }
1008
1009     OC_LOG(INFO, TAG, PCF("Device initialized successfully."));
1010     return OC_STACK_OK;
1011
1012     exit:
1013         DeleteDeviceInfo();
1014         return res;
1015
1016 }