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