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