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