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