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