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