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