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