Imported Upstream version 1.1.0
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocobserve.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 #include <string.h>
22 #include "ocstack.h"
23 #include "ocstackconfig.h"
24 #include "ocstackinternal.h"
25 #include "ocobserve.h"
26 #include "ocresourcehandler.h"
27 #include "ocrandom.h"
28 #include "oic_malloc.h"
29 #include "oic_string.h"
30 #include "ocpayload.h"
31 #include "ocserverrequest.h"
32 #include "logger.h"
33
34 #include "utlist.h"
35 #include "pdu.h"
36
37
38 // Module Name
39 #define MOD_NAME "ocobserve"
40
41 #define TAG  "OIC_RI_OBSERVE"
42
43 #define VERIFY_NON_NULL(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
44
45 static struct ResourceObserver * g_serverObsList = NULL;
46 /**
47  * Determine observe QOS based on the QOS of the request.
48  * The qos passed as a parameter overrides what the client requested.
49  * If we want the client preference taking high priority make:
50  *     qos = resourceObserver->qos;
51  *
52  * @param method RESTful method.
53  * @param resourceObserver Observer.
54  * @param appQoS Quality of service.
55  * @return The quality of service of the observer.
56  */
57 static OCQualityOfService DetermineObserverQoS(OCMethod method,
58         ResourceObserver * resourceObserver, OCQualityOfService appQoS)
59 {
60     if (!resourceObserver)
61     {
62         OIC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
63         return OC_NA_QOS;
64     }
65
66     OCQualityOfService decidedQoS = appQoS;
67     if (appQoS == OC_NA_QOS)
68     {
69         decidedQoS = resourceObserver->qos;
70     }
71
72     if (appQoS != OC_HIGH_QOS)
73     {
74         OIC_LOG_V(INFO, TAG, "Current NON count for this observer is %d",
75                 resourceObserver->lowQosCount);
76 #ifdef WITH_PRESENCE
77         if ((resourceObserver->forceHighQos \
78                 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT) \
79                 && method != OC_REST_PRESENCE)
80 #else
81         if (resourceObserver->forceHighQos \
82                 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
83 #endif
84         {
85             resourceObserver->lowQosCount = 0;
86             // at some point we have to to send CON to check on the
87             // availability of observer
88             OIC_LOG(INFO, TAG, "This time we are sending the  notification as High qos");
89             decidedQoS = OC_HIGH_QOS;
90         }
91         else
92         {
93             (resourceObserver->lowQosCount)++;
94         }
95     }
96     return decidedQoS;
97 }
98
99 #ifdef WITH_PRESENCE
100 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
101         OCPresenceTrigger trigger, OCResourceType *resourceType, OCQualityOfService qos)
102 #else
103 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
104         OCQualityOfService qos)
105 #endif
106 {
107     OIC_LOG(INFO, TAG, "Entering SendObserverNotification");
108     if (!resPtr)
109     {
110         return OC_STACK_INVALID_PARAM;
111     }
112
113     OCStackResult result = OC_STACK_ERROR;
114     ResourceObserver * resourceObserver = g_serverObsList;
115     uint8_t numObs = 0;
116     OCServerRequest * request = NULL;
117     OCEntityHandlerRequest ehRequest = {0};
118     OCEntityHandlerResult ehResult = OC_EH_ERROR;
119     bool observeErrorFlag = false;
120
121     // Find clients that are observing this resource
122     while (resourceObserver)
123     {
124         if (resourceObserver->resource == resPtr)
125         {
126             numObs++;
127 #ifdef WITH_PRESENCE
128             if (method != OC_REST_PRESENCE)
129             {
130 #endif
131                 qos = DetermineObserverQoS(method, resourceObserver, qos);
132
133                 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
134                         0, resPtr->sequenceNum, qos, resourceObserver->query,
135                         NULL, NULL,
136                         resourceObserver->token, resourceObserver->tokenLength,
137                         resourceObserver->resUri, 0, resourceObserver->acceptFormat,
138                         &resourceObserver->devAddr);
139
140                 if (request)
141                 {
142                     request->observeResult = OC_STACK_OK;
143                     if (result == OC_STACK_OK)
144                     {
145                         result = FormOCEntityHandlerRequest(
146                                     &ehRequest,
147                                     (OCRequestHandle) request,
148                                     request->method,
149                                     &request->devAddr,
150                                     (OCResourceHandle) resPtr,
151                                     request->query,
152                                     PAYLOAD_TYPE_REPRESENTATION,
153                                     request->payload,
154                                     request->payloadSize,
155                                     request->numRcvdVendorSpecificHeaderOptions,
156                                     request->rcvdVendorSpecificHeaderOptions,
157                                     OC_OBSERVE_NO_OPTION,
158                                     0);
159                         if (result == OC_STACK_OK)
160                         {
161                             ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest,
162                                                 resPtr->entityHandlerCallbackParam);
163                             if (ehResult == OC_EH_ERROR)
164                             {
165                                 FindAndDeleteServerRequest(request);
166                             }
167                         }
168                         OCPayloadDestroy(ehRequest.payload);
169                     }
170                 }
171 #ifdef WITH_PRESENCE
172             }
173             else
174             {
175                 OCEntityHandlerResponse ehResponse = {0};
176
177                 //This is effectively the implementation for the presence entity handler.
178                 OIC_LOG(DEBUG, TAG, "This notification is for Presence");
179                 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
180                         0, resPtr->sequenceNum, qos, resourceObserver->query,
181                         NULL, NULL,
182                         resourceObserver->token, resourceObserver->tokenLength,
183                         resourceObserver->resUri, 0, resourceObserver->acceptFormat,
184                         &resourceObserver->devAddr);
185
186                 if (result == OC_STACK_OK)
187                 {
188                     OCPresencePayload* presenceResBuf = OCPresencePayloadCreate(
189                             resPtr->sequenceNum, maxAge, trigger,
190                             resourceType ? resourceType->resourcetypename : NULL);
191
192                     if (!presenceResBuf)
193                     {
194                         return OC_STACK_NO_MEMORY;
195                     }
196
197                     if (result == OC_STACK_OK)
198                     {
199                         ehResponse.ehResult = OC_EH_OK;
200                         ehResponse.payload = (OCPayload*)presenceResBuf;
201                         ehResponse.persistentBufferFlag = 0;
202                         ehResponse.requestHandle = (OCRequestHandle) request;
203                         ehResponse.resourceHandle = (OCResourceHandle) resPtr;
204                         OICStrcpy(ehResponse.resourceUri, sizeof(ehResponse.resourceUri),
205                                 resourceObserver->resUri);
206                         result = OCDoResponse(&ehResponse);
207                     }
208
209                     OCPresencePayloadDestroy(presenceResBuf);
210                 }
211             }
212 #endif
213
214             // Since we are in a loop, set an error flag to indicate at least one error occurred.
215             if (result != OC_STACK_OK)
216             {
217                 observeErrorFlag = true;
218             }
219         }
220         resourceObserver = resourceObserver->next;
221     }
222
223     if (numObs == 0)
224     {
225         OIC_LOG(INFO, TAG, "Resource has no observers");
226         result = OC_STACK_NO_OBSERVERS;
227     }
228     else if (observeErrorFlag)
229     {
230         OIC_LOG(ERROR, TAG, "Observer notification error");
231         result = OC_STACK_ERROR;
232     }
233     return result;
234 }
235
236 OCStackResult SendListObserverNotification (OCResource * resource,
237         OCObservationId  *obsIdList, uint8_t numberOfIds,
238         const OCRepPayload *payload,
239         uint32_t maxAge,
240         OCQualityOfService qos)
241 {
242     (void)maxAge;
243     if (!resource || !obsIdList || !payload)
244     {
245         return OC_STACK_INVALID_PARAM;
246     }
247
248     uint8_t numIds = numberOfIds;
249     ResourceObserver *observer = NULL;
250     uint8_t numSentNotification = 0;
251     OCServerRequest * request = NULL;
252     OCStackResult result = OC_STACK_ERROR;
253     bool observeErrorFlag = false;
254
255     OIC_LOG(INFO, TAG, "Entering SendListObserverNotification");
256     while(numIds)
257     {
258         observer = GetObserverUsingId (*obsIdList);
259         if (observer)
260         {
261             // Found observer - verify if it matches the resource handle
262             if (observer->resource == resource)
263             {
264                 qos = DetermineObserverQoS(OC_REST_GET, observer, qos);
265
266
267                 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
268                         0, resource->sequenceNum, qos, observer->query,
269                         NULL, NULL, observer->token, observer->tokenLength,
270                         observer->resUri, 0, observer->acceptFormat,
271                         &observer->devAddr);
272
273                 if (request)
274                 {
275                     request->observeResult = OC_STACK_OK;
276                     if (result == OC_STACK_OK)
277                     {
278                         OCEntityHandlerResponse ehResponse = {0};
279                         ehResponse.ehResult = OC_EH_OK;
280                         ehResponse.payload = (OCPayload*)OCRepPayloadCreate();
281                         if (!ehResponse.payload)
282                         {
283                             FindAndDeleteServerRequest(request);
284                             continue;
285                         }
286                         memcpy(ehResponse.payload, payload, sizeof(*payload));
287                         ehResponse.persistentBufferFlag = 0;
288                         ehResponse.requestHandle = (OCRequestHandle) request;
289                         ehResponse.resourceHandle = (OCResourceHandle) resource;
290                         result = OCDoResponse(&ehResponse);
291                         if (result == OC_STACK_OK)
292                         {
293                             OIC_LOG_V(INFO, TAG, "Observer id %d notified.", *obsIdList);
294
295                             // Increment only if OCDoResponse is successful
296                             numSentNotification++;
297
298                             OICFree(ehResponse.payload);
299                             FindAndDeleteServerRequest(request);
300                         }
301                         else
302                         {
303                             OIC_LOG_V(INFO, TAG, "Error notifying observer id %d.", *obsIdList);
304                         }
305                     }
306                     else
307                     {
308                         FindAndDeleteServerRequest(request);
309                     }
310                 }
311                 // Since we are in a loop, set an error flag to indicate
312                 // at least one error occurred.
313                 if (result != OC_STACK_OK)
314                 {
315                     observeErrorFlag = true;
316                 }
317             }
318         }
319         obsIdList++;
320         numIds--;
321     }
322
323     if (numSentNotification == numberOfIds && !observeErrorFlag)
324     {
325         return OC_STACK_OK;
326     }
327     else if (numSentNotification == 0)
328     {
329         return OC_STACK_NO_OBSERVERS;
330     }
331     else
332     {
333         OIC_LOG(ERROR, TAG, "Observer notification error");
334         return OC_STACK_ERROR;
335     }
336 }
337
338 OCStackResult GenerateObserverId (OCObservationId *observationId)
339 {
340     ResourceObserver *resObs = NULL;
341
342     OIC_LOG(INFO, TAG, "Entering GenerateObserverId");
343     VERIFY_NON_NULL (observationId);
344
345     do
346     {
347         *observationId = OCGetRandomByte();
348         // Check if observation Id already exists
349         resObs = GetObserverUsingId (*observationId);
350     } while (NULL != resObs);
351
352     OIC_LOG_V(INFO, TAG, "GeneratedObservation ID is %u", *observationId);
353
354     return OC_STACK_OK;
355 exit:
356     return OC_STACK_ERROR;
357 }
358
359 OCStackResult AddObserver (const char         *resUri,
360                            const char         *query,
361                            OCObservationId    obsId,
362                            CAToken_t          token,
363                            uint8_t            tokenLength,
364                            OCResource         *resHandle,
365                            OCQualityOfService qos,
366                            OCPayloadFormat    acceptFormat,
367                            const OCDevAddr    *devAddr)
368 {
369     // Check if resource exists and is observable.
370     if (!resHandle)
371     {
372         return OC_STACK_INVALID_PARAM;
373     }
374     if (!(resHandle->resourceProperties & OC_OBSERVABLE))
375     {
376         return OC_STACK_RESOURCE_ERROR;
377     }
378
379     if (!resUri || !token || !*token)
380     {
381         return OC_STACK_INVALID_PARAM;
382     }
383
384     ResourceObserver *obsNode = (ResourceObserver *) OICCalloc(1, sizeof(ResourceObserver));
385     if (obsNode)
386     {
387         obsNode->observeId = obsId;
388
389         obsNode->resUri = OICStrdup(resUri);
390         VERIFY_NON_NULL (obsNode->resUri);
391
392         obsNode->qos = qos;
393         obsNode->acceptFormat = acceptFormat;
394         if (query)
395         {
396             obsNode->query = OICStrdup(query);
397             VERIFY_NON_NULL (obsNode->query);
398         }
399         // If tokenLength is zero, the return value depends on the
400         // particular library implementation (it may or may not be a null pointer).
401         if (tokenLength)
402         {
403             obsNode->token = (CAToken_t)OICMalloc(tokenLength);
404             VERIFY_NON_NULL (obsNode->token);
405             memcpy(obsNode->token, token, tokenLength);
406         }
407         obsNode->tokenLength = tokenLength;
408
409         obsNode->devAddr = *devAddr;
410         obsNode->resource = resHandle;
411
412         LL_APPEND (g_serverObsList, obsNode);
413
414         return OC_STACK_OK;
415     }
416
417 exit:
418     if (obsNode)
419     {
420         OICFree(obsNode->resUri);
421         OICFree(obsNode->query);
422         OICFree(obsNode);
423     }
424     return OC_STACK_NO_MEMORY;
425 }
426
427 ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
428 {
429     ResourceObserver *out = NULL;
430
431     if (observeId)
432     {
433         LL_FOREACH (g_serverObsList, out)
434         {
435             if (out->observeId == observeId)
436             {
437                 return out;
438             }
439         }
440     }
441     OIC_LOG(INFO, TAG, "Observer node not found!!");
442     return NULL;
443 }
444
445 ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLength)
446 {
447     ResourceObserver *out = NULL;
448
449     if (token && *token)
450     {
451         OIC_LOG(INFO, TAG, "Looking for token");
452         OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
453         OIC_LOG(INFO, TAG, "\tFound token:");
454
455         LL_FOREACH (g_serverObsList, out)
456         {
457             OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
458             if ((memcmp(out->token, token, tokenLength) == 0))
459             {
460                 return out;
461             }
462         }
463     }
464     else
465     {
466         OIC_LOG(ERROR, TAG, "Passed in NULL token");
467     }
468
469     OIC_LOG(INFO, TAG, "Observer node not found!!");
470     return NULL;
471 }
472
473 OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
474 {
475     if (!token || !*token)
476     {
477         return OC_STACK_INVALID_PARAM;
478     }
479
480     ResourceObserver *obsNode = GetObserverUsingToken (token, tokenLength);
481     if (obsNode)
482     {
483         OIC_LOG_V(INFO, TAG, "deleting observer id  %u with token", obsNode->observeId);
484         OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
485         LL_DELETE (g_serverObsList, obsNode);
486         OICFree(obsNode->resUri);
487         OICFree(obsNode->query);
488         OICFree(obsNode->token);
489         OICFree(obsNode);
490     }
491     // it is ok if we did not find the observer...
492     return OC_STACK_OK;
493 }
494
495 void DeleteObserverList()
496 {
497     ResourceObserver *out = NULL;
498     ResourceObserver *tmp = NULL;
499     LL_FOREACH_SAFE (g_serverObsList, out, tmp)
500     {
501         if (out)
502         {
503             DeleteObserverUsingToken ((out->token), out->tokenLength);
504         }
505     }
506     g_serverObsList = NULL;
507 }
508
509 /*
510  * CA layer expects observe registration/de-reg/notiifcations to be passed as a header
511  * option, which breaks the protocol abstraction requirement between RI & CA, and
512  * has to be fixed in the future. The function below adds the header option for observe.
513  * It should be noted that the observe header option is assumed to be the first option
514  * in the list of user defined header options and hence it is inserted at the front
515  * of the header options list and number of options adjusted accordingly.
516  */
517 OCStackResult
518 CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
519                            OCHeaderOption *ocHdrOpt,
520                            uint8_t numOptions,
521                            uint8_t observeFlag)
522 {
523     if (!caHdrOpt)
524     {
525         return OC_STACK_INVALID_PARAM;
526     }
527
528     if (numOptions > 0 && !ocHdrOpt)
529     {
530         OIC_LOG (INFO, TAG, "options are NULL though number is non zero");
531         return OC_STACK_INVALID_PARAM;
532     }
533
534     CAHeaderOption_t *tmpHdrOpt = NULL;
535
536     tmpHdrOpt = (CAHeaderOption_t *) OICCalloc ((numOptions+1), sizeof(CAHeaderOption_t));
537     if (NULL == tmpHdrOpt)
538     {
539         return OC_STACK_NO_MEMORY;
540     }
541     tmpHdrOpt[0].protocolID = CA_COAP_ID;
542     tmpHdrOpt[0].optionID = COAP_OPTION_OBSERVE;
543     tmpHdrOpt[0].optionLength = sizeof(uint8_t);
544     tmpHdrOpt[0].optionData[0] = observeFlag;
545     for (uint8_t i = 0; i < numOptions; i++)
546     {
547         memcpy (&(tmpHdrOpt[i+1]), &(ocHdrOpt[i]), sizeof(CAHeaderOption_t));
548     }
549
550     *caHdrOpt = tmpHdrOpt;
551     return OC_STACK_OK;
552 }
553
554 /*
555  * CA layer passes observe information to the RI layer as a header option, which
556  * breaks the protocol abstraction requirement between RI & CA, and has to be fixed
557  * in the future. The function below removes the observe header option and processes it.
558  * It should be noted that the observe header option is always assumed to be the first
559  * option in the list of user defined header options and hence it is deleted from the
560  * front of the header options list and the number of options is adjusted accordingly.
561  */
562 OCStackResult
563 GetObserveHeaderOption (uint32_t * observationOption,
564                         CAHeaderOption_t *options,
565                         uint8_t * numOptions)
566 {
567     if (!observationOption)
568     {
569         return OC_STACK_INVALID_PARAM;
570     }
571
572     if (!options || !numOptions)
573     {
574         OIC_LOG (INFO, TAG, "No options present");
575         return OC_STACK_OK;
576     }
577
578     for(uint8_t i = 0; i < *numOptions; i++)
579     {
580         if (options[i].protocolID == CA_COAP_ID &&
581                 options[i].optionID == COAP_OPTION_OBSERVE)
582         {
583             *observationOption = options[i].optionData[0];
584             for(uint8_t c = i; c < *numOptions-1; c++)
585             {
586                 options[i] = options[i+1];
587             }
588             (*numOptions)--;
589             return OC_STACK_OK;
590         }
591     }
592     return OC_STACK_OK;
593 }
594