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