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