Merge branch 'master' into cloud-interface
[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
29 #ifdef WITH_STRING_H
30 #include <string.h>
31 #endif
32 #ifdef WITH_STRINGS_H
33 #include <strings.h>
34 #endif
35
36 #include "ocresource.h"
37 #include "ocresourcehandler.h"
38 #include "ocobserve.h"
39 #include "occollection.h"
40 #include "oic_malloc.h"
41 #include "oic_string.h"
42 #include "logger.h"
43 #include "cJSON.h"
44 #include "ocpayload.h"
45 #include "secureresourcemanager.h"
46 #include "cacommon.h"
47 #include "cainterface.h"
48 #include "rdpayload.h"
49 #include "ocpayload.h"
50
51 #ifdef WITH_RD
52 #include "rd_server.h"
53 #endif
54
55 #ifdef ROUTING_GATEWAY
56 #include "routingmanager.h"
57 #endif
58
59 /// Module Name
60 #define TAG "OIC_RI_RESOURCE"
61
62 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
63             {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
64
65 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
66              TAG, #arg " is NULL"); return (retVal); } }
67
68 #include "platform_features.h"
69
70 extern OCResource *headResource;
71 static OCPlatformInfo savedPlatformInfo = {0};
72 static OCDeviceInfo savedDeviceInfo = {0};
73
74 /**
75  * Prepares a Payload for response.
76  */
77 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
78                                                   OCDiscoveryPayload* payload,
79                                                   OCDevAddr *endpoint,
80                                                   bool rdResponse);
81
82 //-----------------------------------------------------------------------------
83 // Default resource entity handler function
84 //-----------------------------------------------------------------------------
85 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
86         OCEntityHandlerRequest * request, void* callbackParam)
87 {
88     //TODO ("Implement me!!!!");
89     // TODO:  remove silence unused param warnings
90     (void) flag;
91     (void) request;
92     (void) callbackParam;
93     return  OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
94 }
95
96 /* This method will retrieve the port at which the secure resource is hosted */
97 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
98 {
99     uint16_t p = 0;
100
101     if (endpoint->adapter == OC_ADAPTER_IP)
102     {
103         if (endpoint->flags & OC_IP_USE_V6)
104         {
105             p = caglobals.ip.u6s.port;
106         }
107         else if (endpoint->flags & OC_IP_USE_V4)
108         {
109             p = caglobals.ip.u4s.port;
110         }
111     }
112
113     *port = p;
114     return OC_STACK_OK;
115 }
116
117 #ifdef TCP_ADAPTER
118 /* This method will retrieve the tcp port */
119 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
120 {
121     uint16_t p = 0;
122
123     if (endpoint->adapter == OC_ADAPTER_IP)
124     {
125         if (endpoint->flags & OC_IP_USE_V4)
126         {
127             p = caglobals.tcp.ipv4.port;
128         }
129         else if (endpoint->flags & OC_IP_USE_V6)
130         {
131             p = caglobals.tcp.ipv6.port;
132         }
133     }
134
135     *port = p;
136     return OC_STACK_OK;
137 }
138 #endif
139
140 /*
141  * Function will extract 0, 1 or 2 filters from query.
142  * More than 2 filters or unsupported filters will result in error.
143  * If both filters are of the same supported type, the 2nd one will be picked.
144  * Resource and device filters in the SAME query are NOT validated
145  * and resources will likely not clear filters.
146  */
147 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
148 {
149
150     char *key = NULL;
151     char *value = NULL;
152     char *restOfQuery = NULL;
153     int numKeyValuePairsParsed = 0;
154
155     *filterOne = NULL;
156     *filterTwo = NULL;
157
158     OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
159
160     char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
161
162     while(keyValuePair)
163     {
164         if (numKeyValuePairsParsed >= 2)
165         {
166             OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
167             return OC_STACK_INVALID_QUERY;
168         }
169
170         key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
171
172         if (!key || !value)
173         {
174             return OC_STACK_INVALID_QUERY;
175         }
176         else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
177         {
178             *filterOne = value;     // if
179         }
180         else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
181         {
182             *filterTwo = value;     // rt
183         }
184         else
185         {
186             OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
187             return OC_STACK_INVALID_QUERY;
188         }
189         ++numKeyValuePairsParsed;
190
191         keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
192     }
193
194     OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
195     return OC_STACK_OK;
196 }
197
198 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
199 {
200     if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
201     {
202         return OC_WELL_KNOWN_URI;
203     }
204     else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
205     {
206         return OC_DEVICE_URI;
207     }
208     else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
209     {
210         return OC_PLATFORM_URI;
211     }
212     else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
213     {
214         return OC_RESOURCE_TYPES_URI;
215     }
216 #ifdef ROUTING_GATEWAY
217     else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
218     {
219         return OC_GATEWAY_URI;
220     }
221 #endif
222 #ifdef WITH_PRESENCE
223     else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
224     {
225         return OC_PRESENCE;
226     }
227 #endif //WITH_PRESENCE
228     return OC_UNKNOWN_URI;
229 }
230
231 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
232                                             char **filterOne, char **filterTwo)
233 {
234     if(!filterOne || !filterTwo)
235     {
236         return OC_STACK_INVALID_PARAM;
237     }
238
239     *filterOne = NULL;
240     *filterTwo = NULL;
241
242     #ifdef WITH_PRESENCE
243     if (uri == OC_PRESENCE)
244     {
245         //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
246         OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
247         return OC_STACK_OK;
248     }
249     #endif
250
251     OCStackResult result = OC_STACK_OK;
252
253     if (query && *query)
254     {
255         result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
256     }
257
258     return result;
259 }
260
261 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
262                     OCRepPayload** payload)
263 {
264     OCRepPayload *tempPayload = OCRepPayloadCreate();
265
266     if (!resourcePtr)
267     {
268         OCRepPayloadDestroy(tempPayload);
269         return OC_STACK_INVALID_PARAM;
270     }
271
272     if(!tempPayload)
273     {
274         return OC_STACK_NO_MEMORY;
275     }
276
277     OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
278
279     OCResourceType *resType = resourcePtr->rsrcType;
280     while(resType)
281     {
282         OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
283         resType = resType->next;
284     }
285
286     OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
287     while(resInterface)
288     {
289         OCRepPayloadAddInterface(tempPayload, resInterface->name);
290         resInterface = resInterface->next;
291     }
292
293     OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
294     while(resAttrib)
295     {
296         OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
297                                 resAttrib->attrValue);
298         resAttrib = resAttrib->next;
299     }
300
301     if(!*payload)
302     {
303         *payload = tempPayload;
304     }
305     else
306     {
307         OCRepPayloadAppend(*payload, tempPayload);
308     }
309
310     return OC_STACK_OK;
311 }
312
313 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
314                         OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
315 {
316     if (!resourcePtr || !payload)
317     {
318         return OC_STACK_INVALID_PARAM;
319     }
320     uint16_t securePort = 0;
321     if (resourcePtr->resourceProperties & OC_SECURE)
322     {
323        if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
324        {
325            securePort = 0;
326        }
327     }
328
329     if (rdResponse)
330     {
331         securePort = devAddr->port;
332     }
333
334     uint16_t tcpPort = 0;
335 #ifdef TCP_ADAPTER
336     if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
337     {
338         tcpPort = 0;
339     }
340     OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
341 #else
342     OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
343 #endif
344
345     return OC_STACK_OK;
346 }
347
348 uint8_t IsCollectionResource (OCResource *resource)
349 {
350     if(!resource)
351     {
352         return 0;
353     }
354
355     if(resource->rsrcChildResourcesHead != NULL)
356     {
357         return 1;
358     }
359
360     return 0;
361 }
362
363 OCResource *FindResourceByUri(const char* resourceUri)
364 {
365     if(!resourceUri)
366     {
367         return NULL;
368     }
369
370     OCResource * pointer = headResource;
371     while (pointer)
372     {
373         if (strcmp(resourceUri, pointer->uri) == 0)
374         {
375             return pointer;
376         }
377         pointer = pointer->next;
378     }
379     OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
380     return NULL;
381 }
382
383
384 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
385                                          ResourceHandling *handling,
386                                          OCResource **resource)
387 {
388     if(!request || !handling || !resource)
389     {
390         return OC_STACK_INVALID_PARAM;
391     }
392
393     OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
394
395     // Check if virtual resource
396     if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
397     {
398         OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
399         *handling = OC_RESOURCE_VIRTUAL;
400         *resource = headResource;
401         return OC_STACK_OK;
402     }
403     if (strlen((const char*)(request->resourceUrl)) == 0)
404     {
405         // Resource URL not specified
406         *handling = OC_RESOURCE_NOT_SPECIFIED;
407         return OC_STACK_NO_RESOURCE;
408     }
409     else
410     {
411         OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
412         *resource = resourcePtr;
413         if (!resourcePtr)
414         {
415             if(defaultDeviceHandler)
416             {
417                 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
418                 return OC_STACK_OK;
419             }
420
421             // Resource does not exist
422             // and default device handler does not exist
423             *handling = OC_RESOURCE_NOT_SPECIFIED;
424             return OC_STACK_NO_RESOURCE;
425         }
426
427         if (IsCollectionResource (resourcePtr))
428         {
429             // Collection resource
430             if (resourcePtr->entityHandler != defaultResourceEHandler)
431             {
432                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
433                 return OC_STACK_OK;
434             }
435             else
436             {
437                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
438                 return OC_STACK_OK;
439             }
440         }
441         else
442         {
443             // Resource not a collection
444             if (resourcePtr->entityHandler != defaultResourceEHandler)
445             {
446                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
447                 return OC_STACK_OK;
448             }
449             else
450             {
451                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
452                 return OC_STACK_OK;
453             }
454         }
455     }
456 }
457
458 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
459 {
460     OCStackResult result;
461
462     switch (ehResult)
463     {
464         case OC_EH_OK:
465             result = OC_STACK_OK;
466             break;
467         case OC_EH_SLOW:
468             result = OC_STACK_SLOW_RESOURCE;
469             break;
470         case OC_EH_ERROR:
471             result = OC_STACK_ERROR;
472             break;
473         case OC_EH_FORBIDDEN:
474             result = OC_STACK_RESOURCE_ERROR;
475             break;
476         case OC_EH_RESOURCE_CREATED:
477             result = OC_STACK_RESOURCE_CREATED;
478             break;
479         case OC_EH_RESOURCE_DELETED:
480             result = OC_STACK_RESOURCE_DELETED;
481             break;
482         case OC_EH_RESOURCE_NOT_FOUND:
483             result = OC_STACK_NO_RESOURCE;
484             break;
485         default:
486             result = OC_STACK_ERROR;
487     }
488
489     return result;
490 }
491
492 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
493 {
494     if (!resource)
495     {
496         return false;
497     }
498
499     // Null or empty is analogous to no filter.
500     if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
501     {
502         return true;
503     }
504
505     OCResourceType *resourceTypePtr = resource->rsrcType;
506
507     while (resourceTypePtr)
508     {
509         if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
510         {
511             return true;
512         }
513         resourceTypePtr = resourceTypePtr->next;
514     }
515
516     OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
517     return false;
518 }
519
520 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
521 {
522     if (!resource)
523     {
524         return false;
525     }
526
527     // Null or empty is analogous to no filter.
528     if (interfaceFilter == NULL || *interfaceFilter == 0)
529     {
530         return true;
531     }
532
533     OCResourceInterface *interfacePtr = resource->rsrcInterface;
534
535     while (interfacePtr)
536     {
537         if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
538             (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
539              strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
540         {
541             return true;
542         }
543         interfacePtr = interfacePtr->next;
544     }
545
546     OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
547     return false;
548 }
549
550 /*
551  * If the filters are null, they will be assumed to NOT be present
552  * and the resource will not be matched against them.
553  * Function will return true if all non null AND non empty filters passed in find a match.
554  */
555 static bool includeThisResourceInResponse(OCResource *resource,
556                                           char *interfaceFilter,
557                                           char *resourceTypeFilter)
558 {
559     if (!resource)
560     {
561         OIC_LOG(ERROR, TAG, "Invalid resource");
562         return false;
563     }
564
565     if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
566     {
567         /*
568          * At least one valid filter should be available to
569          * include the resource in discovery response
570          */
571         if (!(resourceTypeFilter && *resourceTypeFilter))
572         {
573             OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
574                 resource", resource->uri);
575             return false;
576         }
577     }
578     else if ( !(resource->resourceProperties & OC_ACTIVE) ||
579          !(resource->resourceProperties & OC_DISCOVERABLE))
580     {
581         OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
582         return false;
583     }
584
585     return resourceMatchesIFFilter(resource, interfaceFilter) &&
586            resourceMatchesRTFilter(resource, resourceTypeFilter);
587
588 }
589
590 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
591                                 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
592 {
593     OCEntityHandlerResponse response = {0};
594
595     response.ehResult = ehResult;
596     response.payload = discoveryPayload;
597     response.persistentBufferFlag = 0;
598     response.requestHandle = (OCRequestHandle) request;
599     response.resourceHandle = (OCResourceHandle) resource;
600
601     return OCDoResponse(&response);
602 }
603
604 #ifdef WITH_RD
605 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
606      OCResource **payload, OCDevAddr *devAddr)
607 {
608     OCResourceCollectionPayload *repPayload;
609     if (!payload)
610     {
611         return OC_STACK_ERROR;
612     }
613     if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
614     {
615         if (!repPayload)
616         {
617             return OC_STACK_ERROR;
618         }
619         OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
620         if (!ptr)
621         {
622            return OC_STACK_NO_MEMORY;
623         }
624
625         ptr->uri = OICStrdup(repPayload->setLinks->href);
626         if (!ptr->uri)
627         {
628            return OC_STACK_NO_MEMORY;
629         }
630         OCStringLL *rt = repPayload->setLinks->rt;
631         while (rt)
632         {
633             OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
634             if(!temp)
635             {
636                 OICFree(ptr->uri);
637                 return OC_STACK_NO_MEMORY;
638             }
639             temp->next = NULL;
640             temp->resourcetypename = OICStrdup(rt->value);
641             if (!ptr->rsrcType)
642             {
643                 ptr->rsrcType = temp;
644             }
645             else
646             {
647                 OCResourceType *type = ptr->rsrcType;
648                 while (type->next)
649                 {
650                     type = type->next;
651                 }
652                 type->next = temp;
653             }
654             rt = rt->next;
655         }
656
657         OCStringLL *itf = repPayload->setLinks->itf;
658         while (itf)
659         {
660             OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
661             if (!temp)
662             {
663                 OICFree(ptr->uri);
664
665                 return OC_STACK_NO_MEMORY;
666             }
667             temp->next = NULL;
668             temp->name = OICStrdup(itf->value);
669             if (!ptr->rsrcInterface)
670             {
671                 ptr->rsrcInterface = temp;
672             }
673             else
674             {
675                 OCResourceInterface *type = ptr->rsrcInterface;
676                 while (type->next)
677                 {
678                     type = type->next;
679                 }
680                 type->next = temp;
681             }
682             itf = itf->next;
683         }
684
685         ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
686
687         OCFreeCollectionResource(repPayload);
688         *payload = ptr;
689         return OC_STACK_OK;
690     }
691     else
692     {
693         OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
694                              on the resource directory");
695     }
696     return OC_STACK_ERROR;
697 }
698 #endif
699
700 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
701 {
702     if (!request || !resource)
703     {
704         return OC_STACK_INVALID_PARAM;
705     }
706
707     OCStackResult discoveryResult = OC_STACK_ERROR;
708
709     bool bMulticast    = false;     // Was the discovery request a multicast request?
710     OCPayload* payload = NULL;
711
712     OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
713
714     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
715
716     // Step 1: Generate the response to discovery request
717     if (virtualUriInRequest == OC_WELL_KNOWN_URI)
718     {
719         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
720         {
721             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
722             return OC_STACK_UNAUTHORIZED_REQ;
723         }
724
725         char *interfaceQuery = NULL;
726         char *resourceTypeQuery = NULL;
727
728         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
729                 &interfaceQuery, &resourceTypeQuery);
730         bool interfaceQueryAllocated = false;
731         if (!interfaceQuery && !resourceTypeQuery)
732         {
733             interfaceQueryAllocated = true;
734             interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
735         }
736
737         if (discoveryResult == OC_STACK_OK)
738         {
739             payload = (OCPayload *)OCDiscoveryPayloadCreate();
740
741             if (payload)
742             {
743                 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
744                 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
745                 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
746
747                 const char* uid = OCGetServerInstanceIDString();
748                 if (uid)
749                 {
750                     memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
751                 }
752
753                 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
754                 {
755                     for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
756                     {
757                         bool result = false;
758                         if (resource->resourceProperties & OC_DISCOVERABLE)
759                         {
760                             result = true;
761                         }
762
763                         if (result)
764                         {
765                             discoveryResult = BuildVirtualResourceResponse(resource,
766                             discPayload, &request->devAddr, false);
767                         }
768                     }
769                 }
770                 else
771                 {
772                     if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
773                     {
774                         discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
775                         VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
776                         if (savedDeviceInfo.deviceName)
777                         {
778                             discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
779                             VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
780                         }
781                         discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
782                         VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
783                         discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
784                         VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
785                         OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
786                         OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
787                         VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
788                     }
789                     bool foundResourceAtRD = false;
790                     for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
791                     {
792 #ifdef WITH_RD
793                         if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
794                         {
795                             OCResource *resource1 = NULL;
796                             OCDevAddr devAddr;
797                             discoveryResult = checkResourceExistsAtRD(interfaceQuery,
798                                 resourceTypeQuery, &resource1, &devAddr);
799                             if (discoveryResult != OC_STACK_OK)
800                             {
801                                  break;
802                             }
803                             discoveryResult = BuildVirtualResourceResponse(resource1,
804                                 discPayload, &devAddr, true);
805                             if (payload)
806                             {
807                                 discPayload->baseURI = OICStrdup(devAddr.addr);
808                             }
809                             OICFree(resource1->uri);
810                             for (OCResourceType *rsrcRt = resource1->rsrcType, *rsrcRtNext = NULL; rsrcRt; )
811                             {
812                                 rsrcRtNext = rsrcRt->next;
813                                 OICFree(rsrcRt->resourcetypename);
814                                 OICFree(rsrcRt);
815                                 rsrcRt = rsrcRtNext;
816                             }
817
818                             for (OCResourceInterface *rsrcPtr = resource1->rsrcInterface, *rsrcNext = NULL; rsrcPtr; )
819                             {
820                                 rsrcNext = rsrcPtr->next;
821                                 OICFree(rsrcPtr->name);
822                                 OICFree(rsrcPtr);
823                                 rsrcPtr = rsrcNext;
824                             }
825                             foundResourceAtRD = true;
826                         }
827 #endif
828                         if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
829                         {
830                             discoveryResult = BuildVirtualResourceResponse(resource,
831                                 discPayload, &request->devAddr, false);
832                         }
833                     }
834                     // Set discoveryResult appropriately if no 'valid' resources are available
835                     if (discPayload->resources == NULL && !foundResourceAtRD)
836                     {
837                         discoveryResult = OC_STACK_NO_RESOURCE;
838                     }
839                 }
840             }
841             else
842             {
843                 discoveryResult = OC_STACK_NO_MEMORY;
844             }
845         }
846         else
847         {
848             OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
849         }
850         if (interfaceQueryAllocated)
851         {
852             OICFree(interfaceQuery);
853         }
854     }
855     else if (virtualUriInRequest == OC_DEVICE_URI)
856     {
857         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
858         {
859             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
860             return OC_STACK_UNAUTHORIZED_REQ;
861         }
862
863         const char* deviceId = OCGetServerInstanceIDString();
864         if (!deviceId)
865         {
866             discoveryResult = OC_STACK_ERROR;
867         }
868         else
869         {
870             char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
871             if (!dataModelVersions)
872             {
873                 discoveryResult = OC_STACK_NO_MEMORY;
874             }
875             else
876             {
877                 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
878                     savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
879                 if (!payload)
880                 {
881                      discoveryResult = OC_STACK_NO_MEMORY;
882                 }
883                 else
884                 {
885                      discoveryResult = OC_STACK_OK;
886                 }
887                 OICFree(dataModelVersions);
888             }
889         }
890     }
891     else if (virtualUriInRequest == OC_PLATFORM_URI)
892     {
893         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
894         {
895             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
896             return OC_STACK_UNAUTHORIZED_REQ;
897         }
898
899         payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
900         if (!payload)
901         {
902             discoveryResult = OC_STACK_NO_MEMORY;
903         }
904         else
905         {
906             discoveryResult = OC_STACK_OK;
907         }
908     }
909 #ifdef ROUTING_GATEWAY
910     else if (OC_GATEWAY_URI == virtualUriInRequest)
911     {
912         // Received request for a gateway
913         OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
914         discoveryResult = RMHandleGatewayRequest(request, resource);
915
916     }
917 #endif
918
919     /**
920      * Step 2: Send the discovery response
921      *
922      * Iotivity should respond to discovery requests in below manner:
923      * 1)If query filter matching fails and discovery request is multicast,
924      *   it should NOT send any response.
925      * 2)If query filter matching fails and discovery request is unicast,
926      *   it should send an error(RESOURCE_NOT_FOUND - 404) response.
927      * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
928      *   request is multicast, it should NOT send any response.
929      * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
930      *   request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
931      */
932
933 #ifdef WITH_PRESENCE
934     if ((virtualUriInRequest == OC_PRESENCE) &&
935         (resource->resourceProperties & OC_ACTIVE))
936     {
937         // Presence uses observer notification api to respond via SendPresenceNotification.
938         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
939     }
940     else
941     #endif
942 #ifdef ROUTING_GATEWAY
943     // Gateway uses the RMHandleGatewayRequest to respond to the request.
944     if (OC_GATEWAY_URI != virtualUriInRequest)
945 #endif
946     {
947         if(discoveryResult == OC_STACK_OK)
948         {
949             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
950         }
951         else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
952                (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
953         {
954             OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d)  \
955                 discovery request", discoveryResult, virtualUriInRequest);
956             SendNonPersistantDiscoveryResponse(request, resource, NULL,
957                 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
958         }
959         else
960         {
961             // Ignoring the discovery request as per RFC 7252, Section #8.2
962             OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
963                 any useful data to send");
964         }
965     }
966
967     OCPayloadDestroy(payload);
968
969     return OC_STACK_OK;
970 }
971
972 static OCStackResult
973 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
974 {
975     if(!request)
976     {
977         return OC_STACK_INVALID_PARAM;
978     }
979
980     OCStackResult result = OC_STACK_OK;
981     OCEntityHandlerResult ehResult = OC_EH_ERROR;
982     OCEntityHandlerRequest ehRequest = {0};
983
984     OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
985     result = FormOCEntityHandlerRequest(&ehRequest,
986                                         (OCRequestHandle) request,
987                                         request->method,
988                                         &request->devAddr,
989                                         (OCResourceHandle) NULL, request->query,
990                                         PAYLOAD_TYPE_REPRESENTATION,
991                                         request->payload,
992                                         request->payloadSize,
993                                         request->numRcvdVendorSpecificHeaderOptions,
994                                         request->rcvdVendorSpecificHeaderOptions,
995                                         (OCObserveAction)request->observationOption,
996                                         (OCObservationId)0,
997                                         request->coapID);
998     VERIFY_SUCCESS(result, OC_STACK_OK);
999
1000     // At this point we know for sure that defaultDeviceHandler exists
1001     ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
1002                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
1003     if(ehResult == OC_EH_SLOW)
1004     {
1005         OIC_LOG(INFO, TAG, "This is a slow resource");
1006         request->slowFlag = 1;
1007     }
1008     else if(ehResult == OC_EH_ERROR)
1009     {
1010         FindAndDeleteServerRequest(request);
1011     }
1012     result = EntityHandlerCodeToOCStackCode(ehResult);
1013 exit:
1014     OCPayloadDestroy(ehRequest.payload);
1015     return result;
1016 }
1017
1018 static OCStackResult
1019 HandleResourceWithEntityHandler (OCServerRequest *request,
1020                                  OCResource *resource,
1021                                  uint8_t collectionResource)
1022 {
1023     if(!request || ! resource)
1024     {
1025         return OC_STACK_INVALID_PARAM;
1026     }
1027
1028     OCStackResult result = OC_STACK_ERROR;
1029     OCEntityHandlerResult ehResult = OC_EH_ERROR;
1030     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1031     ResourceObserver *resObs = NULL;
1032
1033     OCEntityHandlerRequest ehRequest = {0};
1034
1035     OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1036     OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1037     // check the security resource
1038     if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1039     {
1040         type = PAYLOAD_TYPE_SECURITY;
1041
1042     }
1043
1044     if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
1045     {
1046         type = PAYLOAD_TYPE_RD;
1047     }
1048
1049     result = FormOCEntityHandlerRequest(&ehRequest,
1050                                         (OCRequestHandle)request,
1051                                         request->method,
1052                                         &request->devAddr,
1053                                         (OCResourceHandle)resource,
1054                                         request->query,
1055                                         type,
1056                                         request->payload,
1057                                         request->payloadSize,
1058                                         request->numRcvdVendorSpecificHeaderOptions,
1059                                         request->rcvdVendorSpecificHeaderOptions,
1060                                         (OCObserveAction)request->observationOption,
1061                                         0,
1062                                         request->coapID);
1063     VERIFY_SUCCESS(result, OC_STACK_OK);
1064
1065     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1066     {
1067         OIC_LOG(INFO, TAG, "No observation requested");
1068         ehFlag = OC_REQUEST_FLAG;
1069     }
1070     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
1071     {
1072         OIC_LOG(INFO, TAG, "Observation registration requested");
1073
1074         ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1075                                     request->tokenLength);
1076
1077         if (obs)
1078         {
1079             OIC_LOG (INFO, TAG, "Observer with this token already present");
1080             OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1081             OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1082             OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1083
1084             // server requests are usually free'd when the response is sent out
1085             // for the request in ocserverrequest.c : HandleSingleResponse()
1086             // Since we are making an early return and not responding, the server request
1087             // needs to be deleted.
1088             FindAndDeleteServerRequest (request);
1089             return OC_STACK_OK;
1090         }
1091
1092         result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1093         VERIFY_SUCCESS(result, OC_STACK_OK);
1094
1095         result = AddObserver ((const char*)(request->resourceUrl),
1096                 (const char *)(request->query),
1097                 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1098                 resource, request->qos, request->acceptFormat,
1099                 &request->devAddr);
1100
1101         if(result == OC_STACK_OK)
1102         {
1103             OIC_LOG(INFO, TAG, "Added observer successfully");
1104             request->observeResult = OC_STACK_OK;
1105             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1106         }
1107         else
1108         {
1109             // The error in observeResult for the request will be used when responding to this
1110             // request by omitting the observation option/sequence number.
1111             request->observeResult = OC_STACK_ERROR;
1112             OIC_LOG(ERROR, TAG, "Observer Addition failed");
1113             ehFlag = OC_REQUEST_FLAG;
1114             FindAndDeleteServerRequest(request);
1115             goto exit;
1116         }
1117
1118     }
1119     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1120             !collectionResource)
1121     {
1122         OIC_LOG(INFO, TAG, "Deregistering observation requested");
1123
1124         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1125
1126         if (NULL == resObs)
1127         {
1128             // Stack does not contain this observation request
1129             // Either token is incorrect or observation list is corrupted
1130             result = OC_STACK_ERROR;
1131             goto exit;
1132         }
1133         ehRequest.obsInfo.obsId = resObs->observeId;
1134         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1135
1136         result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1137
1138         if(result == OC_STACK_OK)
1139         {
1140             OIC_LOG(INFO, TAG, "Removed observer successfully");
1141             request->observeResult = OC_STACK_OK;
1142         }
1143         else
1144         {
1145             request->observeResult = OC_STACK_ERROR;
1146             OIC_LOG(ERROR, TAG, "Observer Removal failed");
1147             FindAndDeleteServerRequest(request);
1148             goto exit;
1149         }
1150     }
1151     else
1152     {
1153         result = OC_STACK_ERROR;
1154         goto exit;
1155     }
1156
1157     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1158     if(ehResult == OC_EH_SLOW)
1159     {
1160         OIC_LOG(INFO, TAG, "This is a slow resource");
1161         request->slowFlag = 1;
1162     }
1163     else if(ehResult == OC_EH_ERROR)
1164     {
1165         FindAndDeleteServerRequest(request);
1166     }
1167     result = EntityHandlerCodeToOCStackCode(ehResult);
1168 exit:
1169     OCPayloadDestroy(ehRequest.payload);
1170     return result;
1171 }
1172
1173 static OCStackResult
1174 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1175                                               OCResource *resource)
1176 {
1177     if(!request || !resource)
1178     {
1179         return OC_STACK_INVALID_PARAM;
1180     }
1181
1182     OCStackResult result = OC_STACK_ERROR;
1183     OCEntityHandlerRequest ehRequest = {0};
1184
1185     result = FormOCEntityHandlerRequest(&ehRequest,
1186                                         (OCRequestHandle)request,
1187                                         request->method,
1188                                         &request->devAddr,
1189                                         (OCResourceHandle)resource,
1190                                         request->query,
1191                                         PAYLOAD_TYPE_REPRESENTATION,
1192                                         request->payload,
1193                                         request->payloadSize,
1194                                         request->numRcvdVendorSpecificHeaderOptions,
1195                                         request->rcvdVendorSpecificHeaderOptions,
1196                                         (OCObserveAction)request->observationOption,
1197                                         (OCObservationId)0,
1198                                         request->coapID);
1199     if(result == OC_STACK_OK)
1200     {
1201         result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1202     }
1203
1204     OCPayloadDestroy(ehRequest.payload);
1205     return result;
1206 }
1207
1208 OCStackResult
1209 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1210 {
1211     OCStackResult ret = OC_STACK_OK;
1212
1213     switch (resHandling)
1214     {
1215         case OC_RESOURCE_VIRTUAL:
1216         {
1217             ret = HandleVirtualResource (request, resource);
1218             break;
1219         }
1220         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1221         {
1222             ret = HandleDefaultDeviceEntityHandler(request);
1223             break;
1224         }
1225         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1226         {
1227             OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1228             return OC_STACK_ERROR;
1229         }
1230         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1231         {
1232             ret = HandleResourceWithEntityHandler (request, resource, 0);
1233             break;
1234         }
1235         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1236         {
1237             ret = HandleResourceWithEntityHandler (request, resource, 1);
1238             break;
1239         }
1240         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1241         {
1242             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1243             break;
1244         }
1245         case OC_RESOURCE_NOT_SPECIFIED:
1246         {
1247             ret = OC_STACK_NO_RESOURCE;
1248             break;
1249         }
1250         default:
1251         {
1252             OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1253             return OC_STACK_ERROR;
1254         }
1255     }
1256     return ret;
1257 }
1258
1259 void DeletePlatformInfo()
1260 {
1261     OIC_LOG(INFO, TAG, "Deleting platform info.");
1262
1263     OICFree(savedPlatformInfo.platformID);
1264     savedPlatformInfo.platformID = NULL;
1265
1266     OICFree(savedPlatformInfo.manufacturerName);
1267     savedPlatformInfo.manufacturerName = NULL;
1268
1269     OICFree(savedPlatformInfo.manufacturerUrl);
1270     savedPlatformInfo.manufacturerUrl = NULL;
1271
1272     OICFree(savedPlatformInfo.modelNumber);
1273     savedPlatformInfo.modelNumber = NULL;
1274
1275     OICFree(savedPlatformInfo.dateOfManufacture);
1276     savedPlatformInfo.dateOfManufacture = NULL;
1277
1278     OICFree(savedPlatformInfo.platformVersion);
1279     savedPlatformInfo.platformVersion = NULL;
1280
1281     OICFree(savedPlatformInfo.operatingSystemVersion);
1282     savedPlatformInfo.operatingSystemVersion = NULL;
1283
1284     OICFree(savedPlatformInfo.hardwareVersion);
1285     savedPlatformInfo.hardwareVersion = NULL;
1286
1287     OICFree(savedPlatformInfo.firmwareVersion);
1288     savedPlatformInfo.firmwareVersion = NULL;
1289
1290     OICFree(savedPlatformInfo.supportUrl);
1291     savedPlatformInfo.supportUrl = NULL;
1292
1293     OICFree(savedPlatformInfo.systemTime);
1294     savedPlatformInfo.systemTime = NULL;
1295 }
1296
1297 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1298 {
1299     savedPlatformInfo.platformID = OICStrdup(info.platformID);
1300     savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1301     savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1302     savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1303     savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1304     savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1305     savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1306     savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1307     savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1308     savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1309     savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1310
1311     if ((!savedPlatformInfo.platformID && info.platformID)||
1312         (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1313         (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1314         (!savedPlatformInfo.modelNumber && info.modelNumber)||
1315         (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1316         (!savedPlatformInfo.platformVersion && info.platformVersion)||
1317         (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1318         (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1319         (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1320         (!savedPlatformInfo.supportUrl && info.supportUrl)||
1321         (!savedPlatformInfo.systemTime && info.systemTime))
1322     {
1323         DeletePlatformInfo();
1324         return OC_STACK_INVALID_PARAM;
1325     }
1326
1327     return OC_STACK_OK;
1328
1329 }
1330
1331 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1332 {
1333     DeletePlatformInfo();
1334
1335     OCStackResult res = DeepCopyPlatFormInfo(info);
1336
1337     if (res != OC_STACK_OK)
1338     {
1339         OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1340     }
1341     else
1342     {
1343         OIC_LOG(INFO, TAG, "Platform info saved.");
1344     }
1345
1346     return res;
1347 }
1348
1349 void DeleteDeviceInfo()
1350 {
1351     OIC_LOG(INFO, TAG, "Deleting device info.");
1352
1353     OICFree(savedDeviceInfo.deviceName);
1354     OCFreeOCStringLL(savedDeviceInfo.types);
1355     OICFree(savedDeviceInfo.specVersion);
1356     OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1357     savedDeviceInfo.deviceName = NULL;
1358     savedDeviceInfo.specVersion = NULL;
1359     savedDeviceInfo.dataModelVersions = NULL;
1360 }
1361
1362 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1363 {
1364     savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1365
1366     if(!savedDeviceInfo.deviceName && info.deviceName)
1367     {
1368         DeleteDeviceInfo();
1369         return OC_STACK_NO_MEMORY;
1370     }
1371
1372     if (info.types)
1373     {
1374         savedDeviceInfo.types = CloneOCStringLL(info.types);
1375         if(!savedDeviceInfo.types && info.types)
1376         {
1377             DeleteDeviceInfo();
1378             return OC_STACK_NO_MEMORY;
1379         }
1380     }
1381
1382     if (info.specVersion)
1383     {
1384         savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1385         if(!savedDeviceInfo.specVersion && info.specVersion)
1386         {
1387             DeleteDeviceInfo();
1388             return OC_STACK_NO_MEMORY;
1389         }
1390     }
1391     else
1392     {
1393         savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1394         if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1395         {
1396             DeleteDeviceInfo();
1397             return OC_STACK_NO_MEMORY;
1398         }
1399     }
1400
1401     if (info.dataModelVersions)
1402     {
1403         savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1404         if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1405         {
1406             DeleteDeviceInfo();
1407             return OC_STACK_NO_MEMORY;
1408         }
1409     }
1410     else
1411     {
1412         savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1413         if (!savedDeviceInfo.dataModelVersions)
1414         {
1415             return OC_STACK_NO_MEMORY;
1416         }
1417         savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1418         if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1419         {
1420             DeleteDeviceInfo();
1421             return OC_STACK_NO_MEMORY;
1422         }
1423     }
1424
1425     return OC_STACK_OK;
1426 }
1427
1428 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1429 {
1430     OCStackResult res = OC_STACK_OK;
1431
1432     DeleteDeviceInfo();
1433
1434     res = DeepCopyDeviceInfo(info);
1435
1436     VERIFY_SUCCESS(res, OC_STACK_OK);
1437
1438     if (OCGetServerInstanceIDString() == NULL)
1439     {
1440         OIC_LOG(INFO, TAG, "Device ID generation failed");
1441         res =  OC_STACK_ERROR;
1442         goto exit;
1443     }
1444
1445     OIC_LOG(INFO, TAG, "Device initialized successfully.");
1446     return OC_STACK_OK;
1447
1448 exit:
1449     DeleteDeviceInfo();
1450     return res;
1451 }