Clean compilar warnings
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocresource.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1-2001 base
24 // specification (excluding the XSI extension).
25 // For POSIX.1-2001 base specification,
26 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
27 #define _POSIX_C_SOURCE 200112L
28 #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 #ifdef TCP_ADAPTER
346     uint16_t tcpPort = 0;
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         case OC_EH_CONTENT:
477         case OC_EH_VALID:
478             result = OC_STACK_OK;
479             break;
480         case OC_EH_SLOW:
481             result = OC_STACK_SLOW_RESOURCE;
482             break;
483         case OC_EH_ERROR:
484             result = OC_STACK_ERROR;
485             break;
486         case OC_EH_FORBIDDEN:
487             result = OC_STACK_RESOURCE_ERROR;
488             break;
489         case OC_EH_RESOURCE_CREATED:
490             result = OC_STACK_RESOURCE_CREATED;
491             break;
492         case OC_EH_RESOURCE_DELETED:
493             result = OC_STACK_RESOURCE_DELETED;
494             break;
495         case OC_EH_CHANGED:
496             result = OC_STACK_RESOURCE_CHANGED;
497             break;
498         case OC_EH_RESOURCE_NOT_FOUND:
499             result = OC_STACK_NO_RESOURCE;
500             break;
501         default:
502             result = OC_STACK_ERROR;
503     }
504
505     return result;
506 }
507
508 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
509 {
510     if (!resource)
511     {
512         return false;
513     }
514
515     // Null or empty is analogous to no filter.
516     if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
517     {
518         return true;
519     }
520
521     OCResourceType *resourceTypePtr = resource->rsrcType;
522
523     while (resourceTypePtr)
524     {
525         if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
526         {
527             return true;
528         }
529         resourceTypePtr = resourceTypePtr->next;
530     }
531
532     OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
533     return false;
534 }
535
536 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
537 {
538     if (!resource)
539     {
540         return false;
541     }
542
543     // Null or empty is analogous to no filter.
544     if (interfaceFilter == NULL || *interfaceFilter == 0)
545     {
546         return true;
547     }
548
549     OCResourceInterface *interfacePtr = resource->rsrcInterface;
550
551     while (interfacePtr)
552     {
553         if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
554             (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
555              strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
556         {
557             return true;
558         }
559         interfacePtr = interfacePtr->next;
560     }
561
562     OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
563     return false;
564 }
565
566 /*
567  * If the filters are null, they will be assumed to NOT be present
568  * and the resource will not be matched against them.
569  * Function will return true if all non null AND non empty filters passed in find a match.
570  */
571 static bool includeThisResourceInResponse(OCResource *resource,
572                                           char *interfaceFilter,
573                                           char *resourceTypeFilter)
574 {
575     if (!resource)
576     {
577         OIC_LOG(ERROR, TAG, "Invalid resource");
578         return false;
579     }
580
581     if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
582     {
583         /*
584          * At least one valid filter should be available to
585          * include the resource in discovery response
586          */
587         if (!(resourceTypeFilter && *resourceTypeFilter))
588         {
589             OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
590                 resource", resource->uri);
591             return false;
592         }
593     }
594     else if ( !(resource->resourceProperties & OC_ACTIVE) ||
595          !(resource->resourceProperties & OC_DISCOVERABLE))
596     {
597         OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
598         return false;
599     }
600
601     return resourceMatchesIFFilter(resource, interfaceFilter) &&
602            resourceMatchesRTFilter(resource, resourceTypeFilter);
603
604 }
605
606 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
607                                 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
608 {
609     OCEntityHandlerResponse response = {0};
610
611     response.ehResult = ehResult;
612     response.payload = discoveryPayload;
613     response.persistentBufferFlag = 0;
614     response.requestHandle = (OCRequestHandle) request;
615     response.resourceHandle = (OCResourceHandle) resource;
616
617     return OCDoResponse(&response);
618 }
619
620 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
621 {
622     if (!request || !resource)
623     {
624         return OC_STACK_INVALID_PARAM;
625     }
626
627     OCStackResult discoveryResult = OC_STACK_ERROR;
628     OCPayload* payload = NULL;
629
630     OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
631
632     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
633
634     // Step 1: Generate the response to discovery request
635     if (virtualUriInRequest == OC_WELL_KNOWN_URI
636 #ifdef MQ_BROKER
637             || virtualUriInRequest == OC_MQ_BROKER_URI
638 #endif
639             )
640     {
641         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
642         {
643             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
644             return OC_STACK_UNAUTHORIZED_REQ;
645         }
646
647         char *interfaceQuery = NULL;
648         char *resourceTypeQuery = NULL;
649
650         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
651                 &interfaceQuery, &resourceTypeQuery);
652         bool interfaceQueryAllocated = false;
653         if (!interfaceQuery && !resourceTypeQuery)
654         {
655             interfaceQueryAllocated = true;
656             interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
657         }
658
659         if (discoveryResult == OC_STACK_OK)
660         {
661             payload = (OCPayload *)OCDiscoveryPayloadCreate();
662
663             if (payload)
664             {
665                 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
666                 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
667                 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
668
669                 const char* uid = OCGetServerInstanceIDString();
670                 if (uid)
671                 {
672                     memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
673                 }
674
675                 if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
676                 {
677                     OCResourceProperty prop = OC_DISCOVERABLE;
678 #ifdef MQ_BROKER
679                     if (OC_MQ_BROKER_URI == virtualUriInRequest)
680                     {
681                         prop = OC_MQ_BROKER;
682                     }
683 #endif
684
685                     for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
686                     {
687                         bool result = false;
688
689                         if (resource->resourceProperties & prop)
690                         {
691                             result = true;
692                         }
693
694                         if (result)
695                         {
696                             discoveryResult = BuildVirtualResourceResponse(resource,
697                             discPayload, &request->devAddr, false);
698                         }
699                     }
700                 }
701                 else
702                 {
703                     if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
704                     {
705                         discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
706                         VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
707                         if (savedDeviceInfo.deviceName)
708                         {
709                             discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
710                             VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
711                         }
712                         discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
713                         VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
714                         discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
715                         VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
716                         OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
717                         OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
718                         VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
719                     }
720                     bool foundResourceAtRD = false;
721                     for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
722                     {
723                         if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
724                         {
725                             discoveryResult = BuildVirtualResourceResponse(resource,
726                                 discPayload, &request->devAddr, false);
727                         }
728                     }
729                     // Set discoveryResult appropriately if no 'valid' resources are available
730                     if (discPayload->resources == NULL && !foundResourceAtRD)
731                     {
732                         discoveryResult = OC_STACK_NO_RESOURCE;
733                     }
734                 }
735             }
736             else
737             {
738                 discoveryResult = OC_STACK_NO_MEMORY;
739             }
740         }
741         else
742         {
743             OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
744         }
745         if (interfaceQueryAllocated)
746         {
747             OICFree(interfaceQuery);
748         }
749     }
750     else if (virtualUriInRequest == OC_DEVICE_URI)
751     {
752         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
753         {
754             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
755             return OC_STACK_UNAUTHORIZED_REQ;
756         }
757
758         const char* deviceId = OCGetServerInstanceIDString();
759         if (!deviceId)
760         {
761             discoveryResult = OC_STACK_ERROR;
762         }
763         else
764         {
765             char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
766             if (!dataModelVersions)
767             {
768                 discoveryResult = OC_STACK_NO_MEMORY;
769             }
770             else
771             {
772                 payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
773                     savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
774                 if (!payload)
775                 {
776                      discoveryResult = OC_STACK_NO_MEMORY;
777                 }
778                 else
779                 {
780                      discoveryResult = OC_STACK_OK;
781                 }
782                 OICFree(dataModelVersions);
783             }
784         }
785     }
786     else if (virtualUriInRequest == OC_PLATFORM_URI)
787     {
788         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
789         {
790             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
791             return OC_STACK_UNAUTHORIZED_REQ;
792         }
793
794         payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
795         if (!payload)
796         {
797             discoveryResult = OC_STACK_NO_MEMORY;
798         }
799         else
800         {
801             discoveryResult = OC_STACK_OK;
802         }
803     }
804 #ifdef ROUTING_GATEWAY
805     else if (OC_GATEWAY_URI == virtualUriInRequest)
806     {
807         // Received request for a gateway
808         OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
809         discoveryResult = RMHandleGatewayRequest(request, resource);
810
811     }
812 #endif
813
814     /**
815      * Step 2: Send the discovery response
816      *
817      * Iotivity should respond to discovery requests in below manner:
818      * 1)If query filter matching fails and discovery request is multicast,
819      *   it should NOT send any response.
820      * 2)If query filter matching fails and discovery request is unicast,
821      *   it should send an error(RESOURCE_NOT_FOUND - 404) response.
822      * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
823      *   request is multicast, it should NOT send any response.
824      * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
825      *   request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
826      */
827
828 #ifdef WITH_PRESENCE
829     if ((virtualUriInRequest == OC_PRESENCE) &&
830         (resource->resourceProperties & OC_ACTIVE))
831     {
832         // Need to send ACK when the request is CON.
833         if (request->qos == OC_HIGH_QOS)
834         {
835             CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
836             CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
837             SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
838                                     0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
839         }
840
841         // Presence uses observer notification api to respond via SendPresenceNotification.
842         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
843     }
844     else
845     #endif
846 #ifdef ROUTING_GATEWAY
847     // Gateway uses the RMHandleGatewayRequest to respond to the request.
848     if (OC_GATEWAY_URI != virtualUriInRequest)
849 #endif
850     {
851         if(discoveryResult == OC_STACK_OK)
852         {
853             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
854         }
855         else if(((request->devAddr.flags &  OC_MULTICAST) == false) &&
856             (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
857             (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
858         {
859             OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
860                 discoveryResult, virtualUriInRequest);
861             SendNonPersistantDiscoveryResponse(request, resource, NULL,
862                 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
863         }
864         else
865         {
866             // Ignoring the discovery request as per RFC 7252, Section #8.2
867             OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
868         }
869     }
870
871     OCPayloadDestroy(payload);
872
873     return OC_STACK_OK;
874 }
875
876 static OCStackResult
877 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
878 {
879     if(!request)
880     {
881         return OC_STACK_INVALID_PARAM;
882     }
883
884     OCStackResult result = OC_STACK_OK;
885     OCEntityHandlerResult ehResult = OC_EH_ERROR;
886     OCEntityHandlerRequest ehRequest = {0};
887
888     OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
889     result = FormOCEntityHandlerRequest(&ehRequest,
890                                         (OCRequestHandle) request,
891                                         request->method,
892                                         &request->devAddr,
893                                         (OCResourceHandle) NULL, request->query,
894                                         PAYLOAD_TYPE_REPRESENTATION,
895                                         request->payload,
896                                         request->payloadSize,
897                                         request->numRcvdVendorSpecificHeaderOptions,
898                                         request->rcvdVendorSpecificHeaderOptions,
899                                         (OCObserveAction)request->observationOption,
900                                         (OCObservationId)0,
901                                         request->coapID);
902     VERIFY_SUCCESS(result, OC_STACK_OK);
903
904     // At this point we know for sure that defaultDeviceHandler exists
905     ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
906                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
907     if(ehResult == OC_EH_SLOW)
908     {
909         OIC_LOG(INFO, TAG, "This is a slow resource");
910         request->slowFlag = 1;
911     }
912     else if(ehResult == OC_EH_ERROR)
913     {
914         FindAndDeleteServerRequest(request);
915     }
916     result = EntityHandlerCodeToOCStackCode(ehResult);
917 exit:
918     OCPayloadDestroy(ehRequest.payload);
919     return result;
920 }
921
922 static OCStackResult
923 HandleResourceWithEntityHandler (OCServerRequest *request,
924                                  OCResource *resource,
925                                  uint8_t collectionResource)
926 {
927     if(!request || ! resource)
928     {
929         return OC_STACK_INVALID_PARAM;
930     }
931
932     OCStackResult result = OC_STACK_ERROR;
933     OCEntityHandlerResult ehResult = OC_EH_ERROR;
934     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
935     ResourceObserver *resObs = NULL;
936
937     OCEntityHandlerRequest ehRequest = {0};
938
939     OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
940     OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
941     // check the security resource
942     if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
943     {
944         type = PAYLOAD_TYPE_SECURITY;
945
946     }
947
948     if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
949     {
950         type = PAYLOAD_TYPE_RD;
951     }
952
953     result = FormOCEntityHandlerRequest(&ehRequest,
954                                         (OCRequestHandle)request,
955                                         request->method,
956                                         &request->devAddr,
957                                         (OCResourceHandle)resource,
958                                         request->query,
959                                         type,
960                                         request->payload,
961                                         request->payloadSize,
962                                         request->numRcvdVendorSpecificHeaderOptions,
963                                         request->rcvdVendorSpecificHeaderOptions,
964                                         (OCObserveAction)request->observationOption,
965                                         0,
966                                         request->coapID);
967     VERIFY_SUCCESS(result, OC_STACK_OK);
968
969     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
970     {
971         OIC_LOG(INFO, TAG, "No observation requested");
972         ehFlag = OC_REQUEST_FLAG;
973     }
974     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
975     {
976         OIC_LOG(INFO, TAG, "Observation registration requested");
977
978         ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
979                                     request->tokenLength);
980
981         if (obs)
982         {
983             OIC_LOG (INFO, TAG, "Observer with this token already present");
984             OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
985             OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
986             OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
987
988             // server requests are usually free'd when the response is sent out
989             // for the request in ocserverrequest.c : HandleSingleResponse()
990             // Since we are making an early return and not responding, the server request
991             // needs to be deleted.
992             FindAndDeleteServerRequest (request);
993             return OC_STACK_OK;
994         }
995
996         result = GenerateObserverId(&ehRequest.obsInfo.obsId);
997         VERIFY_SUCCESS(result, OC_STACK_OK);
998
999         result = AddObserver ((const char*)(request->resourceUrl),
1000                 (const char *)(request->query),
1001                 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1002                 resource, request->qos, request->acceptFormat,
1003                 &request->devAddr);
1004
1005         if(result == OC_STACK_OK)
1006         {
1007             OIC_LOG(INFO, TAG, "Added observer successfully");
1008             request->observeResult = OC_STACK_OK;
1009             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1010         }
1011         else
1012         {
1013             // The error in observeResult for the request will be used when responding to this
1014             // request by omitting the observation option/sequence number.
1015             request->observeResult = OC_STACK_ERROR;
1016             OIC_LOG(ERROR, TAG, "Observer Addition failed");
1017             ehFlag = OC_REQUEST_FLAG;
1018             FindAndDeleteServerRequest(request);
1019             goto exit;
1020         }
1021
1022     }
1023     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1024             !collectionResource)
1025     {
1026         OIC_LOG(INFO, TAG, "Deregistering observation requested");
1027
1028         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1029
1030         if (NULL == resObs)
1031         {
1032             // Stack does not contain this observation request
1033             // Either token is incorrect or observation list is corrupted
1034             result = OC_STACK_ERROR;
1035             goto exit;
1036         }
1037         ehRequest.obsInfo.obsId = resObs->observeId;
1038         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1039
1040         result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1041
1042         if(result == OC_STACK_OK)
1043         {
1044             OIC_LOG(INFO, TAG, "Removed observer successfully");
1045             request->observeResult = OC_STACK_OK;
1046             // There should be no observe option header for de-registration response.
1047             // Set as an invalid value here so we can detect it later and remove the field in response.
1048             request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1049         }
1050         else
1051         {
1052             request->observeResult = OC_STACK_ERROR;
1053             OIC_LOG(ERROR, TAG, "Observer Removal failed");
1054             FindAndDeleteServerRequest(request);
1055             goto exit;
1056         }
1057     }
1058     else
1059     {
1060         result = OC_STACK_ERROR;
1061         goto exit;
1062     }
1063
1064     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1065     if(ehResult == OC_EH_SLOW)
1066     {
1067         OIC_LOG(INFO, TAG, "This is a slow resource");
1068         request->slowFlag = 1;
1069     }
1070     else if(ehResult == OC_EH_ERROR)
1071     {
1072         FindAndDeleteServerRequest(request);
1073     }
1074     result = EntityHandlerCodeToOCStackCode(ehResult);
1075 exit:
1076     OCPayloadDestroy(ehRequest.payload);
1077     return result;
1078 }
1079
1080 static OCStackResult
1081 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1082                                               OCResource *resource)
1083 {
1084     if(!request || !resource)
1085     {
1086         return OC_STACK_INVALID_PARAM;
1087     }
1088
1089     OCStackResult result = OC_STACK_ERROR;
1090     OCEntityHandlerRequest ehRequest = {0};
1091
1092     result = FormOCEntityHandlerRequest(&ehRequest,
1093                                         (OCRequestHandle)request,
1094                                         request->method,
1095                                         &request->devAddr,
1096                                         (OCResourceHandle)resource,
1097                                         request->query,
1098                                         PAYLOAD_TYPE_REPRESENTATION,
1099                                         request->payload,
1100                                         request->payloadSize,
1101                                         request->numRcvdVendorSpecificHeaderOptions,
1102                                         request->rcvdVendorSpecificHeaderOptions,
1103                                         (OCObserveAction)request->observationOption,
1104                                         (OCObservationId)0,
1105                                         request->coapID);
1106     if(result == OC_STACK_OK)
1107     {
1108         result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1109     }
1110
1111     OCPayloadDestroy(ehRequest.payload);
1112     return result;
1113 }
1114
1115 OCStackResult
1116 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1117 {
1118     OCStackResult ret = OC_STACK_OK;
1119
1120     switch (resHandling)
1121     {
1122         case OC_RESOURCE_VIRTUAL:
1123         {
1124             ret = HandleVirtualResource (request, resource);
1125             break;
1126         }
1127         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1128         {
1129             ret = HandleDefaultDeviceEntityHandler(request);
1130             break;
1131         }
1132         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1133         {
1134             OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1135             return OC_STACK_ERROR;
1136         }
1137         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1138         {
1139             ret = HandleResourceWithEntityHandler (request, resource, 0);
1140             break;
1141         }
1142         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1143         {
1144             ret = HandleResourceWithEntityHandler (request, resource, 1);
1145             break;
1146         }
1147         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1148         {
1149             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1150             break;
1151         }
1152         case OC_RESOURCE_NOT_SPECIFIED:
1153         {
1154             ret = OC_STACK_NO_RESOURCE;
1155             break;
1156         }
1157         default:
1158         {
1159             OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1160             return OC_STACK_ERROR;
1161         }
1162     }
1163     return ret;
1164 }
1165
1166 void DeletePlatformInfo()
1167 {
1168     OIC_LOG(INFO, TAG, "Deleting platform info.");
1169
1170     OICFree(savedPlatformInfo.platformID);
1171     savedPlatformInfo.platformID = NULL;
1172
1173     OICFree(savedPlatformInfo.manufacturerName);
1174     savedPlatformInfo.manufacturerName = NULL;
1175
1176     OICFree(savedPlatformInfo.manufacturerUrl);
1177     savedPlatformInfo.manufacturerUrl = NULL;
1178
1179     OICFree(savedPlatformInfo.modelNumber);
1180     savedPlatformInfo.modelNumber = NULL;
1181
1182     OICFree(savedPlatformInfo.dateOfManufacture);
1183     savedPlatformInfo.dateOfManufacture = NULL;
1184
1185     OICFree(savedPlatformInfo.platformVersion);
1186     savedPlatformInfo.platformVersion = NULL;
1187
1188     OICFree(savedPlatformInfo.operatingSystemVersion);
1189     savedPlatformInfo.operatingSystemVersion = NULL;
1190
1191     OICFree(savedPlatformInfo.hardwareVersion);
1192     savedPlatformInfo.hardwareVersion = NULL;
1193
1194     OICFree(savedPlatformInfo.firmwareVersion);
1195     savedPlatformInfo.firmwareVersion = NULL;
1196
1197     OICFree(savedPlatformInfo.supportUrl);
1198     savedPlatformInfo.supportUrl = NULL;
1199
1200     OICFree(savedPlatformInfo.systemTime);
1201     savedPlatformInfo.systemTime = NULL;
1202 }
1203
1204 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1205 {
1206     savedPlatformInfo.platformID = OICStrdup(info.platformID);
1207     savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1208     savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1209     savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1210     savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1211     savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1212     savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1213     savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1214     savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1215     savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1216     savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1217
1218     if ((!savedPlatformInfo.platformID && info.platformID)||
1219         (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1220         (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1221         (!savedPlatformInfo.modelNumber && info.modelNumber)||
1222         (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1223         (!savedPlatformInfo.platformVersion && info.platformVersion)||
1224         (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1225         (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1226         (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1227         (!savedPlatformInfo.supportUrl && info.supportUrl)||
1228         (!savedPlatformInfo.systemTime && info.systemTime))
1229     {
1230         DeletePlatformInfo();
1231         return OC_STACK_INVALID_PARAM;
1232     }
1233
1234     return OC_STACK_OK;
1235
1236 }
1237
1238 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1239 {
1240     DeletePlatformInfo();
1241
1242     OCStackResult res = DeepCopyPlatFormInfo(info);
1243
1244     if (res != OC_STACK_OK)
1245     {
1246         OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1247     }
1248     else
1249     {
1250         OIC_LOG(INFO, TAG, "Platform info saved.");
1251     }
1252
1253     return res;
1254 }
1255
1256 void DeleteDeviceInfo()
1257 {
1258     OIC_LOG(INFO, TAG, "Deleting device info.");
1259
1260     OICFree(savedDeviceInfo.deviceName);
1261     OCFreeOCStringLL(savedDeviceInfo.types);
1262     OICFree(savedDeviceInfo.specVersion);
1263     OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1264     savedDeviceInfo.deviceName = NULL;
1265     savedDeviceInfo.specVersion = NULL;
1266     savedDeviceInfo.dataModelVersions = NULL;
1267 }
1268
1269 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1270 {
1271     savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1272
1273     if(!savedDeviceInfo.deviceName && info.deviceName)
1274     {
1275         DeleteDeviceInfo();
1276         return OC_STACK_NO_MEMORY;
1277     }
1278
1279     if (info.types)
1280     {
1281         savedDeviceInfo.types = CloneOCStringLL(info.types);
1282         OCStringLL *type = info.types;
1283         bool found = false;
1284         while (type)
1285         {
1286             if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1287             {
1288                 found = true;
1289             }
1290             type = type->next;
1291         }
1292         if (!found)
1293         {
1294             // Append the oic.wk.d at the start of rt link parameter value.
1295             OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1296             if (!dest)
1297             {
1298                 DeleteDeviceInfo();
1299                 return OC_STACK_NO_MEMORY;
1300             }
1301             dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1302             if (!dest->value)
1303             {
1304                 DeleteDeviceInfo();
1305                 return OC_STACK_NO_MEMORY;
1306             }
1307             dest->next = savedDeviceInfo.types;
1308             savedDeviceInfo.types = dest;
1309         }
1310         if(!savedDeviceInfo.types && info.types)
1311         {
1312             DeleteDeviceInfo();
1313             return OC_STACK_NO_MEMORY;
1314         }
1315     }
1316
1317     if (info.specVersion)
1318     {
1319         savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1320         if(!savedDeviceInfo.specVersion && info.specVersion)
1321         {
1322             DeleteDeviceInfo();
1323             return OC_STACK_NO_MEMORY;
1324         }
1325     }
1326     else
1327     {
1328         savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1329         if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1330         {
1331             DeleteDeviceInfo();
1332             return OC_STACK_NO_MEMORY;
1333         }
1334     }
1335
1336     if (info.dataModelVersions)
1337     {
1338         savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1339         if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1340         {
1341             DeleteDeviceInfo();
1342             return OC_STACK_NO_MEMORY;
1343         }
1344     }
1345     else
1346     {
1347         savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1348         if (!savedDeviceInfo.dataModelVersions)
1349         {
1350             return OC_STACK_NO_MEMORY;
1351         }
1352         savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1353         if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1354         {
1355             DeleteDeviceInfo();
1356             return OC_STACK_NO_MEMORY;
1357         }
1358     }
1359
1360     return OC_STACK_OK;
1361 }
1362
1363 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1364 {
1365     OCStackResult res = OC_STACK_OK;
1366
1367     DeleteDeviceInfo();
1368
1369     res = DeepCopyDeviceInfo(info);
1370
1371     VERIFY_SUCCESS(res, OC_STACK_OK);
1372
1373     if (OCGetServerInstanceIDString() == NULL)
1374     {
1375         OIC_LOG(INFO, TAG, "Device ID generation failed");
1376         res =  OC_STACK_ERROR;
1377         goto exit;
1378     }
1379
1380     OIC_LOG(INFO, TAG, "Device initialized successfully.");
1381     return OC_STACK_OK;
1382
1383 exit:
1384     DeleteDeviceInfo();
1385     return res;
1386 }