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