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