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;
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 //#ifdef DIRECT_PAIRING
138 OCDirectPairingCB gDirectpairingCallback = NULL;
141 //-----------------------------------------------------------------------------
143 //-----------------------------------------------------------------------------
144 #define TAG "OIC_RI_STACK"
145 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
146 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
147 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
148 TAG, #arg " is NULL"); return (retVal); } }
149 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
150 TAG, #arg " is NULL"); return; } }
151 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
154 //TODO: we should allow the server to define this
155 #define MAX_OBSERVE_AGE (0x2FFFFUL)
157 #define MILLISECONDS_PER_SECOND (1000)
159 //-----------------------------------------------------------------------------
160 // Private internal function prototypes
161 //-----------------------------------------------------------------------------
164 * Generate handle of OCDoResource invocation for callback management.
166 * @return Generated OCDoResource handle.
168 static OCDoHandle GenerateInvocationHandle();
171 * Initialize resource data structures, variables, etc.
173 * @return ::OC_STACK_OK on success, some other value upon failure.
175 static OCStackResult initResources();
178 * Add a resource to the end of the linked list of resources.
180 * @param resource Resource to be added
182 static void insertResource(OCResource *resource);
185 * Find a resource in the linked list of resources.
187 * @param resource Resource to be found.
188 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
191 static OCResource *findResource(OCResource *resource);
194 * Insert a resource type into a resource's resource type linked list.
195 * If resource type already exists, it will not be inserted and the
196 * resourceType will be free'd.
197 * resourceType->next should be null to avoid memory leaks.
198 * Function returns silently for null args.
200 * @param resource Resource where resource type is to be inserted.
201 * @param resourceType Resource type to be inserted.
203 static void insertResourceType(OCResource *resource,
204 OCResourceType *resourceType);
207 * Get a resource type at the specified index within a resource.
209 * @param handle Handle of resource.
210 * @param index Index of resource type.
212 * @return Pointer to resource type if found, NULL otherwise.
214 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
218 * Insert a resource interface into a resource's resource interface linked list.
219 * If resource interface already exists, it will not be inserted and the
220 * resourceInterface will be free'd.
221 * resourceInterface->next should be null to avoid memory leaks.
223 * @param resource Resource where resource interface is to be inserted.
224 * @param resourceInterface Resource interface to be inserted.
226 static void insertResourceInterface(OCResource *resource,
227 OCResourceInterface *resourceInterface);
230 * Get a resource interface at the specified index within a resource.
232 * @param handle Handle of resource.
233 * @param index Index of resource interface.
235 * @return Pointer to resource interface if found, NULL otherwise.
237 static OCResourceInterface *findResourceInterfaceAtIndex(
238 OCResourceHandle handle, uint8_t index);
241 * Delete all of the dynamically allocated elements that were created for the resource type.
243 * @param resourceType Specified resource type.
245 static void deleteResourceType(OCResourceType *resourceType);
248 * Delete all of the dynamically allocated elements that were created for the resource interface.
250 * @param resourceInterface Specified resource interface.
252 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
255 * Delete all of the dynamically allocated elements that were created for the resource.
257 * @param resource Specified resource.
259 static void deleteResourceElements(OCResource *resource);
262 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
265 * @param handle Handle of resource to be deleted.
267 * @return ::OC_STACK_OK on success, some other value upon failure.
269 static OCStackResult deleteResource(OCResource *resource);
272 * Delete all of the resources in the resource list.
274 static void deleteAllResources();
277 * Increment resource sequence number. Handles rollover.
279 * @param resPtr Pointer to resource.
281 static void incrementSequenceNumber(OCResource * resPtr);
284 * Verify the lengths of the URI and the query separately.
286 * @param inputUri Input URI and query.
287 * @param uriLen The length of the initial URI with query.
288 * @return ::OC_STACK_OK on success, some other value upon failure.
290 static OCStackResult verifyUriQueryLength(const char * inputUri,
294 * Attempts to initialize every network interface that the CA Layer might have compiled in.
296 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
297 * return something other than @ref CA_STATUS_OK, then this function fails.
299 * @return ::CA_STATUS_OK on success, some other value upon failure.
301 static CAResult_t OCSelectNetwork();
304 * Get the CoAP ticks after the specified number of milli-seconds.
306 * @param afterMilliSeconds Milli-seconds.
310 static uint32_t GetTicks(uint32_t afterMilliSeconds);
313 * Convert CAResult_t to OCStackResult.
315 * @param caResult CAResult_t code.
316 * @return ::OC_STACK_OK on success, some other value upon failure.
318 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
321 * Convert CAResponseResult_t to OCStackResult.
323 * @param caCode CAResponseResult_t code.
324 * @return ::OC_STACK_OK on success, some other value upon failure.
326 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
329 * Convert OCStackResult to CAResponseResult_t.
331 * @param caCode OCStackResult code.
332 * @param method OCMethod method the return code replies to.
333 * @return ::CA_CONTENT on OK, some other value upon failure.
335 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
338 * Convert OCTransportFlags_t to CATransportModifiers_t.
340 * @param ocConType OCTransportFlags_t input.
341 * @return CATransportFlags
343 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
346 * Convert CATransportFlags_t to OCTransportModifiers_t.
348 * @param caConType CATransportFlags_t input.
349 * @return OCTransportFlags
351 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
354 * Handle response from presence request.
356 * @param endPoint CA remote endpoint.
357 * @param responseInfo CA response info.
358 * @return ::OC_STACK_OK on success, some other value upon failure.
360 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
361 const CAResponseInfo_t *responseInfo);
364 * This function will be called back by CA layer when a response is received.
366 * @param endPoint CA remote endpoint.
367 * @param responseInfo CA response info.
369 static void HandleCAResponses(const CAEndpoint_t* endPoint,
370 const CAResponseInfo_t* responseInfo);
373 * This function will be called back by CA layer when a request is received.
375 * @param endPoint CA remote endpoint.
376 * @param requestInfo CA request info.
378 static void HandleCARequests(const CAEndpoint_t* endPoint,
379 const CARequestInfo_t* requestInfo);
382 * Extract query from a URI.
384 * @param uri Full URI with query.
385 * @param query Pointer to string that will contain query.
386 * @param newURI Pointer to string that will contain URI.
387 * @return ::OC_STACK_OK on success, some other value upon failure.
389 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
392 * Finds a resource type in an OCResourceType link-list.
394 * @param resourceTypeList The link-list to be searched through.
395 * @param resourceTypeName The key to search for.
397 * @return Resource type that matches the key (ie. resourceTypeName) or
398 * NULL if there is either an invalid parameter or this function was unable to find the key.
400 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
401 const char * resourceTypeName);
404 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
405 * TTL will be set to maxAge.
407 * @param cbNode Callback Node for which presence ttl is to be reset.
408 * @param maxAge New value of ttl in seconds.
410 * @return ::OC_STACK_OK on success, some other value upon failure.
412 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
415 * Ensure the accept header option is set appropriatly before sending the requests and routing
416 * header option is updated with destination.
418 * @param object CA remote endpoint.
419 * @param requestInfo CA request info.
421 * @return ::OC_STACK_OK on success, some other value upon failure.
423 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
425 //-----------------------------------------------------------------------------
426 // Internal functions
427 //-----------------------------------------------------------------------------
429 uint32_t GetTicks(uint32_t afterMilliSeconds)
434 // Guard against overflow of uint32_t
435 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
436 COAP_TICKS_PER_SECOND)
438 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
446 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
448 VERIFY_NON_NULL_NR(in, FATAL);
449 VERIFY_NON_NULL_NR(out, FATAL);
451 out->adapter = (OCTransportAdapter)in->adapter;
452 out->flags = CAToOCTransportFlags(in->flags);
453 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
454 out->port = in->port;
455 out->ifindex = in->ifindex;
456 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
457 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
461 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
463 VERIFY_NON_NULL_NR(in, FATAL);
464 VERIFY_NON_NULL_NR(out, FATAL);
466 out->adapter = (CATransportAdapter_t)in->adapter;
467 out->flags = OCToCATransportFlags(in->flags);
468 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
469 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
470 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
472 out->port = in->port;
473 out->ifindex = in->ifindex;
476 void FixUpClientResponse(OCClientResponse *cr)
478 VERIFY_NON_NULL_NR(cr, FATAL);
480 cr->addr = &cr->devAddr;
481 cr->connType = (OCConnectivityType)
482 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
485 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
487 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
488 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
490 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
491 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
492 if (OC_STACK_OK != rmResult)
494 OIC_LOG(ERROR, TAG, "Add destination option failed");
499 // OC stack prefer CBOR encoded payloads.
500 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
501 CAResult_t result = CASendRequest(object, requestInfo);
502 if(CA_STATUS_OK != result)
504 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
505 return CAResultToOCResult(result);
509 //-----------------------------------------------------------------------------
510 // Internal API function
511 //-----------------------------------------------------------------------------
513 // This internal function is called to update the stack with the status of
514 // observers and communication failures
515 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
517 OCStackResult result = OC_STACK_ERROR;
518 ResourceObserver * observer = NULL;
519 OCEntityHandlerRequest ehRequest = {0};
523 case OC_OBSERVER_NOT_INTERESTED:
524 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
525 observer = GetObserverUsingToken (token, tokenLength);
528 result = FormOCEntityHandlerRequest(&ehRequest,
529 (OCRequestHandle)NULL,
532 (OCResourceHandle)NULL,
533 NULL, PAYLOAD_TYPE_REPRESENTATION,
535 OC_OBSERVE_DEREGISTER,
536 observer->observeId);
537 if(result != OC_STACK_OK)
541 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
542 observer->resource->entityHandlerCallbackParam);
545 result = DeleteObserverUsingToken (token, tokenLength);
546 if(result == OC_STACK_OK)
548 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
552 result = OC_STACK_OK;
553 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
557 case OC_OBSERVER_STILL_INTERESTED:
558 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
559 observer = GetObserverUsingToken (token, tokenLength);
562 observer->forceHighQos = 0;
563 observer->failedCommCount = 0;
564 result = OC_STACK_OK;
568 result = OC_STACK_OBSERVER_NOT_FOUND;
572 case OC_OBSERVER_FAILED_COMM:
573 OIC_LOG(DEBUG, TAG, "observer is unreachable");
574 observer = GetObserverUsingToken (token, tokenLength);
577 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
579 result = FormOCEntityHandlerRequest(&ehRequest,
580 (OCRequestHandle)NULL,
583 (OCResourceHandle)NULL,
584 NULL, PAYLOAD_TYPE_REPRESENTATION,
586 OC_OBSERVE_DEREGISTER,
587 observer->observeId);
588 if(result != OC_STACK_OK)
590 return OC_STACK_ERROR;
592 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
593 observer->resource->entityHandlerCallbackParam);
595 result = DeleteObserverUsingToken (token, tokenLength);
596 if(result == OC_STACK_OK)
598 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
602 result = OC_STACK_OK;
603 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
608 observer->failedCommCount++;
609 result = OC_STACK_CONTINUE;
611 observer->forceHighQos = 1;
612 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
616 OIC_LOG(ERROR, TAG, "Unknown status");
617 result = OC_STACK_ERROR;
623 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
625 OCStackResult ret = OC_STACK_ERROR;
629 case CA_ADAPTER_NOT_ENABLED:
630 case CA_SERVER_NOT_STARTED:
631 ret = OC_STACK_ADAPTER_NOT_ENABLED;
633 case CA_MEMORY_ALLOC_FAILED:
634 ret = OC_STACK_NO_MEMORY;
636 case CA_STATUS_INVALID_PARAM:
637 ret = OC_STACK_INVALID_PARAM;
645 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
647 OCStackResult ret = OC_STACK_ERROR;
652 ret = OC_STACK_RESOURCE_CREATED;
655 ret = OC_STACK_RESOURCE_DELETED;
663 ret = OC_STACK_INVALID_QUERY;
665 case CA_UNAUTHORIZED_REQ:
666 ret = OC_STACK_UNAUTHORIZED_REQ;
669 ret = OC_STACK_INVALID_OPTION;
672 ret = OC_STACK_NO_RESOURCE;
674 case CA_RETRANSMIT_TIMEOUT:
675 ret = OC_STACK_COMM_ERROR;
677 case CA_REQUEST_ENTITY_TOO_LARGE:
678 ret = OC_STACK_TOO_LARGE_REQ;
686 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
688 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
697 // This Response Code is like HTTP 204 "No Content" but only used in
698 // response to POST and PUT requests.
702 // This Response Code is like HTTP 200 "OK" but only used in response to
707 // This should not happen but,
708 // give it a value just in case but output an error
710 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
713 case OC_STACK_RESOURCE_CREATED:
716 case OC_STACK_RESOURCE_DELETED:
719 case OC_STACK_INVALID_QUERY:
722 case OC_STACK_INVALID_OPTION:
725 case OC_STACK_NO_RESOURCE:
728 case OC_STACK_COMM_ERROR:
729 ret = CA_RETRANSMIT_TIMEOUT;
731 case OC_STACK_UNAUTHORIZED_REQ:
732 ret = CA_UNAUTHORIZED_REQ;
740 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
742 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
744 // supply default behavior.
745 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
747 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
749 if ((caFlags & OC_MASK_SCOPE) == 0)
751 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
756 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
758 return (OCTransportFlags)caFlags;
761 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
763 uint32_t lowerBound = 0;
764 uint32_t higherBound = 0;
766 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
768 return OC_STACK_INVALID_PARAM;
771 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
773 cbNode->presence->TTL = maxAgeSeconds;
775 for (int index = 0; index < PresenceTimeOutSize; index++)
777 // Guard against overflow
778 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
781 lowerBound = GetTicks((PresenceTimeOut[index] *
782 cbNode->presence->TTL *
783 MILLISECONDS_PER_SECOND)/100);
787 lowerBound = GetTicks(UINT32_MAX);
790 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
793 higherBound = GetTicks((PresenceTimeOut[index + 1] *
794 cbNode->presence->TTL *
795 MILLISECONDS_PER_SECOND)/100);
799 higherBound = GetTicks(UINT32_MAX);
802 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
804 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
805 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
806 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
809 cbNode->presence->TTLlevel = 0;
811 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
815 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
817 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
819 return OC_RSRVD_TRIGGER_CREATE;
821 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
823 return OC_RSRVD_TRIGGER_CHANGE;
827 return OC_RSRVD_TRIGGER_DELETE;
831 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
835 return OC_PRESENCE_TRIGGER_CREATE;
837 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
839 return OC_PRESENCE_TRIGGER_CREATE;
841 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
843 return OC_PRESENCE_TRIGGER_CHANGE;
847 return OC_PRESENCE_TRIGGER_DELETE;
852 * The cononical presence allows constructed URIs to be string compared.
854 * requestUri must be a char array of size CA_MAX_URI_LENGTH
856 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
859 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
860 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
861 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
863 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
865 if (ep->adapter == CA_ADAPTER_IP)
867 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
869 if ('\0' == ep->addr[0]) // multicast
871 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
875 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
876 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
881 if ('\0' == ep->addr[0]) // multicast
883 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
884 ep->port = OC_MULTICAST_PORT;
886 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
887 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
891 // might work for other adapters (untested, but better than nothing)
892 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
893 OC_RSRVD_PRESENCE_URI);
897 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
898 const CAResponseInfo_t *responseInfo)
900 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
901 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
903 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
904 ClientCB * cbNode = NULL;
905 char *resourceTypeName = NULL;
906 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
907 OCStackResult result = OC_STACK_ERROR;
910 char presenceUri[CA_MAX_URI_LENGTH];
912 int presenceSubscribe = 0;
913 int multicastPresenceSubscribe = 0;
915 if (responseInfo->result != CA_CONTENT)
917 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
918 return OC_STACK_ERROR;
921 // check for unicast presence
922 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
923 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
925 return OC_STACK_INVALID_URI;
928 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
931 presenceSubscribe = 1;
935 // check for multiicast presence
936 CAEndpoint_t ep = { .adapter = endpoint->adapter,
937 .flags = endpoint->flags };
939 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
941 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
944 multicastPresenceSubscribe = 1;
948 if (!presenceSubscribe && !multicastPresenceSubscribe)
950 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
954 response.payload = NULL;
955 response.result = OC_STACK_OK;
957 CopyEndpointToDevAddr(endpoint, &response.devAddr);
958 FixUpClientResponse(&response);
960 if (responseInfo->info.payload)
962 result = OCParsePayload(&response.payload,
963 PAYLOAD_TYPE_PRESENCE,
964 responseInfo->info.payload,
965 responseInfo->info.payloadSize);
967 if(result != OC_STACK_OK)
969 OIC_LOG(ERROR, TAG, "Presence parse failed");
972 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
974 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
975 result = OC_STACK_ERROR;
978 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
979 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
980 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
983 if (presenceSubscribe)
985 if(cbNode->sequenceNumber == response.sequenceNumber)
987 OIC_LOG(INFO, TAG, "No presence change");
988 ResetPresenceTTL(cbNode, maxAge);
989 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
995 OIC_LOG(INFO, TAG, "Stopping presence");
996 response.result = OC_STACK_PRESENCE_STOPPED;
999 OICFree(cbNode->presence->timeOut);
1000 OICFree(cbNode->presence);
1001 cbNode->presence = NULL;
1006 if(!cbNode->presence)
1008 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1010 if(!(cbNode->presence))
1012 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1013 result = OC_STACK_NO_MEMORY;
1017 VERIFY_NON_NULL_V(cbNode->presence);
1018 cbNode->presence->timeOut = NULL;
1019 cbNode->presence->timeOut = (uint32_t *)
1020 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1021 if(!(cbNode->presence->timeOut)){
1023 "Could not allocate memory for cbNode->presence->timeOut");
1024 OICFree(cbNode->presence);
1025 result = OC_STACK_NO_MEMORY;
1030 ResetPresenceTTL(cbNode, maxAge);
1032 cbNode->sequenceNumber = response.sequenceNumber;
1034 // Ensure that a filter is actually applied.
1035 if( resourceTypeName && cbNode->filterResourceType)
1037 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1046 // This is the multicast case
1047 OCMulticastNode* mcNode = NULL;
1048 mcNode = GetMCPresenceNode(presenceUri);
1052 if(mcNode->nonce == response.sequenceNumber)
1054 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1057 mcNode->nonce = response.sequenceNumber;
1061 OIC_LOG(INFO, TAG, "Stopping presence");
1062 response.result = OC_STACK_PRESENCE_STOPPED;
1067 char* uri = OICStrdup(presenceUri);
1071 "No Memory for URI to store in the presence node");
1072 result = OC_STACK_NO_MEMORY;
1076 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1077 if(result == OC_STACK_NO_MEMORY)
1080 "No Memory for Multicast Presence Node");
1084 // presence node now owns uri
1087 // Ensure that a filter is actually applied.
1088 if(resourceTypeName && cbNode->filterResourceType)
1090 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1097 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1099 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1101 FindAndDeleteClientCB(cbNode);
1105 OCPayloadDestroy(response.payload);
1109 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1111 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1113 if(responseInfo->info.resourceUri &&
1114 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1116 HandlePresenceResponse(endPoint, responseInfo);
1120 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1121 responseInfo->info.tokenLength, NULL, NULL);
1123 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1124 responseInfo->info.tokenLength);
1128 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1129 if(responseInfo->result == CA_EMPTY)
1131 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1132 // We do not have a case for the client to receive a RESET
1133 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1135 //This is the case of receiving an ACK on a request to a slow resource!
1136 OIC_LOG(INFO, TAG, "This is a pure ACK");
1137 //TODO: should we inform the client
1138 // app that at least the request was received at the server?
1141 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1143 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1144 OIC_LOG(INFO, TAG, "Calling into application address space");
1146 OCClientResponse response =
1147 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1148 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1149 FixUpClientResponse(&response);
1150 response.resourceUri = responseInfo->info.resourceUri;
1151 memcpy(response.identity.id, responseInfo->info.identity.id,
1152 sizeof (response.identity.id));
1153 response.identity.id_length = responseInfo->info.identity.id_length;
1155 response.result = CAResponseToOCStackResult(responseInfo->result);
1156 cbNode->callBack(cbNode->context,
1157 cbNode->handle, &response);
1158 FindAndDeleteClientCB(cbNode);
1162 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1163 OIC_LOG(INFO, TAG, "Calling into application address space");
1165 OCClientResponse response =
1166 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1167 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1168 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1169 FixUpClientResponse(&response);
1170 response.resourceUri = responseInfo->info.resourceUri;
1171 memcpy(response.identity.id, responseInfo->info.identity.id,
1172 sizeof (response.identity.id));
1173 response.identity.id_length = responseInfo->info.identity.id_length;
1175 response.result = CAResponseToOCStackResult(responseInfo->result);
1177 if(responseInfo->info.payload &&
1178 responseInfo->info.payloadSize)
1180 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1181 // check the security resource
1182 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1184 type = PAYLOAD_TYPE_SECURITY;
1186 else if (cbNode->method == OC_REST_DISCOVER)
1188 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1189 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1191 type = PAYLOAD_TYPE_DISCOVERY;
1193 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1195 type = PAYLOAD_TYPE_DEVICE;
1197 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1199 type = PAYLOAD_TYPE_PLATFORM;
1201 #ifdef ROUTING_GATEWAY
1202 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1204 type = PAYLOAD_TYPE_REPRESENTATION;
1207 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1209 type = PAYLOAD_TYPE_RD;
1212 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1214 type = PAYLOAD_TYPE_REPRESENTATION;
1219 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1220 cbNode->method, cbNode->requestUri);
1224 else if (cbNode->method == OC_REST_GET ||
1225 cbNode->method == OC_REST_PUT ||
1226 cbNode->method == OC_REST_POST ||
1227 cbNode->method == OC_REST_OBSERVE ||
1228 cbNode->method == OC_REST_OBSERVE_ALL ||
1229 cbNode->method == OC_REST_DELETE)
1231 char targetUri[MAX_URI_LENGTH];
1232 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1233 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1234 if (strcmp(targetUri, cbNode->requestUri) == 0)
1236 type = PAYLOAD_TYPE_RD;
1238 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1240 type = PAYLOAD_TYPE_PLATFORM;
1242 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1244 type = PAYLOAD_TYPE_DEVICE;
1246 if (type == PAYLOAD_TYPE_INVALID)
1248 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1249 cbNode->method, cbNode->requestUri);
1250 type = PAYLOAD_TYPE_REPRESENTATION;
1255 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1256 cbNode->method, cbNode->requestUri);
1260 if(OC_STACK_OK != OCParsePayload(&response.payload,
1262 responseInfo->info.payload,
1263 responseInfo->info.payloadSize))
1265 OIC_LOG(ERROR, TAG, "Error converting payload");
1266 OCPayloadDestroy(response.payload);
1271 response.numRcvdVendorSpecificHeaderOptions = 0;
1272 if(responseInfo->info.numOptions > 0)
1275 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1276 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1279 uint32_t observationOption;
1280 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1281 for (observationOption=0, i=0;
1282 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1286 (observationOption << 8) | optionData[i];
1288 response.sequenceNumber = observationOption;
1290 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1295 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1298 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1300 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1301 OCPayloadDestroy(response.payload);
1305 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1307 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1308 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1312 if (cbNode->method == OC_REST_OBSERVE &&
1313 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1314 response.sequenceNumber <= cbNode->sequenceNumber)
1316 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1317 response.sequenceNumber);
1321 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1324 cbNode->sequenceNumber = response.sequenceNumber;
1326 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1328 FindAndDeleteClientCB(cbNode);
1332 // To keep discovery callbacks active.
1333 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1334 MILLISECONDS_PER_SECOND);
1338 //Need to send ACK when the response is CON
1339 if(responseInfo->info.type == CA_MSG_CONFIRM)
1341 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1342 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1345 OCPayloadDestroy(response.payload);
1352 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1353 if(responseInfo->result == CA_EMPTY)
1355 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1356 if(responseInfo->info.type == CA_MSG_RESET)
1358 OIC_LOG(INFO, TAG, "This is a RESET");
1359 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1360 OC_OBSERVER_NOT_INTERESTED);
1362 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1364 OIC_LOG(INFO, TAG, "This is a pure ACK");
1365 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1366 OC_OBSERVER_STILL_INTERESTED);
1369 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1371 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1372 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1373 OC_OBSERVER_FAILED_COMM);
1378 if(!cbNode && !observer)
1380 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1381 || myStackMode == OC_GATEWAY)
1383 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1384 if(responseInfo->result == CA_EMPTY)
1386 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1390 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1391 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1392 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1396 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1397 || myStackMode == OC_GATEWAY)
1399 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1400 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1402 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1403 responseInfo->info.messageId);
1405 if (responseInfo->info.type == CA_MSG_RESET)
1407 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1408 responseInfo->info.messageId);
1415 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1418 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1420 VERIFY_NON_NULL_NR(endPoint, FATAL);
1421 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1423 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1425 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1426 #ifdef ROUTING_GATEWAY
1427 bool needRIHandling = false;
1429 * Routing manager is going to update either of endpoint or response or both.
1430 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1431 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1434 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1436 if(ret != OC_STACK_OK || !needRIHandling)
1438 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1444 * Put source in sender endpoint so that the next packet from application can be routed to
1445 * proper destination and remove "RM" coap header option before passing request / response to
1446 * RI as this option will make no sense to either RI or application.
1448 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1449 (uint8_t *) &(responseInfo->info.numOptions),
1450 (CAEndpoint_t *) endPoint);
1453 OCHandleResponse(endPoint, responseInfo);
1455 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1459 * This function handles error response from CA
1460 * code shall be added to handle the errors
1462 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1464 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1466 if (NULL == endPoint)
1468 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1472 if (NULL == errorInfo)
1474 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1478 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1479 errorInfo->info.tokenLength, NULL, NULL);
1482 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1483 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1484 FixUpClientResponse(&response);
1485 response.resourceUri = errorInfo->info.resourceUri;
1486 memcpy(response.identity.id, errorInfo->info.identity.id,
1487 sizeof (response.identity.id));
1488 response.identity.id_length = errorInfo->info.identity.id_length;
1489 response.result = CAResultToOCStackResult(errorInfo->result);
1491 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1492 FindAndDeleteClientCB(cbNode);
1495 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1499 * This function sends out Direct Stack Responses. These are responses that are not coming
1500 * from the application entity handler. These responses have no payload and are usually ACKs,
1501 * RESETs or some error conditions that were caught by the stack.
1503 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1504 const CAResponseResult_t responseResult, const CAMessageType_t type,
1505 const uint8_t numOptions, const CAHeaderOption_t *options,
1506 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1508 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1509 CAResponseInfo_t respInfo = {
1510 .result = responseResult
1512 respInfo.info.messageId = coapID;
1513 respInfo.info.numOptions = numOptions;
1515 if (respInfo.info.numOptions)
1517 respInfo.info.options =
1518 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1519 memcpy (respInfo.info.options, options,
1520 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1524 respInfo.info.payload = NULL;
1525 respInfo.info.token = token;
1526 respInfo.info.tokenLength = tokenLength;
1527 respInfo.info.type = type;
1528 respInfo.info.resourceUri = OICStrdup (resourceUri);
1529 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1531 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1532 // Add the destination to route option from the endpoint->routeData.
1533 bool doPost = false;
1534 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1535 if(OC_STACK_OK != result)
1537 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1542 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1543 CARequestInfo_t reqInfo = {.method = CA_POST };
1544 /* The following initialization is not done in a single initializer block as in
1545 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1546 * does not have designated initalizers. This is a work-around for now.
1548 reqInfo.info.type = CA_MSG_NONCONFIRM;
1549 reqInfo.info.messageId = coapID;
1550 reqInfo.info.tokenLength = tokenLength;
1551 reqInfo.info.token = token;
1552 reqInfo.info.numOptions = respInfo.info.numOptions;
1553 reqInfo.info.payload = NULL;
1554 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1555 if (reqInfo.info.numOptions)
1557 reqInfo.info.options =
1558 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1559 if (NULL == reqInfo.info.options)
1561 OIC_LOG(ERROR, TAG, "Calloc failed");
1562 return OC_STACK_NO_MEMORY;
1564 memcpy (reqInfo.info.options, respInfo.info.options,
1565 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1568 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1569 OICFree (reqInfo.info.resourceUri);
1570 OICFree (reqInfo.info.options);
1571 OICFree (respInfo.info.resourceUri);
1572 OICFree (respInfo.info.options);
1573 if (CA_STATUS_OK != caResult)
1575 OIC_LOG(ERROR, TAG, "CASendRequest error");
1576 return CAResultToOCResult(caResult);
1582 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1584 // resourceUri in the info field is cloned in the CA layer and
1585 // thus ownership is still here.
1586 OICFree (respInfo.info.resourceUri);
1587 OICFree (respInfo.info.options);
1588 if(CA_STATUS_OK != caResult)
1590 OIC_LOG(ERROR, TAG, "CASendResponse error");
1591 return CAResultToOCResult(caResult);
1594 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1598 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1600 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1601 OCStackResult result = OC_STACK_ERROR;
1602 if(!protocolRequest)
1604 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1605 return OC_STACK_INVALID_PARAM;
1608 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1609 protocolRequest->tokenLength);
1612 OIC_LOG(INFO, TAG, "This is a new Server Request");
1613 result = AddServerRequest(&request, protocolRequest->coapID,
1614 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1615 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1616 protocolRequest->observationOption, protocolRequest->qos,
1617 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1618 protocolRequest->payload, protocolRequest->requestToken,
1619 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1620 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1621 &protocolRequest->devAddr);
1622 if (OC_STACK_OK != result)
1624 OIC_LOG(ERROR, TAG, "Error adding server request");
1630 OIC_LOG(ERROR, TAG, "Out of Memory");
1631 return OC_STACK_NO_MEMORY;
1634 if(!protocolRequest->reqMorePacket)
1636 request->requestComplete = 1;
1641 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1644 if(request->requestComplete)
1646 OIC_LOG(INFO, TAG, "This Server Request is complete");
1647 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1648 OCResource *resource = NULL;
1649 result = DetermineResourceHandling (request, &resHandling, &resource);
1650 if (result == OC_STACK_OK)
1652 result = ProcessRequest(resHandling, resource, request);
1657 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1658 result = OC_STACK_CONTINUE;
1663 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1665 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1668 if (requestInfo->info.resourceUri &&
1669 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1671 HandleKeepAliveRequest(endPoint, requestInfo);
1676 OCStackResult requestResult = OC_STACK_ERROR;
1678 if(myStackMode == OC_CLIENT)
1680 //TODO: should the client be responding to requests?
1684 OCServerProtocolRequest serverRequest = {0};
1686 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1688 char * uriWithoutQuery = NULL;
1689 char * query = NULL;
1691 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1693 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1695 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1698 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1699 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1701 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1703 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1704 OICFree(uriWithoutQuery);
1708 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1709 OICFree(uriWithoutQuery);
1716 if(strlen(query) < MAX_QUERY_LENGTH)
1718 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1723 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1729 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1731 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1732 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1733 if (!serverRequest.payload)
1735 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1738 memcpy (serverRequest.payload, requestInfo->info.payload,
1739 requestInfo->info.payloadSize);
1743 serverRequest.reqTotalSize = 0;
1746 switch (requestInfo->method)
1749 serverRequest.method = OC_REST_GET;
1752 serverRequest.method = OC_REST_PUT;
1755 serverRequest.method = OC_REST_POST;
1758 serverRequest.method = OC_REST_DELETE;
1761 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1762 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1763 requestInfo->info.type, requestInfo->info.numOptions,
1764 requestInfo->info.options, requestInfo->info.token,
1765 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1766 OICFree(serverRequest.payload);
1770 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1771 requestInfo->info.tokenLength);
1773 serverRequest.tokenLength = requestInfo->info.tokenLength;
1774 if (serverRequest.tokenLength) {
1776 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1778 if (!serverRequest.requestToken)
1780 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1781 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1782 requestInfo->info.type, requestInfo->info.numOptions,
1783 requestInfo->info.options, requestInfo->info.token,
1784 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1785 OICFree(serverRequest.payload);
1788 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1791 switch (requestInfo->info.acceptFormat)
1793 case CA_FORMAT_APPLICATION_CBOR:
1794 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1796 case CA_FORMAT_UNDEFINED:
1797 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1800 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1803 if (requestInfo->info.type == CA_MSG_CONFIRM)
1805 serverRequest.qos = OC_HIGH_QOS;
1809 serverRequest.qos = OC_LOW_QOS;
1811 // CA does not need the following field
1812 // Are we sure CA does not need them? how is it responding to multicast
1813 serverRequest.delayedResNeeded = 0;
1815 serverRequest.coapID = requestInfo->info.messageId;
1817 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1819 // copy vendor specific header options
1820 uint8_t tempNum = (requestInfo->info.numOptions);
1822 // Assume no observation requested and it is a pure GET.
1823 // If obs registration/de-registration requested it'll be fetched from the
1824 // options in GetObserveHeaderOption()
1825 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1827 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1828 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1831 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1832 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1833 requestInfo->info.type, requestInfo->info.numOptions,
1834 requestInfo->info.options, requestInfo->info.token,
1835 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1836 OICFree(serverRequest.payload);
1837 OICFree(serverRequest.requestToken);
1840 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1841 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1843 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1844 sizeof(CAHeaderOption_t)*tempNum);
1847 requestResult = HandleStackRequests (&serverRequest);
1849 // Send ACK to client as precursor to slow response
1850 if (requestResult == OC_STACK_SLOW_RESOURCE)
1852 if (requestInfo->info.type == CA_MSG_CONFIRM)
1854 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1855 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1858 else if(requestResult != OC_STACK_OK)
1860 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1862 CAResponseResult_t stackResponse =
1863 OCToCAStackResult(requestResult, serverRequest.method);
1865 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1866 requestInfo->info.type, requestInfo->info.numOptions,
1867 requestInfo->info.options, requestInfo->info.token,
1868 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1870 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1871 // The token is copied in there, and is thus still owned by this function.
1872 OICFree(serverRequest.payload);
1873 OICFree(serverRequest.requestToken);
1874 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1877 //This function will be called back by CA layer when a request is received
1878 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1880 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1883 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1889 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1893 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1894 #ifdef ROUTING_GATEWAY
1895 bool needRIHandling = false;
1896 bool isEmptyMsg = false;
1898 * Routing manager is going to update either of endpoint or request or both.
1899 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1900 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1901 * destination. It can also remove "RM" coap header option before passing request / response to
1902 * RI as this option will make no sense to either RI or application.
1904 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1905 &needRIHandling, &isEmptyMsg);
1906 if(OC_STACK_OK != ret || !needRIHandling)
1908 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1914 * Put source in sender endpoint so that the next packet from application can be routed to
1915 * proper destination and remove RM header option.
1917 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1918 (uint8_t *) &(requestInfo->info.numOptions),
1919 (CAEndpoint_t *) endPoint);
1921 #ifdef ROUTING_GATEWAY
1925 * In Gateways, the MSGType in route option is used to check if the actual
1926 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
1927 * EMPTY response is sent in the form of POST request which need to be changed
1928 * to a EMPTY response by RM. This translation is done in this part of the code.
1930 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1931 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1932 .info.messageId = requestInfo->info.messageId,
1933 .info.type = CA_MSG_ACKNOWLEDGE};
1934 OCHandleResponse(endPoint, &respInfo);
1940 // Normal handling of the packet
1941 OCHandleRequests(endPoint, requestInfo);
1943 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1946 bool validatePlatformInfo(OCPlatformInfo info)
1949 if (!info.platformID)
1951 OIC_LOG(ERROR, TAG, "No platform ID found.");
1955 if (info.manufacturerName)
1957 size_t lenManufacturerName = strlen(info.manufacturerName);
1959 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1961 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1967 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1971 if (info.manufacturerUrl)
1973 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1975 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1982 //-----------------------------------------------------------------------------
1984 //-----------------------------------------------------------------------------
1986 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1989 !raInfo->username ||
1990 !raInfo->hostname ||
1991 !raInfo->xmpp_domain)
1994 return OC_STACK_INVALID_PARAM;
1996 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1997 gRASetInfo = (result == OC_STACK_OK)? true : false;
2003 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2007 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2010 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2012 if(stackState == OC_STACK_INITIALIZED)
2014 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2015 OCStop() between them are ignored.");
2019 #ifndef ROUTING_GATEWAY
2020 if (OC_GATEWAY == mode)
2022 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2023 return OC_STACK_INVALID_PARAM;
2030 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2031 return OC_STACK_ERROR;
2035 OCStackResult result = OC_STACK_ERROR;
2036 OIC_LOG(INFO, TAG, "Entering OCInit");
2039 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2040 || (mode == OC_GATEWAY)))
2042 OIC_LOG(ERROR, TAG, "Invalid mode");
2043 return OC_STACK_ERROR;
2047 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2049 caglobals.client = true;
2051 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2053 caglobals.server = true;
2056 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2057 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2059 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2061 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2062 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2064 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2067 defaultDeviceHandler = NULL;
2068 defaultDeviceHandlerCallbackParameter = NULL;
2070 result = CAResultToOCResult(CAInitialize());
2071 VERIFY_SUCCESS(result, OC_STACK_OK);
2073 result = CAResultToOCResult(OCSelectNetwork());
2074 VERIFY_SUCCESS(result, OC_STACK_OK);
2076 switch (myStackMode)
2079 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2080 result = CAResultToOCResult(CAStartDiscoveryServer());
2081 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2084 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2085 result = CAResultToOCResult(CAStartListeningServer());
2086 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2088 case OC_CLIENT_SERVER:
2090 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2091 result = CAResultToOCResult(CAStartListeningServer());
2092 if(result == OC_STACK_OK)
2094 result = CAResultToOCResult(CAStartDiscoveryServer());
2098 VERIFY_SUCCESS(result, OC_STACK_OK);
2101 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2104 #ifdef WITH_PRESENCE
2105 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2106 #endif // WITH_PRESENCE
2108 //Update Stack state to initialized
2109 stackState = OC_STACK_INITIALIZED;
2111 // Initialize resource
2112 if(myStackMode != OC_CLIENT)
2114 result = initResources();
2117 // Initialize the SRM Policy Engine
2118 if(result == OC_STACK_OK)
2120 result = SRMInitPolicyEngine();
2121 // TODO after BeachHead delivery: consolidate into single SRMInit()
2123 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2124 RMSetStackMode(mode);
2125 #ifdef ROUTING_GATEWAY
2126 if (OC_GATEWAY == myStackMode)
2128 result = RMInitialize();
2134 if (result == OC_STACK_OK)
2136 result = InitializeKeepAlive(myStackMode);
2141 if(result != OC_STACK_OK)
2143 OIC_LOG(ERROR, TAG, "Stack initialization error");
2144 deleteAllResources();
2146 stackState = OC_STACK_UNINITIALIZED;
2151 OCStackResult OCStop()
2153 OIC_LOG(INFO, TAG, "Entering OCStop");
2155 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2157 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2160 else if (stackState != OC_STACK_INITIALIZED)
2162 OIC_LOG(ERROR, TAG, "Stack not initialized");
2163 return OC_STACK_ERROR;
2166 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2168 #ifdef WITH_PRESENCE
2169 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2170 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2171 presenceResource.presenceTTL = 0;
2172 #endif // WITH_PRESENCE
2174 #ifdef ROUTING_GATEWAY
2175 if (OC_GATEWAY == myStackMode)
2182 TerminateKeepAlive(myStackMode);
2185 // Free memory dynamically allocated for resources
2186 deleteAllResources();
2188 DeletePlatformInfo();
2190 // Remove all observers
2191 DeleteObserverList();
2192 // Remove all the client callbacks
2193 DeleteClientCBList();
2195 // De-init the SRM Policy Engine
2196 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2197 SRMDeInitPolicyEngine();
2200 stackState = OC_STACK_UNINITIALIZED;
2204 OCStackResult OCStartMulticastServer()
2206 if(stackState != OC_STACK_INITIALIZED)
2208 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2209 return OC_STACK_ERROR;
2211 CAResult_t ret = CAStartListeningServer();
2212 if (CA_STATUS_OK != ret)
2214 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2215 return OC_STACK_ERROR;
2220 OCStackResult OCStopMulticastServer()
2222 CAResult_t ret = CAStopListeningServer();
2223 if (CA_STATUS_OK != ret)
2225 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2226 return OC_STACK_ERROR;
2231 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2236 return CA_MSG_CONFIRM;
2241 return CA_MSG_NONCONFIRM;
2245 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2249 query = strchr (inputUri, '?');
2253 if((query - inputUri) > MAX_URI_LENGTH)
2255 return OC_STACK_INVALID_URI;
2258 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2260 return OC_STACK_INVALID_QUERY;
2263 else if(uriLen > MAX_URI_LENGTH)
2265 return OC_STACK_INVALID_URI;
2271 * A request uri consists of the following components in order:
2274 * CoAP over UDP prefix "coap://"
2275 * CoAP over TCP prefix "coap+tcp://"
2277 * IPv6 address "[1234::5678]"
2278 * IPv4 address "192.168.1.1"
2279 * optional port ":5683"
2280 * resource uri "/oc/core..."
2282 * for PRESENCE requests, extract resource type.
2284 static OCStackResult ParseRequestUri(const char *fullUri,
2285 OCTransportAdapter adapter,
2286 OCTransportFlags flags,
2287 OCDevAddr **devAddr,
2289 char **resourceType)
2291 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2293 OCStackResult result = OC_STACK_OK;
2294 OCDevAddr *da = NULL;
2298 // provide defaults for all returned values
2305 *resourceUri = NULL;
2309 *resourceType = NULL;
2312 // delimit url prefix, if any
2313 const char *start = fullUri;
2314 char *slash2 = strstr(start, "//");
2319 char *slash = strchr(start, '/');
2322 return OC_STACK_INVALID_URI;
2325 // process url scheme
2326 size_t prefixLen = slash2 - fullUri;
2330 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2336 // TODO: this logic should come in with unit tests exercising the various strings
2337 // processs url prefix, if any
2338 size_t urlLen = slash - start;
2342 if (urlLen && devAddr)
2343 { // construct OCDevAddr
2344 if (start[0] == '[')
2346 char *close = strchr(++start, ']');
2347 if (!close || close > slash)
2349 return OC_STACK_INVALID_URI;
2352 if (close[1] == ':')
2359 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2363 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2365 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2369 char *dot = strchr(start, '.');
2370 if (dot && dot < slash)
2372 colon = strchr(start, ':');
2373 end = (colon && colon < slash) ? colon : slash;
2378 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2382 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2384 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2392 if (len >= sizeof(da->addr))
2394 return OC_STACK_INVALID_URI;
2396 // collect port, if any
2397 if (colon && colon < slash)
2399 for (colon++; colon < slash; colon++)
2402 if (c < '0' || c > '9')
2404 return OC_STACK_INVALID_URI;
2406 port = 10 * port + c - '0';
2411 if (len >= sizeof(da->addr))
2413 return OC_STACK_INVALID_URI;
2416 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2419 return OC_STACK_NO_MEMORY;
2421 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2423 da->adapter = adapter;
2425 if (!strncmp(fullUri, "coaps:", 6))
2427 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2432 // process resource uri, if any
2434 { // request uri and query
2435 size_t ulen = strlen(slash); // resource uri length
2436 size_t tlen = 0; // resource type length
2439 static const char strPresence[] = "/oic/ad?rt=";
2440 static const size_t lenPresence = sizeof(strPresence) - 1;
2441 if (!strncmp(slash, strPresence, lenPresence))
2443 type = slash + lenPresence;
2444 tlen = ulen - lenPresence;
2449 *resourceUri = (char *)OICMalloc(ulen + 1);
2452 result = OC_STACK_NO_MEMORY;
2455 strcpy(*resourceUri, slash);
2458 if (type && resourceType)
2460 *resourceType = (char *)OICMalloc(tlen + 1);
2463 result = OC_STACK_NO_MEMORY;
2467 OICStrcpy(*resourceType, (tlen+1), type);
2474 // free all returned values
2481 OICFree(*resourceUri);
2485 OICFree(*resourceType);
2490 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2491 char *resourceUri, char **requestUri)
2493 char uri[CA_MAX_URI_LENGTH];
2495 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2497 *requestUri = OICStrdup(uri);
2500 return OC_STACK_NO_MEMORY;
2507 * Discover or Perform requests on a specified resource
2509 OCStackResult OCDoResource(OCDoHandle *handle,
2511 const char *requestUri,
2512 const OCDevAddr *destination,
2514 OCConnectivityType connectivityType,
2515 OCQualityOfService qos,
2516 OCCallbackData *cbData,
2517 OCHeaderOption *options,
2520 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2522 // Validate input parameters
2523 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2524 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2525 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2527 OCStackResult result = OC_STACK_ERROR;
2528 CAResult_t caResult;
2529 CAToken_t token = NULL;
2530 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2531 ClientCB *clientCB = NULL;
2532 OCDoHandle resHandle = NULL;
2533 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2534 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2536 OCTransportAdapter adapter;
2537 OCTransportFlags flags;
2538 // the request contents are put here
2539 CARequestInfo_t requestInfo = {.method = CA_GET};
2540 // requestUri will be parsed into the following three variables
2541 OCDevAddr *devAddr = NULL;
2542 char *resourceUri = NULL;
2543 char *resourceType = NULL;
2546 * Support original behavior with address on resourceUri argument.
2548 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2549 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2551 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2553 if (result != OC_STACK_OK)
2555 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2562 case OC_REST_OBSERVE:
2563 case OC_REST_OBSERVE_ALL:
2564 case OC_REST_CANCEL_OBSERVE:
2565 requestInfo.method = CA_GET;
2568 requestInfo.method = CA_PUT;
2571 requestInfo.method = CA_POST;
2573 case OC_REST_DELETE:
2574 requestInfo.method = CA_DELETE;
2576 case OC_REST_DISCOVER:
2578 if (destination || devAddr)
2580 requestInfo.isMulticast = false;
2584 tmpDevAddr.adapter = adapter;
2585 tmpDevAddr.flags = flags;
2586 destination = &tmpDevAddr;
2587 requestInfo.isMulticast = true;
2589 // CA_DISCOVER will become GET and isMulticast
2590 requestInfo.method = CA_GET;
2592 #ifdef WITH_PRESENCE
2593 case OC_REST_PRESENCE:
2594 // Replacing method type with GET because "presence"
2595 // is a stack layer only implementation.
2596 requestInfo.method = CA_GET;
2600 result = OC_STACK_INVALID_METHOD;
2604 if (!devAddr && !destination)
2606 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2607 result = OC_STACK_INVALID_PARAM;
2611 /* If not original behavior, use destination argument */
2612 if (destination && !devAddr)
2614 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2617 result = OC_STACK_NO_MEMORY;
2620 *devAddr = *destination;
2623 resHandle = GenerateInvocationHandle();
2626 result = OC_STACK_NO_MEMORY;
2630 caResult = CAGenerateToken(&token, tokenLength);
2631 if (caResult != CA_STATUS_OK)
2633 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2634 result= OC_STACK_ERROR;
2638 // fill in request data
2639 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2640 requestInfo.info.token = token;
2641 requestInfo.info.tokenLength = tokenLength;
2642 requestInfo.info.resourceUri = resourceUri;
2644 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2646 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2647 options, numOptions, OC_OBSERVE_REGISTER);
2648 if (result != OC_STACK_OK)
2652 requestInfo.info.numOptions = numOptions + 1;
2656 requestInfo.info.numOptions = numOptions;
2657 requestInfo.info.options =
2658 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2659 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2660 numOptions * sizeof(CAHeaderOption_t));
2663 CopyDevAddrToEndpoint(devAddr, &endpoint);
2668 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2671 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2674 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2678 requestInfo.info.payload = NULL;
2679 requestInfo.info.payloadSize = 0;
2680 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2683 if (result != OC_STACK_OK)
2685 OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2689 // prepare for response
2690 #ifdef WITH_PRESENCE
2691 if (method == OC_REST_PRESENCE)
2693 char *presenceUri = NULL;
2694 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2695 if (OC_STACK_OK != result)
2700 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2701 // Presence notification will form a canonical uri to
2702 // look for callbacks into the application.
2703 resourceUri = presenceUri;
2707 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2708 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2709 method, devAddr, resourceUri, resourceType, ttl);
2710 if (OC_STACK_OK != result)
2715 devAddr = NULL; // Client CB list entry now owns it
2716 resourceUri = NULL; // Client CB list entry now owns it
2717 resourceType = NULL; // Client CB list entry now owns it
2720 result = OCSendRequest(&endpoint, &requestInfo);
2721 if (OC_STACK_OK != result)
2728 *handle = resHandle;
2732 if (result != OC_STACK_OK)
2734 OIC_LOG(ERROR, TAG, "OCDoResource error");
2735 FindAndDeleteClientCB(clientCB);
2736 CADestroyToken(token);
2744 // This is the owner of the payload object, so we free it
2745 OCPayloadDestroy(payload);
2746 OICFree(requestInfo.info.payload);
2748 OICFree(resourceUri);
2749 OICFree(resourceType);
2750 OICFree(requestInfo.info.options);
2754 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2758 * This ftn is implemented one of two ways in the case of observation:
2760 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2761 * Remove the callback associated on client side.
2762 * When the next notification comes in from server,
2763 * reply with RESET message to server.
2764 * Keep in mind that the server will react to RESET only
2765 * if the last notification was sent as CON
2767 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2768 * and it is associated with an observe request
2769 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2770 * Send CON Observe request to server with
2771 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2772 * Remove the callback associated on client side.
2774 OCStackResult ret = OC_STACK_OK;
2775 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2776 CARequestInfo_t requestInfo = {.method = CA_GET};
2780 return OC_STACK_INVALID_PARAM;
2783 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2786 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2787 return OC_STACK_ERROR;
2790 switch (clientCB->method)
2792 case OC_REST_OBSERVE:
2793 case OC_REST_OBSERVE_ALL:
2795 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2797 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2799 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2801 FindAndDeleteClientCB(clientCB);
2805 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2807 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2808 requestInfo.info.token = clientCB->token;
2809 requestInfo.info.tokenLength = clientCB->tokenLength;
2811 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2812 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2814 return OC_STACK_ERROR;
2816 requestInfo.info.numOptions = numOptions + 1;
2817 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2820 ret = OCSendRequest(&endpoint, &requestInfo);
2822 if (requestInfo.info.options)
2824 OICFree (requestInfo.info.options);
2826 if (requestInfo.info.resourceUri)
2828 OICFree (requestInfo.info.resourceUri);
2833 case OC_REST_DISCOVER:
2834 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2835 clientCB->requestUri);
2836 FindAndDeleteClientCB(clientCB);
2839 #ifdef WITH_PRESENCE
2840 case OC_REST_PRESENCE:
2841 FindAndDeleteClientCB(clientCB);
2846 ret = OC_STACK_INVALID_METHOD;
2854 * @brief Register Persistent storage callback.
2855 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2857 * OC_STACK_OK - No errors; Success
2858 * OC_STACK_INVALID_PARAM - Invalid parameter
2860 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2862 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2863 if(!persistentStorageHandler)
2865 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2866 return OC_STACK_INVALID_PARAM;
2870 if( !persistentStorageHandler->open ||
2871 !persistentStorageHandler->close ||
2872 !persistentStorageHandler->read ||
2873 !persistentStorageHandler->unlink ||
2874 !persistentStorageHandler->write)
2876 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2877 return OC_STACK_INVALID_PARAM;
2880 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2883 #ifdef WITH_PRESENCE
2885 OCStackResult OCProcessPresence()
2887 OCStackResult result = OC_STACK_OK;
2889 // the following line floods the log with messages that are irrelevant
2890 // to most purposes. Uncomment as needed.
2891 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2892 ClientCB* cbNode = NULL;
2893 OCClientResponse clientResponse;
2894 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2896 LL_FOREACH(cbList, cbNode)
2898 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2903 uint32_t now = GetTicks(0);
2904 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2905 cbNode->presence->TTLlevel);
2906 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2908 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2913 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2915 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2916 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2918 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2920 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2922 clientResponse.sequenceNumber = 0;
2923 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2924 clientResponse.devAddr = *cbNode->devAddr;
2925 FixUpClientResponse(&clientResponse);
2926 clientResponse.payload = NULL;
2928 // Increment the TTLLevel (going to a next state), so we don't keep
2929 // sending presence notification to client.
2930 cbNode->presence->TTLlevel++;
2931 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2932 cbNode->presence->TTLlevel);
2934 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2935 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2937 FindAndDeleteClientCB(cbNode);
2941 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2946 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2947 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2948 CARequestInfo_t requestInfo = {.method = CA_GET};
2950 OIC_LOG(DEBUG, TAG, "time to test server presence");
2952 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2954 requestData.type = CA_MSG_NONCONFIRM;
2955 requestData.token = cbNode->token;
2956 requestData.tokenLength = cbNode->tokenLength;
2957 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2958 requestInfo.method = CA_GET;
2959 requestInfo.info = requestData;
2961 result = OCSendRequest(&endpoint, &requestInfo);
2962 if (OC_STACK_OK != result)
2967 cbNode->presence->TTLlevel++;
2968 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2971 if (result != OC_STACK_OK)
2973 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2978 #endif // WITH_PRESENCE
2980 OCStackResult OCProcess()
2982 #ifdef WITH_PRESENCE
2983 OCProcessPresence();
2985 CAHandleRequestResponse();
2987 #ifdef ROUTING_GATEWAY
2997 #ifdef WITH_PRESENCE
2998 OCStackResult OCStartPresence(const uint32_t ttl)
3000 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3001 OCChangeResourceProperty(
3002 &(((OCResource *)presenceResource.handle)->resourceProperties),
3005 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3007 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3008 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3012 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3013 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3017 presenceResource.presenceTTL = ttl;
3019 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3021 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3023 presenceState = OC_PRESENCE_INITIALIZED;
3025 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3027 CAToken_t caToken = NULL;
3028 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3029 if (caResult != CA_STATUS_OK)
3031 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3032 CADestroyToken(caToken);
3033 return OC_STACK_ERROR;
3036 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3037 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3038 CADestroyToken(caToken);
3041 // Each time OCStartPresence is called
3042 // a different random 32-bit integer number is used
3043 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3045 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3046 OC_PRESENCE_TRIGGER_CREATE);
3049 OCStackResult OCStopPresence()
3051 OCStackResult result = OC_STACK_ERROR;
3053 if(presenceResource.handle)
3055 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3057 // make resource inactive
3058 result = OCChangeResourceProperty(
3059 &(((OCResource *) presenceResource.handle)->resourceProperties),
3063 if(result != OC_STACK_OK)
3066 "Changing the presence resource properties to ACTIVE not successful");
3070 return SendStopNotification();
3074 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3075 void* callbackParameter)
3077 defaultDeviceHandler = entityHandler;
3078 defaultDeviceHandlerCallbackParameter = callbackParameter;
3083 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3085 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3087 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3089 if (validatePlatformInfo(platformInfo))
3091 return SavePlatformInfo(platformInfo);
3095 return OC_STACK_INVALID_PARAM;
3100 return OC_STACK_ERROR;
3104 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3106 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3108 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3110 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3111 return OC_STACK_INVALID_PARAM;
3114 if (deviceInfo.types)
3116 OCStringLL *type = deviceInfo.types;
3117 OCResource *resource = findResource((OCResource *) deviceResource);
3120 return OC_STACK_INVALID_PARAM;
3122 deleteResourceType(resource->rsrcType);
3123 resource->rsrcType = NULL;
3127 OCBindResourceTypeToResource(deviceResource, type->value);
3131 return SaveDeviceInfo(deviceInfo);
3134 OCStackResult OCCreateResource(OCResourceHandle *handle,
3135 const char *resourceTypeName,
3136 const char *resourceInterfaceName,
3137 const char *uri, OCEntityHandler entityHandler,
3138 void* callbackParam,
3139 uint8_t resourceProperties)
3142 OCResource *pointer = NULL;
3143 OCStackResult result = OC_STACK_ERROR;
3145 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3147 if(myStackMode == OC_CLIENT)
3149 return OC_STACK_INVALID_PARAM;
3151 // Validate parameters
3152 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3154 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3155 return OC_STACK_INVALID_URI;
3157 // Is it presented during resource discovery?
3158 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3160 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3161 return OC_STACK_INVALID_PARAM;
3164 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3166 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3169 // Make sure resourceProperties bitmask has allowed properties specified
3170 if (resourceProperties
3171 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3172 OC_EXPLICIT_DISCOVERABLE))
3174 OIC_LOG(ERROR, TAG, "Invalid property");
3175 return OC_STACK_INVALID_PARAM;
3178 // If the headResource is NULL, then no resources have been created...
3179 pointer = headResource;
3182 // At least one resources is in the resource list, so we need to search for
3183 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3186 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3188 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3189 return OC_STACK_INVALID_PARAM;
3191 pointer = pointer->next;
3194 // Create the pointer and insert it into the resource list
3195 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3198 result = OC_STACK_NO_MEMORY;
3201 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3203 insertResource(pointer);
3206 pointer->uri = OICStrdup(uri);
3209 result = OC_STACK_NO_MEMORY;
3213 // Set properties. Set OC_ACTIVE
3214 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3217 // Add the resourcetype to the resource
3218 result = BindResourceTypeToResource(pointer, resourceTypeName);
3219 if (result != OC_STACK_OK)
3221 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3225 // Add the resourceinterface to the resource
3226 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3227 if (result != OC_STACK_OK)
3229 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3233 // If an entity handler has been passed, attach it to the newly created
3234 // resource. Otherwise, set the default entity handler.
3237 pointer->entityHandler = entityHandler;
3238 pointer->entityHandlerCallbackParam = callbackParam;
3242 pointer->entityHandler = defaultResourceEHandler;
3243 pointer->entityHandlerCallbackParam = NULL;
3246 // Initialize a pointer indicating child resources in case of collection
3247 pointer->rsrcChildResourcesHead = NULL;
3250 result = OC_STACK_OK;
3252 #ifdef WITH_PRESENCE
3253 if (presenceResource.handle)
3255 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3256 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3260 if (result != OC_STACK_OK)
3262 // Deep delete of resource and other dynamic elements that it contains
3263 deleteResource(pointer);
3268 OCStackResult OCBindResource(
3269 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3271 OCResource *resource = NULL;
3272 OCChildResource *tempChildResource = NULL;
3273 OCChildResource *newChildResource = NULL;
3275 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3277 // Validate parameters
3278 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3279 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3280 // Container cannot contain itself
3281 if (collectionHandle == resourceHandle)
3283 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3284 return OC_STACK_INVALID_PARAM;
3287 // Use the handle to find the resource in the resource linked list
3288 resource = findResource((OCResource *) collectionHandle);
3291 OIC_LOG(ERROR, TAG, "Collection handle not found");
3292 return OC_STACK_INVALID_PARAM;
3295 // Look for an open slot to add add the child resource.
3296 // If found, add it and return success
3298 tempChildResource = resource->rsrcChildResourcesHead;
3300 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3302 // TODO: what if one of child resource was deregistered without unbinding?
3303 tempChildResource = tempChildResource->next;
3306 // Do memory allocation for child resource
3307 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3308 if(!newChildResource)
3310 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3311 return OC_STACK_ERROR;
3314 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3315 newChildResource->next = NULL;
3317 if(!resource->rsrcChildResourcesHead)
3319 resource->rsrcChildResourcesHead = newChildResource;
3322 tempChildResource->next = newChildResource;
3325 OIC_LOG(INFO, TAG, "resource bound");
3327 #ifdef WITH_PRESENCE
3328 if (presenceResource.handle)
3330 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3331 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3332 OC_PRESENCE_TRIGGER_CHANGE);
3339 OCStackResult OCUnBindResource(
3340 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3342 OCResource *resource = NULL;
3343 OCChildResource *tempChildResource = NULL;
3344 OCChildResource *tempLastChildResource = NULL;
3346 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3348 // Validate parameters
3349 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3350 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3351 // Container cannot contain itself
3352 if (collectionHandle == resourceHandle)
3354 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3355 return OC_STACK_INVALID_PARAM;
3358 // Use the handle to find the resource in the resource linked list
3359 resource = findResource((OCResource *) collectionHandle);
3362 OIC_LOG(ERROR, TAG, "Collection handle not found");
3363 return OC_STACK_INVALID_PARAM;
3366 // Look for an open slot to add add the child resource.
3367 // If found, add it and return success
3368 if(!resource->rsrcChildResourcesHead)
3370 OIC_LOG(INFO, TAG, "resource not found in collection");
3372 // Unable to add resourceHandle, so return error
3373 return OC_STACK_ERROR;
3377 tempChildResource = resource->rsrcChildResourcesHead;
3379 while (tempChildResource)
3381 if(tempChildResource->rsrcResource == resourceHandle)
3383 // if resource going to be unbinded is the head one.
3384 if( tempChildResource == resource->rsrcChildResourcesHead )
3386 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3387 OICFree(resource->rsrcChildResourcesHead);
3388 resource->rsrcChildResourcesHead = temp;
3393 OCChildResource *temp = tempChildResource->next;
3394 OICFree(tempChildResource);
3395 tempLastChildResource->next = temp;
3399 OIC_LOG(INFO, TAG, "resource unbound");
3401 // Send notification when resource is unbounded successfully.
3402 #ifdef WITH_PRESENCE
3403 if (presenceResource.handle)
3405 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3406 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3407 OC_PRESENCE_TRIGGER_CHANGE);
3410 tempChildResource = NULL;
3411 tempLastChildResource = NULL;
3417 tempLastChildResource = tempChildResource;
3418 tempChildResource = tempChildResource->next;
3421 OIC_LOG(INFO, TAG, "resource not found in collection");
3423 tempChildResource = NULL;
3424 tempLastChildResource = NULL;
3426 // Unable to add resourceHandle, so return error
3427 return OC_STACK_ERROR;
3430 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3432 if (!resourceItemName)
3436 // Per RFC 6690 only registered values must follow the first rule below.
3437 // At this point in time the only values registered begin with "core", and
3438 // all other values are specified as opaque strings where multiple values
3439 // are separated by a space.
3440 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3442 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3444 if (resourceItemName[index] != '.'
3445 && resourceItemName[index] != '-'
3446 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3447 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3455 for (size_t index = 0; resourceItemName[index]; ++index)
3457 if (resourceItemName[index] == ' '
3458 || resourceItemName[index] == '\t'
3459 || resourceItemName[index] == '\r'
3460 || resourceItemName[index] == '\n')
3470 OCStackResult BindResourceTypeToResource(OCResource* resource,
3471 const char *resourceTypeName)
3473 OCResourceType *pointer = NULL;
3475 OCStackResult result = OC_STACK_ERROR;
3477 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3479 if (!ValidateResourceTypeInterface(resourceTypeName))
3481 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3482 return OC_STACK_INVALID_PARAM;
3485 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3488 result = OC_STACK_NO_MEMORY;
3492 str = OICStrdup(resourceTypeName);
3495 result = OC_STACK_NO_MEMORY;
3498 pointer->resourcetypename = str;
3499 pointer->next = NULL;
3501 insertResourceType(resource, pointer);
3502 result = OC_STACK_OK;
3505 if (result != OC_STACK_OK)
3514 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3515 const char *resourceInterfaceName)
3517 OCResourceInterface *pointer = NULL;
3519 OCStackResult result = OC_STACK_ERROR;
3521 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3523 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3525 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3526 return OC_STACK_INVALID_PARAM;
3529 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3531 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3534 result = OC_STACK_NO_MEMORY;
3538 str = OICStrdup(resourceInterfaceName);
3541 result = OC_STACK_NO_MEMORY;
3544 pointer->name = str;
3546 // Bind the resourceinterface to the resource
3547 insertResourceInterface(resource, pointer);
3549 result = OC_STACK_OK;
3552 if (result != OC_STACK_OK)
3561 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3562 const char *resourceTypeName)
3565 OCStackResult result = OC_STACK_ERROR;
3566 OCResource *resource = NULL;
3568 resource = findResource((OCResource *) handle);
3571 OIC_LOG(ERROR, TAG, "Resource not found");
3572 return OC_STACK_ERROR;
3575 result = BindResourceTypeToResource(resource, resourceTypeName);
3577 #ifdef WITH_PRESENCE
3578 if(presenceResource.handle)
3580 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3581 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3588 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3589 const char *resourceInterfaceName)
3592 OCStackResult result = OC_STACK_ERROR;
3593 OCResource *resource = NULL;
3595 resource = findResource((OCResource *) handle);
3598 OIC_LOG(ERROR, TAG, "Resource not found");
3599 return OC_STACK_ERROR;
3602 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3604 #ifdef WITH_PRESENCE
3605 if (presenceResource.handle)
3607 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3608 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3615 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3617 OCResource *pointer = headResource;
3619 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3623 *numResources = *numResources + 1;
3624 pointer = pointer->next;
3629 OCResourceHandle OCGetResourceHandle(uint8_t index)
3631 OCResource *pointer = headResource;
3633 for( uint8_t i = 0; i < index && pointer; ++i)
3635 pointer = pointer->next;
3637 return (OCResourceHandle) pointer;
3640 OCStackResult OCDeleteResource(OCResourceHandle handle)
3644 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3645 return OC_STACK_INVALID_PARAM;
3648 OCResource *resource = findResource((OCResource *) handle);
3649 if (resource == NULL)
3651 OIC_LOG(ERROR, TAG, "Resource not found");
3652 return OC_STACK_NO_RESOURCE;
3655 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3657 OIC_LOG(ERROR, TAG, "Error deleting resource");
3658 return OC_STACK_ERROR;
3664 const char *OCGetResourceUri(OCResourceHandle handle)
3666 OCResource *resource = NULL;
3668 resource = findResource((OCResource *) handle);
3671 return resource->uri;
3673 return (const char *) NULL;
3676 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3678 OCResource *resource = NULL;
3680 resource = findResource((OCResource *) handle);
3683 return resource->resourceProperties;
3685 return (OCResourceProperty)-1;
3688 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3689 uint8_t *numResourceTypes)
3691 OCResource *resource = NULL;
3692 OCResourceType *pointer = NULL;
3694 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3695 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3697 *numResourceTypes = 0;
3699 resource = findResource((OCResource *) handle);
3702 pointer = resource->rsrcType;
3705 *numResourceTypes = *numResourceTypes + 1;
3706 pointer = pointer->next;
3712 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3714 OCResourceType *resourceType = NULL;
3716 resourceType = findResourceTypeAtIndex(handle, index);
3719 return resourceType->resourcetypename;
3721 return (const char *) NULL;
3724 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3725 uint8_t *numResourceInterfaces)
3727 OCResourceInterface *pointer = NULL;
3728 OCResource *resource = NULL;
3730 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3731 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3733 *numResourceInterfaces = 0;
3734 resource = findResource((OCResource *) handle);
3737 pointer = resource->rsrcInterface;
3740 *numResourceInterfaces = *numResourceInterfaces + 1;
3741 pointer = pointer->next;
3747 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3749 OCResourceInterface *resourceInterface = NULL;
3751 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3752 if (resourceInterface)
3754 return resourceInterface->name;
3756 return (const char *) NULL;
3759 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3762 OCResource *resource = NULL;
3763 OCChildResource *tempChildResource = NULL;
3766 resource = findResource((OCResource *) collectionHandle);
3772 tempChildResource = resource->rsrcChildResourcesHead;
3774 while(tempChildResource)
3778 return tempChildResource->rsrcResource;
3781 tempChildResource = tempChildResource->next;
3784 // In this case, the number of resource handles in the collection exceeds the index
3785 tempChildResource = NULL;
3789 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3790 OCEntityHandler entityHandler,
3791 void* callbackParam)
3793 OCResource *resource = NULL;
3795 // Validate parameters
3796 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3798 // Use the handle to find the resource in the resource linked list
3799 resource = findResource((OCResource *)handle);
3802 OIC_LOG(ERROR, TAG, "Resource not found");
3803 return OC_STACK_ERROR;
3807 resource->entityHandler = entityHandler;
3808 resource->entityHandlerCallbackParam = callbackParam;
3810 #ifdef WITH_PRESENCE
3811 if (presenceResource.handle)
3813 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3814 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3821 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3823 OCResource *resource = NULL;
3825 resource = findResource((OCResource *)handle);
3828 OIC_LOG(ERROR, TAG, "Resource not found");
3833 return resource->entityHandler;
3836 void incrementSequenceNumber(OCResource * resPtr)
3838 // Increment the sequence number
3839 resPtr->sequenceNum += 1;
3840 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3842 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3847 #ifdef WITH_PRESENCE
3848 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3849 OCPresenceTrigger trigger)
3851 OCResource *resPtr = NULL;
3852 OCStackResult result = OC_STACK_ERROR;
3853 OCMethod method = OC_REST_PRESENCE;
3854 uint32_t maxAge = 0;
3855 resPtr = findResource((OCResource *) presenceResource.handle);
3858 return OC_STACK_NO_RESOURCE;
3861 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3863 maxAge = presenceResource.presenceTTL;
3865 result = SendAllObserverNotification(method, resPtr, maxAge,
3866 trigger, resourceType, OC_LOW_QOS);
3872 OCStackResult SendStopNotification()
3874 OCResource *resPtr = NULL;
3875 OCStackResult result = OC_STACK_ERROR;
3876 OCMethod method = OC_REST_PRESENCE;
3877 resPtr = findResource((OCResource *) presenceResource.handle);
3880 return OC_STACK_NO_RESOURCE;
3883 // maxAge is 0. ResourceType is NULL.
3884 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3890 #endif // WITH_PRESENCE
3891 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3893 OCResource *resPtr = NULL;
3894 OCStackResult result = OC_STACK_ERROR;
3895 OCMethod method = OC_REST_NOMETHOD;
3896 uint32_t maxAge = 0;
3898 OIC_LOG(INFO, TAG, "Notifying all observers");
3899 #ifdef WITH_PRESENCE
3900 if(handle == presenceResource.handle)
3904 #endif // WITH_PRESENCE
3905 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3907 // Verify that the resource exists
3908 resPtr = findResource ((OCResource *) handle);
3911 return OC_STACK_NO_RESOURCE;
3915 //only increment in the case of regular observing (not presence)
3916 incrementSequenceNumber(resPtr);
3917 method = OC_REST_OBSERVE;
3918 maxAge = MAX_OBSERVE_AGE;
3919 #ifdef WITH_PRESENCE
3920 result = SendAllObserverNotification (method, resPtr, maxAge,
3921 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3923 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3930 OCNotifyListOfObservers (OCResourceHandle handle,
3931 OCObservationId *obsIdList,
3932 uint8_t numberOfIds,
3933 const OCRepPayload *payload,
3934 OCQualityOfService qos)
3936 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3938 OCResource *resPtr = NULL;
3939 //TODO: we should allow the server to define this
3940 uint32_t maxAge = MAX_OBSERVE_AGE;
3942 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3943 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3944 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3946 resPtr = findResource ((OCResource *) handle);
3947 if (NULL == resPtr || myStackMode == OC_CLIENT)
3949 return OC_STACK_NO_RESOURCE;
3953 incrementSequenceNumber(resPtr);
3955 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3956 payload, maxAge, qos));
3959 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3961 OCStackResult result = OC_STACK_ERROR;
3962 OCServerRequest *serverRequest = NULL;
3964 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3966 // Validate input parameters
3967 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3968 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3971 // Get pointer to request info
3972 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3975 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3976 result = serverRequest->ehResponseHandler(ehResponse);
3982 //#ifdef DIRECT_PAIRING
3983 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3985 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3986 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3988 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3992 return (const OCDPDev_t*)DPGetDiscoveredDevices();
3995 const OCDPDev_t* OCGetDirectPairedDevices()
3997 return (const OCDPDev_t*)DPGetPairedDevices();
4000 void DirectPairingCB (OCDirectPairingDev_t * peer, OCStackResult result)
4002 if (gDirectpairingCallback)
4004 gDirectpairingCallback((OCDPDev_t*)peer, result);
4005 gDirectpairingCallback = NULL;
4009 OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4010 OCDirectPairingCB resultCallback)
4012 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4013 if(NULL == peer || NULL == pinNumber)
4015 OIC_LOG(ERROR, TAG, "Invalid parameters");
4016 return OC_STACK_INVALID_PARAM;
4018 if (NULL == resultCallback)
4020 OIC_LOG(ERROR, TAG, "Invalid callback");
4021 return OC_STACK_INVALID_CALLBACK;
4024 gDirectpairingCallback = resultCallback;
4025 return DPDirectPairing((OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4026 pinNumber, DirectPairingCB);
4028 //#endif // DIRECT_PAIRING
4030 //-----------------------------------------------------------------------------
4031 // Private internal function definitions
4032 //-----------------------------------------------------------------------------
4033 static OCDoHandle GenerateInvocationHandle()
4035 OCDoHandle handle = NULL;
4036 // Generate token here, it will be deleted when the transaction is deleted
4037 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4040 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4046 #ifdef WITH_PRESENCE
4047 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4048 OCResourceProperty resourceProperties, uint8_t enable)
4052 return OC_STACK_INVALID_PARAM;
4054 if (resourceProperties
4055 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4057 OIC_LOG(ERROR, TAG, "Invalid property");
4058 return OC_STACK_INVALID_PARAM;
4062 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4066 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4072 OCStackResult initResources()
4074 OCStackResult result = OC_STACK_OK;
4076 headResource = NULL;
4077 tailResource = NULL;
4078 // Init Virtual Resources
4079 #ifdef WITH_PRESENCE
4080 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4082 result = OCCreateResource(&presenceResource.handle,
4083 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4085 OC_RSRVD_PRESENCE_URI,
4089 //make resource inactive
4090 result = OCChangeResourceProperty(
4091 &(((OCResource *) presenceResource.handle)->resourceProperties),
4094 #ifndef WITH_ARDUINO
4095 if (result == OC_STACK_OK)
4097 result = SRMInitSecureResources();
4101 if(result == OC_STACK_OK)
4103 result = OCCreateResource(&deviceResource,
4104 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4105 OC_RSRVD_INTERFACE_DEFAULT,
4106 OC_RSRVD_DEVICE_URI,
4110 if(result == OC_STACK_OK)
4112 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4113 OC_RSRVD_INTERFACE_READ);
4117 if(result == OC_STACK_OK)
4119 result = OCCreateResource(&platformResource,
4120 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4121 OC_RSRVD_INTERFACE_DEFAULT,
4122 OC_RSRVD_PLATFORM_URI,
4126 if(result == OC_STACK_OK)
4128 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4129 OC_RSRVD_INTERFACE_READ);
4136 void insertResource(OCResource *resource)
4140 headResource = resource;
4141 tailResource = resource;
4145 tailResource->next = resource;
4146 tailResource = resource;
4148 resource->next = NULL;
4151 OCResource *findResource(OCResource *resource)
4153 OCResource *pointer = headResource;
4157 if (pointer == resource)
4161 pointer = pointer->next;
4166 void deleteAllResources()
4168 OCResource *pointer = headResource;
4169 OCResource *temp = NULL;
4173 temp = pointer->next;
4174 #ifdef WITH_PRESENCE
4175 if (pointer != (OCResource *) presenceResource.handle)
4177 #endif // WITH_PRESENCE
4178 deleteResource(pointer);
4179 #ifdef WITH_PRESENCE
4181 #endif // WITH_PRESENCE
4185 SRMDeInitSecureResources();
4187 #ifdef WITH_PRESENCE
4188 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4189 // presence notification attributed to their deletion to be processed.
4190 deleteResource((OCResource *) presenceResource.handle);
4191 #endif // WITH_PRESENCE
4194 OCStackResult deleteResource(OCResource *resource)
4196 OCResource *prev = NULL;
4197 OCResource *temp = NULL;
4200 OIC_LOG(DEBUG,TAG,"resource is NULL");
4201 return OC_STACK_INVALID_PARAM;
4204 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4206 temp = headResource;
4209 if (temp == resource)
4211 // Invalidate all Resource Properties.
4212 resource->resourceProperties = (OCResourceProperty) 0;
4213 #ifdef WITH_PRESENCE
4214 if(resource != (OCResource *) presenceResource.handle)
4216 #endif // WITH_PRESENCE
4217 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4218 #ifdef WITH_PRESENCE
4221 if(presenceResource.handle)
4223 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4224 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4227 // Only resource in list.
4228 if (temp == headResource && temp == tailResource)
4230 headResource = NULL;
4231 tailResource = NULL;
4234 else if (temp == headResource)
4236 headResource = temp->next;
4239 else if (temp == tailResource)
4241 tailResource = prev;
4242 tailResource->next = NULL;
4246 prev->next = temp->next;
4249 deleteResourceElements(temp);
4260 return OC_STACK_ERROR;
4263 void deleteResourceElements(OCResource *resource)
4270 OICFree(resource->uri);
4271 deleteResourceType(resource->rsrcType);
4272 deleteResourceInterface(resource->rsrcInterface);
4275 void deleteResourceType(OCResourceType *resourceType)
4277 OCResourceType *pointer = resourceType;
4278 OCResourceType *next = NULL;
4282 next = pointer->next;
4283 OICFree(pointer->resourcetypename);
4289 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4291 OCResourceInterface *pointer = resourceInterface;
4292 OCResourceInterface *next = NULL;
4296 next = pointer->next;
4297 OICFree(pointer->name);
4303 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4305 OCResourceType *pointer = NULL;
4306 OCResourceType *previous = NULL;
4307 if (!resource || !resourceType)
4311 // resource type list is empty.
4312 else if (!resource->rsrcType)
4314 resource->rsrcType = resourceType;
4318 pointer = resource->rsrcType;
4322 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4324 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4325 OICFree(resourceType->resourcetypename);
4326 OICFree(resourceType);
4330 pointer = pointer->next;
4335 previous->next = resourceType;
4338 resourceType->next = NULL;
4340 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4343 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4345 OCResource *resource = NULL;
4346 OCResourceType *pointer = NULL;
4348 // Find the specified resource
4349 resource = findResource((OCResource *) handle);
4355 // Make sure a resource has a resourcetype
4356 if (!resource->rsrcType)
4361 // Iterate through the list
4362 pointer = resource->rsrcType;
4363 for(uint8_t i = 0; i< index && pointer; ++i)
4365 pointer = pointer->next;
4370 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4372 if(resourceTypeList && resourceTypeName)
4374 OCResourceType * rtPointer = resourceTypeList;
4375 while(resourceTypeName && rtPointer)
4377 if(rtPointer->resourcetypename &&
4378 strcmp(resourceTypeName, (const char *)
4379 (rtPointer->resourcetypename)) == 0)
4383 rtPointer = rtPointer->next;
4391 * Insert a new interface into interface linked list only if not already present.
4392 * If alredy present, 2nd arg is free'd.
4393 * Default interface will always be first if present.
4395 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4397 OCResourceInterface *pointer = NULL;
4398 OCResourceInterface *previous = NULL;
4400 newInterface->next = NULL;
4402 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4404 if (!*firstInterface)
4406 // If first interface is not oic.if.baseline, by default add it as first interface type.
4407 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4409 *firstInterface = newInterface;
4413 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4414 if (result != OC_STACK_OK)
4416 OICFree(newInterface->name);
4417 OICFree(newInterface);
4420 if (*firstInterface)
4422 (*firstInterface)->next = newInterface;
4426 // If once add oic.if.baseline, later too below code take care of freeing memory.
4427 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4429 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4431 OICFree(newInterface->name);
4432 OICFree(newInterface);
4435 // This code will not hit anymore, keeping
4438 newInterface->next = *firstInterface;
4439 *firstInterface = newInterface;
4444 pointer = *firstInterface;
4447 if (strcmp(newInterface->name, pointer->name) == 0)
4449 OICFree(newInterface->name);
4450 OICFree(newInterface);
4454 pointer = pointer->next;
4456 previous->next = newInterface;
4460 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4463 OCResource *resource = NULL;
4464 OCResourceInterface *pointer = NULL;
4466 // Find the specified resource
4467 resource = findResource((OCResource *) handle);
4473 // Make sure a resource has a resourceinterface
4474 if (!resource->rsrcInterface)
4479 // Iterate through the list
4480 pointer = resource->rsrcInterface;
4482 for (uint8_t i = 0; i < index && pointer; ++i)
4484 pointer = pointer->next;
4490 * This function splits the uri using the '?' delimiter.
4491 * "uriWithoutQuery" is the block of characters between the beginning
4492 * till the delimiter or '\0' which ever comes first.
4493 * "query" is whatever is to the right of the delimiter if present.
4494 * No delimiter sets the query to NULL.
4495 * If either are present, they will be malloc'ed into the params 2, 3.
4496 * The first param, *uri is left untouched.
4498 * NOTE: This function does not account for whitespace at the end of the uri NOR
4499 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4500 * part of the query.
4502 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4506 return OC_STACK_INVALID_URI;
4508 if(!query || !uriWithoutQuery)
4510 return OC_STACK_INVALID_PARAM;
4514 *uriWithoutQuery = NULL;
4516 size_t uriWithoutQueryLen = 0;
4517 size_t queryLen = 0;
4518 size_t uriLen = strlen(uri);
4520 char *pointerToDelimiter = strstr(uri, "?");
4522 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4523 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4525 if (uriWithoutQueryLen)
4527 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4528 if (!*uriWithoutQuery)
4532 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4536 *query = (char *) OICCalloc(queryLen + 1, 1);
4539 OICFree(*uriWithoutQuery);
4540 *uriWithoutQuery = NULL;
4543 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4549 return OC_STACK_NO_MEMORY;
4552 static const OicUuid_t* OCGetServerInstanceID(void)
4554 static bool generated = false;
4555 static OicUuid_t sid;
4561 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4563 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4570 const char* OCGetServerInstanceIDString(void)
4572 static bool generated = false;
4573 static char sidStr[UUID_STRING_SIZE];
4580 const OicUuid_t *sid = OCGetServerInstanceID();
4581 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4583 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4591 CAResult_t OCSelectNetwork()
4593 CAResult_t retResult = CA_STATUS_FAILED;
4594 CAResult_t caResult = CA_STATUS_OK;
4596 CATransportAdapter_t connTypes[] = {
4598 CA_ADAPTER_RFCOMM_BTEDR,
4599 CA_ADAPTER_GATT_BTLE,
4602 ,CA_ADAPTER_REMOTE_ACCESS
4609 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4611 for(int i = 0; i<numConnTypes; i++)
4613 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4614 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4616 caResult = CASelectNetwork(connTypes[i]);
4617 if(caResult == CA_STATUS_OK)
4619 retResult = CA_STATUS_OK;
4624 if(retResult != CA_STATUS_OK)
4626 return caResult; // Returns error of appropriate transport that failed fatally.
4632 OCStackResult CAResultToOCResult(CAResult_t caResult)
4638 case CA_STATUS_INVALID_PARAM:
4639 return OC_STACK_INVALID_PARAM;
4640 case CA_ADAPTER_NOT_ENABLED:
4641 return OC_STACK_ADAPTER_NOT_ENABLED;
4642 case CA_SERVER_STARTED_ALREADY:
4644 case CA_SERVER_NOT_STARTED:
4645 return OC_STACK_ERROR;
4646 case CA_DESTINATION_NOT_REACHABLE:
4647 return OC_STACK_COMM_ERROR;
4648 case CA_SOCKET_OPERATION_FAILED:
4649 return OC_STACK_COMM_ERROR;
4650 case CA_SEND_FAILED:
4651 return OC_STACK_COMM_ERROR;
4652 case CA_RECEIVE_FAILED:
4653 return OC_STACK_COMM_ERROR;
4654 case CA_MEMORY_ALLOC_FAILED:
4655 return OC_STACK_NO_MEMORY;
4656 case CA_REQUEST_TIMEOUT:
4657 return OC_STACK_TIMEOUT;
4658 case CA_DESTINATION_DISCONNECTED:
4659 return OC_STACK_COMM_ERROR;
4660 case CA_STATUS_FAILED:
4661 return OC_STACK_ERROR;
4662 case CA_NOT_SUPPORTED:
4663 return OC_STACK_NOTIMPL;
4665 return OC_STACK_ERROR;