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