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