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