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