Fixes to send the correct sender info when a presence notification is sent
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocstack.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
22 //-----------------------------------------------------------------------------
23 // Includes
24 //-----------------------------------------------------------------------------
25 #define _POSIX_C_SOURCE 200112L
26 #include <string.h>
27
28 #include "ocstack.h"
29 #include "ocstackinternal.h"
30 #include "ocresourcehandler.h"
31 #include "occlientcb.h"
32 #include "ocobserve.h"
33 #include "ocrandom.h"
34 #include "debug.h"
35 #include "occoap.h"
36 #include "ocmalloc.h"
37 #include "ocserverrequest.h"
38
39 #ifdef CA_INT
40     #include "cacommon.h"
41     #include "cainterface.h"
42 #endif
43
44 //-----------------------------------------------------------------------------
45 // Typedefs
46 //-----------------------------------------------------------------------------
47 typedef enum {
48     OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
49 } OCStackState;
50
51 #ifdef WITH_PRESENCE
52 typedef enum {
53     OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
54 } OCPresenceState;
55 #endif
56
57 //-----------------------------------------------------------------------------
58 // Private variables
59 //-----------------------------------------------------------------------------
60 static OCStackState stackState = OC_STACK_UNINITIALIZED;
61
62 OCResource *headResource = NULL;
63 #ifdef WITH_PRESENCE
64 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
65 static PresenceResource presenceResource;
66 uint8_t PresenceTimeOutSize = 0;
67 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
68 #endif
69
70 OCMode myStackMode;
71 OCDeviceEntityHandler defaultDeviceHandler;
72 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
73
74 //-----------------------------------------------------------------------------
75 // Macros
76 //-----------------------------------------------------------------------------
77 #define TAG  PCF("OCStack")
78 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
79             {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
80 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
81              TAG, PCF(#arg " is NULL")); return (retVal); } }
82 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
83     goto exit;} }
84
85 //TODO: we should allow the server to define this
86 #define MAX_OBSERVE_AGE (0x2FFFFUL)
87
88 //-----------------------------------------------------------------------------
89 // Externs
90 //-----------------------------------------------------------------------------
91 extern void DeinitOCSecurityInfo();
92
93 //-----------------------------------------------------------------------------
94 // Internal API function
95 //-----------------------------------------------------------------------------
96
97 // This internal function is called to update the stack with the status of
98 // observers and communication failures
99 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
100 {
101     OCStackResult result = OC_STACK_ERROR;
102     ResourceObserver * observer = NULL;
103     OCEntityHandlerRequest ehRequest = {0};
104
105     switch(status)
106     {
107     case OC_OBSERVER_NOT_INTERESTED:
108         OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
109         #ifdef CA_INT
110         observer = GetObserverUsingToken (token->token);
111         #else
112         observer = GetObserverUsingToken (token);
113         #endif
114         if(observer)
115         {
116             result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
117                     OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
118                     NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
119             if(result != OC_STACK_OK)
120             {
121                 return result;
122             }
123             observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
124         }
125         //observer is not observing anymore
126         #ifdef CA_INT
127         result = DeleteObserverUsingToken (token->token);
128         #else
129         result = DeleteObserverUsingToken (token);
130         #endif
131         if(result == OC_STACK_OK)
132         {
133             OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
134         }
135         else
136         {
137             result = OC_STACK_OK;
138             OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
139         }
140         break;
141     case OC_OBSERVER_STILL_INTERESTED:
142         //observer is still interested
143         OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
144                 notifications, reset the failedCount"));
145         #ifdef CA_INT
146         observer = GetObserverUsingToken (token->token);
147         #else
148         observer = GetObserverUsingToken (token);
149         #endif
150         if(observer)
151         {
152             observer->forceHighQos = 0;
153             observer->failedCommCount = 0;
154             result = OC_STACK_OK;
155         }
156         else
157         {
158             result = OC_STACK_OBSERVER_NOT_FOUND;
159         }
160         break;
161     case OC_OBSERVER_FAILED_COMM:
162         //observer is not reachable
163         OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
164         #ifdef CA_INT
165         observer = GetObserverUsingToken (token->token);
166         #else
167         observer = GetObserverUsingToken (token);
168         #endif
169         if(observer)
170         {
171             if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
172             {
173                 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
174                         OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
175                         NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
176                 if(result != OC_STACK_OK)
177                 {
178                     return OC_STACK_ERROR;
179                 }
180                 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
181                 //observer is unreachable
182                 result = DeleteObserverUsingToken (token);
183                 if(result == OC_STACK_OK)
184                 {
185                     OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
186                 }
187                 else
188                 {
189                     result = OC_STACK_OK;
190                     OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
191                 }
192             }
193             else
194             {
195                 observer->failedCommCount++;
196                 result = OC_STACK_CONTINUE;
197             }
198             observer->forceHighQos = 1;
199             OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
200         }
201         break;
202     default:
203         OC_LOG(ERROR, TAG, PCF("Unknown status"));
204         result = OC_STACK_ERROR;
205         break;
206         }
207     return result;
208 }
209
210 #ifdef CA_INT
211 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
212 {
213     OCStackResult ret = OC_STACK_ERROR;
214
215     switch(caCode)
216     {
217         case CA_SUCCESS:
218             ret = OC_STACK_OK;
219             break;
220         case CA_CREATED:
221             ret = OC_STACK_RESOURCE_CREATED;
222             break;
223         case CA_DELETED:
224             ret = OC_STACK_RESOURCE_DELETED;
225             break;
226         case CA_BAD_REQ:
227             ret = OC_STACK_INVALID_QUERY;
228             break;
229         case CA_BAD_OPT:
230             ret = OC_STACK_INVALID_OPTION;
231             break;
232         case CA_NOT_FOUND:
233             ret = OC_STACK_NO_RESOURCE;
234             break;
235         default:
236             break;
237     }
238     return ret;
239 }
240
241 // update response.addr appropriately from endPoint.addressInfo
242 void UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
243 {
244     struct sockaddr_in sa;
245     inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
246     sa.sin_port = htons(endPoint->addressInfo.IP.port);
247     static OCDevAddr address;
248     memcpy((void*)&address.addr, &(sa), sizeof(sa));
249     response->addr = &address;
250 }
251
252 void HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
253 {
254     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
255     ClientCB * cbNode = NULL;
256     char *resourceTypeName = NULL;
257     char * tok = NULL;
258     char * bufRes = responseInfo->info.payload;
259     OCClientResponse *response = (OCClientResponse *) OCMalloc(sizeof(OCClientResponse));
260
261     UpdateResponseAddr(response, endPoint);
262
263     if(!bufRes)
264     {
265         goto exit;
266     }
267
268     tok = strtok(bufRes, "[:]}");
269     bufRes[strlen(bufRes)] = ':';
270     tok = strtok(NULL, "[:]}");
271     bufRes[strlen((char *)bufRes)] = ':';
272     response->sequenceNumber = (uint32_t )atoi(tok);
273     tok = strtok(NULL, "[:]}");
274     tok = strtok(NULL, "[:]}");
275     if(tok)
276     {
277         resourceTypeName = (char *)OCMalloc(strlen(tok));
278         if(!resourceTypeName)
279         {
280             goto exit;
281         }
282         bufRes[strlen((char *)bufRes)] = ':';
283         strcpy(resourceTypeName, tok);
284         OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
285                 resourceTypeName);
286     }
287     bufRes[strlen((char *)bufRes)] = ']';
288
289     response->resJSONPayload = responseInfo->info.payload;
290     response->result = OC_STACK_OK;
291
292     char *fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
293     char *ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
294
295     strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, strlen(endPoint->addressInfo.IP.ipAddress));
296     ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
297
298     snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
299                 OC_PRESENCE_URI);
300
301     cbNode = GetClientCB(NULL, NULL, fullUri);
302
303     if(cbNode)
304     {
305         cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response);
306     }
307
308     if (cbResult == OC_STACK_DELETE_TRANSACTION)
309     {
310         FindAndDeleteClientCB(cbNode);
311     }
312
313 exit:
314
315 OCFree(fullUri);
316 OCFree(ipAddress);
317 OCFree(resourceTypeName);
318 }
319
320
321 //This function will be called back by CA layer when a response is received
322 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
323 {
324     OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
325     OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
326     if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
327     {
328         HandlePresenceResponse(endPoint, responseInfo);
329         return 0;
330     }
331     ClientCB *cbNode = GetClientCB((CAToken_t *)&responseInfo->info.token, NULL, NULL);
332
333     if (cbNode)
334     {
335         OC_LOG(INFO, TAG, PCF("Calling into application address space"));
336         OCClientResponse response;
337
338         UpdateResponseAddr(&response, endPoint);
339         response.connType = endPoint->connectivityType;
340
341         response.result = CAToOCStackResult(responseInfo->result);
342         response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
343         response.numRcvdVendorSpecificHeaderOptions = 0;
344         if(responseInfo->info.numOptions > 0)
345         {
346             //First option alwas with option ID COAP_OPTION_OBSERVE if it is availbale
347             if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
348             {
349                 memcpy (&(response.sequenceNumber),
350                 &(responseInfo->info.options[0].optionData), 4);
351             }
352             else
353             {
354                memcpy (&(response.rcvdVendorSpecificHeaderOptions[0]),
355                  &(responseInfo->info.options[0]), sizeof(OCHeaderOption));
356             }
357             for (uint8_t i = 1; i < responseInfo->info.numOptions; i++)
358             {
359                 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i]),
360                  &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
361             }
362             response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
363         }
364         result = cbNode->callBack(cbNode->context,
365                 cbNode->handle, &response);
366         if (result == OC_STACK_DELETE_TRANSACTION)
367         {
368             FindAndDeleteClientCB(cbNode);
369         }
370     }
371     OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
372     OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
373 }
374
375 //This function will be called back by CA layer when a request is received
376 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
377 {
378     CAInfo_t responseData;
379     CAResponseInfo_t responseInfo;
380     OCStackResult requestResult = OC_STACK_ERROR;
381
382     OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
383
384 #if 1
385     if(myStackMode == OC_CLIENT)
386     {
387         //TODO: should the client be responding to requests?
388         return;
389     }
390
391     OCServerProtocolRequest serverRequest;
392
393     memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
394     OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
395
396     char * newUri = (char *)endPoint->resourceUri;
397     unsigned char * query = NULL;
398     unsigned char * resourceType = NULL;
399     getQueryFromUri(endPoint->resourceUri, &query, &newUri);
400     OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
401     OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
402     //copy URI
403     memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
404     //copy query
405     if(query)
406     {
407         memcpy (&(serverRequest.query), query, strlen(query));
408     }
409     //copy request payload
410     if (requestInfo->info.payload)
411     {
412         serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
413         memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
414                 strlen(requestInfo->info.payload));
415         serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
416     }
417     else
418     {
419         serverRequest.reqTotalSize = 1;
420     }
421
422     switch (requestInfo->method)
423     {
424         case CA_GET:
425             {
426                 serverRequest.method = OC_REST_GET;
427                 break;
428             }
429         case CA_PUT:
430             {
431                 serverRequest.method = OC_REST_PUT;
432                 break;
433             }
434         case CA_POST:
435             {
436                 serverRequest.method = OC_REST_POST;
437                 break;
438             }
439         case CA_DELETE:
440             {
441                 serverRequest.method = OC_REST_DELETE;
442                 break;
443             }
444         default:
445             {
446                 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
447                 return;
448             }
449     }
450
451     // copy token
452     OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
453     OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
454     // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
455     // Need to remove OCCoapToken
456     memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
457             strlen(requestInfo->info.token));
458     serverRequest.requestToken.tokenLength = strlen(requestInfo->info.token);
459
460     if (requestInfo->info.type == CA_MSG_CONFIRM)
461     {
462         serverRequest.qos = OC_HIGH_QOS;
463     }
464     else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
465     {
466         serverRequest.qos = OC_LOW_QOS;
467     }
468     else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
469     {
470         // TODO-CA: Need to handle this
471     }
472     else if (requestInfo->info.type == CA_MSG_RESET)
473     {
474         // TODO-CA: Need to handle this
475     }
476     // CA does not need the following 3 fields
477     serverRequest.coapID = 0;
478     serverRequest.delayedResNeeded = 0;
479     serverRequest.secured = endPoint->isSecured;
480
481     // copy the address
482     serverRequest.addressInfo      = endPoint->addressInfo;
483     serverRequest.connectivityType = endPoint->connectivityType;
484     if (requestInfo->info.token)
485     {
486         strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
487     }
488
489     // copy vendor specific header options
490     // TODO-CA: CA is including non-vendor header options as well, like observe.
491     // Need to filter those out
492     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &(requestInfo->info.numOptions));
493     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
494     {
495         // TODO-CA: Need to send an error indicating the num of options is incorrect
496         return;
497     }
498     serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
499     if (serverRequest.numRcvdVendorSpecificHeaderOptions)
500     {
501         memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
502             sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
503     }
504
505     requestResult = HandleStackRequests (&serverRequest);
506 #endif
507
508     OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
509 }
510
511 #endif // CA_INT
512
513 //This function will be called back by occoap layer when a request is received
514 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
515 {
516     OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
517     OCStackResult result = OC_STACK_ERROR;
518     ResourceHandling resHandling;
519     OCResource *resource;
520
521     OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
522     if(!request)
523     {
524         OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
525 #ifdef CA_INT
526         result = AddServerCARequest(&request, protocolRequest->coapID,
527                 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
528                 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
529                 protocolRequest->observationOption, protocolRequest->qos,
530                 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
531                 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
532                 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
533                 protocolRequest->reqTotalSize,
534                 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
535 #else
536         result = AddServerRequest(&request, protocolRequest->coapID,
537                 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
538                 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
539                 protocolRequest->observationOption, protocolRequest->qos,
540                 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
541                 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
542                 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
543                 protocolRequest->reqTotalSize);
544 #endif
545         if (OC_STACK_OK != result)
546         {
547             OC_LOG(ERROR, TAG, PCF("Error adding server request"));
548             return result;
549         }
550         VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
551
552         if(!protocolRequest->reqMorePacket)
553         {
554             request->requestComplete = 1;
555         }
556     }
557     else
558     {
559         OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
560     }
561
562     if(request->requestComplete)
563     {
564         OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
565         result = DetermineResourceHandling (request, &resHandling, &resource);
566         if (result == OC_STACK_OK)
567         {
568             result = ProcessRequest(resHandling, resource, request);
569         }
570         else
571         {
572             result = OC_STACK_ERROR;
573         }
574     }
575     else
576     {
577         OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
578         result = OC_STACK_CONTINUE;
579     }
580     return result;
581 }
582
583 //This function will be called back by occoap layer when a response is received
584 OCStackResult HandleStackResponses(OCResponse * response)
585 {
586     OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
587     OCStackResult result = OC_STACK_OK;
588     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
589     uint8_t isObserveNotification = 0;
590     ClientCB * cbNode = NULL;
591     #ifdef WITH_PRESENCE
592     uint8_t isPresenceNotification = 0;
593     uint8_t isMulticastPresence = 0;
594     char * resourceTypeName = NULL;
595     uint32_t lowerBound = 0;
596     uint32_t higherBound = 0;
597     char * tok = NULL;
598     unsigned char * bufRes = response->bufRes;
599     #endif // WITH_PRESENCE
600
601     cbNode = response->cbNode;
602     if(!cbNode)
603     {
604         cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
605     }
606
607     if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
608     {
609         isObserveNotification = 1;
610         OC_LOG(INFO, TAG, PCF("Received an observe notification"));
611     }
612
613     OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
614             response->clientResponse->sequenceNumber);
615     OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
616     OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
617
618 #ifdef WITH_PRESENCE
619     if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
620         isPresenceNotification = 1;
621         if(!bufRes)
622         {
623             result = OC_STACK_INVALID_PARAM;
624             goto exit;
625         }
626         tok = strtok((char *)bufRes, "[:]}");
627         bufRes[strlen((char *)bufRes)] = ':';
628         tok = strtok(NULL, "[:]}");
629         bufRes[strlen((char *)bufRes)] = ':';
630         response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
631         OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
632         tok = strtok(NULL, "[:]}");
633         response->maxAge = (uint32_t )atoi(tok);
634         OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
635         tok = strtok(NULL, "[:]}");
636         if(tok)
637         {
638             resourceTypeName = (char *)OCMalloc(strlen(tok));
639             if(!resourceTypeName)
640             {
641                 goto exit;
642             }
643             bufRes[strlen((char *)bufRes)] = ':';
644             strcpy(resourceTypeName, tok);
645             OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
646                     resourceTypeName);
647         }
648         bufRes[strlen((char *)bufRes)] = ']';
649     }
650
651     // Check if the application subcribed for presence
652     if(!cbNode)
653     {
654         cbNode = GetClientCB(NULL, NULL, response->fullUri);
655     }
656
657     // Check if application subscribed for multicast presence
658     if(!cbNode)
659     {
660         snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
661                 OC_MULTICAST_IP, response->rcvdUri);
662         cbNode = GetClientCB(NULL, NULL, response->fullUri);
663         if(cbNode)
664         {
665             isMulticastPresence = 1;
666             isPresenceNotification = 0;
667         }
668     }
669
670     if(cbNode && isPresenceNotification)
671     {
672         OC_LOG(INFO, TAG, PCF("Received a presence notification"));
673         if(!cbNode->presence)
674         {
675             cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
676             VERIFY_NON_NULL_V(cbNode->presence);
677             cbNode->presence->timeOut = NULL;
678             cbNode->presence->timeOut = (uint32_t *)
679                     OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
680             if(!(cbNode->presence->timeOut)){
681                 OCFree(cbNode->presence);
682                 result = OC_STACK_NO_MEMORY;
683             }
684         }
685         if(response->maxAge == 0)
686         {
687             OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
688             response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
689             if(cbNode->presence)
690             {
691                 OCFree(cbNode->presence->timeOut);
692                 OCFree(cbNode->presence);
693                 cbNode->presence = NULL;
694             }
695         }
696         else
697         {
698             OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
699             cbNode->presence->TTL = response->maxAge;
700             for(int index = 0; index < PresenceTimeOutSize; index++)
701             {
702                 lowerBound = GetTime(((float)(PresenceTimeOut[index])
703                         /(float)100)*(float)cbNode->presence->TTL);
704                 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
705                         /(float)100)*(float)cbNode->presence->TTL);
706                 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
707                 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout  %d", lowerBound);
708                 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
709                 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry  %d",
710                         cbNode->presence->timeOut[index]);
711             }
712             cbNode->presence->TTLlevel = 0;
713             OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
714             if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
715             {
716                 OC_LOG(INFO, TAG, PCF("===============No presence change"));
717                 goto exit;
718             }
719             OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
720             cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
721         }
722
723         // Ensure that a filter is actually applied.
724         if(resourceTypeName && cbNode->filterResourceType)
725         {
726             if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
727             {
728                 goto exit;
729             }
730         }
731     }
732     else if(cbNode && isMulticastPresence)
733     {
734         // Check if the same nonce for a given host
735         OCMulticastNode* mcNode = NULL;
736         mcNode = GetMCPresenceNode(response->fullUri);
737
738         if(response->maxAge == 0)
739         {
740             OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
741             response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
742             if(cbNode->presence)
743             {
744                 OCFree(cbNode->presence->timeOut);
745                 OCFree(cbNode->presence);
746                 cbNode->presence = NULL;
747             }
748         }
749         else if(mcNode != NULL)
750         {
751             if(mcNode->nonce == response->clientResponse->sequenceNumber)
752             {
753                 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
754                 result = OC_STACK_NO_MEMORY;
755                 goto exit;
756             }
757             mcNode->nonce = response->clientResponse->sequenceNumber;
758         }
759         else
760         {
761             uint32_t uriLen = strlen((char*)response->fullUri);
762             unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
763             if(uri)
764             {
765                 memcpy(uri, response->fullUri, (uriLen + 1));
766             }
767             else
768             {
769                 OC_LOG(INFO, TAG,
770                     PCF("===============No Memory for URI to store in the presence node"));
771                 result = OC_STACK_NO_MEMORY;
772                 goto exit;
773             }
774             result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
775                     response->clientResponse->sequenceNumber);
776             if(result == OC_STACK_NO_MEMORY)
777             {
778                 OC_LOG(INFO, TAG,
779                     PCF("===============No Memory for Multicast Presence Node"));
780                 result = OC_STACK_NO_MEMORY;
781                 goto exit;
782             }
783         }
784
785         // Ensure that a filter is actually applied.
786         if(resourceTypeName && cbNode->filterResourceType)
787         {
788             if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
789             {
790                 goto exit;
791             }
792         }
793     }
794
795     else if(!cbNode && isPresenceNotification)
796     {
797     OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
798                  ------------ ignoring"));
799     }
800     #endif // WITH_PRESENCE
801
802     if(cbNode)
803     {
804         if(isObserveNotification)
805         {
806             OC_LOG(INFO, TAG, PCF("Received an observe notification"));
807             //TODO: check the standard for methods to detect wrap around condition
808             if(cbNode->method == OC_REST_OBSERVE &&
809                     (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
810                             (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
811                                     response->clientResponse->sequenceNumber ==
812                                             MAX_SEQUENCE_NUMBER)))
813             {
814                 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
815                         Ignoring Incoming:%d  Against Current:%d.",
816                         response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
817                 goto exit;
818             }
819             if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
820                 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
821             }
822         }
823
824         response->clientResponse->resJSONPayload = bufRes;
825
826         cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
827
828         if (cbResult == OC_STACK_DELETE_TRANSACTION ||
829                 response->clientResponse->result == OC_STACK_COMM_ERROR ||
830                 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
831                         !isPresenceNotification && !isMulticastPresence))
832         {
833             FindAndDeleteClientCB(cbNode);
834         }
835     }
836     else
837     {
838         result = OC_STACK_ERROR;
839     }
840
841     exit:
842     #ifdef WITH_PRESENCE
843     OCFree(resourceTypeName);
844     #endif
845     return result;
846 }
847
848 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
849 {
850     size_t index = 0;
851     unsigned char *itr, *coap;
852     uint8_t dotCount = 0;
853
854     ipAddr[index] = 0;
855     *port = 0;
856     /* search for scheme */
857     itr = ipAddrStr;
858     if (!isdigit((unsigned char) *ipAddrStr))
859     {
860         coap = (unsigned char *) OC_COAP_SCHEME;
861         while (*coap && tolower(*itr) == *coap)
862         {
863             coap++;
864             itr++;
865         }
866     }
867     ipAddrStr = itr;
868
869     while (*ipAddrStr) {
870         if (isdigit((unsigned char) *ipAddrStr))
871         {
872             ipAddr[index] *= 10;
873             ipAddr[index] += *ipAddrStr - '0';
874         }
875         else if ((unsigned char) *ipAddrStr == '.')
876         {
877             index++;
878             dotCount++;
879             ipAddr[index] = 0;
880         }
881         else
882         {
883             break;
884         }
885         ipAddrStr++;
886     }
887     if(*ipAddrStr == ':')
888     {
889         ipAddrStr++;
890         while (*ipAddrStr){
891             if (isdigit((unsigned char) *ipAddrStr))
892             {
893                 *port *= 10;
894                 *port += *ipAddrStr - '0';
895             }
896             else
897             {
898                 break;
899             }
900             ipAddrStr++;
901         }
902     }
903
904
905     if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
906             && dotCount == 3)
907     {
908         return 1;
909     }
910     else
911     {
912         return 0;
913     }
914 }
915
916 //-----------------------------------------------------------------------------
917 // Private internal function prototypes
918 //-----------------------------------------------------------------------------
919
920 static OCDoHandle GenerateInvocationHandle();
921 static OCStackResult initResources();
922 static void insertResource(OCResource *resource);
923 static OCResource *findResource(OCResource *resource);
924 static void insertResourceType(OCResource *resource,
925         OCResourceType *resourceType);
926 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
927         uint8_t index);
928 static void insertResourceInterface(OCResource *resource,
929         OCResourceInterface *resourceInterface);
930 static OCResourceInterface *findResourceInterfaceAtIndex(
931         OCResourceHandle handle, uint8_t index);
932 static void deleteResourceType(OCResourceType *resourceType);
933 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
934 static void deleteResourceElements(OCResource *resource);
935 static int deleteResource(OCResource *resource);
936 static void deleteAllResources();
937 static void incrementSequenceNumber(OCResource * resPtr);
938 static OCStackResult verifyUriQueryLength(const char * inputUri,
939         uint16_t uriLen);
940 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
941 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
942
943 //-----------------------------------------------------------------------------
944 // Public APIs
945 //-----------------------------------------------------------------------------
946
947 /**
948  * Initialize the OC Stack.  Must be called prior to starting the stack.
949  *
950  * @param ipAddr
951  *     IP Address of host device
952  * @param port
953  *     Port of host device
954  * @param mode
955  *     Host device is client, server, or client-server
956  *
957  * @return
958  *     OC_STACK_OK    - no errors
959  *     OC_STACK_ERROR - stack init error
960  */
961 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
962 {
963     OCStackResult result = OC_STACK_ERROR;
964     OC_LOG(INFO, TAG, PCF("Entering OCInit"));
965
966     if (ipAddr)
967     {
968         OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
969     }
970
971     OCSeedRandom();
972 #ifdef CA_INT
973     CAInitialize();
974     //It is ok to select network to CA_WIFI for now
975     CAResult_t caResult = CASelectNetwork(CA_WIFI|CA_ETHERNET);
976     if(caResult == CA_STATUS_OK)
977     {
978         OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
979         caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
980         if(caResult == CA_STATUS_OK)
981         {
982             OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
983             stackState = OC_STACK_INITIALIZED;
984             result = OC_STACK_OK;
985             switch (mode)
986             {
987                 case OC_CLIENT:
988                     caResult = CAStartDiscoveryServer();
989                     OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
990                     break;
991                 case OC_SERVER:
992                     caResult = CAStartListeningServer();
993                     OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
994                     break;
995                 case OC_CLIENT_SERVER:
996                     caResult = CAStartListeningServer();
997                     if(caResult == CA_STATUS_OK)
998                     {
999                         caResult = CAStartDiscoveryServer();
1000                     }
1001                     OC_LOG(INFO, TAG, PCF("Client-server mode"));
1002                     break;
1003                 default:
1004                     OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1005                     return OC_STACK_ERROR;
1006                     break;
1007             }
1008
1009         }
1010         if (caResult == CA_STATUS_OK)
1011         {
1012             result = OC_STACK_OK;
1013         }
1014         else
1015         {
1016             result = OC_STACK_ERROR;
1017         }
1018     }
1019 #else
1020     switch (mode)
1021     {
1022     case OC_CLIENT:
1023         OC_LOG(INFO, TAG, PCF("Client mode"));
1024         break;
1025     case OC_SERVER:
1026         OC_LOG(INFO, TAG, PCF("Server mode"));
1027         break;
1028     case OC_CLIENT_SERVER:
1029         OC_LOG(INFO, TAG, PCF("Client-server mode"));
1030         break;
1031     default:
1032         OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1033         return OC_STACK_ERROR;
1034         break;
1035     }
1036
1037     // Make call to OCCoAP layer
1038     result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
1039 #endif //CA_INT
1040
1041     myStackMode = mode;
1042     defaultDeviceHandler = NULL;
1043
1044 #ifdef WITH_PRESENCE
1045     PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1046 #endif // WITH_PRESENCE
1047
1048     if (result == OC_STACK_OK)
1049     {
1050         stackState = OC_STACK_INITIALIZED;
1051     }
1052     // Initialize resource
1053     if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1054     {
1055         result = initResources();
1056     }
1057     if(result != OC_STACK_OK)
1058     {
1059         OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1060     }
1061     return result;
1062 }
1063
1064 /**
1065  * Stop the OC stack.  Use for a controlled shutdown.
1066  * @return
1067  *     OC_STACK_OK    - no errors
1068  *     OC_STACK_ERROR - stack not initialized
1069  */
1070 OCStackResult OCStop()
1071 {
1072     OCStackResult result = OC_STACK_ERROR;
1073
1074     OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1075
1076     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1077     {
1078         OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1079         return OC_STACK_OK;
1080     }
1081     else if (stackState != OC_STACK_INITIALIZED)
1082     {
1083         OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1084         return OC_STACK_ERROR;
1085     }
1086
1087     stackState = OC_STACK_UNINIT_IN_PROGRESS;
1088
1089     #ifdef WITH_PRESENCE
1090     // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1091     // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1092     presenceResource.presenceTTL = 0;
1093     #endif // WITH_PRESENCE
1094
1095     // Free memory dynamically allocated for resources
1096     deleteAllResources();
1097     DeleteDeviceInfo();
1098
1099     // Make call to OCCoAP layer
1100     if (OCStopCoAP() == OC_STACK_OK)
1101     {
1102         // Remove all observers
1103         DeleteObserverList();
1104         // Remove all the client callbacks
1105         DeleteClientCBList();
1106         stackState = OC_STACK_UNINITIALIZED;
1107         result = OC_STACK_OK;
1108     } else {
1109         stackState = OC_STACK_INITIALIZED;
1110         result = OC_STACK_ERROR;
1111     }
1112
1113     // Deinit security blob
1114     DeinitOCSecurityInfo();
1115
1116     if (result != OC_STACK_OK) {
1117         OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1118     }
1119
1120     return result;
1121 }
1122
1123 /**
1124  * Verify the lengths of the URI and the query separately
1125  *
1126  * @param inputUri       - Input URI and query.
1127  * @param uriLen         - The length of the initial URI with query.
1128  *
1129  * Note: The '?' that appears after the URI is not considered as
1130  * a part of the query.
1131  */
1132 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1133 {
1134     char *query;
1135
1136     query = strchr (inputUri, '?');
1137
1138     if (query != NULL)
1139     {
1140         if((query - inputUri) > MAX_URI_LENGTH)
1141         {
1142             return OC_STACK_INVALID_URI;
1143         }
1144
1145         if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1146         {
1147             return OC_STACK_INVALID_QUERY;
1148         }
1149     }
1150     else if(uriLen > MAX_URI_LENGTH)
1151     {
1152         return OC_STACK_INVALID_URI;
1153     }
1154     return OC_STACK_OK;
1155 }
1156
1157 /**
1158  * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1159  *
1160  * @param handle             - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1161  * @param method             - @ref OCMethod to perform on the resource
1162  * @param requiredUri        - URI of the resource to interact with
1163  * @param referenceUri       - URI of the reference resource
1164  * @param request            - JSON encoded request
1165  * @param qos                - quality of service
1166  * @param cbData             - struct that contains asynchronous callback function that is invoked
1167  *                             by the stack when discovery or resource interaction is complete
1168  * @param options            - The address of an array containing the vendor specific header
1169  *                             header options to be sent with the request
1170  * @param numOptions         - Number of vendor specific header options to be included
1171  *
1172  * @return
1173  *     OC_STACK_OK               - no errors
1174  *     OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1175  *     OC_STACK_INVALID_METHOD   - invalid resource method
1176  *     OC_STACK_INVALID_URI      - invalid required or reference URI
1177  */
1178 #ifdef CA_INT
1179 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1180                            const char *referenceUri, const char *request, uint8_t conType,
1181                            OCQualityOfService qos, OCCallbackData *cbData,
1182                            OCHeaderOption * options, uint8_t numOptions)
1183 #else
1184 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1185                            const char *referenceUri, const char *request,
1186                            OCQualityOfService qos, OCCallbackData *cbData,
1187                            OCHeaderOption * options, uint8_t numOptions)
1188 #endif
1189 {
1190     OCStackResult result = OC_STACK_ERROR;
1191     OCCoAPToken token;
1192     ClientCB *clientCB = NULL;
1193     unsigned char * requestUri = NULL;
1194     unsigned char * resourceType = NULL;
1195     unsigned char * query = NULL;
1196     char * newUri = (char *)requiredUri;
1197     (void) referenceUri;
1198 #ifdef CA_INT
1199     CARemoteEndpoint_t* endpoint = NULL;
1200     CAResult_t caResult;
1201     CAToken_t caToken = NULL;
1202     CAInfo_t requestData;
1203     CARequestInfo_t requestInfo;
1204     CAGroupEndpoint_t grpEnd;
1205
1206     // To track if memory is allocated for additional header options
1207     uint8_t hdrOptionMemAlloc = 0;
1208 #endif // CA_INT
1209
1210     OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1211
1212     // Validate input parameters
1213     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1214     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1215
1216     TODO ("Need to form the final query by concatenating require and reference URI's");
1217     VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1218
1219     uint16_t uriLen = strlen(requiredUri);
1220
1221     // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1222     switch (method)
1223     {
1224         case OC_REST_GET:
1225         case OC_REST_PUT:
1226         case OC_REST_POST:
1227         case OC_REST_DELETE:
1228         case OC_REST_OBSERVE:
1229         case OC_REST_OBSERVE_ALL:
1230         case OC_REST_CANCEL_OBSERVE:
1231             break;
1232         #ifdef WITH_PRESENCE
1233         case OC_REST_PRESENCE:
1234             break;
1235         #endif
1236         default:
1237             result = OC_STACK_INVALID_METHOD;
1238             goto exit;
1239     }
1240
1241     if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1242     {
1243         goto exit;
1244     }
1245
1246     if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1247     {
1248         result = OC_STACK_INVALID_PARAM;
1249         goto exit;
1250     }
1251
1252 #ifdef WITH_PRESENCE
1253     if(method == OC_REST_PRESENCE)
1254     {
1255         // Replacing method type with GET because "presence" is a stack layer only implementation.
1256         method = OC_REST_GET;
1257         result = getQueryFromUri(requiredUri, &query, &newUri);
1258         if(query)
1259         {
1260             result = getResourceType((char *) query, &resourceType);
1261             if(resourceType)
1262             {
1263                 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1264             }
1265             else
1266             {
1267                 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1268             }
1269         }
1270         else
1271         {
1272             OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1273         }
1274         if(result != OC_STACK_OK)
1275         {
1276             goto exit;
1277         }
1278     }
1279 #endif // WITH_PRESENCE
1280
1281     requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1282     if(requestUri)
1283     {
1284         memcpy(requestUri, newUri, (uriLen + 1));
1285     }
1286     else
1287     {
1288         result = OC_STACK_NO_MEMORY;
1289         goto exit;
1290     }
1291
1292     *handle = GenerateInvocationHandle();
1293     if(!*handle)
1294     {
1295         result = OC_STACK_NO_MEMORY;
1296         goto exit;
1297     }
1298
1299 #ifdef CA_INT
1300     memset(&requestData, 0, sizeof(CAInfo_t));
1301     memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1302     memset(&grpEnd, 0, sizeof(CAGroupEndpoint_t));
1303     switch (method)
1304     {
1305         case OC_REST_GET:
1306         case OC_REST_OBSERVE:
1307         case OC_REST_OBSERVE_ALL:
1308         case OC_REST_CANCEL_OBSERVE:
1309             {
1310                 requestInfo.method = CA_GET;
1311                 break;
1312             }
1313         case OC_REST_PUT:
1314             {
1315                 requestInfo.method = CA_PUT;
1316                 break;
1317             }
1318         case OC_REST_POST:
1319             {
1320                 requestInfo.method = CA_POST;
1321                 break;
1322             }
1323         case OC_REST_DELETE:
1324             {
1325                 requestInfo.method = CA_DELETE;
1326                 break;
1327             }
1328         #ifdef WITH_PRESENCE
1329         case OC_REST_PRESENCE:
1330             //TODO-CA: What should be the CA method?
1331             break;
1332         #endif
1333         default:
1334             result = OC_STACK_INVALID_METHOD;
1335             goto exit;
1336     }
1337
1338     //High QoS is not supported
1339     if(qos == OC_HIGH_QOS)
1340     {
1341         result = OC_STACK_INVALID_PARAM;
1342         goto exit;
1343     }
1344     // TODO-CA: Handle multi-cast scenario
1345     // Create remote end point
1346     caResult = CACreateRemoteEndpoint(newUri, conType, &endpoint);
1347     // TODO-CA: Connectivity type should be passed to API
1348     endpoint->connectivityType = conType;
1349
1350     if (caResult != CA_STATUS_OK)
1351     {
1352         OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1353         goto exit;
1354     }
1355
1356     // create token
1357     caResult = CAGenerateToken(&caToken);
1358
1359     //TODO-CA Remove this temporary fix (for some reason same token is being generated)
1360     static count = 0;
1361     count++;
1362     caToken[0] += count;
1363
1364     if (caResult != CA_STATUS_OK)
1365     {
1366         OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1367         caToken = NULL;
1368         goto exit;
1369     }
1370
1371     // TODO-CA: Map QoS to the right CA msg type
1372     requestData.type = CA_MSG_NONCONFIRM;
1373     requestData.token = caToken;
1374     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1375     {
1376         result = CreateObserveHeaderOption (&(requestData.options), options,
1377                                     numOptions, OC_OBSERVE_REGISTER);
1378         if (result != OC_STACK_OK)
1379         {
1380             goto exit;
1381         }
1382         hdrOptionMemAlloc = 1;
1383         requestData.numOptions = numOptions + 1;
1384     }
1385     else
1386     {
1387         requestData.options = (CAHeaderOption_t*)options;
1388         requestData.numOptions = numOptions;
1389     }
1390     requestData.payload = (char *)request;
1391
1392     requestInfo.info = requestData;
1393
1394     // send request
1395     //TODO-CA Change This logic. Currently hardcoded to WIFI & ETHERNET
1396     //Need to support other adapter types.
1397     if(conType == (CA_WIFI | CA_ETHERNET))
1398     {
1399         //TODO-CA remove hardcoded resource uri. Instead, extract it from newUri
1400         grpEnd.connectivityType = conType;
1401         grpEnd.resourceUri = "/oc/core";
1402
1403         caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1404     }
1405     else
1406     {
1407         caResult = CASendRequest(endpoint, &requestInfo);
1408     }
1409     if (caResult != CA_STATUS_OK)
1410     {
1411         OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1412         goto exit;
1413     }
1414
1415     if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1416                              requestUri, resourceType)) != OC_STACK_OK)
1417     {
1418         result = OC_STACK_NO_MEMORY;
1419         goto exit;
1420     }
1421
1422 #else // CA_INT
1423
1424     // Generate token which will be used by OCStack to match responses received
1425     // with the request
1426     OCGenerateCoAPToken(&token);
1427
1428     if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1429             != OC_STACK_OK)
1430     {
1431         result = OC_STACK_NO_MEMORY;
1432         goto exit;
1433     }
1434
1435     // Make call to OCCoAP layer
1436     result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1437 #endif // CA_INT
1438
1439 exit:
1440     if(newUri != requiredUri)
1441     {
1442         OCFree(newUri);
1443     }
1444     if (result != OC_STACK_OK)
1445     {
1446         OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1447         FindAndDeleteClientCB(clientCB);
1448     }
1449 #ifdef CA_INT
1450     CADestroyRemoteEndpoint(endpoint);
1451     if (hdrOptionMemAlloc)
1452     {
1453         OCFree(requestData.options);
1454     }
1455 #endif // CA_INT
1456     return result;
1457 }
1458
1459 /**
1460  * Cancel a request associated with a specific @ref OCDoResource invocation.
1461  *
1462  * @param handle - Used to identify a specific OCDoResource invocation.
1463  * @param qos    - used to specify Quality of Service (read below for more info)
1464  * @param options- used to specify vendor specific header options when sending
1465  *                 explicit observe cancellation
1466  * @param numOptions- Number of header options to be included
1467  *
1468  * @return
1469  *     OC_STACK_OK               - No errors; Success
1470  *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
1471  */
1472 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1473         uint8_t numOptions)
1474 {
1475     /*
1476      * This ftn is implemented one of two ways in the case of observation:
1477      *
1478      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1479      *      Remove the callback associated on client side.
1480      *      When the next notification comes in from server,
1481      *      reply with RESET message to server.
1482      *      Keep in mind that the server will react to RESET only
1483      *      if the last notification was sent ans CON
1484      *
1485      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1486      *      and it is associated with an observe request
1487      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1488      *      Send CON Observe request to server with
1489      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1490      *      Remove the callback associated on client side.
1491      */
1492     OCStackResult ret = OC_STACK_OK;
1493 #ifdef CA_INT
1494     CARemoteEndpoint_t* endpoint = NULL;
1495     CAResult_t caResult;
1496     CAInfo_t requestData;
1497     CARequestInfo_t requestInfo;
1498     // Track if memory is allocated for additional header options
1499     uint8_t hdrOptionMemAlloc = 0;
1500 #endif // CA_INT
1501
1502     if(!handle) {
1503         return OC_STACK_INVALID_PARAM;
1504     }
1505
1506     OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1507
1508     ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1509
1510     if(clientCB) {
1511         switch (clientCB->method)
1512         {
1513             case OC_REST_OBSERVE:
1514             case OC_REST_OBSERVE_ALL:
1515                 #ifdef CA_INT
1516                 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1517                                                   &endpoint);
1518                 endpoint->connectivityType = CA_WIFI;
1519                 if (caResult != CA_STATUS_OK)
1520                 {
1521                     OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1522                     return OC_STACK_ERROR;
1523                 }
1524
1525                 memset(&requestData, 0, sizeof(CAInfo_t));
1526                 // TODO-CA: Map QoS to the right CA msg type
1527                 requestData.type = CA_MSG_NONCONFIRM;
1528                 requestData.token = clientCB->token;
1529                 if (CreateObserveHeaderOption (&(requestData.options),
1530                             options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1531                 {
1532                     return OC_STACK_ERROR;
1533                 }
1534                 hdrOptionMemAlloc = 1;
1535                 requestData.numOptions = numOptions + 1;
1536                 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1537                 requestInfo.method = CA_GET;
1538                 requestInfo.info = requestData;
1539                 // send request
1540                 caResult = CASendRequest(endpoint, &requestInfo);
1541                 if (caResult != CA_STATUS_OK)
1542                 {
1543                     OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1544                 }
1545                 if(caResult == CA_STATUS_OK)
1546                 {
1547                     ret = OC_STACK_OK;
1548                 }
1549                 #else // CA_INT
1550                 if(qos == OC_HIGH_QOS)
1551                 {
1552                     ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1553                             &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1554                             numOptions);
1555                 }
1556                 else
1557                 {
1558                     FindAndDeleteClientCB(clientCB);
1559                 }
1560                 break;
1561                 #endif // CA_INT
1562             #ifdef WITH_PRESENCE
1563             case OC_REST_PRESENCE:
1564                 FindAndDeleteClientCB(clientCB);
1565                 break;
1566             #endif
1567             default:
1568                 return OC_STACK_INVALID_METHOD;
1569         }
1570     }
1571 #ifdef CA_INT
1572     CADestroyRemoteEndpoint(endpoint);
1573     if (hdrOptionMemAlloc)
1574     {
1575         OCFree(requestData.options);
1576     }
1577 #endif // CA_INT
1578
1579     return ret;
1580 }
1581 #ifdef WITH_PRESENCE
1582 OCStackResult OCProcessPresence()
1583 {
1584     OCStackResult result = OC_STACK_OK;
1585     uint8_t ipAddr[4] = { 0 };
1586     uint16_t port = 0;
1587
1588     OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1589     ClientCB* cbNode = NULL;
1590     OCDevAddr dst;
1591     OCClientResponse clientResponse;
1592     OCResponse * response = NULL;
1593
1594     LL_FOREACH(cbList, cbNode) {
1595         if(OC_REST_PRESENCE == cbNode->method)
1596         {
1597             if(cbNode->presence)
1598             {
1599                 uint32_t now = GetTime(0);
1600                 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1601                 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1602
1603
1604                 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1605                 {
1606                     goto exit;
1607                 }
1608
1609                 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1610                     OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1611                             cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1612                 }
1613
1614                 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1615                 {
1616                     OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1617                     if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1618                     {
1619                         OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1620                                 &dst);
1621                         result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1622                                 (OCDevAddr *) &dst, 0, NULL);
1623                         if(result != OC_STACK_OK)
1624                         {
1625                             goto exit;
1626                         }
1627                         result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1628                                 &cbNode->token, &clientResponse, NULL);
1629                         if(result != OC_STACK_OK)
1630                         {
1631                             goto exit;
1632                         }
1633
1634                         // Increment the TTLLevel (going to a next state), so we don't keep
1635                         // sending presence notification to client.
1636                         cbNode->presence->TTLlevel++;
1637                         OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1638                                                 cbNode->presence->TTLlevel);
1639                     }
1640                     else
1641                     {
1642                         result = OC_STACK_INVALID_IP;
1643                         goto exit;
1644                     }
1645                     HandleStackResponses(response);
1646                 }
1647                 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1648                 {
1649                     OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1650                     OCCoAPToken token;
1651                     OCGenerateCoAPToken(&token);
1652                     result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1653                             &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1654                     if(result != OC_STACK_OK)
1655                     {
1656                         goto exit;
1657                     }
1658                     cbNode->presence->TTLlevel++;
1659                     OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1660                 }
1661             }
1662         }
1663     }
1664 exit:
1665     if (result != OC_STACK_OK)
1666     {
1667         OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1668     }
1669     return result;
1670 }
1671 #endif
1672
1673 /**
1674  * Called in main loop of OC client or server.  Allows low-level processing of
1675  * stack services.
1676  *
1677  * @return
1678  *     OC_STACK_OK    - no errors
1679  *     OC_STACK_ERROR - stack process error
1680  */
1681 OCStackResult OCProcess() {
1682
1683     OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1684     #ifdef WITH_PRESENCE
1685     OCProcessPresence();
1686     #endif
1687 #ifdef CA_INT
1688     CAHandleRequestResponse();
1689 #else
1690     OCProcessCoAP();
1691 #endif // CA_INT
1692
1693     return OC_STACK_OK;
1694 }
1695
1696 #ifdef WITH_PRESENCE
1697 /**
1698  * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1699  * presence notifications to clients via multicast. Once this API has been called with a success,
1700  * clients may query for this server's presence and this server's stack will respond via multicast.
1701  *
1702  * Server can call this function when it comes online for the first time, or when it comes back
1703  * online from offline mode, or when it re enters network.
1704  *
1705  * @param ttl - Time To Live in seconds
1706  * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1707  *
1708  * @return
1709  *     OC_STACK_OK      - No errors; Success
1710  */
1711 OCStackResult OCStartPresence(const uint32_t ttl)
1712 {
1713     OCChangeResourceProperty(
1714             &(((OCResource *)presenceResource.handle)->resourceProperties),
1715             OC_ACTIVE, 1);
1716
1717     if(ttl > 0)
1718     {
1719         presenceResource.presenceTTL = ttl;
1720     }
1721
1722     if(OC_PRESENCE_UNINITIALIZED == presenceState)
1723     {
1724         OCDevAddr multiCastAddr;
1725         OCCoAPToken token;
1726
1727         presenceState = OC_PRESENCE_INITIALIZED;
1728         OCGenerateCoAPToken(&token);
1729         OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1730 #ifdef CA_INT
1731         CAAddress_t addressInfo;
1732         strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
1733         addressInfo.IP.port = 5298;
1734
1735         CAToken_t caToken = NULL;
1736        CAGenerateToken(&caToken);
1737
1738         AddCAObserver(OC_PRESENCE_URI, NULL, 0, &token,
1739                 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
1740                 &addressInfo, CA_WIFI, caToken);
1741 #else
1742         //add the presence observer
1743         AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1744             (OCResource *)presenceResource.handle, OC_LOW_QOS);
1745 #endif
1746     }
1747
1748     // Each time OCStartPresence is called
1749     // a different random 32-bit integer number is used
1750     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1751
1752     return SendPresenceNotification(NULL);
1753 }
1754
1755 /**
1756  * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1757  * presence notifications to clients via multicast. Once this API has been called with a success,
1758  * this server's stack will not respond to clients querying for this server's presence.
1759  *
1760  * Server can call this function when it is terminating, going offline, or when going
1761  * away from network.
1762  *
1763  * @return
1764  *     OC_STACK_OK      - No errors; Success
1765  */
1766 OCStackResult OCStopPresence()
1767 {
1768     OCStackResult result = OC_STACK_ERROR;
1769     //make resource inactive
1770     result = OCChangeResourceProperty(
1771             &(((OCResource *) presenceResource.handle)->resourceProperties),
1772             OC_ACTIVE, 0);
1773     result = SendPresenceNotification(NULL);
1774
1775     return result;
1776 }
1777 #endif
1778
1779
1780 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1781 {
1782     defaultDeviceHandler = entityHandler;
1783
1784     return OC_STACK_OK;
1785 }
1786
1787 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
1788 {
1789     OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
1790
1791     if(myStackMode == OC_CLIENT)
1792     {
1793         return OC_STACK_ERROR;
1794     }
1795
1796     return SaveDeviceInfo(deviceInfo);
1797 }
1798
1799 /**
1800  * Create a resource
1801  *
1802  * @param handle - pointer to handle to newly created resource.  Set by ocstack.  Used to refer to resource
1803  * @param resourceTypeName - name of resource type.  Example: "core.led"
1804  * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
1805  * @param uri - URI of the resource.  Example:  "/a/led"
1806  * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1807  *                        NULL for default entity handler
1808  * @param resourceProperties - properties supported by resource.  Example: OC_DISCOVERABLE|OC_OBSERVABLE
1809  *
1810  * @return
1811  *     OC_STACK_OK    - no errors
1812  *     OC_STACK_ERROR - stack process error
1813  */
1814 OCStackResult OCCreateResource(OCResourceHandle *handle,
1815         const char *resourceTypeName,
1816         const char *resourceInterfaceName,
1817         const char *uri, OCEntityHandler entityHandler,
1818         uint8_t resourceProperties) {
1819
1820     OCResource *pointer = NULL;
1821     char *str = NULL;
1822     size_t size;
1823     OCStackResult result = OC_STACK_ERROR;
1824
1825     OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1826
1827     if(myStackMode == OC_CLIENT)
1828     {
1829         return result;
1830     }
1831     // Validate parameters
1832     if(!uri || (strlen(uri) == 0))
1833     {
1834         OC_LOG(ERROR, TAG, PCF("URI is invalid"));
1835         return OC_STACK_INVALID_URI;
1836     }
1837     // Is it presented during resource discovery?
1838     if (!handle || !resourceTypeName) {
1839         OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1840         return OC_STACK_INVALID_PARAM;
1841     }
1842
1843     if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1844         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1845     }
1846
1847     // Make sure resourceProperties bitmask has allowed properties specified
1848     if (resourceProperties
1849             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1850         OC_LOG(ERROR, TAG, PCF("Invalid property"));
1851         return OC_STACK_INVALID_PARAM;
1852     }
1853
1854     // If the headResource is NULL, then no resources have been created...
1855     pointer = headResource;
1856     if (pointer) {
1857         // At least one resources is in the resource list, so we need to search for
1858         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
1859         while (pointer) {
1860             if (strcmp(uri, pointer->uri) == 0) {
1861                 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1862                 return OC_STACK_INVALID_PARAM;
1863             }
1864             pointer = pointer->next;
1865         }
1866     }
1867     // Create the pointer and insert it into the resource list
1868     pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1869     if (!pointer) {
1870         goto exit;
1871     }
1872     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1873
1874     insertResource(pointer);
1875
1876     // Set the uri
1877     size = strlen(uri) + 1;
1878     str = (char *) OCMalloc(size);
1879     if (!str) {
1880         goto exit;
1881     }
1882     strncpy(str, uri, size);
1883     pointer->uri = str;
1884
1885     // Set properties.  Set OC_ACTIVE
1886     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1887             | OC_ACTIVE);
1888
1889     // Add the resourcetype to the resource
1890     result = BindResourceTypeToResource(pointer, resourceTypeName);
1891     if (result != OC_STACK_OK) {
1892         OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1893         goto exit;
1894     }
1895
1896     // Add the resourceinterface to the resource
1897     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1898     if (result != OC_STACK_OK) {
1899         OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1900         goto exit;
1901     }
1902
1903     // If an entity handler has been passed, attach it to the newly created
1904     // resource.  Otherwise, set the default entity handler.
1905     if (entityHandler)
1906     {
1907         pointer->entityHandler = entityHandler;
1908     }
1909     else
1910     {
1911         pointer->entityHandler = defaultResourceEHandler;
1912     }
1913
1914     *handle = pointer;
1915     result = OC_STACK_OK;
1916
1917     #ifdef WITH_PRESENCE
1918     if(presenceResource.handle)
1919     {
1920         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1921         SendPresenceNotification(pointer->rsrcType);
1922     }
1923     #endif
1924 exit:
1925     if (result != OC_STACK_OK)
1926     {
1927         // Deep delete of resource and other dynamic elements that it contains
1928         deleteResource(pointer);
1929         OCFree(str);
1930     }
1931     return result;
1932 }
1933
1934
1935
1936 /**
1937  * Create a resource. with host ip address for remote resource
1938  *
1939  * @param handle - pointer to handle to newly created resource.  Set by ocstack.
1940  *                 Used to refer to resource
1941  * @param resourceTypeName - name of resource type.  Example: "core.led"
1942  * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
1943  * @param host - HOST address of the remote resource.  Example:  "coap://xxx.xxx.xxx.xxx:xxxxx"
1944  * @param uri - URI of the resource.  Example:  "/a/led"
1945  * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1946  *                        NULL for default entity handler
1947  * @param resourceProperties - properties supported by resource.
1948  *                             Example: OC_DISCOVERABLE|OC_OBSERVABLE
1949  *
1950  * @return
1951  *     OC_STACK_OK    - no errors
1952  *     OC_STACK_ERROR - stack process error
1953  */
1954
1955 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1956         const char *resourceTypeName,
1957         const char *resourceInterfaceName,
1958         const char *host,
1959         const char *uri,
1960         OCEntityHandler entityHandler,
1961         uint8_t resourceProperties)
1962 {
1963     char *str = NULL;
1964     size_t size;
1965     OCStackResult result = OC_STACK_ERROR;
1966
1967     result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1968                                 uri, entityHandler, resourceProperties);
1969
1970     if (result != OC_STACK_ERROR)
1971     {
1972         // Set the uri
1973         size = strlen(host) + 1;
1974         str = (char *) OCMalloc(size);
1975         if (!str)
1976         {
1977             return OC_STACK_ERROR;
1978         }
1979         strncpy(str, host, size);
1980         ((OCResource *) *handle)->host = str;
1981     }
1982
1983     return result;
1984 }
1985
1986 /**
1987  * Add a resource to a collection resource.
1988  *
1989  * @param collectionHandle - handle to the collection resource
1990  * @param resourceHandle - handle to resource to be added to the collection resource
1991  *
1992  * @return
1993  *     OC_STACK_OK    - no errors
1994  *     OC_STACK_ERROR - stack process error
1995  *     OC_STACK_INVALID_PARAM - invalid collectionhandle
1996  */
1997 OCStackResult OCBindResource(
1998         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1999     OCResource *resource;
2000     uint8_t i;
2001
2002     OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2003
2004     // Validate parameters
2005     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2006     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2007     // Container cannot contain itself
2008     if (collectionHandle == resourceHandle) {
2009         OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2010         return OC_STACK_INVALID_PARAM;
2011     }
2012
2013     // Use the handle to find the resource in the resource linked list
2014     resource = findResource((OCResource *) collectionHandle);
2015     if (!resource) {
2016         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2017         return OC_STACK_INVALID_PARAM;
2018     }
2019
2020     // Look for an open slot to add add the child resource.
2021     // If found, add it and return success
2022     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2023         if (!resource->rsrcResources[i]) {
2024             resource->rsrcResources[i] = (OCResource *) resourceHandle;
2025             OC_LOG(INFO, TAG, PCF("resource bound"));
2026             return OC_STACK_OK;
2027         }
2028     }
2029
2030     #ifdef WITH_PRESENCE
2031     if(presenceResource.handle)
2032     {
2033         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2034         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2035     }
2036     #endif
2037
2038     // Unable to add resourceHandle, so return error
2039     return OC_STACK_ERROR;
2040 }
2041
2042 /**
2043  * Remove a resource from a collection resource.
2044  *
2045  * @param collectionHandle - handle to the collection resource
2046  * @param resourceHandle - handle to resource to be added to the collection resource
2047  *
2048  * @return
2049  *     OC_STACK_OK    - no errors
2050  *     OC_STACK_ERROR - stack process error
2051  *     OC_STACK_INVALID_PARAM - invalid collectionHandle
2052  */
2053 OCStackResult OCUnBindResource(
2054         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2055     OCResource *resource;
2056     uint8_t i;
2057
2058     OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2059
2060     // Validate parameters
2061     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2062     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2063     // Container cannot contain itself
2064     if (collectionHandle == resourceHandle) {
2065         OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2066         return OC_STACK_INVALID_PARAM;
2067     }
2068
2069     // Use the handle to find the resource in the resource linked list
2070     resource = findResource((OCResource *) collectionHandle);
2071     if (!resource) {
2072         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2073         return OC_STACK_INVALID_PARAM;
2074     }
2075
2076     // Look for an open slot to add add the child resource.
2077     // If found, add it and return success
2078     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2079         if (resourceHandle == resource->rsrcResources[i]) {
2080             resource->rsrcResources[i] = (OCResource *) NULL;
2081             OC_LOG(INFO, TAG, PCF("resource unbound"));
2082             return OC_STACK_OK;
2083         }
2084     }
2085
2086     OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2087
2088     #ifdef WITH_PRESENCE
2089     if(presenceResource.handle)
2090     {
2091         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2092         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2093     }
2094     #endif
2095
2096     // Unable to add resourceHandle, so return error
2097     return OC_STACK_ERROR;
2098 }
2099
2100 OCStackResult BindResourceTypeToResource(OCResource* resource,
2101                                             const char *resourceTypeName)
2102 {
2103     OCResourceType *pointer = NULL;
2104     char *str = NULL;
2105     size_t size;
2106     OCStackResult result = OC_STACK_ERROR;
2107
2108     OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2109
2110     // Validate parameters
2111     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2112     // TODO:  Does resource attribute resentation really have to be maintained in stack?
2113     // Is it presented during resource discovery?
2114
2115     TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2116
2117     // Create the resourcetype and insert it into the resource list
2118     pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2119     if (!pointer) {
2120         goto exit;
2121     }
2122
2123     // Set the resourceTypeName
2124     size = strlen(resourceTypeName) + 1;
2125     str = (char *) OCMalloc(size);
2126     if (!str) {
2127         goto exit;
2128     }
2129     strncpy(str, resourceTypeName, size);
2130     pointer->resourcetypename = str;
2131
2132     insertResourceType(resource, pointer);
2133     result = OC_STACK_OK;
2134
2135     exit: if (result != OC_STACK_OK) {
2136         OCFree(pointer);
2137         OCFree(str);
2138     }
2139
2140     return result;
2141 }
2142
2143 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2144         const char *resourceInterfaceName)
2145 {
2146     OCResourceInterface *pointer = NULL;
2147     char *str = NULL;
2148     size_t size;
2149     OCStackResult result = OC_STACK_ERROR;
2150
2151     OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2152
2153     // Validate parameters
2154     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2155
2156     TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2157
2158     // Create the resourceinterface and insert it into the resource list
2159     pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2160     if (!pointer) {
2161         goto exit;
2162     }
2163
2164     // Set the resourceinterface name
2165     size = strlen(resourceInterfaceName) + 1;
2166     str = (char *) OCMalloc(size);
2167     if (!str) {
2168         goto exit;
2169     }
2170     strncpy(str, resourceInterfaceName, size);
2171     pointer->name = str;
2172
2173     // Bind the resourceinterface to the resource
2174     insertResourceInterface(resource, pointer);
2175
2176     result = OC_STACK_OK;
2177
2178     exit: if (result != OC_STACK_OK) {
2179         OCFree(pointer);
2180         OCFree(str);
2181     }
2182
2183     return result;
2184 }
2185
2186 /**
2187  * Bind a resourcetype to a resource.
2188  *
2189  * @param handle - handle to the resource
2190  * @param resourceTypeName - name of resource type.  Example: "core.led"
2191  *
2192  * @return
2193  *     OC_STACK_OK    - no errors
2194  *     OC_STACK_ERROR - stack process error
2195  */
2196 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2197         const char *resourceTypeName) {
2198
2199     OCStackResult result = OC_STACK_ERROR;
2200     OCResource *resource;
2201
2202     // Make sure resource exists
2203     resource = findResource((OCResource *) handle);
2204     if (!resource) {
2205         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2206         return OC_STACK_ERROR;
2207     }
2208
2209     // call internal function
2210     result = BindResourceTypeToResource(resource, resourceTypeName);
2211
2212     #ifdef WITH_PRESENCE
2213     if(presenceResource.handle)
2214     {
2215         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2216         SendPresenceNotification(resource->rsrcType);
2217     }
2218     #endif
2219
2220     return result;
2221 }
2222
2223 /**
2224  * Bind a resourceinterface to a resource.
2225  *
2226  * @param handle - handle to the resource
2227  * @param resourceInterfaceName - name of resource interface.  Example: "oc.mi.b"
2228  *
2229  * @return
2230  *     OC_STACK_OK    - no errors
2231  *     OC_STACK_ERROR - stack process error
2232  */
2233
2234 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2235         const char *resourceInterfaceName) {
2236
2237     OCStackResult result = OC_STACK_ERROR;
2238     OCResource *resource;
2239
2240     // Make sure resource exists
2241     resource = findResource((OCResource *) handle);
2242     if (!resource) {
2243         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2244         return OC_STACK_ERROR;
2245     }
2246
2247     // call internal function
2248     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2249
2250     #ifdef WITH_PRESENCE
2251     if(presenceResource.handle)
2252     {
2253         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2254         SendPresenceNotification(resource->rsrcType);
2255     }
2256     #endif
2257
2258     return result;
2259 }
2260
2261 /**
2262  * Get the number of resources that have been created in the stack.
2263  *
2264  * @param numResources - pointer to count variable
2265  *
2266  * @return
2267  *     OC_STACK_OK    - no errors
2268  *     OC_STACK_ERROR - stack process error
2269
2270  */
2271 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2272     OCResource *pointer = headResource;
2273
2274     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2275     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2276     *numResources = 0;
2277     while (pointer) {
2278         *numResources = *numResources + 1;
2279         pointer = pointer->next;
2280     }
2281     return OC_STACK_OK;
2282 }
2283
2284 /**
2285  * Get a resource handle by index.
2286  *
2287  * @param index - index of resource, 0 to Count - 1
2288  *
2289  * @return
2290  *    Resource handle - if found
2291  *    NULL - if not found
2292  */
2293 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2294     OCResource *pointer = headResource;
2295     uint8_t i = 0;
2296
2297     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2298
2299     // Iterate through the list
2300     while ((i < index) && pointer) {
2301         i++;
2302         pointer = pointer->next;
2303     }
2304     return (OCResourceHandle) pointer;
2305 }
2306
2307 /**
2308  * Delete resource specified by handle.  Deletes resource and all resourcetype and resourceinterface
2309  * linked lists.
2310  *
2311  * @param handle - handle of resource to be deleted
2312  *
2313  * @return
2314  *     OC_STACK_OK              - no errors
2315  *     OC_STACK_ERROR           - stack process error
2316  *     OC_STACK_NO_RESOURCE     - resource not found
2317  *     OC_STACK_INVALID_PARAM   - invalid param
2318  */
2319 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2320     OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2321
2322     if (!handle) {
2323         OC_LOG(ERROR, TAG, PCF("Invalid param"));
2324         return OC_STACK_INVALID_PARAM;
2325     }
2326
2327     OCResource *resource = findResource((OCResource *) handle);
2328     if (resource == NULL) {
2329         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2330         return OC_STACK_NO_RESOURCE;
2331     }
2332
2333     if (deleteResource((OCResource *) handle) == 0) {
2334         OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2335         return OC_STACK_ERROR;
2336     }
2337
2338     return OC_STACK_OK;
2339 }
2340
2341 /**
2342  * Get the URI of the resource specified by handle.
2343  *
2344  * @param handle - handle of resource
2345  * @return
2346  *    URI string - if resource found
2347  *    NULL - resource not found
2348  */
2349 const char *OCGetResourceUri(OCResourceHandle handle) {
2350     OCResource *resource;
2351     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2352
2353     resource = findResource((OCResource *) handle);
2354     if (resource) {
2355         return resource->uri;
2356     }
2357     return (const char *) NULL;
2358 }
2359
2360 /**
2361  * Get the properties of the resource specified by handle.
2362  * NOTE: that after a resource is created, the OC_ACTIVE property is set
2363  * for the resource by the stack.
2364  *
2365  * @param handle - handle of resource
2366  * @return
2367  *    property bitmap - if resource found
2368  *    NULL - resource not found
2369  */
2370 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2371     OCResource *resource;
2372     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2373
2374     resource = findResource((OCResource *) handle);
2375     if (resource) {
2376         return resource->resourceProperties;
2377     }
2378     return 0;
2379 }
2380
2381 /**
2382  * Get the number of resource types of the resource.
2383  *
2384  * @param handle - handle of resource
2385  * @param numResourceTypes - pointer to count variable
2386  *
2387  * @return
2388  *     OC_STACK_OK    - no errors
2389  *     OC_STACK_ERROR - stack process error
2390  */
2391 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2392         uint8_t *numResourceTypes) {
2393     OCResource *resource;
2394     OCResourceType *pointer;
2395
2396     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2397     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2398     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2399
2400     *numResourceTypes = 0;
2401
2402     resource = findResource((OCResource *) handle);
2403     if (resource) {
2404         pointer = resource->rsrcType;
2405         while (pointer) {
2406             *numResourceTypes = *numResourceTypes + 1;
2407             pointer = pointer->next;
2408         }
2409     }
2410     return OC_STACK_OK;
2411 }
2412
2413 /**
2414  * Get name of resource type of the resource.
2415  *
2416  * @param handle - handle of resource
2417  * @param index - index of resource, 0 to Count - 1
2418  *
2419  * @return
2420  *    resource type name - if resource found
2421  *    NULL - resource not found
2422  */
2423 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2424     OCResourceType *resourceType;
2425
2426     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2427
2428     resourceType = findResourceTypeAtIndex(handle, index);
2429     if (resourceType) {
2430         return resourceType->resourcetypename;
2431     }
2432     return (const char *) NULL;
2433 }
2434
2435
2436
2437 /**
2438  * Get the number of resource interfaces of the resource.
2439  *
2440  * @param handle - handle of resource
2441  * @param numResources - pointer to count variable
2442  *
2443  * @return
2444  *     OC_STACK_OK    - no errors
2445  *     OC_STACK_ERROR - stack process error
2446  */
2447 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2448         uint8_t *numResourceInterfaces) {
2449     OCResourceInterface *pointer;
2450     OCResource *resource;
2451
2452     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2453
2454     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2455     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2456
2457     *numResourceInterfaces = 0;
2458     resource = findResource((OCResource *) handle);
2459     if (resource) {
2460         pointer = resource->rsrcInterface;
2461         while (pointer) {
2462             *numResourceInterfaces = *numResourceInterfaces + 1;
2463             pointer = pointer->next;
2464         }
2465     }
2466     return OC_STACK_OK;
2467 }
2468
2469 /**
2470  * Get name of resource interface of the resource.
2471  *
2472  * @param handle - handle of resource
2473  * @param index - index of resource, 0 to Count - 1
2474  *
2475  * @return
2476  *    resource interface name - if resource found
2477  *    NULL - resource not found
2478  */
2479 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2480     OCResourceInterface *resourceInterface;
2481
2482     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2483
2484     resourceInterface = findResourceInterfaceAtIndex(handle, index);
2485     if (resourceInterface) {
2486         return resourceInterface->name;
2487     }
2488     return (const char *) NULL;
2489 }
2490
2491 /**
2492  * Get resource handle from the collection resource by index.
2493  *
2494  * @param collectionHandle - handle of collection resource
2495  * @param index - index of contained resource, 0 to Count - 1
2496  *
2497  * @return
2498  *    handle to resource - if resource found
2499  *    NULL - resource not found
2500  */
2501 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2502         uint8_t index) {
2503     OCResource *resource;
2504
2505     OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2506
2507     if (index >= MAX_CONTAINED_RESOURCES) {
2508         return NULL;
2509     }
2510
2511     resource = findResource((OCResource *) collectionHandle);
2512     if (!resource) {
2513         return NULL;
2514     }
2515
2516     return resource->rsrcResources[index];
2517 }
2518
2519 /**
2520  * Bind an entity handler to the resource.
2521  *
2522  * @param handle - handle to the resource that the contained resource is to be bound
2523  * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2524  * @return
2525  *     OC_STACK_OK    - no errors
2526  *     OC_STACK_ERROR - stack process error
2527  */
2528 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2529         OCEntityHandler entityHandler) {
2530     OCResource *resource;
2531
2532     OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2533
2534     // Validate parameters
2535     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2536     //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2537
2538     // Use the handle to find the resource in the resource linked list
2539     resource = findResource((OCResource *)handle);
2540     if (!resource) {
2541         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2542         return OC_STACK_ERROR;
2543     }
2544
2545     // Bind the handler
2546     resource->entityHandler = entityHandler;
2547
2548     #ifdef WITH_PRESENCE
2549     if(presenceResource.handle)
2550     {
2551         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2552         SendPresenceNotification(resource->rsrcType);
2553     }
2554     #endif
2555
2556     return OC_STACK_OK;
2557 }
2558
2559 /**
2560  * Get the entity handler for a resource.
2561  *
2562  * @param handle - handle of resource
2563  *
2564  * @return
2565  *    entity handler - if resource found
2566  *    NULL - resource not found
2567  */
2568 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2569     OCResource *resource;
2570
2571     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2572
2573     // Use the handle to find the resource in the resource linked list
2574     resource = findResource((OCResource *)handle);
2575     if (!resource) {
2576         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2577         return NULL;
2578     }
2579
2580     // Bind the handler
2581     return resource->entityHandler;
2582 }
2583
2584 void incrementSequenceNumber(OCResource * resPtr)
2585 {
2586     // Increment the sequence number
2587     resPtr->sequenceNum += 1;
2588     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2589     {
2590         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2591     }
2592     return;
2593 }
2594
2595 /**
2596  * Notify Presence subscribers that a resource has been modified
2597  *
2598  * @param resourceType - Handle to the resourceType linked list of resource
2599  *                       that was modified.
2600  * @param qos          - Quality Of Service
2601  *
2602  */
2603 #ifdef WITH_PRESENCE
2604 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2605 {
2606     OCResource *resPtr = NULL;
2607     OCStackResult result;
2608     OCMethod method = OC_REST_PRESENCE;
2609     uint32_t maxAge = 0;
2610     resPtr = findResource((OCResource *) presenceResource.handle);
2611     if(NULL == resPtr)
2612     {
2613         return OC_STACK_NO_RESOURCE;
2614     }
2615     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2616     {
2617         maxAge = presenceResource.presenceTTL;
2618     }
2619     else
2620     {
2621         maxAge = 0;
2622     }
2623
2624     result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2625     return result;
2626 }
2627 #endif // WITH_PRESENCE
2628 /**
2629  * Notify observers that an observed value has changed.
2630  *
2631  * @param handle - handle of resource
2632  *
2633  * @return
2634  *     OC_STACK_OK    - no errors
2635  *     OC_STACK_NO_RESOURCE - invalid resource handle
2636  *     OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2637  */
2638 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2639
2640     OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2641
2642     OCResource *resPtr = NULL;
2643     OCStackResult result;
2644     OCMethod method = OC_REST_NOMETHOD;
2645     uint32_t maxAge = 0;
2646
2647     OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2648     #ifdef WITH_PRESENCE
2649     if(handle == presenceResource.handle)
2650     {
2651         return OC_STACK_OK;
2652     }
2653     #endif // WITH_PRESENCE
2654     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2655
2656     // Verify that the resource exists
2657     resPtr = findResource ((OCResource *) handle);
2658     if (NULL == resPtr)
2659     {
2660         return OC_STACK_NO_RESOURCE;
2661     }
2662     else
2663     {
2664         //only increment in the case of regular observing (not presence)
2665         incrementSequenceNumber(resPtr);
2666         method = OC_REST_OBSERVE;
2667         maxAge = MAX_OBSERVE_AGE;
2668         #ifdef WITH_PRESENCE
2669         result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2670         #else
2671         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2672         #endif
2673         return result;
2674     }
2675 }
2676
2677 OCStackResult
2678 OCNotifyListOfObservers (OCResourceHandle handle,
2679                          OCObservationId  *obsIdList,
2680                          uint8_t          numberOfIds,
2681                          unsigned char    *notificationJSONPayload,
2682                          OCQualityOfService qos)
2683 {
2684     OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2685
2686     OCResource *resPtr = NULL;
2687     //TODO: we should allow the server to define this
2688     uint32_t maxAge = MAX_OBSERVE_AGE;
2689
2690     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2691     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2692     VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2693
2694     // Verify that the resource exists
2695     resPtr = findResource ((OCResource *) handle);
2696     if (NULL == resPtr || myStackMode == OC_CLIENT)
2697     {
2698         return OC_STACK_NO_RESOURCE;
2699     }
2700     else
2701     {
2702         incrementSequenceNumber(resPtr);
2703     }
2704     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2705             notificationJSONPayload, maxAge, qos));
2706 }
2707
2708 /**
2709  * Send a response to a request.
2710  * The response can be a regular, slow, or block (i.e. a response that
2711  * is too large to be sent in a single PDU and must span multiple transmissions)
2712  *
2713  * @param response - pointer to structure that contains response parameters
2714  *
2715  * @return
2716  *     OC_STACK_OK                         - No errors; Success
2717  *     OC_STACK_INVALID_PARAM              - Invalid pointer to OCServerResponse
2718  *     OC_STACK_INVALID_REQUEST_HANDLE     - Request handle not found
2719  *     OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2720  *                                           persistent response buffer is necessary
2721  */
2722 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2723 {
2724     OCStackResult result = OC_STACK_ERROR;
2725     OCServerRequest *serverRequest = NULL;
2726
2727     OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2728
2729     // Validate input parameters
2730     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2731     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2732
2733     // TODO: Placeholder for creating a response entry when implementing
2734     // block transfer feature
2735
2736     // If a response payload is present, check if block transfer is required
2737     if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2738             (const char *)ehResponse->payload, ehResponse->payloadSize))
2739     {
2740         OC_LOG(INFO, TAG, PCF("Block transfer required"));
2741
2742         // Persistent response buffer is needed for block transfer
2743         if (!ehResponse->persistentBufferFlag)
2744         {
2745             OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2746             return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2747         }
2748         // TODO: Placeholder for block transfer handling
2749         // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2750             // when implementing the block transfer feature
2751     }
2752     else
2753     {
2754         // Normal response
2755         // Get pointer to request info
2756         serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2757         if(serverRequest)
2758         {
2759             result = serverRequest->ehResponseHandler(ehResponse);
2760         }
2761     }
2762     return result;
2763 }
2764
2765 /**
2766  * Cancel a response.  Applies to a block response
2767  *
2768  * @param responseHandle - response handle set by stack in OCServerResponse after
2769  *                         OCDoResponse is called
2770  *
2771  * @return
2772  *     OC_STACK_OK               - No errors; Success
2773  *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
2774  */
2775 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2776 {
2777     OCStackResult result = OC_STACK_NOTIMPL;
2778
2779     OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2780
2781     // TODO: validate response handle
2782
2783     return result;
2784 }
2785
2786 //-----------------------------------------------------------------------------
2787 // Private internal function definitions
2788 //-----------------------------------------------------------------------------
2789 /**
2790  * Generate handle of OCDoResource invocation for callback management.
2791  */
2792 static OCDoHandle GenerateInvocationHandle()
2793 {
2794     OCDoHandle handle = NULL;
2795     // Generate token here, it will be deleted when the transaction is deleted
2796     handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2797     if (handle)
2798     {
2799         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2800     }
2801
2802     return handle;
2803 }
2804 #ifdef WITH_PRESENCE
2805 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2806         OCResourceProperty resourceProperties, uint8_t enable)
2807 {
2808     if (resourceProperties
2809             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2810         OC_LOG(ERROR, TAG, PCF("Invalid property"));
2811         return OC_STACK_INVALID_PARAM;
2812     }
2813     if(!enable)
2814     {
2815         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2816     }
2817     else
2818     {
2819         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2820     }
2821     return OC_STACK_OK;
2822 }
2823 #endif
2824
2825 /**
2826  * Initialize resource data structures, variables, etc.
2827  */
2828 OCStackResult initResources() {
2829     OCStackResult result = OC_STACK_OK;
2830     // Init application resource vars
2831     headResource = NULL;
2832     // Init Virtual Resources
2833     #ifdef WITH_PRESENCE
2834     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2835     //presenceResource.token = OCGenerateCoAPToken();
2836     result = OCCreateResource(&presenceResource.handle,
2837             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2838             "core.r",
2839             OC_PRESENCE_URI,
2840             NULL,
2841             OC_OBSERVABLE);
2842     //make resource inactive
2843     result = OCChangeResourceProperty(
2844             &(((OCResource *) presenceResource.handle)->resourceProperties),
2845             OC_ACTIVE, 0);
2846     #endif
2847     return result;
2848 }
2849
2850 /**
2851  * Add a resource to the end of the linked list of resources.
2852  *
2853  * @param resource - resource to be added
2854  */
2855 void insertResource(OCResource *resource) {
2856     OCResource *pointer;
2857
2858     if (!headResource) {
2859         headResource = resource;
2860     } else {
2861         pointer = headResource;
2862
2863         while (pointer->next) {
2864             pointer = pointer->next;
2865         }
2866         pointer->next = resource;
2867     }
2868     resource->next = NULL;
2869 }
2870
2871 /**
2872  * Find a resource in the linked list of resources.
2873  *
2874  * @param resource - resource to be found
2875  * @return
2876  *     NULL                - resource not found
2877  *     pointer to resource - pointer to resource that was found in the linked list
2878  */
2879 OCResource *findResource(OCResource *resource) {
2880     OCResource *pointer = headResource;
2881
2882     while (pointer) {
2883         if (pointer == resource) {
2884             return resource;
2885         }
2886         pointer = pointer->next;
2887     }
2888     return NULL;
2889 }
2890
2891 void deleteAllResources()
2892 {
2893     OCResource *pointer = headResource;
2894     OCResource *temp;
2895
2896     while (pointer)
2897     {
2898         temp = pointer->next;
2899         #ifdef WITH_PRESENCE
2900         if(pointer != (OCResource *) presenceResource.handle)
2901         {
2902             #endif // WITH_PRESENCE
2903             deleteResource(pointer);
2904             #ifdef WITH_PRESENCE
2905         }
2906         #endif // WITH_PRESENCE
2907         pointer = temp;
2908     }
2909
2910     #ifdef WITH_PRESENCE
2911     // Ensure that the last resource to be deleted is the presence resource. This allows for all
2912     // presence notification attributed to their deletion to be processed.
2913     deleteResource((OCResource *) presenceResource.handle);
2914     #endif // WITH_PRESENCE
2915 }
2916
2917 /**
2918  * Delete the resource from the linked list.
2919  *
2920  * @param resource - resource to be deleted
2921  * @return
2922  *    0 - error
2923  *    1 - success
2924  */
2925 int deleteResource(OCResource *resource) {
2926     OCResource *prev = NULL;
2927     OCResource *temp;
2928
2929     temp = headResource;
2930     while (temp) {
2931         if (temp == resource) {
2932             // Invalidate all Resource Properties.
2933             resource->resourceProperties = (OCResourceProperty) 0;
2934             #ifdef WITH_PRESENCE
2935             if(resource != (OCResource *) presenceResource.handle)
2936             {
2937             #endif // WITH_PRESENCE
2938                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2939             #ifdef WITH_PRESENCE
2940             }
2941
2942             if(presenceResource.handle)
2943             {
2944                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2945                 if(resource != (OCResource *) presenceResource.handle)
2946                 {
2947                     SendPresenceNotification(resource->rsrcType);
2948                 }
2949                 else
2950                 {
2951                     SendPresenceNotification(NULL);
2952                 }
2953             }
2954         #endif
2955
2956             if (temp == headResource) {
2957                 headResource = temp->next;
2958             } else {
2959                 prev->next = temp->next;
2960             }
2961
2962             deleteResourceElements(temp);
2963             OCFree(temp);
2964             return 1;
2965         } else {
2966             prev = temp;
2967             temp = temp->next;
2968         }
2969     }
2970
2971     return 0;
2972 }
2973
2974 /**
2975  * Delete all of the dynamically allocated elements that were created for the resource.
2976  *
2977  * @param resource - specified resource
2978  */
2979 void deleteResourceElements(OCResource *resource) {
2980     if (!resource) {
2981         return;
2982     }
2983
2984     // remove URI
2985     OCFree(resource->uri);
2986
2987     // Delete resourcetype linked list
2988     deleteResourceType(resource->rsrcType);
2989
2990     // Delete resourceinterface linked list
2991     deleteResourceInterface(resource->rsrcInterface);
2992 }
2993
2994 /**
2995  * Delete all of the dynamically allocated elements that were created for the resource type.
2996  *
2997  * @param resourceType - specified resource type
2998  */
2999 void deleteResourceType(OCResourceType *resourceType) {
3000     OCResourceType *pointer = resourceType;
3001     OCResourceType *next;
3002
3003     while (pointer) {
3004         next = pointer->next;
3005         OCFree(pointer->resourcetypename);
3006         OCFree(pointer);
3007         pointer = next;
3008     }
3009 }
3010
3011 /**
3012  * Delete all of the dynamically allocated elements that were created for the resource interface.
3013  *
3014  * @param resourceInterface - specified resource interface
3015  */
3016 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3017     OCResourceInterface *pointer = resourceInterface;
3018     OCResourceInterface *next;
3019
3020     while (pointer) {
3021         next = pointer->next;
3022         OCFree(pointer->name);
3023         OCFree(pointer);
3024         pointer = next;
3025     }
3026 }
3027
3028 /**
3029  * Insert a resource type into a resource's resource type linked list.
3030  *
3031  * @param resource - resource where resource type is to be inserted
3032  * @param resourceType - resource type to be inserted
3033  */
3034 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3035     OCResourceType *pointer;
3036
3037     if (resource && !resource->rsrcType) {
3038         resource->rsrcType = resourceType;
3039     } else {
3040         if(resource)
3041         {
3042             pointer = resource->rsrcType;
3043         }
3044         else
3045         {
3046             pointer = resourceType;
3047         }
3048         while (pointer->next) {
3049             pointer = pointer->next;
3050         }
3051         pointer->next = resourceType;
3052     }
3053     resourceType->next = NULL;
3054 }
3055
3056 /**
3057  * Get a resource type at the specified index within a resource.
3058  *
3059  * @param handle - handle of resource
3060  * @param index - index of resource type
3061  *
3062  * @return
3063  *    resourcetype - if found
3064  *    NULL - not found
3065  */
3066 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3067     OCResource *resource;
3068     OCResourceType *pointer;
3069     uint8_t i;
3070
3071     // Find the specified resource
3072     resource = findResource((OCResource *) handle);
3073     if (!resource) {
3074         return NULL;
3075     }
3076
3077     // Make sure a resource has a resourcetype
3078     if (!resource->rsrcType) {
3079         return NULL;
3080     }
3081
3082     // Iterate through the list
3083     pointer = resource->rsrcType;
3084     i = 0;
3085     while ((i < index) && pointer) {
3086         i++;
3087         pointer = pointer->next;
3088     }
3089     return pointer;
3090 }
3091
3092 /**
3093  * Finds a resource type in an OCResourceType link-list.
3094  *
3095  * @param resourceTypeList - the link-list to be searched through
3096  * @param resourceTypeName - the key to search for
3097  *
3098  * @return
3099  *      resourceType that matches the key (ie. resourceTypeName)
3100  *      NULL - either an invalid parameter or this function was unable to find the key.
3101  */
3102 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3103 {
3104     if(resourceTypeList && resourceTypeName)
3105     {
3106         OCResourceType * rtPointer = resourceTypeList;
3107         while(resourceTypeName && rtPointer)
3108         {
3109             if(rtPointer->resourcetypename &&
3110                     strcmp(resourceTypeName, (const char *)
3111                     (rtPointer->resourcetypename)) == 0)
3112             {
3113                 break;
3114             }
3115             rtPointer = rtPointer->next;
3116         }
3117         return rtPointer;
3118     }
3119     return NULL;
3120 }
3121 /**
3122  * Insert a resource interface into a resource's resource interface linked list.
3123  *
3124  * @param resource - resource where resource interface is to be inserted
3125  * @param resourceInterface - resource interface to be inserted
3126  */
3127 void insertResourceInterface(OCResource *resource,
3128         OCResourceInterface *resourceInterface) {
3129     OCResourceInterface *pointer;
3130
3131     if (!resource->rsrcInterface) {
3132         resource->rsrcInterface = resourceInterface;
3133     } else {
3134         pointer = resource->rsrcInterface;
3135         while (pointer->next) {
3136             pointer = pointer->next;
3137         }
3138         pointer->next = resourceInterface;
3139     }
3140     resourceInterface->next = NULL;
3141 }
3142
3143 /**
3144  * Get a resource interface at the specified index within a resource.
3145  *
3146  * @param handle - handle of resource
3147  * @param index - index of resource interface
3148  *
3149  * @return
3150  *    resourceinterface - if found
3151  *    NULL - not found
3152  */
3153 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3154         uint8_t index) {
3155     OCResource *resource;
3156     OCResourceInterface *pointer;
3157     uint8_t i = 0;
3158
3159     // Find the specified resource
3160     resource = findResource((OCResource *) handle);
3161     if (!resource) {
3162         return NULL;
3163     }
3164
3165     // Make sure a resource has a resourceinterface
3166     if (!resource->rsrcInterface) {
3167         return NULL;
3168     }
3169
3170     // Iterate through the list
3171     pointer = resource->rsrcInterface;
3172
3173     while ((i < index) && pointer) {
3174         i++;
3175         pointer = pointer->next;
3176     }
3177     return pointer;
3178 }
3179
3180 /**
3181  * Determine if a request/response must be sent in a block transfer because it is too large to be
3182  * sent in a single PDU.  This function can be used for either a request or a response
3183  *
3184  * @param request  - NULL or pointer to request
3185  * @param response - NULL or pointer to response
3186  * @param size     - 0 or size of the request/response.  If 0, strlen is used for determining
3187  *                   the length of the request/response
3188  *
3189  * @return
3190  *    0 - packet transfer NOT required (i.e. normal request/response)
3191  *    1 - packet transfer required (i.e. block transfer needed)
3192  */
3193 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3194 {
3195     uint8_t result = 0;
3196
3197     // Determine if we are checking a request or a response
3198     if (request)
3199     {
3200         // If size is greater than 0, use it for the request size value, otherwise
3201         // assume request is null terminated and use strlen for size value
3202         if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3203         {
3204             result = 1;
3205         }
3206     }
3207     else if (response)
3208     {
3209         // If size is greater than 0, use it for the response size value, otherwise
3210         // assume response is null terminated and use strlen for size value
3211         if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3212         {
3213             result = 1;
3214         }
3215     }
3216     return result;
3217 }
3218
3219 /**
3220  * Retrieves a resource type based upon a query ontains only just one
3221  * resource attribute (and that has to be of type "rt").
3222  *
3223  * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3224  * before passing in.
3225  *
3226  * @param query - The quert part of the URI
3227  * @param resourceType - The resource type to be populated; pass by reference.
3228  *
3229  * @return
3230  *  OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3231  *  OC_STACK_OK            - Success
3232  */
3233 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3234 {
3235     if(!query)
3236     {
3237         return OC_STACK_INVALID_PARAM;
3238     }
3239
3240     OCStackResult result = OC_STACK_ERROR;
3241
3242     if(strncmp(query, "rt=", 3) == 0)
3243     {
3244         *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3245         if(!*resourceType)
3246         {
3247             result = OC_STACK_NO_MEMORY;
3248         }
3249
3250         strcpy((char *)*resourceType, ((const char *)&query[3]));
3251         result = OC_STACK_OK;
3252     }
3253
3254     return result;
3255 }
3256
3257 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3258 {
3259     if(!uri)
3260     {
3261         return OC_STACK_INVALID_URI;
3262     }
3263     if(!query || !newURI)
3264     {
3265         return OC_STACK_INVALID_PARAM;
3266     }
3267     char * leftToken = NULL;
3268     char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3269     if(!tempURI)
3270     {
3271         goto exit;
3272     }
3273     strcpy(tempURI, uri);
3274     char* strTokPtr;
3275     leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3276
3277     //TODO-CA: This could be simplified. Clean up required.
3278     while(leftToken != NULL)
3279     {
3280         if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3281         {
3282             *query = (unsigned char *) OCMalloc(strlen(leftToken));
3283             if(!*query)
3284             {
3285                 goto exit;
3286             }
3287             strcpy((char *)*query, ((const char *)&leftToken[0]));
3288             break;
3289         }
3290         leftToken = strtok_r(NULL, "?", &strTokPtr);
3291     }
3292
3293     *newURI = tempURI;
3294
3295     return OC_STACK_OK;
3296
3297     exit:
3298         return OC_STACK_NO_MEMORY;
3299 }
3300
3301 const ServerID OCGetServerInstanceID(void)
3302 {
3303     static bool generated = false;
3304     static ServerID sid;
3305
3306     if(generated)
3307     {
3308         return sid;
3309     }
3310
3311     sid = OCGetRandom();
3312     generated = true;
3313     return sid;
3314 }
3315
3316 const char* OCGetServerInstanceIDString(void)
3317 {
3318     // max printed length of a base 10
3319     // uint32 is 10 characters, so 11 includes null.
3320     // This will change as the representation gets switched
3321     // to another value
3322     static char buffer[11];
3323     int n = sprintf(buffer, "%u", OCGetServerInstanceID());
3324     if (n < 0)
3325     {
3326         buffer[0]='\0';
3327     }
3328
3329     return buffer;
3330 }