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