Fix klocwork issue in c stack
[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 = {0};
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     switch (method)
1638     {
1639         case OC_REST_GET:
1640         case OC_REST_OBSERVE:
1641         case OC_REST_OBSERVE_ALL:
1642         case OC_REST_CANCEL_OBSERVE:
1643             {
1644                 requestInfo.method = CA_GET;
1645                 break;
1646             }
1647         case OC_REST_PUT:
1648             {
1649                 requestInfo.method = CA_PUT;
1650                 break;
1651             }
1652         case OC_REST_POST:
1653             {
1654                 requestInfo.method = CA_POST;
1655                 break;
1656             }
1657         case OC_REST_DELETE:
1658             {
1659                 requestInfo.method = CA_DELETE;
1660                 break;
1661             }
1662         #ifdef WITH_PRESENCE
1663         case OC_REST_PRESENCE:
1664             {
1665                 // Replacing method type with GET because "presence"
1666                 // is a stack layer only implementation.
1667                 requestInfo.method = CA_GET;
1668                 break;
1669             }
1670         #endif
1671         default:
1672             result = OC_STACK_INVALID_METHOD;
1673             goto exit;
1674     }
1675
1676     //High QoS is not supported
1677     if(qos == OC_HIGH_QOS)
1678     {
1679         result = OC_STACK_INVALID_PARAM;
1680         goto exit;
1681     }
1682
1683     // create token
1684     caResult = CAGenerateToken(&token);
1685     if (caResult != CA_STATUS_OK)
1686     {
1687         OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1688         CADestroyToken(token);
1689         goto exit;
1690     }
1691
1692     requestData.type = qualityOfServiceToMessageType(qos);
1693     requestData.token = token;
1694     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1695     {
1696         result = CreateObserveHeaderOption (&(requestData.options), options,
1697                                     numOptions, OC_OBSERVE_REGISTER);
1698         if (result != OC_STACK_OK)
1699         {
1700             goto exit;
1701         }
1702         hdrOptionMemAlloc = 1;
1703         requestData.numOptions = numOptions + 1;
1704     }
1705     else
1706     {
1707         requestData.options = (CAHeaderOption_t*)options;
1708         requestData.numOptions = numOptions;
1709     }
1710     requestData.payload = (char *)request;
1711
1712     requestInfo.info = requestData;
1713
1714     CAConnectivityType_t caConType;
1715
1716     result = OCToCAConnectivityType((OCConnectivityType) conType, &caConType);
1717     if (result != OC_STACK_OK)
1718     {
1719         OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1720         goto exit;
1721     }
1722
1723     // send request
1724     if(conType == OC_ALL)
1725     {
1726         grpEnd.connectivityType = caConType;
1727
1728         grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1729         if(!grpEnd.resourceUri)
1730         {
1731             result = OC_STACK_NO_MEMORY;
1732             goto exit;
1733         }
1734         strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1735
1736         caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1737     }
1738     else
1739     {
1740         caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1741
1742         if (caResult != CA_STATUS_OK)
1743         {
1744             OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1745             goto exit;
1746         }
1747
1748         caResult = CASendRequest(endpoint, &requestInfo);
1749     }
1750
1751     if (caResult != CA_STATUS_OK)
1752     {
1753         OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1754         goto exit;
1755     }
1756
1757     if((result = AddClientCB(&clientCB, cbData, &token, handle, method,
1758                              requestUri, resourceType)) != OC_STACK_OK)
1759     {
1760         result = OC_STACK_NO_MEMORY;
1761         goto exit;
1762     }
1763
1764 exit:
1765     if(newUri != requiredUri)
1766     {
1767         OCFree(newUri);
1768     }
1769     if (result != OC_STACK_OK)
1770     {
1771         OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1772         FindAndDeleteClientCB(clientCB);
1773     }
1774     CADestroyRemoteEndpoint(endpoint);
1775     OCFree(grpEnd.resourceUri);
1776     if (hdrOptionMemAlloc)
1777     {
1778         OCFree(requestData.options);
1779     }
1780     return result;
1781 }
1782
1783 /**
1784  * Cancel a request associated with a specific @ref OCDoResource invocation.
1785  *
1786  * @param handle - Used to identify a specific OCDoResource invocation.
1787  * @param qos    - used to specify Quality of Service (read below for more info)
1788  * @param options- used to specify vendor specific header options when sending
1789  *                 explicit observe cancellation
1790  * @param numOptions- Number of header options to be included
1791  *
1792  * @return
1793  *     OC_STACK_OK               - No errors; Success
1794  *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
1795  */
1796 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1797         uint8_t numOptions)
1798 {
1799     /*
1800      * This ftn is implemented one of two ways in the case of observation:
1801      *
1802      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1803      *      Remove the callback associated on client side.
1804      *      When the next notification comes in from server,
1805      *      reply with RESET message to server.
1806      *      Keep in mind that the server will react to RESET only
1807      *      if the last notification was sent ans CON
1808      *
1809      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1810      *      and it is associated with an observe request
1811      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1812      *      Send CON Observe request to server with
1813      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1814      *      Remove the callback associated on client side.
1815      */
1816     OCStackResult ret = OC_STACK_OK;
1817     CARemoteEndpoint_t* endpoint = NULL;
1818     CAResult_t caResult;
1819     CAInfo_t requestData;
1820     CARequestInfo_t requestInfo;
1821     // Track if memory is allocated for additional header options
1822     uint8_t hdrOptionMemAlloc = 0;
1823
1824     if(!handle) {
1825         return OC_STACK_INVALID_PARAM;
1826     }
1827
1828     OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1829
1830     ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1831
1832     if(clientCB) {
1833         switch (clientCB->method)
1834         {
1835             case OC_REST_OBSERVE:
1836             case OC_REST_OBSERVE_ALL:
1837                 //TODO-CA : Why CA_WIFI alone?
1838                 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1839                                                   &endpoint);
1840                 if (caResult != CA_STATUS_OK)
1841                 {
1842                     OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1843                     return OC_STACK_ERROR;
1844                 }
1845
1846                 memset(&requestData, 0, sizeof(CAInfo_t));
1847                 requestData.type =  qualityOfServiceToMessageType(qos);
1848                 requestData.token = clientCB->token;
1849                 if (CreateObserveHeaderOption (&(requestData.options),
1850                             options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1851                 {
1852                     return OC_STACK_ERROR;
1853                 }
1854                 hdrOptionMemAlloc = 1;
1855                 requestData.numOptions = numOptions + 1;
1856                 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1857                 requestInfo.method = CA_GET;
1858                 requestInfo.info = requestData;
1859                 // send request
1860                 caResult = CASendRequest(endpoint, &requestInfo);
1861                 if (caResult != CA_STATUS_OK)
1862                 {
1863                     OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1864                 }
1865                 if(caResult == CA_STATUS_OK)
1866                 {
1867                     ret = OC_STACK_OK;
1868                 }
1869             #ifdef WITH_PRESENCE
1870             case OC_REST_PRESENCE:
1871                 FindAndDeleteClientCB(clientCB);
1872                 break;
1873             #endif
1874             default:
1875                 return OC_STACK_INVALID_METHOD;
1876         }
1877     }
1878     CADestroyRemoteEndpoint(endpoint);
1879     if (hdrOptionMemAlloc)
1880     {
1881         OCFree(requestData.options);
1882     }
1883
1884     return ret;
1885 }
1886
1887 #ifdef WITH_PRESENCE
1888 OCStackResult OCProcessPresence()
1889 {
1890     OCStackResult result = OC_STACK_OK;
1891     uint8_t ipAddr[4] = { 0 };
1892     uint16_t port = 0;
1893
1894     OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1895     ClientCB* cbNode = NULL;
1896     OCDevAddr dst;
1897     OCClientResponse clientResponse;
1898     OCResponse * response = NULL;
1899     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1900
1901     LL_FOREACH(cbList, cbNode) {
1902         if(OC_REST_PRESENCE == cbNode->method)
1903         {
1904             if(cbNode->presence)
1905             {
1906                 uint32_t now = GetTime(0);
1907                 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
1908                                                         cbNode->presence->TTLlevel);
1909                 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1910
1911
1912                 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1913                 {
1914                     goto exit;
1915                 }
1916
1917                 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1918                     OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1919                             cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1920                 }
1921
1922                 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1923                 {
1924                     OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1925                     if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1926                     {
1927                         OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1928                                 &dst);
1929
1930                         clientResponse.sequenceNumber = 0;
1931                         clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
1932                         clientResponse.addr = (OCDevAddr *) &dst;
1933                         clientResponse.resJSONPayload = NULL;
1934
1935                         result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1936                                 &cbNode->token, &clientResponse, NULL);
1937                         if(result != OC_STACK_OK)
1938                         {
1939                             goto exit;
1940                         }
1941
1942                         // Increment the TTLLevel (going to a next state), so we don't keep
1943                         // sending presence notification to client.
1944                         cbNode->presence->TTLlevel++;
1945                         OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1946                                                 cbNode->presence->TTLlevel);
1947                     }
1948                     else
1949                     {
1950                         result = OC_STACK_INVALID_IP;
1951                         goto exit;
1952                     }
1953
1954                     cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1955                     if (cbResult == OC_STACK_DELETE_TRANSACTION)
1956                     {
1957                         FindAndDeleteClientCB(cbNode);
1958                     }
1959                 }
1960
1961                 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1962                 {
1963                     CAResult_t caResult;
1964                     CARemoteEndpoint_t* endpoint = NULL;
1965                     CAInfo_t requestData;
1966                     CARequestInfo_t requestInfo;
1967
1968                     OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1969
1970                     //TODO-CA : Why CA_WIFI alone?
1971                     caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
1972                                                   &endpoint);
1973
1974                     if (caResult != CA_STATUS_OK)
1975                     {
1976                         OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1977                         goto exit;
1978                     }
1979
1980                     memset(&requestData, 0, sizeof(CAInfo_t));
1981                     requestData.type = CA_MSG_NONCONFIRM;
1982                     requestData.token = cbNode->token;
1983
1984                     memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1985                     requestInfo.method = CA_GET;
1986                     requestInfo.info = requestData;
1987
1988                     caResult = CASendRequest(endpoint, &requestInfo);
1989
1990                     if (caResult != CA_STATUS_OK)
1991                     {
1992                         OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1993                         goto exit;
1994                     }
1995
1996                     cbNode->presence->TTLlevel++;
1997                     OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1998                                                             cbNode->presence->TTLlevel);
1999                 }
2000             }
2001         }
2002     }
2003 exit:
2004     if (result != OC_STACK_OK)
2005     {
2006         OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2007     }
2008     return result;
2009 }
2010 #endif // WITH_PRESENCE
2011
2012 /**
2013  * Called in main loop of OC client or server.  Allows low-level processing of
2014  * stack services.
2015  *
2016  * @return
2017  *     OC_STACK_OK    - no errors
2018  *     OC_STACK_ERROR - stack process error
2019  */
2020 OCStackResult OCProcess()
2021 {
2022     #ifdef WITH_PRESENCE
2023     OCProcessPresence();
2024     #endif
2025     CAHandleRequestResponse();
2026
2027     return OC_STACK_OK;
2028 }
2029
2030 #ifdef WITH_PRESENCE
2031 /**
2032  * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
2033  * presence notifications to clients via multicast. Once this API has been called with a success,
2034  * clients may query for this server's presence and this server's stack will respond via multicast.
2035  *
2036  * Server can call this function when it comes online for the first time, or when it comes back
2037  * online from offline mode, or when it re enters network.
2038  *
2039  * @param ttl - Time To Live in seconds
2040  * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
2041  *
2042  * @return
2043  *     OC_STACK_OK      - No errors; Success
2044  */
2045 OCStackResult OCStartPresence(const uint32_t ttl)
2046 {
2047     OCChangeResourceProperty(
2048             &(((OCResource *)presenceResource.handle)->resourceProperties),
2049             OC_ACTIVE, 1);
2050
2051     if(ttl > 0)
2052     {
2053         presenceResource.presenceTTL = ttl;
2054     }
2055
2056     if(OC_PRESENCE_UNINITIALIZED == presenceState)
2057     {
2058         OCDevAddr multiCastAddr;
2059         presenceState = OC_PRESENCE_INITIALIZED;
2060
2061         OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
2062
2063         CAAddress_t addressInfo;
2064         strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
2065         addressInfo.IP.port = 5683;
2066
2067         //TODO make sure there is no memory leak here since another copy
2068         //of token is being created inside AddObserver
2069         CAToken_t caToken = NULL;
2070         CAResult_t caResult = CAGenerateToken(&caToken);
2071         if (caResult != CA_STATUS_OK)
2072         {
2073             OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2074             CADestroyToken(caToken);
2075             return OC_STACK_ERROR;
2076         }
2077
2078         AddObserver(OC_PRESENCE_URI, NULL, 0, &caToken,
2079                 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
2080                 &addressInfo, CA_WIFI);
2081     }
2082
2083     // Each time OCStartPresence is called
2084     // a different random 32-bit integer number is used
2085     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2086
2087     return SendPresenceNotification(NULL);
2088 }
2089
2090 /**
2091  * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
2092  * presence notifications to clients via multicast. Once this API has been called with a success,
2093  * this server's stack will not respond to clients querying for this server's presence.
2094  *
2095  * Server can call this function when it is terminating, going offline, or when going
2096  * away from network.
2097  *
2098  * @return
2099  *     OC_STACK_OK      - No errors; Success
2100  */
2101 OCStackResult OCStopPresence()
2102 {
2103     OCStackResult result = OC_STACK_ERROR;
2104     //make resource inactive
2105     result = OCChangeResourceProperty(
2106             &(((OCResource *) presenceResource.handle)->resourceProperties),
2107             OC_ACTIVE, 0);
2108     result = SendPresenceNotification(NULL);
2109
2110     return result;
2111 }
2112 #endif
2113
2114
2115 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
2116 {
2117     defaultDeviceHandler = entityHandler;
2118
2119     return OC_STACK_OK;
2120 }
2121
2122 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2123 {
2124     OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2125
2126     if(myStackMode == OC_CLIENT)
2127     {
2128         return OC_STACK_ERROR;
2129     }
2130
2131     return SaveDeviceInfo(deviceInfo);
2132 }
2133
2134 /**
2135  * Create a resource
2136  *
2137  * @param handle - pointer to handle to newly created resource.  Set by ocstack.
2138  *                 Used to refer to resource
2139  * @param resourceTypeName - name of resource type.  Example: "core.led"
2140  * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
2141  * @param uri - URI of the resource.  Example:  "/a/led"
2142  * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2143  *                        NULL for default entity handler
2144  * @param resourceProperties - properties supported by resource.
2145  *                             Example: OC_DISCOVERABLE|OC_OBSERVABLE
2146  *
2147  * @return
2148  *     OC_STACK_OK    - no errors
2149  *     OC_STACK_ERROR - stack process error
2150  */
2151 OCStackResult OCCreateResource(OCResourceHandle *handle,
2152         const char *resourceTypeName,
2153         const char *resourceInterfaceName,
2154         const char *uri, OCEntityHandler entityHandler,
2155         uint8_t resourceProperties) {
2156
2157     OCResource *pointer = NULL;
2158     char *str = NULL;
2159     size_t size;
2160     OCStackResult result = OC_STACK_ERROR;
2161
2162     OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2163
2164     if(myStackMode == OC_CLIENT)
2165     {
2166         return result;
2167     }
2168     // Validate parameters
2169     if(!uri || (strlen(uri) == 0))
2170     {
2171         OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2172         return OC_STACK_INVALID_URI;
2173     }
2174     // Is it presented during resource discovery?
2175     if (!handle || !resourceTypeName) {
2176         OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2177         return OC_STACK_INVALID_PARAM;
2178     }
2179
2180     if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
2181         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2182     }
2183
2184     // Make sure resourceProperties bitmask has allowed properties specified
2185     if (resourceProperties
2186             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
2187         OC_LOG(ERROR, TAG, PCF("Invalid property"));
2188         return OC_STACK_INVALID_PARAM;
2189     }
2190
2191     // If the headResource is NULL, then no resources have been created...
2192     pointer = headResource;
2193     if (pointer) {
2194         // At least one resources is in the resource list, so we need to search for
2195         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
2196         while (pointer) {
2197             if (strcmp(uri, pointer->uri) == 0) {
2198                 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2199                 return OC_STACK_INVALID_PARAM;
2200             }
2201             pointer = pointer->next;
2202         }
2203     }
2204     // Create the pointer and insert it into the resource list
2205     pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2206     if (!pointer) {
2207         goto exit;
2208     }
2209     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2210
2211     insertResource(pointer);
2212
2213     // Set the uri
2214     size = strlen(uri) + 1;
2215     str = (char *) OCMalloc(size);
2216     if (!str) {
2217         goto exit;
2218     }
2219     strncpy(str, uri, size);
2220     pointer->uri = str;
2221
2222     // Set properties.  Set OC_ACTIVE
2223     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2224             | OC_ACTIVE);
2225
2226     // Add the resourcetype to the resource
2227     result = BindResourceTypeToResource(pointer, resourceTypeName);
2228     if (result != OC_STACK_OK) {
2229         OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2230         goto exit;
2231     }
2232
2233     // Add the resourceinterface to the resource
2234     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2235     if (result != OC_STACK_OK) {
2236         OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2237         goto exit;
2238     }
2239
2240     // If an entity handler has been passed, attach it to the newly created
2241     // resource.  Otherwise, set the default entity handler.
2242     if (entityHandler)
2243     {
2244         pointer->entityHandler = entityHandler;
2245     }
2246     else
2247     {
2248         pointer->entityHandler = defaultResourceEHandler;
2249     }
2250
2251     *handle = pointer;
2252     result = OC_STACK_OK;
2253
2254     #ifdef WITH_PRESENCE
2255     if(presenceResource.handle)
2256     {
2257         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2258         SendPresenceNotification(pointer->rsrcType);
2259     }
2260     #endif
2261 exit:
2262     if (result != OC_STACK_OK)
2263     {
2264         // Deep delete of resource and other dynamic elements that it contains
2265         deleteResource(pointer);
2266         OCFree(str);
2267     }
2268     return result;
2269 }
2270
2271
2272
2273 /**
2274  * Create a resource. with host ip address for remote resource
2275  *
2276  * @param handle - pointer to handle to newly created resource.  Set by ocstack.
2277  *                 Used to refer to resource
2278  * @param resourceTypeName - name of resource type.  Example: "core.led"
2279  * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
2280  * @param host - HOST address of the remote resource.  Example:  "coap://xxx.xxx.xxx.xxx:xxxxx"
2281  * @param uri - URI of the resource.  Example:  "/a/led"
2282  * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2283  *                        NULL for default entity handler
2284  * @param resourceProperties - properties supported by resource.
2285  *                             Example: OC_DISCOVERABLE|OC_OBSERVABLE
2286  *
2287  * @return
2288  *     OC_STACK_OK    - no errors
2289  *     OC_STACK_ERROR - stack process error
2290  */
2291
2292 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2293         const char *resourceTypeName,
2294         const char *resourceInterfaceName,
2295         const char *host,
2296         const char *uri,
2297         OCEntityHandler entityHandler,
2298         uint8_t resourceProperties)
2299 {
2300     char *str = NULL;
2301     size_t size;
2302     OCStackResult result = OC_STACK_ERROR;
2303
2304     result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2305                                 uri, entityHandler, resourceProperties);
2306
2307     if (result != OC_STACK_ERROR)
2308     {
2309         // Set the uri
2310         size = strlen(host) + 1;
2311         str = (char *) OCMalloc(size);
2312         if (!str)
2313         {
2314             return OC_STACK_ERROR;
2315         }
2316         strncpy(str, host, size);
2317         ((OCResource *) *handle)->host = str;
2318     }
2319
2320     return result;
2321 }
2322
2323 /**
2324  * Add a resource to a collection resource.
2325  *
2326  * @param collectionHandle - handle to the collection resource
2327  * @param resourceHandle - handle to resource to be added to the collection resource
2328  *
2329  * @return
2330  *     OC_STACK_OK    - no errors
2331  *     OC_STACK_ERROR - stack process error
2332  *     OC_STACK_INVALID_PARAM - invalid collectionhandle
2333  */
2334 OCStackResult OCBindResource(
2335         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2336     OCResource *resource;
2337     uint8_t i;
2338
2339     OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2340
2341     // Validate parameters
2342     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2343     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2344     // Container cannot contain itself
2345     if (collectionHandle == resourceHandle) {
2346         OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2347         return OC_STACK_INVALID_PARAM;
2348     }
2349
2350     // Use the handle to find the resource in the resource linked list
2351     resource = findResource((OCResource *) collectionHandle);
2352     if (!resource) {
2353         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2354         return OC_STACK_INVALID_PARAM;
2355     }
2356
2357     // Look for an open slot to add add the child resource.
2358     // If found, add it and return success
2359     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2360         if (!resource->rsrcResources[i]) {
2361             resource->rsrcResources[i] = (OCResource *) resourceHandle;
2362             OC_LOG(INFO, TAG, PCF("resource bound"));
2363             return OC_STACK_OK;
2364         }
2365     }
2366
2367     #ifdef WITH_PRESENCE
2368     if(presenceResource.handle)
2369     {
2370         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2371         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2372     }
2373     #endif
2374
2375     // Unable to add resourceHandle, so return error
2376     return OC_STACK_ERROR;
2377 }
2378
2379 /**
2380  * Remove a resource from a collection resource.
2381  *
2382  * @param collectionHandle - handle to the collection resource
2383  * @param resourceHandle - handle to resource to be added to the collection resource
2384  *
2385  * @return
2386  *     OC_STACK_OK    - no errors
2387  *     OC_STACK_ERROR - stack process error
2388  *     OC_STACK_INVALID_PARAM - invalid collectionHandle
2389  */
2390 OCStackResult OCUnBindResource(
2391         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2392     OCResource *resource;
2393     uint8_t i;
2394
2395     OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2396
2397     // Validate parameters
2398     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2399     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2400     // Container cannot contain itself
2401     if (collectionHandle == resourceHandle) {
2402         OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2403         return OC_STACK_INVALID_PARAM;
2404     }
2405
2406     // Use the handle to find the resource in the resource linked list
2407     resource = findResource((OCResource *) collectionHandle);
2408     if (!resource) {
2409         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2410         return OC_STACK_INVALID_PARAM;
2411     }
2412
2413     // Look for an open slot to add add the child resource.
2414     // If found, add it and return success
2415     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2416         if (resourceHandle == resource->rsrcResources[i]) {
2417             resource->rsrcResources[i] = (OCResource *) NULL;
2418             OC_LOG(INFO, TAG, PCF("resource unbound"));
2419             return OC_STACK_OK;
2420         }
2421     }
2422
2423     OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2424
2425     #ifdef WITH_PRESENCE
2426     if(presenceResource.handle)
2427     {
2428         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2429         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2430     }
2431     #endif
2432
2433     // Unable to add resourceHandle, so return error
2434     return OC_STACK_ERROR;
2435 }
2436
2437 OCStackResult BindResourceTypeToResource(OCResource* resource,
2438                                             const char *resourceTypeName)
2439 {
2440     OCResourceType *pointer = NULL;
2441     char *str = NULL;
2442     size_t size;
2443     OCStackResult result = OC_STACK_ERROR;
2444
2445     OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2446
2447     // Validate parameters
2448     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2449     // TODO:  Does resource attribute resentation really have to be maintained in stack?
2450     // Is it presented during resource discovery?
2451
2452     //TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2453
2454     // Create the resourcetype and insert it into the resource list
2455     pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2456     if (!pointer) {
2457         goto exit;
2458     }
2459
2460     // Set the resourceTypeName
2461     size = strlen(resourceTypeName) + 1;
2462     str = (char *) OCMalloc(size);
2463     if (!str) {
2464         goto exit;
2465     }
2466     strncpy(str, resourceTypeName, size);
2467     pointer->resourcetypename = str;
2468
2469     insertResourceType(resource, pointer);
2470     result = OC_STACK_OK;
2471
2472     exit: if (result != OC_STACK_OK) {
2473         OCFree(pointer);
2474         OCFree(str);
2475     }
2476
2477     return result;
2478 }
2479
2480 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2481         const char *resourceInterfaceName)
2482 {
2483     OCResourceInterface *pointer = NULL;
2484     char *str = NULL;
2485     size_t size;
2486     OCStackResult result = OC_STACK_ERROR;
2487
2488     OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2489
2490     // Validate parameters
2491     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2492
2493     //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2494
2495     // Create the resourceinterface and insert it into the resource list
2496     pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2497     if (!pointer) {
2498         goto exit;
2499     }
2500
2501     // Set the resourceinterface name
2502     size = strlen(resourceInterfaceName) + 1;
2503     str = (char *) OCMalloc(size);
2504     if (!str) {
2505         goto exit;
2506     }
2507     strncpy(str, resourceInterfaceName, size);
2508     pointer->name = str;
2509
2510     // Bind the resourceinterface to the resource
2511     insertResourceInterface(resource, pointer);
2512
2513     result = OC_STACK_OK;
2514
2515     exit: if (result != OC_STACK_OK) {
2516         OCFree(pointer);
2517         OCFree(str);
2518     }
2519
2520     return result;
2521 }
2522
2523 /**
2524  * Bind a resourcetype to a resource.
2525  *
2526  * @param handle - handle to the resource
2527  * @param resourceTypeName - name of resource type.  Example: "core.led"
2528  *
2529  * @return
2530  *     OC_STACK_OK    - no errors
2531  *     OC_STACK_ERROR - stack process error
2532  */
2533 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2534         const char *resourceTypeName) {
2535
2536     OCStackResult result = OC_STACK_ERROR;
2537     OCResource *resource;
2538
2539     // Make sure resource exists
2540     resource = findResource((OCResource *) handle);
2541     if (!resource) {
2542         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2543         return OC_STACK_ERROR;
2544     }
2545
2546     // call internal function
2547     result = BindResourceTypeToResource(resource, resourceTypeName);
2548
2549     #ifdef WITH_PRESENCE
2550     if(presenceResource.handle)
2551     {
2552         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2553         SendPresenceNotification(resource->rsrcType);
2554     }
2555     #endif
2556
2557     return result;
2558 }
2559
2560 /**
2561  * Bind a resourceinterface to a resource.
2562  *
2563  * @param handle - handle to the resource
2564  * @param resourceInterfaceName - name of resource interface.  Example: "oc.mi.b"
2565  *
2566  * @return
2567  *     OC_STACK_OK    - no errors
2568  *     OC_STACK_ERROR - stack process error
2569  */
2570
2571 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2572         const char *resourceInterfaceName) {
2573
2574     OCStackResult result = OC_STACK_ERROR;
2575     OCResource *resource;
2576
2577     // Make sure resource exists
2578     resource = findResource((OCResource *) handle);
2579     if (!resource) {
2580         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2581         return OC_STACK_ERROR;
2582     }
2583
2584     // call internal function
2585     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2586
2587     #ifdef WITH_PRESENCE
2588     if(presenceResource.handle)
2589     {
2590         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2591         SendPresenceNotification(resource->rsrcType);
2592     }
2593     #endif
2594
2595     return result;
2596 }
2597
2598 /**
2599  * Get the number of resources that have been created in the stack.
2600  *
2601  * @param numResources - pointer to count variable
2602  *
2603  * @return
2604  *     OC_STACK_OK    - no errors
2605  *     OC_STACK_ERROR - stack process error
2606
2607  */
2608 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2609     OCResource *pointer = headResource;
2610
2611     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2612     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2613     *numResources = 0;
2614     while (pointer) {
2615         *numResources = *numResources + 1;
2616         pointer = pointer->next;
2617     }
2618     return OC_STACK_OK;
2619 }
2620
2621 /**
2622  * Get a resource handle by index.
2623  *
2624  * @param index - index of resource, 0 to Count - 1
2625  *
2626  * @return
2627  *    Resource handle - if found
2628  *    NULL - if not found
2629  */
2630 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2631     OCResource *pointer = headResource;
2632     uint8_t i = 0;
2633
2634     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2635
2636     // Iterate through the list
2637     while ((i < index) && pointer) {
2638         i++;
2639         pointer = pointer->next;
2640     }
2641     return (OCResourceHandle) pointer;
2642 }
2643
2644 /**
2645  * Delete resource specified by handle.  Deletes resource and all resourcetype and resourceinterface
2646  * linked lists.
2647  *
2648  * @param handle - handle of resource to be deleted
2649  *
2650  * @return
2651  *     OC_STACK_OK              - no errors
2652  *     OC_STACK_ERROR           - stack process error
2653  *     OC_STACK_NO_RESOURCE     - resource not found
2654  *     OC_STACK_INVALID_PARAM   - invalid param
2655  */
2656 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2657     OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2658
2659     if (!handle) {
2660         OC_LOG(ERROR, TAG, PCF("Invalid param"));
2661         return OC_STACK_INVALID_PARAM;
2662     }
2663
2664     OCResource *resource = findResource((OCResource *) handle);
2665     if (resource == NULL) {
2666         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2667         return OC_STACK_NO_RESOURCE;
2668     }
2669
2670     if (deleteResource((OCResource *) handle) == 0) {
2671         OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2672         return OC_STACK_ERROR;
2673     }
2674
2675     return OC_STACK_OK;
2676 }
2677
2678 /**
2679  * Get the URI of the resource specified by handle.
2680  *
2681  * @param handle - handle of resource
2682  * @return
2683  *    URI string - if resource found
2684  *    NULL - resource not found
2685  */
2686 const char *OCGetResourceUri(OCResourceHandle handle) {
2687     OCResource *resource;
2688     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2689
2690     resource = findResource((OCResource *) handle);
2691     if (resource) {
2692         return resource->uri;
2693     }
2694     return (const char *) NULL;
2695 }
2696
2697 /**
2698  * Get the properties of the resource specified by handle.
2699  * NOTE: that after a resource is created, the OC_ACTIVE property is set
2700  * for the resource by the stack.
2701  *
2702  * @param handle - handle of resource
2703  * @return
2704  *    property bitmap - if resource found
2705  *    NULL - resource not found
2706  */
2707 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2708     OCResource *resource;
2709     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2710
2711     resource = findResource((OCResource *) handle);
2712     if (resource) {
2713         return resource->resourceProperties;
2714     }
2715     return 0;
2716 }
2717
2718 /**
2719  * Get the number of resource types of the resource.
2720  *
2721  * @param handle - handle of resource
2722  * @param numResourceTypes - pointer to count variable
2723  *
2724  * @return
2725  *     OC_STACK_OK    - no errors
2726  *     OC_STACK_ERROR - stack process error
2727  */
2728 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2729         uint8_t *numResourceTypes) {
2730     OCResource *resource;
2731     OCResourceType *pointer;
2732
2733     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2734     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2735     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2736
2737     *numResourceTypes = 0;
2738
2739     resource = findResource((OCResource *) handle);
2740     if (resource) {
2741         pointer = resource->rsrcType;
2742         while (pointer) {
2743             *numResourceTypes = *numResourceTypes + 1;
2744             pointer = pointer->next;
2745         }
2746     }
2747     return OC_STACK_OK;
2748 }
2749
2750 /**
2751  * Get name of resource type of the resource.
2752  *
2753  * @param handle - handle of resource
2754  * @param index - index of resource, 0 to Count - 1
2755  *
2756  * @return
2757  *    resource type name - if resource found
2758  *    NULL - resource not found
2759  */
2760 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2761     OCResourceType *resourceType;
2762
2763     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2764
2765     resourceType = findResourceTypeAtIndex(handle, index);
2766     if (resourceType) {
2767         return resourceType->resourcetypename;
2768     }
2769     return (const char *) NULL;
2770 }
2771
2772
2773
2774 /**
2775  * Get the number of resource interfaces of the resource.
2776  *
2777  * @param handle - handle of resource
2778  * @param numResources - pointer to count variable
2779  *
2780  * @return
2781  *     OC_STACK_OK    - no errors
2782  *     OC_STACK_ERROR - stack process error
2783  */
2784 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2785         uint8_t *numResourceInterfaces) {
2786     OCResourceInterface *pointer;
2787     OCResource *resource;
2788
2789     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2790
2791     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2792     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2793
2794     *numResourceInterfaces = 0;
2795     resource = findResource((OCResource *) handle);
2796     if (resource) {
2797         pointer = resource->rsrcInterface;
2798         while (pointer) {
2799             *numResourceInterfaces = *numResourceInterfaces + 1;
2800             pointer = pointer->next;
2801         }
2802     }
2803     return OC_STACK_OK;
2804 }
2805
2806 /**
2807  * Get name of resource interface of the resource.
2808  *
2809  * @param handle - handle of resource
2810  * @param index - index of resource, 0 to Count - 1
2811  *
2812  * @return
2813  *    resource interface name - if resource found
2814  *    NULL - resource not found
2815  */
2816 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2817     OCResourceInterface *resourceInterface;
2818
2819     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2820
2821     resourceInterface = findResourceInterfaceAtIndex(handle, index);
2822     if (resourceInterface) {
2823         return resourceInterface->name;
2824     }
2825     return (const char *) NULL;
2826 }
2827
2828 /**
2829  * Get resource handle from the collection resource by index.
2830  *
2831  * @param collectionHandle - handle of collection resource
2832  * @param index - index of contained resource, 0 to Count - 1
2833  *
2834  * @return
2835  *    handle to resource - if resource found
2836  *    NULL - resource not found
2837  */
2838 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2839         uint8_t index) {
2840     OCResource *resource;
2841
2842     OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2843
2844     if (index >= MAX_CONTAINED_RESOURCES) {
2845         return NULL;
2846     }
2847
2848     resource = findResource((OCResource *) collectionHandle);
2849     if (!resource) {
2850         return NULL;
2851     }
2852
2853     return resource->rsrcResources[index];
2854 }
2855
2856 /**
2857  * Bind an entity handler to the resource.
2858  *
2859  * @param handle - handle to the resource that the contained resource is to be bound
2860  * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2861  * @return
2862  *     OC_STACK_OK    - no errors
2863  *     OC_STACK_ERROR - stack process error
2864  */
2865 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2866         OCEntityHandler entityHandler) {
2867     OCResource *resource;
2868
2869     OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2870
2871     // Validate parameters
2872     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2873     //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2874
2875     // Use the handle to find the resource in the resource linked list
2876     resource = findResource((OCResource *)handle);
2877     if (!resource) {
2878         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2879         return OC_STACK_ERROR;
2880     }
2881
2882     // Bind the handler
2883     resource->entityHandler = entityHandler;
2884
2885     #ifdef WITH_PRESENCE
2886     if(presenceResource.handle)
2887     {
2888         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2889         SendPresenceNotification(resource->rsrcType);
2890     }
2891     #endif
2892
2893     return OC_STACK_OK;
2894 }
2895
2896 /**
2897  * Get the entity handler for a resource.
2898  *
2899  * @param handle - handle of resource
2900  *
2901  * @return
2902  *    entity handler - if resource found
2903  *    NULL - resource not found
2904  */
2905 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2906     OCResource *resource;
2907
2908     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2909
2910     // Use the handle to find the resource in the resource linked list
2911     resource = findResource((OCResource *)handle);
2912     if (!resource) {
2913         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2914         return NULL;
2915     }
2916
2917     // Bind the handler
2918     return resource->entityHandler;
2919 }
2920
2921 void incrementSequenceNumber(OCResource * resPtr)
2922 {
2923     // Increment the sequence number
2924     resPtr->sequenceNum += 1;
2925     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2926     {
2927         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2928     }
2929     return;
2930 }
2931
2932 /**
2933  * Notify Presence subscribers that a resource has been modified
2934  *
2935  * @param resourceType - Handle to the resourceType linked list of resource
2936  *                       that was modified.
2937  * @param qos          - Quality Of Service
2938  *
2939  */
2940 #ifdef WITH_PRESENCE
2941 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2942 {
2943     OCResource *resPtr = NULL;
2944     OCStackResult result;
2945     OCMethod method = OC_REST_PRESENCE;
2946     uint32_t maxAge = 0;
2947     resPtr = findResource((OCResource *) presenceResource.handle);
2948     if(NULL == resPtr)
2949     {
2950         return OC_STACK_NO_RESOURCE;
2951     }
2952     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2953     {
2954         maxAge = presenceResource.presenceTTL;
2955     }
2956     else
2957     {
2958         maxAge = 0;
2959     }
2960
2961     result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2962
2963     return result;
2964 }
2965 #endif // WITH_PRESENCE
2966 /**
2967  * Notify observers that an observed value has changed.
2968  *
2969  * @param handle - handle of resource
2970  *
2971  * @return
2972  *     OC_STACK_OK    - no errors
2973  *     OC_STACK_NO_RESOURCE - invalid resource handle
2974  *     OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2975  */
2976 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2977
2978     OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2979
2980     OCResource *resPtr = NULL;
2981     OCStackResult result;
2982     OCMethod method = OC_REST_NOMETHOD;
2983     uint32_t maxAge = 0;
2984
2985     OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2986     #ifdef WITH_PRESENCE
2987     if(handle == presenceResource.handle)
2988     {
2989         return OC_STACK_OK;
2990     }
2991     #endif // WITH_PRESENCE
2992     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2993
2994     // Verify that the resource exists
2995     resPtr = findResource ((OCResource *) handle);
2996     if (NULL == resPtr)
2997     {
2998         return OC_STACK_NO_RESOURCE;
2999     }
3000     else
3001     {
3002         //only increment in the case of regular observing (not presence)
3003         incrementSequenceNumber(resPtr);
3004         method = OC_REST_OBSERVE;
3005         maxAge = MAX_OBSERVE_AGE;
3006         #ifdef WITH_PRESENCE
3007         result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
3008         #else
3009         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3010         #endif
3011         return result;
3012     }
3013 }
3014
3015 OCStackResult
3016 OCNotifyListOfObservers (OCResourceHandle handle,
3017                          OCObservationId  *obsIdList,
3018                          uint8_t          numberOfIds,
3019                          unsigned char    *notificationJSONPayload,
3020                          OCQualityOfService qos)
3021 {
3022     OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3023
3024     OCResource *resPtr = NULL;
3025     //TODO: we should allow the server to define this
3026     uint32_t maxAge = MAX_OBSERVE_AGE;
3027
3028     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3029     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3030     VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3031
3032     // Verify that the resource exists
3033     resPtr = findResource ((OCResource *) handle);
3034     if (NULL == resPtr || myStackMode == OC_CLIENT)
3035     {
3036         return OC_STACK_NO_RESOURCE;
3037     }
3038     else
3039     {
3040         incrementSequenceNumber(resPtr);
3041     }
3042     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3043             notificationJSONPayload, maxAge, qos));
3044 }
3045
3046 /**
3047  * Send a response to a request.
3048  * The response can be a regular, slow, or block (i.e. a response that
3049  * is too large to be sent in a single PDU and must span multiple transmissions)
3050  *
3051  * @param response - pointer to structure that contains response parameters
3052  *
3053  * @return
3054  *     OC_STACK_OK                         - No errors; Success
3055  *     OC_STACK_INVALID_PARAM              - Invalid pointer to OCServerResponse
3056  *     OC_STACK_INVALID_REQUEST_HANDLE     - Request handle not found
3057  *     OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
3058  *                                           persistent response buffer is necessary
3059  */
3060 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3061 {
3062     OCStackResult result = OC_STACK_ERROR;
3063     OCServerRequest *serverRequest = NULL;
3064
3065     OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3066
3067     // Validate input parameters
3068     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3069     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3070
3071     // TODO: Placeholder for creating a response entry when implementing
3072     // block transfer feature
3073
3074     // If a response payload is present, check if block transfer is required
3075     if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3076             (const char *)ehResponse->payload, ehResponse->payloadSize))
3077     {
3078         OC_LOG(INFO, TAG, PCF("Block transfer required"));
3079
3080         // Persistent response buffer is needed for block transfer
3081         if (!ehResponse->persistentBufferFlag)
3082         {
3083             OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3084             return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3085         }
3086         // TODO: Placeholder for block transfer handling
3087         // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3088             // when implementing the block transfer feature
3089     }
3090     else
3091     {
3092         // Normal response
3093         // Get pointer to request info
3094         serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3095         if(serverRequest)
3096         {
3097             result = serverRequest->ehResponseHandler(ehResponse);
3098         }
3099     }
3100     return result;
3101 }
3102
3103 /**
3104  * Cancel a response.  Applies to a block response
3105  *
3106  * @param responseHandle - response handle set by stack in OCServerResponse after
3107  *                         OCDoResponse is called
3108  *
3109  * @return
3110  *     OC_STACK_OK               - No errors; Success
3111  *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
3112  */
3113 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
3114 {
3115     OCStackResult result = OC_STACK_NOTIMPL;
3116
3117     OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
3118
3119     // TODO: validate response handle
3120
3121     return result;
3122 }
3123
3124 //-----------------------------------------------------------------------------
3125 // Private internal function definitions
3126 //-----------------------------------------------------------------------------
3127 /**
3128  * Generate handle of OCDoResource invocation for callback management.
3129  */
3130 static OCDoHandle GenerateInvocationHandle()
3131 {
3132     OCDoHandle handle = NULL;
3133     // Generate token here, it will be deleted when the transaction is deleted
3134     handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3135     if (handle)
3136     {
3137         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3138     }
3139
3140     return handle;
3141 }
3142 #ifdef WITH_PRESENCE
3143 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3144         OCResourceProperty resourceProperties, uint8_t enable)
3145 {
3146     if (resourceProperties
3147             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
3148         OC_LOG(ERROR, TAG, PCF("Invalid property"));
3149         return OC_STACK_INVALID_PARAM;
3150     }
3151     if(!enable)
3152     {
3153         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3154     }
3155     else
3156     {
3157         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3158     }
3159     return OC_STACK_OK;
3160 }
3161 #endif
3162
3163 /**
3164  * Initialize resource data structures, variables, etc.
3165  */
3166 OCStackResult initResources() {
3167     OCStackResult result = OC_STACK_OK;
3168     // Init application resource vars
3169     headResource = NULL;
3170     // Init Virtual Resources
3171     #ifdef WITH_PRESENCE
3172     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3173     //presenceResource.token = OCGenerateCoAPToken();
3174     result = OCCreateResource(&presenceResource.handle,
3175             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3176             "core.r",
3177             OC_PRESENCE_URI,
3178             NULL,
3179             OC_OBSERVABLE);
3180     //make resource inactive
3181     result = OCChangeResourceProperty(
3182             &(((OCResource *) presenceResource.handle)->resourceProperties),
3183             OC_ACTIVE, 0);
3184     #endif
3185     return result;
3186 }
3187
3188 /**
3189  * Add a resource to the end of the linked list of resources.
3190  *
3191  * @param resource - resource to be added
3192  */
3193 void insertResource(OCResource *resource) {
3194     OCResource *pointer;
3195
3196     if (!headResource) {
3197         headResource = resource;
3198     } else {
3199         pointer = headResource;
3200
3201         while (pointer->next) {
3202             pointer = pointer->next;
3203         }
3204         pointer->next = resource;
3205     }
3206     resource->next = NULL;
3207 }
3208
3209 /**
3210  * Find a resource in the linked list of resources.
3211  *
3212  * @param resource - resource to be found
3213  * @return
3214  *     NULL                - resource not found
3215  *     pointer to resource - pointer to resource that was found in the linked list
3216  */
3217 OCResource *findResource(OCResource *resource) {
3218     OCResource *pointer = headResource;
3219
3220     while (pointer) {
3221         if (pointer == resource) {
3222             return resource;
3223         }
3224         pointer = pointer->next;
3225     }
3226     return NULL;
3227 }
3228
3229 void deleteAllResources()
3230 {
3231     OCResource *pointer = headResource;
3232     OCResource *temp;
3233
3234     while (pointer)
3235     {
3236         temp = pointer->next;
3237         #ifdef WITH_PRESENCE
3238         if(pointer != (OCResource *) presenceResource.handle)
3239         {
3240             #endif // WITH_PRESENCE
3241             deleteResource(pointer);
3242             #ifdef WITH_PRESENCE
3243         }
3244         #endif // WITH_PRESENCE
3245         pointer = temp;
3246     }
3247
3248     #ifdef WITH_PRESENCE
3249     // Ensure that the last resource to be deleted is the presence resource. This allows for all
3250     // presence notification attributed to their deletion to be processed.
3251     deleteResource((OCResource *) presenceResource.handle);
3252     #endif // WITH_PRESENCE
3253 }
3254
3255 /**
3256  * Delete the resource from the linked list.
3257  *
3258  * @param resource - resource to be deleted
3259  * @return
3260  *    0 - error
3261  *    1 - success
3262  */
3263 int deleteResource(OCResource *resource) {
3264     OCResource *prev = NULL;
3265     OCResource *temp;
3266
3267     temp = headResource;
3268     while (temp) {
3269         if (temp == resource) {
3270             // Invalidate all Resource Properties.
3271             resource->resourceProperties = (OCResourceProperty) 0;
3272             #ifdef WITH_PRESENCE
3273             if(resource != (OCResource *) presenceResource.handle)
3274             {
3275             #endif // WITH_PRESENCE
3276                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3277             #ifdef WITH_PRESENCE
3278             }
3279
3280             if(presenceResource.handle)
3281             {
3282                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3283                 if(resource != (OCResource *) presenceResource.handle)
3284                 {
3285                     SendPresenceNotification(resource->rsrcType);
3286                 }
3287                 else
3288                 {
3289                     SendPresenceNotification(NULL);
3290                 }
3291             }
3292         #endif
3293
3294             if (temp == headResource) {
3295                 headResource = temp->next;
3296             } else {
3297                 prev->next = temp->next;
3298             }
3299
3300             deleteResourceElements(temp);
3301             OCFree(temp);
3302             return 1;
3303         } else {
3304             prev = temp;
3305             temp = temp->next;
3306         }
3307     }
3308
3309     return 0;
3310 }
3311
3312 /**
3313  * Delete all of the dynamically allocated elements that were created for the resource.
3314  *
3315  * @param resource - specified resource
3316  */
3317 void deleteResourceElements(OCResource *resource) {
3318     if (!resource) {
3319         return;
3320     }
3321
3322     // remove URI
3323     OCFree(resource->uri);
3324
3325     // Delete resourcetype linked list
3326     deleteResourceType(resource->rsrcType);
3327
3328     // Delete resourceinterface linked list
3329     deleteResourceInterface(resource->rsrcInterface);
3330 }
3331
3332 /**
3333  * Delete all of the dynamically allocated elements that were created for the resource type.
3334  *
3335  * @param resourceType - specified resource type
3336  */
3337 void deleteResourceType(OCResourceType *resourceType) {
3338     OCResourceType *pointer = resourceType;
3339     OCResourceType *next;
3340
3341     while (pointer) {
3342         next = pointer->next;
3343         OCFree(pointer->resourcetypename);
3344         OCFree(pointer);
3345         pointer = next;
3346     }
3347 }
3348
3349 /**
3350  * Delete all of the dynamically allocated elements that were created for the resource interface.
3351  *
3352  * @param resourceInterface - specified resource interface
3353  */
3354 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3355     OCResourceInterface *pointer = resourceInterface;
3356     OCResourceInterface *next;
3357
3358     while (pointer) {
3359         next = pointer->next;
3360         OCFree(pointer->name);
3361         OCFree(pointer);
3362         pointer = next;
3363     }
3364 }
3365
3366 /**
3367  * Insert a resource type into a resource's resource type linked list.
3368  *
3369  * @param resource - resource where resource type is to be inserted
3370  * @param resourceType - resource type to be inserted
3371  */
3372 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3373     OCResourceType *pointer;
3374
3375     if (resource && !resource->rsrcType) {
3376         resource->rsrcType = resourceType;
3377     } else {
3378         if(resource)
3379         {
3380             pointer = resource->rsrcType;
3381         }
3382         else
3383         {
3384             pointer = resourceType;
3385         }
3386         while (pointer->next) {
3387             pointer = pointer->next;
3388         }
3389         pointer->next = resourceType;
3390     }
3391     resourceType->next = NULL;
3392 }
3393
3394 /**
3395  * Get a resource type at the specified index within a resource.
3396  *
3397  * @param handle - handle of resource
3398  * @param index - index of resource type
3399  *
3400  * @return
3401  *    resourcetype - if found
3402  *    NULL - not found
3403  */
3404 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3405     OCResource *resource;
3406     OCResourceType *pointer;
3407     uint8_t i;
3408
3409     // Find the specified resource
3410     resource = findResource((OCResource *) handle);
3411     if (!resource) {
3412         return NULL;
3413     }
3414
3415     // Make sure a resource has a resourcetype
3416     if (!resource->rsrcType) {
3417         return NULL;
3418     }
3419
3420     // Iterate through the list
3421     pointer = resource->rsrcType;
3422     i = 0;
3423     while ((i < index) && pointer) {
3424         i++;
3425         pointer = pointer->next;
3426     }
3427     return pointer;
3428 }
3429
3430 /**
3431  * Finds a resource type in an OCResourceType link-list.
3432  *
3433  * @param resourceTypeList - the link-list to be searched through
3434  * @param resourceTypeName - the key to search for
3435  *
3436  * @return
3437  *      resourceType that matches the key (ie. resourceTypeName)
3438  *      NULL - either an invalid parameter or this function was unable to find the key.
3439  */
3440 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3441 {
3442     if(resourceTypeList && resourceTypeName)
3443     {
3444         OCResourceType * rtPointer = resourceTypeList;
3445         while(resourceTypeName && rtPointer)
3446         {
3447             if(rtPointer->resourcetypename &&
3448                     strcmp(resourceTypeName, (const char *)
3449                     (rtPointer->resourcetypename)) == 0)
3450             {
3451                 break;
3452             }
3453             rtPointer = rtPointer->next;
3454         }
3455         return rtPointer;
3456     }
3457     return NULL;
3458 }
3459 /**
3460  * Insert a resource interface into a resource's resource interface linked list.
3461  *
3462  * @param resource - resource where resource interface is to be inserted
3463  * @param resourceInterface - resource interface to be inserted
3464  */
3465 void insertResourceInterface(OCResource *resource,
3466         OCResourceInterface *resourceInterface) {
3467     OCResourceInterface *pointer;
3468
3469     if (!resource->rsrcInterface) {
3470         resource->rsrcInterface = resourceInterface;
3471     } else {
3472         pointer = resource->rsrcInterface;
3473         while (pointer->next) {
3474             pointer = pointer->next;
3475         }
3476         pointer->next = resourceInterface;
3477     }
3478     resourceInterface->next = NULL;
3479 }
3480
3481 /**
3482  * Get a resource interface at the specified index within a resource.
3483  *
3484  * @param handle - handle of resource
3485  * @param index - index of resource interface
3486  *
3487  * @return
3488  *    resourceinterface - if found
3489  *    NULL - not found
3490  */
3491 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3492         uint8_t index) {
3493     OCResource *resource;
3494     OCResourceInterface *pointer;
3495     uint8_t i = 0;
3496
3497     // Find the specified resource
3498     resource = findResource((OCResource *) handle);
3499     if (!resource) {
3500         return NULL;
3501     }
3502
3503     // Make sure a resource has a resourceinterface
3504     if (!resource->rsrcInterface) {
3505         return NULL;
3506     }
3507
3508     // Iterate through the list
3509     pointer = resource->rsrcInterface;
3510
3511     while ((i < index) && pointer) {
3512         i++;
3513         pointer = pointer->next;
3514     }
3515     return pointer;
3516 }
3517
3518 /**
3519  * Determine if a request/response must be sent in a block transfer because it is too large to be
3520  * sent in a single PDU.  This function can be used for either a request or a response
3521  *
3522  * @param request  - NULL or pointer to request
3523  * @param response - NULL or pointer to response
3524  * @param size     - 0 or size of the request/response.  If 0, strlen is used for determining
3525  *                   the length of the request/response
3526  *
3527  * @return
3528  *    0 - packet transfer NOT required (i.e. normal request/response)
3529  *    1 - packet transfer required (i.e. block transfer needed)
3530  */
3531 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3532 {
3533     uint8_t result = 0;
3534
3535     // Determine if we are checking a request or a response
3536     if (request)
3537     {
3538         // If size is greater than 0, use it for the request size value, otherwise
3539         // assume request is null terminated and use strlen for size value
3540         if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3541         {
3542             result = 1;
3543         }
3544     }
3545     else if (response)
3546     {
3547         // If size is greater than 0, use it for the response size value, otherwise
3548         // assume response is null terminated and use strlen for size value
3549         if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3550         {
3551             result = 1;
3552         }
3553     }
3554     return result;
3555 }
3556
3557 /**
3558  * Retrieves a resource type based upon a query ontains only just one
3559  * resource attribute (and that has to be of type "rt").
3560  *
3561  * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3562  * before passing in.
3563  *
3564  * @param query - The quert part of the URI
3565  * @param resourceType - The resource type to be populated; pass by reference.
3566  *
3567  * @return
3568  *  OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3569  *  OC_STACK_OK            - Success
3570  */
3571 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3572 {
3573     if(!query)
3574     {
3575         return OC_STACK_INVALID_PARAM;
3576     }
3577
3578     OCStackResult result = OC_STACK_ERROR;
3579
3580     if(strncmp(query, "rt=", 3) == 0)
3581     {
3582         *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3583         if(!*resourceType)
3584         {
3585             result = OC_STACK_NO_MEMORY;
3586         }
3587
3588         strcpy((char *)*resourceType, ((const char *)&query[3]));
3589         result = OC_STACK_OK;
3590     }
3591
3592     return result;
3593 }
3594
3595 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3596 {
3597     if(!uri)
3598     {
3599         return OC_STACK_INVALID_URI;
3600     }
3601     if(!query || !newURI)
3602     {
3603         return OC_STACK_INVALID_PARAM;
3604     }
3605     char * leftToken = NULL;
3606     char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3607     if(!tempURI)
3608     {
3609         goto exit;
3610     }
3611     strcpy(tempURI, uri);
3612     char* strTokPtr;
3613     leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3614
3615     //TODO-CA: This could be simplified. Clean up required.
3616     while(leftToken != NULL)
3617     {
3618         if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3619         {
3620             *query = (unsigned char *) OCMalloc(strlen(leftToken) + 1);
3621             if(!*query)
3622             {
3623                 OCFree(tempURI);
3624                 goto exit;
3625             }
3626             strcpy((char *)*query, ((const char *)&leftToken[0]));
3627             break;
3628         }
3629         leftToken = strtok_r(NULL, "?", &strTokPtr);
3630     }
3631
3632     *newURI = tempURI;
3633
3634     return OC_STACK_OK;
3635
3636     exit:
3637         return OC_STACK_NO_MEMORY;
3638 }
3639
3640 const ServerID OCGetServerInstanceID(void)
3641 {
3642     static bool generated = false;
3643     static ServerID sid;
3644
3645     if(generated)
3646     {
3647         return sid;
3648     }
3649
3650     sid = OCGetRandom();
3651     generated = true;
3652     return sid;
3653 }
3654
3655 const char* OCGetServerInstanceIDString(void)
3656 {
3657     // max printed length of a base 10
3658     // uint32 is 10 characters, so 11 includes null.
3659     // This will change as the representation gets switched
3660     // to another value
3661     static char buffer[11];
3662     int n = sprintf(buffer, "%u", OCGetServerInstanceID());
3663     if (n < 0)
3664     {
3665         buffer[0]='\0';
3666     }
3667
3668     return buffer;
3669 }