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