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