Fix for SVACE defects
[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 OCResource *FindResourceByUri(const char* resourceUri)
559 {
560     if(!resourceUri)
561     {
562         return NULL;
563     }
564
565     OCResource * pointer = headResource;
566     while (pointer)
567     {
568         if (strcmp(resourceUri, pointer->uri) == 0)
569         {
570             return pointer;
571         }
572         pointer = pointer->next;
573     }
574     OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
575     return NULL;
576 }
577
578 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
579                                          ResourceHandling *handling,
580                                          OCResource **resource)
581 {
582     if(!request || !handling || !resource)
583     {
584         return OC_STACK_INVALID_PARAM;
585     }
586
587     OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
588
589     // Check if virtual resource
590     if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
591     {
592         OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
593         *handling = OC_RESOURCE_VIRTUAL;
594         *resource = headResource;
595         return OC_STACK_OK;
596     }
597     if (strlen((const char*)(request->resourceUrl)) == 0)
598     {
599         // Resource URL not specified
600         *handling = OC_RESOURCE_NOT_SPECIFIED;
601         return OC_STACK_NO_RESOURCE;
602     }
603     else
604     {
605         OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
606         *resource = resourcePtr;
607         if (!resourcePtr)
608         {
609             if(defaultDeviceHandler)
610             {
611                 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
612                 return OC_STACK_OK;
613             }
614
615             // Resource does not exist
616             // and default device handler does not exist
617             *handling = OC_RESOURCE_NOT_SPECIFIED;
618             return OC_STACK_NO_RESOURCE;
619         }
620
621         if (resourcePtr && resourcePtr->rsrcChildResourcesHead != NULL)
622         {
623             // Collection resource
624             if (resourcePtr->entityHandler != defaultResourceEHandler)
625             {
626                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
627                 return OC_STACK_OK;
628             }
629             else
630             {
631                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
632                 return OC_STACK_OK;
633             }
634         }
635         else
636         {
637             // Resource not a collection
638             if (resourcePtr->entityHandler != defaultResourceEHandler)
639             {
640                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
641                 return OC_STACK_OK;
642             }
643             else
644             {
645                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
646                 return OC_STACK_OK;
647             }
648         }
649     }
650 }
651
652 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
653 {
654     OCStackResult result;
655
656     switch (ehResult)
657     {
658         case OC_EH_OK:
659         case OC_EH_CONTENT:
660         case OC_EH_VALID:
661             result = OC_STACK_OK;
662             break;
663         case OC_EH_SLOW:
664             result = OC_STACK_SLOW_RESOURCE;
665             break;
666         case OC_EH_ERROR:
667             result = OC_STACK_ERROR;
668             break;
669         case OC_EH_FORBIDDEN:
670             result = OC_STACK_FORBIDDEN_REQ;
671             break;
672         case OC_EH_RESOURCE_CREATED:
673             result = OC_STACK_RESOURCE_CREATED;
674             break;
675         case OC_EH_RESOURCE_DELETED:
676             result = OC_STACK_RESOURCE_DELETED;
677             break;
678         case OC_EH_CHANGED:
679             result = OC_STACK_RESOURCE_CHANGED;
680             break;
681         case OC_EH_RESOURCE_NOT_FOUND:
682             result = OC_STACK_NO_RESOURCE;
683             break;
684         case OC_EH_TOO_MANY_REQUESTS:
685             result = OC_STACK_TOO_MANY_REQUESTS;
686             break;
687         case OC_EH_INTERNAL_SERVER_ERROR:
688             result = OC_STACK_INTERNAL_SERVER_ERROR;
689             break;
690         case OC_EH_NOT_IMPLEMENTED:
691             result = OC_STACK_NOT_IMPLEMENTED;
692             break;
693         case OC_EH_BAD_GATEWAY:
694             result = OC_STACK_BAD_GATEWAY;
695             break;
696         case OC_EH_SERVICE_UNAVAILABLE:
697             result = OC_STACK_SERVICE_UNAVAILABLE;
698             break;
699         case OC_EH_RETRANSMIT_TIMEOUT:
700             result = OC_STACK_GATEWAY_TIMEOUT;
701             break;
702         case OC_EH_PROXY_NOT_SUPPORTED:
703             result = OC_STACK_PROXY_NOT_SUPPORTED;
704             break;
705         default:
706             result = OC_STACK_ERROR;
707     }
708
709     return result;
710 }
711
712 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
713 {
714     if (!resource)
715     {
716         return false;
717     }
718
719     // Null is analogous to no filter.
720     if (NULL == resourceTypeFilter)
721     {
722         return true;
723     }
724
725     // Empty resourceType filter is analogous to error query
726     if (0 == strlen(resourceTypeFilter))
727     {
728         return false;
729     }
730
731     for (OCResourceType *rtPtr = resource->rsrcType; rtPtr; rtPtr = rtPtr->next)
732     {
733         if (0 == strcmp(rtPtr->resourcetypename, resourceTypeFilter))
734         {
735             return true;
736         }
737     }
738
739     OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
740     return false;
741 }
742
743 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
744 {
745     if (!resource)
746     {
747         return false;
748     }
749
750     // Null is analogous to no filter.
751     if (NULL == interfaceFilter)
752     {
753         return true;
754     }
755
756     // Empty interface filter is analogous to error query
757     if (0 == strlen(interfaceFilter))
758     {
759         return false;
760     }
761
762     for (OCResourceInterface *ifPtr = resource->rsrcInterface; ifPtr; ifPtr = ifPtr->next)
763     {
764         if (0 == strcmp(ifPtr->name, interfaceFilter) ||
765             0 == strcmp(OC_RSRVD_INTERFACE_LL, interfaceFilter) ||
766             0 == strcmp(OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter))
767         {
768             return true;
769         }
770     }
771
772     OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
773     return false;
774 }
775
776 /*
777  * If the filters are null, they will be assumed to NOT be present
778  * and the resource will not be matched against them.
779  * Function will return true if all non null AND non empty filters passed in find a match.
780  */
781 static bool includeThisResourceInResponse(OCResource *resource,
782                                           char *interfaceFilter,
783                                           char *resourceTypeFilter)
784 {
785     if (!resource)
786     {
787         OIC_LOG(ERROR, TAG, "Invalid resource");
788         return false;
789     }
790
791     if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
792     {
793         /*
794          * At least one valid filter should be available to
795          * include the resource in discovery response
796          */
797         if (!(resourceTypeFilter && *resourceTypeFilter))
798         {
799             OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE\
800                 resource", resource->uri);
801             return false;
802         }
803     }
804     else if (!(resource->resourceProperties & OC_ACTIVE) ||
805          !(resource->resourceProperties & OC_DISCOVERABLE))
806     {
807         OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
808         return false;
809     }
810
811     return resourceMatchesIFFilter(resource, interfaceFilter) &&
812            resourceMatchesRTFilter(resource, resourceTypeFilter);
813 }
814
815 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
816                                 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
817 {
818     OCEntityHandlerResponse response = {0};
819
820     response.ehResult = ehResult;
821     response.payload = discoveryPayload;
822     response.persistentBufferFlag = 0;
823     response.requestHandle = (OCRequestHandle) request->requestId;
824     response.resourceHandle = (OCResourceHandle) resource;
825
826     return OCDoResponse(&response);
827 }
828
829 static OCStackResult EHRequest(OCEntityHandlerRequest *ehRequest, OCPayloadType type,
830     OCServerRequest *request, OCResource *resource)
831 {
832     return FormOCEntityHandlerRequest(ehRequest,
833                                      (OCRequestHandle)request->requestId,
834                                      request->method,
835                                      &request->devAddr,
836                                      (OCResourceHandle)resource,
837                                      request->query,
838                                      type,
839                                      request->payload,
840                                      request->payloadSize,
841                                      request->numRcvdVendorSpecificHeaderOptions,
842                                      request->rcvdVendorSpecificHeaderOptions,
843                                      (OCObserveAction)request->observationOption,
844                                      (OCObservationId)0,
845                                      request->coapID);
846 }
847
848 #ifdef RD_SERVER
849 /**
850  * Find resource at the resource directory server. This resource is not local resource but a
851  * remote resource.
852  *
853  * @param resource The resource to check the matching resource URI.
854  * @param interfaceQuery The interface query parameter.
855  * @param resourceTypeQuery The resourceType query parameter.
856  * @param discPayload The payload that will be added with the resource information if found at RD.
857  *
858  * @return ::OC_STACK_OK if the resource is found else ::OC_STACK_NO_RESOURCE.
859  * In case if build is not with flag RD_SERVER, it returns ::OC_STACK_NO_RESOURCE.
860  */
861 static OCStackResult findResourceAtRD(const OCResource* resource, const char *interfaceQuery,
862     const char *resourceTypeQuery, OCDiscoveryPayload *discPayload)
863 {
864     if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
865     {
866         if (OC_STACK_OK == OCRDDatabaseCheckResources(interfaceQuery, resourceTypeQuery, discPayload))
867         {
868             return OC_STACK_OK;
869         }
870     }
871
872     return OC_STACK_NO_RESOURCE;
873 }
874 #endif
875
876 /**
877  * Creates a discovery payload and add device id information. This information is included in all
878  * /oic/res response.
879  *
880  * @param payload  payload that will have memory alllocated and device id information added.
881  *
882  * @return ::OC_STACK_OK if successful in allocating memory and adding ID information.
883  * ::OC_STACK_NO_MEMORY if failed allocating the memory.
884  */
885 static OCStackResult discoveryPayloadCreateAndAddDeviceId(OCPayload **payload)
886 {
887     if (*payload)
888     {
889         OIC_LOG(DEBUG, TAG, "Payload is already allocated");
890         return OC_STACK_OK;
891     }
892
893     *payload = (OCPayload *) OCDiscoveryPayloadCreate();
894     VERIFY_PARAM_NON_NULL(TAG, *payload, "Failed adding device id to discovery payload.");
895
896     {
897         OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)*payload;
898         discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
899         VERIFY_PARAM_NON_NULL(TAG, discPayload->sid, "Failed adding device id to discovery payload.");
900
901         const char* uid = OCGetServerInstanceIDString();
902         if (uid)
903         {
904             memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
905         }
906
907     }
908     return OC_STACK_OK;
909 exit:
910     OCPayloadDestroy(*payload);
911     return OC_STACK_NO_MEMORY;
912 }
913
914 /**
915  * Add the common properties to the payload, they are only included in case of oic.if.baseline response.
916  *
917  * @param discPayload payload that will have the baseline information included.
918  *
919  * @return ::OC_STACK_OK if successful in adding all the information. ::OC_STACK_NO_MEMORY if failed
920  * allocating the memory for the baseline information.
921  */
922 static OCStackResult addDiscoveryBaselineCommonProperties(OCDiscoveryPayload *discPayload)
923 {
924     if (!discPayload)
925     {
926         OIC_LOG(ERROR, TAG, "Payload is not allocated");
927         return OC_STACK_ERROR;
928     }
929
930     OCGetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME, (void **)&discPayload->name);
931
932     discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
933     VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt to discovery payload.");
934     discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
935     VERIFY_PARAM_NON_NULL(TAG, discPayload->type, "Failed adding rt value to discovery payload.");
936
937     OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
938     OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
939     VERIFY_PARAM_NON_NULL(TAG, discPayload->iface, "Failed adding if to discovery payload.");
940
941     return OC_STACK_OK;
942
943 exit:
944     return OC_STACK_NO_MEMORY;
945 }
946
947 static bool isUnicast(OCServerRequest *request)
948 {
949     bool isMulticast = request->devAddr.flags &  OC_MULTICAST;
950     return (isMulticast == false &&
951            (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
952            (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE));
953 }
954
955 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
956 {
957     if (!request || !resource)
958     {
959         return OC_STACK_INVALID_PARAM;
960     }
961
962     OCPayload* payload = NULL;
963     char *interfaceQuery = NULL;
964     char *resourceTypeQuery = NULL;
965
966     OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
967
968     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
969
970 #ifdef TCP_ADAPTER
971     if (OC_KEEPALIVE_RESOURCE_URI == virtualUriInRequest)
972     {
973         // Received request for a keepalive
974         OIC_LOG(INFO, TAG, "Request is for KeepAlive Request");
975         return OCHandleKeepAliveRequest(request, resource);
976     }
977 #endif
978
979     OCStackResult discoveryResult = OC_STACK_ERROR;
980     if (request->method == OC_REST_PUT || request->method == OC_REST_POST ||
981         request->method == OC_REST_DELETE)
982     {
983         OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d",
984             request->resourceUrl, request->method);
985         return OC_STACK_UNAUTHORIZED_REQ;
986     }
987
988     // Step 1: Generate the response to discovery request
989     if (virtualUriInRequest == OC_WELL_KNOWN_URI
990 #ifdef MQ_BROKER
991             || virtualUriInRequest == OC_MQ_BROKER_URI
992 #endif
993             )
994     {
995         discoveryResult = getQueryParamsForFiltering(virtualUriInRequest, request->query,
996                 &interfaceQuery, &resourceTypeQuery);
997         VERIFY_SUCCESS(discoveryResult);
998
999         if (!interfaceQuery && !resourceTypeQuery)
1000         {
1001             // If no query is sent, default interface is used i.e. oic.if.ll.
1002             interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
1003         }
1004
1005         discoveryResult = discoveryPayloadCreateAndAddDeviceId(&payload);
1006         VERIFY_PARAM_NON_NULL(TAG, payload, "Failed creating Discovery Payload.");
1007         VERIFY_SUCCESS(discoveryResult);
1008
1009         OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
1010         if (interfaceQuery && 0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_DEFAULT))
1011         {
1012             discoveryResult = addDiscoveryBaselineCommonProperties(discPayload);
1013             VERIFY_SUCCESS(discoveryResult);
1014         }
1015         OCResourceProperty prop = OC_DISCOVERABLE;
1016 #ifdef MQ_BROKER
1017         prop = (OC_MQ_BROKER_URI == virtualUriInRequest) ? OC_MQ_BROKER : prop;
1018 #endif
1019         for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
1020         {
1021             // This case will handle when no resource type and it is oic.if.ll.
1022             // Do not assume check if the query is ll
1023             if (!resourceTypeQuery &&
1024                 (interfaceQuery && 0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
1025             {
1026                 // Only include discoverable type
1027                 if (resource->resourceProperties & prop)
1028                 {
1029                     discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
1030                 }
1031             }
1032             else if (includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
1033             {
1034                 discoveryResult = BuildVirtualResourceResponse(resource, discPayload, &request->devAddr);
1035             }
1036             else
1037             {
1038                 discoveryResult = OC_STACK_OK;
1039             }
1040         }
1041         if (discPayload->resources == NULL)
1042         {
1043             discoveryResult = OC_STACK_NO_RESOURCE;
1044         }
1045     }
1046     else if (virtualUriInRequest == OC_DEVICE_URI)
1047     {
1048         OCResource *resourcePtr = FindResourceByUri(OC_RSRVD_DEVICE_URI);
1049         VERIFY_PARAM_NON_NULL(TAG, resourcePtr, "Device URI not found.");
1050         discoveryResult = BuildDevicePlatformPayload(resourcePtr, (OCRepPayload **)&payload, true);
1051     }
1052     else if (virtualUriInRequest == OC_PLATFORM_URI)
1053     {
1054         OCResource *resourcePtr = FindResourceByUri(OC_RSRVD_PLATFORM_URI);
1055         VERIFY_PARAM_NON_NULL(TAG, resourcePtr, "Platform URI not found.");
1056         discoveryResult = BuildDevicePlatformPayload(resourcePtr, (OCRepPayload **)&payload, false);
1057     }
1058 #ifdef ROUTING_GATEWAY
1059     else if (OC_GATEWAY_URI == virtualUriInRequest)
1060     {
1061         // Received request for a gateway
1062         OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
1063         discoveryResult = RMHandleGatewayRequest(request, resource);
1064     }
1065 #endif
1066
1067     /**
1068      * Step 2: Send the discovery response
1069      *
1070      * Iotivity should respond to discovery requests in below manner:
1071      * 1)If query filter matching fails and discovery request is multicast,
1072      *   it should NOT send any response.
1073      * 2)If query filter matching fails and discovery request is unicast,
1074      *   it should send an error(RESOURCE_NOT_FOUND - 404) response.
1075      * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
1076      *   request is multicast, it should NOT send any response.
1077      * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
1078      *   request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
1079      */
1080
1081 #ifdef WITH_PRESENCE
1082     if ((virtualUriInRequest == OC_PRESENCE) &&
1083         (resource->resourceProperties & OC_ACTIVE))
1084     {
1085         // Need to send ACK when the request is CON.
1086         if (request->qos == OC_HIGH_QOS)
1087         {
1088             CAEndpoint_t endpoint = { .adapter = CA_DEFAULT_ADAPTER };
1089             CopyDevAddrToEndpoint(&request->devAddr, &endpoint);
1090             SendDirectStackResponse(&endpoint, request->coapID, CA_EMPTY, CA_MSG_ACKNOWLEDGE,
1091                                     0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1092         }
1093         FindAndDeleteServerRequest(request);
1094
1095         // Presence uses observer notification api to respond via SendPresenceNotification.
1096         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
1097     }
1098     else
1099 #endif
1100 #if ROUTING_GATEWAY
1101     // Gateway uses the RMHandleGatewayRequest to respond to the request.
1102     if (OC_GATEWAY_URI != virtualUriInRequest)
1103 #endif
1104     {
1105         OIC_LOG_PAYLOAD(DEBUG, payload);
1106         if(discoveryResult == OC_STACK_OK)
1107         {
1108
1109             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
1110         }
1111         else // Error handling
1112         {
1113             if (isUnicast(request))
1114             {
1115                 OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
1116                     discoveryResult, virtualUriInRequest);
1117                 SendNonPersistantDiscoveryResponse(request, resource, NULL,
1118                     (discoveryResult == OC_STACK_NO_RESOURCE) ?
1119                         OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
1120             }
1121             else // Multicast
1122             {
1123                 // Ignoring the discovery request as per RFC 7252, Section #8.2
1124                 OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send.");
1125                 // the request should be removed.
1126                 // since it never remove and causes a big memory waste.
1127                 FindAndDeleteServerRequest(request);
1128             }
1129             discoveryResult = OC_STACK_CONTINUE;
1130         }
1131     }
1132
1133 exit:
1134     if (interfaceQuery)
1135     {
1136         OICFree(interfaceQuery);
1137     }
1138
1139     if (resourceTypeQuery)
1140     {
1141         OICFree(resourceTypeQuery);
1142     }
1143     OCPayloadDestroy(payload);
1144
1145     // To ignore the message, OC_STACK_CONTINUE is sent
1146     return discoveryResult;
1147 }
1148
1149 static OCStackResult
1150 HandleDefaultDeviceEntityHandler(OCServerRequest *request)
1151 {
1152     if (!request)
1153     {
1154         return OC_STACK_INVALID_PARAM;
1155     }
1156
1157     OCEntityHandlerResult ehResult = OC_EH_ERROR;
1158     OCEntityHandlerRequest ehRequest = {0};
1159     OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
1160     OCStackResult result = EHRequest(&ehRequest, PAYLOAD_TYPE_REPRESENTATION, request, NULL);
1161     VERIFY_SUCCESS(result);
1162
1163     // At this point we know for sure that defaultDeviceHandler exists
1164     ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
1165                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
1166     if(ehResult == OC_EH_SLOW)
1167     {
1168         OIC_LOG(INFO, TAG, "This is a slow resource");
1169         request->slowFlag = 1;
1170     }
1171
1172     result = EntityHandlerCodeToOCStackCode(ehResult);
1173
1174     // Clear server request on error case
1175     if (!OCResultToSuccess(result))
1176     {
1177         FindAndDeleteServerRequest(request);
1178     }
1179
1180 exit:
1181     OCPayloadDestroy(ehRequest.payload);
1182     return result;
1183 }
1184
1185 static OCStackResult
1186 HandleResourceWithEntityHandler(OCServerRequest *request,
1187                                 OCResource *resource)
1188 {
1189     if(!request || ! resource)
1190     {
1191         return OC_STACK_INVALID_PARAM;
1192     }
1193
1194     OCStackResult result = OC_STACK_ERROR;
1195     OCEntityHandlerResult ehResult = OC_EH_ERROR;
1196     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
1197     ResourceObserver *resObs = NULL;
1198
1199     OCEntityHandlerRequest ehRequest = {0};
1200
1201     OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
1202     OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
1203     // check the security resource
1204     if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
1205     {
1206         type = PAYLOAD_TYPE_SECURITY;
1207     }
1208
1209     result = EHRequest(&ehRequest, type, request, resource);
1210     VERIFY_SUCCESS(result);
1211
1212     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
1213     {
1214         OIC_LOG(INFO, TAG, "No observation requested");
1215         ehFlag = OC_REQUEST_FLAG;
1216     }
1217     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER)
1218     {
1219         OIC_LOG(INFO, TAG, "Observation registration requested");
1220
1221         ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
1222                                     request->tokenLength);
1223
1224         if (obs)
1225         {
1226             OIC_LOG (INFO, TAG, "Observer with this token already present");
1227             OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
1228             OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
1229             OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
1230
1231             FreeObserver(obs);
1232             return OC_STACK_OK;
1233         }
1234
1235         result = GenerateObserverId(&ehRequest.obsInfo.obsId);
1236         VERIFY_SUCCESS(result);
1237
1238         result = AddObserver ((const char*)(request->resourceUrl),
1239                 (const char *)(request->query),
1240                 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
1241                 resource, request->qos, request->acceptFormat,
1242                 &request->devAddr);
1243
1244         if(result == OC_STACK_OK)
1245         {
1246             OIC_LOG(INFO, TAG, "Added observer successfully");
1247             request->observeResult = OC_STACK_OK;
1248             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1249         }
1250         else if (result == OC_STACK_RESOURCE_ERROR)
1251         {
1252             OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
1253             request->observeResult = OC_STACK_ERROR;
1254             ehFlag = OC_REQUEST_FLAG;
1255         }
1256         else
1257         {
1258             // The error in observeResult for the request will be used when responding to this
1259             // request by omitting the observation option/sequence number.
1260             request->observeResult = OC_STACK_ERROR;
1261             OIC_LOG(ERROR, TAG, "Observer Addition failed");
1262             ehFlag = OC_REQUEST_FLAG;
1263             FindAndDeleteServerRequest(request);
1264             goto exit;
1265         }
1266
1267     }
1268     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER)
1269     {
1270         OIC_LOG(INFO, TAG, "Deregistering observation requested");
1271
1272         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1273
1274         if (NULL == resObs)
1275         {
1276             // Stack does not contain this observation request
1277             // Either token is incorrect or observation list is corrupted
1278             result = OC_STACK_NO_RESOURCE;
1279             goto exit;
1280         }
1281         ehRequest.obsInfo.obsId = resObs->observeId;
1282         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1283
1284         result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1285
1286         if(result == OC_STACK_OK)
1287         {
1288             OIC_LOG(INFO, TAG, "Removed observer successfully");
1289             request->observeResult = OC_STACK_OK;
1290             // There should be no observe option header for de-registration response.
1291             // Set as an invalid value here so we can detect it later and remove the field in response.
1292             request->observationOption = MAX_SEQUENCE_NUMBER + 1;
1293         }
1294         else
1295         {
1296             request->observeResult = OC_STACK_ERROR;
1297             OIC_LOG(ERROR, TAG, "Observer Removal failed");
1298             FindAndDeleteServerRequest(request);
1299             goto exit;
1300         }
1301     }
1302     else
1303     {
1304         result = OC_STACK_ERROR;
1305         goto exit;
1306     }
1307
1308     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1309     if(ehResult == OC_EH_SLOW)
1310     {
1311         OIC_LOG(INFO, TAG, "This is a slow resource");
1312         request->slowFlag = 1;
1313     }
1314
1315     result = EntityHandlerCodeToOCStackCode(ehResult);
1316
1317     // Clear server request on error case
1318     if (!OCResultToSuccess(result))
1319     {
1320         FindAndDeleteServerRequest(request);
1321     }
1322
1323 exit:
1324     OCPayloadDestroy(ehRequest.payload);
1325     FreeObserver(resObs);
1326     return result;
1327 }
1328
1329 static OCStackResult HandleCollectionResourceDefaultEntityHandler(OCServerRequest *request,
1330                                                                   OCResource *resource)
1331 {
1332     if (!request || !resource)
1333     {
1334         return OC_STACK_INVALID_PARAM;
1335     }
1336
1337     OCEntityHandlerRequest ehRequest = {0};
1338     OCStackResult result = EHRequest(&ehRequest, PAYLOAD_TYPE_REPRESENTATION, request, resource);
1339     if(result == OC_STACK_OK)
1340     {
1341         result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1342     }
1343
1344     OCPayloadDestroy(ehRequest.payload);
1345     return result;
1346 }
1347
1348 OCStackResult
1349 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1350 {
1351     OCStackResult ret = OC_STACK_OK;
1352
1353     switch (resHandling)
1354     {
1355         case OC_RESOURCE_VIRTUAL:
1356         {
1357             ret = HandleVirtualResource (request, resource);
1358             break;
1359         }
1360         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1361         {
1362             ret = HandleDefaultDeviceEntityHandler(request);
1363             break;
1364         }
1365         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1366         {
1367             OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1368             return OC_STACK_ERROR;
1369         }
1370         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1371         {
1372             ret = HandleResourceWithEntityHandler (request, resource);
1373             break;
1374         }
1375         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1376         {
1377             ret = HandleResourceWithEntityHandler (request, resource);
1378             break;
1379         }
1380         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1381         {
1382             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1383             break;
1384         }
1385         case OC_RESOURCE_NOT_SPECIFIED:
1386         {
1387             ret = OC_STACK_NO_RESOURCE;
1388             break;
1389         }
1390         default:
1391         {
1392             OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1393             return OC_STACK_ERROR;
1394         }
1395     }
1396     return ret;
1397 }
1398
1399 OCStackResult OCSetPlatformInfo(OCPlatformInfo info)
1400 {
1401     OCResource *resource = NULL;
1402     if (!info.platformID || !info.manufacturerName)
1403     {
1404         OIC_LOG(ERROR, TAG, "No value specified.");
1405         goto exit;
1406     }
1407     if (0 == strlen(info.platformID) || 0 == strlen(info.manufacturerName))
1408     {
1409         OIC_LOG(ERROR, TAG, "The passed value cannot be empty");
1410         goto exit;
1411     }
1412     if ((info.manufacturerName && strlen(info.manufacturerName) > MAX_PLATFORM_NAME_LENGTH) ||
1413         (info.manufacturerUrl && strlen(info.manufacturerUrl) > MAX_PLATFORM_URL_LENGTH) ||
1414         (info.modelNumber && strlen(info.modelNumber) > MAX_PLATFORM_NAME_LENGTH) ||
1415         (info.platformVersion && strlen(info.platformVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1416         (info.operatingSystemVersion && strlen(info.operatingSystemVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1417         (info.hardwareVersion && strlen(info.hardwareVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1418         (info.firmwareVersion && strlen(info.firmwareVersion) > MAX_PLATFORM_NAME_LENGTH) ||
1419         (info.supportUrl && strlen(info.supportUrl) > MAX_PLATFORM_URL_LENGTH))
1420     {
1421         OIC_LOG(ERROR, TAG, "The passed value is bigger than permitted.");
1422         goto exit;
1423     }
1424
1425     resource = FindResourceByUri(OC_RSRVD_PLATFORM_URI);
1426     if (!resource)
1427     {
1428         OIC_LOG(ERROR, TAG, "Platform Resource does not exist.");
1429         goto exit;
1430     }
1431     OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
1432     VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_PLATFORM_ID, info.platformID));
1433     VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_NAME, info.manufacturerName));
1434     OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_URL, info.manufacturerUrl);
1435     OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MODEL_NUM, info.modelNumber);
1436     OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_MFG_DATE, info.dateOfManufacture);
1437     OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_PLATFORM_VERSION, info.platformVersion);
1438     OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_OS_VERSION, info.operatingSystemVersion);
1439     OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_HARDWARE_VERSION, info.hardwareVersion);
1440     OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_FIRMWARE_VERSION, info.firmwareVersion);
1441     OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_SUPPORT_URL, info.supportUrl);
1442     OCSetPropertyValue(PAYLOAD_TYPE_PLATFORM, OC_RSRVD_SYSTEM_TIME, info.systemTime);
1443     OIC_LOG(INFO, TAG, "Platform parameter initialized successfully.");
1444     return OC_STACK_OK;
1445
1446 exit:
1447     return OC_STACK_INVALID_PARAM;
1448 }
1449
1450 OCStackResult OCSetDeviceInfo(OCDeviceInfo info)
1451 {
1452     OCStringLL *dataModelVersion = NULL;
1453     OCResource *resource = FindResourceByUri(OC_RSRVD_DEVICE_URI);
1454     if (!resource)
1455     {
1456         OIC_LOG(ERROR, TAG, "Device Resource does not exist.");
1457         goto exit;
1458     }
1459     if (!info.deviceName || info.deviceName[0] == '\0')
1460     {
1461         OIC_LOG(ERROR, TAG, "Null or empty device name.");
1462        return OC_STACK_INVALID_PARAM;
1463     }
1464
1465     if (OCGetServerInstanceIDString() == NULL)
1466     {
1467         OIC_LOG(INFO, TAG, "Device ID generation failed");
1468         goto exit;
1469     }
1470
1471     VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME, info.deviceName));
1472     for (OCStringLL *temp = info.types; temp; temp = temp->next)
1473     {
1474         if (temp->value)
1475         {
1476             VERIFY_SUCCESS(OCBindResourceTypeToResource(resource, temp->value));
1477         }
1478     }
1479     VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, info.specVersion ?
1480         info.specVersion: OC_SPEC_VERSION));
1481     if (info.dataModelVersions)
1482     {
1483         VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION, info.dataModelVersions));
1484     }
1485     else
1486     {
1487         dataModelVersion = OCCreateOCStringLL(OC_DATA_MODEL_VERSION);
1488         VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION, dataModelVersion));
1489 #ifdef __TIZENRT__
1490         OCFreeOCStringLL(dataModelVersion);
1491 #endif
1492     }
1493     OIC_LOG(INFO, TAG, "Device parameter initialized successfully.");
1494     return OC_STACK_OK;
1495
1496 exit:
1497     if (dataModelVersion)
1498     {
1499         OCFreeOCStringLL(dataModelVersion);
1500     }
1501     return OC_STACK_ERROR;
1502 }
1503
1504 OCStackResult OCGetAttribute(const OCResource *resource, const char *attribute, void **value)
1505 {
1506     if (!resource || !attribute)
1507     {
1508         return OC_STACK_INVALID_PARAM;
1509     }
1510     if (0 == strlen(attribute))
1511     {
1512         return OC_STACK_INVALID_PARAM;
1513     }
1514     for (OCAttribute *temp = resource->rsrcAttributes; temp; temp = temp->next)
1515     {
1516         if (0 == strcmp(attribute, temp->attrName))
1517         {
1518             // A special case as this type return OCStringLL
1519             if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, attribute))
1520             {
1521                 *value = CloneOCStringLL((OCStringLL *)temp->attrValue);
1522                 return OC_STACK_OK;
1523             }
1524             else
1525             {
1526                 *value = OICStrdup((char *)temp->attrValue);
1527                 return OC_STACK_OK;
1528             }
1529         }
1530     }
1531     return OC_STACK_NO_RESOURCE;
1532 }
1533
1534 OCStackResult OCGetPropertyValue(OCPayloadType type, const char *prop, void **value)
1535 {
1536     if (!prop || *value)
1537     {
1538         return OC_STACK_INVALID_PARAM;
1539     }
1540     if (strlen(prop) == 0)
1541     {
1542         return OC_STACK_INVALID_PARAM;
1543     }
1544     OCStackResult res =  OC_STACK_NO_RESOURCE;
1545     if (PAYLOAD_TYPE_DEVICE == type || PAYLOAD_TYPE_PLATFORM == type)
1546     {
1547         const char *pathType = (type == PAYLOAD_TYPE_DEVICE) ? OC_RSRVD_DEVICE_URI : OC_RSRVD_PLATFORM_URI;
1548         OCResource *resource = FindResourceByUri(pathType);
1549         if (!resource)
1550         {
1551             return OC_STACK_NO_RESOURCE;
1552         }
1553
1554         res = OCGetAttribute(resource, prop, value);
1555     }
1556     return res;
1557 }
1558
1559 OCStackResult OCSetAttribute(OCResource* resource, const char* attribute, const void* value)
1560 {
1561     // See if the attribute already exists in the list.
1562     OCAttribute *resAttrib;
1563     for (resAttrib = resource->rsrcAttributes; resAttrib; resAttrib = resAttrib->next)
1564     {
1565         if (0 == strcmp(attribute, resAttrib->attrName))
1566         {
1567             // Found, free the old value.
1568             if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, resAttrib->attrName))
1569             {
1570                 OCFreeOCStringLL((OCStringLL *)resAttrib->attrValue);
1571             }
1572             else
1573             {
1574                 OICFree((char *)resAttrib->attrValue);
1575             }
1576             break;
1577         }
1578     }
1579
1580     // If not already in the list, add it.
1581     if (NULL == resAttrib)
1582     {
1583         resAttrib = (OCAttribute *)OICCalloc(1, sizeof(OCAttribute));
1584         VERIFY_PARAM_NON_NULL(TAG, resAttrib, "Failed allocating OCAttribute");
1585         resAttrib->attrName = OICStrdup(attribute);
1586         VERIFY_PARAM_NON_NULL(TAG, resAttrib->attrName, "Failed allocating attribute name");
1587         resAttrib->next = resource->rsrcAttributes;
1588         resource->rsrcAttributes = resAttrib;
1589     }
1590
1591     // Fill in the new value.
1592     if (0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, attribute))
1593     {
1594         resAttrib->attrValue = CloneOCStringLL((OCStringLL *)value);
1595     }
1596     else
1597     {
1598         resAttrib->attrValue = OICStrdup((char *)value);
1599     }
1600     VERIFY_PARAM_NON_NULL(TAG, resAttrib->attrValue, "Failed allocating attribute value");
1601
1602     return OC_STACK_OK;
1603
1604 exit:
1605     OCDeleteResourceAttributes(resAttrib);
1606     return OC_STACK_NO_MEMORY;
1607
1608 }
1609
1610 OCStackResult OCSetPropertyValue(OCPayloadType type, const char *prop, const void *value)
1611 {
1612     if (!prop || !value)
1613     {
1614         return OC_STACK_INVALID_PARAM;
1615     }
1616     if (strlen(prop) == 0)
1617     {
1618         return OC_STACK_INVALID_PARAM;
1619     }
1620
1621     OCStackResult res = OC_STACK_ERROR;
1622     if (PAYLOAD_TYPE_DEVICE == type || PAYLOAD_TYPE_PLATFORM == type)
1623     {
1624         const char *pathType = (type == PAYLOAD_TYPE_DEVICE) ? OC_RSRVD_DEVICE_URI : OC_RSRVD_PLATFORM_URI;
1625         OCResource *resource = FindResourceByUri(pathType);
1626         if (!resource)
1627         {
1628             OIC_LOG(ERROR, TAG, "Resource does not exist.");
1629         }
1630         else
1631         {
1632             res = OCSetAttribute(resource, prop, value);
1633         }
1634     }
1635
1636     return res;
1637 }