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