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