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