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