Merge branch 'master' into windows-port
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocstack.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21
22 //-----------------------------------------------------------------------------
23 // Includes
24 //-----------------------------------------------------------------------------
25
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
35 #endif
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
38 #endif
39 #include <inttypes.h>
40 #include <string.h>
41 #include <ctype.h>
42
43 #include "ocstack.h"
44 #include "ocstackinternal.h"
45 #include "ocresourcehandler.h"
46 #include "occlientcb.h"
47 #include "ocobserve.h"
48 #include "ocrandom.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
51 #include "logger.h"
52 #include "ocserverrequest.h"
53 #include "secureresourcemanager.h"
54 #include "doxmresource.h"
55 #include "cacommon.h"
56 #include "cainterface.h"
57 #include "ocpayload.h"
58 #include "ocpayloadcbor.h"
59
60 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
61 #include "routingutility.h"
62 #ifdef ROUTING_GATEWAY
63 #include "routingmanager.h"
64 #endif
65 #endif
66
67 #ifdef TCP_ADAPTER
68 #include "oickeepalive.h"
69 #endif
70
71 //#ifdef DIRECT_PAIRING
72 #include "directpairing.h"
73 //#endif
74
75 #ifdef HAVE_ARDUINO_TIME_H
76 #include "Time.h"
77 #endif
78 #ifdef HAVE_SYS_TIME_H
79 #include <sys/time.h>
80 #endif
81 #include "coap_time.h"
82 #include "utlist.h"
83 #include "pdu.h"
84
85 #ifdef HAVE_ARPA_INET_H
86 #include <arpa/inet.h>
87 #endif
88
89 #ifndef UINT32_MAX
90 #define UINT32_MAX   (0xFFFFFFFFUL)
91 #endif
92
93 //-----------------------------------------------------------------------------
94 // Typedefs
95 //-----------------------------------------------------------------------------
96 typedef enum
97 {
98     OC_STACK_UNINITIALIZED = 0,
99     OC_STACK_INITIALIZED,
100     OC_STACK_UNINIT_IN_PROGRESS
101 } OCStackState;
102
103 #ifdef WITH_PRESENCE
104 typedef enum
105 {
106     OC_PRESENCE_UNINITIALIZED = 0,
107     OC_PRESENCE_INITIALIZED
108 } OCPresenceState;
109 #endif
110
111 //-----------------------------------------------------------------------------
112 // Private variables
113 //-----------------------------------------------------------------------------
114 static OCStackState stackState = OC_STACK_UNINITIALIZED;
115
116 OCResource *headResource = NULL;
117 static OCResource *tailResource = NULL;
118 static OCResourceHandle platformResource = {0};
119 static OCResourceHandle deviceResource = {0};
120 #ifdef WITH_PRESENCE
121 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
122 static PresenceResource presenceResource;
123 static uint8_t PresenceTimeOutSize = 0;
124 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
125 #endif
126
127 static OCMode myStackMode;
128 #ifdef RA_ADAPTER
129 //TODO: revisit this design
130 static bool gRASetInfo = false;
131 #endif
132 OCDeviceEntityHandler defaultDeviceHandler;
133 void* defaultDeviceHandlerCallbackParameter = NULL;
134 static const char COAP_TCP[] = "coap+tcp:";
135 static const char CORESPEC[] = "core";
136
137 //#ifdef DIRECT_PAIRING
138 OCDirectPairingCB gDirectpairingCallback = NULL;
139 //#endif
140
141 //-----------------------------------------------------------------------------
142 // Macros
143 //-----------------------------------------------------------------------------
144 #define TAG  "OIC_RI_STACK"
145 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
146             {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
147 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
148              TAG, #arg " is NULL"); return (retVal); } }
149 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
150              TAG, #arg " is NULL"); return; } }
151 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
152     goto exit;} }
153
154 //TODO: we should allow the server to define this
155 #define MAX_OBSERVE_AGE (0x2FFFFUL)
156
157 #define MILLISECONDS_PER_SECOND   (1000)
158
159 //-----------------------------------------------------------------------------
160 // Private internal function prototypes
161 //-----------------------------------------------------------------------------
162
163 /**
164  * Generate handle of OCDoResource invocation for callback management.
165  *
166  * @return Generated OCDoResource handle.
167  */
168 static OCDoHandle GenerateInvocationHandle();
169
170 /**
171  * Initialize resource data structures, variables, etc.
172  *
173  * @return ::OC_STACK_OK on success, some other value upon failure.
174  */
175 static OCStackResult initResources();
176
177 /**
178  * Add a resource to the end of the linked list of resources.
179  *
180  * @param resource Resource to be added
181  */
182 static void insertResource(OCResource *resource);
183
184 /**
185  * Find a resource in the linked list of resources.
186  *
187  * @param resource Resource to be found.
188  * @return Pointer to resource that was found in the linked list or NULL if the resource was not
189  *         found.
190  */
191 static OCResource *findResource(OCResource *resource);
192
193 /**
194  * Insert a resource type into a resource's resource type linked list.
195  * If resource type already exists, it will not be inserted and the
196  * resourceType will be free'd.
197  * resourceType->next should be null to avoid memory leaks.
198  * Function returns silently for null args.
199  *
200  * @param resource Resource where resource type is to be inserted.
201  * @param resourceType Resource type to be inserted.
202  */
203 static void insertResourceType(OCResource *resource,
204         OCResourceType *resourceType);
205
206 /**
207  * Get a resource type at the specified index within a resource.
208  *
209  * @param handle Handle of resource.
210  * @param index Index of resource type.
211  *
212  * @return Pointer to resource type if found, NULL otherwise.
213  */
214 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
215         uint8_t index);
216
217 /**
218  * Insert a resource interface into a resource's resource interface linked list.
219  * If resource interface already exists, it will not be inserted and the
220  * resourceInterface will be free'd.
221  * resourceInterface->next should be null to avoid memory leaks.
222  *
223  * @param resource Resource where resource interface is to be inserted.
224  * @param resourceInterface Resource interface to be inserted.
225  */
226 static void insertResourceInterface(OCResource *resource,
227         OCResourceInterface *resourceInterface);
228
229 /**
230  * Get a resource interface at the specified index within a resource.
231  *
232  * @param handle Handle of resource.
233  * @param index Index of resource interface.
234  *
235  * @return Pointer to resource interface if found, NULL otherwise.
236  */
237 static OCResourceInterface *findResourceInterfaceAtIndex(
238         OCResourceHandle handle, uint8_t index);
239
240 /**
241  * Delete all of the dynamically allocated elements that were created for the resource type.
242  *
243  * @param resourceType Specified resource type.
244  */
245 static void deleteResourceType(OCResourceType *resourceType);
246
247 /**
248  * Delete all of the dynamically allocated elements that were created for the resource interface.
249  *
250  * @param resourceInterface Specified resource interface.
251  */
252 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
253
254 /**
255  * Delete all of the dynamically allocated elements that were created for the resource.
256  *
257  * @param resource Specified resource.
258  */
259 static void deleteResourceElements(OCResource *resource);
260
261 /**
262  * Delete resource specified by handle.  Deletes resource and all resourcetype and resourceinterface
263  * linked lists.
264  *
265  * @param handle Handle of resource to be deleted.
266  *
267  * @return ::OC_STACK_OK on success, some other value upon failure.
268  */
269 static OCStackResult deleteResource(OCResource *resource);
270
271 /**
272  * Delete all of the resources in the resource list.
273  */
274 static void deleteAllResources();
275
276 /**
277  * Increment resource sequence number.  Handles rollover.
278  *
279  * @param resPtr Pointer to resource.
280  */
281 static void incrementSequenceNumber(OCResource * resPtr);
282
283 /**
284  * Verify the lengths of the URI and the query separately.
285  *
286  * @param inputUri Input URI and query.
287  * @param uriLen The length of the initial URI with query.
288  * @return ::OC_STACK_OK on success, some other value upon failure.
289  */
290 static OCStackResult verifyUriQueryLength(const char * inputUri,
291         uint16_t uriLen);
292
293 /*
294  * Attempts to initialize every network interface that the CA Layer might have compiled in.
295  *
296  * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
297  * return something other than @ref CA_STATUS_OK, then this function fails.
298  *
299  * @return ::CA_STATUS_OK on success, some other value upon failure.
300  */
301 static CAResult_t OCSelectNetwork();
302
303 /**
304  * Get the CoAP ticks after the specified number of milli-seconds.
305  *
306  * @param afterMilliSeconds Milli-seconds.
307  * @return
308  *     CoAP ticks
309  */
310 static uint32_t GetTicks(uint32_t afterMilliSeconds);
311
312 /**
313  * Convert CAResult_t to OCStackResult.
314  *
315  * @param caResult CAResult_t code.
316  * @return ::OC_STACK_OK on success, some other value upon failure.
317  */
318 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
319
320 /**
321  * Convert CAResponseResult_t to OCStackResult.
322  *
323  * @param caCode CAResponseResult_t code.
324  * @return ::OC_STACK_OK on success, some other value upon failure.
325  */
326 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
327
328 /**
329  * Convert OCStackResult to CAResponseResult_t.
330  *
331  * @param caCode OCStackResult code.
332  * @param method OCMethod method the return code replies to.
333  * @return ::CA_CONTENT on OK, some other value upon failure.
334  */
335 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
336
337 /**
338  * Convert OCTransportFlags_t to CATransportModifiers_t.
339  *
340  * @param ocConType OCTransportFlags_t input.
341  * @return CATransportFlags
342  */
343 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
344
345 /**
346  * Convert CATransportFlags_t to OCTransportModifiers_t.
347  *
348  * @param caConType CATransportFlags_t input.
349  * @return OCTransportFlags
350  */
351 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
352
353 /**
354  * Handle response from presence request.
355  *
356  * @param endPoint CA remote endpoint.
357  * @param responseInfo CA response info.
358  * @return ::OC_STACK_OK on success, some other value upon failure.
359  */
360 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
361         const CAResponseInfo_t *responseInfo);
362
363 /**
364  * This function will be called back by CA layer when a response is received.
365  *
366  * @param endPoint CA remote endpoint.
367  * @param responseInfo CA response info.
368  */
369 static void HandleCAResponses(const CAEndpoint_t* endPoint,
370         const CAResponseInfo_t* responseInfo);
371
372 /**
373  * This function will be called back by CA layer when a request is received.
374  *
375  * @param endPoint CA remote endpoint.
376  * @param requestInfo CA request info.
377  */
378 static void HandleCARequests(const CAEndpoint_t* endPoint,
379         const CARequestInfo_t* requestInfo);
380
381 /**
382  * Extract query from a URI.
383  *
384  * @param uri Full URI with query.
385  * @param query Pointer to string that will contain query.
386  * @param newURI Pointer to string that will contain URI.
387  * @return ::OC_STACK_OK on success, some other value upon failure.
388  */
389 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
390
391 /**
392  * Finds a resource type in an OCResourceType link-list.
393  *
394  * @param resourceTypeList The link-list to be searched through.
395  * @param resourceTypeName The key to search for.
396  *
397  * @return Resource type that matches the key (ie. resourceTypeName) or
398  *      NULL if there is either an invalid parameter or this function was unable to find the key.
399  */
400 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
401         const char * resourceTypeName);
402
403 /**
404  * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
405  * TTL will be set to maxAge.
406  *
407  * @param cbNode Callback Node for which presence ttl is to be reset.
408  * @param maxAge New value of ttl in seconds.
409
410  * @return ::OC_STACK_OK on success, some other value upon failure.
411  */
412 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
413
414 /**
415  * Ensure the accept header option is set appropriatly before sending the requests and routing
416  * header option is updated with destination.
417  *
418  * @param object CA remote endpoint.
419  * @param requestInfo CA request info.
420  *
421  * @return ::OC_STACK_OK on success, some other value upon failure.
422  */
423 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
424
425 //-----------------------------------------------------------------------------
426 // Internal functions
427 //-----------------------------------------------------------------------------
428
429 uint32_t GetTicks(uint32_t afterMilliSeconds)
430 {
431     coap_tick_t now;
432     coap_ticks(&now);
433
434     // Guard against overflow of uint32_t
435     if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
436                              COAP_TICKS_PER_SECOND)
437     {
438         return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
439     }
440     else
441     {
442         return UINT32_MAX;
443     }
444 }
445
446 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
447 {
448     VERIFY_NON_NULL_NR(in, FATAL);
449     VERIFY_NON_NULL_NR(out, FATAL);
450
451     out->adapter = (OCTransportAdapter)in->adapter;
452     out->flags = CAToOCTransportFlags(in->flags);
453     OICStrcpy(out->addr, sizeof(out->addr), in->addr);
454     out->port = in->port;
455     out->ifindex = in->ifindex;
456 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
457     memcpy(out->routeData, in->routeData, sizeof(out->routeData));
458 #endif
459 }
460
461 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
462 {
463     VERIFY_NON_NULL_NR(in, FATAL);
464     VERIFY_NON_NULL_NR(out, FATAL);
465
466     out->adapter = (CATransportAdapter_t)in->adapter;
467     out->flags = OCToCATransportFlags(in->flags);
468     OICStrcpy(out->addr, sizeof(out->addr), in->addr);
469 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
470     memcpy(out->routeData, in->routeData, sizeof(out->routeData));
471 #endif
472     out->port = in->port;
473     out->ifindex = in->ifindex;
474 }
475
476 void FixUpClientResponse(OCClientResponse *cr)
477 {
478     VERIFY_NON_NULL_NR(cr, FATAL);
479
480     cr->addr = &cr->devAddr;
481     cr->connType = (OCConnectivityType)
482         ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
483 }
484
485 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
486 {
487     VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
488     VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
489
490 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
491     OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
492     if (OC_STACK_OK != rmResult)
493     {
494         OIC_LOG(ERROR, TAG, "Add destination option failed");
495         return rmResult;
496     }
497 #endif
498
499     // OC stack prefer CBOR encoded payloads.
500     requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
501     CAResult_t result = CASendRequest(object, requestInfo);
502     if(CA_STATUS_OK != result)
503     {
504         OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
505         return CAResultToOCResult(result);
506     }
507     return OC_STACK_OK;
508 }
509 //-----------------------------------------------------------------------------
510 // Internal API function
511 //-----------------------------------------------------------------------------
512
513 // This internal function is called to update the stack with the status of
514 // observers and communication failures
515 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
516 {
517     OCStackResult result = OC_STACK_ERROR;
518     ResourceObserver * observer = NULL;
519     OCEntityHandlerRequest ehRequest = {0};
520
521     switch(status)
522     {
523     case OC_OBSERVER_NOT_INTERESTED:
524         OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
525         observer = GetObserverUsingToken (token, tokenLength);
526         if(observer)
527         {
528             result = FormOCEntityHandlerRequest(&ehRequest,
529                                                 (OCRequestHandle)NULL,
530                                                 OC_REST_NOMETHOD,
531                                                 &observer->devAddr,
532                                                 (OCResourceHandle)NULL,
533                                                 NULL, PAYLOAD_TYPE_REPRESENTATION,
534                                                 NULL, 0, 0, NULL,
535                                                 OC_OBSERVE_DEREGISTER,
536                                                 observer->observeId);
537             if(result != OC_STACK_OK)
538             {
539                 return result;
540             }
541             observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
542                             observer->resource->entityHandlerCallbackParam);
543         }
544
545         result = DeleteObserverUsingToken (token, tokenLength);
546         if(result == OC_STACK_OK)
547         {
548             OIC_LOG(DEBUG, TAG, "Removed observer successfully");
549         }
550         else
551         {
552             result = OC_STACK_OK;
553             OIC_LOG(DEBUG, TAG, "Observer Removal failed");
554         }
555         break;
556
557     case OC_OBSERVER_STILL_INTERESTED:
558         OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
559         observer = GetObserverUsingToken (token, tokenLength);
560         if(observer)
561         {
562             observer->forceHighQos = 0;
563             observer->failedCommCount = 0;
564             result = OC_STACK_OK;
565         }
566         else
567         {
568             result = OC_STACK_OBSERVER_NOT_FOUND;
569         }
570         break;
571
572     case OC_OBSERVER_FAILED_COMM:
573         OIC_LOG(DEBUG, TAG, "observer is unreachable");
574         observer = GetObserverUsingToken (token, tokenLength);
575         if(observer)
576         {
577             if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
578             {
579                 result = FormOCEntityHandlerRequest(&ehRequest,
580                                                     (OCRequestHandle)NULL,
581                                                     OC_REST_NOMETHOD,
582                                                     &observer->devAddr,
583                                                     (OCResourceHandle)NULL,
584                                                     NULL, PAYLOAD_TYPE_REPRESENTATION,
585                                                     NULL, 0, 0, NULL,
586                                                     OC_OBSERVE_DEREGISTER,
587                                                     observer->observeId);
588                 if(result != OC_STACK_OK)
589                 {
590                     return OC_STACK_ERROR;
591                 }
592                 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
593                                     observer->resource->entityHandlerCallbackParam);
594
595                 result = DeleteObserverUsingToken (token, tokenLength);
596                 if(result == OC_STACK_OK)
597                 {
598                     OIC_LOG(DEBUG, TAG, "Removed observer successfully");
599                 }
600                 else
601                 {
602                     result = OC_STACK_OK;
603                     OIC_LOG(DEBUG, TAG, "Observer Removal failed");
604                 }
605             }
606             else
607             {
608                 observer->failedCommCount++;
609                 result = OC_STACK_CONTINUE;
610             }
611             observer->forceHighQos = 1;
612             OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
613         }
614         break;
615     default:
616         OIC_LOG(ERROR, TAG, "Unknown status");
617         result = OC_STACK_ERROR;
618         break;
619         }
620     return result;
621 }
622
623 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
624 {
625     OCStackResult ret = OC_STACK_ERROR;
626
627     switch(caResult)
628     {
629         case CA_ADAPTER_NOT_ENABLED:
630         case CA_SERVER_NOT_STARTED:
631             ret = OC_STACK_ADAPTER_NOT_ENABLED;
632             break;
633         case CA_MEMORY_ALLOC_FAILED:
634             ret = OC_STACK_NO_MEMORY;
635             break;
636         case CA_STATUS_INVALID_PARAM:
637             ret = OC_STACK_INVALID_PARAM;
638             break;
639         default:
640             break;
641     }
642     return ret;
643 }
644
645 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
646 {
647     OCStackResult ret = OC_STACK_ERROR;
648
649     switch(caCode)
650     {
651         case CA_CREATED:
652             ret = OC_STACK_RESOURCE_CREATED;
653             break;
654         case CA_DELETED:
655             ret = OC_STACK_RESOURCE_DELETED;
656             break;
657         case CA_CHANGED:
658         case CA_CONTENT:
659         case CA_VALID:
660             ret = OC_STACK_OK;
661             break;
662         case CA_BAD_REQ:
663             ret = OC_STACK_INVALID_QUERY;
664             break;
665         case CA_UNAUTHORIZED_REQ:
666             ret = OC_STACK_UNAUTHORIZED_REQ;
667             break;
668         case CA_BAD_OPT:
669             ret = OC_STACK_INVALID_OPTION;
670             break;
671         case CA_NOT_FOUND:
672             ret = OC_STACK_NO_RESOURCE;
673             break;
674         case CA_RETRANSMIT_TIMEOUT:
675             ret = OC_STACK_COMM_ERROR;
676             break;
677         case CA_REQUEST_ENTITY_TOO_LARGE:
678             ret = OC_STACK_TOO_LARGE_REQ;
679             break;
680         default:
681             break;
682     }
683     return ret;
684 }
685
686 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
687 {
688     CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
689
690     switch(ocCode)
691     {
692         case OC_STACK_OK:
693            switch (method)
694            {
695                case OC_REST_PUT:
696                case OC_REST_POST:
697                    // This Response Code is like HTTP 204 "No Content" but only used in
698                    // response to POST and PUT requests.
699                    ret = CA_CHANGED;
700                    break;
701                case OC_REST_GET:
702                    // This Response Code is like HTTP 200 "OK" but only used in response to
703                    // GET requests.
704                    ret = CA_CONTENT;
705                    break;
706                default:
707                    // This should not happen but,
708                    // give it a value just in case but output an error
709                    ret = CA_CONTENT;
710                    OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
711             }
712             break;
713         case OC_STACK_RESOURCE_CREATED:
714             ret = CA_CREATED;
715             break;
716         case OC_STACK_RESOURCE_DELETED:
717             ret = CA_DELETED;
718             break;
719         case OC_STACK_INVALID_QUERY:
720             ret = CA_BAD_REQ;
721             break;
722         case OC_STACK_INVALID_OPTION:
723             ret = CA_BAD_OPT;
724             break;
725         case OC_STACK_NO_RESOURCE:
726             ret = CA_NOT_FOUND;
727             break;
728         case OC_STACK_COMM_ERROR:
729             ret = CA_RETRANSMIT_TIMEOUT;
730             break;
731         case OC_STACK_UNAUTHORIZED_REQ:
732             ret = CA_UNAUTHORIZED_REQ;
733             break;
734         default:
735             break;
736     }
737     return ret;
738 }
739
740 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
741 {
742     CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
743
744     // supply default behavior.
745     if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
746     {
747         caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
748     }
749     if ((caFlags & OC_MASK_SCOPE) == 0)
750     {
751         caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
752     }
753     return caFlags;
754 }
755
756 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
757 {
758     return (OCTransportFlags)caFlags;
759 }
760
761 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
762 {
763     uint32_t lowerBound  = 0;
764     uint32_t higherBound = 0;
765
766     if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
767     {
768         return OC_STACK_INVALID_PARAM;
769     }
770
771     OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
772
773     cbNode->presence->TTL = maxAgeSeconds;
774
775     for (int index = 0; index < PresenceTimeOutSize; index++)
776     {
777         // Guard against overflow
778         if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
779                                      * 100)
780         {
781             lowerBound = GetTicks((PresenceTimeOut[index] *
782                                   cbNode->presence->TTL *
783                                   MILLISECONDS_PER_SECOND)/100);
784         }
785         else
786         {
787             lowerBound = GetTicks(UINT32_MAX);
788         }
789
790         if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
791                                      * 100)
792         {
793             higherBound = GetTicks((PresenceTimeOut[index + 1] *
794                                    cbNode->presence->TTL *
795                                    MILLISECONDS_PER_SECOND)/100);
796         }
797         else
798         {
799             higherBound = GetTicks(UINT32_MAX);
800         }
801
802         cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
803
804         OIC_LOG_V(DEBUG, TAG, "lowerBound timeout  %d", lowerBound);
805         OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
806         OIC_LOG_V(DEBUG, TAG, "timeOut entry  %d", cbNode->presence->timeOut[index]);
807     }
808
809     cbNode->presence->TTLlevel = 0;
810
811     OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
812     return OC_STACK_OK;
813 }
814
815 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
816 {
817     if (trigger == OC_PRESENCE_TRIGGER_CREATE)
818     {
819         return OC_RSRVD_TRIGGER_CREATE;
820     }
821     else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
822     {
823         return OC_RSRVD_TRIGGER_CHANGE;
824     }
825     else
826     {
827         return OC_RSRVD_TRIGGER_DELETE;
828     }
829 }
830
831 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
832 {
833     if(!triggerStr)
834     {
835         return OC_PRESENCE_TRIGGER_CREATE;
836     }
837     else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
838     {
839         return OC_PRESENCE_TRIGGER_CREATE;
840     }
841     else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
842     {
843         return OC_PRESENCE_TRIGGER_CHANGE;
844     }
845     else
846     {
847         return OC_PRESENCE_TRIGGER_DELETE;
848     }
849 }
850
851 /**
852  * The cononical presence allows constructed URIs to be string compared.
853  *
854  * requestUri must be a char array of size CA_MAX_URI_LENGTH
855  */
856 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
857         char *presenceUri)
858 {
859     VERIFY_NON_NULL(endpoint   , FATAL, OC_STACK_INVALID_PARAM);
860     VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
861     VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
862
863     CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
864
865     if (ep->adapter == CA_ADAPTER_IP)
866     {
867         if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
868         {
869             if ('\0' == ep->addr[0])  // multicast
870             {
871                 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
872             }
873             else
874             {
875                 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
876                         ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
877             }
878         }
879         else
880         {
881             if ('\0' == ep->addr[0])  // multicast
882             {
883                 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
884                 ep->port = OC_MULTICAST_PORT;
885             }
886             return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
887                     ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
888         }
889     }
890
891     // might work for other adapters (untested, but better than nothing)
892     return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
893                     OC_RSRVD_PRESENCE_URI);
894 }
895
896
897 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
898                             const CAResponseInfo_t *responseInfo)
899 {
900     VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
901     VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
902
903     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
904     ClientCB * cbNode = NULL;
905     char *resourceTypeName = NULL;
906     OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
907     OCStackResult result = OC_STACK_ERROR;
908     uint32_t maxAge = 0;
909     int uriLen;
910     char presenceUri[CA_MAX_URI_LENGTH];
911
912     int presenceSubscribe = 0;
913     int multicastPresenceSubscribe = 0;
914
915     if (responseInfo->result != CA_CONTENT)
916     {
917         OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
918         return OC_STACK_ERROR;
919     }
920
921     // check for unicast presence
922     uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
923     if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
924     {
925         return OC_STACK_INVALID_URI;
926     }
927
928     cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
929     if (cbNode)
930     {
931         presenceSubscribe = 1;
932     }
933     else
934     {
935         // check for multiicast presence
936         CAEndpoint_t ep = { .adapter = endpoint->adapter,
937                             .flags = endpoint->flags };
938
939         uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
940
941         cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
942         if (cbNode)
943         {
944             multicastPresenceSubscribe = 1;
945         }
946     }
947
948     if (!presenceSubscribe && !multicastPresenceSubscribe)
949     {
950         OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
951         goto exit;
952     }
953
954     response.payload = NULL;
955     response.result = OC_STACK_OK;
956
957     CopyEndpointToDevAddr(endpoint, &response.devAddr);
958     FixUpClientResponse(&response);
959
960     if (responseInfo->info.payload)
961     {
962         result = OCParsePayload(&response.payload,
963                 PAYLOAD_TYPE_PRESENCE,
964                 responseInfo->info.payload,
965                 responseInfo->info.payloadSize);
966
967         if(result != OC_STACK_OK)
968         {
969             OIC_LOG(ERROR, TAG, "Presence parse failed");
970             goto exit;
971         }
972         if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
973         {
974             OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
975             result = OC_STACK_ERROR;
976             goto exit;
977         }
978         response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
979         resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
980         maxAge = ((OCPresencePayload*)response.payload)->maxAge;
981     }
982
983     if (presenceSubscribe)
984     {
985         if(cbNode->sequenceNumber == response.sequenceNumber)
986         {
987             OIC_LOG(INFO, TAG, "No presence change");
988             ResetPresenceTTL(cbNode, maxAge);
989             OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
990             goto exit;
991         }
992
993         if(maxAge == 0)
994         {
995             OIC_LOG(INFO, TAG, "Stopping presence");
996             response.result = OC_STACK_PRESENCE_STOPPED;
997             if(cbNode->presence)
998             {
999                 OICFree(cbNode->presence->timeOut);
1000                 OICFree(cbNode->presence);
1001                 cbNode->presence = NULL;
1002             }
1003         }
1004         else
1005         {
1006             if(!cbNode->presence)
1007             {
1008                 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1009
1010                 if(!(cbNode->presence))
1011                 {
1012                     OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1013                     result = OC_STACK_NO_MEMORY;
1014                     goto exit;
1015                 }
1016
1017                 VERIFY_NON_NULL_V(cbNode->presence);
1018                 cbNode->presence->timeOut = NULL;
1019                 cbNode->presence->timeOut = (uint32_t *)
1020                         OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1021                 if(!(cbNode->presence->timeOut)){
1022                     OIC_LOG(ERROR, TAG,
1023                                   "Could not allocate memory for cbNode->presence->timeOut");
1024                     OICFree(cbNode->presence);
1025                     result = OC_STACK_NO_MEMORY;
1026                     goto exit;
1027                 }
1028             }
1029
1030             ResetPresenceTTL(cbNode, maxAge);
1031
1032             cbNode->sequenceNumber = response.sequenceNumber;
1033
1034             // Ensure that a filter is actually applied.
1035             if( resourceTypeName && cbNode->filterResourceType)
1036             {
1037                 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1038                 {
1039                     goto exit;
1040                 }
1041             }
1042         }
1043     }
1044     else
1045     {
1046         // This is the multicast case
1047         OCMulticastNode* mcNode = NULL;
1048         mcNode = GetMCPresenceNode(presenceUri);
1049
1050         if(mcNode != NULL)
1051         {
1052             if(mcNode->nonce == response.sequenceNumber)
1053             {
1054                 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1055                 goto exit;
1056             }
1057             mcNode->nonce = response.sequenceNumber;
1058
1059             if(maxAge == 0)
1060             {
1061                 OIC_LOG(INFO, TAG, "Stopping presence");
1062                 response.result = OC_STACK_PRESENCE_STOPPED;
1063             }
1064         }
1065         else
1066         {
1067             char* uri = OICStrdup(presenceUri);
1068             if (!uri)
1069             {
1070                 OIC_LOG(INFO, TAG,
1071                     "No Memory for URI to store in the presence node");
1072                 result = OC_STACK_NO_MEMORY;
1073                 goto exit;
1074             }
1075
1076             result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1077             if(result == OC_STACK_NO_MEMORY)
1078             {
1079                 OIC_LOG(INFO, TAG,
1080                     "No Memory for Multicast Presence Node");
1081                 OICFree(uri);
1082                 goto exit;
1083             }
1084             // presence node now owns uri
1085         }
1086
1087         // Ensure that a filter is actually applied.
1088         if(resourceTypeName && cbNode->filterResourceType)
1089         {
1090             if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1091             {
1092                 goto exit;
1093             }
1094         }
1095     }
1096
1097     cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1098
1099     if (cbResult == OC_STACK_DELETE_TRANSACTION)
1100     {
1101         FindAndDeleteClientCB(cbNode);
1102     }
1103
1104 exit:
1105     OCPayloadDestroy(response.payload);
1106     return result;
1107 }
1108
1109 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1110 {
1111     OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1112
1113     if(responseInfo->info.resourceUri &&
1114         strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1115     {
1116         HandlePresenceResponse(endPoint, responseInfo);
1117         return;
1118     }
1119
1120     ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1121             responseInfo->info.tokenLength, NULL, NULL);
1122
1123     ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1124             responseInfo->info.tokenLength);
1125
1126     if(cbNode)
1127     {
1128         OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1129         if(responseInfo->result == CA_EMPTY)
1130         {
1131             OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1132             // We do not have a case for the client to receive a RESET
1133             if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1134             {
1135                 //This is the case of receiving an ACK on a request to a slow resource!
1136                 OIC_LOG(INFO, TAG, "This is a pure ACK");
1137                 //TODO: should we inform the client
1138                 //      app that at least the request was received at the server?
1139             }
1140         }
1141         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1142         {
1143             OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1144             OIC_LOG(INFO, TAG, "Calling into application address space");
1145
1146             OCClientResponse response =
1147                 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1148             CopyEndpointToDevAddr(endPoint, &response.devAddr);
1149             FixUpClientResponse(&response);
1150             response.resourceUri = responseInfo->info.resourceUri;
1151             memcpy(response.identity.id, responseInfo->info.identity.id,
1152                                                 sizeof (response.identity.id));
1153             response.identity.id_length = responseInfo->info.identity.id_length;
1154
1155             response.result = CAResponseToOCStackResult(responseInfo->result);
1156             cbNode->callBack(cbNode->context,
1157                     cbNode->handle, &response);
1158             FindAndDeleteClientCB(cbNode);
1159         }
1160         else
1161         {
1162             OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1163             OIC_LOG(INFO, TAG, "Calling into application address space");
1164
1165             OCClientResponse response =
1166                 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1167             response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1168             CopyEndpointToDevAddr(endPoint, &response.devAddr);
1169             FixUpClientResponse(&response);
1170             response.resourceUri = responseInfo->info.resourceUri;
1171             memcpy(response.identity.id, responseInfo->info.identity.id,
1172                                                 sizeof (response.identity.id));
1173             response.identity.id_length = responseInfo->info.identity.id_length;
1174
1175             response.result = CAResponseToOCStackResult(responseInfo->result);
1176
1177             if(responseInfo->info.payload &&
1178                responseInfo->info.payloadSize)
1179             {
1180                 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1181                 // check the security resource
1182                 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1183                 {
1184                     type = PAYLOAD_TYPE_SECURITY;
1185                 }
1186                 else if (cbNode->method == OC_REST_DISCOVER)
1187                 {
1188                     if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1189                                 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1190                     {
1191                         type = PAYLOAD_TYPE_DISCOVERY;
1192                     }
1193                     else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1194                     {
1195                         type = PAYLOAD_TYPE_DEVICE;
1196                     }
1197                     else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1198                     {
1199                         type = PAYLOAD_TYPE_PLATFORM;
1200                     }
1201 #ifdef ROUTING_GATEWAY
1202                     else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1203                     {
1204                         type = PAYLOAD_TYPE_REPRESENTATION;
1205                     }
1206 #endif
1207                     else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1208                     {
1209                         type = PAYLOAD_TYPE_RD;
1210                     }
1211 #ifdef TCP_ADAPTER
1212                     else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1213                     {
1214                         type = PAYLOAD_TYPE_REPRESENTATION;
1215                     }
1216 #endif
1217                     else
1218                     {
1219                         OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1220                                 cbNode->method, cbNode->requestUri);
1221                         return;
1222                     }
1223                 }
1224                 else if (cbNode->method == OC_REST_GET ||
1225                          cbNode->method == OC_REST_PUT ||
1226                          cbNode->method == OC_REST_POST ||
1227                          cbNode->method == OC_REST_OBSERVE ||
1228                          cbNode->method == OC_REST_OBSERVE_ALL ||
1229                          cbNode->method == OC_REST_DELETE)
1230                 {
1231                     char targetUri[MAX_URI_LENGTH];
1232                     snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1233                             OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1234                     if (strcmp(targetUri, cbNode->requestUri) == 0)
1235                     {
1236                         type = PAYLOAD_TYPE_RD;
1237                     }
1238                     else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1239                     {
1240                         type = PAYLOAD_TYPE_PLATFORM;
1241                     }
1242                     else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1243                     {
1244                         type = PAYLOAD_TYPE_DEVICE;
1245                     }
1246                     if (type == PAYLOAD_TYPE_INVALID)
1247                     {
1248                         OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1249                                 cbNode->method, cbNode->requestUri);
1250                         type = PAYLOAD_TYPE_REPRESENTATION;
1251                     }
1252                 }
1253                 else
1254                 {
1255                     OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1256                             cbNode->method, cbNode->requestUri);
1257                     return;
1258                 }
1259
1260                 if(OC_STACK_OK != OCParsePayload(&response.payload,
1261                             type,
1262                             responseInfo->info.payload,
1263                             responseInfo->info.payloadSize))
1264                 {
1265                     OIC_LOG(ERROR, TAG, "Error converting payload");
1266                     OCPayloadDestroy(response.payload);
1267                     return;
1268                 }
1269             }
1270
1271             response.numRcvdVendorSpecificHeaderOptions = 0;
1272             if(responseInfo->info.numOptions > 0)
1273             {
1274                 int start = 0;
1275                 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1276                 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1277                 {
1278                     size_t i;
1279                     uint32_t observationOption;
1280                     uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1281                     for (observationOption=0, i=0;
1282                             i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1283                             i++)
1284                     {
1285                         observationOption =
1286                             (observationOption << 8) | optionData[i];
1287                     }
1288                     response.sequenceNumber = observationOption;
1289
1290                     response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1291                     start = 1;
1292                 }
1293                 else
1294                 {
1295                     response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1296                 }
1297
1298                 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1299                 {
1300                     OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1301                     OCPayloadDestroy(response.payload);
1302                     return;
1303                 }
1304
1305                 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1306                 {
1307                     memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1308                             &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1309                 }
1310             }
1311
1312             if (cbNode->method == OC_REST_OBSERVE &&
1313                 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1314                 response.sequenceNumber <= cbNode->sequenceNumber)
1315             {
1316                 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1317                                                  response.sequenceNumber);
1318             }
1319             else
1320             {
1321                 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1322                                                                         cbNode->handle,
1323                                                                         &response);
1324                 cbNode->sequenceNumber = response.sequenceNumber;
1325
1326                 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1327                 {
1328                     FindAndDeleteClientCB(cbNode);
1329                 }
1330                 else
1331                 {
1332                     // To keep discovery callbacks active.
1333                     cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1334                                             MILLISECONDS_PER_SECOND);
1335                 }
1336             }
1337
1338             //Need to send ACK when the response is CON
1339             if(responseInfo->info.type == CA_MSG_CONFIRM)
1340             {
1341                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1342                         CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1343             }
1344
1345             OCPayloadDestroy(response.payload);
1346         }
1347         return;
1348     }
1349
1350     if(observer)
1351     {
1352         OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1353         if(responseInfo->result == CA_EMPTY)
1354         {
1355             OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1356             if(responseInfo->info.type == CA_MSG_RESET)
1357             {
1358                 OIC_LOG(INFO, TAG, "This is a RESET");
1359                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1360                         OC_OBSERVER_NOT_INTERESTED);
1361             }
1362             else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1363             {
1364                 OIC_LOG(INFO, TAG, "This is a pure ACK");
1365                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1366                         OC_OBSERVER_STILL_INTERESTED);
1367             }
1368         }
1369         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1370         {
1371             OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1372             OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1373                     OC_OBSERVER_FAILED_COMM);
1374         }
1375         return;
1376     }
1377
1378     if(!cbNode && !observer)
1379     {
1380         if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1381            || myStackMode == OC_GATEWAY)
1382         {
1383             OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1384             if(responseInfo->result == CA_EMPTY)
1385             {
1386                 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1387             }
1388             else
1389             {
1390                 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1391                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1392                                         CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1393             }
1394         }
1395
1396         if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1397            || myStackMode == OC_GATEWAY)
1398         {
1399             OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1400             if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1401             {
1402                 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1403                                             responseInfo->info.messageId);
1404             }
1405             if (responseInfo->info.type == CA_MSG_RESET)
1406             {
1407                 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1408                                             responseInfo->info.messageId);
1409             }
1410         }
1411
1412         return;
1413     }
1414
1415     OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1416 }
1417
1418 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1419 {
1420     VERIFY_NON_NULL_NR(endPoint, FATAL);
1421     VERIFY_NON_NULL_NR(responseInfo, FATAL);
1422
1423     OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1424
1425 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1426 #ifdef ROUTING_GATEWAY
1427     bool needRIHandling = false;
1428     /*
1429      * Routing manager is going to update either of endpoint or response or both.
1430      * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1431      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1432      * destination.
1433      */
1434     OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1435                                          &needRIHandling);
1436     if(ret != OC_STACK_OK || !needRIHandling)
1437     {
1438         OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1439         return;
1440     }
1441 #endif
1442
1443     /*
1444      * Put source in sender endpoint so that the next packet from application can be routed to
1445      * proper destination and remove "RM" coap header option before passing request / response to
1446      * RI as this option will make no sense to either RI or application.
1447      */
1448     RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1449                  (uint8_t *) &(responseInfo->info.numOptions),
1450                  (CAEndpoint_t *) endPoint);
1451 #endif
1452
1453     OCHandleResponse(endPoint, responseInfo);
1454
1455     OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1456 }
1457
1458 /*
1459  * This function handles error response from CA
1460  * code shall be added to handle the errors
1461  */
1462 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1463 {
1464     OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1465
1466     if (NULL == endPoint)
1467     {
1468         OIC_LOG(ERROR, TAG, "endPoint is NULL");
1469         return;
1470     }
1471
1472     if (NULL == errorInfo)
1473     {
1474         OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1475         return;
1476     }
1477
1478     ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1479                                    errorInfo->info.tokenLength, NULL, NULL);
1480     if (cbNode)
1481     {
1482         OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1483         CopyEndpointToDevAddr(endPoint, &response.devAddr);
1484         FixUpClientResponse(&response);
1485         response.resourceUri = errorInfo->info.resourceUri;
1486         memcpy(response.identity.id, errorInfo->info.identity.id,
1487                sizeof (response.identity.id));
1488         response.identity.id_length = errorInfo->info.identity.id_length;
1489         response.result = CAResultToOCStackResult(errorInfo->result);
1490
1491         cbNode->callBack(cbNode->context, cbNode->handle, &response);
1492         FindAndDeleteClientCB(cbNode);
1493     }
1494
1495     OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1496 }
1497
1498 /*
1499  * This function sends out Direct Stack Responses. These are responses that are not coming
1500  * from the application entity handler. These responses have no payload and are usually ACKs,
1501  * RESETs or some error conditions that were caught by the stack.
1502  */
1503 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1504         const CAResponseResult_t responseResult, const CAMessageType_t type,
1505         const uint8_t numOptions, const CAHeaderOption_t *options,
1506         CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1507 {
1508     OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1509     CAResponseInfo_t respInfo = {
1510         .result = responseResult
1511     };
1512     respInfo.info.messageId = coapID;
1513     respInfo.info.numOptions = numOptions;
1514
1515     if (respInfo.info.numOptions)
1516     {
1517         respInfo.info.options =
1518             (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1519         memcpy (respInfo.info.options, options,
1520                 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1521
1522     }
1523
1524     respInfo.info.payload = NULL;
1525     respInfo.info.token = token;
1526     respInfo.info.tokenLength = tokenLength;
1527     respInfo.info.type = type;
1528     respInfo.info.resourceUri = OICStrdup (resourceUri);
1529     respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1530
1531 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1532     // Add the destination to route option from the endpoint->routeData.
1533     bool doPost = false;
1534     OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1535     if(OC_STACK_OK != result)
1536     {
1537         OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1538         return result;
1539     }
1540     if (doPost)
1541     {
1542         OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1543         CARequestInfo_t reqInfo = {.method = CA_POST };
1544         /* The following initialization is not done in a single initializer block as in
1545          * arduino, .c file is compiled as .cpp and moves it from C99 to C++11.  The latter
1546          * does not have designated initalizers. This is a work-around for now.
1547          */
1548         reqInfo.info.type = CA_MSG_NONCONFIRM;
1549         reqInfo.info.messageId = coapID;
1550         reqInfo.info.tokenLength = tokenLength;
1551         reqInfo.info.token = token;
1552         reqInfo.info.numOptions = respInfo.info.numOptions;
1553         reqInfo.info.payload = NULL;
1554         reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1555         if (reqInfo.info.numOptions)
1556         {
1557             reqInfo.info.options =
1558                 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1559             if (NULL == reqInfo.info.options)
1560             {
1561                 OIC_LOG(ERROR, TAG, "Calloc failed");
1562                 return OC_STACK_NO_MEMORY;
1563             }
1564             memcpy (reqInfo.info.options, respInfo.info.options,
1565                     sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1566
1567         }
1568         CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1569         OICFree (reqInfo.info.resourceUri);
1570         OICFree (reqInfo.info.options);
1571         OICFree (respInfo.info.resourceUri);
1572         OICFree (respInfo.info.options);
1573         if (CA_STATUS_OK != caResult)
1574         {
1575             OIC_LOG(ERROR, TAG, "CASendRequest error");
1576             return CAResultToOCResult(caResult);
1577         }
1578     }
1579     else
1580 #endif
1581     {
1582         CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1583
1584         // resourceUri in the info field is cloned in the CA layer and
1585         // thus ownership is still here.
1586         OICFree (respInfo.info.resourceUri);
1587         OICFree (respInfo.info.options);
1588         if(CA_STATUS_OK != caResult)
1589         {
1590             OIC_LOG(ERROR, TAG, "CASendResponse error");
1591             return CAResultToOCResult(caResult);
1592         }
1593     }
1594     OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1595     return OC_STACK_OK;
1596 }
1597
1598 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1599 {
1600     OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1601     OCStackResult result = OC_STACK_ERROR;
1602     if(!protocolRequest)
1603     {
1604         OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1605         return OC_STACK_INVALID_PARAM;
1606     }
1607
1608     OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1609             protocolRequest->tokenLength);
1610     if(!request)
1611     {
1612         OIC_LOG(INFO, TAG, "This is a new Server Request");
1613         result = AddServerRequest(&request, protocolRequest->coapID,
1614                 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1615                 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1616                 protocolRequest->observationOption, protocolRequest->qos,
1617                 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1618                 protocolRequest->payload, protocolRequest->requestToken,
1619                 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1620                 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1621                 &protocolRequest->devAddr);
1622         if (OC_STACK_OK != result)
1623         {
1624             OIC_LOG(ERROR, TAG, "Error adding server request");
1625             return result;
1626         }
1627
1628         if(!request)
1629         {
1630             OIC_LOG(ERROR, TAG, "Out of Memory");
1631             return OC_STACK_NO_MEMORY;
1632         }
1633
1634         if(!protocolRequest->reqMorePacket)
1635         {
1636             request->requestComplete = 1;
1637         }
1638     }
1639     else
1640     {
1641         OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1642     }
1643
1644     if(request->requestComplete)
1645     {
1646         OIC_LOG(INFO, TAG, "This Server Request is complete");
1647         ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1648         OCResource *resource = NULL;
1649         result = DetermineResourceHandling (request, &resHandling, &resource);
1650         if (result == OC_STACK_OK)
1651         {
1652             result = ProcessRequest(resHandling, resource, request);
1653         }
1654     }
1655     else
1656     {
1657         OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1658         result = OC_STACK_CONTINUE;
1659     }
1660     return result;
1661 }
1662
1663 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1664 {
1665     OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1666
1667 #ifdef TCP_ADAPTER
1668     if (requestInfo->info.resourceUri &&
1669             strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1670     {
1671         HandleKeepAliveRequest(endPoint, requestInfo);
1672         return;
1673     }
1674 #endif
1675
1676     OCStackResult requestResult = OC_STACK_ERROR;
1677
1678     if(myStackMode == OC_CLIENT)
1679     {
1680         //TODO: should the client be responding to requests?
1681         return;
1682     }
1683
1684     OCServerProtocolRequest serverRequest = {0};
1685
1686     OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1687
1688     char * uriWithoutQuery = NULL;
1689     char * query  = NULL;
1690
1691     requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1692
1693     if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1694     {
1695         OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1696         return;
1697     }
1698     OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1699     OIC_LOG_V(INFO, TAG, "Query : %s", query);
1700
1701     if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1702     {
1703         OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1704         OICFree(uriWithoutQuery);
1705     }
1706     else
1707     {
1708         OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1709         OICFree(uriWithoutQuery);
1710         OICFree(query);
1711         return;
1712     }
1713
1714     if(query)
1715     {
1716         if(strlen(query) < MAX_QUERY_LENGTH)
1717         {
1718             OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1719             OICFree(query);
1720         }
1721         else
1722         {
1723             OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1724             OICFree(query);
1725             return;
1726         }
1727     }
1728
1729     if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1730     {
1731         serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1732         serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1733         if (!serverRequest.payload)
1734         {
1735             OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1736             return;
1737         }
1738         memcpy (serverRequest.payload, requestInfo->info.payload,
1739                 requestInfo->info.payloadSize);
1740     }
1741     else
1742     {
1743         serverRequest.reqTotalSize = 0;
1744     }
1745
1746     switch (requestInfo->method)
1747     {
1748         case CA_GET:
1749             serverRequest.method = OC_REST_GET;
1750             break;
1751         case CA_PUT:
1752             serverRequest.method = OC_REST_PUT;
1753             break;
1754         case CA_POST:
1755             serverRequest.method = OC_REST_POST;
1756             break;
1757         case CA_DELETE:
1758             serverRequest.method = OC_REST_DELETE;
1759             break;
1760         default:
1761             OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1762             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1763                         requestInfo->info.type, requestInfo->info.numOptions,
1764                         requestInfo->info.options, requestInfo->info.token,
1765                         requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1766             OICFree(serverRequest.payload);
1767             return;
1768     }
1769
1770     OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1771             requestInfo->info.tokenLength);
1772
1773     serverRequest.tokenLength = requestInfo->info.tokenLength;
1774     if (serverRequest.tokenLength) {
1775         // Non empty token
1776         serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1777
1778         if (!serverRequest.requestToken)
1779         {
1780             OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1781             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1782                     requestInfo->info.type, requestInfo->info.numOptions,
1783                     requestInfo->info.options, requestInfo->info.token,
1784                     requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1785             OICFree(serverRequest.payload);
1786             return;
1787         }
1788         memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1789     }
1790
1791     switch (requestInfo->info.acceptFormat)
1792     {
1793         case CA_FORMAT_APPLICATION_CBOR:
1794             serverRequest.acceptFormat = OC_FORMAT_CBOR;
1795             break;
1796         case CA_FORMAT_UNDEFINED:
1797             serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1798             break;
1799         default:
1800             serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1801     }
1802
1803     if (requestInfo->info.type == CA_MSG_CONFIRM)
1804     {
1805         serverRequest.qos = OC_HIGH_QOS;
1806     }
1807     else
1808     {
1809         serverRequest.qos = OC_LOW_QOS;
1810     }
1811     // CA does not need the following field
1812     // Are we sure CA does not need them? how is it responding to multicast
1813     serverRequest.delayedResNeeded = 0;
1814
1815     serverRequest.coapID = requestInfo->info.messageId;
1816
1817     CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1818
1819     // copy vendor specific header options
1820     uint8_t tempNum = (requestInfo->info.numOptions);
1821
1822     // Assume no observation requested and it is a pure GET.
1823     // If obs registration/de-registration requested it'll be fetched from the
1824     // options in GetObserveHeaderOption()
1825     serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1826
1827     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1828     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1829     {
1830         OIC_LOG(ERROR, TAG,
1831                 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1832         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1833                 requestInfo->info.type, requestInfo->info.numOptions,
1834                 requestInfo->info.options, requestInfo->info.token,
1835                 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1836         OICFree(serverRequest.payload);
1837         OICFree(serverRequest.requestToken);
1838         return;
1839     }
1840     serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1841     if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1842     {
1843         memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1844             sizeof(CAHeaderOption_t)*tempNum);
1845     }
1846
1847     requestResult = HandleStackRequests (&serverRequest);
1848
1849     // Send ACK to client as precursor to slow response
1850     if (requestResult == OC_STACK_SLOW_RESOURCE)
1851     {
1852         if (requestInfo->info.type == CA_MSG_CONFIRM)
1853         {
1854             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1855                                     CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1856         }
1857     }
1858     else if(requestResult != OC_STACK_OK)
1859     {
1860         OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1861
1862         CAResponseResult_t stackResponse =
1863             OCToCAStackResult(requestResult, serverRequest.method);
1864
1865         SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1866                 requestInfo->info.type, requestInfo->info.numOptions,
1867                 requestInfo->info.options, requestInfo->info.token,
1868                 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1869     }
1870     // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1871     // The token is copied in there, and is thus still owned by this function.
1872     OICFree(serverRequest.payload);
1873     OICFree(serverRequest.requestToken);
1874     OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1875 }
1876
1877 //This function will be called back by CA layer when a request is received
1878 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1879 {
1880     OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1881     if(!endPoint)
1882     {
1883         OIC_LOG(ERROR, TAG, "endPoint is NULL");
1884         return;
1885     }
1886
1887     if(!requestInfo)
1888     {
1889         OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1890         return;
1891     }
1892
1893 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1894 #ifdef ROUTING_GATEWAY
1895     bool needRIHandling = false;
1896     bool isEmptyMsg = false;
1897     /*
1898      * Routing manager is going to update either of endpoint or request or both.
1899      * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1900      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1901      * destination. It can also remove "RM" coap header option before passing request / response to
1902      * RI as this option will make no sense to either RI or application.
1903      */
1904     OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1905                                         &needRIHandling, &isEmptyMsg);
1906     if(OC_STACK_OK != ret || !needRIHandling)
1907     {
1908         OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1909         return;
1910     }
1911 #endif
1912
1913     /*
1914      * Put source in sender endpoint so that the next packet from application can be routed to
1915      * proper destination and remove RM header option.
1916      */
1917     RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1918                  (uint8_t *) &(requestInfo->info.numOptions),
1919                  (CAEndpoint_t *) endPoint);
1920
1921 #ifdef ROUTING_GATEWAY
1922     if (isEmptyMsg)
1923     {
1924         /*
1925          * In Gateways, the MSGType in route option is used to check if the actual
1926          * response is EMPTY message(4 bytes CoAP Header).  In case of Client, the
1927          * EMPTY response is sent in the form of POST request which need to be changed
1928          * to a EMPTY response by RM.  This translation is done in this part of the code.
1929          */
1930         OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1931         CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1932                                      .info.messageId = requestInfo->info.messageId,
1933                                      .info.type = CA_MSG_ACKNOWLEDGE};
1934         OCHandleResponse(endPoint, &respInfo);
1935     }
1936     else
1937 #endif
1938 #endif
1939     {
1940         // Normal handling of the packet
1941         OCHandleRequests(endPoint, requestInfo);
1942     }
1943     OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1944 }
1945
1946 bool validatePlatformInfo(OCPlatformInfo info)
1947 {
1948
1949     if (!info.platformID)
1950     {
1951         OIC_LOG(ERROR, TAG, "No platform ID found.");
1952         return false;
1953     }
1954
1955     if (info.manufacturerName)
1956     {
1957         size_t lenManufacturerName = strlen(info.manufacturerName);
1958
1959         if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1960         {
1961             OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1962             return false;
1963         }
1964     }
1965     else
1966     {
1967         OIC_LOG(ERROR, TAG, "No manufacturer name present");
1968         return false;
1969     }
1970
1971     if (info.manufacturerUrl)
1972     {
1973         if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1974         {
1975             OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1976             return false;
1977         }
1978     }
1979     return true;
1980 }
1981
1982 //-----------------------------------------------------------------------------
1983 // Public APIs
1984 //-----------------------------------------------------------------------------
1985 #ifdef RA_ADAPTER
1986 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1987 {
1988     if (!raInfo           ||
1989         !raInfo->username ||
1990         !raInfo->hostname ||
1991         !raInfo->xmpp_domain)
1992     {
1993
1994         return OC_STACK_INVALID_PARAM;
1995     }
1996     OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1997     gRASetInfo = (result == OC_STACK_OK)? true : false;
1998
1999     return result;
2000 }
2001 #endif
2002
2003 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2004 {
2005     (void) ipAddr;
2006     (void) port;
2007     return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2008 }
2009
2010 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2011 {
2012     if(stackState == OC_STACK_INITIALIZED)
2013     {
2014         OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2015                 OCStop() between them are ignored.");
2016         return OC_STACK_OK;
2017     }
2018
2019 #ifndef ROUTING_GATEWAY
2020     if (OC_GATEWAY == mode)
2021     {
2022         OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2023         return OC_STACK_INVALID_PARAM;
2024     }
2025 #endif
2026
2027 #ifdef RA_ADAPTER
2028     if(!gRASetInfo)
2029     {
2030         OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2031         return OC_STACK_ERROR;
2032     }
2033 #endif
2034
2035     OCStackResult result = OC_STACK_ERROR;
2036     OIC_LOG(INFO, TAG, "Entering OCInit");
2037
2038     // Validate mode
2039     if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2040         || (mode == OC_GATEWAY)))
2041     {
2042         OIC_LOG(ERROR, TAG, "Invalid mode");
2043         return OC_STACK_ERROR;
2044     }
2045     myStackMode = mode;
2046
2047     if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2048     {
2049         caglobals.client = true;
2050     }
2051     if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2052     {
2053         caglobals.server = true;
2054     }
2055
2056     caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2057     if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2058     {
2059         caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2060     }
2061     caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2062     if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2063     {
2064         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2065     }
2066
2067     defaultDeviceHandler = NULL;
2068     defaultDeviceHandlerCallbackParameter = NULL;
2069
2070     result = CAResultToOCResult(CAInitialize());
2071     VERIFY_SUCCESS(result, OC_STACK_OK);
2072
2073     result = CAResultToOCResult(OCSelectNetwork());
2074     VERIFY_SUCCESS(result, OC_STACK_OK);
2075
2076     switch (myStackMode)
2077     {
2078         case OC_CLIENT:
2079             CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2080             result = CAResultToOCResult(CAStartDiscoveryServer());
2081             OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2082             break;
2083         case OC_SERVER:
2084             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2085             result = CAResultToOCResult(CAStartListeningServer());
2086             OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2087             break;
2088         case OC_CLIENT_SERVER:
2089         case OC_GATEWAY:
2090             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2091             result = CAResultToOCResult(CAStartListeningServer());
2092             if(result == OC_STACK_OK)
2093             {
2094                 result = CAResultToOCResult(CAStartDiscoveryServer());
2095             }
2096             break;
2097     }
2098     VERIFY_SUCCESS(result, OC_STACK_OK);
2099
2100 #ifdef TCP_ADAPTER
2101     CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2102 #endif
2103
2104 #ifdef WITH_PRESENCE
2105     PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2106 #endif // WITH_PRESENCE
2107
2108     //Update Stack state to initialized
2109     stackState = OC_STACK_INITIALIZED;
2110
2111     // Initialize resource
2112     if(myStackMode != OC_CLIENT)
2113     {
2114         result = initResources();
2115     }
2116
2117     // Initialize the SRM Policy Engine
2118     if(result == OC_STACK_OK)
2119     {
2120         result = SRMInitPolicyEngine();
2121         // TODO after BeachHead delivery: consolidate into single SRMInit()
2122     }
2123 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2124     RMSetStackMode(mode);
2125 #ifdef ROUTING_GATEWAY
2126     if (OC_GATEWAY == myStackMode)
2127     {
2128         result = RMInitialize();
2129     }
2130 #endif
2131 #endif
2132
2133 #ifdef TCP_ADAPTER
2134     if (result == OC_STACK_OK)
2135     {
2136         result = InitializeKeepAlive(myStackMode);
2137     }
2138 #endif
2139
2140 exit:
2141     if(result != OC_STACK_OK)
2142     {
2143         OIC_LOG(ERROR, TAG, "Stack initialization error");
2144         deleteAllResources();
2145         CATerminate();
2146         stackState = OC_STACK_UNINITIALIZED;
2147     }
2148     return result;
2149 }
2150
2151 OCStackResult OCStop()
2152 {
2153     OIC_LOG(INFO, TAG, "Entering OCStop");
2154
2155     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2156     {
2157         OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2158         return OC_STACK_OK;
2159     }
2160     else if (stackState != OC_STACK_INITIALIZED)
2161     {
2162         OIC_LOG(ERROR, TAG, "Stack not initialized");
2163         return OC_STACK_ERROR;
2164     }
2165
2166     stackState = OC_STACK_UNINIT_IN_PROGRESS;
2167
2168 #ifdef WITH_PRESENCE
2169     // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2170     // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2171     presenceResource.presenceTTL = 0;
2172 #endif // WITH_PRESENCE
2173
2174 #ifdef ROUTING_GATEWAY
2175     if (OC_GATEWAY == myStackMode)
2176     {
2177         RMTerminate();
2178     }
2179 #endif
2180
2181 #ifdef TCP_ADAPTER
2182     TerminateKeepAlive(myStackMode);
2183 #endif
2184
2185     // Free memory dynamically allocated for resources
2186     deleteAllResources();
2187     DeleteDeviceInfo();
2188     DeletePlatformInfo();
2189     CATerminate();
2190     // Remove all observers
2191     DeleteObserverList();
2192     // Remove all the client callbacks
2193     DeleteClientCBList();
2194
2195     // De-init the SRM Policy Engine
2196     // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2197     SRMDeInitPolicyEngine();
2198
2199
2200     stackState = OC_STACK_UNINITIALIZED;
2201     return OC_STACK_OK;
2202 }
2203
2204 OCStackResult OCStartMulticastServer()
2205 {
2206     if(stackState != OC_STACK_INITIALIZED)
2207     {
2208         OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2209         return OC_STACK_ERROR;
2210     }
2211     CAResult_t ret = CAStartListeningServer();
2212     if (CA_STATUS_OK != ret)
2213     {
2214         OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2215         return OC_STACK_ERROR;
2216     }
2217     return OC_STACK_OK;
2218 }
2219
2220 OCStackResult OCStopMulticastServer()
2221 {
2222     CAResult_t ret = CAStopListeningServer();
2223     if (CA_STATUS_OK != ret)
2224     {
2225         OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2226         return OC_STACK_ERROR;
2227     }
2228     return OC_STACK_OK;
2229 }
2230
2231 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2232 {
2233     switch (qos)
2234     {
2235         case OC_HIGH_QOS:
2236             return CA_MSG_CONFIRM;
2237         case OC_LOW_QOS:
2238         case OC_MEDIUM_QOS:
2239         case OC_NA_QOS:
2240         default:
2241             return CA_MSG_NONCONFIRM;
2242     }
2243 }
2244
2245 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2246 {
2247     char *query;
2248
2249     query = strchr (inputUri, '?');
2250
2251     if (query != NULL)
2252     {
2253         if((query - inputUri) > MAX_URI_LENGTH)
2254         {
2255             return OC_STACK_INVALID_URI;
2256         }
2257
2258         if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2259         {
2260             return OC_STACK_INVALID_QUERY;
2261         }
2262     }
2263     else if(uriLen > MAX_URI_LENGTH)
2264     {
2265         return OC_STACK_INVALID_URI;
2266     }
2267     return OC_STACK_OK;
2268 }
2269
2270 /**
2271  *  A request uri consists of the following components in order:
2272  *                              example
2273  *  optionally one of
2274  *      CoAP over UDP prefix    "coap://"
2275  *      CoAP over TCP prefix    "coap+tcp://"
2276  *  optionally one of
2277  *      IPv6 address            "[1234::5678]"
2278  *      IPv4 address            "192.168.1.1"
2279  *  optional port               ":5683"
2280  *  resource uri                "/oc/core..."
2281  *
2282  *  for PRESENCE requests, extract resource type.
2283  */
2284 static OCStackResult ParseRequestUri(const char *fullUri,
2285                                         OCTransportAdapter adapter,
2286                                         OCTransportFlags flags,
2287                                         OCDevAddr **devAddr,
2288                                         char **resourceUri,
2289                                         char **resourceType)
2290 {
2291     VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2292
2293     OCStackResult result = OC_STACK_OK;
2294     OCDevAddr *da = NULL;
2295     char *colon = NULL;
2296     char *end;
2297
2298     // provide defaults for all returned values
2299     if (devAddr)
2300     {
2301         *devAddr = NULL;
2302     }
2303     if (resourceUri)
2304     {
2305         *resourceUri = NULL;
2306     }
2307     if (resourceType)
2308     {
2309         *resourceType = NULL;
2310     }
2311
2312     // delimit url prefix, if any
2313     const char *start = fullUri;
2314     char *slash2 = strstr(start, "//");
2315     if (slash2)
2316     {
2317         start = slash2 + 2;
2318     }
2319     char *slash = strchr(start, '/');
2320     if (!slash)
2321     {
2322         return OC_STACK_INVALID_URI;
2323     }
2324
2325     // process url scheme
2326     size_t prefixLen = slash2 - fullUri;
2327     bool istcp = false;
2328     if (prefixLen)
2329     {
2330         if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2331         {
2332             istcp = true;
2333         }
2334     }
2335
2336     // TODO: this logic should come in with unit tests exercising the various strings
2337     // processs url prefix, if any
2338     size_t urlLen = slash - start;
2339     // port
2340     uint16_t port = 0;
2341     size_t len = 0;
2342     if (urlLen && devAddr)
2343     {   // construct OCDevAddr
2344         if (start[0] == '[')
2345         {   // ipv6 address
2346             char *close = strchr(++start, ']');
2347             if (!close || close > slash)
2348             {
2349                 return OC_STACK_INVALID_URI;
2350             }
2351             end = close;
2352             if (close[1] == ':')
2353             {
2354                 colon = close + 1;
2355             }
2356
2357             if (istcp)
2358             {
2359                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2360             }
2361             else
2362             {
2363                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2364             }
2365             flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2366         }
2367         else
2368         {
2369             char *dot = strchr(start, '.');
2370             if (dot && dot < slash)
2371             {   // ipv4 address
2372                 colon = strchr(start, ':');
2373                 end = (colon && colon < slash) ? colon : slash;
2374
2375                 if (istcp)
2376                 {
2377                     // coap over tcp
2378                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2379                 }
2380                 else
2381                 {
2382                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2383                 }
2384                 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2385             }
2386             else
2387             {   // MAC address
2388                 end = slash;
2389             }
2390         }
2391         len = end - start;
2392         if (len >= sizeof(da->addr))
2393         {
2394             return OC_STACK_INVALID_URI;
2395         }
2396         // collect port, if any
2397         if (colon && colon < slash)
2398         {
2399             for (colon++; colon < slash; colon++)
2400             {
2401                 char c = colon[0];
2402                 if (c < '0' || c > '9')
2403                 {
2404                     return OC_STACK_INVALID_URI;
2405                 }
2406                 port = 10 * port + c - '0';
2407             }
2408         }
2409
2410         len = end - start;
2411         if (len >= sizeof(da->addr))
2412         {
2413             return OC_STACK_INVALID_URI;
2414         }
2415
2416         da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2417         if (!da)
2418         {
2419             return OC_STACK_NO_MEMORY;
2420         }
2421         OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2422         da->port = port;
2423         da->adapter = adapter;
2424         da->flags = flags;
2425         if (!strncmp(fullUri, "coaps:", 6))
2426         {
2427             da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2428         }
2429         *devAddr = da;
2430     }
2431
2432     // process resource uri, if any
2433     if (slash)
2434     {   // request uri and query
2435         size_t ulen = strlen(slash); // resource uri length
2436         size_t tlen = 0;      // resource type length
2437         char *type = NULL;
2438
2439         static const char strPresence[] = "/oic/ad?rt=";
2440         static const size_t lenPresence = sizeof(strPresence) - 1;
2441         if (!strncmp(slash, strPresence, lenPresence))
2442         {
2443             type = slash + lenPresence;
2444             tlen = ulen - lenPresence;
2445         }
2446         // resource uri
2447         if (resourceUri)
2448         {
2449             *resourceUri = (char *)OICMalloc(ulen + 1);
2450             if (!*resourceUri)
2451             {
2452                 result = OC_STACK_NO_MEMORY;
2453                 goto error;
2454             }
2455             strcpy(*resourceUri, slash);
2456         }
2457         // resource type
2458         if (type && resourceType)
2459         {
2460             *resourceType = (char *)OICMalloc(tlen + 1);
2461             if (!*resourceType)
2462             {
2463                 result = OC_STACK_NO_MEMORY;
2464                 goto error;
2465             }
2466
2467             OICStrcpy(*resourceType, (tlen+1), type);
2468         }
2469     }
2470
2471     return OC_STACK_OK;
2472
2473 error:
2474     // free all returned values
2475     if (devAddr)
2476     {
2477         OICFree(*devAddr);
2478     }
2479     if (resourceUri)
2480     {
2481         OICFree(*resourceUri);
2482     }
2483     if (resourceType)
2484     {
2485         OICFree(*resourceType);
2486     }
2487     return result;
2488 }
2489
2490 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2491                                         char *resourceUri, char **requestUri)
2492 {
2493     char uri[CA_MAX_URI_LENGTH];
2494
2495     FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2496
2497     *requestUri = OICStrdup(uri);
2498     if (!*requestUri)
2499     {
2500         return OC_STACK_NO_MEMORY;
2501     }
2502
2503     return OC_STACK_OK;
2504 }
2505
2506 /**
2507  * Discover or Perform requests on a specified resource
2508  */
2509 OCStackResult OCDoResource(OCDoHandle *handle,
2510                             OCMethod method,
2511                             const char *requestUri,
2512                             const OCDevAddr *destination,
2513                             OCPayload* payload,
2514                             OCConnectivityType connectivityType,
2515                             OCQualityOfService qos,
2516                             OCCallbackData *cbData,
2517                             OCHeaderOption *options,
2518                             uint8_t numOptions)
2519 {
2520     OIC_LOG(INFO, TAG, "Entering OCDoResource");
2521
2522     // Validate input parameters
2523     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2524     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2525     VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2526
2527     OCStackResult result = OC_STACK_ERROR;
2528     CAResult_t caResult;
2529     CAToken_t token = NULL;
2530     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2531     ClientCB *clientCB = NULL;
2532     OCDoHandle resHandle = NULL;
2533     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2534     OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2535     uint32_t ttl = 0;
2536     OCTransportAdapter adapter;
2537     OCTransportFlags flags;
2538     // the request contents are put here
2539     CARequestInfo_t requestInfo = {.method = CA_GET};
2540     // requestUri  will be parsed into the following three variables
2541     OCDevAddr *devAddr = NULL;
2542     char *resourceUri = NULL;
2543     char *resourceType = NULL;
2544
2545     /*
2546      * Support original behavior with address on resourceUri argument.
2547      */
2548     adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2549     flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2550
2551     result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2552
2553     if (result != OC_STACK_OK)
2554     {
2555         OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2556         goto exit;
2557     }
2558
2559     switch (method)
2560     {
2561     case OC_REST_GET:
2562     case OC_REST_OBSERVE:
2563     case OC_REST_OBSERVE_ALL:
2564     case OC_REST_CANCEL_OBSERVE:
2565         requestInfo.method = CA_GET;
2566         break;
2567     case OC_REST_PUT:
2568         requestInfo.method = CA_PUT;
2569         break;
2570     case OC_REST_POST:
2571         requestInfo.method = CA_POST;
2572         break;
2573     case OC_REST_DELETE:
2574         requestInfo.method = CA_DELETE;
2575         break;
2576     case OC_REST_DISCOVER:
2577         qos = OC_LOW_QOS;
2578         if (destination || devAddr)
2579         {
2580             requestInfo.isMulticast = false;
2581         }
2582         else
2583         {
2584             tmpDevAddr.adapter = adapter;
2585             tmpDevAddr.flags = flags;
2586             destination = &tmpDevAddr;
2587             requestInfo.isMulticast = true;
2588         }
2589         // CA_DISCOVER will become GET and isMulticast
2590         requestInfo.method = CA_GET;
2591         break;
2592 #ifdef WITH_PRESENCE
2593     case OC_REST_PRESENCE:
2594         // Replacing method type with GET because "presence"
2595         // is a stack layer only implementation.
2596         requestInfo.method = CA_GET;
2597         break;
2598 #endif
2599     default:
2600         result = OC_STACK_INVALID_METHOD;
2601         goto exit;
2602     }
2603
2604     if (!devAddr && !destination)
2605     {
2606         OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2607         result = OC_STACK_INVALID_PARAM;
2608         goto exit;
2609     }
2610
2611     /* If not original behavior, use destination argument */
2612     if (destination && !devAddr)
2613     {
2614         devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2615         if (!devAddr)
2616         {
2617             result = OC_STACK_NO_MEMORY;
2618             goto exit;
2619         }
2620         *devAddr = *destination;
2621     }
2622
2623     resHandle = GenerateInvocationHandle();
2624     if (!resHandle)
2625     {
2626         result = OC_STACK_NO_MEMORY;
2627         goto exit;
2628     }
2629
2630     caResult = CAGenerateToken(&token, tokenLength);
2631     if (caResult != CA_STATUS_OK)
2632     {
2633         OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2634         result= OC_STACK_ERROR;
2635         goto exit;
2636     }
2637
2638     // fill in request data
2639     requestInfo.info.type = qualityOfServiceToMessageType(qos);
2640     requestInfo.info.token = token;
2641     requestInfo.info.tokenLength = tokenLength;
2642     requestInfo.info.resourceUri = resourceUri;
2643
2644     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2645     {
2646         result = CreateObserveHeaderOption (&(requestInfo.info.options),
2647                                     options, numOptions, OC_OBSERVE_REGISTER);
2648         if (result != OC_STACK_OK)
2649         {
2650             goto exit;
2651         }
2652         requestInfo.info.numOptions = numOptions + 1;
2653     }
2654     else
2655     {
2656         requestInfo.info.numOptions = numOptions;
2657         requestInfo.info.options =
2658             (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2659         memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2660                numOptions * sizeof(CAHeaderOption_t));
2661     }
2662
2663     CopyDevAddrToEndpoint(devAddr, &endpoint);
2664
2665     if(payload)
2666     {
2667         if((result =
2668             OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2669                 != OC_STACK_OK)
2670         {
2671             OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2672             goto exit;
2673         }
2674         requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2675     }
2676     else
2677     {
2678         requestInfo.info.payload = NULL;
2679         requestInfo.info.payloadSize = 0;
2680         requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2681     }
2682
2683     if (result != OC_STACK_OK)
2684     {
2685         OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2686         goto exit;
2687     }
2688
2689     // prepare for response
2690 #ifdef WITH_PRESENCE
2691     if (method == OC_REST_PRESENCE)
2692     {
2693         char *presenceUri = NULL;
2694         result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2695         if (OC_STACK_OK != result)
2696         {
2697             goto exit;
2698         }
2699
2700         // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2701         // Presence notification will form a canonical uri to
2702         // look for callbacks into the application.
2703         resourceUri = presenceUri;
2704     }
2705 #endif
2706
2707     ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2708     result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2709                             method, devAddr, resourceUri, resourceType, ttl);
2710     if (OC_STACK_OK != result)
2711     {
2712         goto exit;
2713     }
2714
2715     devAddr = NULL;       // Client CB list entry now owns it
2716     resourceUri = NULL;   // Client CB list entry now owns it
2717     resourceType = NULL;  // Client CB list entry now owns it
2718
2719     // send request
2720     result = OCSendRequest(&endpoint, &requestInfo);
2721     if (OC_STACK_OK != result)
2722     {
2723         goto exit;
2724     }
2725
2726     if (handle)
2727     {
2728         *handle = resHandle;
2729     }
2730
2731 exit:
2732     if (result != OC_STACK_OK)
2733     {
2734         OIC_LOG(ERROR, TAG, "OCDoResource error");
2735         FindAndDeleteClientCB(clientCB);
2736         CADestroyToken(token);
2737         if (handle)
2738         {
2739             *handle = NULL;
2740         }
2741         OICFree(resHandle);
2742     }
2743
2744     // This is the owner of the payload object, so we free it
2745     OCPayloadDestroy(payload);
2746     OICFree(requestInfo.info.payload);
2747     OICFree(devAddr);
2748     OICFree(resourceUri);
2749     OICFree(resourceType);
2750     OICFree(requestInfo.info.options);
2751     return result;
2752 }
2753
2754 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2755         uint8_t numOptions)
2756 {
2757     /*
2758      * This ftn is implemented one of two ways in the case of observation:
2759      *
2760      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2761      *      Remove the callback associated on client side.
2762      *      When the next notification comes in from server,
2763      *      reply with RESET message to server.
2764      *      Keep in mind that the server will react to RESET only
2765      *      if the last notification was sent as CON
2766      *
2767      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2768      *      and it is associated with an observe request
2769      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2770      *      Send CON Observe request to server with
2771      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2772      *      Remove the callback associated on client side.
2773      */
2774     OCStackResult ret = OC_STACK_OK;
2775     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2776     CARequestInfo_t requestInfo = {.method = CA_GET};
2777
2778     if(!handle)
2779     {
2780         return OC_STACK_INVALID_PARAM;
2781     }
2782
2783     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2784     if (!clientCB)
2785     {
2786         OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2787         return OC_STACK_ERROR;
2788     }
2789
2790     switch (clientCB->method)
2791     {
2792         case OC_REST_OBSERVE:
2793         case OC_REST_OBSERVE_ALL:
2794
2795             OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2796
2797             CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2798
2799             if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2800             {
2801                 FindAndDeleteClientCB(clientCB);
2802                 break;
2803             }
2804
2805             OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2806
2807             requestInfo.info.type = qualityOfServiceToMessageType(qos);
2808             requestInfo.info.token = clientCB->token;
2809             requestInfo.info.tokenLength = clientCB->tokenLength;
2810
2811             if (CreateObserveHeaderOption (&(requestInfo.info.options),
2812                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2813             {
2814                 return OC_STACK_ERROR;
2815             }
2816             requestInfo.info.numOptions = numOptions + 1;
2817             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2818
2819
2820             ret = OCSendRequest(&endpoint, &requestInfo);
2821
2822             if (requestInfo.info.options)
2823             {
2824                 OICFree (requestInfo.info.options);
2825             }
2826             if (requestInfo.info.resourceUri)
2827             {
2828                 OICFree (requestInfo.info.resourceUri);
2829             }
2830
2831             break;
2832
2833         case OC_REST_DISCOVER:
2834             OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2835                                            clientCB->requestUri);
2836             FindAndDeleteClientCB(clientCB);
2837             break;
2838
2839 #ifdef WITH_PRESENCE
2840         case OC_REST_PRESENCE:
2841             FindAndDeleteClientCB(clientCB);
2842             break;
2843 #endif
2844
2845         default:
2846             ret = OC_STACK_INVALID_METHOD;
2847             break;
2848     }
2849
2850     return ret;
2851 }
2852
2853 /**
2854  * @brief   Register Persistent storage callback.
2855  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2856  * @return
2857  *     OC_STACK_OK    - No errors; Success
2858  *     OC_STACK_INVALID_PARAM - Invalid parameter
2859  */
2860 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2861 {
2862     OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2863     if(!persistentStorageHandler)
2864     {
2865         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2866         return OC_STACK_INVALID_PARAM;
2867     }
2868     else
2869     {
2870         if( !persistentStorageHandler->open ||
2871                 !persistentStorageHandler->close ||
2872                 !persistentStorageHandler->read ||
2873                 !persistentStorageHandler->unlink ||
2874                 !persistentStorageHandler->write)
2875         {
2876             OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2877             return OC_STACK_INVALID_PARAM;
2878         }
2879     }
2880     return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2881 }
2882
2883 #ifdef WITH_PRESENCE
2884
2885 OCStackResult OCProcessPresence()
2886 {
2887     OCStackResult result = OC_STACK_OK;
2888
2889     // the following line floods the log with messages that are irrelevant
2890     // to most purposes.  Uncomment as needed.
2891     //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2892     ClientCB* cbNode = NULL;
2893     OCClientResponse clientResponse;
2894     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2895
2896     LL_FOREACH(cbList, cbNode)
2897     {
2898         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2899         {
2900             continue;
2901         }
2902
2903         uint32_t now = GetTicks(0);
2904         OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2905                                                 cbNode->presence->TTLlevel);
2906         OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2907
2908         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2909         {
2910             goto exit;
2911         }
2912
2913         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2914         {
2915             OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2916                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2917         }
2918         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2919         {
2920             OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2921
2922             clientResponse.sequenceNumber = 0;
2923             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2924             clientResponse.devAddr = *cbNode->devAddr;
2925             FixUpClientResponse(&clientResponse);
2926             clientResponse.payload = NULL;
2927
2928             // Increment the TTLLevel (going to a next state), so we don't keep
2929             // sending presence notification to client.
2930             cbNode->presence->TTLlevel++;
2931             OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2932                                         cbNode->presence->TTLlevel);
2933
2934             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2935             if (cbResult == OC_STACK_DELETE_TRANSACTION)
2936             {
2937                 FindAndDeleteClientCB(cbNode);
2938             }
2939         }
2940
2941         if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2942         {
2943             continue;
2944         }
2945
2946         CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2947         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2948         CARequestInfo_t requestInfo = {.method = CA_GET};
2949
2950         OIC_LOG(DEBUG, TAG, "time to test server presence");
2951
2952         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2953
2954         requestData.type = CA_MSG_NONCONFIRM;
2955         requestData.token = cbNode->token;
2956         requestData.tokenLength = cbNode->tokenLength;
2957         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2958         requestInfo.method = CA_GET;
2959         requestInfo.info = requestData;
2960
2961         result = OCSendRequest(&endpoint, &requestInfo);
2962         if (OC_STACK_OK != result)
2963         {
2964             goto exit;
2965         }
2966
2967         cbNode->presence->TTLlevel++;
2968         OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2969     }
2970 exit:
2971     if (result != OC_STACK_OK)
2972     {
2973         OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2974     }
2975
2976     return result;
2977 }
2978 #endif // WITH_PRESENCE
2979
2980 OCStackResult OCProcess()
2981 {
2982 #ifdef WITH_PRESENCE
2983     OCProcessPresence();
2984 #endif
2985     CAHandleRequestResponse();
2986
2987 #ifdef ROUTING_GATEWAY
2988     RMProcess();
2989 #endif
2990
2991 #ifdef TCP_ADAPTER
2992     ProcessKeepAlive();
2993 #endif
2994     return OC_STACK_OK;
2995 }
2996
2997 #ifdef WITH_PRESENCE
2998 OCStackResult OCStartPresence(const uint32_t ttl)
2999 {
3000     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3001     OCChangeResourceProperty(
3002             &(((OCResource *)presenceResource.handle)->resourceProperties),
3003             OC_ACTIVE, 1);
3004
3005     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3006     {
3007         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3008         OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3009     }
3010     else if (0 == ttl)
3011     {
3012         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3013         OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3014     }
3015     else
3016     {
3017         presenceResource.presenceTTL = ttl;
3018     }
3019     OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3020
3021     if (OC_PRESENCE_UNINITIALIZED == presenceState)
3022     {
3023         presenceState = OC_PRESENCE_INITIALIZED;
3024
3025         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3026
3027         CAToken_t caToken = NULL;
3028         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3029         if (caResult != CA_STATUS_OK)
3030         {
3031             OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3032             CADestroyToken(caToken);
3033             return OC_STACK_ERROR;
3034         }
3035
3036         AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3037                 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3038         CADestroyToken(caToken);
3039     }
3040
3041     // Each time OCStartPresence is called
3042     // a different random 32-bit integer number is used
3043     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3044
3045     return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3046             OC_PRESENCE_TRIGGER_CREATE);
3047 }
3048
3049 OCStackResult OCStopPresence()
3050 {
3051     OCStackResult result = OC_STACK_ERROR;
3052
3053     if(presenceResource.handle)
3054     {
3055         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3056
3057     // make resource inactive
3058     result = OCChangeResourceProperty(
3059             &(((OCResource *) presenceResource.handle)->resourceProperties),
3060             OC_ACTIVE, 0);
3061     }
3062
3063     if(result != OC_STACK_OK)
3064     {
3065         OIC_LOG(ERROR, TAG,
3066                       "Changing the presence resource properties to ACTIVE not successful");
3067         return result;
3068     }
3069
3070     return SendStopNotification();
3071 }
3072 #endif
3073
3074 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3075                                             void* callbackParameter)
3076 {
3077     defaultDeviceHandler = entityHandler;
3078     defaultDeviceHandlerCallbackParameter = callbackParameter;
3079
3080     return OC_STACK_OK;
3081 }
3082
3083 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3084 {
3085     OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3086
3087     if(myStackMode ==  OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3088     {
3089         if (validatePlatformInfo(platformInfo))
3090         {
3091             return SavePlatformInfo(platformInfo);
3092         }
3093         else
3094         {
3095             return OC_STACK_INVALID_PARAM;
3096         }
3097     }
3098     else
3099     {
3100         return OC_STACK_ERROR;
3101     }
3102 }
3103
3104 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3105 {
3106     OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3107
3108     if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3109     {
3110         OIC_LOG(ERROR, TAG, "Null or empty device name.");
3111         return OC_STACK_INVALID_PARAM;
3112     }
3113
3114     if (deviceInfo.types)
3115     {
3116         OCStringLL *type =  deviceInfo.types;
3117         OCResource *resource = findResource((OCResource *) deviceResource);
3118         if (!resource)
3119         {
3120             return OC_STACK_INVALID_PARAM;
3121         }
3122         deleteResourceType(resource->rsrcType);
3123         resource->rsrcType = NULL;
3124
3125         while (type)
3126         {
3127             OCBindResourceTypeToResource(deviceResource, type->value);
3128             type = type->next;
3129         }
3130     }
3131     return SaveDeviceInfo(deviceInfo);
3132 }
3133
3134 OCStackResult OCCreateResource(OCResourceHandle *handle,
3135         const char *resourceTypeName,
3136         const char *resourceInterfaceName,
3137         const char *uri, OCEntityHandler entityHandler,
3138         void* callbackParam,
3139         uint8_t resourceProperties)
3140 {
3141
3142     OCResource *pointer = NULL;
3143     OCStackResult result = OC_STACK_ERROR;
3144
3145     OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3146
3147     if(myStackMode == OC_CLIENT)
3148     {
3149         return OC_STACK_INVALID_PARAM;
3150     }
3151     // Validate parameters
3152     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3153     {
3154         OIC_LOG(ERROR, TAG, "URI is empty or too long");
3155         return OC_STACK_INVALID_URI;
3156     }
3157     // Is it presented during resource discovery?
3158     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3159     {
3160         OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3161         return OC_STACK_INVALID_PARAM;
3162     }
3163
3164     if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3165     {
3166         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3167     }
3168
3169     // Make sure resourceProperties bitmask has allowed properties specified
3170     if (resourceProperties
3171             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3172                OC_EXPLICIT_DISCOVERABLE))
3173     {
3174         OIC_LOG(ERROR, TAG, "Invalid property");
3175         return OC_STACK_INVALID_PARAM;
3176     }
3177
3178     // If the headResource is NULL, then no resources have been created...
3179     pointer = headResource;
3180     if (pointer)
3181     {
3182         // At least one resources is in the resource list, so we need to search for
3183         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
3184         while (pointer)
3185         {
3186             if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3187             {
3188                 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3189                 return OC_STACK_INVALID_PARAM;
3190             }
3191             pointer = pointer->next;
3192         }
3193     }
3194     // Create the pointer and insert it into the resource list
3195     pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3196     if (!pointer)
3197     {
3198         result = OC_STACK_NO_MEMORY;
3199         goto exit;
3200     }
3201     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3202
3203     insertResource(pointer);
3204
3205     // Set the uri
3206     pointer->uri = OICStrdup(uri);
3207     if (!pointer->uri)
3208     {
3209         result = OC_STACK_NO_MEMORY;
3210         goto exit;
3211     }
3212
3213     // Set properties.  Set OC_ACTIVE
3214     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3215             | OC_ACTIVE);
3216
3217     // Add the resourcetype to the resource
3218     result = BindResourceTypeToResource(pointer, resourceTypeName);
3219     if (result != OC_STACK_OK)
3220     {
3221         OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3222         goto exit;
3223     }
3224
3225     // Add the resourceinterface to the resource
3226     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3227     if (result != OC_STACK_OK)
3228     {
3229         OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3230         goto exit;
3231     }
3232
3233     // If an entity handler has been passed, attach it to the newly created
3234     // resource.  Otherwise, set the default entity handler.
3235     if (entityHandler)
3236     {
3237         pointer->entityHandler = entityHandler;
3238         pointer->entityHandlerCallbackParam = callbackParam;
3239     }
3240     else
3241     {
3242         pointer->entityHandler = defaultResourceEHandler;
3243         pointer->entityHandlerCallbackParam = NULL;
3244     }
3245
3246     // Initialize a pointer indicating child resources in case of collection
3247     pointer->rsrcChildResourcesHead = NULL;
3248
3249     *handle = pointer;
3250     result = OC_STACK_OK;
3251
3252 #ifdef WITH_PRESENCE
3253     if (presenceResource.handle)
3254     {
3255         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3256         SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3257     }
3258 #endif
3259 exit:
3260     if (result != OC_STACK_OK)
3261     {
3262         // Deep delete of resource and other dynamic elements that it contains
3263         deleteResource(pointer);
3264     }
3265     return result;
3266 }
3267
3268 OCStackResult OCBindResource(
3269         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3270 {
3271     OCResource *resource = NULL;
3272     OCChildResource *tempChildResource = NULL;
3273     OCChildResource *newChildResource = NULL;
3274
3275     OIC_LOG(INFO, TAG, "Entering OCBindResource");
3276
3277     // Validate parameters
3278     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3279     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3280     // Container cannot contain itself
3281     if (collectionHandle == resourceHandle)
3282     {
3283         OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3284         return OC_STACK_INVALID_PARAM;
3285     }
3286
3287     // Use the handle to find the resource in the resource linked list
3288     resource = findResource((OCResource *) collectionHandle);
3289     if (!resource)
3290     {
3291         OIC_LOG(ERROR, TAG, "Collection handle not found");
3292         return OC_STACK_INVALID_PARAM;
3293     }
3294
3295     // Look for an open slot to add add the child resource.
3296     // If found, add it and return success
3297
3298     tempChildResource = resource->rsrcChildResourcesHead;
3299
3300     while(resource->rsrcChildResourcesHead && tempChildResource->next)
3301     {
3302         // TODO: what if one of child resource was deregistered without unbinding?
3303         tempChildResource = tempChildResource->next;
3304     }
3305
3306     // Do memory allocation for child resource
3307     newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3308     if(!newChildResource)
3309     {
3310         OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3311         return OC_STACK_ERROR;
3312     }
3313
3314     newChildResource->rsrcResource = (OCResource *) resourceHandle;
3315     newChildResource->next = NULL;
3316
3317     if(!resource->rsrcChildResourcesHead)
3318     {
3319         resource->rsrcChildResourcesHead = newChildResource;
3320     }
3321     else {
3322         tempChildResource->next = newChildResource;
3323     }
3324
3325     OIC_LOG(INFO, TAG, "resource bound");
3326
3327 #ifdef WITH_PRESENCE
3328     if (presenceResource.handle)
3329     {
3330         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3331         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3332                 OC_PRESENCE_TRIGGER_CHANGE);
3333     }
3334 #endif
3335
3336     return OC_STACK_OK;
3337 }
3338
3339 OCStackResult OCUnBindResource(
3340         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3341 {
3342     OCResource *resource = NULL;
3343     OCChildResource *tempChildResource = NULL;
3344     OCChildResource *tempLastChildResource = NULL;
3345
3346     OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3347
3348     // Validate parameters
3349     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3350     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3351     // Container cannot contain itself
3352     if (collectionHandle == resourceHandle)
3353     {
3354         OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3355         return OC_STACK_INVALID_PARAM;
3356     }
3357
3358     // Use the handle to find the resource in the resource linked list
3359     resource = findResource((OCResource *) collectionHandle);
3360     if (!resource)
3361     {
3362         OIC_LOG(ERROR, TAG, "Collection handle not found");
3363         return OC_STACK_INVALID_PARAM;
3364     }
3365
3366     // Look for an open slot to add add the child resource.
3367     // If found, add it and return success
3368     if(!resource->rsrcChildResourcesHead)
3369     {
3370         OIC_LOG(INFO, TAG, "resource not found in collection");
3371
3372         // Unable to add resourceHandle, so return error
3373         return OC_STACK_ERROR;
3374
3375     }
3376
3377     tempChildResource = resource->rsrcChildResourcesHead;
3378
3379     while (tempChildResource)
3380     {
3381         if(tempChildResource->rsrcResource == resourceHandle)
3382         {
3383             // if resource going to be unbinded is the head one.
3384             if( tempChildResource == resource->rsrcChildResourcesHead )
3385             {
3386                 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3387                 OICFree(resource->rsrcChildResourcesHead);
3388                 resource->rsrcChildResourcesHead = temp;
3389                 temp = NULL;
3390             }
3391             else
3392             {
3393                 OCChildResource *temp = tempChildResource->next;
3394                 OICFree(tempChildResource);
3395                 tempLastChildResource->next = temp;
3396                 temp = NULL;
3397             }
3398
3399             OIC_LOG(INFO, TAG, "resource unbound");
3400
3401             // Send notification when resource is unbounded successfully.
3402 #ifdef WITH_PRESENCE
3403             if (presenceResource.handle)
3404             {
3405                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3406                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3407                         OC_PRESENCE_TRIGGER_CHANGE);
3408             }
3409 #endif
3410             tempChildResource = NULL;
3411             tempLastChildResource = NULL;
3412
3413             return OC_STACK_OK;
3414
3415         }
3416
3417         tempLastChildResource = tempChildResource;
3418         tempChildResource = tempChildResource->next;
3419     }
3420
3421     OIC_LOG(INFO, TAG, "resource not found in collection");
3422
3423     tempChildResource = NULL;
3424     tempLastChildResource = NULL;
3425
3426     // Unable to add resourceHandle, so return error
3427     return OC_STACK_ERROR;
3428 }
3429
3430 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3431 {
3432     if (!resourceItemName)
3433     {
3434         return false;
3435     }
3436     // Per RFC 6690 only registered values must follow the first rule below.
3437     // At this point in time the only values registered begin with "core", and
3438     // all other values are specified as opaque strings where multiple values
3439     // are separated by a space.
3440     if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3441     {
3442         for(size_t index = sizeof(CORESPEC) - 1;  resourceItemName[index]; ++index)
3443         {
3444             if (resourceItemName[index] != '.'
3445                 && resourceItemName[index] != '-'
3446                 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3447                 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3448             {
3449                 return false;
3450             }
3451         }
3452     }
3453     else
3454     {
3455         for (size_t index = 0; resourceItemName[index]; ++index)
3456         {
3457             if (resourceItemName[index] == ' '
3458                 || resourceItemName[index] == '\t'
3459                 || resourceItemName[index] == '\r'
3460                 || resourceItemName[index] == '\n')
3461             {
3462                 return false;
3463             }
3464         }
3465     }
3466
3467     return true;
3468 }
3469
3470 OCStackResult BindResourceTypeToResource(OCResource* resource,
3471                                             const char *resourceTypeName)
3472 {
3473     OCResourceType *pointer = NULL;
3474     char *str = NULL;
3475     OCStackResult result = OC_STACK_ERROR;
3476
3477     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3478
3479     if (!ValidateResourceTypeInterface(resourceTypeName))
3480     {
3481         OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3482         return OC_STACK_INVALID_PARAM;
3483     }
3484
3485     pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3486     if (!pointer)
3487     {
3488         result = OC_STACK_NO_MEMORY;
3489         goto exit;
3490     }
3491
3492     str = OICStrdup(resourceTypeName);
3493     if (!str)
3494     {
3495         result = OC_STACK_NO_MEMORY;
3496         goto exit;
3497     }
3498     pointer->resourcetypename = str;
3499     pointer->next = NULL;
3500
3501     insertResourceType(resource, pointer);
3502     result = OC_STACK_OK;
3503
3504 exit:
3505     if (result != OC_STACK_OK)
3506     {
3507         OICFree(pointer);
3508         OICFree(str);
3509     }
3510
3511     return result;
3512 }
3513
3514 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3515         const char *resourceInterfaceName)
3516 {
3517     OCResourceInterface *pointer = NULL;
3518     char *str = NULL;
3519     OCStackResult result = OC_STACK_ERROR;
3520
3521     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3522
3523     if (!ValidateResourceTypeInterface(resourceInterfaceName))
3524     {
3525         OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3526         return OC_STACK_INVALID_PARAM;
3527     }
3528
3529     OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3530
3531     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3532     if (!pointer)
3533     {
3534         result = OC_STACK_NO_MEMORY;
3535         goto exit;
3536     }
3537
3538     str = OICStrdup(resourceInterfaceName);
3539     if (!str)
3540     {
3541         result = OC_STACK_NO_MEMORY;
3542         goto exit;
3543     }
3544     pointer->name = str;
3545
3546     // Bind the resourceinterface to the resource
3547     insertResourceInterface(resource, pointer);
3548
3549     result = OC_STACK_OK;
3550
3551     exit:
3552     if (result != OC_STACK_OK)
3553     {
3554         OICFree(pointer);
3555         OICFree(str);
3556     }
3557
3558     return result;
3559 }
3560
3561 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3562         const char *resourceTypeName)
3563 {
3564
3565     OCStackResult result = OC_STACK_ERROR;
3566     OCResource *resource = NULL;
3567
3568     resource = findResource((OCResource *) handle);
3569     if (!resource)
3570     {
3571         OIC_LOG(ERROR, TAG, "Resource not found");
3572         return OC_STACK_ERROR;
3573     }
3574
3575     result = BindResourceTypeToResource(resource, resourceTypeName);
3576
3577 #ifdef WITH_PRESENCE
3578     if(presenceResource.handle)
3579     {
3580         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3581         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3582     }
3583 #endif
3584
3585     return result;
3586 }
3587
3588 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3589         const char *resourceInterfaceName)
3590 {
3591
3592     OCStackResult result = OC_STACK_ERROR;
3593     OCResource *resource = NULL;
3594
3595     resource = findResource((OCResource *) handle);
3596     if (!resource)
3597     {
3598         OIC_LOG(ERROR, TAG, "Resource not found");
3599         return OC_STACK_ERROR;
3600     }
3601
3602     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3603
3604 #ifdef WITH_PRESENCE
3605     if (presenceResource.handle)
3606     {
3607         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3608         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3609     }
3610 #endif
3611
3612     return result;
3613 }
3614
3615 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3616 {
3617     OCResource *pointer = headResource;
3618
3619     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3620     *numResources = 0;
3621     while (pointer)
3622     {
3623         *numResources = *numResources + 1;
3624         pointer = pointer->next;
3625     }
3626     return OC_STACK_OK;
3627 }
3628
3629 OCResourceHandle OCGetResourceHandle(uint8_t index)
3630 {
3631     OCResource *pointer = headResource;
3632
3633     for( uint8_t i = 0; i < index && pointer; ++i)
3634     {
3635         pointer = pointer->next;
3636     }
3637     return (OCResourceHandle) pointer;
3638 }
3639
3640 OCStackResult OCDeleteResource(OCResourceHandle handle)
3641 {
3642     if (!handle)
3643     {
3644         OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3645         return OC_STACK_INVALID_PARAM;
3646     }
3647
3648     OCResource *resource = findResource((OCResource *) handle);
3649     if (resource == NULL)
3650     {
3651         OIC_LOG(ERROR, TAG, "Resource not found");
3652         return OC_STACK_NO_RESOURCE;
3653     }
3654
3655     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3656     {
3657         OIC_LOG(ERROR, TAG, "Error deleting resource");
3658         return OC_STACK_ERROR;
3659     }
3660
3661     return OC_STACK_OK;
3662 }
3663
3664 const char *OCGetResourceUri(OCResourceHandle handle)
3665 {
3666     OCResource *resource = NULL;
3667
3668     resource = findResource((OCResource *) handle);
3669     if (resource)
3670     {
3671         return resource->uri;
3672     }
3673     return (const char *) NULL;
3674 }
3675
3676 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3677 {
3678     OCResource *resource = NULL;
3679
3680     resource = findResource((OCResource *) handle);
3681     if (resource)
3682     {
3683         return resource->resourceProperties;
3684     }
3685     return (OCResourceProperty)-1;
3686 }
3687
3688 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3689         uint8_t *numResourceTypes)
3690 {
3691     OCResource *resource = NULL;
3692     OCResourceType *pointer = NULL;
3693
3694     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3695     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3696
3697     *numResourceTypes = 0;
3698
3699     resource = findResource((OCResource *) handle);
3700     if (resource)
3701     {
3702         pointer = resource->rsrcType;
3703         while (pointer)
3704         {
3705             *numResourceTypes = *numResourceTypes + 1;
3706             pointer = pointer->next;
3707         }
3708     }
3709     return OC_STACK_OK;
3710 }
3711
3712 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3713 {
3714     OCResourceType *resourceType = NULL;
3715
3716     resourceType = findResourceTypeAtIndex(handle, index);
3717     if (resourceType)
3718     {
3719         return resourceType->resourcetypename;
3720     }
3721     return (const char *) NULL;
3722 }
3723
3724 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3725         uint8_t *numResourceInterfaces)
3726 {
3727     OCResourceInterface *pointer = NULL;
3728     OCResource *resource = NULL;
3729
3730     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3731     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3732
3733     *numResourceInterfaces = 0;
3734     resource = findResource((OCResource *) handle);
3735     if (resource)
3736     {
3737         pointer = resource->rsrcInterface;
3738         while (pointer)
3739         {
3740             *numResourceInterfaces = *numResourceInterfaces + 1;
3741             pointer = pointer->next;
3742         }
3743     }
3744     return OC_STACK_OK;
3745 }
3746
3747 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3748 {
3749     OCResourceInterface *resourceInterface = NULL;
3750
3751     resourceInterface = findResourceInterfaceAtIndex(handle, index);
3752     if (resourceInterface)
3753     {
3754         return resourceInterface->name;
3755     }
3756     return (const char *) NULL;
3757 }
3758
3759 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3760         uint8_t index)
3761 {
3762     OCResource *resource = NULL;
3763     OCChildResource *tempChildResource = NULL;
3764     uint8_t num = 0;
3765
3766     resource = findResource((OCResource *) collectionHandle);
3767     if (!resource)
3768     {
3769         return NULL;
3770     }
3771
3772     tempChildResource = resource->rsrcChildResourcesHead;
3773
3774     while(tempChildResource)
3775     {
3776         if( num == index )
3777         {
3778             return tempChildResource->rsrcResource;
3779         }
3780         num++;
3781         tempChildResource = tempChildResource->next;
3782     }
3783
3784     // In this case, the number of resource handles in the collection exceeds the index
3785     tempChildResource = NULL;
3786     return NULL;
3787 }
3788
3789 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3790         OCEntityHandler entityHandler,
3791         void* callbackParam)
3792 {
3793     OCResource *resource = NULL;
3794
3795     // Validate parameters
3796     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3797
3798     // Use the handle to find the resource in the resource linked list
3799     resource = findResource((OCResource *)handle);
3800     if (!resource)
3801     {
3802         OIC_LOG(ERROR, TAG, "Resource not found");
3803         return OC_STACK_ERROR;
3804     }
3805
3806     // Bind the handler
3807     resource->entityHandler = entityHandler;
3808     resource->entityHandlerCallbackParam = callbackParam;
3809
3810 #ifdef WITH_PRESENCE
3811     if (presenceResource.handle)
3812     {
3813         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3814         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3815     }
3816 #endif
3817
3818     return OC_STACK_OK;
3819 }
3820
3821 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3822 {
3823     OCResource *resource = NULL;
3824
3825     resource = findResource((OCResource *)handle);
3826     if (!resource)
3827     {
3828         OIC_LOG(ERROR, TAG, "Resource not found");
3829         return NULL;
3830     }
3831
3832     // Bind the handler
3833     return resource->entityHandler;
3834 }
3835
3836 void incrementSequenceNumber(OCResource * resPtr)
3837 {
3838     // Increment the sequence number
3839     resPtr->sequenceNum += 1;
3840     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3841     {
3842         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3843     }
3844     return;
3845 }
3846
3847 #ifdef WITH_PRESENCE
3848 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3849         OCPresenceTrigger trigger)
3850 {
3851     OCResource *resPtr = NULL;
3852     OCStackResult result = OC_STACK_ERROR;
3853     OCMethod method = OC_REST_PRESENCE;
3854     uint32_t maxAge = 0;
3855     resPtr = findResource((OCResource *) presenceResource.handle);
3856     if(NULL == resPtr)
3857     {
3858         return OC_STACK_NO_RESOURCE;
3859     }
3860
3861     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3862     {
3863         maxAge = presenceResource.presenceTTL;
3864
3865         result = SendAllObserverNotification(method, resPtr, maxAge,
3866                 trigger, resourceType, OC_LOW_QOS);
3867     }
3868
3869     return result;
3870 }
3871
3872 OCStackResult SendStopNotification()
3873 {
3874     OCResource *resPtr = NULL;
3875     OCStackResult result = OC_STACK_ERROR;
3876     OCMethod method = OC_REST_PRESENCE;
3877     resPtr = findResource((OCResource *) presenceResource.handle);
3878     if(NULL == resPtr)
3879     {
3880         return OC_STACK_NO_RESOURCE;
3881     }
3882
3883     // maxAge is 0. ResourceType is NULL.
3884     result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3885             NULL, OC_LOW_QOS);
3886
3887     return result;
3888 }
3889
3890 #endif // WITH_PRESENCE
3891 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3892 {
3893     OCResource *resPtr = NULL;
3894     OCStackResult result = OC_STACK_ERROR;
3895     OCMethod method = OC_REST_NOMETHOD;
3896     uint32_t maxAge = 0;
3897
3898     OIC_LOG(INFO, TAG, "Notifying all observers");
3899 #ifdef WITH_PRESENCE
3900     if(handle == presenceResource.handle)
3901     {
3902         return OC_STACK_OK;
3903     }
3904 #endif // WITH_PRESENCE
3905     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3906
3907     // Verify that the resource exists
3908     resPtr = findResource ((OCResource *) handle);
3909     if (NULL == resPtr)
3910     {
3911         return OC_STACK_NO_RESOURCE;
3912     }
3913     else
3914     {
3915         //only increment in the case of regular observing (not presence)
3916         incrementSequenceNumber(resPtr);
3917         method = OC_REST_OBSERVE;
3918         maxAge = MAX_OBSERVE_AGE;
3919 #ifdef WITH_PRESENCE
3920         result = SendAllObserverNotification (method, resPtr, maxAge,
3921                 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3922 #else
3923         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3924 #endif
3925         return result;
3926     }
3927 }
3928
3929 OCStackResult
3930 OCNotifyListOfObservers (OCResourceHandle handle,
3931                          OCObservationId  *obsIdList,
3932                          uint8_t          numberOfIds,
3933                          const OCRepPayload       *payload,
3934                          OCQualityOfService qos)
3935 {
3936     OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3937
3938     OCResource *resPtr = NULL;
3939     //TODO: we should allow the server to define this
3940     uint32_t maxAge = MAX_OBSERVE_AGE;
3941
3942     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3943     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3944     VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3945
3946     resPtr = findResource ((OCResource *) handle);
3947     if (NULL == resPtr || myStackMode == OC_CLIENT)
3948     {
3949         return OC_STACK_NO_RESOURCE;
3950     }
3951     else
3952     {
3953         incrementSequenceNumber(resPtr);
3954     }
3955     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3956             payload, maxAge, qos));
3957 }
3958
3959 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3960 {
3961     OCStackResult result = OC_STACK_ERROR;
3962     OCServerRequest *serverRequest = NULL;
3963
3964     OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3965
3966     // Validate input parameters
3967     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3968     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3969
3970     // Normal response
3971     // Get pointer to request info
3972     serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3973     if(serverRequest)
3974     {
3975         // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3976         result = serverRequest->ehResponseHandler(ehResponse);
3977     }
3978
3979     return result;
3980 }
3981
3982 //#ifdef DIRECT_PAIRING
3983 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3984 {
3985     OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3986     if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3987     {
3988         OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3989         return NULL;
3990     }
3991
3992     return (const OCDPDev_t*)DPGetDiscoveredDevices();
3993 }
3994
3995 const OCDPDev_t* OCGetDirectPairedDevices()
3996 {
3997     return (const OCDPDev_t*)DPGetPairedDevices();
3998 }
3999
4000 void DirectPairingCB (OCDirectPairingDev_t * peer, OCStackResult result)
4001 {
4002     if (gDirectpairingCallback)
4003     {
4004         gDirectpairingCallback((OCDPDev_t*)peer, result);
4005         gDirectpairingCallback = NULL;
4006     }
4007 }
4008
4009 OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4010                                                      OCDirectPairingCB resultCallback)
4011 {
4012     OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4013     if(NULL ==  peer || NULL == pinNumber)
4014     {
4015         OIC_LOG(ERROR, TAG, "Invalid parameters");
4016         return OC_STACK_INVALID_PARAM;
4017     }
4018     if (NULL == resultCallback)
4019     {
4020         OIC_LOG(ERROR, TAG, "Invalid callback");
4021         return OC_STACK_INVALID_CALLBACK;
4022     }
4023
4024     gDirectpairingCallback = resultCallback;
4025     return DPDirectPairing((OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4026                                            pinNumber, DirectPairingCB);
4027 }
4028 //#endif // DIRECT_PAIRING
4029
4030 //-----------------------------------------------------------------------------
4031 // Private internal function definitions
4032 //-----------------------------------------------------------------------------
4033 static OCDoHandle GenerateInvocationHandle()
4034 {
4035     OCDoHandle handle = NULL;
4036     // Generate token here, it will be deleted when the transaction is deleted
4037     handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4038     if (handle)
4039     {
4040         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4041     }
4042
4043     return handle;
4044 }
4045
4046 #ifdef WITH_PRESENCE
4047 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4048         OCResourceProperty resourceProperties, uint8_t enable)
4049 {
4050     if (!inputProperty)
4051     {
4052         return OC_STACK_INVALID_PARAM;
4053     }
4054     if (resourceProperties
4055             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4056     {
4057         OIC_LOG(ERROR, TAG, "Invalid property");
4058         return OC_STACK_INVALID_PARAM;
4059     }
4060     if(!enable)
4061     {
4062         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4063     }
4064     else
4065     {
4066         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4067     }
4068     return OC_STACK_OK;
4069 }
4070 #endif
4071
4072 OCStackResult initResources()
4073 {
4074     OCStackResult result = OC_STACK_OK;
4075
4076     headResource = NULL;
4077     tailResource = NULL;
4078     // Init Virtual Resources
4079 #ifdef WITH_PRESENCE
4080     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4081
4082     result = OCCreateResource(&presenceResource.handle,
4083             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4084             "core.r",
4085             OC_RSRVD_PRESENCE_URI,
4086             NULL,
4087             NULL,
4088             OC_OBSERVABLE);
4089     //make resource inactive
4090     result = OCChangeResourceProperty(
4091             &(((OCResource *) presenceResource.handle)->resourceProperties),
4092             OC_ACTIVE, 0);
4093 #endif
4094 #ifndef WITH_ARDUINO
4095     if (result == OC_STACK_OK)
4096     {
4097         result = SRMInitSecureResources();
4098     }
4099 #endif
4100
4101     if(result == OC_STACK_OK)
4102     {
4103         result = OCCreateResource(&deviceResource,
4104                                   OC_RSRVD_RESOURCE_TYPE_DEVICE,
4105                                   OC_RSRVD_INTERFACE_DEFAULT,
4106                                   OC_RSRVD_DEVICE_URI,
4107                                   NULL,
4108                                   NULL,
4109                                   OC_DISCOVERABLE);
4110         if(result == OC_STACK_OK)
4111         {
4112             result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4113                                                      OC_RSRVD_INTERFACE_READ);
4114         }
4115     }
4116
4117     if(result == OC_STACK_OK)
4118     {
4119         result = OCCreateResource(&platformResource,
4120                                   OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4121                                   OC_RSRVD_INTERFACE_DEFAULT,
4122                                   OC_RSRVD_PLATFORM_URI,
4123                                   NULL,
4124                                   NULL,
4125                                   OC_DISCOVERABLE);
4126         if(result == OC_STACK_OK)
4127         {
4128             result = BindResourceInterfaceToResource((OCResource *)platformResource,
4129                                                      OC_RSRVD_INTERFACE_READ);
4130         }
4131     }
4132
4133     return result;
4134 }
4135
4136 void insertResource(OCResource *resource)
4137 {
4138     if (!headResource)
4139     {
4140         headResource = resource;
4141         tailResource = resource;
4142     }
4143     else
4144     {
4145         tailResource->next = resource;
4146         tailResource = resource;
4147     }
4148     resource->next = NULL;
4149 }
4150
4151 OCResource *findResource(OCResource *resource)
4152 {
4153     OCResource *pointer = headResource;
4154
4155     while (pointer)
4156     {
4157         if (pointer == resource)
4158         {
4159             return resource;
4160         }
4161         pointer = pointer->next;
4162     }
4163     return NULL;
4164 }
4165
4166 void deleteAllResources()
4167 {
4168     OCResource *pointer = headResource;
4169     OCResource *temp = NULL;
4170
4171     while (pointer)
4172     {
4173         temp = pointer->next;
4174 #ifdef WITH_PRESENCE
4175         if (pointer != (OCResource *) presenceResource.handle)
4176         {
4177 #endif // WITH_PRESENCE
4178             deleteResource(pointer);
4179 #ifdef WITH_PRESENCE
4180         }
4181 #endif // WITH_PRESENCE
4182         pointer = temp;
4183     }
4184
4185     SRMDeInitSecureResources();
4186
4187 #ifdef WITH_PRESENCE
4188     // Ensure that the last resource to be deleted is the presence resource. This allows for all
4189     // presence notification attributed to their deletion to be processed.
4190     deleteResource((OCResource *) presenceResource.handle);
4191 #endif // WITH_PRESENCE
4192 }
4193
4194 OCStackResult deleteResource(OCResource *resource)
4195 {
4196     OCResource *prev = NULL;
4197     OCResource *temp = NULL;
4198     if(!resource)
4199     {
4200         OIC_LOG(DEBUG,TAG,"resource is NULL");
4201         return OC_STACK_INVALID_PARAM;
4202     }
4203
4204     OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4205
4206     temp = headResource;
4207     while (temp)
4208     {
4209         if (temp == resource)
4210         {
4211             // Invalidate all Resource Properties.
4212             resource->resourceProperties = (OCResourceProperty) 0;
4213 #ifdef WITH_PRESENCE
4214             if(resource != (OCResource *) presenceResource.handle)
4215             {
4216 #endif // WITH_PRESENCE
4217                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4218 #ifdef WITH_PRESENCE
4219             }
4220
4221             if(presenceResource.handle)
4222             {
4223                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4224                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4225             }
4226 #endif
4227             // Only resource in list.
4228             if (temp == headResource && temp == tailResource)
4229             {
4230                 headResource = NULL;
4231                 tailResource = NULL;
4232             }
4233             // Deleting head.
4234             else if (temp == headResource)
4235             {
4236                 headResource = temp->next;
4237             }
4238             // Deleting tail.
4239             else if (temp == tailResource)
4240             {
4241                 tailResource = prev;
4242                 tailResource->next = NULL;
4243             }
4244             else
4245             {
4246                 prev->next = temp->next;
4247             }
4248
4249             deleteResourceElements(temp);
4250             OICFree(temp);
4251             return OC_STACK_OK;
4252         }
4253         else
4254         {
4255             prev = temp;
4256             temp = temp->next;
4257         }
4258     }
4259
4260     return OC_STACK_ERROR;
4261 }
4262
4263 void deleteResourceElements(OCResource *resource)
4264 {
4265     if (!resource)
4266     {
4267         return;
4268     }
4269
4270     OICFree(resource->uri);
4271     deleteResourceType(resource->rsrcType);
4272     deleteResourceInterface(resource->rsrcInterface);
4273 }
4274
4275 void deleteResourceType(OCResourceType *resourceType)
4276 {
4277     OCResourceType *pointer = resourceType;
4278     OCResourceType *next = NULL;
4279
4280     while (pointer)
4281     {
4282         next = pointer->next;
4283         OICFree(pointer->resourcetypename);
4284         OICFree(pointer);
4285         pointer = next;
4286     }
4287 }
4288
4289 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4290 {
4291     OCResourceInterface *pointer = resourceInterface;
4292     OCResourceInterface *next = NULL;
4293
4294     while (pointer)
4295     {
4296         next = pointer->next;
4297         OICFree(pointer->name);
4298         OICFree(pointer);
4299         pointer = next;
4300     }
4301 }
4302
4303 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4304 {
4305     OCResourceType *pointer = NULL;
4306     OCResourceType *previous = NULL;
4307     if (!resource || !resourceType)
4308     {
4309         return;
4310     }
4311     // resource type list is empty.
4312     else if (!resource->rsrcType)
4313     {
4314         resource->rsrcType = resourceType;
4315     }
4316     else
4317     {
4318         pointer = resource->rsrcType;
4319
4320         while (pointer)
4321         {
4322             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4323             {
4324                 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4325                 OICFree(resourceType->resourcetypename);
4326                 OICFree(resourceType);
4327                 return;
4328             }
4329             previous = pointer;
4330             pointer = pointer->next;
4331         }
4332
4333         if (previous)
4334         {
4335             previous->next = resourceType;
4336         }
4337     }
4338     resourceType->next = NULL;
4339
4340     OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4341 }
4342
4343 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4344 {
4345     OCResource *resource = NULL;
4346     OCResourceType *pointer = NULL;
4347
4348     // Find the specified resource
4349     resource = findResource((OCResource *) handle);
4350     if (!resource)
4351     {
4352         return NULL;
4353     }
4354
4355     // Make sure a resource has a resourcetype
4356     if (!resource->rsrcType)
4357     {
4358         return NULL;
4359     }
4360
4361     // Iterate through the list
4362     pointer = resource->rsrcType;
4363     for(uint8_t i = 0; i< index && pointer; ++i)
4364     {
4365         pointer = pointer->next;
4366     }
4367     return pointer;
4368 }
4369
4370 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4371 {
4372     if(resourceTypeList && resourceTypeName)
4373     {
4374         OCResourceType * rtPointer = resourceTypeList;
4375         while(resourceTypeName && rtPointer)
4376         {
4377             if(rtPointer->resourcetypename &&
4378                     strcmp(resourceTypeName, (const char *)
4379                     (rtPointer->resourcetypename)) == 0)
4380             {
4381                 break;
4382             }
4383             rtPointer = rtPointer->next;
4384         }
4385         return rtPointer;
4386     }
4387     return NULL;
4388 }
4389
4390 /*
4391  * Insert a new interface into interface linked list only if not already present.
4392  * If alredy present, 2nd arg is free'd.
4393  * Default interface will always be first if present.
4394  */
4395 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4396 {
4397     OCResourceInterface *pointer = NULL;
4398     OCResourceInterface *previous = NULL;
4399
4400     newInterface->next = NULL;
4401
4402     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4403
4404     if (!*firstInterface)
4405     {
4406         // If first interface is not oic.if.baseline, by default add it as first interface type.
4407         if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4408         {
4409             *firstInterface = newInterface;
4410         }
4411         else
4412         {
4413             OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4414             if (result != OC_STACK_OK)
4415             {
4416                 OICFree(newInterface->name);
4417                 OICFree(newInterface);
4418                 return;
4419             }
4420             if (*firstInterface)
4421             {
4422                 (*firstInterface)->next = newInterface;
4423             }
4424         }
4425     }
4426     // If once add oic.if.baseline, later too below code take care of freeing memory.
4427     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4428     {
4429         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4430         {
4431             OICFree(newInterface->name);
4432             OICFree(newInterface);
4433             return;
4434         }
4435         // This code will not hit anymore, keeping
4436         else
4437         {
4438             newInterface->next = *firstInterface;
4439             *firstInterface = newInterface;
4440         }
4441     }
4442     else
4443     {
4444         pointer = *firstInterface;
4445         while (pointer)
4446         {
4447             if (strcmp(newInterface->name, pointer->name) == 0)
4448             {
4449                 OICFree(newInterface->name);
4450                 OICFree(newInterface);
4451                 return;
4452             }
4453             previous = pointer;
4454             pointer = pointer->next;
4455         }
4456         previous->next = newInterface;
4457     }
4458 }
4459
4460 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4461         uint8_t index)
4462 {
4463     OCResource *resource = NULL;
4464     OCResourceInterface *pointer = NULL;
4465
4466     // Find the specified resource
4467     resource = findResource((OCResource *) handle);
4468     if (!resource)
4469     {
4470         return NULL;
4471     }
4472
4473     // Make sure a resource has a resourceinterface
4474     if (!resource->rsrcInterface)
4475     {
4476         return NULL;
4477     }
4478
4479     // Iterate through the list
4480     pointer = resource->rsrcInterface;
4481
4482     for (uint8_t i = 0; i < index && pointer; ++i)
4483     {
4484         pointer = pointer->next;
4485     }
4486     return pointer;
4487 }
4488
4489 /*
4490  * This function splits the uri using the '?' delimiter.
4491  * "uriWithoutQuery" is the block of characters between the beginning
4492  * till the delimiter or '\0' which ever comes first.
4493  * "query" is whatever is to the right of the delimiter if present.
4494  * No delimiter sets the query to NULL.
4495  * If either are present, they will be malloc'ed into the params 2, 3.
4496  * The first param, *uri is left untouched.
4497
4498  * NOTE: This function does not account for whitespace at the end of the uri NOR
4499  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
4500  *       part of the query.
4501  */
4502 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4503 {
4504     if(!uri)
4505     {
4506         return OC_STACK_INVALID_URI;
4507     }
4508     if(!query || !uriWithoutQuery)
4509     {
4510         return OC_STACK_INVALID_PARAM;
4511     }
4512
4513     *query           = NULL;
4514     *uriWithoutQuery = NULL;
4515
4516     size_t uriWithoutQueryLen = 0;
4517     size_t queryLen = 0;
4518     size_t uriLen = strlen(uri);
4519
4520     char *pointerToDelimiter = strstr(uri, "?");
4521
4522     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4523     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4524
4525     if (uriWithoutQueryLen)
4526     {
4527         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4528         if (!*uriWithoutQuery)
4529         {
4530             goto exit;
4531         }
4532         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4533     }
4534     if (queryLen)
4535     {
4536         *query = (char *) OICCalloc(queryLen + 1, 1);
4537         if (!*query)
4538         {
4539             OICFree(*uriWithoutQuery);
4540             *uriWithoutQuery = NULL;
4541             goto exit;
4542         }
4543         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4544     }
4545
4546     return OC_STACK_OK;
4547
4548     exit:
4549         return OC_STACK_NO_MEMORY;
4550 }
4551
4552 static const OicUuid_t* OCGetServerInstanceID(void)
4553 {
4554     static bool generated = false;
4555     static OicUuid_t sid;
4556     if (generated)
4557     {
4558         return &sid;
4559     }
4560
4561     if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4562     {
4563         OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4564         return NULL;
4565     }
4566     generated = true;
4567     return &sid;
4568 }
4569
4570 const char* OCGetServerInstanceIDString(void)
4571 {
4572     static bool generated = false;
4573     static char sidStr[UUID_STRING_SIZE];
4574
4575     if(generated)
4576     {
4577         return sidStr;
4578     }
4579
4580     const OicUuid_t *sid = OCGetServerInstanceID();
4581     if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4582     {
4583         OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4584         return NULL;
4585     }
4586
4587     generated = true;
4588     return sidStr;
4589 }
4590
4591 CAResult_t OCSelectNetwork()
4592 {
4593     CAResult_t retResult = CA_STATUS_FAILED;
4594     CAResult_t caResult = CA_STATUS_OK;
4595
4596     CATransportAdapter_t connTypes[] = {
4597             CA_ADAPTER_IP,
4598             CA_ADAPTER_RFCOMM_BTEDR,
4599             CA_ADAPTER_GATT_BTLE,
4600             CA_ADAPTER_NFC
4601 #ifdef RA_ADAPTER
4602             ,CA_ADAPTER_REMOTE_ACCESS
4603 #endif
4604
4605 #ifdef TCP_ADAPTER
4606             ,CA_ADAPTER_TCP
4607 #endif
4608         };
4609     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4610
4611     for(int i = 0; i<numConnTypes; i++)
4612     {
4613         // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4614         if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4615         {
4616            caResult = CASelectNetwork(connTypes[i]);
4617            if(caResult == CA_STATUS_OK)
4618            {
4619                retResult = CA_STATUS_OK;
4620            }
4621         }
4622     }
4623
4624     if(retResult != CA_STATUS_OK)
4625     {
4626         return caResult; // Returns error of appropriate transport that failed fatally.
4627     }
4628
4629     return retResult;
4630 }
4631
4632 OCStackResult CAResultToOCResult(CAResult_t caResult)
4633 {
4634     switch (caResult)
4635     {
4636         case CA_STATUS_OK:
4637             return OC_STACK_OK;
4638         case CA_STATUS_INVALID_PARAM:
4639             return OC_STACK_INVALID_PARAM;
4640         case CA_ADAPTER_NOT_ENABLED:
4641             return OC_STACK_ADAPTER_NOT_ENABLED;
4642         case CA_SERVER_STARTED_ALREADY:
4643             return OC_STACK_OK;
4644         case CA_SERVER_NOT_STARTED:
4645             return OC_STACK_ERROR;
4646         case CA_DESTINATION_NOT_REACHABLE:
4647             return OC_STACK_COMM_ERROR;
4648         case CA_SOCKET_OPERATION_FAILED:
4649             return OC_STACK_COMM_ERROR;
4650         case CA_SEND_FAILED:
4651             return OC_STACK_COMM_ERROR;
4652         case CA_RECEIVE_FAILED:
4653             return OC_STACK_COMM_ERROR;
4654         case CA_MEMORY_ALLOC_FAILED:
4655             return OC_STACK_NO_MEMORY;
4656         case CA_REQUEST_TIMEOUT:
4657             return OC_STACK_TIMEOUT;
4658         case CA_DESTINATION_DISCONNECTED:
4659             return OC_STACK_COMM_ERROR;
4660         case CA_STATUS_FAILED:
4661             return OC_STACK_ERROR;
4662         case CA_NOT_SUPPORTED:
4663             return OC_STACK_NOTIMPL;
4664         default:
4665             return OC_STACK_ERROR;
4666     }
4667 }