Merge branch 'master' into notification-service
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocresource.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1-2001 base
24 // specification (excluding the XSI extension).
25 // For POSIX.1-2001 base specification,
26 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
27 #define _POSIX_C_SOURCE 200112L
28
29 #ifdef WITH_STRING_H
30 #include <string.h>
31 #endif
32 #ifdef WITH_STRINGS_H
33 #include <strings.h>
34 #endif
35
36 #include "ocresource.h"
37 #include "ocresourcehandler.h"
38 #include "ocobserve.h"
39 #include "occollection.h"
40 #include "oic_malloc.h"
41 #include "oic_string.h"
42 #include "logger.h"
43 #include "cJSON.h"
44 #include "ocpayload.h"
45 #include "secureresourcemanager.h"
46 #include "cacommon.h"
47 #include "cainterface.h"
48 #include "rdpayload.h"
49 #include "ocpayload.h"
50
51 #ifdef WITH_RD
52 #include "rd_server.h"
53 #endif
54
55 #ifdef ROUTING_GATEWAY
56 #include "routingmanager.h"
57 #endif
58
59 /// Module Name
60 #define TAG "OIC_RI_RESOURCE"
61
62 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
63             {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
64
65 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
66              TAG, #arg " is NULL"); return (retVal); } }
67
68 #include "platform_features.h"
69
70 extern OCResource *headResource;
71 static OCPlatformInfo savedPlatformInfo = {0};
72 static OCDeviceInfo savedDeviceInfo = {0};
73
74 /**
75  * Prepares a Payload for response.
76  */
77 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
78                                                   OCDiscoveryPayload* payload,
79                                                   OCDevAddr *endpoint,
80                                                   bool rdResponse);
81
82 //-----------------------------------------------------------------------------
83 // Default resource entity handler function
84 //-----------------------------------------------------------------------------
85 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
86         OCEntityHandlerRequest * request, void* callbackParam)
87 {
88     //TODO ("Implement me!!!!");
89     // TODO:  remove silence unused param warnings
90     (void) flag;
91     (void) request;
92     (void) callbackParam;
93     return  OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
94 }
95
96 /* This method will retrieve the port at which the secure resource is hosted */
97 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
98 {
99     uint16_t p = 0;
100
101     if (endpoint->adapter == OC_ADAPTER_IP)
102     {
103         if (endpoint->flags & OC_IP_USE_V6)
104         {
105             p = caglobals.ip.u6s.port;
106         }
107         else if (endpoint->flags & OC_IP_USE_V4)
108         {
109             p = caglobals.ip.u4s.port;
110         }
111     }
112
113     *port = p;
114     return OC_STACK_OK;
115 }
116
117 #ifdef TCP_ADAPTER
118 /* This method will retrieve the tcp port */
119 static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port)
120 {
121     uint16_t p = 0;
122
123     if (endpoint->adapter == OC_ADAPTER_IP)
124     {
125         if (endpoint->flags & OC_IP_USE_V4)
126         {
127             p = caglobals.tcp.ipv4.port;
128         }
129         else if (endpoint->flags & OC_IP_USE_V6)
130         {
131             p = caglobals.tcp.ipv6.port;
132         }
133     }
134
135     *port = p;
136     return OC_STACK_OK;
137 }
138 #endif
139
140 /*
141  * Function will extract 0, 1 or 2 filters from query.
142  * More than 2 filters or unsupported filters will result in error.
143  * If both filters are of the same supported type, the 2nd one will be picked.
144  * Resource and device filters in the SAME query are NOT validated
145  * and resources will likely not clear filters.
146  */
147 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
148 {
149
150     char *key = NULL;
151     char *value = NULL;
152     char *restOfQuery = NULL;
153     int numKeyValuePairsParsed = 0;
154
155     *filterOne = NULL;
156     *filterTwo = NULL;
157
158     OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
159
160     char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
161
162     while(keyValuePair)
163     {
164         if (numKeyValuePairsParsed >= 2)
165         {
166             OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
167             return OC_STACK_INVALID_QUERY;
168         }
169
170         key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
171
172         if (!key || !value)
173         {
174             return OC_STACK_INVALID_QUERY;
175         }
176         else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
177         {
178             *filterOne = value;     // if
179         }
180         else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
181         {
182             *filterTwo = value;     // rt
183         }
184         else
185         {
186             OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
187             return OC_STACK_INVALID_QUERY;
188         }
189         ++numKeyValuePairsParsed;
190
191         keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
192     }
193
194     OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
195     return OC_STACK_OK;
196 }
197
198 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
199 {
200     if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
201     {
202         return OC_WELL_KNOWN_URI;
203     }
204     else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
205     {
206         return OC_DEVICE_URI;
207     }
208     else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
209     {
210         return OC_PLATFORM_URI;
211     }
212     else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
213     {
214         return OC_RESOURCE_TYPES_URI;
215     }
216 #ifdef ROUTING_GATEWAY
217     else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
218     {
219         return OC_GATEWAY_URI;
220     }
221 #endif
222 #ifdef WITH_PRESENCE
223     else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
224     {
225         return OC_PRESENCE;
226     }
227 #endif //WITH_PRESENCE
228     return OC_UNKNOWN_URI;
229 }
230
231 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
232                                             char **filterOne, char **filterTwo)
233 {
234     if(!filterOne || !filterTwo)
235     {
236         return OC_STACK_INVALID_PARAM;
237     }
238
239     *filterOne = NULL;
240     *filterTwo = NULL;
241
242     #ifdef WITH_PRESENCE
243     if (uri == OC_PRESENCE)
244     {
245         //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
246         OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
247         return OC_STACK_OK;
248     }
249     #endif
250
251     OCStackResult result = OC_STACK_OK;
252
253     if (query && *query)
254     {
255         result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
256     }
257
258     return result;
259 }
260
261 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
262                     OCRepPayload** payload)
263 {
264     OCRepPayload *tempPayload = OCRepPayloadCreate();
265
266     if (!resourcePtr)
267     {
268         OCRepPayloadDestroy(tempPayload);
269         return OC_STACK_INVALID_PARAM;
270     }
271
272     if(!tempPayload)
273     {
274         return OC_STACK_NO_MEMORY;
275     }
276
277     OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
278
279     OCResourceType *resType = resourcePtr->rsrcType;
280     while(resType)
281     {
282         OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
283         resType = resType->next;
284     }
285
286     OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
287     while(resInterface)
288     {
289         OCRepPayloadAddInterface(tempPayload, resInterface->name);
290         resInterface = resInterface->next;
291     }
292
293     OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
294     while(resAttrib)
295     {
296         OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
297                                 resAttrib->attrValue);
298         resAttrib = resAttrib->next;
299     }
300
301     if(!*payload)
302     {
303         *payload = tempPayload;
304     }
305     else
306     {
307         OCRepPayloadAppend(*payload, tempPayload);
308     }
309
310     return OC_STACK_OK;
311 }
312
313 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
314                         OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
315 {
316     if (!resourcePtr || !payload)
317     {
318         return OC_STACK_INVALID_PARAM;
319     }
320     uint16_t securePort = 0;
321     if (resourcePtr->resourceProperties & OC_SECURE)
322     {
323        if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK)
324        {
325            securePort = 0;
326        }
327     }
328
329     if (rdResponse)
330     {
331         securePort = devAddr->port;
332     }
333
334     uint16_t tcpPort = 0;
335 #ifdef TCP_ADAPTER
336     if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK)
337     {
338         tcpPort = 0;
339     }
340     OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
341 #else
342     OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
343 #endif
344
345     return OC_STACK_OK;
346 }
347
348 uint8_t IsCollectionResource (OCResource *resource)
349 {
350     if(!resource)
351     {
352         return 0;
353     }
354
355     if(resource->rsrcChildResourcesHead != NULL)
356     {
357         return 1;
358     }
359
360     return 0;
361 }
362
363 OCResource *FindResourceByUri(const char* resourceUri)
364 {
365     if(!resourceUri)
366     {
367         return NULL;
368     }
369
370     OCResource * pointer = headResource;
371     while (pointer)
372     {
373         if (strcmp(resourceUri, pointer->uri) == 0)
374         {
375             return pointer;
376         }
377         pointer = pointer->next;
378     }
379     OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
380     return NULL;
381 }
382
383
384 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
385                                          ResourceHandling *handling,
386                                          OCResource **resource)
387 {
388     if(!request || !handling || !resource)
389     {
390         return OC_STACK_INVALID_PARAM;
391     }
392
393     OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
394
395     // Check if virtual resource
396     if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
397     {
398         OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
399         *handling = OC_RESOURCE_VIRTUAL;
400         *resource = headResource;
401         return OC_STACK_OK;
402     }
403     if (strlen((const char*)(request->resourceUrl)) == 0)
404     {
405         // Resource URL not specified
406         *handling = OC_RESOURCE_NOT_SPECIFIED;
407         return OC_STACK_NO_RESOURCE;
408     }
409     else
410     {
411         OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
412         *resource = resourcePtr;
413         if (!resourcePtr)
414         {
415             if(defaultDeviceHandler)
416             {
417                 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
418                 return OC_STACK_OK;
419             }
420
421             // Resource does not exist
422             // and default device handler does not exist
423             *handling = OC_RESOURCE_NOT_SPECIFIED;
424             return OC_STACK_NO_RESOURCE;
425         }
426
427         if (IsCollectionResource (resourcePtr))
428         {
429             // Collection resource
430             if (resourcePtr->entityHandler != defaultResourceEHandler)
431             {
432                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
433                 return OC_STACK_OK;
434             }
435             else
436             {
437                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
438                 return OC_STACK_OK;
439             }
440         }
441         else
442         {
443             // Resource not a collection
444             if (resourcePtr->entityHandler != defaultResourceEHandler)
445             {
446                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
447                 return OC_STACK_OK;
448             }
449             else
450             {
451                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
452                 return OC_STACK_OK;
453             }
454         }
455     }
456 }
457
458 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
459 {
460     OCStackResult result;
461
462     switch (ehResult)
463     {
464         case OC_EH_OK:
465             result = OC_STACK_OK;
466             break;
467         case OC_EH_SLOW:
468             result = OC_STACK_SLOW_RESOURCE;
469             break;
470         case OC_EH_ERROR:
471             result = OC_STACK_ERROR;
472             break;
473         case OC_EH_FORBIDDEN:
474             result = OC_STACK_RESOURCE_ERROR;
475             break;
476         case OC_EH_RESOURCE_CREATED:
477             result = OC_STACK_RESOURCE_CREATED;
478             break;
479         case OC_EH_RESOURCE_DELETED:
480             result = OC_STACK_RESOURCE_DELETED;
481             break;
482         case OC_EH_CHANGED:
483             result = OC_STACK_RESOURCE_CHANGED;
484             break;
485         case OC_EH_RESOURCE_NOT_FOUND:
486             result = OC_STACK_NO_RESOURCE;
487             break;
488         default:
489             result = OC_STACK_ERROR;
490     }
491
492     return result;
493 }
494
495 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
496 {
497     if (!resource)
498     {
499         return false;
500     }
501
502     // Null or empty is analogous to no filter.
503     if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
504     {
505         return true;
506     }
507
508     OCResourceType *resourceTypePtr = resource->rsrcType;
509
510     while (resourceTypePtr)
511     {
512         if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
513         {
514             return true;
515         }
516         resourceTypePtr = resourceTypePtr->next;
517     }
518
519     OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
520     return false;
521 }
522
523 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
524 {
525     if (!resource)
526     {
527         return false;
528     }
529
530     // Null or empty is analogous to no filter.
531     if (interfaceFilter == NULL || *interfaceFilter == 0)
532     {
533         return true;
534     }
535
536     OCResourceInterface *interfacePtr = resource->rsrcInterface;
537
538     while (interfacePtr)
539     {
540         if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
541             (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
542              strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
543         {
544             return true;
545         }
546         interfacePtr = interfacePtr->next;
547     }
548
549     OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
550     return false;
551 }
552
553 /*
554  * If the filters are null, they will be assumed to NOT be present
555  * and the resource will not be matched against them.
556  * Function will return true if all non null AND non empty filters passed in find a match.
557  */
558 static bool includeThisResourceInResponse(OCResource *resource,
559                                           char *interfaceFilter,
560                                           char *resourceTypeFilter)
561 {
562     if (!resource)
563     {
564         OIC_LOG(ERROR, TAG, "Invalid resource");
565         return false;
566     }
567
568     if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
569     {
570         /*
571          * At least one valid filter should be available to
572          * include the resource in discovery response
573          */
574         if (!(resourceTypeFilter && *resourceTypeFilter))
575         {
576             OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
577                 resource", resource->uri);
578             return false;
579         }
580     }
581     else if ( !(resource->resourceProperties & OC_ACTIVE) ||
582          !(resource->resourceProperties & OC_DISCOVERABLE))
583     {
584         OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
585         return false;
586     }
587
588     return resourceMatchesIFFilter(resource, interfaceFilter) &&
589            resourceMatchesRTFilter(resource, resourceTypeFilter);
590
591 }
592
593 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
594                                 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
595 {
596     OCEntityHandlerResponse response = {0};
597
598     response.ehResult = ehResult;
599     response.payload = discoveryPayload;
600     response.persistentBufferFlag = 0;
601     response.requestHandle = (OCRequestHandle) request;
602     response.resourceHandle = (OCResourceHandle) resource;
603
604     return OCDoResponse(&response);
605 }
606
607 #ifdef WITH_RD
608 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
609      OCResource **payload, OCDevAddr *devAddr)
610 {
611     OCResourceCollectionPayload *repPayload;
612     if (!payload)
613     {
614         return OC_STACK_ERROR;
615     }
616     if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
617     {
618         if (!repPayload)
619         {
620             return OC_STACK_ERROR;
621         }
622         OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
623         if (!ptr)
624         {
625            return OC_STACK_NO_MEMORY;
626         }
627
628         ptr->uri = OICStrdup(repPayload->setLinks->href);
629         if (!ptr->uri)
630         {
631            return OC_STACK_NO_MEMORY;
632         }
633         OCStringLL *rt = repPayload->setLinks->rt;
634         while (rt)
635         {
636             OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
637             if(!temp)
638             {
639                 OICFree(ptr->uri);
640                 return OC_STACK_NO_MEMORY;
641             }
642             temp->next = NULL;
643             temp->resourcetypename = OICStrdup(rt->value);
644             if (!ptr->rsrcType)
645             {
646                 ptr->rsrcType = temp;
647             }
648             else
649             {
650                 OCResourceType *type = ptr->rsrcType;
651                 while (type->next)
652                 {
653                     type = type->next;
654                 }
655                 type->next = temp;
656             }
657             rt = rt->next;
658         }
659
660         OCStringLL *itf = repPayload->setLinks->itf;
661         while (itf)
662         {
663             OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
664             if (!temp)
665             {
666                 OICFree(ptr->uri);
667
668                 return OC_STACK_NO_MEMORY;
669             }
670             temp->next = NULL;
671             temp->name = OICStrdup(itf->value);
672             if (!ptr->rsrcInterface)
673             {
674                 ptr->rsrcInterface = temp;
675             }
676             else
677             {
678                 OCResourceInterface *type = ptr->rsrcInterface;
679                 while (type->next)
680                 {
681                     type = type->next;
682                 }
683                 type->next = temp;
684             }
685             itf = itf->next;
686         }
687
688         ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
689
690         OCFreeCollectionResource(repPayload);
691         *payload = ptr;
692         return OC_STACK_OK;
693     }
694     else
695     {
696         OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
697                              on the resource directory");
698     }
699     return OC_STACK_ERROR;
700 }
701 #endif
702
703 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
704 {
705     if (!request || !resource)
706     {
707         return OC_STACK_INVALID_PARAM;
708     }
709
710     OCStackResult discoveryResult = OC_STACK_ERROR;
711     OCPayload* payload = NULL;
712
713     OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
714
715     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
716
717     // Step 1: Generate the response to discovery request
718     if (virtualUriInRequest == OC_WELL_KNOWN_URI)
719     {
720         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
721         {
722             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
723             return OC_STACK_UNAUTHORIZED_REQ;
724         }
725
726         char *interfaceQuery = NULL;
727         char *resourceTypeQuery = NULL;
728
729         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
730                 &interfaceQuery, &resourceTypeQuery);
731         bool interfaceQueryAllocated = false;
732         if (!interfaceQuery && !resourceTypeQuery)
733         {
734             interfaceQueryAllocated = true;
735             interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
736         }
737
738         if (discoveryResult == OC_STACK_OK)
739         {
740             payload = (OCPayload *)OCDiscoveryPayloadCreate();
741
742             if (payload)
743             {
744                 OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
745                 discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
746                 VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
747
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->iface, OC_RSRVD_INTERFACE_LL);
787                         OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
788                         VERIFY_NON_NULL(discPayload->iface, 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             // The error in observeResult for the request will be used when responding to this
1111             // request by omitting the observation option/sequence number.
1112             request->observeResult = OC_STACK_ERROR;
1113             OIC_LOG(ERROR, TAG, "Observer Addition failed");
1114             ehFlag = OC_REQUEST_FLAG;
1115             FindAndDeleteServerRequest(request);
1116             goto exit;
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         }
1144         else
1145         {
1146             request->observeResult = OC_STACK_ERROR;
1147             OIC_LOG(ERROR, TAG, "Observer Removal failed");
1148             FindAndDeleteServerRequest(request);
1149             goto exit;
1150         }
1151     }
1152     else
1153     {
1154         result = OC_STACK_ERROR;
1155         goto exit;
1156     }
1157
1158     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1159     if(ehResult == OC_EH_SLOW)
1160     {
1161         OIC_LOG(INFO, TAG, "This is a slow resource");
1162         request->slowFlag = 1;
1163     }
1164     else if(ehResult == OC_EH_ERROR)
1165     {
1166         FindAndDeleteServerRequest(request);
1167     }
1168     result = EntityHandlerCodeToOCStackCode(ehResult);
1169 exit:
1170     OCPayloadDestroy(ehRequest.payload);
1171     return result;
1172 }
1173
1174 static OCStackResult
1175 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1176                                               OCResource *resource)
1177 {
1178     if(!request || !resource)
1179     {
1180         return OC_STACK_INVALID_PARAM;
1181     }
1182
1183     OCStackResult result = OC_STACK_ERROR;
1184     OCEntityHandlerRequest ehRequest = {0};
1185
1186     result = FormOCEntityHandlerRequest(&ehRequest,
1187                                         (OCRequestHandle)request,
1188                                         request->method,
1189                                         &request->devAddr,
1190                                         (OCResourceHandle)resource,
1191                                         request->query,
1192                                         PAYLOAD_TYPE_REPRESENTATION,
1193                                         request->payload,
1194                                         request->payloadSize,
1195                                         request->numRcvdVendorSpecificHeaderOptions,
1196                                         request->rcvdVendorSpecificHeaderOptions,
1197                                         (OCObserveAction)request->observationOption,
1198                                         (OCObservationId)0,
1199                                         request->coapID);
1200     if(result == OC_STACK_OK)
1201     {
1202         result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1203     }
1204
1205     OCPayloadDestroy(ehRequest.payload);
1206     return result;
1207 }
1208
1209 OCStackResult
1210 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1211 {
1212     OCStackResult ret = OC_STACK_OK;
1213
1214     switch (resHandling)
1215     {
1216         case OC_RESOURCE_VIRTUAL:
1217         {
1218             ret = HandleVirtualResource (request, resource);
1219             break;
1220         }
1221         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1222         {
1223             ret = HandleDefaultDeviceEntityHandler(request);
1224             break;
1225         }
1226         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1227         {
1228             OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1229             return OC_STACK_ERROR;
1230         }
1231         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1232         {
1233             ret = HandleResourceWithEntityHandler (request, resource, 0);
1234             break;
1235         }
1236         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1237         {
1238             ret = HandleResourceWithEntityHandler (request, resource, 1);
1239             break;
1240         }
1241         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1242         {
1243             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1244             break;
1245         }
1246         case OC_RESOURCE_NOT_SPECIFIED:
1247         {
1248             ret = OC_STACK_NO_RESOURCE;
1249             break;
1250         }
1251         default:
1252         {
1253             OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1254             return OC_STACK_ERROR;
1255         }
1256     }
1257     return ret;
1258 }
1259
1260 void DeletePlatformInfo()
1261 {
1262     OIC_LOG(INFO, TAG, "Deleting platform info.");
1263
1264     OICFree(savedPlatformInfo.platformID);
1265     savedPlatformInfo.platformID = NULL;
1266
1267     OICFree(savedPlatformInfo.manufacturerName);
1268     savedPlatformInfo.manufacturerName = NULL;
1269
1270     OICFree(savedPlatformInfo.manufacturerUrl);
1271     savedPlatformInfo.manufacturerUrl = NULL;
1272
1273     OICFree(savedPlatformInfo.modelNumber);
1274     savedPlatformInfo.modelNumber = NULL;
1275
1276     OICFree(savedPlatformInfo.dateOfManufacture);
1277     savedPlatformInfo.dateOfManufacture = NULL;
1278
1279     OICFree(savedPlatformInfo.platformVersion);
1280     savedPlatformInfo.platformVersion = NULL;
1281
1282     OICFree(savedPlatformInfo.operatingSystemVersion);
1283     savedPlatformInfo.operatingSystemVersion = NULL;
1284
1285     OICFree(savedPlatformInfo.hardwareVersion);
1286     savedPlatformInfo.hardwareVersion = NULL;
1287
1288     OICFree(savedPlatformInfo.firmwareVersion);
1289     savedPlatformInfo.firmwareVersion = NULL;
1290
1291     OICFree(savedPlatformInfo.supportUrl);
1292     savedPlatformInfo.supportUrl = NULL;
1293
1294     OICFree(savedPlatformInfo.systemTime);
1295     savedPlatformInfo.systemTime = NULL;
1296 }
1297
1298 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1299 {
1300     savedPlatformInfo.platformID = OICStrdup(info.platformID);
1301     savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1302     savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1303     savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1304     savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1305     savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1306     savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1307     savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1308     savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1309     savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1310     savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1311
1312     if ((!savedPlatformInfo.platformID && info.platformID)||
1313         (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1314         (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1315         (!savedPlatformInfo.modelNumber && info.modelNumber)||
1316         (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1317         (!savedPlatformInfo.platformVersion && info.platformVersion)||
1318         (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1319         (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1320         (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1321         (!savedPlatformInfo.supportUrl && info.supportUrl)||
1322         (!savedPlatformInfo.systemTime && info.systemTime))
1323     {
1324         DeletePlatformInfo();
1325         return OC_STACK_INVALID_PARAM;
1326     }
1327
1328     return OC_STACK_OK;
1329
1330 }
1331
1332 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1333 {
1334     DeletePlatformInfo();
1335
1336     OCStackResult res = DeepCopyPlatFormInfo(info);
1337
1338     if (res != OC_STACK_OK)
1339     {
1340         OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1341     }
1342     else
1343     {
1344         OIC_LOG(INFO, TAG, "Platform info saved.");
1345     }
1346
1347     return res;
1348 }
1349
1350 void DeleteDeviceInfo()
1351 {
1352     OIC_LOG(INFO, TAG, "Deleting device info.");
1353
1354     OICFree(savedDeviceInfo.deviceName);
1355     OCFreeOCStringLL(savedDeviceInfo.types);
1356     OICFree(savedDeviceInfo.specVersion);
1357     OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
1358     savedDeviceInfo.deviceName = NULL;
1359     savedDeviceInfo.specVersion = NULL;
1360     savedDeviceInfo.dataModelVersions = NULL;
1361 }
1362
1363 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1364 {
1365     savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1366
1367     if(!savedDeviceInfo.deviceName && info.deviceName)
1368     {
1369         DeleteDeviceInfo();
1370         return OC_STACK_NO_MEMORY;
1371     }
1372
1373     if (info.types)
1374     {
1375         savedDeviceInfo.types = CloneOCStringLL(info.types);
1376         OCStringLL *type = info.types;
1377         bool found = false;
1378         while (type)
1379         {
1380             if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE))
1381             {
1382                 found = true;
1383             }
1384             type = type->next;
1385         }
1386         if (!found)
1387         {
1388             // Append the oic.wk.d at the start of rt link parameter value.
1389             OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
1390             if (!dest)
1391             {
1392                 DeleteDeviceInfo();
1393                 return OC_STACK_NO_MEMORY;
1394             }
1395             dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE);
1396             if (!dest->value)
1397             {
1398                 DeleteDeviceInfo();
1399                 return OC_STACK_NO_MEMORY;
1400             }
1401             dest->next = savedDeviceInfo.types;
1402             savedDeviceInfo.types = dest;
1403         }
1404         if(!savedDeviceInfo.types && info.types)
1405         {
1406             DeleteDeviceInfo();
1407             return OC_STACK_NO_MEMORY;
1408         }
1409     }
1410
1411     if (info.specVersion)
1412     {
1413         savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
1414         if(!savedDeviceInfo.specVersion && info.specVersion)
1415         {
1416             DeleteDeviceInfo();
1417             return OC_STACK_NO_MEMORY;
1418         }
1419     }
1420     else
1421     {
1422         savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
1423         if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
1424         {
1425             DeleteDeviceInfo();
1426             return OC_STACK_NO_MEMORY;
1427         }
1428     }
1429
1430     if (info.dataModelVersions)
1431     {
1432         savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
1433         if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
1434         {
1435             DeleteDeviceInfo();
1436             return OC_STACK_NO_MEMORY;
1437         }
1438     }
1439     else
1440     {
1441         savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
1442         if (!savedDeviceInfo.dataModelVersions)
1443         {
1444             return OC_STACK_NO_MEMORY;
1445         }
1446         savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
1447         if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
1448         {
1449             DeleteDeviceInfo();
1450             return OC_STACK_NO_MEMORY;
1451         }
1452     }
1453
1454     return OC_STACK_OK;
1455 }
1456
1457 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1458 {
1459     OCStackResult res = OC_STACK_OK;
1460
1461     DeleteDeviceInfo();
1462
1463     res = DeepCopyDeviceInfo(info);
1464
1465     VERIFY_SUCCESS(res, OC_STACK_OK);
1466
1467     if (OCGetServerInstanceIDString() == NULL)
1468     {
1469         OIC_LOG(INFO, TAG, "Device ID generation failed");
1470         res =  OC_STACK_ERROR;
1471         goto exit;
1472     }
1473
1474     OIC_LOG(INFO, TAG, "Device initialized successfully.");
1475     return OC_STACK_OK;
1476
1477 exit:
1478     DeleteDeviceInfo();
1479     return res;
1480 }