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