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