Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocresource.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1-2001 base
24 // specification (excluding the XSI extension).
25 // For POSIX.1-2001 base specification,
26 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
27 #define _POSIX_C_SOURCE 200112L
28 #include "ocresource.h"
29 #include <string.h>
30 #include "ocresourcehandler.h"
31 #include "ocobserve.h"
32 #include "occollection.h"
33 #include "oic_malloc.h"
34 #include "oic_string.h"
35 #include "logger.h"
36 #include "cJSON.h"
37 #include "ocpayload.h"
38
39 #include "cacommon.h"
40 #include "cainterface.h"
41
42
43 /// Module Name
44 #define TAG PCF("ocresource")
45 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
46             {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
47
48 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
49              TAG, PCF(#arg " is NULL")); return (retVal); } }
50
51 extern OCResource *headResource;
52 static OCPlatformInfo savedPlatformInfo = {};
53 static OCDeviceInfo savedDeviceInfo = {};
54
55 //-----------------------------------------------------------------------------
56 // Default resource entity handler function
57 //-----------------------------------------------------------------------------
58 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
59         OCEntityHandlerRequest * request, void* callbackParam)
60 {
61     //TODO ("Implement me!!!!");
62     // TODO:  remove silence unused param warnings
63     (void) flag;
64     (void) request;
65     (void) callbackParam;
66     return  OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
67 }
68
69 /* This method will retrieve the port at which the secure resource is hosted */
70 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
71 {
72     uint16_t p = 0;
73
74     if (endpoint->adapter == OC_ADAPTER_IP)
75     {
76         if (endpoint->flags & OC_IP_USE_V6)
77         {
78             p = caglobals.ip.u6s.port;
79         }
80         else if (endpoint->flags & OC_IP_USE_V4)
81         {
82             p = caglobals.ip.u4s.port;
83         }
84     }
85
86     *port = p;
87     return OC_STACK_OK;
88 }
89
90 /*
91  * Function will extract 0, 1 or 2 filters from query.
92  * More than 2 filters or unsupported filters will result in error.
93  * If both filters are of the same supported type, the 2nd one will be picked.
94  * Resource and device filters in the SAME query are NOT validated
95  * and resources will likely not clear filters.
96  */
97 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
98 {
99
100     char *key = NULL;
101     char *value = NULL;
102     char *restOfQuery = NULL;
103     int numKeyValuePairsParsed = 0;
104
105     *filterOne = NULL;
106     *filterTwo = NULL;
107
108     OC_LOG_V(INFO, TAG, "Extracting params from %s", query);
109
110     char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
111
112     while(keyValuePair)
113     {
114         if (numKeyValuePairsParsed >= 2)
115         {
116             OC_LOG(ERROR, TAG, PCF("More than 2 queries params in URI."));
117             return OC_STACK_INVALID_QUERY;
118         }
119
120         key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
121
122         if (!key || !value)
123         {
124             return OC_STACK_INVALID_QUERY;
125         }
126         else if (strcmp (key, OC_RSRVD_INTERFACE) == 0)
127         {
128             *filterOne = value;     // if
129         }
130         else if (strcmp (key, OC_RSRVD_RESOURCE_TYPE) == 0)
131         {
132             *filterTwo = value;     // rt
133         }
134         else
135         {
136             OC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
137             return OC_STACK_INVALID_QUERY;
138         }
139         ++numKeyValuePairsParsed;
140
141         keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
142     }
143
144     OC_LOG_V(INFO, TAG, "Extracted params %s and %s.", *filterOne, *filterTwo);
145     return OC_STACK_OK;
146 }
147
148 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
149 {
150     if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
151     {
152         return OC_WELL_KNOWN_URI;
153     }
154     else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
155     {
156         return OC_DEVICE_URI;
157     }
158     else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
159     {
160         return OC_PLATFORM_URI;
161     }
162     else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
163     {
164         return OC_RESOURCE_TYPES_URI;
165     }
166 #ifdef WITH_PRESENCE
167     else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
168     {
169         return OC_PRESENCE;
170     }
171 #endif //WITH_PRESENCE
172     return OC_UNKNOWN_URI;
173 }
174
175 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
176                                             char **filterOne, char **filterTwo)
177 {
178     if(!filterOne || !filterTwo)
179     {
180         return OC_STACK_INVALID_PARAM;
181     }
182
183     *filterOne = NULL;
184     *filterTwo = NULL;
185
186     #ifdef WITH_PRESENCE
187     if (uri == OC_PRESENCE)
188     {
189         //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
190         OC_LOG(INFO, TAG, PCF("OC_PRESENCE Request for virtual resource."));
191         return OC_STACK_OK;
192     }
193     #endif
194
195     OCStackResult result = OC_STACK_OK;
196
197     if (query && *query)
198     {
199         result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
200     }
201
202     return result;
203 }
204
205 OCStackResult 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 = NULL;
344         resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
345         *resource = resourcePtr;
346         if (!resourcePtr)
347         {
348             if(defaultDeviceHandler)
349             {
350                 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
351                 return OC_STACK_OK;
352             }
353
354             // Resource does not exist
355             // and default device handler does not exist
356             *handling = OC_RESOURCE_NOT_SPECIFIED;
357             return OC_STACK_NO_RESOURCE;
358         }
359
360         if (IsCollectionResource (resourcePtr))
361         {
362             // Collection resource
363             if (resourcePtr->entityHandler != defaultResourceEHandler)
364             {
365                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
366                 return OC_STACK_OK;
367             }
368             else
369             {
370                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
371                 return OC_STACK_OK;
372             }
373         }
374         else
375         {
376             // Resource not a collection
377             if (resourcePtr->entityHandler != defaultResourceEHandler)
378             {
379                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
380                 return OC_STACK_OK;
381             }
382             else
383             {
384                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
385                 return OC_STACK_OK;
386             }
387         }
388     }
389 }
390
391 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
392 {
393     OCStackResult result;
394
395     switch (ehResult)
396     {
397         case OC_EH_OK:
398             result = OC_STACK_OK;
399             break;
400         case OC_EH_SLOW:
401             result = OC_STACK_SLOW_RESOURCE;
402             break;
403         case OC_EH_ERROR:
404             result = OC_STACK_ERROR;
405             break;
406         case OC_EH_FORBIDDEN:
407             result = OC_STACK_RESOURCE_ERROR;
408             break;
409         case OC_EH_RESOURCE_CREATED:
410             result = OC_STACK_RESOURCE_CREATED;
411             break;
412         case OC_EH_RESOURCE_DELETED:
413             result = OC_STACK_RESOURCE_DELETED;
414             break;
415         case OC_EH_RESOURCE_NOT_FOUND:
416             result = OC_STACK_NO_RESOURCE;
417             break;
418         default:
419             result = OC_STACK_ERROR;
420     }
421
422     return result;
423 }
424
425 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
426 {
427     if (!resource)
428     {
429         return false;
430     }
431
432     // Null or empty is analogous to no filter.
433     if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
434     {
435         return true;
436     }
437
438     OCResourceType *resourceTypePtr = resource->rsrcType;
439
440     while (resourceTypePtr)
441     {
442         if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
443         {
444             return true;
445         }
446         resourceTypePtr = resourceTypePtr->next;
447     }
448
449     OC_LOG_V(INFO, TAG, PCF("%s does not contain rt=%s."), resource->uri, resourceTypeFilter);
450     return false;
451 }
452
453 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
454 {
455     if (!resource)
456     {
457         return false;
458     }
459
460     // Null or empty is analogous to no filter.
461     if (interfaceFilter == NULL || *interfaceFilter == 0)
462     {
463         return true;
464     }
465
466     OCResourceInterface *interfacePtr = resource->rsrcInterface;
467
468     while (interfacePtr)
469     {
470         if (strcmp (interfacePtr->name, interfaceFilter) == 0)
471         {
472             return true;
473         }
474         interfacePtr = interfacePtr->next;
475     }
476
477     OC_LOG_V(INFO, TAG, PCF("%s does not contain if=%s."), resource->uri, interfaceFilter);
478     return false;
479 }
480
481 /*
482  * If the filters are null, they will be assumed to NOT be present
483  * and the resource will not be matched against them.
484  * Function will return true if all non null AND non empty filters passed in find a match.
485  */
486 static bool includeThisResourceInResponse(OCResource *resource,
487                                                  char *interfaceFilter,
488                                                  char *resourceTypeFilter)
489 {
490     if (!resource)
491     {
492         OC_LOG(ERROR, TAG, PCF("Invalid resource"));
493         return false;
494     }
495
496     if ( resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
497     {
498         /*
499          * At least one valid filter should be available to
500          * include the resource in discovery response
501          */
502         if (!((interfaceFilter && *interfaceFilter ) ||
503               (resourceTypeFilter && *resourceTypeFilter)))
504         {
505             OC_LOG_V(INFO, TAG, PCF("%s no query string for EXPLICIT_DISCOVERABLE \
506                 resource"), resource->uri);
507             return false;
508         }
509     }
510     else if ( !(resource->resourceProperties & OC_ACTIVE) ||
511          !(resource->resourceProperties & OC_DISCOVERABLE))
512     {
513         OC_LOG_V(INFO, TAG, PCF("%s not ACTIVE or DISCOVERABLE"), resource->uri);
514         return false;
515     }
516
517     return resourceMatchesIFFilter(resource, interfaceFilter) &&
518            resourceMatchesRTFilter(resource, resourceTypeFilter);
519
520 }
521
522 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
523                                 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
524 {
525     OCEntityHandlerResponse response = {};
526
527     response.ehResult = ehResult;
528     response.payload = discoveryPayload;
529     response.persistentBufferFlag = 0;
530     response.requestHandle = (OCRequestHandle) request;
531     response.resourceHandle = (OCResourceHandle) resource;
532
533     return OCDoResponse(&response);
534 }
535
536 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
537 {
538     if (!request || !resource)
539     {
540         return OC_STACK_INVALID_PARAM;
541     }
542
543     OCStackResult discoveryResult = OC_STACK_ERROR;
544
545     bool bMulticast    = false;     // Was the discovery request a multicast request?
546     OCPayload* payload = NULL;
547
548     OC_LOG(INFO, TAG, PCF("Entering HandleVirtualResource"));
549
550     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
551
552     // Step 1: Generate the response to discovery request
553     if (virtualUriInRequest == OC_WELL_KNOWN_URI)
554     {
555         char *filterOne = NULL;
556         char *filterTwo = NULL;
557
558         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
559                 &filterOne, &filterTwo);
560
561         if (discoveryResult == OC_STACK_OK)
562         {
563             payload = (OCPayload*)OCDiscoveryPayloadCreate();
564
565             if(payload)
566             {
567                 for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
568                 {
569                     if(includeThisResourceInResponse(resource, filterOne, filterTwo))
570                     {
571                         discoveryResult = BuildVirtualResourceResponse(resource,
572                                 (OCDiscoveryPayload*)payload,
573                                 &request->devAddr);
574                     }
575                 }
576                 // Set discoveryResult appropriately if no 'valid' resources are available.
577                 if (((OCDiscoveryPayload*)payload)->resources == NULL)
578                 {
579                     discoveryResult = OC_STACK_NO_RESOURCE;
580                 }
581             }
582             else
583             {
584                 discoveryResult = OC_STACK_NO_MEMORY;
585             }
586         }
587         else
588         {
589             OC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
590         }
591     }
592     else if (virtualUriInRequest == OC_DEVICE_URI)
593     {
594         payload = (OCPayload*)OCDevicePayloadCreate(OC_RSRVD_DEVICE_URI,
595                 OCGetServerInstanceID(), savedDeviceInfo.deviceName,
596                 OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
597         if (!payload)
598         {
599             discoveryResult = OC_STACK_NO_MEMORY;
600         }
601         else
602         {
603             discoveryResult = OC_STACK_OK;
604         }
605     }
606     else if (virtualUriInRequest == OC_PLATFORM_URI)
607     {
608         payload = (OCPayload*)OCPlatformPayloadCreate(
609                 OC_RSRVD_PLATFORM_URI,
610                 &savedPlatformInfo);
611         if (!payload)
612         {
613             discoveryResult = OC_STACK_NO_MEMORY;
614         }
615         else
616         {
617             discoveryResult = OC_STACK_OK;
618         }
619     }
620
621     /**
622      * Step 2: Send the discovery response
623      *
624      * Iotivity should respond to discovery requests in below manner:
625      * 1)If query filter matching fails and discovery request is multicast,
626      *   it should NOT send any response.
627      * 2)If query filter matching fails and discovery request is unicast,
628      *   it should send an error(RESOURCE_NOT_FOUND - 404) response.
629      * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
630      *   request is multicast, it should NOT send any response.
631      * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
632      *   request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
633      */
634
635     #ifdef WITH_PRESENCE
636     if ((virtualUriInRequest == OC_PRESENCE) &&
637         (resource->resourceProperties & OC_ACTIVE))
638     {
639         // Presence uses observer notification api to respond via SendPresenceNotification.
640         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
641     }
642     else
643     #endif
644     {
645         if(discoveryResult == OC_STACK_OK)
646         {
647             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
648         }
649         else if(bMulticast == false)
650         {
651             OC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d)  \
652                 discovery request", discoveryResult, virtualUriInRequest);
653             SendNonPersistantDiscoveryResponse(request, resource, NULL,
654                 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
655         }
656         else
657         {
658             // Ignoring the discovery request as per RFC 7252, Section #8.2
659             OC_LOG_V(INFO, TAG, "Silently ignoring the request since device does not have \
660                 any useful data to send");
661         }
662     }
663
664     OCPayloadDestroy(payload);
665
666     return OC_STACK_OK;
667 }
668
669 static OCStackResult
670 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
671 {
672     if(!request)
673     {
674         return OC_STACK_INVALID_PARAM;
675     }
676
677     OCStackResult result = OC_STACK_OK;
678     OCEntityHandlerResult ehResult = OC_EH_ERROR;
679     OCEntityHandlerRequest ehRequest = {};
680
681     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithDefaultDeviceEntityHandler"));
682     result = FormOCEntityHandlerRequest(&ehRequest,
683                                         (OCRequestHandle) request,
684                                         request->method,
685                                         &request->devAddr,
686                                         (OCResourceHandle) NULL, request->query,
687                                         request->payload,
688                                         request->payloadSize,
689                                         request->numRcvdVendorSpecificHeaderOptions,
690                                         request->rcvdVendorSpecificHeaderOptions,
691                                         (OCObserveAction)request->observationOption,
692                                         (OCObservationId)0);
693     VERIFY_SUCCESS(result, OC_STACK_OK);
694
695     // At this point we know for sure that defaultDeviceHandler exists
696     ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
697                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
698     if(ehResult == OC_EH_SLOW)
699     {
700         OC_LOG(INFO, TAG, PCF("This is a slow resource"));
701         request->slowFlag = 1;
702     }
703     else if(ehResult == OC_EH_ERROR)
704     {
705         FindAndDeleteServerRequest(request);
706     }
707     result = EntityHandlerCodeToOCStackCode(ehResult);
708 exit:
709     return result;
710 }
711
712 static OCStackResult
713 HandleResourceWithEntityHandler (OCServerRequest *request,
714                                  OCResource *resource,
715                                  uint8_t collectionResource)
716 {
717     if(!request || ! resource)
718     {
719         return OC_STACK_INVALID_PARAM;
720     }
721
722     OCStackResult result = OC_STACK_ERROR;
723     OCEntityHandlerResult ehResult = OC_EH_ERROR;
724     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
725     ResourceObserver *resObs = NULL;
726
727     OCEntityHandlerRequest ehRequest = {};
728
729     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithEntityHandler"));
730
731     result = FormOCEntityHandlerRequest(&ehRequest,
732                                         (OCRequestHandle)request,
733                                         request->method,
734                                         &request->devAddr,
735                                         (OCResourceHandle)resource,
736                                         request->query,
737                                         request->payload,
738                                         request->payloadSize,
739                                         request->numRcvdVendorSpecificHeaderOptions,
740                                         request->rcvdVendorSpecificHeaderOptions,
741                                         (OCObserveAction)request->observationOption,
742                                         0);
743     VERIFY_SUCCESS(result, OC_STACK_OK);
744
745     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
746     {
747         OC_LOG(INFO, TAG, PCF("No observation requested"));
748         ehFlag = OC_REQUEST_FLAG;
749     }
750     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
751     {
752         OC_LOG(INFO, TAG, PCF("Observation registration requested"));
753
754         result = GenerateObserverId(&ehRequest.obsInfo.obsId);
755         VERIFY_SUCCESS(result, OC_STACK_OK);
756
757         result = AddObserver ((const char*)(request->resourceUrl),
758                 (const char *)(request->query),
759                 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
760                 resource, request->qos,
761                 &request->devAddr);
762
763         if(result == OC_STACK_OK)
764         {
765             OC_LOG(INFO, TAG, PCF("Added observer successfully"));
766             request->observeResult = OC_STACK_OK;
767             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
768         }
769         else
770         {
771             result = OC_STACK_OK;
772
773             // The error in observeResult for the request will be used when responding to this
774             // request by omitting the observation option/sequence number.
775             request->observeResult = OC_STACK_ERROR;
776             OC_LOG(ERROR, TAG, PCF("Observer Addition failed"));
777             ehFlag = OC_REQUEST_FLAG;
778         }
779
780     }
781     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
782             !collectionResource)
783     {
784         OC_LOG(INFO, TAG, PCF("Deregistering observation requested"));
785
786         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
787
788         if (NULL == resObs)
789         {
790             // Stack does not contain this observation request
791             // Either token is incorrect or observation list is corrupted
792             result = OC_STACK_ERROR;
793             goto exit;
794         }
795         ehRequest.obsInfo.obsId = resObs->observeId;
796         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
797
798         result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
799
800         if(result == OC_STACK_OK)
801         {
802             OC_LOG(INFO, TAG, PCF("Removed observer successfully"));
803             request->observeResult = OC_STACK_OK;
804         }
805         else
806         {
807             result = OC_STACK_OK;
808             request->observeResult = OC_STACK_ERROR;
809             OC_LOG(ERROR, TAG, PCF("Observer Removal failed"));
810         }
811     }
812     else
813     {
814         result = OC_STACK_ERROR;
815         goto exit;
816     }
817
818     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
819     if(ehResult == OC_EH_SLOW)
820     {
821         OC_LOG(INFO, TAG, PCF("This is a slow resource"));
822         request->slowFlag = 1;
823     }
824     else if(ehResult == OC_EH_ERROR)
825     {
826         FindAndDeleteServerRequest(request);
827     }
828     result = EntityHandlerCodeToOCStackCode(ehResult);
829 exit:
830     return result;
831 }
832
833 static OCStackResult
834 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
835                                               OCResource *resource)
836 {
837     if(!request || !resource)
838     {
839         return OC_STACK_INVALID_PARAM;
840     }
841
842     OCStackResult result = OC_STACK_ERROR;
843     OCEntityHandlerRequest ehRequest = {};
844
845     result = FormOCEntityHandlerRequest(&ehRequest,
846                                         (OCRequestHandle)request,
847                                         request->method,
848                                         &request->devAddr,
849                                         (OCResourceHandle)resource,
850                                         request->query,
851                                         request->payload,
852                                         request->payloadSize,
853                                         request->numRcvdVendorSpecificHeaderOptions,
854                                         request->rcvdVendorSpecificHeaderOptions,
855                                         (OCObserveAction)request->observationOption,
856                                         (OCObservationId)0);
857     if(result != OC_STACK_OK)
858     {
859         return result;
860     }
861
862     return (DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest));
863 }
864
865 OCStackResult
866 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
867 {
868     OCStackResult ret = OC_STACK_OK;
869
870     switch (resHandling)
871     {
872         case OC_RESOURCE_VIRTUAL:
873         {
874             ret = HandleVirtualResource (request, resource);
875             break;
876         }
877         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
878         {
879             ret = HandleDefaultDeviceEntityHandler(request);
880             break;
881         }
882         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
883         {
884             OC_LOG(INFO, TAG, PCF("OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER"));
885             return OC_STACK_ERROR;
886         }
887         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
888         {
889             ret = HandleResourceWithEntityHandler (request, resource, 0);
890             break;
891         }
892         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
893         {
894             ret = HandleResourceWithEntityHandler (request, resource, 1);
895             break;
896         }
897         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
898         {
899             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
900             break;
901         }
902         case OC_RESOURCE_NOT_SPECIFIED:
903         {
904             ret = OC_STACK_NO_RESOURCE;
905             break;
906         }
907         default:
908         {
909             OC_LOG(INFO, TAG, PCF("Invalid Resource Determination"));
910             return OC_STACK_ERROR;
911         }
912     }
913     return ret;
914 }
915
916 void DeletePlatformInfo()
917 {
918     OC_LOG(INFO, TAG, PCF("Deleting platform info."));
919
920     OICFree(savedPlatformInfo.platformID);
921     savedPlatformInfo.platformID = NULL;
922
923     OICFree(savedPlatformInfo.manufacturerName);
924     savedPlatformInfo.manufacturerName = NULL;
925
926     OICFree(savedPlatformInfo.manufacturerUrl);
927     savedPlatformInfo.manufacturerUrl = NULL;
928
929     OICFree(savedPlatformInfo.modelNumber);
930     savedPlatformInfo.modelNumber = NULL;
931
932     OICFree(savedPlatformInfo.dateOfManufacture);
933     savedPlatformInfo.dateOfManufacture = NULL;
934
935     OICFree(savedPlatformInfo.platformVersion);
936     savedPlatformInfo.platformVersion = NULL;
937
938     OICFree(savedPlatformInfo.operatingSystemVersion);
939     savedPlatformInfo.operatingSystemVersion = NULL;
940
941     OICFree(savedPlatformInfo.hardwareVersion);
942     savedPlatformInfo.hardwareVersion = NULL;
943
944     OICFree(savedPlatformInfo.firmwareVersion);
945     savedPlatformInfo.firmwareVersion = NULL;
946
947     OICFree(savedPlatformInfo.supportUrl);
948     savedPlatformInfo.supportUrl = NULL;
949
950     OICFree(savedPlatformInfo.systemTime);
951     savedPlatformInfo.systemTime = NULL;
952 }
953
954 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
955 {
956     savedPlatformInfo.platformID = OICStrdup(info.platformID);
957     savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
958     savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
959     savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
960     savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
961     savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
962     savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
963     savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
964     savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
965     savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
966     savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
967
968     if ((!savedPlatformInfo.platformID && info.platformID)||
969         (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
970         (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
971         (!savedPlatformInfo.modelNumber && info.modelNumber)||
972         (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
973         (!savedPlatformInfo.platformVersion && info.platformVersion)||
974         (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
975         (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
976         (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
977         (!savedPlatformInfo.supportUrl && info.supportUrl)||
978         (!savedPlatformInfo.systemTime && info.systemTime))
979     {
980         DeletePlatformInfo();
981         return OC_STACK_INVALID_PARAM;
982     }
983
984     return OC_STACK_OK;
985
986 }
987
988 OCStackResult SavePlatformInfo(OCPlatformInfo info)
989 {
990     DeletePlatformInfo();
991
992     OCStackResult res = DeepCopyPlatFormInfo(info);
993
994     if (res != OC_STACK_OK)
995     {
996         OC_LOG_V(ERROR, TAG, PCF("Failed to save platform info. errno(%d)"), res);
997     }
998     else
999     {
1000         OC_LOG(ERROR, TAG, PCF("Platform info saved."));
1001     }
1002
1003     return res;
1004 }
1005
1006 void DeleteDeviceInfo()
1007 {
1008     OC_LOG(INFO, TAG, PCF("Deleting device info."));
1009
1010     OICFree(savedDeviceInfo.deviceName);
1011     savedDeviceInfo.deviceName = NULL;
1012 }
1013
1014 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1015 {
1016     savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1017
1018     if(!savedDeviceInfo.deviceName && info.deviceName)
1019     {
1020         DeleteDeviceInfo();
1021         return OC_STACK_NO_MEMORY;
1022     }
1023
1024     return OC_STACK_OK;
1025 }
1026
1027 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1028 {
1029     OCStackResult res = OC_STACK_OK;
1030
1031     DeleteDeviceInfo();
1032
1033     res = DeepCopyDeviceInfo(info);
1034
1035     VERIFY_SUCCESS(res, OC_STACK_OK);
1036
1037     if(OCGetServerInstanceID() == NULL)
1038     {
1039         OC_LOG(INFO, TAG, PCF("Device ID generation failed"));
1040         res =  OC_STACK_ERROR;
1041         goto exit;
1042     }
1043
1044     OC_LOG(INFO, TAG, PCF("Device initialized successfully."));
1045     return OC_STACK_OK;
1046
1047     exit:
1048         DeleteDeviceInfo();
1049         return res;
1050
1051 }