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