bbd3370f69255a2c0c35d33ffd6b45fdc35a9555
[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 "ocobserve"
39
40 #define TAG  "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, "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, "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, resourceObserver->acceptFormat,
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, "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, resourceObserver->acceptFormat,
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, "Resource has no observers");
224         result = OC_STACK_NO_OBSERVERS;
225     }
226     else if (observeErrorFlag)
227     {
228         OC_LOG(ERROR, TAG, "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, "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, observer->acceptFormat,
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, "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, "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, "GeneratedObservation 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                            OCPayloadFormat    acceptFormat,
365                            const OCDevAddr    *devAddr)
366 {
367     // Check if resource exists and is observable.
368     if (!resHandle)
369     {
370         return OC_STACK_INVALID_PARAM;
371     }
372     if (!(resHandle->resourceProperties & OC_OBSERVABLE))
373     {
374         return OC_STACK_RESOURCE_ERROR;
375     }
376     ResourceObserver *obsNode = NULL;
377
378     if(!resUri || !token || !*token)
379     {
380         return OC_STACK_INVALID_PARAM;
381     }
382
383     obsNode = (ResourceObserver *) OICCalloc(1, sizeof(ResourceObserver));
384     if (obsNode)
385     {
386         obsNode->observeId = obsId;
387
388         obsNode->resUri = OICStrdup(resUri);
389         VERIFY_NON_NULL (obsNode->resUri);
390
391         obsNode->qos = qos;
392         obsNode->acceptFormat = acceptFormat;
393         if(query)
394         {
395             obsNode->query = OICStrdup(query);
396             VERIFY_NON_NULL (obsNode->query);
397         }
398         // If tokenLength is zero, the return value depends on the
399         // particular library implementation (it may or may not be a null pointer).
400         if(tokenLength)
401         {
402             obsNode->token = (CAToken_t)OICMalloc(tokenLength);
403             VERIFY_NON_NULL (obsNode->token);
404             memcpy(obsNode->token, token, tokenLength);
405         }
406         obsNode->tokenLength = tokenLength;
407
408         obsNode->devAddr = *devAddr;
409         obsNode->resource = resHandle;
410
411         LL_APPEND (serverObsList, obsNode);
412
413         return OC_STACK_OK;
414     }
415
416 exit:
417     if (obsNode)
418     {
419         OICFree(obsNode->resUri);
420         OICFree(obsNode->query);
421         OICFree(obsNode);
422     }
423     return OC_STACK_NO_MEMORY;
424 }
425
426 ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
427 {
428     ResourceObserver *out = NULL;
429
430     if (observeId)
431     {
432         LL_FOREACH (serverObsList, out)
433         {
434             if (out->observeId == observeId)
435             {
436                 return out;
437             }
438         }
439     }
440     OC_LOG(INFO, TAG, "Observer node not found!!");
441     return NULL;
442 }
443
444 ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLength)
445 {
446     ResourceObserver *out = NULL;
447
448     if(token && *token)
449     {
450         OC_LOG(INFO, TAG, "Looking for token");
451         OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
452         OC_LOG(INFO, TAG, "\tFound token:");
453
454         LL_FOREACH (serverObsList, out)
455         {
456             OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
457             if((memcmp(out->token, token, tokenLength) == 0))
458             {
459                 return out;
460             }
461         }
462     }
463     else
464     {
465         OC_LOG(ERROR, TAG, "Passed in NULL token");
466     }
467
468     OC_LOG(INFO, TAG, "Observer node not found!!");
469     return NULL;
470 }
471
472 OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
473 {
474     if(!token || !*token)
475     {
476         return OC_STACK_INVALID_PARAM;
477     }
478
479     ResourceObserver *obsNode = NULL;
480
481     obsNode = GetObserverUsingToken (token, tokenLength);
482     if (obsNode)
483     {
484         OC_LOG_V(INFO, TAG, "deleting observer id  %u with token", obsNode->observeId);
485         OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
486         LL_DELETE (serverObsList, obsNode);
487         OICFree(obsNode->resUri);
488         OICFree(obsNode->query);
489         OICFree(obsNode->token);
490         OICFree(obsNode);
491     }
492     // it is ok if we did not find the observer...
493     return OC_STACK_OK;
494 }
495
496 void DeleteObserverList()
497 {
498     ResourceObserver *out = NULL;
499     ResourceObserver *tmp = NULL;
500     LL_FOREACH_SAFE (serverObsList, out, tmp)
501     {
502         if(out)
503         {
504             DeleteObserverUsingToken ((out->token), out->tokenLength);
505         }
506     }
507     serverObsList = NULL;
508 }
509
510 /*
511  * CA layer expects observe registration/de-reg/notiifcations to be passed as a header
512  * option, which breaks the protocol abstraction requirement between RI & CA, and
513  * has to be fixed in the future. The function below adds the header option for observe.
514  * It should be noted that the observe header option is assumed to be the first option
515  * in the list of user defined header options and hence it is inserted at the front
516  * of the header options list and number of options adjusted accordingly.
517  */
518 OCStackResult
519 CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
520                            OCHeaderOption *ocHdrOpt,
521                            uint8_t numOptions,
522                            uint8_t observeFlag)
523 {
524     if(!caHdrOpt || !ocHdrOpt)
525     {
526         return OC_STACK_INVALID_PARAM;
527     }
528
529     CAHeaderOption_t *tmpHdrOpt = NULL;
530
531     tmpHdrOpt = (CAHeaderOption_t *) OICCalloc ((numOptions+1), sizeof(CAHeaderOption_t));
532     if (NULL == tmpHdrOpt)
533     {
534         return OC_STACK_NO_MEMORY;
535     }
536     tmpHdrOpt[0].protocolID = CA_COAP_ID;
537     tmpHdrOpt[0].optionID = COAP_OPTION_OBSERVE;
538     tmpHdrOpt[0].optionLength = sizeof(uint8_t);
539     tmpHdrOpt[0].optionData[0] = observeFlag;
540     for (uint8_t i = 0; i < numOptions; i++)
541     {
542         memcpy (&(tmpHdrOpt[i+1]), &(ocHdrOpt[i]), sizeof(CAHeaderOption_t));
543     }
544
545     *caHdrOpt = tmpHdrOpt;
546     return OC_STACK_OK;
547 }
548
549 /*
550  * CA layer passes observe information to the RI layer as a header option, which
551  * breaks the protocol abstraction requirement between RI & CA, and has to be fixed
552  * in the future. The function below removes the observe header option and processes it.
553  * It should be noted that the observe header option is always assumed to be the first
554  * option in the list of user defined header options and hence it is deleted from the
555  * front of the header options list and the number of options is adjusted accordingly.
556  */
557 OCStackResult
558 GetObserveHeaderOption (uint32_t * observationOption,
559                         CAHeaderOption_t *options,
560                         uint8_t * numOptions)
561 {
562     if(!observationOption)
563     {
564         return OC_STACK_INVALID_PARAM;
565     }
566
567     if(!options || !numOptions)
568     {
569         return OC_STACK_INVALID_PARAM;
570     }
571
572     *observationOption = OC_OBSERVE_NO_OPTION;
573
574     for(uint8_t i = 0; i < *numOptions; i++)
575     {
576         if(options[i].protocolID == CA_COAP_ID &&
577                 options[i].optionID == COAP_OPTION_OBSERVE)
578         {
579             *observationOption = options[i].optionData[0];
580             for(uint8_t c = i; c < *numOptions-1; c++)
581             {
582                 options[i] = options[i+1];
583             }
584             (*numOptions)--;
585             return OC_STACK_OK;
586         }
587     }
588     return OC_STACK_OK;
589 }
590