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