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