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