Merge "[CA-Integration] Use 5298 port for MC query since CA uses 5298 as MC port...
[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         result = getResourceType(requiredUri, &resourceType, &newUri);
1169         if(resourceType) {
1170             OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1171         }
1172         else
1173         {
1174             OC_LOG(DEBUG, TAG, PCF("Got Resource Type is NULL."));
1175         }
1176         if(result != OC_STACK_OK)
1177         {
1178             goto exit;
1179         }
1180     }
1181 #endif // WITH_PRESENCE
1182
1183     requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1184     if(requestUri)
1185     {
1186         memcpy(requestUri, newUri, (uriLen + 1));
1187     }
1188     else
1189     {
1190         result = OC_STACK_NO_MEMORY;
1191         goto exit;
1192     }
1193
1194     *handle = GenerateInvocationHandle();
1195     if(!*handle)
1196     {
1197         result = OC_STACK_NO_MEMORY;
1198         goto exit;
1199     }
1200
1201 #ifdef CA_INT
1202     memset(&requestData, 0, sizeof(CAInfo_t));
1203     memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1204     switch (method)
1205     {
1206         case OC_REST_GET:
1207         case OC_REST_OBSERVE:
1208         case OC_REST_OBSERVE_ALL:
1209         case OC_REST_CANCEL_OBSERVE:
1210             {
1211                 requestInfo.method = CA_GET;
1212                 break;
1213             }
1214         case OC_REST_PUT:
1215             {
1216                 requestInfo.method = CA_PUT;
1217                 break;
1218             }
1219         case OC_REST_POST:
1220             {
1221                 requestInfo.method = CA_POST;
1222                 break;
1223             }
1224         case OC_REST_DELETE:
1225             {
1226                 requestInfo.method = CA_DELETE;
1227                 break;
1228             }
1229         #ifdef WITH_PRESENCE
1230         case OC_REST_PRESENCE:
1231             //TODO-CA: What should be the CA method?
1232             break;
1233         #endif
1234         default:
1235             result = OC_STACK_INVALID_METHOD;
1236             goto exit;
1237     }
1238
1239     // TODO-CA: Handle multi-cast scenario
1240     // Create remote end point
1241     caResult = CACreateRemoteEndpoint(newUri, CA_WIFI, &endpoint);
1242     // TODO-CA: Connectivity type should be passed to API
1243     endpoint->connectivityType = CA_WIFI;
1244     if (caResult != CA_STATUS_OK)
1245     {
1246         OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1247         goto exit;
1248     }
1249
1250     // create token
1251     caResult = CAGenerateToken(&caToken);
1252
1253     if (caResult != CA_STATUS_OK)
1254     {
1255         OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1256         caToken = NULL;
1257         goto exit;
1258     }
1259
1260     // TODO-CA: Map QoS to the right CA msg type
1261     requestData.type = CA_MSG_NONCONFIRM;
1262     requestData.token = caToken;
1263     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1264     {
1265         result = CreateObserveHeaderOption (&(requestData.options), options,
1266                                     numOptions, OC_OBSERVE_REGISTER);
1267         if (result != OC_STACK_OK)
1268         {
1269             goto exit;
1270         }
1271         hdrOptionMemAlloc = 1;
1272         requestData.numOptions = numOptions + 1;
1273     }
1274     else
1275     {
1276         requestData.options = (CAHeaderOption_t*)options;
1277         requestData.numOptions = numOptions;
1278     }
1279     requestData.payload = (char *)request;
1280
1281     requestInfo.info = requestData;
1282
1283     // send request
1284     caResult = CASendRequest(endpoint, &requestInfo);
1285     if (caResult != CA_STATUS_OK)
1286     {
1287         OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1288         goto exit;
1289     }
1290
1291     if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1292                              requestUri, resourceType)) != OC_STACK_OK)
1293     {
1294         result = OC_STACK_NO_MEMORY;
1295         goto exit;
1296     }
1297
1298 #else // CA_INT
1299
1300     // Generate token which will be used by OCStack to match responses received
1301     // with the request
1302     OCGenerateCoAPToken(&token);
1303
1304     if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1305             != OC_STACK_OK)
1306     {
1307         result = OC_STACK_NO_MEMORY;
1308         goto exit;
1309     }
1310
1311 #ifdef WITH_PRESENCE
1312     if(method == OC_REST_PRESENCE)
1313     {
1314         // Replacing method type with GET because "presence" is a stack layer only implementation.
1315         method = OC_REST_GET;
1316     }
1317 #endif
1318
1319     // Make call to OCCoAP layer
1320     result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1321 #endif // CA_INT
1322
1323 exit:
1324     if(newUri != requiredUri)
1325     {
1326         OCFree(newUri);
1327     }
1328     if (result != OC_STACK_OK)
1329     {
1330         OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1331         FindAndDeleteClientCB(clientCB);
1332     }
1333 #ifdef CA_INT
1334     CADestroyRemoteEndpoint(endpoint);
1335     if (hdrOptionMemAlloc)
1336     {
1337         OCFree(requestData.options);
1338     }
1339 #endif // CA_INT
1340     return result;
1341 }
1342
1343 /**
1344  * Cancel a request associated with a specific @ref OCDoResource invocation.
1345  *
1346  * @param handle - Used to identify a specific OCDoResource invocation.
1347  * @param qos    - used to specify Quality of Service (read below for more info)
1348  * @param options- used to specify vendor specific header options when sending
1349  *                 explicit observe cancellation
1350  * @param numOptions- Number of header options to be included
1351  *
1352  * @return
1353  *     OC_STACK_OK               - No errors; Success
1354  *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
1355  */
1356 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1357         uint8_t numOptions) 
1358 {
1359     /*
1360      * This ftn is implemented one of two ways in the case of observation:
1361      *
1362      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1363      *      Remove the callback associated on client side.
1364      *      When the next notification comes in from server,
1365      *      reply with RESET message to server.
1366      *      Keep in mind that the server will react to RESET only
1367      *      if the last notification was sent ans CON
1368      *
1369      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1370      *      and it is associated with an observe request
1371      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1372      *      Send CON Observe request to server with
1373      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1374      *      Remove the callback associated on client side.
1375      */
1376     OCStackResult ret = OC_STACK_OK;
1377 #ifdef CA_INT
1378     CARemoteEndpoint_t* endpoint = NULL;
1379     CAResult_t caResult;
1380     CAInfo_t requestData;
1381     CARequestInfo_t requestInfo;
1382     // Track if memory is allocated for additional header options
1383     uint8_t hdrOptionMemAlloc = 0;
1384 #endif // CA_INT
1385
1386     if(!handle) {
1387         return OC_STACK_INVALID_PARAM;
1388     }
1389
1390     OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1391
1392     ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1393
1394     if(clientCB) {
1395         switch (clientCB->method)
1396         {
1397             case OC_REST_OBSERVE:
1398             case OC_REST_OBSERVE_ALL:
1399                 #ifdef CA_INT
1400                 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI, 
1401                                                   &endpoint);
1402                 endpoint->connectivityType = CA_WIFI;
1403                 if (caResult != CA_STATUS_OK)
1404                 {
1405                     OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1406                     return OC_STACK_ERROR;
1407                 }
1408
1409                 memset(&requestData, 0, sizeof(CAInfo_t));
1410                 // TODO-CA: Map QoS to the right CA msg type
1411                 requestData.type = CA_MSG_NONCONFIRM;
1412                 requestData.token = clientCB->token;
1413                 if (CreateObserveHeaderOption (&(requestData.options),
1414                             options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1415                 {
1416                     return OC_STACK_ERROR;
1417                 }
1418                 hdrOptionMemAlloc = 1;
1419                 requestData.numOptions = numOptions + 1;
1420                 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1421                 requestInfo.method = CA_GET;
1422                 requestInfo.info = requestData;
1423                 // send request
1424                 caResult = CASendRequest(endpoint, &requestInfo);
1425                 if (caResult != CA_STATUS_OK)
1426                 {
1427                     OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1428                 }
1429                 if(caResult == CA_STATUS_OK)
1430                 {
1431                     ret = OC_STACK_OK;
1432                 }
1433                 #else // CA_INT
1434                 if(qos == OC_HIGH_QOS)
1435                 {
1436                     ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1437                             &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1438                             numOptions);
1439                 }
1440                 else
1441                 {
1442                     FindAndDeleteClientCB(clientCB);
1443                 }
1444                 break;
1445                 #endif // CA_INT
1446             #ifdef WITH_PRESENCE
1447             case OC_REST_PRESENCE:
1448                 FindAndDeleteClientCB(clientCB);
1449                 break;
1450             #endif
1451             default:
1452                 return OC_STACK_INVALID_METHOD;
1453         }
1454     }
1455 #ifdef CA_INT
1456     CADestroyRemoteEndpoint(endpoint);
1457     if (hdrOptionMemAlloc)
1458     {
1459         OCFree(requestData.options);
1460     }
1461 #endif // CA_INT
1462
1463     return ret;
1464 }
1465 #ifdef WITH_PRESENCE
1466 OCStackResult OCProcessPresence()
1467 {
1468     OCStackResult result = OC_STACK_OK;
1469     uint8_t ipAddr[4] = { 0 };
1470     uint16_t port = 0;
1471
1472     OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1473     ClientCB* cbNode = NULL;
1474     OCDevAddr dst;
1475     OCClientResponse clientResponse;
1476     OCResponse * response = NULL;
1477
1478     LL_FOREACH(cbList, cbNode) {
1479         if(OC_REST_PRESENCE == cbNode->method)
1480         {
1481             if(cbNode->presence)
1482             {
1483                 uint32_t now = GetTime(0);
1484                 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1485                 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1486
1487
1488                 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1489                 {
1490                     goto exit;
1491                 }
1492
1493                 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1494                     OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1495                             cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1496                 }
1497
1498                 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1499                 {
1500                     OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1501                     if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1502                     {
1503                         OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1504                                 &dst);
1505                         result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1506                                 (OCDevAddr *) &dst, 0, NULL);
1507                         if(result != OC_STACK_OK)
1508                         {
1509                             goto exit;
1510                         }
1511                         result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1512                                 &cbNode->token, &clientResponse, NULL);
1513                         if(result != OC_STACK_OK)
1514                         {
1515                             goto exit;
1516                         }
1517
1518                         // Increment the TTLLevel (going to a next state), so we don't keep
1519                         // sending presence notification to client.
1520                         cbNode->presence->TTLlevel++;
1521                         OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1522                                                 cbNode->presence->TTLlevel);
1523                     }
1524                     else
1525                     {
1526                         result = OC_STACK_INVALID_IP;
1527                         goto exit;
1528                     }
1529                     HandleStackResponses(response);
1530                 }
1531                 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1532                 {
1533                     OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1534                     OCCoAPToken token;
1535                     OCGenerateCoAPToken(&token);
1536                     result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1537                             &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1538                     if(result != OC_STACK_OK)
1539                     {
1540                         goto exit;
1541                     }
1542                     cbNode->presence->TTLlevel++;
1543                     OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1544                 }
1545             }
1546         }
1547     }
1548 exit:
1549     if (result != OC_STACK_OK)
1550     {
1551         OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1552     }
1553     return result;
1554 }
1555 #endif
1556
1557 /**
1558  * Called in main loop of OC client or server.  Allows low-level processing of
1559  * stack services.
1560  *
1561  * @return
1562  *     OC_STACK_OK    - no errors
1563  *     OC_STACK_ERROR - stack process error
1564  */
1565 OCStackResult OCProcess() {
1566
1567     OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1568     #ifdef WITH_PRESENCE
1569     OCProcessPresence();
1570     #endif
1571 #ifdef CA_INT
1572     CAHandleRequestResponse();
1573 #else
1574     OCProcessCoAP();
1575 #endif // CA_INT
1576
1577     return OC_STACK_OK;
1578 }
1579
1580 #ifdef WITH_PRESENCE
1581 /**
1582  * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1583  * presence notifications to clients via multicast. Once this API has been called with a success,
1584  * clients may query for this server's presence and this server's stack will respond via multicast.
1585  *
1586  * Server can call this function when it comes online for the first time, or when it comes back
1587  * online from offline mode, or when it re enters network.
1588  *
1589  * @param ttl - Time To Live in seconds
1590  * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1591  *
1592  * @return
1593  *     OC_STACK_OK      - No errors; Success
1594  */
1595 OCStackResult OCStartPresence(const uint32_t ttl)
1596 {
1597     OCChangeResourceProperty(
1598             &(((OCResource *)presenceResource.handle)->resourceProperties),
1599             OC_ACTIVE, 1);
1600
1601     if(ttl > 0)
1602     {
1603         presenceResource.presenceTTL = ttl;
1604     }
1605
1606     if(OC_PRESENCE_UNINITIALIZED == presenceState)
1607     {
1608         OCDevAddr multiCastAddr;
1609         OCCoAPToken token;
1610
1611         presenceState = OC_PRESENCE_INITIALIZED;
1612         OCGenerateCoAPToken(&token);
1613         OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1614         //add the presence observer
1615         AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1616             (OCResource *)presenceResource.handle, OC_LOW_QOS);
1617     }
1618
1619     // Each time OCStartPresence is called
1620     // a different random 32-bit integer number is used
1621     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1622
1623     return SendPresenceNotification(NULL);
1624 }
1625
1626 /**
1627  * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1628  * presence notifications to clients via multicast. Once this API has been called with a success,
1629  * this server's stack will not respond to clients querying for this server's presence.
1630  *
1631  * Server can call this function when it is terminating, going offline, or when going
1632  * away from network.
1633  *
1634  * @return
1635  *     OC_STACK_OK      - No errors; Success
1636  */
1637 OCStackResult OCStopPresence()
1638 {
1639     OCStackResult result = OC_STACK_ERROR;
1640     //make resource inactive
1641     result = OCChangeResourceProperty(
1642             &(((OCResource *) presenceResource.handle)->resourceProperties),
1643             OC_ACTIVE, 0);
1644     result = SendPresenceNotification(NULL);
1645
1646     return result;
1647 }
1648 #endif
1649
1650
1651 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1652 {
1653     defaultDeviceHandler = entityHandler;
1654
1655     return OC_STACK_OK;
1656 }
1657
1658 /**
1659  * Create a resource
1660  *
1661  * @param handle - pointer to handle to newly created resource.  Set by ocstack.  Used to refer to resource
1662  * @param resourceTypeName - name of resource type.  Example: "core.led"
1663  * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
1664  * @param uri - URI of the resource.  Example:  "/a/led"
1665  * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1666  *                        NULL for default entity handler
1667  * @param resourceProperties - properties supported by resource.  Example: OC_DISCOVERABLE|OC_OBSERVABLE
1668  *
1669  * @return
1670  *     OC_STACK_OK    - no errors
1671  *     OC_STACK_ERROR - stack process error
1672  */
1673 OCStackResult OCCreateResource(OCResourceHandle *handle,
1674         const char *resourceTypeName,
1675         const char *resourceInterfaceName,
1676         const char *uri, OCEntityHandler entityHandler,
1677         uint8_t resourceProperties) {
1678
1679     OCResource *pointer = NULL;
1680     char *str = NULL;
1681     size_t size;
1682     OCStackResult result = OC_STACK_ERROR;
1683
1684     OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1685
1686     if(myStackMode == OC_CLIENT)
1687     {
1688         return result;
1689     }
1690     // Validate parameters
1691     // Is it presented during resource discovery?
1692     if (!handle || !resourceTypeName || !uri) {
1693         OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1694         return OC_STACK_INVALID_PARAM;
1695     }
1696
1697     if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1698         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1699     }
1700
1701     // Make sure resourceProperties bitmask has allowed properties specified
1702     if (resourceProperties
1703             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1704         OC_LOG(ERROR, TAG, PCF("Invalid property"));
1705         return OC_STACK_INVALID_PARAM;
1706     }
1707
1708     // If the headResource is NULL, then no resources have been created...
1709     pointer = headResource;
1710     if (pointer) {
1711         // At least one resources is in the resource list, so we need to search for
1712         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
1713         while (pointer) {
1714             if (strcmp(uri, pointer->uri) == 0) {
1715                 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1716                 return OC_STACK_INVALID_PARAM;
1717             }
1718             pointer = pointer->next;
1719         }
1720     }
1721     // Create the pointer and insert it into the resource list
1722     pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1723     if (!pointer) {
1724         goto exit;
1725     }
1726     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1727
1728     insertResource(pointer);
1729
1730     // Set the uri
1731     size = strlen(uri) + 1;
1732     str = (char *) OCMalloc(size);
1733     if (!str) {
1734         goto exit;
1735     }
1736     strncpy(str, uri, size);
1737     pointer->uri = str;
1738
1739     // Set properties.  Set OC_ACTIVE
1740     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1741             | OC_ACTIVE);
1742
1743     // Add the resourcetype to the resource
1744     result = BindResourceTypeToResource(pointer, resourceTypeName);
1745     if (result != OC_STACK_OK) {
1746         OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1747         goto exit;
1748     }
1749
1750     // Add the resourceinterface to the resource
1751     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1752     if (result != OC_STACK_OK) {
1753         OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1754         goto exit;
1755     }
1756
1757     // If an entity handler has been passed, attach it to the newly created
1758     // resource.  Otherwise, set the default entity handler.
1759     if (entityHandler)
1760     {
1761         pointer->entityHandler = entityHandler;
1762     }
1763     else
1764     {
1765         pointer->entityHandler = defaultResourceEHandler;
1766     }
1767
1768     *handle = pointer;
1769     result = OC_STACK_OK;
1770
1771     #ifdef WITH_PRESENCE
1772     if(presenceResource.handle)
1773     {
1774         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1775         SendPresenceNotification(pointer->rsrcType);
1776     }
1777     #endif
1778 exit:
1779     if (result != OC_STACK_OK)
1780     {
1781         // Deep delete of resource and other dynamic elements that it contains
1782         deleteResource(pointer);
1783         OCFree(str);
1784     }
1785     return result;
1786 }
1787
1788
1789
1790 /**
1791  * Create a resource. with host ip address for remote resource
1792  *
1793  * @param handle - pointer to handle to newly created resource.  Set by ocstack.
1794  *                 Used to refer to resource
1795  * @param resourceTypeName - name of resource type.  Example: "core.led"
1796  * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
1797  * @param host - HOST address of the remote resource.  Example:  "coap://xxx.xxx.xxx.xxx:xxxxx"
1798  * @param uri - URI of the resource.  Example:  "/a/led"
1799  * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1800  *                        NULL for default entity handler
1801  * @param resourceProperties - properties supported by resource.
1802  *                             Example: OC_DISCOVERABLE|OC_OBSERVABLE
1803  *
1804  * @return
1805  *     OC_STACK_OK    - no errors
1806  *     OC_STACK_ERROR - stack process error
1807  */
1808
1809 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1810         const char *resourceTypeName,
1811         const char *resourceInterfaceName,
1812         const char *host,
1813         const char *uri,
1814         OCEntityHandler entityHandler,
1815         uint8_t resourceProperties)
1816 {
1817     char *str = NULL;
1818     size_t size;
1819     OCStackResult result = OC_STACK_ERROR;
1820
1821     result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1822                                 uri, entityHandler, resourceProperties);
1823
1824     if (result != OC_STACK_ERROR)
1825     {
1826         // Set the uri
1827         size = strlen(host) + 1;
1828         str = (char *) OCMalloc(size);
1829         if (!str)
1830         {
1831             return OC_STACK_ERROR;
1832         }
1833         strncpy(str, host, size);
1834         ((OCResource *) *handle)->host = str;
1835     }
1836
1837     return result;
1838 }
1839
1840 /**
1841  * Add a resource to a collection resource.
1842  *
1843  * @param collectionHandle - handle to the collection resource
1844  * @param resourceHandle - handle to resource to be added to the collection resource
1845  *
1846  * @return
1847  *     OC_STACK_OK    - no errors
1848  *     OC_STACK_ERROR - stack process error
1849  *     OC_STACK_INVALID_PARAM - invalid collectionhandle
1850  */
1851 OCStackResult OCBindResource(
1852         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1853     OCResource *resource;
1854     uint8_t i;
1855
1856     OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1857
1858     // Validate parameters
1859     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1860     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1861     // Container cannot contain itself
1862     if (collectionHandle == resourceHandle) {
1863         OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1864         return OC_STACK_INVALID_PARAM;
1865     }
1866
1867     // Use the handle to find the resource in the resource linked list
1868     resource = findResource((OCResource *) collectionHandle);
1869     if (!resource) {
1870         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1871         return OC_STACK_INVALID_PARAM;
1872     }
1873
1874     // Look for an open slot to add add the child resource.
1875     // If found, add it and return success
1876     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1877         if (!resource->rsrcResources[i]) {
1878             resource->rsrcResources[i] = (OCResource *) resourceHandle;
1879             OC_LOG(INFO, TAG, PCF("resource bound"));
1880             return OC_STACK_OK;
1881         }
1882     }
1883
1884     #ifdef WITH_PRESENCE
1885     if(presenceResource.handle)
1886     {
1887         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1888         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1889     }
1890     #endif
1891
1892     // Unable to add resourceHandle, so return error
1893     return OC_STACK_ERROR;
1894 }
1895
1896 /**
1897  * Remove a resource from a collection resource.
1898  *
1899  * @param collectionHandle - handle to the collection resource
1900  * @param resourceHandle - handle to resource to be added to the collection resource
1901  *
1902  * @return
1903  *     OC_STACK_OK    - no errors
1904  *     OC_STACK_ERROR - stack process error
1905  *     OC_STACK_INVALID_PARAM - invalid collectionHandle
1906  */
1907 OCStackResult OCUnBindResource(
1908         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1909     OCResource *resource;
1910     uint8_t i;
1911
1912     OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1913
1914     // Validate parameters
1915     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1916     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1917     // Container cannot contain itself
1918     if (collectionHandle == resourceHandle) {
1919         OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1920         return OC_STACK_INVALID_PARAM;
1921     }
1922
1923     // Use the handle to find the resource in the resource linked list
1924     resource = findResource((OCResource *) collectionHandle);
1925     if (!resource) {
1926         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1927         return OC_STACK_INVALID_PARAM;
1928     }
1929
1930     // Look for an open slot to add add the child resource.
1931     // If found, add it and return success
1932     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1933         if (resourceHandle == resource->rsrcResources[i]) {
1934             resource->rsrcResources[i] = (OCResource *) NULL;
1935             OC_LOG(INFO, TAG, PCF("resource unbound"));
1936             return OC_STACK_OK;
1937         }
1938     }
1939
1940     OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1941
1942     #ifdef WITH_PRESENCE
1943     if(presenceResource.handle)
1944     {
1945         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1946         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1947     }
1948     #endif
1949
1950     // Unable to add resourceHandle, so return error
1951     return OC_STACK_ERROR;
1952 }
1953
1954 OCStackResult BindResourceTypeToResource(OCResource* resource,
1955                                             const char *resourceTypeName)
1956 {
1957     OCResourceType *pointer = NULL;
1958     char *str = NULL;
1959     size_t size;
1960     OCStackResult result = OC_STACK_ERROR;
1961
1962     OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1963
1964     // Validate parameters
1965     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1966     // TODO:  Does resource attribute resentation really have to be maintained in stack?
1967     // Is it presented during resource discovery?
1968
1969     TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1970
1971     // Create the resourcetype and insert it into the resource list
1972     pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1973     if (!pointer) {
1974         goto exit;
1975     }
1976
1977     // Set the resourceTypeName
1978     size = strlen(resourceTypeName) + 1;
1979     str = (char *) OCMalloc(size);
1980     if (!str) {
1981         goto exit;
1982     }
1983     strncpy(str, resourceTypeName, size);
1984     pointer->resourcetypename = str;
1985
1986     insertResourceType(resource, pointer);
1987     result = OC_STACK_OK;
1988
1989     exit: if (result != OC_STACK_OK) {
1990         OCFree(pointer);
1991         OCFree(str);
1992     }
1993
1994     return result;
1995 }
1996
1997 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1998         const char *resourceInterfaceName)
1999 {
2000     OCResourceInterface *pointer = NULL;
2001     char *str = NULL;
2002     size_t size;
2003     OCStackResult result = OC_STACK_ERROR;
2004
2005     OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2006
2007     // Validate parameters
2008     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2009
2010     TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2011
2012     // Create the resourceinterface and insert it into the resource list
2013     pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2014     if (!pointer) {
2015         goto exit;
2016     }
2017
2018     // Set the resourceinterface name
2019     size = strlen(resourceInterfaceName) + 1;
2020     str = (char *) OCMalloc(size);
2021     if (!str) {
2022         goto exit;
2023     }
2024     strncpy(str, resourceInterfaceName, size);
2025     pointer->name = str;
2026
2027     // Bind the resourceinterface to the resource
2028     insertResourceInterface(resource, pointer);
2029
2030     result = OC_STACK_OK;
2031
2032     exit: if (result != OC_STACK_OK) {
2033         OCFree(pointer);
2034         OCFree(str);
2035     }
2036
2037     return result;
2038 }
2039
2040 /**
2041  * Bind a resourcetype to a resource.
2042  *
2043  * @param handle - handle to the resource
2044  * @param resourceTypeName - name of resource type.  Example: "core.led"
2045  *
2046  * @return
2047  *     OC_STACK_OK    - no errors
2048  *     OC_STACK_ERROR - stack process error
2049  */
2050 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2051         const char *resourceTypeName) {
2052
2053     OCStackResult result = OC_STACK_ERROR;
2054     OCResource *resource;
2055
2056     // Make sure resource exists
2057     resource = findResource((OCResource *) handle);
2058     if (!resource) {
2059         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2060         return OC_STACK_ERROR;
2061     }
2062
2063     // call internal function
2064     result = BindResourceTypeToResource(resource, resourceTypeName);
2065
2066     #ifdef WITH_PRESENCE
2067     if(presenceResource.handle)
2068     {
2069         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2070         SendPresenceNotification(resource->rsrcType);
2071     }
2072     #endif
2073
2074     return result;
2075 }
2076
2077 /**
2078  * Bind a resourceinterface to a resource.
2079  *
2080  * @param handle - handle to the resource
2081  * @param resourceInterfaceName - name of resource interface.  Example: "oc.mi.b"
2082  *
2083  * @return
2084  *     OC_STACK_OK    - no errors
2085  *     OC_STACK_ERROR - stack process error
2086  */
2087
2088 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2089         const char *resourceInterfaceName) {
2090
2091     OCStackResult result = OC_STACK_ERROR;
2092     OCResource *resource;
2093
2094     // Make sure resource exists
2095     resource = findResource((OCResource *) handle);
2096     if (!resource) {
2097         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2098         return OC_STACK_ERROR;
2099     }
2100
2101     // call internal function
2102     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2103
2104     #ifdef WITH_PRESENCE
2105     if(presenceResource.handle)
2106     {
2107         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2108         SendPresenceNotification(resource->rsrcType);
2109     }
2110     #endif
2111
2112     return result;
2113 }
2114
2115 /**
2116  * Get the number of resources that have been created in the stack.
2117  *
2118  * @param numResources - pointer to count variable
2119  *
2120  * @return
2121  *     OC_STACK_OK    - no errors
2122  *     OC_STACK_ERROR - stack process error
2123
2124  */
2125 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2126     OCResource *pointer = headResource;
2127
2128     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2129     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2130     *numResources = 0;
2131     while (pointer) {
2132         *numResources = *numResources + 1;
2133         pointer = pointer->next;
2134     }
2135     return OC_STACK_OK;
2136 }
2137
2138 /**
2139  * Get a resource handle by index.
2140  *
2141  * @param index - index of resource, 0 to Count - 1
2142  *
2143  * @return
2144  *    Resource handle - if found
2145  *    NULL - if not found
2146  */
2147 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2148     OCResource *pointer = headResource;
2149     uint8_t i = 0;
2150
2151     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2152
2153     // Iterate through the list
2154     while ((i < index) && pointer) {
2155         i++;
2156         pointer = pointer->next;
2157     }
2158     return (OCResourceHandle) pointer;
2159 }
2160
2161 /**
2162  * Delete resource specified by handle.  Deletes resource and all resourcetype and resourceinterface
2163  * linked lists.
2164  *
2165  * @param handle - handle of resource to be deleted
2166  *
2167  * @return
2168  *     OC_STACK_OK              - no errors
2169  *     OC_STACK_ERROR           - stack process error
2170  *     OC_STACK_NO_RESOURCE     - resource not found
2171  *     OC_STACK_INVALID_PARAM   - invalid param
2172  */
2173 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2174     OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2175
2176     if (!handle) {
2177         OC_LOG(ERROR, TAG, PCF("Invalid param"));
2178         return OC_STACK_INVALID_PARAM;
2179     }
2180
2181     OCResource *resource = findResource((OCResource *) handle);
2182     if (resource == NULL) {
2183         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2184         return OC_STACK_NO_RESOURCE;
2185     }
2186
2187     if (deleteResource((OCResource *) handle) == 0) {
2188         OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2189         return OC_STACK_ERROR;
2190     }
2191
2192     return OC_STACK_OK;
2193 }
2194
2195 /**
2196  * Get the URI of the resource specified by handle.
2197  *
2198  * @param handle - handle of resource
2199  * @return
2200  *    URI string - if resource found
2201  *    NULL - resource not found
2202  */
2203 const char *OCGetResourceUri(OCResourceHandle handle) {
2204     OCResource *resource;
2205     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2206
2207     resource = findResource((OCResource *) handle);
2208     if (resource) {
2209         return resource->uri;
2210     }
2211     return (const char *) NULL;
2212 }
2213
2214 /**
2215  * Get the properties of the resource specified by handle.
2216  * NOTE: that after a resource is created, the OC_ACTIVE property is set
2217  * for the resource by the stack.
2218  *
2219  * @param handle - handle of resource
2220  * @return
2221  *    property bitmap - if resource found
2222  *    NULL - resource not found
2223  */
2224 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2225     OCResource *resource;
2226     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2227
2228     resource = findResource((OCResource *) handle);
2229     if (resource) {
2230         return resource->resourceProperties;
2231     }
2232     return 0;
2233 }
2234
2235 /**
2236  * Get the number of resource types of the resource.
2237  *
2238  * @param handle - handle of resource
2239  * @param numResourceTypes - pointer to count variable
2240  *
2241  * @return
2242  *     OC_STACK_OK    - no errors
2243  *     OC_STACK_ERROR - stack process error
2244  */
2245 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2246         uint8_t *numResourceTypes) {
2247     OCResource *resource;
2248     OCResourceType *pointer;
2249
2250     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2251     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2252     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2253
2254     *numResourceTypes = 0;
2255
2256     resource = findResource((OCResource *) handle);
2257     if (resource) {
2258         pointer = resource->rsrcType;
2259         while (pointer) {
2260             *numResourceTypes = *numResourceTypes + 1;
2261             pointer = pointer->next;
2262         }
2263     }
2264     return OC_STACK_OK;
2265 }
2266
2267 /**
2268  * Get name of resource type of the resource.
2269  *
2270  * @param handle - handle of resource
2271  * @param index - index of resource, 0 to Count - 1
2272  *
2273  * @return
2274  *    resource type name - if resource found
2275  *    NULL - resource not found
2276  */
2277 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2278     OCResourceType *resourceType;
2279
2280     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2281
2282     resourceType = findResourceTypeAtIndex(handle, index);
2283     if (resourceType) {
2284         return resourceType->resourcetypename;
2285     }
2286     return (const char *) NULL;
2287 }
2288
2289
2290
2291 /**
2292  * Get the number of resource interfaces of the resource.
2293  *
2294  * @param handle - handle of resource
2295  * @param numResources - pointer to count variable
2296  *
2297  * @return
2298  *     OC_STACK_OK    - no errors
2299  *     OC_STACK_ERROR - stack process error
2300  */
2301 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2302         uint8_t *numResourceInterfaces) {
2303     OCResourceInterface *pointer;
2304     OCResource *resource;
2305
2306     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2307
2308     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2309     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2310
2311     *numResourceInterfaces = 0;
2312     resource = findResource((OCResource *) handle);
2313     if (resource) {
2314         pointer = resource->rsrcInterface;
2315         while (pointer) {
2316             *numResourceInterfaces = *numResourceInterfaces + 1;
2317             pointer = pointer->next;
2318         }
2319     }
2320     return OC_STACK_OK;
2321 }
2322
2323 /**
2324  * Get name of resource interface of the resource.
2325  *
2326  * @param handle - handle of resource
2327  * @param index - index of resource, 0 to Count - 1
2328  *
2329  * @return
2330  *    resource interface name - if resource found
2331  *    NULL - resource not found
2332  */
2333 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2334     OCResourceInterface *resourceInterface;
2335
2336     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2337
2338     resourceInterface = findResourceInterfaceAtIndex(handle, index);
2339     if (resourceInterface) {
2340         return resourceInterface->name;
2341     }
2342     return (const char *) NULL;
2343 }
2344
2345 /**
2346  * Get resource handle from the collection resource by index.
2347  *
2348  * @param collectionHandle - handle of collection resource
2349  * @param index - index of contained resource, 0 to Count - 1
2350  *
2351  * @return
2352  *    handle to resource - if resource found
2353  *    NULL - resource not found
2354  */
2355 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2356         uint8_t index) {
2357     OCResource *resource;
2358
2359     OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2360
2361     if (index >= MAX_CONTAINED_RESOURCES) {
2362         return NULL;
2363     }
2364
2365     resource = findResource((OCResource *) collectionHandle);
2366     if (!resource) {
2367         return NULL;
2368     }
2369
2370     return resource->rsrcResources[index];
2371 }
2372
2373 /**
2374  * Bind an entity handler to the resource.
2375  *
2376  * @param handle - handle to the resource that the contained resource is to be bound
2377  * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2378  * @return
2379  *     OC_STACK_OK    - no errors
2380  *     OC_STACK_ERROR - stack process error
2381  */
2382 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2383         OCEntityHandler entityHandler) {
2384     OCResource *resource;
2385
2386     OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2387
2388     // Validate parameters
2389     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2390     //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2391
2392     // Use the handle to find the resource in the resource linked list
2393     resource = findResource((OCResource *)handle);
2394     if (!resource) {
2395         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2396         return OC_STACK_ERROR;
2397     }
2398
2399     // Bind the handler
2400     resource->entityHandler = entityHandler;
2401
2402     #ifdef WITH_PRESENCE
2403     if(presenceResource.handle)
2404     {
2405         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2406         SendPresenceNotification(resource->rsrcType);
2407     }
2408     #endif
2409
2410     return OC_STACK_OK;
2411 }
2412
2413 /**
2414  * Get the entity handler for a resource.
2415  *
2416  * @param handle - handle of resource
2417  *
2418  * @return
2419  *    entity handler - if resource found
2420  *    NULL - resource not found
2421  */
2422 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2423     OCResource *resource;
2424
2425     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2426
2427     // Use the handle to find the resource in the resource linked list
2428     resource = findResource((OCResource *)handle);
2429     if (!resource) {
2430         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2431         return NULL;
2432     }
2433
2434     // Bind the handler
2435     return resource->entityHandler;
2436 }
2437
2438 void incrementSequenceNumber(OCResource * resPtr)
2439 {
2440     // Increment the sequence number
2441     resPtr->sequenceNum += 1;
2442     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2443     {
2444         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2445     }
2446     return;
2447 }
2448
2449 /**
2450  * Notify Presence subscribers that a resource has been modified
2451  *
2452  * @param resourceType - Handle to the resourceType linked list of resource
2453  *                       that was modified.
2454  * @param qos          - Quality Of Service
2455  *
2456  */
2457 #ifdef WITH_PRESENCE
2458 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2459 {
2460     OCResource *resPtr = NULL;
2461     OCStackResult result;
2462     OCMethod method = OC_REST_PRESENCE;
2463     uint32_t maxAge = 0;
2464     resPtr = findResource((OCResource *) presenceResource.handle);
2465     if(NULL == resPtr)
2466     {
2467         return OC_STACK_NO_RESOURCE;
2468     }
2469     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2470     {
2471         maxAge = presenceResource.presenceTTL;
2472     }
2473     else
2474     {
2475         maxAge = 0;
2476     }
2477
2478     result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2479     return result;
2480 }
2481 #endif // WITH_PRESENCE
2482 /**
2483  * Notify observers that an observed value has changed.
2484  *
2485  * @param handle - handle of resource
2486  *
2487  * @return
2488  *     OC_STACK_OK    - no errors
2489  *     OC_STACK_NO_RESOURCE - invalid resource handle
2490  *     OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2491  */
2492 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2493
2494     OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2495
2496     OCResource *resPtr = NULL;
2497     OCStackResult result;
2498     OCMethod method = OC_REST_NOMETHOD;
2499     uint32_t maxAge = 0;
2500
2501     OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2502     #ifdef WITH_PRESENCE
2503     if(handle == presenceResource.handle)
2504     {
2505         return OC_STACK_OK;
2506     }
2507     #endif // WITH_PRESENCE
2508     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2509
2510     // Verify that the resource exists
2511     resPtr = findResource ((OCResource *) handle);
2512     if (NULL == resPtr)
2513     {
2514         return OC_STACK_NO_RESOURCE;
2515     }
2516     else
2517     {
2518         //only increment in the case of regular observing (not presence)
2519         incrementSequenceNumber(resPtr);
2520         method = OC_REST_OBSERVE;
2521         maxAge = MAX_OBSERVE_AGE;
2522         #ifdef WITH_PRESENCE
2523         result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2524         #else
2525         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2526         #endif
2527         return result;
2528     }
2529 }
2530
2531 OCStackResult
2532 OCNotifyListOfObservers (OCResourceHandle handle,
2533                          OCObservationId  *obsIdList,
2534                          uint8_t          numberOfIds,
2535                          unsigned char    *notificationJSONPayload,
2536                          OCQualityOfService qos)
2537 {
2538     OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2539
2540     OCResource *resPtr = NULL;
2541     //TODO: we should allow the server to define this
2542     uint32_t maxAge = MAX_OBSERVE_AGE;
2543
2544     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2545     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2546     VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2547
2548     // Verify that the resource exists
2549     resPtr = findResource ((OCResource *) handle);
2550     if (NULL == resPtr || myStackMode == OC_CLIENT)
2551     {
2552         return OC_STACK_NO_RESOURCE;
2553     }
2554     else
2555     {
2556         incrementSequenceNumber(resPtr);
2557     }
2558     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2559             notificationJSONPayload, maxAge, qos));
2560 }
2561
2562 /**
2563  * Send a response to a request.
2564  * The response can be a regular, slow, or block (i.e. a response that
2565  * is too large to be sent in a single PDU and must span multiple transmissions)
2566  *
2567  * @param response - pointer to structure that contains response parameters
2568  *
2569  * @return
2570  *     OC_STACK_OK                         - No errors; Success
2571  *     OC_STACK_INVALID_PARAM              - Invalid pointer to OCServerResponse
2572  *     OC_STACK_INVALID_REQUEST_HANDLE     - Request handle not found
2573  *     OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2574  *                                           persistent response buffer is necessary
2575  */
2576 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2577 {
2578     OCStackResult result = OC_STACK_ERROR;
2579     OCServerRequest *serverRequest = NULL;
2580
2581     OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2582
2583     // Validate input parameters
2584     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2585     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2586
2587     // TODO: Placeholder for creating a response entry when implementing
2588     // block transfer feature
2589
2590     // If a response payload is present, check if block transfer is required
2591     if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2592             (const char *)ehResponse->payload, ehResponse->payloadSize))
2593     {
2594         OC_LOG(INFO, TAG, PCF("Block transfer required"));
2595
2596         // Persistent response buffer is needed for block transfer
2597         if (!ehResponse->persistentBufferFlag)
2598         {
2599             OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2600             return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2601         }
2602         // TODO: Placeholder for block transfer handling
2603         // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2604             // when implementing the block transfer feature
2605     }
2606     else
2607     {
2608         // Normal response
2609
2610         // Get pointer to request info
2611         serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2612         if(serverRequest)
2613         {
2614             result = serverRequest->ehResponseHandler(ehResponse);
2615         }
2616     }
2617     return result;
2618 }
2619
2620 /**
2621  * Cancel a response.  Applies to a block response
2622  *
2623  * @param responseHandle - response handle set by stack in OCServerResponse after
2624  *                         OCDoResponse is called
2625  *
2626  * @return
2627  *     OC_STACK_OK               - No errors; Success
2628  *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
2629  */
2630 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2631 {
2632     OCStackResult result = OC_STACK_NOTIMPL;
2633
2634     OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2635
2636     // TODO: validate response handle
2637
2638     return result;
2639 }
2640
2641 //-----------------------------------------------------------------------------
2642 // Private internal function definitions
2643 //-----------------------------------------------------------------------------
2644 /**
2645  * Generate handle of OCDoResource invocation for callback management.
2646  */
2647 static OCDoHandle GenerateInvocationHandle()
2648 {
2649     OCDoHandle handle = NULL;
2650     // Generate token here, it will be deleted when the transaction is deleted
2651     handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2652     if (handle)
2653     {
2654         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2655     }
2656
2657     return handle;
2658 }
2659 #ifdef WITH_PRESENCE
2660 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2661         OCResourceProperty resourceProperties, uint8_t enable)
2662 {
2663     if (resourceProperties
2664             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2665         OC_LOG(ERROR, TAG, PCF("Invalid property"));
2666         return OC_STACK_INVALID_PARAM;
2667     }
2668     if(!enable)
2669     {
2670         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2671     }
2672     else
2673     {
2674         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2675     }
2676     return OC_STACK_OK;
2677 }
2678 #endif
2679
2680 /**
2681  * Initialize resource data structures, variables, etc.
2682  */
2683 OCStackResult initResources() {
2684     OCStackResult result = OC_STACK_OK;
2685     // Init application resource vars
2686     headResource = NULL;
2687     // Init Virtual Resources
2688     #ifdef WITH_PRESENCE
2689     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2690     //presenceResource.token = OCGenerateCoAPToken();
2691     result = OCCreateResource(&presenceResource.handle,
2692             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2693             "core.r",
2694             OC_PRESENCE_URI,
2695             NULL,
2696             OC_OBSERVABLE);
2697     //make resource inactive
2698     result = OCChangeResourceProperty(
2699             &(((OCResource *) presenceResource.handle)->resourceProperties),
2700             OC_ACTIVE, 0);
2701     #endif
2702     return result;
2703 }
2704
2705 /**
2706  * Add a resource to the end of the linked list of resources.
2707  *
2708  * @param resource - resource to be added
2709  */
2710 void insertResource(OCResource *resource) {
2711     OCResource *pointer;
2712
2713     if (!headResource) {
2714         headResource = resource;
2715     } else {
2716         pointer = headResource;
2717
2718         while (pointer->next) {
2719             pointer = pointer->next;
2720         }
2721         pointer->next = resource;
2722     }
2723     resource->next = NULL;
2724 }
2725
2726 /**
2727  * Find a resource in the linked list of resources.
2728  *
2729  * @param resource - resource to be found
2730  * @return
2731  *     NULL                - resource not found
2732  *     pointer to resource - pointer to resource that was found in the linked list
2733  */
2734 OCResource *findResource(OCResource *resource) {
2735     OCResource *pointer = headResource;
2736
2737     while (pointer) {
2738         if (pointer == resource) {
2739             return resource;
2740         }
2741         pointer = pointer->next;
2742     }
2743     return NULL;
2744 }
2745
2746 void deleteAllResources()
2747 {
2748     OCResource *pointer = headResource;
2749     OCResource *temp;
2750
2751     while (pointer)
2752     {
2753         temp = pointer->next;
2754         #ifdef WITH_PRESENCE
2755         if(pointer != (OCResource *) presenceResource.handle)
2756         {
2757             #endif // WITH_PRESENCE
2758             deleteResource(pointer);
2759             #ifdef WITH_PRESENCE
2760         }
2761         #endif // WITH_PRESENCE
2762         pointer = temp;
2763     }
2764
2765     #ifdef WITH_PRESENCE
2766     // Ensure that the last resource to be deleted is the presence resource. This allows for all
2767     // presence notification attributed to their deletion to be processed.
2768     deleteResource((OCResource *) presenceResource.handle);
2769     #endif // WITH_PRESENCE
2770 }
2771
2772 /**
2773  * Delete the resource from the linked list.
2774  *
2775  * @param resource - resource to be deleted
2776  * @return
2777  *    0 - error
2778  *    1 - success
2779  */
2780 int deleteResource(OCResource *resource) {
2781     OCResource *prev = NULL;
2782     OCResource *temp;
2783
2784     temp = headResource;
2785     while (temp) {
2786         if (temp == resource) {
2787             // Invalidate all Resource Properties.
2788             resource->resourceProperties = (OCResourceProperty) 0;
2789             #ifdef WITH_PRESENCE
2790             if(resource != (OCResource *) presenceResource.handle)
2791             {
2792             #endif // WITH_PRESENCE
2793                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2794             #ifdef WITH_PRESENCE
2795             }
2796
2797             if(presenceResource.handle)
2798             {
2799                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2800                 if(resource != (OCResource *) presenceResource.handle)
2801                 {
2802                     SendPresenceNotification(resource->rsrcType);
2803                 }
2804                 else
2805                 {
2806                     SendPresenceNotification(NULL);
2807                 }
2808             }
2809         #endif
2810
2811             if (temp == headResource) {
2812                 headResource = temp->next;
2813             } else {
2814                 prev->next = temp->next;
2815             }
2816
2817             deleteResourceElements(temp);
2818             OCFree(temp);
2819             return 1;
2820         } else {
2821             prev = temp;
2822             temp = temp->next;
2823         }
2824     }
2825
2826     return 0;
2827 }
2828
2829 /**
2830  * Delete all of the dynamically allocated elements that were created for the resource.
2831  *
2832  * @param resource - specified resource
2833  */
2834 void deleteResourceElements(OCResource *resource) {
2835     if (!resource) {
2836         return;
2837     }
2838
2839     // remove URI
2840     OCFree(resource->uri);
2841
2842     // Delete resourcetype linked list
2843     deleteResourceType(resource->rsrcType);
2844
2845     // Delete resourceinterface linked list
2846     deleteResourceInterface(resource->rsrcInterface);
2847 }
2848
2849 /**
2850  * Delete all of the dynamically allocated elements that were created for the resource type.
2851  *
2852  * @param resourceType - specified resource type
2853  */
2854 void deleteResourceType(OCResourceType *resourceType) {
2855     OCResourceType *pointer = resourceType;
2856     OCResourceType *next;
2857
2858     while (pointer) {
2859         next = pointer->next;
2860         OCFree(pointer->resourcetypename);
2861         OCFree(pointer);
2862         pointer = next;
2863     }
2864 }
2865
2866 /**
2867  * Delete all of the dynamically allocated elements that were created for the resource interface.
2868  *
2869  * @param resourceInterface - specified resource interface
2870  */
2871 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2872     OCResourceInterface *pointer = resourceInterface;
2873     OCResourceInterface *next;
2874
2875     while (pointer) {
2876         next = pointer->next;
2877         OCFree(pointer->name);
2878         OCFree(pointer);
2879         pointer = next;
2880     }
2881 }
2882
2883 /**
2884  * Insert a resource type into a resource's resource type linked list.
2885  *
2886  * @param resource - resource where resource type is to be inserted
2887  * @param resourceType - resource type to be inserted
2888  */
2889 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2890     OCResourceType *pointer;
2891
2892     if (resource && !resource->rsrcType) {
2893         resource->rsrcType = resourceType;
2894     } else {
2895         if(resource)
2896         {
2897             pointer = resource->rsrcType;
2898         }
2899         else
2900         {
2901             pointer = resourceType;
2902         }
2903         while (pointer->next) {
2904             pointer = pointer->next;
2905         }
2906         pointer->next = resourceType;
2907     }
2908     resourceType->next = NULL;
2909 }
2910
2911 /**
2912  * Get a resource type at the specified index within a resource.
2913  *
2914  * @param handle - handle of resource
2915  * @param index - index of resource type
2916  *
2917  * @return
2918  *    resourcetype - if found
2919  *    NULL - not found
2920  */
2921 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2922     OCResource *resource;
2923     OCResourceType *pointer;
2924     uint8_t i;
2925
2926     // Find the specified resource
2927     resource = findResource((OCResource *) handle);
2928     if (!resource) {
2929         return NULL;
2930     }
2931
2932     // Make sure a resource has a resourcetype
2933     if (!resource->rsrcType) {
2934         return NULL;
2935     }
2936
2937     // Iterate through the list
2938     pointer = resource->rsrcType;
2939     i = 0;
2940     while ((i < index) && pointer) {
2941         i++;
2942         pointer = pointer->next;
2943     }
2944     return pointer;
2945 }
2946
2947 /**
2948  * Finds a resource type in an OCResourceType link-list.
2949  *
2950  * @param resourceTypeList - the link-list to be searched through
2951  * @param resourceTypeName - the key to search for
2952  *
2953  * @return
2954  *      resourceType that matches the key (ie. resourceTypeName)
2955  *      NULL - either an invalid parameter or this function was unable to find the key.
2956  */
2957 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2958 {
2959     if(resourceTypeList && resourceTypeName)
2960     {
2961         OCResourceType * rtPointer = resourceTypeList;
2962         while(resourceTypeName && rtPointer)
2963         {
2964             if(rtPointer->resourcetypename &&
2965                     strcmp(resourceTypeName, (const char *)
2966                     (rtPointer->resourcetypename)) == 0)
2967             {
2968                 break;
2969             }
2970             rtPointer = rtPointer->next;
2971         }
2972         return rtPointer;
2973     }
2974     return NULL;
2975 }
2976 /**
2977  * Insert a resource interface into a resource's resource interface linked list.
2978  *
2979  * @param resource - resource where resource interface is to be inserted
2980  * @param resourceInterface - resource interface to be inserted
2981  */
2982 void insertResourceInterface(OCResource *resource,
2983         OCResourceInterface *resourceInterface) {
2984     OCResourceInterface *pointer;
2985
2986     if (!resource->rsrcInterface) {
2987         resource->rsrcInterface = resourceInterface;
2988     } else {
2989         pointer = resource->rsrcInterface;
2990         while (pointer->next) {
2991             pointer = pointer->next;
2992         }
2993         pointer->next = resourceInterface;
2994     }
2995     resourceInterface->next = NULL;
2996 }
2997
2998 /**
2999  * Get a resource interface at the specified index within a resource.
3000  *
3001  * @param handle - handle of resource
3002  * @param index - index of resource interface
3003  *
3004  * @return
3005  *    resourceinterface - if found
3006  *    NULL - not found
3007  */
3008 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3009         uint8_t index) {
3010     OCResource *resource;
3011     OCResourceInterface *pointer;
3012     uint8_t i = 0;
3013
3014     // Find the specified resource
3015     resource = findResource((OCResource *) handle);
3016     if (!resource) {
3017         return NULL;
3018     }
3019
3020     // Make sure a resource has a resourceinterface
3021     if (!resource->rsrcInterface) {
3022         return NULL;
3023     }
3024
3025     // Iterate through the list
3026     pointer = resource->rsrcInterface;
3027
3028     while ((i < index) && pointer) {
3029         i++;
3030         pointer = pointer->next;
3031     }
3032     return pointer;
3033 }
3034
3035 /**
3036  * Determine if a request/response must be sent in a block transfer because it is too large to be
3037  * sent in a single PDU.  This function can be used for either a request or a response
3038  *
3039  * @param request  - NULL or pointer to request
3040  * @param response - NULL or pointer to response
3041  * @param size     - 0 or size of the request/response.  If 0, strlen is used for determining
3042  *                   the length of the request/response
3043  *
3044  * @return
3045  *    0 - packet transfer NOT required (i.e. normal request/response)
3046  *    1 - packet transfer required (i.e. block transfer needed)
3047  */
3048 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3049 {
3050     uint8_t result = 0;
3051
3052     // Determine if we are checking a request or a response
3053     if (request)
3054     {
3055         // If size is greater than 0, use it for the request size value, otherwise
3056         // assume request is null terminated and use strlen for size value
3057         if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3058         {
3059             result = 1;
3060         }
3061     }
3062     else if (response)
3063     {
3064         // If size is greater than 0, use it for the response size value, otherwise
3065         // assume response is null terminated and use strlen for size value
3066         if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3067         {
3068             result = 1;
3069         }
3070     }
3071     return result;
3072 }
3073
3074 /**
3075  * Retrieves a resource type based upon a uri string if the uri string contains only just one
3076  * resource attribute (and that has to be of type "rt").
3077  *
3078  * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
3079  * or newURI before passing in.
3080  *
3081  * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
3082  * @param resourceType - The resource type to be populated; pass by reference.
3083  * @param newURI - Return URI without resourceType appended to the end of it. This is used to
3084  *                 ensure that the uri parameter is not modified; pass by reference.
3085  *
3086  * @return
3087  *  OC_STACK_INVALID_URI   - Returns this if the URI is invalid/NULL.
3088  *  OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3089  *  OC_STACK_OK            - Success
3090  */
3091 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
3092 {
3093     if(!uri)
3094     {
3095         return OC_STACK_INVALID_URI;
3096     }
3097     if(!resourceType || !newURI)
3098     {
3099         return OC_STACK_INVALID_PARAM;
3100     }
3101     char * leftToken = NULL;
3102     char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3103     if(!tempURI)
3104     {
3105         goto exit;
3106     }
3107     strcpy(tempURI, uri);
3108     leftToken = strtok((char *)tempURI, "?");
3109
3110     while(leftToken != NULL)
3111     {
3112         if(strncmp(leftToken, "rt=", 3) == 0)
3113         {
3114             *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
3115             if(!*resourceType)
3116             {
3117                 goto exit;
3118             }
3119             strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
3120             break;
3121         }
3122         leftToken = strtok(NULL, "?");
3123     }
3124
3125     *newURI = tempURI;
3126
3127     return OC_STACK_OK;
3128
3129     exit:
3130         return OC_STACK_NO_MEMORY;
3131 }
3132
3133 const ServerID OCGetServerInstanceID(void)
3134 {
3135     static bool generated = false;
3136     static ServerID sid;
3137
3138     if(generated)
3139     {
3140         return sid;
3141     }
3142
3143     sid = OCGetRandom();
3144     generated = true;
3145     return sid;
3146 }
3147
3148 const char* OCGetServerInstanceIDString(void)
3149 {
3150     // max printed length of a base 10
3151     // uint32 is 10 characters, so 11 includes null.
3152     // This will change as the representation gets switched
3153     // to another value
3154     static char buffer[11];
3155     int n = sprintf(buffer, "%u", OCGetServerInstanceID());
3156     if (n < 0)
3157     {
3158         buffer[0]='\0';
3159     }
3160
3161     return buffer;
3162 }