1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
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
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
44 #include "ocstackinternal.h"
45 #include "ocresourcehandler.h"
46 #include "occlientcb.h"
47 #include "ocobserve.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
52 #include "ocserverrequest.h"
53 #include "secureresourcemanager.h"
54 #include "doxmresource.h"
56 #include "cainterface.h"
57 #include "ocpayload.h"
58 #include "ocpayloadcbor.h"
60 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
61 #include "routingutility.h"
62 #ifdef ROUTING_GATEWAY
63 #include "routingmanager.h"
68 #include "oickeepalive.h"
71 //#ifdef DIRECT_PAIRING
72 #include "directpairing.h"
75 #ifdef HAVE_ARDUINO_TIME_H
78 #ifdef HAVE_SYS_TIME_H
81 #include "coap_time.h"
85 #ifdef HAVE_ARPA_INET_H
86 #include <arpa/inet.h>
90 #define UINT32_MAX (0xFFFFFFFFUL)
93 //-----------------------------------------------------------------------------
95 //-----------------------------------------------------------------------------
98 OC_STACK_UNINITIALIZED = 0,
100 OC_STACK_UNINIT_IN_PROGRESS
106 OC_PRESENCE_UNINITIALIZED = 0,
107 OC_PRESENCE_INITIALIZED
111 //-----------------------------------------------------------------------------
113 //-----------------------------------------------------------------------------
114 static OCStackState stackState = OC_STACK_UNINITIALIZED;
116 OCResource *headResource = NULL;
117 static OCResource *tailResource = NULL;
118 static OCResourceHandle platformResource = {0};
119 static OCResourceHandle deviceResource = {0};
121 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
122 static PresenceResource presenceResource = {0};
123 static uint8_t PresenceTimeOutSize = 0;
124 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
127 static OCMode myStackMode;
129 //TODO: revisit this design
130 static bool gRASetInfo = false;
132 OCDeviceEntityHandler defaultDeviceHandler;
133 void* defaultDeviceHandlerCallbackParameter = NULL;
134 static const char COAP_TCP[] = "coap+tcp:";
135 static const char CORESPEC[] = "core";
137 //-----------------------------------------------------------------------------
139 //-----------------------------------------------------------------------------
140 #define TAG "OIC_RI_STACK"
141 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
142 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
143 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
144 TAG, #arg " is NULL"); return (retVal); } }
145 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
146 TAG, #arg " is NULL"); return; } }
147 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
150 //TODO: we should allow the server to define this
151 #define MAX_OBSERVE_AGE (0x2FFFFUL)
153 #define MILLISECONDS_PER_SECOND (1000)
155 //-----------------------------------------------------------------------------
156 // Private internal function prototypes
157 //-----------------------------------------------------------------------------
160 * Generate handle of OCDoResource invocation for callback management.
162 * @return Generated OCDoResource handle.
164 static OCDoHandle GenerateInvocationHandle();
167 * Initialize resource data structures, variables, etc.
169 * @return ::OC_STACK_OK on success, some other value upon failure.
171 static OCStackResult initResources();
174 * Add a resource to the end of the linked list of resources.
176 * @param resource Resource to be added
178 static void insertResource(OCResource *resource);
181 * Find a resource in the linked list of resources.
183 * @param resource Resource to be found.
184 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
187 static OCResource *findResource(OCResource *resource);
190 * Insert a resource type into a resource's resource type linked list.
191 * If resource type already exists, it will not be inserted and the
192 * resourceType will be free'd.
193 * resourceType->next should be null to avoid memory leaks.
194 * Function returns silently for null args.
196 * @param resource Resource where resource type is to be inserted.
197 * @param resourceType Resource type to be inserted.
199 static void insertResourceType(OCResource *resource,
200 OCResourceType *resourceType);
203 * Get a resource type at the specified index within a resource.
205 * @param handle Handle of resource.
206 * @param index Index of resource type.
208 * @return Pointer to resource type if found, NULL otherwise.
210 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
214 * Insert a resource interface into a resource's resource interface linked list.
215 * If resource interface already exists, it will not be inserted and the
216 * resourceInterface will be free'd.
217 * resourceInterface->next should be null to avoid memory leaks.
219 * @param resource Resource where resource interface is to be inserted.
220 * @param resourceInterface Resource interface to be inserted.
222 static void insertResourceInterface(OCResource *resource,
223 OCResourceInterface *resourceInterface);
226 * Get a resource interface at the specified index within a resource.
228 * @param handle Handle of resource.
229 * @param index Index of resource interface.
231 * @return Pointer to resource interface if found, NULL otherwise.
233 static OCResourceInterface *findResourceInterfaceAtIndex(
234 OCResourceHandle handle, uint8_t index);
237 * Delete all of the dynamically allocated elements that were created for the resource type.
239 * @param resourceType Specified resource type.
241 static void deleteResourceType(OCResourceType *resourceType);
244 * Delete all of the dynamically allocated elements that were created for the resource interface.
246 * @param resourceInterface Specified resource interface.
248 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
251 * Delete all of the dynamically allocated elements that were created for the resource.
253 * @param resource Specified resource.
255 static void deleteResourceElements(OCResource *resource);
258 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
261 * @param handle Handle of resource to be deleted.
263 * @return ::OC_STACK_OK on success, some other value upon failure.
265 static OCStackResult deleteResource(OCResource *resource);
268 * Delete all of the resources in the resource list.
270 static void deleteAllResources();
273 * Increment resource sequence number. Handles rollover.
275 * @param resPtr Pointer to resource.
277 static void incrementSequenceNumber(OCResource * resPtr);
280 * Attempts to initialize every network interface that the CA Layer might have compiled in.
282 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
283 * return something other than @ref CA_STATUS_OK, then this function fails.
285 * @return ::CA_STATUS_OK on success, some other value upon failure.
287 static CAResult_t OCSelectNetwork();
290 * Get the CoAP ticks after the specified number of milli-seconds.
292 * @param afterMilliSeconds Milli-seconds.
296 static uint32_t GetTicks(uint32_t afterMilliSeconds);
299 * Convert CAResult_t to OCStackResult.
301 * @param caResult CAResult_t code.
302 * @return ::OC_STACK_OK on success, some other value upon failure.
304 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
307 * Convert CAResponseResult_t to OCStackResult.
309 * @param caCode CAResponseResult_t code.
310 * @return ::OC_STACK_OK on success, some other value upon failure.
312 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
315 * Convert OCStackResult to CAResponseResult_t.
317 * @param caCode OCStackResult code.
318 * @param method OCMethod method the return code replies to.
319 * @return ::CA_CONTENT on OK, some other value upon failure.
321 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
324 * Convert OCTransportFlags_t to CATransportModifiers_t.
326 * @param ocConType OCTransportFlags_t input.
327 * @return CATransportFlags
329 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
332 * Convert CATransportFlags_t to OCTransportModifiers_t.
334 * @param caConType CATransportFlags_t input.
335 * @return OCTransportFlags
337 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
340 * Handle response from presence request.
342 * @param endPoint CA remote endpoint.
343 * @param responseInfo CA response info.
344 * @return ::OC_STACK_OK on success, some other value upon failure.
346 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
347 const CAResponseInfo_t *responseInfo);
350 * This function will be called back by CA layer when a response is received.
352 * @param endPoint CA remote endpoint.
353 * @param responseInfo CA response info.
355 static void HandleCAResponses(const CAEndpoint_t* endPoint,
356 const CAResponseInfo_t* responseInfo);
359 * This function will be called back by CA layer when a request is received.
361 * @param endPoint CA remote endpoint.
362 * @param requestInfo CA request info.
364 static void HandleCARequests(const CAEndpoint_t* endPoint,
365 const CARequestInfo_t* requestInfo);
368 * Extract query from a URI.
370 * @param uri Full URI with query.
371 * @param query Pointer to string that will contain query.
372 * @param newURI Pointer to string that will contain URI.
373 * @return ::OC_STACK_OK on success, some other value upon failure.
375 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
378 * Finds a resource type in an OCResourceType link-list.
380 * @param resourceTypeList The link-list to be searched through.
381 * @param resourceTypeName The key to search for.
383 * @return Resource type that matches the key (ie. resourceTypeName) or
384 * NULL if there is either an invalid parameter or this function was unable to find the key.
386 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
387 const char * resourceTypeName);
390 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
391 * TTL will be set to maxAge.
393 * @param cbNode Callback Node for which presence ttl is to be reset.
394 * @param maxAge New value of ttl in seconds.
396 * @return ::OC_STACK_OK on success, some other value upon failure.
398 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
401 * Ensure the accept header option is set appropriatly before sending the requests and routing
402 * header option is updated with destination.
404 * @param object CA remote endpoint.
405 * @param requestInfo CA request info.
407 * @return ::OC_STACK_OK on success, some other value upon failure.
409 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
411 //-----------------------------------------------------------------------------
412 // Internal functions
413 //-----------------------------------------------------------------------------
415 uint32_t GetTicks(uint32_t afterMilliSeconds)
420 // Guard against overflow of uint32_t
421 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
422 COAP_TICKS_PER_SECOND)
424 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
432 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
434 VERIFY_NON_NULL_NR(in, FATAL);
435 VERIFY_NON_NULL_NR(out, FATAL);
437 out->adapter = (OCTransportAdapter)in->adapter;
438 out->flags = CAToOCTransportFlags(in->flags);
439 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
440 out->port = in->port;
441 out->ifindex = in->ifindex;
442 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
443 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
447 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
449 VERIFY_NON_NULL_NR(in, FATAL);
450 VERIFY_NON_NULL_NR(out, FATAL);
452 out->adapter = (CATransportAdapter_t)in->adapter;
453 out->flags = OCToCATransportFlags(in->flags);
454 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
455 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
456 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
458 out->port = in->port;
459 out->ifindex = in->ifindex;
462 void FixUpClientResponse(OCClientResponse *cr)
464 VERIFY_NON_NULL_NR(cr, FATAL);
466 cr->addr = &cr->devAddr;
467 cr->connType = (OCConnectivityType)
468 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
471 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
473 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
474 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
476 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
477 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
478 if (OC_STACK_OK != rmResult)
480 OIC_LOG(ERROR, TAG, "Add destination option failed");
485 // OC stack prefer CBOR encoded payloads.
486 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
487 CAResult_t result = CASendRequest(object, requestInfo);
488 if(CA_STATUS_OK != result)
490 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
491 return CAResultToOCResult(result);
495 //-----------------------------------------------------------------------------
496 // Internal API function
497 //-----------------------------------------------------------------------------
499 // This internal function is called to update the stack with the status of
500 // observers and communication failures
501 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
503 OCStackResult result = OC_STACK_ERROR;
504 ResourceObserver * observer = NULL;
505 OCEntityHandlerRequest ehRequest = {0};
509 case OC_OBSERVER_NOT_INTERESTED:
510 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
511 observer = GetObserverUsingToken (token, tokenLength);
514 result = FormOCEntityHandlerRequest(&ehRequest,
515 (OCRequestHandle)NULL,
518 (OCResourceHandle)NULL,
519 NULL, PAYLOAD_TYPE_REPRESENTATION,
521 OC_OBSERVE_DEREGISTER,
524 if(result != OC_STACK_OK)
528 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
529 observer->resource->entityHandlerCallbackParam);
532 result = DeleteObserverUsingToken (token, tokenLength);
533 if(result == OC_STACK_OK)
535 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
539 result = OC_STACK_OK;
540 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
544 case OC_OBSERVER_STILL_INTERESTED:
545 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
546 observer = GetObserverUsingToken (token, tokenLength);
549 observer->forceHighQos = 0;
550 observer->failedCommCount = 0;
551 result = OC_STACK_OK;
555 result = OC_STACK_OBSERVER_NOT_FOUND;
559 case OC_OBSERVER_FAILED_COMM:
560 OIC_LOG(DEBUG, TAG, "observer is unreachable");
561 observer = GetObserverUsingToken (token, tokenLength);
564 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
566 result = FormOCEntityHandlerRequest(&ehRequest,
567 (OCRequestHandle)NULL,
570 (OCResourceHandle)NULL,
571 NULL, PAYLOAD_TYPE_REPRESENTATION,
573 OC_OBSERVE_DEREGISTER,
576 if(result != OC_STACK_OK)
578 return OC_STACK_ERROR;
580 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
581 observer->resource->entityHandlerCallbackParam);
583 result = DeleteObserverUsingToken (token, tokenLength);
584 if(result == OC_STACK_OK)
586 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
590 result = OC_STACK_OK;
591 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
596 observer->failedCommCount++;
597 result = OC_STACK_CONTINUE;
599 observer->forceHighQos = 1;
600 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
604 OIC_LOG(ERROR, TAG, "Unknown status");
605 result = OC_STACK_ERROR;
611 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
613 OCStackResult ret = OC_STACK_ERROR;
617 case CA_ADAPTER_NOT_ENABLED:
618 case CA_SERVER_NOT_STARTED:
619 ret = OC_STACK_ADAPTER_NOT_ENABLED;
621 case CA_MEMORY_ALLOC_FAILED:
622 ret = OC_STACK_NO_MEMORY;
624 case CA_STATUS_INVALID_PARAM:
625 ret = OC_STACK_INVALID_PARAM;
633 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
635 OCStackResult ret = OC_STACK_ERROR;
640 ret = OC_STACK_RESOURCE_CREATED;
643 ret = OC_STACK_RESOURCE_DELETED;
651 ret = OC_STACK_INVALID_QUERY;
653 case CA_UNAUTHORIZED_REQ:
654 ret = OC_STACK_UNAUTHORIZED_REQ;
657 ret = OC_STACK_INVALID_OPTION;
660 ret = OC_STACK_NO_RESOURCE;
662 case CA_RETRANSMIT_TIMEOUT:
663 ret = OC_STACK_COMM_ERROR;
665 case CA_REQUEST_ENTITY_TOO_LARGE:
666 ret = OC_STACK_TOO_LARGE_REQ;
674 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
676 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
685 // This Response Code is like HTTP 204 "No Content" but only used in
686 // response to POST and PUT requests.
690 // This Response Code is like HTTP 200 "OK" but only used in response to
695 // This should not happen but,
696 // give it a value just in case but output an error
698 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
701 case OC_STACK_RESOURCE_CREATED:
704 case OC_STACK_RESOURCE_DELETED:
707 case OC_STACK_INVALID_QUERY:
710 case OC_STACK_INVALID_OPTION:
713 case OC_STACK_NO_RESOURCE:
716 case OC_STACK_COMM_ERROR:
717 ret = CA_RETRANSMIT_TIMEOUT;
719 case OC_STACK_UNAUTHORIZED_REQ:
720 ret = CA_UNAUTHORIZED_REQ;
728 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
730 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
732 // supply default behavior.
733 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
735 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
737 if ((caFlags & OC_MASK_SCOPE) == 0)
739 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
744 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
746 return (OCTransportFlags)caFlags;
749 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
751 uint32_t lowerBound = 0;
752 uint32_t higherBound = 0;
754 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
756 return OC_STACK_INVALID_PARAM;
759 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
761 cbNode->presence->TTL = maxAgeSeconds;
763 for (int index = 0; index < PresenceTimeOutSize; index++)
765 // Guard against overflow
766 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
769 lowerBound = GetTicks((PresenceTimeOut[index] *
770 cbNode->presence->TTL *
771 MILLISECONDS_PER_SECOND)/100);
775 lowerBound = GetTicks(UINT32_MAX);
778 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
781 higherBound = GetTicks((PresenceTimeOut[index + 1] *
782 cbNode->presence->TTL *
783 MILLISECONDS_PER_SECOND)/100);
787 higherBound = GetTicks(UINT32_MAX);
790 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
792 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
793 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
794 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
797 cbNode->presence->TTLlevel = 0;
799 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
803 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
805 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
807 return OC_RSRVD_TRIGGER_CREATE;
809 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
811 return OC_RSRVD_TRIGGER_CHANGE;
815 return OC_RSRVD_TRIGGER_DELETE;
819 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
823 return OC_PRESENCE_TRIGGER_CREATE;
825 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
827 return OC_PRESENCE_TRIGGER_CREATE;
829 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
831 return OC_PRESENCE_TRIGGER_CHANGE;
835 return OC_PRESENCE_TRIGGER_DELETE;
840 * The cononical presence allows constructed URIs to be string compared.
842 * requestUri must be a char array of size CA_MAX_URI_LENGTH
844 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
847 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
848 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
849 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
851 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
853 if (ep->adapter == CA_ADAPTER_IP)
855 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
857 if ('\0' == ep->addr[0]) // multicast
859 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
863 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
864 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
869 if ('\0' == ep->addr[0]) // multicast
871 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
872 ep->port = OC_MULTICAST_PORT;
874 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
875 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
879 // might work for other adapters (untested, but better than nothing)
880 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
881 OC_RSRVD_PRESENCE_URI);
885 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
886 const CAResponseInfo_t *responseInfo)
888 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
889 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
891 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
892 ClientCB * cbNode = NULL;
893 char *resourceTypeName = NULL;
894 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
895 OCStackResult result = OC_STACK_ERROR;
898 char presenceUri[CA_MAX_URI_LENGTH];
900 int presenceSubscribe = 0;
901 int multicastPresenceSubscribe = 0;
903 if (responseInfo->result != CA_CONTENT)
905 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
906 return OC_STACK_ERROR;
909 // check for unicast presence
910 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
911 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
913 return OC_STACK_INVALID_URI;
916 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
919 presenceSubscribe = 1;
923 // check for multiicast presence
924 CAEndpoint_t ep = { .adapter = endpoint->adapter,
925 .flags = endpoint->flags };
927 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
929 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
932 multicastPresenceSubscribe = 1;
936 if (!presenceSubscribe && !multicastPresenceSubscribe)
938 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
942 response.payload = NULL;
943 response.result = OC_STACK_OK;
945 CopyEndpointToDevAddr(endpoint, &response.devAddr);
946 FixUpClientResponse(&response);
948 if (responseInfo->info.payload)
950 result = OCParsePayload(&response.payload,
951 PAYLOAD_TYPE_PRESENCE,
952 responseInfo->info.payload,
953 responseInfo->info.payloadSize);
955 if(result != OC_STACK_OK)
957 OIC_LOG(ERROR, TAG, "Presence parse failed");
960 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
962 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
963 result = OC_STACK_ERROR;
966 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
967 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
968 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
971 if (presenceSubscribe)
973 if(cbNode->sequenceNumber == response.sequenceNumber)
975 OIC_LOG(INFO, TAG, "No presence change");
976 ResetPresenceTTL(cbNode, maxAge);
977 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
983 OIC_LOG(INFO, TAG, "Stopping presence");
984 response.result = OC_STACK_PRESENCE_STOPPED;
987 OICFree(cbNode->presence->timeOut);
988 OICFree(cbNode->presence);
989 cbNode->presence = NULL;
994 if(!cbNode->presence)
996 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
998 if(!(cbNode->presence))
1000 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1001 result = OC_STACK_NO_MEMORY;
1005 VERIFY_NON_NULL_V(cbNode->presence);
1006 cbNode->presence->timeOut = NULL;
1007 cbNode->presence->timeOut = (uint32_t *)
1008 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1009 if(!(cbNode->presence->timeOut)){
1011 "Could not allocate memory for cbNode->presence->timeOut");
1012 OICFree(cbNode->presence);
1013 result = OC_STACK_NO_MEMORY;
1018 ResetPresenceTTL(cbNode, maxAge);
1020 cbNode->sequenceNumber = response.sequenceNumber;
1022 // Ensure that a filter is actually applied.
1023 if( resourceTypeName && cbNode->filterResourceType)
1025 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1034 // This is the multicast case
1035 OCMulticastNode* mcNode = NULL;
1036 mcNode = GetMCPresenceNode(presenceUri);
1040 if(mcNode->nonce == response.sequenceNumber)
1042 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1045 mcNode->nonce = response.sequenceNumber;
1049 OIC_LOG(INFO, TAG, "Stopping presence");
1050 response.result = OC_STACK_PRESENCE_STOPPED;
1055 char* uri = OICStrdup(presenceUri);
1059 "No Memory for URI to store in the presence node");
1060 result = OC_STACK_NO_MEMORY;
1064 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1065 if(result == OC_STACK_NO_MEMORY)
1068 "No Memory for Multicast Presence Node");
1072 // presence node now owns uri
1075 // Ensure that a filter is actually applied.
1076 if(resourceTypeName && cbNode->filterResourceType)
1078 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1085 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1087 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1089 FindAndDeleteClientCB(cbNode);
1093 OCPayloadDestroy(response.payload);
1097 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1099 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1101 if(responseInfo->info.resourceUri &&
1102 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1104 HandlePresenceResponse(endPoint, responseInfo);
1108 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1109 responseInfo->info.tokenLength, NULL, NULL);
1111 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1112 responseInfo->info.tokenLength);
1116 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1117 if(responseInfo->result == CA_EMPTY)
1119 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1120 // We do not have a case for the client to receive a RESET
1121 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1123 //This is the case of receiving an ACK on a request to a slow resource!
1124 OIC_LOG(INFO, TAG, "This is a pure ACK");
1125 //TODO: should we inform the client
1126 // app that at least the request was received at the server?
1129 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1131 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1132 OIC_LOG(INFO, TAG, "Calling into application address space");
1134 OCClientResponse response =
1135 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1136 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1137 FixUpClientResponse(&response);
1138 response.resourceUri = responseInfo->info.resourceUri;
1139 memcpy(response.identity.id, responseInfo->info.identity.id,
1140 sizeof (response.identity.id));
1141 response.identity.id_length = responseInfo->info.identity.id_length;
1143 response.result = CAResponseToOCStackResult(responseInfo->result);
1144 cbNode->callBack(cbNode->context,
1145 cbNode->handle, &response);
1146 FindAndDeleteClientCB(cbNode);
1150 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1151 OIC_LOG(INFO, TAG, "Calling into application address space");
1153 OCClientResponse response =
1154 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1155 response.sequenceNumber = -1;
1156 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1157 FixUpClientResponse(&response);
1158 response.resourceUri = responseInfo->info.resourceUri;
1159 memcpy(response.identity.id, responseInfo->info.identity.id,
1160 sizeof (response.identity.id));
1161 response.identity.id_length = responseInfo->info.identity.id_length;
1163 response.result = CAResponseToOCStackResult(responseInfo->result);
1165 if(responseInfo->info.payload &&
1166 responseInfo->info.payloadSize)
1168 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1169 // check the security resource
1170 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1172 type = PAYLOAD_TYPE_SECURITY;
1174 else if (cbNode->method == OC_REST_DISCOVER)
1176 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1177 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1179 type = PAYLOAD_TYPE_DISCOVERY;
1181 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1183 type = PAYLOAD_TYPE_DEVICE;
1185 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1187 type = PAYLOAD_TYPE_PLATFORM;
1189 #ifdef ROUTING_GATEWAY
1190 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1192 type = PAYLOAD_TYPE_REPRESENTATION;
1195 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1197 type = PAYLOAD_TYPE_RD;
1200 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1202 type = PAYLOAD_TYPE_REPRESENTATION;
1207 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1208 cbNode->method, cbNode->requestUri);
1212 else if (cbNode->method == OC_REST_GET ||
1213 cbNode->method == OC_REST_PUT ||
1214 cbNode->method == OC_REST_POST ||
1215 cbNode->method == OC_REST_OBSERVE ||
1216 cbNode->method == OC_REST_OBSERVE_ALL ||
1217 cbNode->method == OC_REST_DELETE)
1219 char targetUri[MAX_URI_LENGTH];
1220 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1221 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1222 if (strcmp(targetUri, cbNode->requestUri) == 0)
1224 type = PAYLOAD_TYPE_RD;
1226 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1228 type = PAYLOAD_TYPE_PLATFORM;
1230 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1232 type = PAYLOAD_TYPE_DEVICE;
1234 if (type == PAYLOAD_TYPE_INVALID)
1236 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1237 cbNode->method, cbNode->requestUri);
1238 type = PAYLOAD_TYPE_REPRESENTATION;
1243 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1244 cbNode->method, cbNode->requestUri);
1248 if(OC_STACK_OK != OCParsePayload(&response.payload,
1250 responseInfo->info.payload,
1251 responseInfo->info.payloadSize))
1253 OIC_LOG(ERROR, TAG, "Error converting payload");
1254 OCPayloadDestroy(response.payload);
1259 response.numRcvdVendorSpecificHeaderOptions = 0;
1260 if(responseInfo->info.numOptions > 0)
1263 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1264 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1267 uint32_t observationOption;
1268 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1269 for (observationOption=0, i=0;
1270 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1274 (observationOption << 8) | optionData[i];
1276 response.sequenceNumber = observationOption;
1278 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1283 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1286 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1288 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1289 OCPayloadDestroy(response.payload);
1293 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1295 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1296 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1300 if (cbNode->method == OC_REST_OBSERVE &&
1301 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1302 response.sequenceNumber <= cbNode->sequenceNumber)
1304 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1305 response.sequenceNumber);
1309 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1312 cbNode->sequenceNumber = response.sequenceNumber;
1314 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1316 FindAndDeleteClientCB(cbNode);
1320 // To keep discovery callbacks active.
1321 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1322 MILLISECONDS_PER_SECOND);
1326 //Need to send ACK when the response is CON
1327 if(responseInfo->info.type == CA_MSG_CONFIRM)
1329 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1330 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1333 OCPayloadDestroy(response.payload);
1340 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1341 if(responseInfo->result == CA_EMPTY)
1343 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1344 if(responseInfo->info.type == CA_MSG_RESET)
1346 OIC_LOG(INFO, TAG, "This is a RESET");
1347 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1348 OC_OBSERVER_NOT_INTERESTED);
1350 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1352 OIC_LOG(INFO, TAG, "This is a pure ACK");
1353 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1354 OC_OBSERVER_STILL_INTERESTED);
1357 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1359 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1360 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1361 OC_OBSERVER_FAILED_COMM);
1366 if(!cbNode && !observer)
1368 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1369 || myStackMode == OC_GATEWAY)
1371 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1372 if(responseInfo->result == CA_EMPTY)
1374 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1378 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1379 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1380 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1384 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1385 || myStackMode == OC_GATEWAY)
1387 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1388 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1390 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1391 responseInfo->info.messageId);
1393 if (responseInfo->info.type == CA_MSG_RESET)
1395 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1396 responseInfo->info.messageId);
1403 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1406 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1408 VERIFY_NON_NULL_NR(endPoint, FATAL);
1409 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1411 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1413 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1414 #ifdef ROUTING_GATEWAY
1415 bool needRIHandling = false;
1417 * Routing manager is going to update either of endpoint or response or both.
1418 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1419 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1422 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1424 if(ret != OC_STACK_OK || !needRIHandling)
1426 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1432 * Put source in sender endpoint so that the next packet from application can be routed to
1433 * proper destination and remove "RM" coap header option before passing request / response to
1434 * RI as this option will make no sense to either RI or application.
1436 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1437 (uint8_t *) &(responseInfo->info.numOptions),
1438 (CAEndpoint_t *) endPoint);
1441 OCHandleResponse(endPoint, responseInfo);
1443 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1447 * This function handles error response from CA
1448 * code shall be added to handle the errors
1450 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1452 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1454 if (NULL == endPoint)
1456 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1460 if (NULL == errorInfo)
1462 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1466 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1467 errorInfo->info.tokenLength, NULL, NULL);
1470 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1471 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1472 FixUpClientResponse(&response);
1473 response.resourceUri = errorInfo->info.resourceUri;
1474 memcpy(response.identity.id, errorInfo->info.identity.id,
1475 sizeof (response.identity.id));
1476 response.identity.id_length = errorInfo->info.identity.id_length;
1477 response.result = CAResultToOCStackResult(errorInfo->result);
1479 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1480 FindAndDeleteClientCB(cbNode);
1483 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1487 * This function sends out Direct Stack Responses. These are responses that are not coming
1488 * from the application entity handler. These responses have no payload and are usually ACKs,
1489 * RESETs or some error conditions that were caught by the stack.
1491 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1492 const CAResponseResult_t responseResult, const CAMessageType_t type,
1493 const uint8_t numOptions, const CAHeaderOption_t *options,
1494 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1496 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1497 CAResponseInfo_t respInfo = {
1498 .result = responseResult
1500 respInfo.info.messageId = coapID;
1501 respInfo.info.numOptions = numOptions;
1503 if (respInfo.info.numOptions)
1505 respInfo.info.options =
1506 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1507 memcpy (respInfo.info.options, options,
1508 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1512 respInfo.info.payload = NULL;
1513 respInfo.info.token = token;
1514 respInfo.info.tokenLength = tokenLength;
1515 respInfo.info.type = type;
1516 respInfo.info.resourceUri = OICStrdup (resourceUri);
1517 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1519 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1520 // Add the destination to route option from the endpoint->routeData.
1521 bool doPost = false;
1522 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1523 if(OC_STACK_OK != result)
1525 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1530 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1531 CARequestInfo_t reqInfo = {.method = CA_POST };
1532 /* The following initialization is not done in a single initializer block as in
1533 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1534 * does not have designated initalizers. This is a work-around for now.
1536 reqInfo.info.type = CA_MSG_NONCONFIRM;
1537 reqInfo.info.messageId = coapID;
1538 reqInfo.info.tokenLength = tokenLength;
1539 reqInfo.info.token = token;
1540 reqInfo.info.numOptions = respInfo.info.numOptions;
1541 reqInfo.info.payload = NULL;
1542 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1543 if (reqInfo.info.numOptions)
1545 reqInfo.info.options =
1546 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1547 if (NULL == reqInfo.info.options)
1549 OIC_LOG(ERROR, TAG, "Calloc failed");
1550 return OC_STACK_NO_MEMORY;
1552 memcpy (reqInfo.info.options, respInfo.info.options,
1553 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1556 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1557 OICFree (reqInfo.info.resourceUri);
1558 OICFree (reqInfo.info.options);
1559 OICFree (respInfo.info.resourceUri);
1560 OICFree (respInfo.info.options);
1561 if (CA_STATUS_OK != caResult)
1563 OIC_LOG(ERROR, TAG, "CASendRequest error");
1564 return CAResultToOCResult(caResult);
1570 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1572 // resourceUri in the info field is cloned in the CA layer and
1573 // thus ownership is still here.
1574 OICFree (respInfo.info.resourceUri);
1575 OICFree (respInfo.info.options);
1576 if(CA_STATUS_OK != caResult)
1578 OIC_LOG(ERROR, TAG, "CASendResponse error");
1579 return CAResultToOCResult(caResult);
1582 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1586 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1588 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1589 OCStackResult result = OC_STACK_ERROR;
1590 if(!protocolRequest)
1592 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1593 return OC_STACK_INVALID_PARAM;
1596 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1597 protocolRequest->tokenLength);
1600 OIC_LOG(INFO, TAG, "This is a new Server Request");
1601 result = AddServerRequest(&request, protocolRequest->coapID,
1602 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1603 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1604 protocolRequest->observationOption, protocolRequest->qos,
1605 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1606 protocolRequest->payload, protocolRequest->requestToken,
1607 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1608 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1609 &protocolRequest->devAddr);
1610 if (OC_STACK_OK != result)
1612 OIC_LOG(ERROR, TAG, "Error adding server request");
1618 OIC_LOG(ERROR, TAG, "Out of Memory");
1619 return OC_STACK_NO_MEMORY;
1622 if(!protocolRequest->reqMorePacket)
1624 request->requestComplete = 1;
1629 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1632 if(request->requestComplete)
1634 OIC_LOG(INFO, TAG, "This Server Request is complete");
1635 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1636 OCResource *resource = NULL;
1637 result = DetermineResourceHandling (request, &resHandling, &resource);
1638 if (result == OC_STACK_OK)
1640 result = ProcessRequest(resHandling, resource, request);
1645 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1646 result = OC_STACK_CONTINUE;
1651 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1653 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1656 if (requestInfo->info.resourceUri &&
1657 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1659 HandleKeepAliveRequest(endPoint, requestInfo);
1664 OCStackResult requestResult = OC_STACK_ERROR;
1666 if(myStackMode == OC_CLIENT)
1668 //TODO: should the client be responding to requests?
1672 OCServerProtocolRequest serverRequest = {0};
1674 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1676 char * uriWithoutQuery = NULL;
1677 char * query = NULL;
1679 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1681 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1683 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1686 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1687 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1689 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1691 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1692 OICFree(uriWithoutQuery);
1696 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1697 OICFree(uriWithoutQuery);
1704 if(strlen(query) < MAX_QUERY_LENGTH)
1706 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1711 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1717 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1719 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1720 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1721 if (!serverRequest.payload)
1723 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1726 memcpy (serverRequest.payload, requestInfo->info.payload,
1727 requestInfo->info.payloadSize);
1731 serverRequest.reqTotalSize = 0;
1734 switch (requestInfo->method)
1737 serverRequest.method = OC_REST_GET;
1740 serverRequest.method = OC_REST_PUT;
1743 serverRequest.method = OC_REST_POST;
1746 serverRequest.method = OC_REST_DELETE;
1749 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1750 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1751 requestInfo->info.type, requestInfo->info.numOptions,
1752 requestInfo->info.options, requestInfo->info.token,
1753 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1754 OICFree(serverRequest.payload);
1758 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1759 requestInfo->info.tokenLength);
1761 serverRequest.tokenLength = requestInfo->info.tokenLength;
1762 if (serverRequest.tokenLength) {
1764 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1766 if (!serverRequest.requestToken)
1768 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1769 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1770 requestInfo->info.type, requestInfo->info.numOptions,
1771 requestInfo->info.options, requestInfo->info.token,
1772 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1773 OICFree(serverRequest.payload);
1776 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1779 switch (requestInfo->info.acceptFormat)
1781 case CA_FORMAT_APPLICATION_CBOR:
1782 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1784 case CA_FORMAT_UNDEFINED:
1785 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1788 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1791 if (requestInfo->info.type == CA_MSG_CONFIRM)
1793 serverRequest.qos = OC_HIGH_QOS;
1797 serverRequest.qos = OC_LOW_QOS;
1799 // CA does not need the following field
1800 // Are we sure CA does not need them? how is it responding to multicast
1801 serverRequest.delayedResNeeded = 0;
1803 serverRequest.coapID = requestInfo->info.messageId;
1805 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1807 // copy vendor specific header options
1808 uint8_t tempNum = (requestInfo->info.numOptions);
1810 // Assume no observation requested and it is a pure GET.
1811 // If obs registration/de-registration requested it'll be fetched from the
1812 // options in GetObserveHeaderOption()
1813 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1815 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1816 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1819 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1820 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1821 requestInfo->info.type, requestInfo->info.numOptions,
1822 requestInfo->info.options, requestInfo->info.token,
1823 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1824 OICFree(serverRequest.payload);
1825 OICFree(serverRequest.requestToken);
1828 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1829 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1831 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1832 sizeof(CAHeaderOption_t)*tempNum);
1835 requestResult = HandleStackRequests (&serverRequest);
1837 // Send ACK to client as precursor to slow response
1838 if (requestResult == OC_STACK_SLOW_RESOURCE)
1840 if (requestInfo->info.type == CA_MSG_CONFIRM)
1842 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1843 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1846 else if(!OCResultToSuccess(requestResult))
1848 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1850 CAResponseResult_t stackResponse =
1851 OCToCAStackResult(requestResult, serverRequest.method);
1853 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1854 requestInfo->info.type, requestInfo->info.numOptions,
1855 requestInfo->info.options, requestInfo->info.token,
1856 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1858 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1859 // The token is copied in there, and is thus still owned by this function.
1860 OICFree(serverRequest.payload);
1861 OICFree(serverRequest.requestToken);
1862 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1865 //This function will be called back by CA layer when a request is received
1866 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1868 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1871 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1877 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1881 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1882 #ifdef ROUTING_GATEWAY
1883 bool needRIHandling = false;
1884 bool isEmptyMsg = false;
1886 * Routing manager is going to update either of endpoint or request or both.
1887 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1888 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1889 * destination. It can also remove "RM" coap header option before passing request / response to
1890 * RI as this option will make no sense to either RI or application.
1892 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1893 &needRIHandling, &isEmptyMsg);
1894 if(OC_STACK_OK != ret || !needRIHandling)
1896 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1902 * Put source in sender endpoint so that the next packet from application can be routed to
1903 * proper destination and remove RM header option.
1905 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1906 (uint8_t *) &(requestInfo->info.numOptions),
1907 (CAEndpoint_t *) endPoint);
1909 #ifdef ROUTING_GATEWAY
1913 * In Gateways, the MSGType in route option is used to check if the actual
1914 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
1915 * EMPTY response is sent in the form of POST request which need to be changed
1916 * to a EMPTY response by RM. This translation is done in this part of the code.
1918 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1919 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1920 .info.messageId = requestInfo->info.messageId,
1921 .info.type = CA_MSG_ACKNOWLEDGE};
1922 OCHandleResponse(endPoint, &respInfo);
1928 // Normal handling of the packet
1929 OCHandleRequests(endPoint, requestInfo);
1931 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1934 bool validatePlatformInfo(OCPlatformInfo info)
1937 if (!info.platformID)
1939 OIC_LOG(ERROR, TAG, "No platform ID found.");
1943 if (info.manufacturerName)
1945 size_t lenManufacturerName = strlen(info.manufacturerName);
1947 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1949 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1955 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1959 if (info.manufacturerUrl)
1961 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1963 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1970 //-----------------------------------------------------------------------------
1972 //-----------------------------------------------------------------------------
1974 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1977 !raInfo->username ||
1978 !raInfo->hostname ||
1979 !raInfo->xmpp_domain)
1982 return OC_STACK_INVALID_PARAM;
1984 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1985 gRASetInfo = (result == OC_STACK_OK)? true : false;
1991 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1995 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1998 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2000 if(stackState == OC_STACK_INITIALIZED)
2002 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2003 OCStop() between them are ignored.");
2007 #ifndef ROUTING_GATEWAY
2008 if (OC_GATEWAY == mode)
2010 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2011 return OC_STACK_INVALID_PARAM;
2018 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2019 return OC_STACK_ERROR;
2023 OCStackResult result = OC_STACK_ERROR;
2024 OIC_LOG(INFO, TAG, "Entering OCInit");
2027 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2028 || (mode == OC_GATEWAY)))
2030 OIC_LOG(ERROR, TAG, "Invalid mode");
2031 return OC_STACK_ERROR;
2035 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2037 caglobals.client = true;
2039 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2041 caglobals.server = true;
2044 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2045 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2047 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2049 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2050 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2052 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2055 defaultDeviceHandler = NULL;
2056 defaultDeviceHandlerCallbackParameter = NULL;
2058 result = CAResultToOCResult(CAInitialize());
2059 VERIFY_SUCCESS(result, OC_STACK_OK);
2061 result = CAResultToOCResult(OCSelectNetwork());
2062 VERIFY_SUCCESS(result, OC_STACK_OK);
2064 switch (myStackMode)
2067 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2068 result = CAResultToOCResult(CAStartDiscoveryServer());
2069 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2072 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2073 result = CAResultToOCResult(CAStartListeningServer());
2074 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2076 case OC_CLIENT_SERVER:
2078 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2079 result = CAResultToOCResult(CAStartListeningServer());
2080 if(result == OC_STACK_OK)
2082 result = CAResultToOCResult(CAStartDiscoveryServer());
2086 VERIFY_SUCCESS(result, OC_STACK_OK);
2089 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2092 #ifdef WITH_PRESENCE
2093 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2094 #endif // WITH_PRESENCE
2096 //Update Stack state to initialized
2097 stackState = OC_STACK_INITIALIZED;
2099 // Initialize resource
2100 if(myStackMode != OC_CLIENT)
2102 result = initResources();
2105 // Initialize the SRM Policy Engine
2106 if(result == OC_STACK_OK)
2108 result = SRMInitPolicyEngine();
2109 // TODO after BeachHead delivery: consolidate into single SRMInit()
2111 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2112 RMSetStackMode(mode);
2113 #ifdef ROUTING_GATEWAY
2114 if (OC_GATEWAY == myStackMode)
2116 result = RMInitialize();
2122 if (result == OC_STACK_OK)
2124 result = InitializeKeepAlive(myStackMode);
2129 if(result != OC_STACK_OK)
2131 OIC_LOG(ERROR, TAG, "Stack initialization error");
2132 deleteAllResources();
2134 stackState = OC_STACK_UNINITIALIZED;
2139 OCStackResult OCStop()
2141 OIC_LOG(INFO, TAG, "Entering OCStop");
2143 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2145 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2148 else if (stackState != OC_STACK_INITIALIZED)
2150 OIC_LOG(ERROR, TAG, "Stack not initialized");
2151 return OC_STACK_ERROR;
2154 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2156 #ifdef WITH_PRESENCE
2157 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2158 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2159 presenceResource.presenceTTL = 0;
2160 #endif // WITH_PRESENCE
2162 #ifdef ROUTING_GATEWAY
2163 if (OC_GATEWAY == myStackMode)
2170 TerminateKeepAlive(myStackMode);
2173 // Free memory dynamically allocated for resources
2174 deleteAllResources();
2176 DeletePlatformInfo();
2178 // Remove all observers
2179 DeleteObserverList();
2180 // Remove all the client callbacks
2181 DeleteClientCBList();
2183 // De-init the SRM Policy Engine
2184 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2185 SRMDeInitPolicyEngine();
2188 stackState = OC_STACK_UNINITIALIZED;
2192 OCStackResult OCStartMulticastServer()
2194 if(stackState != OC_STACK_INITIALIZED)
2196 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2197 return OC_STACK_ERROR;
2199 CAResult_t ret = CAStartListeningServer();
2200 if (CA_STATUS_OK != ret)
2202 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2203 return OC_STACK_ERROR;
2208 OCStackResult OCStopMulticastServer()
2210 CAResult_t ret = CAStopListeningServer();
2211 if (CA_STATUS_OK != ret)
2213 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2214 return OC_STACK_ERROR;
2219 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2224 return CA_MSG_CONFIRM;
2229 return CA_MSG_NONCONFIRM;
2234 * A request uri consists of the following components in order:
2237 * CoAP over UDP prefix "coap://"
2238 * CoAP over TCP prefix "coap+tcp://"
2240 * IPv6 address "[1234::5678]"
2241 * IPv4 address "192.168.1.1"
2242 * optional port ":5683"
2243 * resource uri "/oc/core..."
2245 * for PRESENCE requests, extract resource type.
2247 static OCStackResult ParseRequestUri(const char *fullUri,
2248 OCTransportAdapter adapter,
2249 OCTransportFlags flags,
2250 OCDevAddr **devAddr,
2252 char **resourceType)
2254 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2256 OCStackResult result = OC_STACK_OK;
2257 OCDevAddr *da = NULL;
2261 // provide defaults for all returned values
2268 *resourceUri = NULL;
2272 *resourceType = NULL;
2275 // delimit url prefix, if any
2276 const char *start = fullUri;
2277 char *slash2 = strstr(start, "//");
2282 char *slash = strchr(start, '/');
2285 return OC_STACK_INVALID_URI;
2288 // process url scheme
2289 size_t prefixLen = slash2 - fullUri;
2293 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2299 // TODO: this logic should come in with unit tests exercising the various strings
2300 // processs url prefix, if any
2301 size_t urlLen = slash - start;
2305 if (urlLen && devAddr)
2306 { // construct OCDevAddr
2307 if (start[0] == '[')
2309 char *close = strchr(++start, ']');
2310 if (!close || close > slash)
2312 return OC_STACK_INVALID_URI;
2315 if (close[1] == ':')
2322 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2326 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2328 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2332 char *dot = strchr(start, '.');
2333 if (dot && dot < slash)
2335 colon = strchr(start, ':');
2336 end = (colon && colon < slash) ? colon : slash;
2341 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2345 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2347 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2355 if (len >= sizeof(da->addr))
2357 return OC_STACK_INVALID_URI;
2359 // collect port, if any
2360 if (colon && colon < slash)
2362 for (colon++; colon < slash; colon++)
2365 if (c < '0' || c > '9')
2367 return OC_STACK_INVALID_URI;
2369 port = 10 * port + c - '0';
2374 if (len >= sizeof(da->addr))
2376 return OC_STACK_INVALID_URI;
2379 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2382 return OC_STACK_NO_MEMORY;
2384 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2386 da->adapter = adapter;
2388 if (!strncmp(fullUri, "coaps:", 6))
2390 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2395 // process resource uri, if any
2397 { // request uri and query
2398 size_t ulen = strlen(slash); // resource uri length
2399 size_t tlen = 0; // resource type length
2402 static const char strPresence[] = "/oic/ad?rt=";
2403 static const size_t lenPresence = sizeof(strPresence) - 1;
2404 if (!strncmp(slash, strPresence, lenPresence))
2406 type = slash + lenPresence;
2407 tlen = ulen - lenPresence;
2412 *resourceUri = (char *)OICMalloc(ulen + 1);
2415 result = OC_STACK_NO_MEMORY;
2418 strcpy(*resourceUri, slash);
2421 if (type && resourceType)
2423 *resourceType = (char *)OICMalloc(tlen + 1);
2426 result = OC_STACK_NO_MEMORY;
2430 OICStrcpy(*resourceType, (tlen+1), type);
2437 // free all returned values
2444 OICFree(*resourceUri);
2448 OICFree(*resourceType);
2453 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2454 char *resourceUri, char **requestUri)
2456 char uri[CA_MAX_URI_LENGTH];
2458 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2460 *requestUri = OICStrdup(uri);
2463 return OC_STACK_NO_MEMORY;
2470 * Discover or Perform requests on a specified resource
2472 OCStackResult OCDoResource(OCDoHandle *handle,
2474 const char *requestUri,
2475 const OCDevAddr *destination,
2477 OCConnectivityType connectivityType,
2478 OCQualityOfService qos,
2479 OCCallbackData *cbData,
2480 OCHeaderOption *options,
2483 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2485 // Validate input parameters
2486 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2487 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2488 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2490 OCStackResult result = OC_STACK_ERROR;
2491 CAResult_t caResult;
2492 CAToken_t token = NULL;
2493 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2494 ClientCB *clientCB = NULL;
2495 OCDoHandle resHandle = NULL;
2496 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2497 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2499 OCTransportAdapter adapter;
2500 OCTransportFlags flags;
2501 // the request contents are put here
2502 CARequestInfo_t requestInfo = {.method = CA_GET};
2503 // requestUri will be parsed into the following three variables
2504 OCDevAddr *devAddr = NULL;
2505 char *resourceUri = NULL;
2506 char *resourceType = NULL;
2509 * Support original behavior with address on resourceUri argument.
2511 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2512 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2514 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2516 if (result != OC_STACK_OK)
2518 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2525 case OC_REST_OBSERVE:
2526 case OC_REST_OBSERVE_ALL:
2527 case OC_REST_CANCEL_OBSERVE:
2528 requestInfo.method = CA_GET;
2531 requestInfo.method = CA_PUT;
2534 requestInfo.method = CA_POST;
2536 case OC_REST_DELETE:
2537 requestInfo.method = CA_DELETE;
2539 case OC_REST_DISCOVER:
2541 if (destination || devAddr)
2543 requestInfo.isMulticast = false;
2547 tmpDevAddr.adapter = adapter;
2548 tmpDevAddr.flags = flags;
2549 destination = &tmpDevAddr;
2550 requestInfo.isMulticast = true;
2552 // CA_DISCOVER will become GET and isMulticast
2553 requestInfo.method = CA_GET;
2555 #ifdef WITH_PRESENCE
2556 case OC_REST_PRESENCE:
2557 // Replacing method type with GET because "presence"
2558 // is a stack layer only implementation.
2559 requestInfo.method = CA_GET;
2563 result = OC_STACK_INVALID_METHOD;
2567 if (!devAddr && !destination)
2569 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2570 result = OC_STACK_INVALID_PARAM;
2574 /* If not original behavior, use destination argument */
2575 if (destination && !devAddr)
2577 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2580 result = OC_STACK_NO_MEMORY;
2583 *devAddr = *destination;
2586 resHandle = GenerateInvocationHandle();
2589 result = OC_STACK_NO_MEMORY;
2593 caResult = CAGenerateToken(&token, tokenLength);
2594 if (caResult != CA_STATUS_OK)
2596 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2597 result= OC_STACK_ERROR;
2601 // fill in request data
2602 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2603 requestInfo.info.token = token;
2604 requestInfo.info.tokenLength = tokenLength;
2605 requestInfo.info.resourceUri = resourceUri;
2607 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2609 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2610 options, numOptions, OC_OBSERVE_REGISTER);
2611 if (result != OC_STACK_OK)
2615 requestInfo.info.numOptions = numOptions + 1;
2619 requestInfo.info.numOptions = numOptions;
2620 requestInfo.info.options =
2621 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2622 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2623 numOptions * sizeof(CAHeaderOption_t));
2626 CopyDevAddrToEndpoint(devAddr, &endpoint);
2631 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2634 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2637 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2641 requestInfo.info.payload = NULL;
2642 requestInfo.info.payloadSize = 0;
2643 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2646 // prepare for response
2647 #ifdef WITH_PRESENCE
2648 if (method == OC_REST_PRESENCE)
2650 char *presenceUri = NULL;
2651 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2652 if (OC_STACK_OK != result)
2657 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2658 // Presence notification will form a canonical uri to
2659 // look for callbacks into the application.
2660 resourceUri = presenceUri;
2664 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2665 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2666 method, devAddr, resourceUri, resourceType, ttl);
2667 if (OC_STACK_OK != result)
2672 devAddr = NULL; // Client CB list entry now owns it
2673 resourceUri = NULL; // Client CB list entry now owns it
2674 resourceType = NULL; // Client CB list entry now owns it
2677 result = OCSendRequest(&endpoint, &requestInfo);
2678 if (OC_STACK_OK != result)
2685 *handle = resHandle;
2689 if (result != OC_STACK_OK)
2691 OIC_LOG(ERROR, TAG, "OCDoResource error");
2692 FindAndDeleteClientCB(clientCB);
2693 CADestroyToken(token);
2701 // This is the owner of the payload object, so we free it
2702 OCPayloadDestroy(payload);
2703 OICFree(requestInfo.info.payload);
2705 OICFree(resourceUri);
2706 OICFree(resourceType);
2707 OICFree(requestInfo.info.options);
2711 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2715 * This ftn is implemented one of two ways in the case of observation:
2717 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2718 * Remove the callback associated on client side.
2719 * When the next notification comes in from server,
2720 * reply with RESET message to server.
2721 * Keep in mind that the server will react to RESET only
2722 * if the last notification was sent as CON
2724 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2725 * and it is associated with an observe request
2726 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2727 * Send CON Observe request to server with
2728 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2729 * Remove the callback associated on client side.
2731 OCStackResult ret = OC_STACK_OK;
2732 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2733 CARequestInfo_t requestInfo = {.method = CA_GET};
2737 return OC_STACK_INVALID_PARAM;
2740 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2743 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2744 return OC_STACK_ERROR;
2747 switch (clientCB->method)
2749 case OC_REST_OBSERVE:
2750 case OC_REST_OBSERVE_ALL:
2752 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2754 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2756 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2758 FindAndDeleteClientCB(clientCB);
2762 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2764 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2765 requestInfo.info.token = clientCB->token;
2766 requestInfo.info.tokenLength = clientCB->tokenLength;
2768 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2769 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2771 return OC_STACK_ERROR;
2773 requestInfo.info.numOptions = numOptions + 1;
2774 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2777 ret = OCSendRequest(&endpoint, &requestInfo);
2779 if (requestInfo.info.options)
2781 OICFree (requestInfo.info.options);
2783 if (requestInfo.info.resourceUri)
2785 OICFree (requestInfo.info.resourceUri);
2790 case OC_REST_DISCOVER:
2791 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2792 clientCB->requestUri);
2793 FindAndDeleteClientCB(clientCB);
2796 #ifdef WITH_PRESENCE
2797 case OC_REST_PRESENCE:
2798 FindAndDeleteClientCB(clientCB);
2803 ret = OC_STACK_INVALID_METHOD;
2811 * @brief Register Persistent storage callback.
2812 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2814 * OC_STACK_OK - No errors; Success
2815 * OC_STACK_INVALID_PARAM - Invalid parameter
2817 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2819 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2820 if(!persistentStorageHandler)
2822 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2823 return OC_STACK_INVALID_PARAM;
2827 if( !persistentStorageHandler->open ||
2828 !persistentStorageHandler->close ||
2829 !persistentStorageHandler->read ||
2830 !persistentStorageHandler->unlink ||
2831 !persistentStorageHandler->write)
2833 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2834 return OC_STACK_INVALID_PARAM;
2837 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2840 #ifdef WITH_PRESENCE
2842 OCStackResult OCProcessPresence()
2844 OCStackResult result = OC_STACK_OK;
2846 // the following line floods the log with messages that are irrelevant
2847 // to most purposes. Uncomment as needed.
2848 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2849 ClientCB* cbNode = NULL;
2850 OCClientResponse clientResponse;
2851 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2853 LL_FOREACH(cbList, cbNode)
2855 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2860 uint32_t now = GetTicks(0);
2861 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2862 cbNode->presence->TTLlevel);
2863 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2865 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2870 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2872 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2873 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2875 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2877 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2879 clientResponse.sequenceNumber = 0;
2880 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2881 clientResponse.devAddr = *cbNode->devAddr;
2882 FixUpClientResponse(&clientResponse);
2883 clientResponse.payload = NULL;
2885 // Increment the TTLLevel (going to a next state), so we don't keep
2886 // sending presence notification to client.
2887 cbNode->presence->TTLlevel++;
2888 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2889 cbNode->presence->TTLlevel);
2891 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2892 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2894 FindAndDeleteClientCB(cbNode);
2898 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2903 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2904 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2905 CARequestInfo_t requestInfo = {.method = CA_GET};
2907 OIC_LOG(DEBUG, TAG, "time to test server presence");
2909 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2911 requestData.type = CA_MSG_NONCONFIRM;
2912 requestData.token = cbNode->token;
2913 requestData.tokenLength = cbNode->tokenLength;
2914 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2915 requestInfo.method = CA_GET;
2916 requestInfo.info = requestData;
2918 result = OCSendRequest(&endpoint, &requestInfo);
2919 if (OC_STACK_OK != result)
2924 cbNode->presence->TTLlevel++;
2925 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2928 if (result != OC_STACK_OK)
2930 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2935 #endif // WITH_PRESENCE
2937 OCStackResult OCProcess()
2939 #ifdef WITH_PRESENCE
2940 OCProcessPresence();
2942 CAHandleRequestResponse();
2944 #ifdef ROUTING_GATEWAY
2954 #ifdef WITH_PRESENCE
2955 OCStackResult OCStartPresence(const uint32_t ttl)
2957 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2958 OCChangeResourceProperty(
2959 &(((OCResource *)presenceResource.handle)->resourceProperties),
2962 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2964 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2965 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2969 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2970 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2974 presenceResource.presenceTTL = ttl;
2976 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2978 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2980 presenceState = OC_PRESENCE_INITIALIZED;
2982 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2984 CAToken_t caToken = NULL;
2985 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2986 if (caResult != CA_STATUS_OK)
2988 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2989 CADestroyToken(caToken);
2990 return OC_STACK_ERROR;
2993 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2994 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2995 CADestroyToken(caToken);
2998 // Each time OCStartPresence is called
2999 // a different random 32-bit integer number is used
3000 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3002 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3003 OC_PRESENCE_TRIGGER_CREATE);
3006 OCStackResult OCStopPresence()
3008 OCStackResult result = OC_STACK_ERROR;
3010 if(presenceResource.handle)
3012 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3014 // make resource inactive
3015 result = OCChangeResourceProperty(
3016 &(((OCResource *) presenceResource.handle)->resourceProperties),
3020 if(result != OC_STACK_OK)
3023 "Changing the presence resource properties to ACTIVE not successful");
3027 return SendStopNotification();
3031 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3032 void* callbackParameter)
3034 defaultDeviceHandler = entityHandler;
3035 defaultDeviceHandlerCallbackParameter = callbackParameter;
3040 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3042 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3044 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3046 if (validatePlatformInfo(platformInfo))
3048 return SavePlatformInfo(platformInfo);
3052 return OC_STACK_INVALID_PARAM;
3057 return OC_STACK_ERROR;
3061 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3063 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3065 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3067 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3068 return OC_STACK_INVALID_PARAM;
3071 if (deviceInfo.types)
3073 OCStringLL *type = deviceInfo.types;
3074 OCResource *resource = findResource((OCResource *) deviceResource);
3077 return OC_STACK_INVALID_PARAM;
3082 OCBindResourceTypeToResource(deviceResource, type->value);
3086 return SaveDeviceInfo(deviceInfo);
3089 OCStackResult OCCreateResource(OCResourceHandle *handle,
3090 const char *resourceTypeName,
3091 const char *resourceInterfaceName,
3092 const char *uri, OCEntityHandler entityHandler,
3093 void* callbackParam,
3094 uint8_t resourceProperties)
3097 OCResource *pointer = NULL;
3098 OCStackResult result = OC_STACK_ERROR;
3100 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3102 if(myStackMode == OC_CLIENT)
3104 return OC_STACK_INVALID_PARAM;
3106 // Validate parameters
3107 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3109 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3110 return OC_STACK_INVALID_URI;
3112 // Is it presented during resource discovery?
3113 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3115 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3116 return OC_STACK_INVALID_PARAM;
3119 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3121 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3124 // Make sure resourceProperties bitmask has allowed properties specified
3125 if (resourceProperties
3126 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3127 OC_EXPLICIT_DISCOVERABLE))
3129 OIC_LOG(ERROR, TAG, "Invalid property");
3130 return OC_STACK_INVALID_PARAM;
3133 // If the headResource is NULL, then no resources have been created...
3134 pointer = headResource;
3137 // At least one resources is in the resource list, so we need to search for
3138 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3141 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3143 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3144 return OC_STACK_INVALID_PARAM;
3146 pointer = pointer->next;
3149 // Create the pointer and insert it into the resource list
3150 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3153 result = OC_STACK_NO_MEMORY;
3156 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3158 insertResource(pointer);
3161 pointer->uri = OICStrdup(uri);
3164 result = OC_STACK_NO_MEMORY;
3168 // Set properties. Set OC_ACTIVE
3169 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3172 // Add the resourcetype to the resource
3173 result = BindResourceTypeToResource(pointer, resourceTypeName);
3174 if (result != OC_STACK_OK)
3176 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3180 // Add the resourceinterface to the resource
3181 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3182 if (result != OC_STACK_OK)
3184 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3188 // If an entity handler has been passed, attach it to the newly created
3189 // resource. Otherwise, set the default entity handler.
3192 pointer->entityHandler = entityHandler;
3193 pointer->entityHandlerCallbackParam = callbackParam;
3197 pointer->entityHandler = defaultResourceEHandler;
3198 pointer->entityHandlerCallbackParam = NULL;
3201 // Initialize a pointer indicating child resources in case of collection
3202 pointer->rsrcChildResourcesHead = NULL;
3205 result = OC_STACK_OK;
3207 #ifdef WITH_PRESENCE
3208 if (presenceResource.handle)
3210 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3211 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3215 if (result != OC_STACK_OK)
3217 // Deep delete of resource and other dynamic elements that it contains
3218 deleteResource(pointer);
3223 OCStackResult OCBindResource(
3224 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3226 OCResource *resource = NULL;
3227 OCChildResource *tempChildResource = NULL;
3228 OCChildResource *newChildResource = NULL;
3230 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3232 // Validate parameters
3233 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3234 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3235 // Container cannot contain itself
3236 if (collectionHandle == resourceHandle)
3238 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3239 return OC_STACK_INVALID_PARAM;
3242 // Use the handle to find the resource in the resource linked list
3243 resource = findResource((OCResource *) collectionHandle);
3246 OIC_LOG(ERROR, TAG, "Collection handle not found");
3247 return OC_STACK_INVALID_PARAM;
3250 // Look for an open slot to add add the child resource.
3251 // If found, add it and return success
3253 tempChildResource = resource->rsrcChildResourcesHead;
3255 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3257 // TODO: what if one of child resource was deregistered without unbinding?
3258 tempChildResource = tempChildResource->next;
3261 // Do memory allocation for child resource
3262 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3263 if(!newChildResource)
3265 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3266 return OC_STACK_ERROR;
3269 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3270 newChildResource->next = NULL;
3272 if(!resource->rsrcChildResourcesHead)
3274 resource->rsrcChildResourcesHead = newChildResource;
3277 tempChildResource->next = newChildResource;
3280 OIC_LOG(INFO, TAG, "resource bound");
3282 #ifdef WITH_PRESENCE
3283 if (presenceResource.handle)
3285 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3286 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3287 OC_PRESENCE_TRIGGER_CHANGE);
3294 OCStackResult OCUnBindResource(
3295 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3297 OCResource *resource = NULL;
3298 OCChildResource *tempChildResource = NULL;
3299 OCChildResource *tempLastChildResource = NULL;
3301 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3303 // Validate parameters
3304 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3305 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3306 // Container cannot contain itself
3307 if (collectionHandle == resourceHandle)
3309 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3310 return OC_STACK_INVALID_PARAM;
3313 // Use the handle to find the resource in the resource linked list
3314 resource = findResource((OCResource *) collectionHandle);
3317 OIC_LOG(ERROR, TAG, "Collection handle not found");
3318 return OC_STACK_INVALID_PARAM;
3321 // Look for an open slot to add add the child resource.
3322 // If found, add it and return success
3323 if(!resource->rsrcChildResourcesHead)
3325 OIC_LOG(INFO, TAG, "resource not found in collection");
3327 // Unable to add resourceHandle, so return error
3328 return OC_STACK_ERROR;
3332 tempChildResource = resource->rsrcChildResourcesHead;
3334 while (tempChildResource)
3336 if(tempChildResource->rsrcResource == resourceHandle)
3338 // if resource going to be unbinded is the head one.
3339 if( tempChildResource == resource->rsrcChildResourcesHead )
3341 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3342 OICFree(resource->rsrcChildResourcesHead);
3343 resource->rsrcChildResourcesHead = temp;
3348 OCChildResource *temp = tempChildResource->next;
3349 OICFree(tempChildResource);
3350 tempLastChildResource->next = temp;
3354 OIC_LOG(INFO, TAG, "resource unbound");
3356 // Send notification when resource is unbounded successfully.
3357 #ifdef WITH_PRESENCE
3358 if (presenceResource.handle)
3360 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3361 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3362 OC_PRESENCE_TRIGGER_CHANGE);
3365 tempChildResource = NULL;
3366 tempLastChildResource = NULL;
3372 tempLastChildResource = tempChildResource;
3373 tempChildResource = tempChildResource->next;
3376 OIC_LOG(INFO, TAG, "resource not found in collection");
3378 tempChildResource = NULL;
3379 tempLastChildResource = NULL;
3381 // Unable to add resourceHandle, so return error
3382 return OC_STACK_ERROR;
3385 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3387 if (!resourceItemName)
3391 // Per RFC 6690 only registered values must follow the first rule below.
3392 // At this point in time the only values registered begin with "core", and
3393 // all other values are specified as opaque strings where multiple values
3394 // are separated by a space.
3395 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3397 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3399 if (resourceItemName[index] != '.'
3400 && resourceItemName[index] != '-'
3401 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3402 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3410 for (size_t index = 0; resourceItemName[index]; ++index)
3412 if (resourceItemName[index] == ' '
3413 || resourceItemName[index] == '\t'
3414 || resourceItemName[index] == '\r'
3415 || resourceItemName[index] == '\n')
3425 OCStackResult BindResourceTypeToResource(OCResource* resource,
3426 const char *resourceTypeName)
3428 OCResourceType *pointer = NULL;
3430 OCStackResult result = OC_STACK_ERROR;
3432 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3434 if (!ValidateResourceTypeInterface(resourceTypeName))
3436 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3437 return OC_STACK_INVALID_PARAM;
3440 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3443 result = OC_STACK_NO_MEMORY;
3447 str = OICStrdup(resourceTypeName);
3450 result = OC_STACK_NO_MEMORY;
3453 pointer->resourcetypename = str;
3454 pointer->next = NULL;
3456 insertResourceType(resource, pointer);
3457 result = OC_STACK_OK;
3460 if (result != OC_STACK_OK)
3469 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3470 const char *resourceInterfaceName)
3472 OCResourceInterface *pointer = NULL;
3474 OCStackResult result = OC_STACK_ERROR;
3476 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3478 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3480 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3481 return OC_STACK_INVALID_PARAM;
3484 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3486 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3489 result = OC_STACK_NO_MEMORY;
3493 str = OICStrdup(resourceInterfaceName);
3496 result = OC_STACK_NO_MEMORY;
3499 pointer->name = str;
3501 // Bind the resourceinterface to the resource
3502 insertResourceInterface(resource, pointer);
3504 result = OC_STACK_OK;
3507 if (result != OC_STACK_OK)
3516 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3517 const char *resourceTypeName)
3520 OCStackResult result = OC_STACK_ERROR;
3521 OCResource *resource = NULL;
3523 resource = findResource((OCResource *) handle);
3526 OIC_LOG(ERROR, TAG, "Resource not found");
3527 return OC_STACK_ERROR;
3530 result = BindResourceTypeToResource(resource, resourceTypeName);
3532 #ifdef WITH_PRESENCE
3533 if(presenceResource.handle)
3535 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3536 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3543 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3544 const char *resourceInterfaceName)
3547 OCStackResult result = OC_STACK_ERROR;
3548 OCResource *resource = NULL;
3550 resource = findResource((OCResource *) handle);
3553 OIC_LOG(ERROR, TAG, "Resource not found");
3554 return OC_STACK_ERROR;
3557 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3559 #ifdef WITH_PRESENCE
3560 if (presenceResource.handle)
3562 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3563 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3570 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3572 OCResource *pointer = headResource;
3574 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3578 *numResources = *numResources + 1;
3579 pointer = pointer->next;
3584 OCResourceHandle OCGetResourceHandle(uint8_t index)
3586 OCResource *pointer = headResource;
3588 for( uint8_t i = 0; i < index && pointer; ++i)
3590 pointer = pointer->next;
3592 return (OCResourceHandle) pointer;
3595 OCStackResult OCDeleteResource(OCResourceHandle handle)
3599 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3600 return OC_STACK_INVALID_PARAM;
3603 OCResource *resource = findResource((OCResource *) handle);
3604 if (resource == NULL)
3606 OIC_LOG(ERROR, TAG, "Resource not found");
3607 return OC_STACK_NO_RESOURCE;
3610 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3612 OIC_LOG(ERROR, TAG, "Error deleting resource");
3613 return OC_STACK_ERROR;
3619 const char *OCGetResourceUri(OCResourceHandle handle)
3621 OCResource *resource = NULL;
3623 resource = findResource((OCResource *) handle);
3626 return resource->uri;
3628 return (const char *) NULL;
3631 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3633 OCResource *resource = NULL;
3635 resource = findResource((OCResource *) handle);
3638 return resource->resourceProperties;
3640 return (OCResourceProperty)-1;
3643 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3644 uint8_t *numResourceTypes)
3646 OCResource *resource = NULL;
3647 OCResourceType *pointer = NULL;
3649 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3650 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3652 *numResourceTypes = 0;
3654 resource = findResource((OCResource *) handle);
3657 pointer = resource->rsrcType;
3660 *numResourceTypes = *numResourceTypes + 1;
3661 pointer = pointer->next;
3667 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3669 OCResourceType *resourceType = NULL;
3671 resourceType = findResourceTypeAtIndex(handle, index);
3674 return resourceType->resourcetypename;
3676 return (const char *) NULL;
3679 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3680 uint8_t *numResourceInterfaces)
3682 OCResourceInterface *pointer = NULL;
3683 OCResource *resource = NULL;
3685 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3686 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3688 *numResourceInterfaces = 0;
3689 resource = findResource((OCResource *) handle);
3692 pointer = resource->rsrcInterface;
3695 *numResourceInterfaces = *numResourceInterfaces + 1;
3696 pointer = pointer->next;
3702 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3704 OCResourceInterface *resourceInterface = NULL;
3706 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3707 if (resourceInterface)
3709 return resourceInterface->name;
3711 return (const char *) NULL;
3714 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3717 OCResource *resource = NULL;
3718 OCChildResource *tempChildResource = NULL;
3721 resource = findResource((OCResource *) collectionHandle);
3727 tempChildResource = resource->rsrcChildResourcesHead;
3729 while(tempChildResource)
3733 return tempChildResource->rsrcResource;
3736 tempChildResource = tempChildResource->next;
3739 // In this case, the number of resource handles in the collection exceeds the index
3740 tempChildResource = NULL;
3744 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3745 OCEntityHandler entityHandler,
3746 void* callbackParam)
3748 OCResource *resource = NULL;
3750 // Validate parameters
3751 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3753 // Use the handle to find the resource in the resource linked list
3754 resource = findResource((OCResource *)handle);
3757 OIC_LOG(ERROR, TAG, "Resource not found");
3758 return OC_STACK_ERROR;
3762 resource->entityHandler = entityHandler;
3763 resource->entityHandlerCallbackParam = callbackParam;
3765 #ifdef WITH_PRESENCE
3766 if (presenceResource.handle)
3768 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3769 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3776 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3778 OCResource *resource = NULL;
3780 resource = findResource((OCResource *)handle);
3783 OIC_LOG(ERROR, TAG, "Resource not found");
3788 return resource->entityHandler;
3791 void incrementSequenceNumber(OCResource * resPtr)
3793 // Increment the sequence number
3794 resPtr->sequenceNum += 1;
3795 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3797 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3802 #ifdef WITH_PRESENCE
3803 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3804 OCPresenceTrigger trigger)
3806 OCResource *resPtr = NULL;
3807 OCStackResult result = OC_STACK_ERROR;
3808 OCMethod method = OC_REST_PRESENCE;
3809 uint32_t maxAge = 0;
3810 resPtr = findResource((OCResource *) presenceResource.handle);
3813 return OC_STACK_NO_RESOURCE;
3816 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3818 maxAge = presenceResource.presenceTTL;
3820 result = SendAllObserverNotification(method, resPtr, maxAge,
3821 trigger, resourceType, OC_LOW_QOS);
3827 OCStackResult SendStopNotification()
3829 OCResource *resPtr = NULL;
3830 OCStackResult result = OC_STACK_ERROR;
3831 OCMethod method = OC_REST_PRESENCE;
3832 resPtr = findResource((OCResource *) presenceResource.handle);
3835 return OC_STACK_NO_RESOURCE;
3838 // maxAge is 0. ResourceType is NULL.
3839 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3845 #endif // WITH_PRESENCE
3846 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3848 OCResource *resPtr = NULL;
3849 OCStackResult result = OC_STACK_ERROR;
3850 OCMethod method = OC_REST_NOMETHOD;
3851 uint32_t maxAge = 0;
3853 OIC_LOG(INFO, TAG, "Notifying all observers");
3854 #ifdef WITH_PRESENCE
3855 if(handle == presenceResource.handle)
3859 #endif // WITH_PRESENCE
3860 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3862 // Verify that the resource exists
3863 resPtr = findResource ((OCResource *) handle);
3866 return OC_STACK_NO_RESOURCE;
3870 //only increment in the case of regular observing (not presence)
3871 incrementSequenceNumber(resPtr);
3872 method = OC_REST_OBSERVE;
3873 maxAge = MAX_OBSERVE_AGE;
3874 #ifdef WITH_PRESENCE
3875 result = SendAllObserverNotification (method, resPtr, maxAge,
3876 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3878 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3885 OCNotifyListOfObservers (OCResourceHandle handle,
3886 OCObservationId *obsIdList,
3887 uint8_t numberOfIds,
3888 const OCRepPayload *payload,
3889 OCQualityOfService qos)
3891 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3893 OCResource *resPtr = NULL;
3894 //TODO: we should allow the server to define this
3895 uint32_t maxAge = MAX_OBSERVE_AGE;
3897 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3898 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3899 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3901 resPtr = findResource ((OCResource *) handle);
3902 if (NULL == resPtr || myStackMode == OC_CLIENT)
3904 return OC_STACK_NO_RESOURCE;
3908 incrementSequenceNumber(resPtr);
3910 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3911 payload, maxAge, qos));
3914 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3916 OCStackResult result = OC_STACK_ERROR;
3917 OCServerRequest *serverRequest = NULL;
3919 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3921 // Validate input parameters
3922 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3923 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3926 // Get pointer to request info
3927 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3930 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3931 result = serverRequest->ehResponseHandler(ehResponse);
3937 //#ifdef DIRECT_PAIRING
3938 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3940 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3941 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3943 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3947 return (const OCDPDev_t*)DPGetDiscoveredDevices();
3950 const OCDPDev_t* OCGetDirectPairedDevices()
3952 return (const OCDPDev_t*)DPGetPairedDevices();
3955 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3956 OCDirectPairingCB resultCallback)
3958 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3959 if(NULL == peer || NULL == pinNumber)
3961 OIC_LOG(ERROR, TAG, "Invalid parameters");
3962 return OC_STACK_INVALID_PARAM;
3964 if (NULL == resultCallback)
3966 OIC_LOG(ERROR, TAG, "Invalid callback");
3967 return OC_STACK_INVALID_CALLBACK;
3970 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3971 pinNumber, (OCDirectPairingResultCB)resultCallback);
3973 //#endif // DIRECT_PAIRING
3975 //-----------------------------------------------------------------------------
3976 // Private internal function definitions
3977 //-----------------------------------------------------------------------------
3978 static OCDoHandle GenerateInvocationHandle()
3980 OCDoHandle handle = NULL;
3981 // Generate token here, it will be deleted when the transaction is deleted
3982 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3985 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3991 #ifdef WITH_PRESENCE
3992 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3993 OCResourceProperty resourceProperties, uint8_t enable)
3997 return OC_STACK_INVALID_PARAM;
3999 if (resourceProperties
4000 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4002 OIC_LOG(ERROR, TAG, "Invalid property");
4003 return OC_STACK_INVALID_PARAM;
4007 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4011 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4017 OCStackResult initResources()
4019 OCStackResult result = OC_STACK_OK;
4021 headResource = NULL;
4022 tailResource = NULL;
4023 // Init Virtual Resources
4024 #ifdef WITH_PRESENCE
4025 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4027 result = OCCreateResource(&presenceResource.handle,
4028 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4030 OC_RSRVD_PRESENCE_URI,
4034 //make resource inactive
4035 result = OCChangeResourceProperty(
4036 &(((OCResource *) presenceResource.handle)->resourceProperties),
4039 #ifndef WITH_ARDUINO
4040 if (result == OC_STACK_OK)
4042 result = SRMInitSecureResources();
4046 if(result == OC_STACK_OK)
4048 result = OCCreateResource(&deviceResource,
4049 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4050 OC_RSRVD_INTERFACE_DEFAULT,
4051 OC_RSRVD_DEVICE_URI,
4055 if(result == OC_STACK_OK)
4057 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4058 OC_RSRVD_INTERFACE_READ);
4062 if(result == OC_STACK_OK)
4064 result = OCCreateResource(&platformResource,
4065 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4066 OC_RSRVD_INTERFACE_DEFAULT,
4067 OC_RSRVD_PLATFORM_URI,
4071 if(result == OC_STACK_OK)
4073 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4074 OC_RSRVD_INTERFACE_READ);
4081 void insertResource(OCResource *resource)
4085 headResource = resource;
4086 tailResource = resource;
4090 tailResource->next = resource;
4091 tailResource = resource;
4093 resource->next = NULL;
4096 OCResource *findResource(OCResource *resource)
4098 OCResource *pointer = headResource;
4102 if (pointer == resource)
4106 pointer = pointer->next;
4111 void deleteAllResources()
4113 OCResource *pointer = headResource;
4114 OCResource *temp = NULL;
4118 temp = pointer->next;
4119 #ifdef WITH_PRESENCE
4120 if (pointer != (OCResource *) presenceResource.handle)
4122 #endif // WITH_PRESENCE
4123 deleteResource(pointer);
4124 #ifdef WITH_PRESENCE
4126 #endif // WITH_PRESENCE
4129 memset(&platformResource, 0, sizeof(platformResource));
4130 memset(&deviceResource, 0, sizeof(deviceResource));
4132 SRMDeInitSecureResources();
4134 #ifdef WITH_PRESENCE
4135 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4136 // presence notification attributed to their deletion to be processed.
4137 deleteResource((OCResource *) presenceResource.handle);
4138 memset(&presenceResource, 0, sizeof(presenceResource));
4139 #endif // WITH_PRESENCE
4142 OCStackResult deleteResource(OCResource *resource)
4144 OCResource *prev = NULL;
4145 OCResource *temp = NULL;
4148 OIC_LOG(DEBUG,TAG,"resource is NULL");
4149 return OC_STACK_INVALID_PARAM;
4152 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4154 temp = headResource;
4157 if (temp == resource)
4159 // Invalidate all Resource Properties.
4160 resource->resourceProperties = (OCResourceProperty) 0;
4161 #ifdef WITH_PRESENCE
4162 if(resource != (OCResource *) presenceResource.handle)
4164 #endif // WITH_PRESENCE
4165 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4166 #ifdef WITH_PRESENCE
4169 if(presenceResource.handle)
4171 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4172 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4175 // Only resource in list.
4176 if (temp == headResource && temp == tailResource)
4178 headResource = NULL;
4179 tailResource = NULL;
4182 else if (temp == headResource)
4184 headResource = temp->next;
4187 else if (temp == tailResource)
4189 tailResource = prev;
4190 tailResource->next = NULL;
4194 prev->next = temp->next;
4197 deleteResourceElements(temp);
4208 return OC_STACK_ERROR;
4211 void deleteResourceElements(OCResource *resource)
4218 OICFree(resource->uri);
4219 deleteResourceType(resource->rsrcType);
4220 deleteResourceInterface(resource->rsrcInterface);
4223 void deleteResourceType(OCResourceType *resourceType)
4225 OCResourceType *pointer = resourceType;
4226 OCResourceType *next = NULL;
4230 next = pointer->next;
4231 OICFree(pointer->resourcetypename);
4237 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4239 OCResourceInterface *pointer = resourceInterface;
4240 OCResourceInterface *next = NULL;
4244 next = pointer->next;
4245 OICFree(pointer->name);
4251 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4253 OCResourceType *pointer = NULL;
4254 OCResourceType *previous = NULL;
4255 if (!resource || !resourceType)
4259 // resource type list is empty.
4260 else if (!resource->rsrcType)
4262 resource->rsrcType = resourceType;
4266 pointer = resource->rsrcType;
4270 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4272 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4273 OICFree(resourceType->resourcetypename);
4274 OICFree(resourceType);
4278 pointer = pointer->next;
4283 previous->next = resourceType;
4286 resourceType->next = NULL;
4288 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4291 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4293 OCResource *resource = NULL;
4294 OCResourceType *pointer = NULL;
4296 // Find the specified resource
4297 resource = findResource((OCResource *) handle);
4303 // Make sure a resource has a resourcetype
4304 if (!resource->rsrcType)
4309 // Iterate through the list
4310 pointer = resource->rsrcType;
4311 for(uint8_t i = 0; i< index && pointer; ++i)
4313 pointer = pointer->next;
4318 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4320 if(resourceTypeList && resourceTypeName)
4322 OCResourceType * rtPointer = resourceTypeList;
4323 while(resourceTypeName && rtPointer)
4325 if(rtPointer->resourcetypename &&
4326 strcmp(resourceTypeName, (const char *)
4327 (rtPointer->resourcetypename)) == 0)
4331 rtPointer = rtPointer->next;
4339 * Insert a new interface into interface linked list only if not already present.
4340 * If alredy present, 2nd arg is free'd.
4341 * Default interface will always be first if present.
4343 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4345 OCResourceInterface *pointer = NULL;
4346 OCResourceInterface *previous = NULL;
4348 newInterface->next = NULL;
4350 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4352 if (!*firstInterface)
4354 // If first interface is not oic.if.baseline, by default add it as first interface type.
4355 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4357 *firstInterface = newInterface;
4361 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4362 if (result != OC_STACK_OK)
4364 OICFree(newInterface->name);
4365 OICFree(newInterface);
4368 if (*firstInterface)
4370 (*firstInterface)->next = newInterface;
4374 // If once add oic.if.baseline, later too below code take care of freeing memory.
4375 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4377 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4379 OICFree(newInterface->name);
4380 OICFree(newInterface);
4383 // This code will not hit anymore, keeping
4386 newInterface->next = *firstInterface;
4387 *firstInterface = newInterface;
4392 pointer = *firstInterface;
4395 if (strcmp(newInterface->name, pointer->name) == 0)
4397 OICFree(newInterface->name);
4398 OICFree(newInterface);
4402 pointer = pointer->next;
4407 previous->next = newInterface;
4412 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4415 OCResource *resource = NULL;
4416 OCResourceInterface *pointer = NULL;
4418 // Find the specified resource
4419 resource = findResource((OCResource *) handle);
4425 // Make sure a resource has a resourceinterface
4426 if (!resource->rsrcInterface)
4431 // Iterate through the list
4432 pointer = resource->rsrcInterface;
4434 for (uint8_t i = 0; i < index && pointer; ++i)
4436 pointer = pointer->next;
4442 * This function splits the uri using the '?' delimiter.
4443 * "uriWithoutQuery" is the block of characters between the beginning
4444 * till the delimiter or '\0' which ever comes first.
4445 * "query" is whatever is to the right of the delimiter if present.
4446 * No delimiter sets the query to NULL.
4447 * If either are present, they will be malloc'ed into the params 2, 3.
4448 * The first param, *uri is left untouched.
4450 * NOTE: This function does not account for whitespace at the end of the uri NOR
4451 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4452 * part of the query.
4454 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4458 return OC_STACK_INVALID_URI;
4460 if(!query || !uriWithoutQuery)
4462 return OC_STACK_INVALID_PARAM;
4466 *uriWithoutQuery = NULL;
4468 size_t uriWithoutQueryLen = 0;
4469 size_t queryLen = 0;
4470 size_t uriLen = strlen(uri);
4472 char *pointerToDelimiter = strstr(uri, "?");
4474 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4475 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4477 if (uriWithoutQueryLen)
4479 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4480 if (!*uriWithoutQuery)
4484 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4488 *query = (char *) OICCalloc(queryLen + 1, 1);
4491 OICFree(*uriWithoutQuery);
4492 *uriWithoutQuery = NULL;
4495 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4501 return OC_STACK_NO_MEMORY;
4504 static const OicUuid_t* OCGetServerInstanceID(void)
4506 static bool generated = false;
4507 static OicUuid_t sid;
4513 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4515 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4522 const char* OCGetServerInstanceIDString(void)
4524 static bool generated = false;
4525 static char sidStr[UUID_STRING_SIZE];
4532 const OicUuid_t *sid = OCGetServerInstanceID();
4533 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4535 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4543 CAResult_t OCSelectNetwork()
4545 CAResult_t retResult = CA_STATUS_FAILED;
4546 CAResult_t caResult = CA_STATUS_OK;
4548 CATransportAdapter_t connTypes[] = {
4550 CA_ADAPTER_RFCOMM_BTEDR,
4551 CA_ADAPTER_GATT_BTLE,
4554 ,CA_ADAPTER_REMOTE_ACCESS
4561 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4563 for(int i = 0; i<numConnTypes; i++)
4565 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4566 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4568 caResult = CASelectNetwork(connTypes[i]);
4569 if(caResult == CA_STATUS_OK)
4571 retResult = CA_STATUS_OK;
4576 if(retResult != CA_STATUS_OK)
4578 return caResult; // Returns error of appropriate transport that failed fatally.
4584 OCStackResult CAResultToOCResult(CAResult_t caResult)
4590 case CA_STATUS_INVALID_PARAM:
4591 return OC_STACK_INVALID_PARAM;
4592 case CA_ADAPTER_NOT_ENABLED:
4593 return OC_STACK_ADAPTER_NOT_ENABLED;
4594 case CA_SERVER_STARTED_ALREADY:
4596 case CA_SERVER_NOT_STARTED:
4597 return OC_STACK_ERROR;
4598 case CA_DESTINATION_NOT_REACHABLE:
4599 return OC_STACK_COMM_ERROR;
4600 case CA_SOCKET_OPERATION_FAILED:
4601 return OC_STACK_COMM_ERROR;
4602 case CA_SEND_FAILED:
4603 return OC_STACK_COMM_ERROR;
4604 case CA_RECEIVE_FAILED:
4605 return OC_STACK_COMM_ERROR;
4606 case CA_MEMORY_ALLOC_FAILED:
4607 return OC_STACK_NO_MEMORY;
4608 case CA_REQUEST_TIMEOUT:
4609 return OC_STACK_TIMEOUT;
4610 case CA_DESTINATION_DISCONNECTED:
4611 return OC_STACK_COMM_ERROR;
4612 case CA_STATUS_FAILED:
4613 return OC_STACK_ERROR;
4614 case CA_NOT_SUPPORTED:
4615 return OC_STACK_NOTIMPL;
4617 return OC_STACK_ERROR;
4621 bool OCResultToSuccess(OCStackResult ocResult)
4626 case OC_STACK_RESOURCE_CREATED:
4627 case OC_STACK_RESOURCE_DELETED:
4628 case OC_STACK_CONTINUE: