e8e58d436a0a85445cde6f9e386dba177c462bb9
[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 "occoap.h"
28 #include "utlist.h"
29 #include "debug.h"
30 #include "ocrandom.h"
31 #include "ocmalloc.h"
32 #include "ocserverrequest.h"
33
34 // Module Name
35 #define MOD_NAME PCF("ocobserve")
36
37 #define TAG  PCF("OCStackObserve")
38
39 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
40
41 static struct ResourceObserver * serverObsList = NULL;
42
43 // send notifications based on the qos of the request
44 // The qos passed as a parameter overrides what the client requested
45 // If we want the client preference taking high priority make:
46 // qos = resourceObserver->qos;
47 OCQualityOfService DetermineObserverQoS(OCMethod method, ResourceObserver * resourceObserver,
48         OCQualityOfService appQoS)
49 {
50     OCQualityOfService decidedQoS = appQoS;
51     if(appQoS == OC_NA_QOS)
52     {
53         decidedQoS = resourceObserver->qos;
54     }
55
56     if(appQoS != OC_HIGH_QOS)
57     {
58         OC_LOG_V(INFO, TAG, "Current NON count for this observer is %d",
59                 resourceObserver->lowQosCount);
60         #ifdef WITH_PRESENCE
61         if((resourceObserver->forceHighQos \
62                 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT) \
63                 && method != OC_REST_PRESENCE)
64         #else
65         if(resourceObserver->forceHighQos \
66                 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
67         #endif
68             {
69             resourceObserver->lowQosCount = 0;
70             // at some point we have to to send CON to check on the
71             // availability of observer
72             OC_LOG(INFO, TAG, PCF("This time we are sending the  notification as High qos"));
73             decidedQoS = OC_HIGH_QOS;
74             }
75         else
76         {
77             (resourceObserver->lowQosCount)++;
78         }
79     }
80     return decidedQoS;
81 }
82
83 #ifdef WITH_PRESENCE
84 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
85         OCResourceType *resourceType, OCQualityOfService qos)
86 #else
87 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
88         OCQualityOfService qos)
89 #endif
90 {
91     OC_LOG(INFO, TAG, PCF("Entering SendObserverNotification"));
92     OCStackResult result = OC_STACK_ERROR;
93     ResourceObserver * resourceObserver = serverObsList;
94     uint8_t numObs = 0;
95     OCServerRequest * request = NULL;
96     OCEntityHandlerRequest ehRequest = {0};
97     OCEntityHandlerResult ehResult = OC_EH_ERROR;
98
99     // Find clients that are observing this resource
100     while (resourceObserver)
101     {
102         if (resourceObserver->resource == resPtr)
103         {
104             numObs++;
105             #ifdef WITH_PRESENCE
106             if(method != OC_REST_PRESENCE)
107             {
108             #endif
109                 qos = DetermineObserverQoS(method, resourceObserver, qos);
110                 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
111                         0, resPtr->sequenceNum, qos, resourceObserver->query,
112                         NULL, NULL,
113                         &resourceObserver->token, resourceObserver->addr,
114                         resourceObserver->resUri, 0);
115                 request->observeResult = OC_STACK_OK;
116                 if(request && result == OC_STACK_OK)
117                 {
118                     result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
119                                 request->method, (OCResourceHandle) resPtr, request->query,
120                                 request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
121                                 request->rcvdVendorSpecificHeaderOptions, OC_OBSERVE_NO_OPTION, 0);
122                     if(result == OC_STACK_OK)
123                     {
124                         ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest);
125                         if(ehResult == OC_EH_ERROR)
126                         {
127                             FindAndDeleteServerRequest(request);
128                         }
129                     }
130                 }
131             #ifdef WITH_PRESENCE
132             }
133             else
134             {
135                 OCEntityHandlerResponse ehResponse = {0};
136                 unsigned char presenceResBuf[MAX_RESPONSE_LENGTH] = {0};
137                 //This is effectively the implementation for the presence entity handler.
138                 OC_LOG(DEBUG, TAG, PCF("This notification is for Presence"));
139                 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
140                         0, OC_OBSERVE_NO_OPTION, OC_LOW_QOS,
141                         NULL, NULL, NULL, &resourceObserver->token,
142                         resourceObserver->addr, resourceObserver->resUri, 0);
143                 if(result == OC_STACK_OK)
144                 {
145                     // we create the payload here
146                     if(resourceType && resourceType->resourcetypename)
147                     {
148                         sprintf((char *)presenceResBuf, "%u:%u:%s",
149                                 resPtr->sequenceNum, maxAge, resourceType->resourcetypename);
150                     }
151                     else
152                     {
153                         sprintf((char *)presenceResBuf, "%u:%u", resPtr->sequenceNum, maxAge);
154                     }
155                     ehResponse.ehResult = OC_EH_OK;
156                     ehResponse.payload = presenceResBuf;
157                     ehResponse.payloadSize = strlen((const char *)presenceResBuf) + 1;
158                     ehResponse.persistentBufferFlag = 0;
159                     ehResponse.requestHandle = (OCRequestHandle) request;
160                     ehResponse.resourceHandle = (OCResourceHandle) resPtr;
161                     strcpy((char *)ehResponse.resourceUri, (const char *)resourceObserver->resUri);
162                     result = OCDoResponse(&ehResponse);
163                 }
164             }
165             #endif
166         }
167         resourceObserver = resourceObserver->next;
168     }
169     if (numObs == 0)
170     {
171         OC_LOG(INFO, TAG, PCF("Resource has no observers"));
172         result = OC_STACK_NO_OBSERVERS;
173     }
174     return result;
175 }
176
177 OCStackResult SendListObserverNotification (OCResource * resource,
178         OCObservationId  *obsIdList, uint8_t numberOfIds,
179         unsigned char *notificationJSONPayload, uint32_t maxAge,
180         OCQualityOfService qos)
181 {
182     uint8_t numIds = numberOfIds;
183     ResourceObserver *observation = NULL;
184     uint8_t numSentNotification = 0;
185     OCServerRequest * request = NULL;
186     OCStackResult result = OC_STACK_ERROR;
187     OCEntityHandlerResponse ehResponse = {0};
188
189     OC_LOG(INFO, TAG, PCF("Entering SendListObserverNotification"));
190     while(numIds)
191     {
192         OC_LOG_V(INFO, TAG, "Need to notify observation id %d", *obsIdList);
193         observation = NULL;
194         observation = GetObserverUsingId (*obsIdList);
195         if(observation)
196         {
197             // Found observation - verify if it matches the resource handle
198             if (observation->resource == resource)
199             {
200                 qos = DetermineObserverQoS(OC_REST_GET, observation, qos);
201
202                 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
203                         0, resource->sequenceNum, qos, observation->query,
204                         NULL, NULL, &observation->token,
205                         observation->addr, observation->resUri, 0);
206                 request->observeResult = OC_STACK_OK;
207                 if(request && result == OC_STACK_OK)
208                 {
209                     memset(&ehResponse, 0, sizeof(OCEntityHandlerResponse));
210                     ehResponse.ehResult = OC_EH_OK;
211                     ehResponse.payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
212                     if(!ehResponse.payload)
213                     {
214                         FindAndDeleteServerRequest(request);
215                         continue;
216                     }
217                     strcpy((char *)ehResponse.payload, (const char *)notificationJSONPayload);
218                     ehResponse.payloadSize = strlen((const char *)ehResponse.payload) + 1;
219                     ehResponse.persistentBufferFlag = 0;
220                     ehResponse.requestHandle = (OCRequestHandle) request;
221                     ehResponse.resourceHandle = (OCResourceHandle) resource;
222                     result = OCDoResponse(&ehResponse);
223                     if(result == OC_STACK_OK)
224                     {
225                         OCFree(ehResponse.payload);
226                         FindAndDeleteServerRequest(request);
227                     }
228                 }
229                 else
230                 {
231                     FindAndDeleteServerRequest(request);
232                 }
233
234                 numSentNotification++;
235             }
236         }
237         obsIdList++;
238         numIds--;
239     }
240     if(numSentNotification == numberOfIds)
241     {
242         return OC_STACK_OK;
243     }
244     else if(numSentNotification == 0)
245     {
246         return OC_STACK_NO_OBSERVERS;
247     }
248     else
249     {
250         //TODO: we need to signal that not every one in the
251         // list got an update, should we also indicate who did not receive on?
252         return OC_STACK_OK;
253     }
254 }
255
256 OCStackResult GenerateObserverId (OCObservationId *observationId)
257 {
258     ResourceObserver *resObs = NULL;
259
260     OC_LOG(INFO, TAG, PCF("Entering GenerateObserverId"));
261     VERIFY_NON_NULL (observationId);
262
263     do
264     {
265         *observationId = OCGetRandomByte();
266         // Check if observation Id already exists
267         resObs = GetObserverUsingId (*observationId);
268     } while (NULL != resObs);
269
270     OC_LOG_V(INFO, TAG, "Observation ID is %u", *observationId);
271
272     return OC_STACK_OK;
273 exit:
274     return OC_STACK_ERROR;
275 }
276
277 OCStackResult AddObserver (const char         *resUri,
278                            const char         *query,
279                            OCObservationId    obsId,
280                            OCCoAPToken        *token,
281                            OCDevAddr          *addr,
282                            OCResource         *resHandle,
283                            OCQualityOfService qos)
284 {
285     ResourceObserver *obsNode = NULL;
286
287     obsNode = (ResourceObserver *) OCCalloc(1, sizeof(ResourceObserver));
288     if (obsNode)
289     {
290         obsNode->observeId = obsId;
291
292         obsNode->resUri = (unsigned char *)OCMalloc(strlen(resUri)+1);
293         VERIFY_NON_NULL (obsNode->resUri);
294         memcpy (obsNode->resUri, resUri, strlen(resUri)+1);
295
296         obsNode->qos = qos;
297         if(query)
298         {
299             obsNode->query = (unsigned char *)OCMalloc(strlen(query)+1);
300             VERIFY_NON_NULL (obsNode->query);
301             memcpy (obsNode->query, query, strlen(query)+1);
302         }
303
304         obsNode->token.tokenLength = token->tokenLength;
305         memcpy (obsNode->token.token, token->token, token->tokenLength);
306
307         obsNode->addr = (OCDevAddr *)OCMalloc(sizeof(OCDevAddr));
308         VERIFY_NON_NULL (obsNode->addr);
309         memcpy (obsNode->addr, addr, sizeof(OCDevAddr));
310
311         obsNode->resource = resHandle;
312
313         LL_APPEND (serverObsList, obsNode);
314         return OC_STACK_OK;
315     }
316
317 exit:
318     if (obsNode)
319     {
320         OCFree(obsNode->resUri);
321         OCFree(obsNode->query);
322         OCFree(obsNode->addr);
323         OCFree(obsNode);
324     }
325     return OC_STACK_NO_MEMORY;
326 }
327
328 ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
329 {
330     ResourceObserver *out = NULL;
331
332     if (observeId)
333     {
334         LL_FOREACH (serverObsList, out)
335         {
336             if (out->observeId == observeId)
337             {
338                 return out;
339             }
340         }
341     }
342     OC_LOG(INFO, TAG, PCF("Observer node not found!!"));
343     return NULL;
344 }
345
346 ResourceObserver* GetObserverUsingToken (const OCCoAPToken * token)
347 {
348     ResourceObserver *out = NULL;
349
350     if(token)
351     {
352         LL_FOREACH (serverObsList, out)
353         {
354             OC_LOG(INFO, TAG,PCF("comparing tokens"));
355             OC_LOG_BUFFER(INFO, TAG, token->token, token->tokenLength);
356             OC_LOG_BUFFER(INFO, TAG, out->token.token, out->token.tokenLength);
357             if((out->token.tokenLength == token->tokenLength) &&
358                (memcmp(out->token.token, token->token, token->tokenLength) == 0))
359             {
360                 return out;
361             }
362         }
363     }
364     OC_LOG(INFO, TAG, PCF("Observer node not found!!"));
365     return NULL;
366 }
367
368 OCStackResult DeleteObserverUsingToken (OCCoAPToken * token)
369 {
370     ResourceObserver *obsNode = NULL;
371
372     obsNode = GetObserverUsingToken (token);
373     if (obsNode)
374     {
375         OC_LOG_V(INFO, TAG, PCF("deleting tokens"));
376         OC_LOG_BUFFER(INFO, TAG, obsNode->token.token, obsNode->token.tokenLength);
377         LL_DELETE (serverObsList, obsNode);
378         OCFree(obsNode->resUri);
379         OCFree(obsNode->query);
380         OCFree(obsNode->addr);
381         OCFree(obsNode);
382     }
383     // it is ok if we did not find the observer...
384     return OC_STACK_OK;
385 }
386
387 void DeleteObserverList()
388 {
389     ResourceObserver *out = NULL;
390     ResourceObserver *tmp = NULL;
391     LL_FOREACH_SAFE (serverObsList, out, tmp)
392     {
393         DeleteObserverUsingToken (&(out->token));
394     }
395     serverObsList = NULL;
396 }