Add API support to get and set device spec version and data model version.
[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     uint16_t tcpPort = 0;
332 #ifdef TCP_ADAPTER
333     if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
334     {
335         tcpPort = 0;
336     }
337 #endif
338
339     OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
340     return OC_STACK_OK;
341 }
342
343 uint8_t IsCollectionResource (OCResource *resource)
344 {
345     if(!resource)
346     {
347         return 0;
348     }
349
350     if(resource->rsrcChildResourcesHead != NULL)
351     {
352         return 1;
353     }
354
355     return 0;
356 }
357
358 OCResource *FindResourceByUri(const char* resourceUri)
359 {
360     if(!resourceUri)
361     {
362         return NULL;
363     }
364
365     OCResource * pointer = headResource;
366     while (pointer)
367     {
368         if (strcmp(resourceUri, pointer->uri) == 0)
369         {
370             return pointer;
371         }
372         pointer = pointer->next;
373     }
374     OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
375     return NULL;
376 }
377
378
379 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
380                                          ResourceHandling *handling,
381                                          OCResource **resource)
382 {
383     if(!request || !handling || !resource)
384     {
385         return OC_STACK_INVALID_PARAM;
386     }
387
388     OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
389
390     // Check if virtual resource
391     if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
392     {
393         OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
394         *handling = OC_RESOURCE_VIRTUAL;
395         *resource = headResource;
396         return OC_STACK_OK;
397     }
398     if (strlen((const char*)(request->resourceUrl)) == 0)
399     {
400         // Resource URL not specified
401         *handling = OC_RESOURCE_NOT_SPECIFIED;
402         return OC_STACK_NO_RESOURCE;
403     }
404     else
405     {
406         OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
407         *resource = resourcePtr;
408         if (!resourcePtr)
409         {
410             if(defaultDeviceHandler)
411             {
412                 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
413                 return OC_STACK_OK;
414             }
415
416             // Resource does not exist
417             // and default device handler does not exist
418             *handling = OC_RESOURCE_NOT_SPECIFIED;
419             return OC_STACK_NO_RESOURCE;
420         }
421
422         if (IsCollectionResource (resourcePtr))
423         {
424             // Collection resource
425             if (resourcePtr->entityHandler != defaultResourceEHandler)
426             {
427                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
428                 return OC_STACK_OK;
429             }
430             else
431             {
432                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
433                 return OC_STACK_OK;
434             }
435         }
436         else
437         {
438             // Resource not a collection
439             if (resourcePtr->entityHandler != defaultResourceEHandler)
440             {
441                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
442                 return OC_STACK_OK;
443             }
444             else
445             {
446                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
447                 return OC_STACK_OK;
448             }
449         }
450     }
451 }
452
453 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
454 {
455     OCStackResult result;
456
457     switch (ehResult)
458     {
459         case OC_EH_OK:
460             result = OC_STACK_OK;
461             break;
462         case OC_EH_SLOW:
463             result = OC_STACK_SLOW_RESOURCE;
464             break;
465         case OC_EH_ERROR:
466             result = OC_STACK_ERROR;
467             break;
468         case OC_EH_FORBIDDEN:
469             result = OC_STACK_RESOURCE_ERROR;
470             break;
471         case OC_EH_RESOURCE_CREATED:
472             result = OC_STACK_RESOURCE_CREATED;
473             break;
474         case OC_EH_RESOURCE_DELETED:
475             result = OC_STACK_RESOURCE_DELETED;
476             break;
477         case OC_EH_RESOURCE_NOT_FOUND:
478             result = OC_STACK_NO_RESOURCE;
479             break;
480         default:
481             result = OC_STACK_ERROR;
482     }
483
484     return result;
485 }
486
487 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
488 {
489     if (!resource)
490     {
491         return false;
492     }
493
494     // Null or empty is analogous to no filter.
495     if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
496     {
497         return true;
498     }
499
500     OCResourceType *resourceTypePtr = resource->rsrcType;
501
502     while (resourceTypePtr)
503     {
504         if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
505         {
506             return true;
507         }
508         resourceTypePtr = resourceTypePtr->next;
509     }
510
511     OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
512     return false;
513 }
514
515 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
516 {
517     if (!resource)
518     {
519         return false;
520     }
521
522     // Null or empty is analogous to no filter.
523     if (interfaceFilter == NULL || *interfaceFilter == 0)
524     {
525         return true;
526     }
527
528     OCResourceInterface *interfacePtr = resource->rsrcInterface;
529
530     while (interfacePtr)
531     {
532         if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
533             (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
534              strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
535         {
536             return true;
537         }
538         interfacePtr = interfacePtr->next;
539     }
540
541     OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
542     return false;
543 }
544
545 /*
546  * If the filters are null, they will be assumed to NOT be present
547  * and the resource will not be matched against them.
548  * Function will return true if all non null AND non empty filters passed in find a match.
549  */
550 static bool includeThisResourceInResponse(OCResource *resource,
551                                           char *interfaceFilter,
552                                           char *resourceTypeFilter)
553 {
554     if (!resource)
555     {
556         OIC_LOG(ERROR, TAG, "Invalid resource");
557         return false;
558     }
559
560     if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
561     {
562         /*
563          * At least one valid filter should be available to
564          * include the resource in discovery response
565          */
566         if (!(resourceTypeFilter && *resourceTypeFilter))
567         {
568             OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
569                 resource", resource->uri);
570             return false;
571         }
572     }
573     else if ( !(resource->resourceProperties & OC_ACTIVE) ||
574          !(resource->resourceProperties & OC_DISCOVERABLE))
575     {
576         OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
577         return false;
578     }
579
580     return resourceMatchesIFFilter(resource, interfaceFilter) &&
581            resourceMatchesRTFilter(resource, resourceTypeFilter);
582
583 }
584
585 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
586                                 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
587 {
588     OCEntityHandlerResponse response = {0};
589
590     response.ehResult = ehResult;
591     response.payload = discoveryPayload;
592     response.persistentBufferFlag = 0;
593     response.requestHandle = (OCRequestHandle) request;
594     response.resourceHandle = (OCResourceHandle) resource;
595
596     return OCDoResponse(&response);
597 }
598
599 #ifdef WITH_RD
600 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
601      OCResource **payload, OCDevAddr *devAddr)
602 {
603     OCResourceCollectionPayload *repPayload;
604     if (!payload)
605     {
606         return OC_STACK_ERROR;
607     }
608     if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
609     {
610         if (!repPayload)
611         {
612             return OC_STACK_ERROR;
613         }
614         OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
615         if (!ptr)
616         {
617            return OC_STACK_NO_MEMORY;
618         }
619
620         ptr->uri = OICStrdup(repPayload->setLinks->href);
621         if (!ptr->uri)
622         {
623            return OC_STACK_NO_MEMORY;
624         }
625         OCStringLL *rt = repPayload->setLinks->rt;
626         while (rt)
627         {
628             OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
629             if(!temp)
630             {
631                 OICFree(ptr->uri);
632                 return OC_STACK_NO_MEMORY;
633             }
634             temp->next = NULL;
635             temp->resourcetypename = OICStrdup(rt->value);
636             if (!ptr->rsrcType)
637             {
638                 ptr->rsrcType = temp;
639             }
640             else
641             {
642                 OCResourceType *type = ptr->rsrcType;
643                 while (type->next)
644                 {
645                     type = type->next;
646                 }
647                 type->next = temp;
648             }
649             rt = rt->next;
650         }
651
652         OCStringLL *itf = repPayload->setLinks->itf;
653         while (itf)
654         {
655             OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
656             if (!temp)
657             {
658                 OICFree(ptr->uri);
659
660                 return OC_STACK_NO_MEMORY;
661             }
662             temp->next = NULL;
663             temp->name = OICStrdup(itf->value);
664             if (!ptr->rsrcInterface)
665             {
666                 ptr->rsrcInterface = temp;
667             }
668             else
669             {
670                 OCResourceInterface *type = ptr->rsrcInterface;
671                 while (type->next)
672                 {
673                     type = type->next;
674                 }
675                 type->next = temp;
676             }
677             itf = itf->next;
678         }
679
680         ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
681
682         OCFreeCollectionResource(repPayload);
683         *payload = ptr;
684         return OC_STACK_OK;
685     }
686     else
687     {
688         OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
689                              on the resource directory");
690     }
691     return OC_STACK_ERROR;
692 }
693 #endif
694
695 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
696 {
697     if (!request || !resource)
698     {
699         return OC_STACK_INVALID_PARAM;
700     }
701
702     OCStackResult discoveryResult = OC_STACK_ERROR;
703
704     bool bMulticast    = false;     // Was the discovery request a multicast request?
705     OCPayload* payload = NULL;
706
707     OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
708
709     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
710
711     // Step 1: Generate the response to discovery request
712     if (virtualUriInRequest == OC_WELL_KNOWN_URI)
713     {
714         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
715         {
716             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
717             return OC_STACK_UNAUTHORIZED_REQ;
718         }
719
720         char *interfaceQuery = NULL;
721         char *resourceTypeQuery = NULL;
722
723         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
724                 &interfaceQuery, &resourceTypeQuery);
725         bool interfaceQueryAllocated = false;
726         if (!interfaceQuery && !resourceTypeQuery)
727         {
728             interfaceQueryAllocated = true;
729             interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
730         }
731
732         if (discoveryResult == OC_STACK_OK)
733         {
734             payload = (OCPayload *)OCDiscoveryPayloadCreate();
735
736             if (payload)
737             {
738                 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
739                 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
740                 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
741
742                 const char* uid = OCGetServerInstanceIDString();
743                 if (uid)
744                 {
745                     memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
746                 }
747
748                 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
749                 {
750                     for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
751                     {
752                         bool result = false;
753                         if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
754                         {
755                             if (resourceTypeQuery && resourceMatchesRTFilter(resource, resourceTypeQuery))
756                             {
757                                 result = true;
758                             }
759                         }
760                         if (resource->resourceProperties & OC_DISCOVERABLE)
761                         {
762                             result = true;
763                         }
764
765                         if (result)
766                         {
767                             discoveryResult = BuildVirtualResourceResponse(resource,
768                             discPayload, &request->devAddr, false);
769                         }
770                     }
771                 }
772                 else
773                 {
774                     if ((interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))) ||
775                         !interfaceQuery)
776                     {
777                         discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
778                         VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
779                         if (savedDeviceInfo.deviceName)
780                         {
781                             discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
782                             VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
783                         }
784                         discPayload->type = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
785                         VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
786                         OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_LL);
787                         OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_DEFAULT);
788                         VERIFY_NON_NULL(discPayload->interface, ERROR, OC_STACK_NO_MEMORY);
789                     }
790                     bool foundResourceAtRD = false;
791                     for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
792                     {
793 #ifdef WITH_RD
794                         if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
795                         {
796                             OCResource *resource1 = NULL;
797                             OCDevAddr devAddr;
798                             discoveryResult = checkResourceExistsAtRD(interfaceQuery,
799                                 resourceTypeQuery, &resource1, &devAddr);
800                             if (discoveryResult != OC_STACK_OK)
801                             {
802                                  break;
803                             }
804                             discoveryResult = BuildVirtualResourceResponse(resource1,
805                                 discPayload, &devAddr, true);
806                             if (payload)
807                             {
808                                 discPayload->baseURI = OICStrdup(devAddr.addr);
809                             }
810                             OICFree(resource1->uri);
811                             for (OCResourceType *rsrcRt = resource1->rsrcType, *rsrcRtNext = NULL; rsrcRt; )
812                             {
813                                 rsrcRtNext = rsrcRt->next;
814                                 OICFree(rsrcRt->resourcetypename);
815                                 OICFree(rsrcRt);
816                                 rsrcRt = rsrcRtNext;
817                             }
818
819                             for (OCResourceInterface *rsrcPtr = resource1->rsrcInterface, *rsrcNext = NULL; rsrcPtr; )
820                             {
821                                 rsrcNext = rsrcPtr->next;
822                                 OICFree(rsrcPtr->name);
823                                 OICFree(rsrcPtr);
824                                 rsrcPtr = rsrcNext;
825                             }
826                             foundResourceAtRD = true;
827                         }
828 #endif
829                         if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
830                         {
831                             discoveryResult = BuildVirtualResourceResponse(resource,
832                                 discPayload, &request->devAddr, false);
833                         }
834                     }
835                     // Set discoveryResult appropriately if no 'valid' resources are available
836                     if (discPayload->resources == NULL && !foundResourceAtRD)
837                     {
838                         discoveryResult = OC_STACK_NO_RESOURCE;
839                     }
840                 }
841             }
842             else
843             {
844                 discoveryResult = OC_STACK_NO_MEMORY;
845             }
846         }
847         else
848         {
849             OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
850         }
851         if (interfaceQueryAllocated)
852         {
853             OICFree(interfaceQuery);
854         }
855     }
856     else if (virtualUriInRequest == OC_DEVICE_URI)
857     {
858         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
859         {
860             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
861             return OC_STACK_UNAUTHORIZED_REQ;
862         }
863
864         const char* deviceId = OCGetServerInstanceIDString();
865         if (!deviceId)
866         {
867             discoveryResult = OC_STACK_ERROR;
868         }
869         else
870         {
871             payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
872                 savedDeviceInfo.types, savedDeviceInfo.specVersion, savedDeviceInfo.dataModleVersion);
873             if (!payload)
874             {
875                 discoveryResult = OC_STACK_NO_MEMORY;
876             }
877             else
878             {
879                 discoveryResult = OC_STACK_OK;
880             }
881         }
882     }
883     else if (virtualUriInRequest == OC_PLATFORM_URI)
884     {
885         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
886         {
887             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
888             return OC_STACK_UNAUTHORIZED_REQ;
889         }
890
891         payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
892         if (!payload)
893         {
894             discoveryResult = OC_STACK_NO_MEMORY;
895         }
896         else
897         {
898             discoveryResult = OC_STACK_OK;
899         }
900     }
901 #ifdef ROUTING_GATEWAY
902     else if (OC_GATEWAY_URI == virtualUriInRequest)
903     {
904         // Received request for a gateway
905         OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
906         discoveryResult = RMHandleGatewayRequest(request, resource);
907
908     }
909 #endif
910
911     /**
912      * Step 2: Send the discovery response
913      *
914      * Iotivity should respond to discovery requests in below manner:
915      * 1)If query filter matching fails and discovery request is multicast,
916      *   it should NOT send any response.
917      * 2)If query filter matching fails and discovery request is unicast,
918      *   it should send an error(RESOURCE_NOT_FOUND - 404) response.
919      * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
920      *   request is multicast, it should NOT send any response.
921      * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
922      *   request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
923      */
924
925 #ifdef WITH_PRESENCE
926     if ((virtualUriInRequest == OC_PRESENCE) &&
927         (resource->resourceProperties & OC_ACTIVE))
928     {
929         // Presence uses observer notification api to respond via SendPresenceNotification.
930         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
931     }
932     else
933     #endif
934 #ifdef ROUTING_GATEWAY
935     // Gateway uses the RMHandleGatewayRequest to respond to the request.
936     if (OC_GATEWAY_URI != virtualUriInRequest)
937 #endif
938     {
939         if(discoveryResult == OC_STACK_OK)
940         {
941             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
942         }
943         else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
944                (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
945         {
946             OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d)  \
947                 discovery request", discoveryResult, virtualUriInRequest);
948             SendNonPersistantDiscoveryResponse(request, resource, NULL,
949                 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
950         }
951         else
952         {
953             // Ignoring the discovery request as per RFC 7252, Section #8.2
954             OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
955                 any useful data to send");
956         }
957     }
958
959     OCPayloadDestroy(payload);
960
961     return OC_STACK_OK;
962 }
963
964 static OCStackResult
965 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
966 {
967     if(!request)
968     {
969         return OC_STACK_INVALID_PARAM;
970     }
971
972     OCStackResult result = OC_STACK_OK;
973     OCEntityHandlerResult ehResult = OC_EH_ERROR;
974     OCEntityHandlerRequest ehRequest = {0};
975
976     OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
977     result = FormOCEntityHandlerRequest(&ehRequest,
978                                         (OCRequestHandle) request,
979                                         request->method,
980                                         &request->devAddr,
981                                         (OCResourceHandle) NULL, request->query,
982                                         PAYLOAD_TYPE_REPRESENTATION,
983                                         request->payload,
984                                         request->payloadSize,
985                                         request->numRcvdVendorSpecificHeaderOptions,
986                                         request->rcvdVendorSpecificHeaderOptions,
987                                         (OCObserveAction)request->observationOption,
988                                         (OCObservationId)0);
989     VERIFY_SUCCESS(result, OC_STACK_OK);
990
991     // At this point we know for sure that defaultDeviceHandler exists
992     ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
993                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
994     if(ehResult == OC_EH_SLOW)
995     {
996         OIC_LOG(INFO, TAG, "This is a slow resource");
997         request->slowFlag = 1;
998     }
999     else if(ehResult == OC_EH_ERROR)
1000     {
1001         FindAndDeleteServerRequest(request);
1002     }
1003     result = EntityHandlerCodeToOCStackCode(ehResult);
1004 exit:
1005     OCPayloadDestroy(ehRequest.payload);
1006     return result;
1007 }
1008
1009 static OCStackResult
1010 HandleResourceWithEntityHandler (OCServerRequest *request,
1011                                  OCResource *resource,
1012                                  uint8_t collectionResource)
1013 {
1014     if(!request || ! resource)
1015     {
1016         return OC_STACK_INVALID_PARAM;
1017     }
1018
1019     OCStackResult result = OC_STACK_ERROR;
1020     OCEntityHandlerResult ehResult = OC_EH_ERROR;
1021     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1022     ResourceObserver *resObs = NULL;
1023
1024     OCEntityHandlerRequest ehRequest = {0};
1025
1026     OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1027     OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1028     // check the security resource
1029     if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1030     {
1031         type = PAYLOAD_TYPE_SECURITY;
1032
1033     }
1034
1035     if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
1036     {
1037         type = PAYLOAD_TYPE_RD;
1038     }
1039
1040     result = FormOCEntityHandlerRequest(&ehRequest,
1041                                         (OCRequestHandle)request,
1042                                         request->method,
1043                                         &request->devAddr,
1044                                         (OCResourceHandle)resource,
1045                                         request->query,
1046                                         type,
1047                                         request->payload,
1048                                         request->payloadSize,
1049                                         request->numRcvdVendorSpecificHeaderOptions,
1050                                         request->rcvdVendorSpecificHeaderOptions,
1051                                         (OCObserveAction)request->observationOption,
1052                                         0);
1053     VERIFY_SUCCESS(result, OC_STACK_OK);
1054
1055     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1056     {
1057         OIC_LOG(INFO, TAG, "No observation requested");
1058         ehFlag = OC_REQUEST_FLAG;
1059     }
1060     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
1061     {
1062         OIC_LOG(INFO, TAG, "Observation registration requested");
1063
1064         ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1065                                     request->tokenLength);
1066
1067         if (obs)
1068         {
1069             OIC_LOG (INFO, TAG, "Observer with this token already present");
1070             OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1071             OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1072             OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1073
1074             // server requests are usually free'd when the response is sent out
1075             // for the request in ocserverrequest.c : HandleSingleResponse()
1076             // Since we are making an early return and not responding, the server request
1077             // needs to be deleted.
1078             FindAndDeleteServerRequest (request);
1079             return OC_STACK_OK;
1080         }
1081
1082         result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1083         VERIFY_SUCCESS(result, OC_STACK_OK);
1084
1085         result = AddObserver ((const char*)(request->resourceUrl),
1086                 (const char *)(request->query),
1087                 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1088                 resource, request->qos, request->acceptFormat,
1089                 &request->devAddr);
1090
1091         if(result == OC_STACK_OK)
1092         {
1093             OIC_LOG(INFO, TAG, "Added observer successfully");
1094             request->observeResult = OC_STACK_OK;
1095             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1096         }
1097         else
1098         {
1099             result = OC_STACK_OK;
1100
1101             // The error in observeResult for the request will be used when responding to this
1102             // request by omitting the observation option/sequence number.
1103             request->observeResult = OC_STACK_ERROR;
1104             OIC_LOG(ERROR, TAG, "Observer Addition failed");
1105             ehFlag = OC_REQUEST_FLAG;
1106         }
1107
1108     }
1109     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1110             !collectionResource)
1111     {
1112         OIC_LOG(INFO, TAG, "Deregistering observation requested");
1113
1114         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1115
1116         if (NULL == resObs)
1117         {
1118             // Stack does not contain this observation request
1119             // Either token is incorrect or observation list is corrupted
1120             result = OC_STACK_ERROR;
1121             goto exit;
1122         }
1123         ehRequest.obsInfo.obsId = resObs->observeId;
1124         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1125
1126         result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1127
1128         if(result == OC_STACK_OK)
1129         {
1130             OIC_LOG(INFO, TAG, "Removed observer successfully");
1131             request->observeResult = OC_STACK_OK;
1132         }
1133         else
1134         {
1135             result = OC_STACK_OK;
1136             request->observeResult = OC_STACK_ERROR;
1137             OIC_LOG(ERROR, TAG, "Observer Removal failed");
1138         }
1139     }
1140     else
1141     {
1142         result = OC_STACK_ERROR;
1143         goto exit;
1144     }
1145
1146     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1147     if(ehResult == OC_EH_SLOW)
1148     {
1149         OIC_LOG(INFO, TAG, "This is a slow resource");
1150         request->slowFlag = 1;
1151     }
1152     else if(ehResult == OC_EH_ERROR)
1153     {
1154         FindAndDeleteServerRequest(request);
1155     }
1156     result = EntityHandlerCodeToOCStackCode(ehResult);
1157 exit:
1158     OCPayloadDestroy(ehRequest.payload);
1159     return result;
1160 }
1161
1162 static OCStackResult
1163 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1164                                               OCResource *resource)
1165 {
1166     if(!request || !resource)
1167     {
1168         return OC_STACK_INVALID_PARAM;
1169     }
1170
1171     OCStackResult result = OC_STACK_ERROR;
1172     OCEntityHandlerRequest ehRequest = {0};
1173
1174     result = FormOCEntityHandlerRequest(&ehRequest,
1175                                         (OCRequestHandle)request,
1176                                         request->method,
1177                                         &request->devAddr,
1178                                         (OCResourceHandle)resource,
1179                                         request->query,
1180                                         PAYLOAD_TYPE_REPRESENTATION,
1181                                         request->payload,
1182                                         request->payloadSize,
1183                                         request->numRcvdVendorSpecificHeaderOptions,
1184                                         request->rcvdVendorSpecificHeaderOptions,
1185                                         (OCObserveAction)request->observationOption,
1186                                         (OCObservationId)0);
1187     if(result == OC_STACK_OK)
1188     {
1189         result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1190     }
1191
1192     OCPayloadDestroy(ehRequest.payload);
1193     return result;
1194 }
1195
1196 OCStackResult
1197 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1198 {
1199     OCStackResult ret = OC_STACK_OK;
1200
1201     switch (resHandling)
1202     {
1203         case OC_RESOURCE_VIRTUAL:
1204         {
1205             ret = HandleVirtualResource (request, resource);
1206             break;
1207         }
1208         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1209         {
1210             ret = HandleDefaultDeviceEntityHandler(request);
1211             break;
1212         }
1213         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1214         {
1215             OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1216             return OC_STACK_ERROR;
1217         }
1218         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1219         {
1220             ret = HandleResourceWithEntityHandler (request, resource, 0);
1221             break;
1222         }
1223         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1224         {
1225             ret = HandleResourceWithEntityHandler (request, resource, 1);
1226             break;
1227         }
1228         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1229         {
1230             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1231             break;
1232         }
1233         case OC_RESOURCE_NOT_SPECIFIED:
1234         {
1235             ret = OC_STACK_NO_RESOURCE;
1236             break;
1237         }
1238         default:
1239         {
1240             OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1241             return OC_STACK_ERROR;
1242         }
1243     }
1244     return ret;
1245 }
1246
1247 void DeletePlatformInfo()
1248 {
1249     OIC_LOG(INFO, TAG, "Deleting platform info.");
1250
1251     OICFree(savedPlatformInfo.platformID);
1252     savedPlatformInfo.platformID = NULL;
1253
1254     OICFree(savedPlatformInfo.manufacturerName);
1255     savedPlatformInfo.manufacturerName = NULL;
1256
1257     OICFree(savedPlatformInfo.manufacturerUrl);
1258     savedPlatformInfo.manufacturerUrl = NULL;
1259
1260     OICFree(savedPlatformInfo.modelNumber);
1261     savedPlatformInfo.modelNumber = NULL;
1262
1263     OICFree(savedPlatformInfo.dateOfManufacture);
1264     savedPlatformInfo.dateOfManufacture = NULL;
1265
1266     OICFree(savedPlatformInfo.platformVersion);
1267     savedPlatformInfo.platformVersion = NULL;
1268
1269     OICFree(savedPlatformInfo.operatingSystemVersion);
1270     savedPlatformInfo.operatingSystemVersion = NULL;
1271
1272     OICFree(savedPlatformInfo.hardwareVersion);
1273     savedPlatformInfo.hardwareVersion = NULL;
1274
1275     OICFree(savedPlatformInfo.firmwareVersion);
1276     savedPlatformInfo.firmwareVersion = NULL;
1277
1278     OICFree(savedPlatformInfo.supportUrl);
1279     savedPlatformInfo.supportUrl = NULL;
1280
1281     OICFree(savedPlatformInfo.systemTime);
1282     savedPlatformInfo.systemTime = NULL;
1283 }
1284
1285 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1286 {
1287     savedPlatformInfo.platformID = OICStrdup(info.platformID);
1288     savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1289     savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1290     savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1291     savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1292     savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1293     savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1294     savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1295     savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1296     savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1297     savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1298
1299     if ((!savedPlatformInfo.platformID && info.platformID)||
1300         (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1301         (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1302         (!savedPlatformInfo.modelNumber && info.modelNumber)||
1303         (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1304         (!savedPlatformInfo.platformVersion && info.platformVersion)||
1305         (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1306         (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1307         (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1308         (!savedPlatformInfo.supportUrl && info.supportUrl)||
1309         (!savedPlatformInfo.systemTime && info.systemTime))
1310     {
1311         DeletePlatformInfo();
1312         return OC_STACK_INVALID_PARAM;
1313     }
1314
1315     return OC_STACK_OK;
1316
1317 }
1318
1319 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1320 {
1321     DeletePlatformInfo();
1322
1323     OCStackResult res = DeepCopyPlatFormInfo(info);
1324
1325     if (res != OC_STACK_OK)
1326     {
1327         OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1328     }
1329     else
1330     {
1331         OIC_LOG(INFO, TAG, "Platform info saved.");
1332     }
1333
1334     return res;
1335 }
1336
1337 void DeleteDeviceInfo()
1338 {
1339     OIC_LOG(INFO, TAG, "Deleting device info.");
1340
1341     OICFree(savedDeviceInfo.deviceName);
1342     OCFreeOCStringLL(savedDeviceInfo.types);
1343     OICFree(savedDeviceInfo.specVersion);
1344     OICFree(savedDeviceInfo.dataModleVersion);
1345     savedDeviceInfo.deviceName = NULL;
1346     savedDeviceInfo.specVersion = NULL;
1347     savedDeviceInfo.dataModleVersion = NULL;
1348 }
1349
1350 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1351 {
1352     savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1353
1354     if(!savedDeviceInfo.deviceName && info.deviceName)
1355     {
1356         DeleteDeviceInfo();
1357         return OC_STACK_NO_MEMORY;
1358     }
1359
1360     if (info.types)
1361     {
1362         savedDeviceInfo.types = CloneOCStringLL(info.types);
1363         if(!savedDeviceInfo.types && info.types)
1364         {
1365             DeleteDeviceInfo();
1366             return OC_STACK_NO_MEMORY;
1367         }
1368     }
1369
1370     if (info.specVersion)
1371     {
1372         savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1373         if(!savedDeviceInfo.specVersion && info.specVersion)
1374         {
1375             DeleteDeviceInfo();
1376             return OC_STACK_NO_MEMORY;
1377         }
1378     }
1379     else
1380     {
1381         savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1382         if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1383         {
1384             DeleteDeviceInfo();
1385             return OC_STACK_NO_MEMORY;
1386         }
1387     }
1388
1389     if (info.dataModleVersion)
1390     {
1391         savedDeviceInfo.dataModleVersion = OICStrdup(info.dataModleVersion);
1392         if(!savedDeviceInfo.dataModleVersion && info.dataModleVersion)
1393         {
1394             DeleteDeviceInfo();
1395             return OC_STACK_NO_MEMORY;
1396         }
1397     }
1398     else
1399     {
1400         savedDeviceInfo.dataModleVersion = OICStrdup(OC_DATA_MODEL_VERSION);
1401         if(!savedDeviceInfo.dataModleVersion && OC_DATA_MODEL_VERSION)
1402         {
1403             DeleteDeviceInfo();
1404             return OC_STACK_NO_MEMORY;
1405         }
1406     }
1407
1408     return OC_STACK_OK;
1409 }
1410
1411 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1412 {
1413     OCStackResult res = OC_STACK_OK;
1414
1415     DeleteDeviceInfo();
1416
1417     res = DeepCopyDeviceInfo(info);
1418
1419     VERIFY_SUCCESS(res, OC_STACK_OK);
1420
1421     if (OCGetServerInstanceIDString() == NULL)
1422     {
1423         OIC_LOG(INFO, TAG, "Device ID generation failed");
1424         res =  OC_STACK_ERROR;
1425         goto exit;
1426     }
1427
1428     OIC_LOG(INFO, TAG, "Device initialized successfully.");
1429     return OC_STACK_OK;
1430
1431 exit:
1432     DeleteDeviceInfo();
1433     return res;
1434 }