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