Modifying version number for building on tizen 3.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 "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                         snprintf((char *)presenceResBuf, sizeof(presenceResBuf), "%u:%u:%s",
149                                 resPtr->sequenceNum, maxAge, resourceType->resourcetypename);
150                     }
151                     else
152                     {
153                         snprintf((char *)presenceResBuf, sizeof(presenceResBuf), "%u:%u",
154                                 resPtr->sequenceNum, maxAge);
155                     }
156                     ehResponse.ehResult = OC_EH_OK;
157                     ehResponse.payload = presenceResBuf;
158                     ehResponse.payloadSize = strlen((const char *)presenceResBuf) + 1;
159                     ehResponse.persistentBufferFlag = 0;
160                     ehResponse.requestHandle = (OCRequestHandle) request;
161                     ehResponse.resourceHandle = (OCResourceHandle) resPtr;
162                     strcpy((char *)ehResponse.resourceUri, (const char *)resourceObserver->resUri);
163                     result = OCDoResponse(&ehResponse);
164                 }
165             }
166             #endif
167         }
168         resourceObserver = resourceObserver->next;
169     }
170     if (numObs == 0)
171     {
172         OC_LOG(INFO, TAG, PCF("Resource has no observers"));
173         result = OC_STACK_NO_OBSERVERS;
174     }
175     return result;
176 }
177
178 OCStackResult SendListObserverNotification (OCResource * resource,
179         OCObservationId  *obsIdList, uint8_t numberOfIds,
180         unsigned char *notificationJSONPayload, uint32_t maxAge,
181         OCQualityOfService qos)
182 {
183     uint8_t numIds = numberOfIds;
184     ResourceObserver *observation = NULL;
185     uint8_t numSentNotification = 0;
186     OCServerRequest * request = NULL;
187     OCStackResult result = OC_STACK_ERROR;
188     OCEntityHandlerResponse ehResponse = {0};
189
190     OC_LOG(INFO, TAG, PCF("Entering SendListObserverNotification"));
191     while(numIds)
192     {
193         OC_LOG_V(INFO, TAG, "Need to notify observation id %d", *obsIdList);
194         observation = NULL;
195         observation = GetObserverUsingId (*obsIdList);
196         if(observation)
197         {
198             // Found observation - verify if it matches the resource handle
199             if (observation->resource == resource)
200             {
201                 qos = DetermineObserverQoS(OC_REST_GET, observation, qos);
202
203                 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
204                         0, resource->sequenceNum, qos, observation->query,
205                         NULL, NULL, &observation->token,
206                         observation->addr, observation->resUri, 0);
207                 request->observeResult = OC_STACK_OK;
208                 if(request && result == OC_STACK_OK)
209                 {
210                     memset(&ehResponse, 0, sizeof(OCEntityHandlerResponse));
211                     ehResponse.ehResult = OC_EH_OK;
212                     ehResponse.payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
213                     if(!ehResponse.payload)
214                     {
215                         FindAndDeleteServerRequest(request);
216                         continue;
217                     }
218                     strcpy((char *)ehResponse.payload, (const char *)notificationJSONPayload);
219                     ehResponse.payloadSize = strlen((const char *)ehResponse.payload) + 1;
220                     ehResponse.persistentBufferFlag = 0;
221                     ehResponse.requestHandle = (OCRequestHandle) request;
222                     ehResponse.resourceHandle = (OCResourceHandle) resource;
223                     result = OCDoResponse(&ehResponse);
224                     if(result == OC_STACK_OK)
225                     {
226                         OCFree(ehResponse.payload);
227                         FindAndDeleteServerRequest(request);
228                     }
229                 }
230                 else
231                 {
232                     FindAndDeleteServerRequest(request);
233                 }
234
235                 numSentNotification++;
236             }
237         }
238         obsIdList++;
239         numIds--;
240     }
241     if(numSentNotification == numberOfIds)
242     {
243         return OC_STACK_OK;
244     }
245     else if(numSentNotification == 0)
246     {
247         return OC_STACK_NO_OBSERVERS;
248     }
249     else
250     {
251         //TODO: we need to signal that not every one in the
252         // list got an update, should we also indicate who did not receive on?
253         return OC_STACK_OK;
254     }
255 }
256
257 OCStackResult GenerateObserverId (OCObservationId *observationId)
258 {
259     ResourceObserver *resObs = NULL;
260
261     OC_LOG(INFO, TAG, PCF("Entering GenerateObserverId"));
262     VERIFY_NON_NULL (observationId);
263
264     do
265     {
266         *observationId = OCGetRandomByte();
267         // Check if observation Id already exists
268         resObs = GetObserverUsingId (*observationId);
269     } while (NULL != resObs);
270
271     OC_LOG_V(INFO, TAG, "Observation ID is %u", *observationId);
272
273     return OC_STACK_OK;
274 exit:
275     return OC_STACK_ERROR;
276 }
277
278 OCStackResult AddObserver (const char         *resUri,
279                            const char         *query,
280                            OCObservationId    obsId,
281                            OCCoAPToken        *token,
282                            OCDevAddr          *addr,
283                            OCResource         *resHandle,
284                            OCQualityOfService qos)
285 {
286     ResourceObserver *obsNode = NULL;
287
288     obsNode = (ResourceObserver *) OCCalloc(1, sizeof(ResourceObserver));
289     if (obsNode)
290     {
291         obsNode->observeId = obsId;
292
293         obsNode->resUri = (unsigned char *)OCMalloc(strlen(resUri)+1);
294         VERIFY_NON_NULL (obsNode->resUri);
295         memcpy (obsNode->resUri, resUri, strlen(resUri)+1);
296
297         obsNode->qos = qos;
298         if(query)
299         {
300             obsNode->query = (unsigned char *)OCMalloc(strlen(query)+1);
301             VERIFY_NON_NULL (obsNode->query);
302             memcpy (obsNode->query, query, strlen(query)+1);
303         }
304
305         obsNode->token.tokenLength = token->tokenLength;
306         memcpy (obsNode->token.token, token->token, token->tokenLength);
307
308         obsNode->addr = (OCDevAddr *)OCMalloc(sizeof(OCDevAddr));
309         VERIFY_NON_NULL (obsNode->addr);
310         memcpy (obsNode->addr, addr, sizeof(OCDevAddr));
311
312         obsNode->resource = resHandle;
313
314         LL_APPEND (serverObsList, obsNode);
315         return OC_STACK_OK;
316     }
317
318 exit:
319     if (obsNode)
320     {
321         OCFree(obsNode->resUri);
322         OCFree(obsNode->query);
323         OCFree(obsNode->addr);
324         OCFree(obsNode);
325     }
326     return OC_STACK_NO_MEMORY;
327 }
328
329 ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
330 {
331     ResourceObserver *out = NULL;
332
333     if (observeId)
334     {
335         LL_FOREACH (serverObsList, out)
336         {
337             if (out->observeId == observeId)
338             {
339                 return out;
340             }
341         }
342     }
343     OC_LOG(INFO, TAG, PCF("Observer node not found!!"));
344     return NULL;
345 }
346
347 ResourceObserver* GetObserverUsingToken (const OCCoAPToken * token)
348 {
349     ResourceObserver *out = NULL;
350
351     if(token)
352     {
353         LL_FOREACH (serverObsList, out)
354         {
355             OC_LOG(INFO, TAG,PCF("comparing tokens"));
356             OC_LOG_BUFFER(INFO, TAG, token->token, token->tokenLength);
357             OC_LOG_BUFFER(INFO, TAG, out->token.token, out->token.tokenLength);
358             if((out->token.tokenLength == token->tokenLength) &&
359                (memcmp(out->token.token, token->token, token->tokenLength) == 0))
360             {
361                 return out;
362             }
363         }
364     }
365     OC_LOG(INFO, TAG, PCF("Observer node not found!!"));
366     return NULL;
367 }
368
369 OCStackResult DeleteObserverUsingToken (OCCoAPToken * token)
370 {
371     ResourceObserver *obsNode = NULL;
372
373     obsNode = GetObserverUsingToken (token);
374     if (obsNode)
375     {
376         OC_LOG_V(INFO, TAG, PCF("deleting tokens"));
377         OC_LOG_BUFFER(INFO, TAG, obsNode->token.token, obsNode->token.tokenLength);
378         LL_DELETE (serverObsList, obsNode);
379         OCFree(obsNode->resUri);
380         OCFree(obsNode->query);
381         OCFree(obsNode->addr);
382         OCFree(obsNode);
383     }
384     // it is ok if we did not find the observer...
385     return OC_STACK_OK;
386 }
387
388 void DeleteObserverList()
389 {
390     ResourceObserver *out = NULL;
391     ResourceObserver *tmp = NULL;
392     LL_FOREACH_SAFE (serverObsList, out, tmp)
393     {
394         DeleteObserverUsingToken (&(out->token));
395     }
396     serverObsList = NULL;
397 }