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