IOT-1075 PUT/POST/DELETE for /oic/res, /oic/d, /oic/p returns error
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocresource.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1-2001 base
24 // specification (excluding the XSI extension).
25 // For POSIX.1-2001 base specification,
26 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
27 #define _POSIX_C_SOURCE 200112L
28
29 #ifdef WITH_ARDUINO
30 #include <string.h>
31 #else
32 #include <strings.h>
33 #endif
34
35 #include "ocresource.h"
36 #include "ocresourcehandler.h"
37 #include "ocobserve.h"
38 #include "occollection.h"
39 #include "oic_malloc.h"
40 #include "oic_string.h"
41 #include "logger.h"
42 #include "cJSON.h"
43 #include "ocpayload.h"
44 #include "secureresourcemanager.h"
45 #include "cacommon.h"
46 #include "cainterface.h"
47 #include "rdpayload.h"
48 #include "ocpayload.h"
49
50 #ifdef WITH_RD
51 #include "rd_server.h"
52 #endif
53
54 #ifdef ROUTING_GATEWAY
55 #include "routingmanager.h"
56 #endif
57
58 /// Module Name
59 #define TAG "OIC_RI_RESOURCE"
60
61 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
62             {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
63
64 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
65              TAG, #arg " is NULL"); return (retVal); } }
66
67 extern OCResource *headResource;
68 static OCPlatformInfo savedPlatformInfo = {0};
69 static OCDeviceInfo savedDeviceInfo = {0};
70
71 /**
72  * Prepares a Payload for response.
73  */
74 static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
75                                                   OCDiscoveryPayload* payload,
76                                                   OCDevAddr *endpoint,
77                                                   bool rdResponse);
78
79 //-----------------------------------------------------------------------------
80 // Default resource entity handler function
81 //-----------------------------------------------------------------------------
82 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
83         OCEntityHandlerRequest * request, void* callbackParam)
84 {
85     //TODO ("Implement me!!!!");
86     // TODO:  remove silence unused param warnings
87     (void) flag;
88     (void) request;
89     (void) callbackParam;
90     return  OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
91 }
92
93 /* This method will retrieve the port at which the secure resource is hosted */
94 static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port)
95 {
96     uint16_t p = 0;
97
98     if (endpoint->adapter == OC_ADAPTER_IP)
99     {
100         if (endpoint->flags & OC_IP_USE_V6)
101         {
102             p = caglobals.ip.u6s.port;
103         }
104         else if (endpoint->flags & OC_IP_USE_V4)
105         {
106             p = caglobals.ip.u4s.port;
107         }
108     }
109
110     *port = p;
111     return OC_STACK_OK;
112 }
113
114 /*
115  * Function will extract 0, 1 or 2 filters from query.
116  * More than 2 filters or unsupported filters will result in error.
117  * If both filters are of the same supported type, the 2nd one will be picked.
118  * Resource and device filters in the SAME query are NOT validated
119  * and resources will likely not clear filters.
120  */
121 static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
122 {
123
124     char *key = NULL;
125     char *value = NULL;
126     char *restOfQuery = NULL;
127     int numKeyValuePairsParsed = 0;
128
129     *filterOne = NULL;
130     *filterTwo = NULL;
131
132     OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
133
134     char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
135
136     while(keyValuePair)
137     {
138         if (numKeyValuePairsParsed >= 2)
139         {
140             OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
141             return OC_STACK_INVALID_QUERY;
142         }
143
144         key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
145
146         if (!key || !value)
147         {
148             return OC_STACK_INVALID_QUERY;
149         }
150         else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
151         {
152             *filterOne = value;     // if
153         }
154         else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
155         {
156             *filterTwo = value;     // rt
157         }
158         else
159         {
160             OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
161             return OC_STACK_INVALID_QUERY;
162         }
163         ++numKeyValuePairsParsed;
164
165         keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
166     }
167
168     OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
169     return OC_STACK_OK;
170 }
171
172 static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
173 {
174     if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
175     {
176         return OC_WELL_KNOWN_URI;
177     }
178     else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
179     {
180         return OC_DEVICE_URI;
181     }
182     else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
183     {
184         return OC_PLATFORM_URI;
185     }
186     else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
187     {
188         return OC_RESOURCE_TYPES_URI;
189     }
190 #ifdef ROUTING_GATEWAY
191     else if (0 == strcmp(uriInRequest, OC_RSRVD_GATEWAY_URI))
192     {
193         return OC_GATEWAY_URI;
194     }
195 #endif
196 #ifdef WITH_PRESENCE
197     else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
198     {
199         return OC_PRESENCE;
200     }
201 #endif //WITH_PRESENCE
202     return OC_UNKNOWN_URI;
203 }
204
205 static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
206                                             char **filterOne, char **filterTwo)
207 {
208     if(!filterOne || !filterTwo)
209     {
210         return OC_STACK_INVALID_PARAM;
211     }
212
213     *filterOne = NULL;
214     *filterTwo = NULL;
215
216     #ifdef WITH_PRESENCE
217     if (uri == OC_PRESENCE)
218     {
219         //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
220         OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
221         return OC_STACK_OK;
222     }
223     #endif
224
225     OCStackResult result = OC_STACK_OK;
226
227     if (query && *query)
228     {
229         result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
230     }
231
232     return result;
233 }
234
235 OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
236                     OCRepPayload** payload)
237 {
238     OCRepPayload *tempPayload = OCRepPayloadCreate();
239
240     if (!resourcePtr)
241     {
242         OCRepPayloadDestroy(tempPayload);
243         return OC_STACK_INVALID_PARAM;
244     }
245
246     if(!tempPayload)
247     {
248         return OC_STACK_NO_MEMORY;
249     }
250
251     OCRepPayloadSetUri(tempPayload, resourcePtr->uri);
252
253     OCResourceType *resType = resourcePtr->rsrcType;
254     while(resType)
255     {
256         OCRepPayloadAddResourceType(tempPayload, resType->resourcetypename);
257         resType = resType->next;
258     }
259
260     OCResourceInterface *resInterface = resourcePtr->rsrcInterface;
261     while(resInterface)
262     {
263         OCRepPayloadAddInterface(tempPayload, resInterface->name);
264         resInterface = resInterface->next;
265     }
266
267     OCAttribute *resAttrib = resourcePtr->rsrcAttributes;
268     while(resAttrib)
269     {
270         OCRepPayloadSetPropString(tempPayload, resAttrib->attrName,
271                                 resAttrib->attrValue);
272         resAttrib = resAttrib->next;
273     }
274
275     if(!*payload)
276     {
277         *payload = tempPayload;
278     }
279     else
280     {
281         OCRepPayloadAppend(*payload, tempPayload);
282     }
283
284     return OC_STACK_OK;
285 }
286
287 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
288                         OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
289 {
290     if (!resourcePtr || !payload)
291     {
292         return OC_STACK_INVALID_PARAM;
293     }
294     uint16_t port = 0;
295     if (resourcePtr->resourceProperties & OC_SECURE)
296     {
297        if (GetSecurePortInfo(devAddr, &port) != OC_STACK_OK)
298        {
299            port = 0;
300        }
301     }
302
303     if (rdResponse)
304     {
305         port = devAddr->port;
306     }
307
308     OCDiscoveryPayloadAddResource(payload, resourcePtr, port);
309     return OC_STACK_OK;
310 }
311
312 uint8_t IsCollectionResource (OCResource *resource)
313 {
314     if(!resource)
315     {
316         return 0;
317     }
318
319     if(resource->rsrcChildResourcesHead != NULL)
320     {
321         return 1;
322     }
323
324     return 0;
325 }
326
327 OCResource *FindResourceByUri(const char* resourceUri)
328 {
329     if(!resourceUri)
330     {
331         return NULL;
332     }
333
334     OCResource * pointer = headResource;
335     while (pointer)
336     {
337         if (strcmp(resourceUri, pointer->uri) == 0)
338         {
339             return pointer;
340         }
341         pointer = pointer->next;
342     }
343     OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
344     return NULL;
345 }
346
347
348 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
349                                          ResourceHandling *handling,
350                                          OCResource **resource)
351 {
352     if(!request || !handling || !resource)
353     {
354         return OC_STACK_INVALID_PARAM;
355     }
356
357     OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
358
359     // Check if virtual resource
360     if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
361     {
362         OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
363         *handling = OC_RESOURCE_VIRTUAL;
364         *resource = headResource;
365         return OC_STACK_OK;
366     }
367     if (strlen((const char*)(request->resourceUrl)) == 0)
368     {
369         // Resource URL not specified
370         *handling = OC_RESOURCE_NOT_SPECIFIED;
371         return OC_STACK_NO_RESOURCE;
372     }
373     else
374     {
375         OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
376         *resource = resourcePtr;
377         if (!resourcePtr)
378         {
379             if(defaultDeviceHandler)
380             {
381                 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
382                 return OC_STACK_OK;
383             }
384
385             // Resource does not exist
386             // and default device handler does not exist
387             *handling = OC_RESOURCE_NOT_SPECIFIED;
388             return OC_STACK_NO_RESOURCE;
389         }
390
391         if (IsCollectionResource (resourcePtr))
392         {
393             // Collection resource
394             if (resourcePtr->entityHandler != defaultResourceEHandler)
395             {
396                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
397                 return OC_STACK_OK;
398             }
399             else
400             {
401                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
402                 return OC_STACK_OK;
403             }
404         }
405         else
406         {
407             // Resource not a collection
408             if (resourcePtr->entityHandler != defaultResourceEHandler)
409             {
410                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
411                 return OC_STACK_OK;
412             }
413             else
414             {
415                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
416                 return OC_STACK_OK;
417             }
418         }
419     }
420 }
421
422 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
423 {
424     OCStackResult result;
425
426     switch (ehResult)
427     {
428         case OC_EH_OK:
429             result = OC_STACK_OK;
430             break;
431         case OC_EH_SLOW:
432             result = OC_STACK_SLOW_RESOURCE;
433             break;
434         case OC_EH_ERROR:
435             result = OC_STACK_ERROR;
436             break;
437         case OC_EH_FORBIDDEN:
438             result = OC_STACK_RESOURCE_ERROR;
439             break;
440         case OC_EH_RESOURCE_CREATED:
441             result = OC_STACK_RESOURCE_CREATED;
442             break;
443         case OC_EH_RESOURCE_DELETED:
444             result = OC_STACK_RESOURCE_DELETED;
445             break;
446         case OC_EH_RESOURCE_NOT_FOUND:
447             result = OC_STACK_NO_RESOURCE;
448             break;
449         default:
450             result = OC_STACK_ERROR;
451     }
452
453     return result;
454 }
455
456 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
457 {
458     if (!resource)
459     {
460         return false;
461     }
462
463     // Null or empty is analogous to no filter.
464     if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
465     {
466         return true;
467     }
468
469     OCResourceType *resourceTypePtr = resource->rsrcType;
470
471     while (resourceTypePtr)
472     {
473         if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
474         {
475             return true;
476         }
477         resourceTypePtr = resourceTypePtr->next;
478     }
479
480     OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
481     return false;
482 }
483
484 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
485 {
486     if (!resource)
487     {
488         return false;
489     }
490
491     // Null or empty is analogous to no filter.
492     if (interfaceFilter == NULL || *interfaceFilter == 0)
493     {
494         return true;
495     }
496
497     OCResourceInterface *interfacePtr = resource->rsrcInterface;
498
499     while (interfacePtr)
500     {
501         if (strcmp (interfacePtr->name, interfaceFilter) == 0)
502         {
503             return true;
504         }
505         interfacePtr = interfacePtr->next;
506     }
507
508     OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
509     return false;
510 }
511
512 /*
513  * If the filters are null, they will be assumed to NOT be present
514  * and the resource will not be matched against them.
515  * Function will return true if all non null AND non empty filters passed in find a match.
516  */
517 static bool includeThisResourceInResponse(OCResource *resource,
518                                                  char *interfaceFilter,
519                                                  char *resourceTypeFilter)
520 {
521     if (!resource)
522     {
523         OIC_LOG(ERROR, TAG, "Invalid resource");
524         return false;
525     }
526
527     if ( resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
528     {
529         /*
530          * At least one valid filter should be available to
531          * include the resource in discovery response
532          */
533         if (!((interfaceFilter && *interfaceFilter ) ||
534               (resourceTypeFilter && *resourceTypeFilter)))
535         {
536             OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
537                 resource", resource->uri);
538             return false;
539         }
540     }
541     else if ( !(resource->resourceProperties & OC_ACTIVE) ||
542          !(resource->resourceProperties & OC_DISCOVERABLE))
543     {
544         OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
545         return false;
546     }
547
548     return resourceMatchesIFFilter(resource, interfaceFilter) &&
549            resourceMatchesRTFilter(resource, resourceTypeFilter);
550
551 }
552
553 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
554                                 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
555 {
556     OCEntityHandlerResponse response = {0};
557
558     response.ehResult = ehResult;
559     response.payload = discoveryPayload;
560     response.persistentBufferFlag = 0;
561     response.requestHandle = (OCRequestHandle) request;
562     response.resourceHandle = (OCResourceHandle) resource;
563
564     return OCDoResponse(&response);
565 }
566
567 #ifdef WITH_RD
568 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
569      OCResource **payload, OCDevAddr *devAddr)
570 {
571     OCResourceCollectionPayload *repPayload;
572     if (!payload)
573     {
574         return OC_STACK_ERROR;
575     }
576     if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
577     {
578         if (!repPayload)
579         {
580             return OC_STACK_ERROR;
581         }
582         OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
583         if (!ptr)
584         {
585            return OC_STACK_NO_MEMORY;
586         }
587
588         ptr->uri = OICStrdup(repPayload->setLinks->href);
589         if (!ptr->uri)
590         {
591            return OC_STACK_NO_MEMORY;
592         }
593         OCStringLL *rt = repPayload->setLinks->rt;
594         while (rt)
595         {
596             OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
597             if(!temp)
598             {
599                 OICFree(ptr->uri);
600                 return OC_STACK_NO_MEMORY;
601             }
602             temp->next = NULL;
603             temp->resourcetypename = OICStrdup(rt->value);
604             if (!ptr->rsrcType)
605             {
606                 ptr->rsrcType = temp;
607             }
608             else
609             {
610                 OCResourceType *type = ptr->rsrcType;
611                 while (type->next)
612                 {
613                     type = type->next;
614                 }
615                 type->next = temp;
616             }
617             rt = rt->next;
618         }
619
620         OCStringLL *itf = repPayload->setLinks->itf;
621         while (itf)
622         {
623             OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
624             if (!temp)
625             {
626                 OICFree(ptr->uri);
627
628                 return OC_STACK_NO_MEMORY;
629             }
630             temp->next = NULL;
631             temp->name = OICStrdup(itf->value);
632             if (!ptr->rsrcInterface)
633             {
634                 ptr->rsrcInterface = temp;
635             }
636             else
637             {
638                 OCResourceInterface *type = ptr->rsrcInterface;
639                 while (type->next)
640                 {
641                     type = type->next;
642                 }
643                 type->next = temp;
644             }
645             itf = itf->next;
646         }
647
648         ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
649
650         OCFreeCollectionResource(repPayload);
651         *payload = ptr;
652         return OC_STACK_OK;
653     }
654     else
655     {
656         OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
657                              on the resource directory");
658     }
659     return OC_STACK_ERROR;
660 }
661 #endif
662
663 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
664 {
665     if (!request || !resource)
666     {
667         return OC_STACK_INVALID_PARAM;
668     }
669
670     OCStackResult discoveryResult = OC_STACK_ERROR;
671
672     bool bMulticast    = false;     // Was the discovery request a multicast request?
673     OCPayload* payload = NULL;
674
675     OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
676
677     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
678
679     // Step 1: Generate the response to discovery request
680     if (virtualUriInRequest == OC_WELL_KNOWN_URI)
681     {
682         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
683         {
684             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
685             return OC_STACK_UNAUTHORIZED_REQ;
686         }
687
688         char *interfaceQuery = NULL;
689         char *resourceTypeQuery = NULL;
690
691         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
692                 &interfaceQuery, &resourceTypeQuery);
693
694         if (discoveryResult == OC_STACK_OK)
695         {
696             payload = (OCPayload *)OCDiscoveryPayloadCreate();
697
698             if (payload)
699             {
700                 ((OCDiscoveryPayload*)payload)->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
701                 VERIFY_NON_NULL(((OCDiscoveryPayload*)payload)->sid, ERROR, OC_STACK_NO_MEMORY);
702                 memcpy(((OCDiscoveryPayload*)payload)->sid, OCGetServerInstanceIDString(), UUID_STRING_SIZE);
703
704                 if (interfaceQuery && 0 == strcmp(OC_RSRVD_INTERFACE_LL, interfaceQuery))
705                 {
706                     for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
707                     {
708                         discoveryResult = BuildVirtualResourceResponse(resource,
709                                 (OCDiscoveryPayload *)payload, &request->devAddr, false);
710                     }
711                 }
712                 else
713                 {
714                     bool foundResourceAtRD = false;
715                     for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
716                     {
717 #ifdef WITH_RD
718                         if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
719                         {
720                             OCResource *resource1 = NULL;
721                             OCDevAddr devAddr;
722                             discoveryResult = checkResourceExistsAtRD(interfaceQuery,
723                                 resourceTypeQuery, &resource1, &devAddr);
724                             if (discoveryResult != OC_STACK_OK)
725                             {
726                                  break;
727                             }
728                             discoveryResult = BuildVirtualResourceResponse(resource1,
729                                 (OCDiscoveryPayload*)payload, &devAddr, true);
730                             if (payload)
731                             {
732                                 ((OCDiscoveryPayload*)payload)->baseURI = OICStrdup(devAddr.addr);
733                             }
734                             OCDiscoveryResourceDestroy(resource1);
735                             foundResourceAtRD = true;
736                         }
737 #endif
738                         if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
739                         {
740                             discoveryResult = BuildVirtualResourceResponse(resource,
741                                 (OCDiscoveryPayload*)payload, &request->devAddr, false);
742                         }
743                     }
744                     // Set discoveryResult appropriately if no 'valid' resources are available
745                     if (((OCDiscoveryPayload*)payload)->resources == NULL && !foundResourceAtRD)
746                     {
747                         discoveryResult = OC_STACK_NO_RESOURCE;
748                     }
749                 }
750             }
751             else
752             {
753                 discoveryResult = OC_STACK_NO_MEMORY;
754             }
755         }
756         else
757         {
758             OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
759         }
760     }
761     else if (virtualUriInRequest == OC_DEVICE_URI)
762     {
763         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
764         {
765             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
766             return OC_STACK_UNAUTHORIZED_REQ;
767         }
768
769         const char* deviceId = OCGetServerInstanceIDString();
770         if (!deviceId)
771         {
772             discoveryResult = OC_STACK_ERROR;
773         }
774         else
775         {
776             payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
777                 savedDeviceInfo.types, OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
778             if (!payload)
779             {
780                 discoveryResult = OC_STACK_NO_MEMORY;
781             }
782             else
783             {
784                 discoveryResult = OC_STACK_OK;
785             }
786         }
787     }
788     else if (virtualUriInRequest == OC_PLATFORM_URI)
789     {
790         if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
791         {
792             OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
793             return OC_STACK_UNAUTHORIZED_REQ;
794         }
795
796         payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
797         if (!payload)
798         {
799             discoveryResult = OC_STACK_NO_MEMORY;
800         }
801         else
802         {
803             discoveryResult = OC_STACK_OK;
804         }
805     }
806 #ifdef ROUTING_GATEWAY
807     else if (OC_GATEWAY_URI == virtualUriInRequest)
808     {
809         // Received request for a gateway
810         OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
811         discoveryResult = RMHandleGatewayRequest(request, resource);
812
813     }
814 #endif
815
816     /**
817      * Step 2: Send the discovery response
818      *
819      * Iotivity should respond to discovery requests in below manner:
820      * 1)If query filter matching fails and discovery request is multicast,
821      *   it should NOT send any response.
822      * 2)If query filter matching fails and discovery request is unicast,
823      *   it should send an error(RESOURCE_NOT_FOUND - 404) response.
824      * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
825      *   request is multicast, it should NOT send any response.
826      * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
827      *   request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
828      */
829
830 #ifdef WITH_PRESENCE
831     if ((virtualUriInRequest == OC_PRESENCE) &&
832         (resource->resourceProperties & OC_ACTIVE))
833     {
834         // Presence uses observer notification api to respond via SendPresenceNotification.
835         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
836     }
837     else
838     #endif
839 #ifdef ROUTING_GATEWAY
840     // Gateway uses the RMHandleGatewayRequest to respond to the request.
841     if (OC_GATEWAY_URI != virtualUriInRequest)
842 #endif
843     {
844         if(discoveryResult == OC_STACK_OK)
845         {
846             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
847         }
848         else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
849                (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
850         {
851             OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d)  \
852                 discovery request", discoveryResult, virtualUriInRequest);
853             SendNonPersistantDiscoveryResponse(request, resource, NULL,
854                 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
855         }
856         else
857         {
858             // Ignoring the discovery request as per RFC 7252, Section #8.2
859             OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
860                 any useful data to send");
861         }
862     }
863
864     OCPayloadDestroy(payload);
865
866     return OC_STACK_OK;
867 }
868
869 static OCStackResult
870 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
871 {
872     if(!request)
873     {
874         return OC_STACK_INVALID_PARAM;
875     }
876
877     OCStackResult result = OC_STACK_OK;
878     OCEntityHandlerResult ehResult = OC_EH_ERROR;
879     OCEntityHandlerRequest ehRequest = {0};
880
881     OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
882     result = FormOCEntityHandlerRequest(&ehRequest,
883                                         (OCRequestHandle) request,
884                                         request->method,
885                                         &request->devAddr,
886                                         (OCResourceHandle) NULL, request->query,
887                                         PAYLOAD_TYPE_REPRESENTATION,
888                                         request->payload,
889                                         request->payloadSize,
890                                         request->numRcvdVendorSpecificHeaderOptions,
891                                         request->rcvdVendorSpecificHeaderOptions,
892                                         (OCObserveAction)request->observationOption,
893                                         (OCObservationId)0);
894     VERIFY_SUCCESS(result, OC_STACK_OK);
895
896     // At this point we know for sure that defaultDeviceHandler exists
897     ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
898                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
899     if(ehResult == OC_EH_SLOW)
900     {
901         OIC_LOG(INFO, TAG, "This is a slow resource");
902         request->slowFlag = 1;
903     }
904     else if(ehResult == OC_EH_ERROR)
905     {
906         FindAndDeleteServerRequest(request);
907     }
908     result = EntityHandlerCodeToOCStackCode(ehResult);
909 exit:
910     OCPayloadDestroy(ehRequest.payload);
911     return result;
912 }
913
914 static OCStackResult
915 HandleResourceWithEntityHandler (OCServerRequest *request,
916                                  OCResource *resource,
917                                  uint8_t collectionResource)
918 {
919     if(!request || ! resource)
920     {
921         return OC_STACK_INVALID_PARAM;
922     }
923
924     OCStackResult result = OC_STACK_ERROR;
925     OCEntityHandlerResult ehResult = OC_EH_ERROR;
926     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
927     ResourceObserver *resObs = NULL;
928
929     OCEntityHandlerRequest ehRequest = {0};
930
931     OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
932     OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
933     // check the security resource
934     if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
935     {
936         type = PAYLOAD_TYPE_SECURITY;
937
938     }
939
940     if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
941     {
942         type = PAYLOAD_TYPE_RD;
943     }
944
945     result = FormOCEntityHandlerRequest(&ehRequest,
946                                         (OCRequestHandle)request,
947                                         request->method,
948                                         &request->devAddr,
949                                         (OCResourceHandle)resource,
950                                         request->query,
951                                         type,
952                                         request->payload,
953                                         request->payloadSize,
954                                         request->numRcvdVendorSpecificHeaderOptions,
955                                         request->rcvdVendorSpecificHeaderOptions,
956                                         (OCObserveAction)request->observationOption,
957                                         0);
958     VERIFY_SUCCESS(result, OC_STACK_OK);
959
960     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
961     {
962         OIC_LOG(INFO, TAG, "No observation requested");
963         ehFlag = OC_REQUEST_FLAG;
964     }
965     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
966     {
967         OIC_LOG(INFO, TAG, "Observation registration requested");
968
969         ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
970                                     request->tokenLength);
971
972         if (obs)
973         {
974             OIC_LOG (INFO, TAG, "Observer with this token already present");
975             OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
976             OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
977             OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
978
979             // server requests are usually free'd when the response is sent out
980             // for the request in ocserverrequest.c : HandleSingleResponse()
981             // Since we are making an early return and not responding, the server request
982             // needs to be deleted.
983             FindAndDeleteServerRequest (request);
984             return OC_STACK_OK;
985         }
986
987         result = GenerateObserverId(&ehRequest.obsInfo.obsId);
988         VERIFY_SUCCESS(result, OC_STACK_OK);
989
990         result = AddObserver ((const char*)(request->resourceUrl),
991                 (const char *)(request->query),
992                 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
993                 resource, request->qos, request->acceptFormat,
994                 &request->devAddr);
995
996         if(result == OC_STACK_OK)
997         {
998             OIC_LOG(INFO, TAG, "Added observer successfully");
999             request->observeResult = OC_STACK_OK;
1000             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
1001         }
1002         else
1003         {
1004             result = OC_STACK_OK;
1005
1006             // The error in observeResult for the request will be used when responding to this
1007             // request by omitting the observation option/sequence number.
1008             request->observeResult = OC_STACK_ERROR;
1009             OIC_LOG(ERROR, TAG, "Observer Addition failed");
1010             ehFlag = OC_REQUEST_FLAG;
1011         }
1012
1013     }
1014     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
1015             !collectionResource)
1016     {
1017         OIC_LOG(INFO, TAG, "Deregistering observation requested");
1018
1019         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
1020
1021         if (NULL == resObs)
1022         {
1023             // Stack does not contain this observation request
1024             // Either token is incorrect or observation list is corrupted
1025             result = OC_STACK_ERROR;
1026             goto exit;
1027         }
1028         ehRequest.obsInfo.obsId = resObs->observeId;
1029         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
1030
1031         result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
1032
1033         if(result == OC_STACK_OK)
1034         {
1035             OIC_LOG(INFO, TAG, "Removed observer successfully");
1036             request->observeResult = OC_STACK_OK;
1037         }
1038         else
1039         {
1040             result = OC_STACK_OK;
1041             request->observeResult = OC_STACK_ERROR;
1042             OIC_LOG(ERROR, TAG, "Observer Removal failed");
1043         }
1044     }
1045     else
1046     {
1047         result = OC_STACK_ERROR;
1048         goto exit;
1049     }
1050
1051     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
1052     if(ehResult == OC_EH_SLOW)
1053     {
1054         OIC_LOG(INFO, TAG, "This is a slow resource");
1055         request->slowFlag = 1;
1056     }
1057     else if(ehResult == OC_EH_ERROR)
1058     {
1059         FindAndDeleteServerRequest(request);
1060     }
1061     result = EntityHandlerCodeToOCStackCode(ehResult);
1062 exit:
1063     OCPayloadDestroy(ehRequest.payload);
1064     return result;
1065 }
1066
1067 static OCStackResult
1068 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
1069                                               OCResource *resource)
1070 {
1071     if(!request || !resource)
1072     {
1073         return OC_STACK_INVALID_PARAM;
1074     }
1075
1076     OCStackResult result = OC_STACK_ERROR;
1077     OCEntityHandlerRequest ehRequest = {0};
1078
1079     result = FormOCEntityHandlerRequest(&ehRequest,
1080                                         (OCRequestHandle)request,
1081                                         request->method,
1082                                         &request->devAddr,
1083                                         (OCResourceHandle)resource,
1084                                         request->query,
1085                                         PAYLOAD_TYPE_REPRESENTATION,
1086                                         request->payload,
1087                                         request->payloadSize,
1088                                         request->numRcvdVendorSpecificHeaderOptions,
1089                                         request->rcvdVendorSpecificHeaderOptions,
1090                                         (OCObserveAction)request->observationOption,
1091                                         (OCObservationId)0);
1092     if(result == OC_STACK_OK)
1093     {
1094         result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
1095     }
1096
1097     OCPayloadDestroy(ehRequest.payload);
1098     return result;
1099 }
1100
1101 OCStackResult
1102 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
1103 {
1104     OCStackResult ret = OC_STACK_OK;
1105
1106     switch (resHandling)
1107     {
1108         case OC_RESOURCE_VIRTUAL:
1109         {
1110             ret = HandleVirtualResource (request, resource);
1111             break;
1112         }
1113         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1114         {
1115             ret = HandleDefaultDeviceEntityHandler(request);
1116             break;
1117         }
1118         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1119         {
1120             OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1121             return OC_STACK_ERROR;
1122         }
1123         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1124         {
1125             ret = HandleResourceWithEntityHandler (request, resource, 0);
1126             break;
1127         }
1128         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1129         {
1130             ret = HandleResourceWithEntityHandler (request, resource, 1);
1131             break;
1132         }
1133         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1134         {
1135             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1136             break;
1137         }
1138         case OC_RESOURCE_NOT_SPECIFIED:
1139         {
1140             ret = OC_STACK_NO_RESOURCE;
1141             break;
1142         }
1143         default:
1144         {
1145             OIC_LOG(INFO, TAG, "Invalid Resource Determination");
1146             return OC_STACK_ERROR;
1147         }
1148     }
1149     return ret;
1150 }
1151
1152 void DeletePlatformInfo()
1153 {
1154     OIC_LOG(INFO, TAG, "Deleting platform info.");
1155
1156     OICFree(savedPlatformInfo.platformID);
1157     savedPlatformInfo.platformID = NULL;
1158
1159     OICFree(savedPlatformInfo.manufacturerName);
1160     savedPlatformInfo.manufacturerName = NULL;
1161
1162     OICFree(savedPlatformInfo.manufacturerUrl);
1163     savedPlatformInfo.manufacturerUrl = NULL;
1164
1165     OICFree(savedPlatformInfo.modelNumber);
1166     savedPlatformInfo.modelNumber = NULL;
1167
1168     OICFree(savedPlatformInfo.dateOfManufacture);
1169     savedPlatformInfo.dateOfManufacture = NULL;
1170
1171     OICFree(savedPlatformInfo.platformVersion);
1172     savedPlatformInfo.platformVersion = NULL;
1173
1174     OICFree(savedPlatformInfo.operatingSystemVersion);
1175     savedPlatformInfo.operatingSystemVersion = NULL;
1176
1177     OICFree(savedPlatformInfo.hardwareVersion);
1178     savedPlatformInfo.hardwareVersion = NULL;
1179
1180     OICFree(savedPlatformInfo.firmwareVersion);
1181     savedPlatformInfo.firmwareVersion = NULL;
1182
1183     OICFree(savedPlatformInfo.supportUrl);
1184     savedPlatformInfo.supportUrl = NULL;
1185
1186     OICFree(savedPlatformInfo.systemTime);
1187     savedPlatformInfo.systemTime = NULL;
1188 }
1189
1190 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1191 {
1192     savedPlatformInfo.platformID = OICStrdup(info.platformID);
1193     savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1194     savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1195     savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1196     savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1197     savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1198     savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1199     savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1200     savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1201     savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1202     savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1203
1204     if ((!savedPlatformInfo.platformID && info.platformID)||
1205         (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1206         (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1207         (!savedPlatformInfo.modelNumber && info.modelNumber)||
1208         (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1209         (!savedPlatformInfo.platformVersion && info.platformVersion)||
1210         (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1211         (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1212         (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1213         (!savedPlatformInfo.supportUrl && info.supportUrl)||
1214         (!savedPlatformInfo.systemTime && info.systemTime))
1215     {
1216         DeletePlatformInfo();
1217         return OC_STACK_INVALID_PARAM;
1218     }
1219
1220     return OC_STACK_OK;
1221
1222 }
1223
1224 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1225 {
1226     DeletePlatformInfo();
1227
1228     OCStackResult res = DeepCopyPlatFormInfo(info);
1229
1230     if (res != OC_STACK_OK)
1231     {
1232         OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1233     }
1234     else
1235     {
1236         OIC_LOG(INFO, TAG, "Platform info saved.");
1237     }
1238
1239     return res;
1240 }
1241
1242 void DeleteDeviceInfo()
1243 {
1244     OIC_LOG(INFO, TAG, "Deleting device info.");
1245
1246     OICFree(savedDeviceInfo.deviceName);
1247     OCFreeOCStringLL(savedDeviceInfo.types);
1248     savedDeviceInfo.deviceName = NULL;
1249
1250 }
1251
1252 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1253 {
1254     savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1255
1256     if(!savedDeviceInfo.deviceName && info.deviceName)
1257     {
1258         DeleteDeviceInfo();
1259         return OC_STACK_NO_MEMORY;
1260     }
1261
1262     if (info.types)
1263     {
1264         savedDeviceInfo.types = CloneOCStringLL(info.types);
1265         if(!savedDeviceInfo.types && info.types)
1266         {
1267             DeleteDeviceInfo();
1268             return OC_STACK_NO_MEMORY;
1269         }
1270     }
1271     return OC_STACK_OK;
1272 }
1273
1274 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1275 {
1276     OCStackResult res = OC_STACK_OK;
1277
1278     DeleteDeviceInfo();
1279
1280     res = DeepCopyDeviceInfo(info);
1281
1282     VERIFY_SUCCESS(res, OC_STACK_OK);
1283
1284     if (OCGetServerInstanceIDString() == NULL)
1285     {
1286         OIC_LOG(INFO, TAG, "Device ID generation failed");
1287         res =  OC_STACK_ERROR;
1288         goto exit;
1289     }
1290
1291     OIC_LOG(INFO, TAG, "Device initialized successfully.");
1292     return OC_STACK_OK;
1293
1294 exit:
1295     DeleteDeviceInfo();
1296     return res;
1297 }