Imported Upstream version 1.0.1
[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     }
309     OCDiscoveryCollectionPayloadAddResource(payload, resourcePtr->tags, resourcePtr->setLinks);
310     return OC_STACK_OK;
311 }
312
313 uint8_t IsCollectionResource (OCResource *resource)
314 {
315     if(!resource)
316     {
317         return 0;
318     }
319
320     for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
321     {
322         if (resource->rsrcResources[i])
323         {
324             return 1;
325         }
326     }
327     return 0;
328 }
329
330 OCResource *FindResourceByUri(const char* resourceUri)
331 {
332     if(!resourceUri)
333     {
334         return NULL;
335     }
336
337     OCResource * pointer = headResource;
338     while (pointer)
339     {
340         if (strcmp(resourceUri, pointer->uri) == 0)
341         {
342             return pointer;
343         }
344         pointer = pointer->next;
345     }
346     OC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
347     return NULL;
348 }
349
350
351 OCStackResult DetermineResourceHandling (const OCServerRequest *request,
352                                          ResourceHandling *handling,
353                                          OCResource **resource)
354 {
355     if(!request || !handling || !resource)
356     {
357         return OC_STACK_INVALID_PARAM;
358     }
359
360     OC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
361
362     // Check if virtual resource
363     if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
364     {
365         OC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
366         *handling = OC_RESOURCE_VIRTUAL;
367         *resource = headResource;
368         return OC_STACK_OK;
369     }
370     if (strlen((const char*)(request->resourceUrl)) == 0)
371     {
372         // Resource URL not specified
373         *handling = OC_RESOURCE_NOT_SPECIFIED;
374         return OC_STACK_NO_RESOURCE;
375     }
376     else
377     {
378         OCResource *resourcePtr = FindResourceByUri((const char*)request->resourceUrl);
379         *resource = resourcePtr;
380         if (!resourcePtr)
381         {
382             if(defaultDeviceHandler)
383             {
384                 *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER;
385                 return OC_STACK_OK;
386             }
387
388             // Resource does not exist
389             // and default device handler does not exist
390             *handling = OC_RESOURCE_NOT_SPECIFIED;
391             return OC_STACK_NO_RESOURCE;
392         }
393
394         if (IsCollectionResource (resourcePtr))
395         {
396             // Collection resource
397             if (resourcePtr->entityHandler != defaultResourceEHandler)
398             {
399                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
400                 return OC_STACK_OK;
401             }
402             else
403             {
404                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
405                 return OC_STACK_OK;
406             }
407         }
408         else
409         {
410             // Resource not a collection
411             if (resourcePtr->entityHandler != defaultResourceEHandler)
412             {
413                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
414                 return OC_STACK_OK;
415             }
416             else
417             {
418                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
419                 return OC_STACK_OK;
420             }
421         }
422     }
423 }
424
425 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
426 {
427     OCStackResult result;
428
429     switch (ehResult)
430     {
431         case OC_EH_OK:
432             result = OC_STACK_OK;
433             break;
434         case OC_EH_SLOW:
435             result = OC_STACK_SLOW_RESOURCE;
436             break;
437         case OC_EH_ERROR:
438             result = OC_STACK_ERROR;
439             break;
440         case OC_EH_FORBIDDEN:
441             result = OC_STACK_RESOURCE_ERROR;
442             break;
443         case OC_EH_RESOURCE_CREATED:
444             result = OC_STACK_RESOURCE_CREATED;
445             break;
446         case OC_EH_RESOURCE_DELETED:
447             result = OC_STACK_RESOURCE_DELETED;
448             break;
449         case OC_EH_RESOURCE_NOT_FOUND:
450             result = OC_STACK_NO_RESOURCE;
451             break;
452         default:
453             result = OC_STACK_ERROR;
454     }
455
456     return result;
457 }
458
459 static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
460 {
461     if (!resource)
462     {
463         return false;
464     }
465
466     // Null or empty is analogous to no filter.
467     if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
468     {
469         return true;
470     }
471
472     OCResourceType *resourceTypePtr = resource->rsrcType;
473
474     while (resourceTypePtr)
475     {
476         if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
477         {
478             return true;
479         }
480         resourceTypePtr = resourceTypePtr->next;
481     }
482
483     OC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
484     return false;
485 }
486
487 static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
488 {
489     if (!resource)
490     {
491         return false;
492     }
493
494     // Null or empty is analogous to no filter.
495     if (interfaceFilter == NULL || *interfaceFilter == 0)
496     {
497         return true;
498     }
499
500     OCResourceInterface *interfacePtr = resource->rsrcInterface;
501
502     while (interfacePtr)
503     {
504         if (strcmp (interfacePtr->name, interfaceFilter) == 0)
505         {
506             return true;
507         }
508         interfacePtr = interfacePtr->next;
509     }
510
511     OC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
512     return false;
513 }
514
515 /*
516  * If the filters are null, they will be assumed to NOT be present
517  * and the resource will not be matched against them.
518  * Function will return true if all non null AND non empty filters passed in find a match.
519  */
520 static bool includeThisResourceInResponse(OCResource *resource,
521                                                  char *interfaceFilter,
522                                                  char *resourceTypeFilter)
523 {
524     if (!resource)
525     {
526         OC_LOG(ERROR, TAG, "Invalid resource");
527         return false;
528     }
529
530     if ( resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
531     {
532         /*
533          * At least one valid filter should be available to
534          * include the resource in discovery response
535          */
536         if (!((interfaceFilter && *interfaceFilter ) ||
537               (resourceTypeFilter && *resourceTypeFilter)))
538         {
539             OC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
540                 resource", resource->uri);
541             return false;
542         }
543     }
544     else if ( !(resource->resourceProperties & OC_ACTIVE) ||
545          !(resource->resourceProperties & OC_DISCOVERABLE))
546     {
547         OC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
548         return false;
549     }
550
551     return resourceMatchesIFFilter(resource, interfaceFilter) &&
552            resourceMatchesRTFilter(resource, resourceTypeFilter);
553
554 }
555
556 OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
557                                 OCPayload *discoveryPayload, OCEntityHandlerResult ehResult)
558 {
559     OCEntityHandlerResponse response = {0};
560
561     response.ehResult = ehResult;
562     response.payload = discoveryPayload;
563     response.persistentBufferFlag = 0;
564     response.requestHandle = (OCRequestHandle) request;
565     response.resourceHandle = (OCResourceHandle) resource;
566
567     return OCDoResponse(&response);
568 }
569
570 #ifdef WITH_RD
571 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
572     OCResourceCollectionPayload **repPayload)
573 {
574     if (OCRDCheckPublishedResource(interfaceType, resourceType, repPayload) == OC_STACK_OK)
575     {
576         return OC_STACK_OK;
577     }
578     else
579     {
580         OC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
581                              on the resource directory");
582     }
583     return OC_STACK_ERROR;
584 }
585 #endif
586
587 static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
588 {
589     if (!request || !resource)
590     {
591         return OC_STACK_INVALID_PARAM;
592     }
593
594     OCStackResult discoveryResult = OC_STACK_ERROR;
595
596     bool bMulticast    = false;     // Was the discovery request a multicast request?
597     OCPayload* payload = NULL;
598
599     OC_LOG(INFO, TAG, "Entering HandleVirtualResource");
600
601     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
602
603     // Step 1: Generate the response to discovery request
604     if (virtualUriInRequest == OC_WELL_KNOWN_URI)
605     {
606         char *filterOne = NULL;
607         char *filterTwo = NULL;
608
609         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
610                 &filterOne, &filterTwo);
611
612         if (discoveryResult == OC_STACK_OK)
613         {
614             payload = (OCPayload*)OCDiscoveryPayloadCreate();
615
616             if(payload)
617             {
618                 ((OCDiscoveryPayload*)payload)->sid = (uint8_t*)OICCalloc(1, UUID_SIZE);
619                 memcpy(((OCDiscoveryPayload*)payload)->sid,
620                     OCGetServerInstanceID(), UUID_SIZE);
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                         discoveryResult = checkResourceExistsAtRD(filterOne, filterTwo, &repPayload);
630                         if (discoveryResult != OC_STACK_OK)
631                         {
632                              break;
633                         }
634                         discoveryResult = BuildVirtualCollectionResourceResponse(repPayload,
635                                     (OCDiscoveryPayload*)payload,
636                                     &request->devAddr);
637                         foundResourceAtRD = true;
638                     }
639 #endif
640                     if(!foundResourceAtRD && includeThisResourceInResponse(resource, filterOne, filterTwo))
641                     {
642                         discoveryResult = BuildVirtualResourceResponse(resource,
643                                 (OCDiscoveryPayload*)payload,
644                                 &request->devAddr);
645                     }
646                 }
647                 // Set discoveryResult appropriately if no 'valid' resources are available
648                 if (((OCDiscoveryPayload*)payload)->resources == NULL && !foundResourceAtRD)
649                 {
650                     discoveryResult = OC_STACK_NO_RESOURCE;
651                 }
652             }
653             else
654             {
655                 discoveryResult = OC_STACK_NO_MEMORY;
656             }
657         }
658         else
659         {
660             OC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
661         }
662     }
663     else if (virtualUriInRequest == OC_DEVICE_URI)
664     {
665         const OicUuid_t* deviceId = OCGetServerInstanceID();
666         if (!deviceId)
667         {
668             discoveryResult = OC_STACK_ERROR;
669         }
670         else
671         {
672             payload = (OCPayload*) OCDevicePayloadCreate((const uint8_t*) &deviceId->id, savedDeviceInfo.deviceName,
673                     OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
674             if (!payload)
675             {
676                 discoveryResult = OC_STACK_NO_MEMORY;
677             }
678             else
679             {
680                 discoveryResult = OC_STACK_OK;
681             }
682         }
683     }
684     else if (virtualUriInRequest == OC_PLATFORM_URI)
685     {
686         payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
687         if (!payload)
688         {
689             discoveryResult = OC_STACK_NO_MEMORY;
690         }
691         else
692         {
693             discoveryResult = OC_STACK_OK;
694         }
695     }
696 #ifdef ROUTING_GATEWAY
697     else if (OC_GATEWAY_URI == virtualUriInRequest)
698     {
699         // Received request for a gateway
700         OC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
701         discoveryResult = RMHandleGatewayRequest(request, resource);
702
703     }
704 #endif
705
706     /**
707      * Step 2: Send the discovery response
708      *
709      * Iotivity should respond to discovery requests in below manner:
710      * 1)If query filter matching fails and discovery request is multicast,
711      *   it should NOT send any response.
712      * 2)If query filter matching fails and discovery request is unicast,
713      *   it should send an error(RESOURCE_NOT_FOUND - 404) response.
714      * 3)If Server does not have any 'DISCOVERABLE' resources and discovery
715      *   request is multicast, it should NOT send any response.
716      * 4)If Server does not have any 'DISCOVERABLE' resources and discovery
717      *   request is unicast, it should send an error(RESOURCE_NOT_FOUND - 404) response.
718      */
719
720 #ifdef WITH_PRESENCE
721     if ((virtualUriInRequest == OC_PRESENCE) &&
722         (resource->resourceProperties & OC_ACTIVE))
723     {
724         // Presence uses observer notification api to respond via SendPresenceNotification.
725         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
726     }
727     else
728     #endif
729 #ifdef ROUTING_GATEWAY
730     // Gateway uses the RMHandleGatewayRequest to respond to the request.
731     if (OC_GATEWAY != virtualUriInRequest)
732 #endif
733     {
734         if(discoveryResult == OC_STACK_OK)
735         {
736             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
737         }
738         else if(bMulticast == false)
739         {
740             OC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d)  \
741                 discovery request", discoveryResult, virtualUriInRequest);
742             SendNonPersistantDiscoveryResponse(request, resource, NULL,
743                 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
744         }
745         else
746         {
747             // Ignoring the discovery request as per RFC 7252, Section #8.2
748             OC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
749                 any useful data to send");
750         }
751     }
752
753     OCPayloadDestroy(payload);
754
755     return OC_STACK_OK;
756 }
757
758 static OCStackResult
759 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
760 {
761     if(!request)
762     {
763         return OC_STACK_INVALID_PARAM;
764     }
765
766     OCStackResult result = OC_STACK_OK;
767     OCEntityHandlerResult ehResult = OC_EH_ERROR;
768     OCEntityHandlerRequest ehRequest = {0};
769
770     OC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
771     result = FormOCEntityHandlerRequest(&ehRequest,
772                                         (OCRequestHandle) request,
773                                         request->method,
774                                         &request->devAddr,
775                                         (OCResourceHandle) NULL, request->query,
776                                         PAYLOAD_TYPE_REPRESENTATION,
777                                         request->payload,
778                                         request->payloadSize,
779                                         request->numRcvdVendorSpecificHeaderOptions,
780                                         request->rcvdVendorSpecificHeaderOptions,
781                                         (OCObserveAction)request->observationOption,
782                                         (OCObservationId)0);
783     VERIFY_SUCCESS(result, OC_STACK_OK);
784
785     // At this point we know for sure that defaultDeviceHandler exists
786     ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest,
787                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
788     if(ehResult == OC_EH_SLOW)
789     {
790         OC_LOG(INFO, TAG, "This is a slow resource");
791         request->slowFlag = 1;
792     }
793     else if(ehResult == OC_EH_ERROR)
794     {
795         FindAndDeleteServerRequest(request);
796     }
797     result = EntityHandlerCodeToOCStackCode(ehResult);
798 exit:
799     OCPayloadDestroy(ehRequest.payload);
800     return result;
801 }
802
803 static OCStackResult
804 HandleResourceWithEntityHandler (OCServerRequest *request,
805                                  OCResource *resource,
806                                  uint8_t collectionResource)
807 {
808     if(!request || ! resource)
809     {
810         return OC_STACK_INVALID_PARAM;
811     }
812
813     OCStackResult result = OC_STACK_ERROR;
814     OCEntityHandlerResult ehResult = OC_EH_ERROR;
815     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
816     ResourceObserver *resObs = NULL;
817
818     OCEntityHandlerRequest ehRequest = {0};
819
820     OC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
821     OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
822     // check the security resource
823     if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
824     {
825         type = PAYLOAD_TYPE_SECURITY;
826
827     }
828
829     if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
830     {
831         type = PAYLOAD_TYPE_RD;
832     }
833
834     result = FormOCEntityHandlerRequest(&ehRequest,
835                                         (OCRequestHandle)request,
836                                         request->method,
837                                         &request->devAddr,
838                                         (OCResourceHandle)resource,
839                                         request->query,
840                                         type,
841                                         request->payload,
842                                         request->payloadSize,
843                                         request->numRcvdVendorSpecificHeaderOptions,
844                                         request->rcvdVendorSpecificHeaderOptions,
845                                         (OCObserveAction)request->observationOption,
846                                         0);
847     VERIFY_SUCCESS(result, OC_STACK_OK);
848
849     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
850     {
851         OC_LOG(INFO, TAG, "No observation requested");
852         ehFlag = OC_REQUEST_FLAG;
853     }
854     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
855     {
856         OC_LOG(INFO, TAG, "Observation registration requested");
857
858         ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
859                                     request->tokenLength);
860
861         if (obs)
862         {
863             OC_LOG (INFO, TAG, "Observer with this token already present");
864             OC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
865             OC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
866             OC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
867
868             // server requests are usually free'd when the response is sent out
869             // for the request in ocserverrequest.c : HandleSingleResponse()
870             // Since we are making an early return and not responding, the server request
871             // needs to be deleted.
872             FindAndDeleteServerRequest (request);
873             return OC_STACK_OK;
874         }
875
876         result = GenerateObserverId(&ehRequest.obsInfo.obsId);
877         VERIFY_SUCCESS(result, OC_STACK_OK);
878
879         result = AddObserver ((const char*)(request->resourceUrl),
880                 (const char *)(request->query),
881                 ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
882                 resource, request->qos, request->acceptFormat,
883                 &request->devAddr);
884
885         if(result == OC_STACK_OK)
886         {
887             OC_LOG(INFO, TAG, "Added observer successfully");
888             request->observeResult = OC_STACK_OK;
889             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
890         }
891         else
892         {
893             result = OC_STACK_OK;
894
895             // The error in observeResult for the request will be used when responding to this
896             // request by omitting the observation option/sequence number.
897             request->observeResult = OC_STACK_ERROR;
898             OC_LOG(ERROR, TAG, "Observer Addition failed");
899             ehFlag = OC_REQUEST_FLAG;
900         }
901
902     }
903     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
904             !collectionResource)
905     {
906         OC_LOG(INFO, TAG, "Deregistering observation requested");
907
908         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
909
910         if (NULL == resObs)
911         {
912             // Stack does not contain this observation request
913             // Either token is incorrect or observation list is corrupted
914             result = OC_STACK_ERROR;
915             goto exit;
916         }
917         ehRequest.obsInfo.obsId = resObs->observeId;
918         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
919
920         result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
921
922         if(result == OC_STACK_OK)
923         {
924             OC_LOG(INFO, TAG, "Removed observer successfully");
925             request->observeResult = OC_STACK_OK;
926         }
927         else
928         {
929             result = OC_STACK_OK;
930             request->observeResult = OC_STACK_ERROR;
931             OC_LOG(ERROR, TAG, "Observer Removal failed");
932         }
933     }
934     else
935     {
936         result = OC_STACK_ERROR;
937         goto exit;
938     }
939
940     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
941     if(ehResult == OC_EH_SLOW)
942     {
943         OC_LOG(INFO, TAG, "This is a slow resource");
944         request->slowFlag = 1;
945     }
946     else if(ehResult == OC_EH_ERROR)
947     {
948         FindAndDeleteServerRequest(request);
949     }
950     result = EntityHandlerCodeToOCStackCode(ehResult);
951 exit:
952     OCPayloadDestroy(ehRequest.payload);
953     return result;
954 }
955
956 static OCStackResult
957 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
958                                               OCResource *resource)
959 {
960     if(!request || !resource)
961     {
962         return OC_STACK_INVALID_PARAM;
963     }
964
965     OCStackResult result = OC_STACK_ERROR;
966     OCEntityHandlerRequest ehRequest = {0};
967
968     result = FormOCEntityHandlerRequest(&ehRequest,
969                                         (OCRequestHandle)request,
970                                         request->method,
971                                         &request->devAddr,
972                                         (OCResourceHandle)resource,
973                                         request->query,
974                                         PAYLOAD_TYPE_REPRESENTATION,
975                                         request->payload,
976                                         request->payloadSize,
977                                         request->numRcvdVendorSpecificHeaderOptions,
978                                         request->rcvdVendorSpecificHeaderOptions,
979                                         (OCObserveAction)request->observationOption,
980                                         (OCObservationId)0);
981     if(result == OC_STACK_OK)
982     {
983         result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
984     }
985
986     OCPayloadDestroy(ehRequest.payload);
987     return result;
988 }
989
990 OCStackResult
991 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request)
992 {
993     OCStackResult ret = OC_STACK_OK;
994
995     switch (resHandling)
996     {
997         case OC_RESOURCE_VIRTUAL:
998         {
999             ret = HandleVirtualResource (request, resource);
1000             break;
1001         }
1002         case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER:
1003         {
1004             ret = HandleDefaultDeviceEntityHandler(request);
1005             break;
1006         }
1007         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
1008         {
1009             OC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
1010             return OC_STACK_ERROR;
1011         }
1012         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
1013         {
1014             ret = HandleResourceWithEntityHandler (request, resource, 0);
1015             break;
1016         }
1017         case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER:
1018         {
1019             ret = HandleResourceWithEntityHandler (request, resource, 1);
1020             break;
1021         }
1022         case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER:
1023         {
1024             ret = HandleCollectionResourceDefaultEntityHandler (request, resource);
1025             break;
1026         }
1027         case OC_RESOURCE_NOT_SPECIFIED:
1028         {
1029             ret = OC_STACK_NO_RESOURCE;
1030             break;
1031         }
1032         default:
1033         {
1034             OC_LOG(INFO, TAG, "Invalid Resource Determination");
1035             return OC_STACK_ERROR;
1036         }
1037     }
1038     return ret;
1039 }
1040
1041 void DeletePlatformInfo()
1042 {
1043     OC_LOG(INFO, TAG, "Deleting platform info.");
1044
1045     OICFree(savedPlatformInfo.platformID);
1046     savedPlatformInfo.platformID = NULL;
1047
1048     OICFree(savedPlatformInfo.manufacturerName);
1049     savedPlatformInfo.manufacturerName = NULL;
1050
1051     OICFree(savedPlatformInfo.manufacturerUrl);
1052     savedPlatformInfo.manufacturerUrl = NULL;
1053
1054     OICFree(savedPlatformInfo.modelNumber);
1055     savedPlatformInfo.modelNumber = NULL;
1056
1057     OICFree(savedPlatformInfo.dateOfManufacture);
1058     savedPlatformInfo.dateOfManufacture = NULL;
1059
1060     OICFree(savedPlatformInfo.platformVersion);
1061     savedPlatformInfo.platformVersion = NULL;
1062
1063     OICFree(savedPlatformInfo.operatingSystemVersion);
1064     savedPlatformInfo.operatingSystemVersion = NULL;
1065
1066     OICFree(savedPlatformInfo.hardwareVersion);
1067     savedPlatformInfo.hardwareVersion = NULL;
1068
1069     OICFree(savedPlatformInfo.firmwareVersion);
1070     savedPlatformInfo.firmwareVersion = NULL;
1071
1072     OICFree(savedPlatformInfo.supportUrl);
1073     savedPlatformInfo.supportUrl = NULL;
1074
1075     OICFree(savedPlatformInfo.systemTime);
1076     savedPlatformInfo.systemTime = NULL;
1077 }
1078
1079 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
1080 {
1081     savedPlatformInfo.platformID = OICStrdup(info.platformID);
1082     savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
1083     savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
1084     savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
1085     savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
1086     savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
1087     savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
1088     savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
1089     savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
1090     savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
1091     savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
1092
1093     if ((!savedPlatformInfo.platformID && info.platformID)||
1094         (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
1095         (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
1096         (!savedPlatformInfo.modelNumber && info.modelNumber)||
1097         (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
1098         (!savedPlatformInfo.platformVersion && info.platformVersion)||
1099         (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
1100         (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
1101         (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
1102         (!savedPlatformInfo.supportUrl && info.supportUrl)||
1103         (!savedPlatformInfo.systemTime && info.systemTime))
1104     {
1105         DeletePlatformInfo();
1106         return OC_STACK_INVALID_PARAM;
1107     }
1108
1109     return OC_STACK_OK;
1110
1111 }
1112
1113 OCStackResult SavePlatformInfo(OCPlatformInfo info)
1114 {
1115     DeletePlatformInfo();
1116
1117     OCStackResult res = DeepCopyPlatFormInfo(info);
1118
1119     if (res != OC_STACK_OK)
1120     {
1121         OC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
1122     }
1123     else
1124     {
1125         OC_LOG(INFO, TAG, "Platform info saved.");
1126     }
1127
1128     return res;
1129 }
1130
1131 void DeleteDeviceInfo()
1132 {
1133     OC_LOG(INFO, TAG, "Deleting device info.");
1134
1135     OICFree(savedDeviceInfo.deviceName);
1136     savedDeviceInfo.deviceName = NULL;
1137 }
1138
1139 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
1140 {
1141     savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
1142
1143     if(!savedDeviceInfo.deviceName && info.deviceName)
1144     {
1145         DeleteDeviceInfo();
1146         return OC_STACK_NO_MEMORY;
1147     }
1148
1149     return OC_STACK_OK;
1150 }
1151
1152 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
1153 {
1154     OCStackResult res = OC_STACK_OK;
1155
1156     DeleteDeviceInfo();
1157
1158     res = DeepCopyDeviceInfo(info);
1159
1160     VERIFY_SUCCESS(res, OC_STACK_OK);
1161
1162     if(OCGetServerInstanceID() == NULL)
1163     {
1164         OC_LOG(INFO, TAG, "Device ID generation failed");
1165         res =  OC_STACK_ERROR;
1166         goto exit;
1167     }
1168
1169     OC_LOG(INFO, TAG, "Device initialized successfully.");
1170     return OC_STACK_OK;
1171
1172 exit:
1173     DeleteDeviceInfo();
1174     return res;
1175 }