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