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 * Attempts to initialize every network interface that the CA Layer might have compiled in.
286 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
287 * return something other than @ref CA_STATUS_OK, then this function fails.
289 * @return ::CA_STATUS_OK on success, some other value upon failure.
291 static CAResult_t OCSelectNetwork();
294 * Get the CoAP ticks after the specified number of milli-seconds.
296 * @param afterMilliSeconds Milli-seconds.
300 static uint32_t GetTicks(uint32_t afterMilliSeconds);
303 * Convert CAResult_t to OCStackResult.
305 * @param caResult CAResult_t code.
306 * @return ::OC_STACK_OK on success, some other value upon failure.
308 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
311 * Convert CAResponseResult_t to OCStackResult.
313 * @param caCode CAResponseResult_t code.
314 * @return ::OC_STACK_OK on success, some other value upon failure.
316 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
319 * Convert OCStackResult to CAResponseResult_t.
321 * @param caCode OCStackResult code.
322 * @param method OCMethod method the return code replies to.
323 * @return ::CA_CONTENT on OK, some other value upon failure.
325 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
328 * Convert OCTransportFlags_t to CATransportModifiers_t.
330 * @param ocConType OCTransportFlags_t input.
331 * @return CATransportFlags
333 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
336 * Convert CATransportFlags_t to OCTransportModifiers_t.
338 * @param caConType CATransportFlags_t input.
339 * @return OCTransportFlags
341 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
344 * Handle response from presence request.
346 * @param endPoint CA remote endpoint.
347 * @param responseInfo CA response info.
348 * @return ::OC_STACK_OK on success, some other value upon failure.
350 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
351 const CAResponseInfo_t *responseInfo);
354 * This function will be called back by CA layer when a response is received.
356 * @param endPoint CA remote endpoint.
357 * @param responseInfo CA response info.
359 static void HandleCAResponses(const CAEndpoint_t* endPoint,
360 const CAResponseInfo_t* responseInfo);
363 * This function will be called back by CA layer when a request is received.
365 * @param endPoint CA remote endpoint.
366 * @param requestInfo CA request info.
368 static void HandleCARequests(const CAEndpoint_t* endPoint,
369 const CARequestInfo_t* requestInfo);
372 * Extract query from a URI.
374 * @param uri Full URI with query.
375 * @param query Pointer to string that will contain query.
376 * @param newURI Pointer to string that will contain URI.
377 * @return ::OC_STACK_OK on success, some other value upon failure.
379 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
382 * Finds a resource type in an OCResourceType link-list.
384 * @param resourceTypeList The link-list to be searched through.
385 * @param resourceTypeName The key to search for.
387 * @return Resource type that matches the key (ie. resourceTypeName) or
388 * NULL if there is either an invalid parameter or this function was unable to find the key.
390 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
391 const char * resourceTypeName);
394 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
395 * TTL will be set to maxAge.
397 * @param cbNode Callback Node for which presence ttl is to be reset.
398 * @param maxAge New value of ttl in seconds.
400 * @return ::OC_STACK_OK on success, some other value upon failure.
402 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
405 * Ensure the accept header option is set appropriatly before sending the requests and routing
406 * header option is updated with destination.
408 * @param object CA remote endpoint.
409 * @param requestInfo CA request info.
411 * @return ::OC_STACK_OK on success, some other value upon failure.
413 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
415 //-----------------------------------------------------------------------------
416 // Internal functions
417 //-----------------------------------------------------------------------------
419 uint32_t GetTicks(uint32_t afterMilliSeconds)
424 // Guard against overflow of uint32_t
425 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
426 COAP_TICKS_PER_SECOND)
428 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
436 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
438 VERIFY_NON_NULL_NR(in, FATAL);
439 VERIFY_NON_NULL_NR(out, FATAL);
441 out->adapter = (OCTransportAdapter)in->adapter;
442 out->flags = CAToOCTransportFlags(in->flags);
443 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
444 out->port = in->port;
445 out->ifindex = in->ifindex;
446 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
447 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
451 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
453 VERIFY_NON_NULL_NR(in, FATAL);
454 VERIFY_NON_NULL_NR(out, FATAL);
456 out->adapter = (CATransportAdapter_t)in->adapter;
457 out->flags = OCToCATransportFlags(in->flags);
458 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
459 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
460 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
462 out->port = in->port;
463 out->ifindex = in->ifindex;
466 void FixUpClientResponse(OCClientResponse *cr)
468 VERIFY_NON_NULL_NR(cr, FATAL);
470 cr->addr = &cr->devAddr;
471 cr->connType = (OCConnectivityType)
472 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
475 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
477 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
478 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
480 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
481 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
482 if (OC_STACK_OK != rmResult)
484 OIC_LOG(ERROR, TAG, "Add destination option failed");
489 // OC stack prefer CBOR encoded payloads.
490 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
491 CAResult_t result = CASendRequest(object, requestInfo);
492 if(CA_STATUS_OK != result)
494 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
495 return CAResultToOCResult(result);
499 //-----------------------------------------------------------------------------
500 // Internal API function
501 //-----------------------------------------------------------------------------
503 // This internal function is called to update the stack with the status of
504 // observers and communication failures
505 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
507 OCStackResult result = OC_STACK_ERROR;
508 ResourceObserver * observer = NULL;
509 OCEntityHandlerRequest ehRequest = {0};
513 case OC_OBSERVER_NOT_INTERESTED:
514 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
515 observer = GetObserverUsingToken (token, tokenLength);
518 result = FormOCEntityHandlerRequest(&ehRequest,
519 (OCRequestHandle)NULL,
522 (OCResourceHandle)NULL,
523 NULL, PAYLOAD_TYPE_REPRESENTATION,
525 OC_OBSERVE_DEREGISTER,
526 observer->observeId);
527 if(result != OC_STACK_OK)
531 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
532 observer->resource->entityHandlerCallbackParam);
535 result = DeleteObserverUsingToken (token, tokenLength);
536 if(result == OC_STACK_OK)
538 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
542 result = OC_STACK_OK;
543 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
547 case OC_OBSERVER_STILL_INTERESTED:
548 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
549 observer = GetObserverUsingToken (token, tokenLength);
552 observer->forceHighQos = 0;
553 observer->failedCommCount = 0;
554 result = OC_STACK_OK;
558 result = OC_STACK_OBSERVER_NOT_FOUND;
562 case OC_OBSERVER_FAILED_COMM:
563 OIC_LOG(DEBUG, TAG, "observer is unreachable");
564 observer = GetObserverUsingToken (token, tokenLength);
567 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
569 result = FormOCEntityHandlerRequest(&ehRequest,
570 (OCRequestHandle)NULL,
573 (OCResourceHandle)NULL,
574 NULL, PAYLOAD_TYPE_REPRESENTATION,
576 OC_OBSERVE_DEREGISTER,
577 observer->observeId);
578 if(result != OC_STACK_OK)
580 return OC_STACK_ERROR;
582 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
583 observer->resource->entityHandlerCallbackParam);
585 result = DeleteObserverUsingToken (token, tokenLength);
586 if(result == OC_STACK_OK)
588 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
592 result = OC_STACK_OK;
593 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
598 observer->failedCommCount++;
599 result = OC_STACK_CONTINUE;
601 observer->forceHighQos = 1;
602 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
606 OIC_LOG(ERROR, TAG, "Unknown status");
607 result = OC_STACK_ERROR;
613 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
615 OCStackResult ret = OC_STACK_ERROR;
619 case CA_ADAPTER_NOT_ENABLED:
620 case CA_SERVER_NOT_STARTED:
621 ret = OC_STACK_ADAPTER_NOT_ENABLED;
623 case CA_MEMORY_ALLOC_FAILED:
624 ret = OC_STACK_NO_MEMORY;
626 case CA_STATUS_INVALID_PARAM:
627 ret = OC_STACK_INVALID_PARAM;
635 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
637 OCStackResult ret = OC_STACK_ERROR;
642 ret = OC_STACK_RESOURCE_CREATED;
645 ret = OC_STACK_RESOURCE_DELETED;
653 ret = OC_STACK_INVALID_QUERY;
655 case CA_UNAUTHORIZED_REQ:
656 ret = OC_STACK_UNAUTHORIZED_REQ;
659 ret = OC_STACK_INVALID_OPTION;
662 ret = OC_STACK_NO_RESOURCE;
664 case CA_RETRANSMIT_TIMEOUT:
665 ret = OC_STACK_COMM_ERROR;
667 case CA_REQUEST_ENTITY_TOO_LARGE:
668 ret = OC_STACK_TOO_LARGE_REQ;
676 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
678 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
687 // This Response Code is like HTTP 204 "No Content" but only used in
688 // response to POST and PUT requests.
692 // This Response Code is like HTTP 200 "OK" but only used in response to
697 // This should not happen but,
698 // give it a value just in case but output an error
700 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
703 case OC_STACK_RESOURCE_CREATED:
706 case OC_STACK_RESOURCE_DELETED:
709 case OC_STACK_INVALID_QUERY:
712 case OC_STACK_INVALID_OPTION:
715 case OC_STACK_NO_RESOURCE:
718 case OC_STACK_COMM_ERROR:
719 ret = CA_RETRANSMIT_TIMEOUT;
721 case OC_STACK_UNAUTHORIZED_REQ:
722 ret = CA_UNAUTHORIZED_REQ;
730 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
732 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
734 // supply default behavior.
735 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
737 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
739 if ((caFlags & OC_MASK_SCOPE) == 0)
741 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
746 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
748 return (OCTransportFlags)caFlags;
751 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
753 uint32_t lowerBound = 0;
754 uint32_t higherBound = 0;
756 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
758 return OC_STACK_INVALID_PARAM;
761 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
763 cbNode->presence->TTL = maxAgeSeconds;
765 for (int index = 0; index < PresenceTimeOutSize; index++)
767 // Guard against overflow
768 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
771 lowerBound = GetTicks((PresenceTimeOut[index] *
772 cbNode->presence->TTL *
773 MILLISECONDS_PER_SECOND)/100);
777 lowerBound = GetTicks(UINT32_MAX);
780 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
783 higherBound = GetTicks((PresenceTimeOut[index + 1] *
784 cbNode->presence->TTL *
785 MILLISECONDS_PER_SECOND)/100);
789 higherBound = GetTicks(UINT32_MAX);
792 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
794 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
795 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
796 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
799 cbNode->presence->TTLlevel = 0;
801 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
805 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
807 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
809 return OC_RSRVD_TRIGGER_CREATE;
811 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
813 return OC_RSRVD_TRIGGER_CHANGE;
817 return OC_RSRVD_TRIGGER_DELETE;
821 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
825 return OC_PRESENCE_TRIGGER_CREATE;
827 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
829 return OC_PRESENCE_TRIGGER_CREATE;
831 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
833 return OC_PRESENCE_TRIGGER_CHANGE;
837 return OC_PRESENCE_TRIGGER_DELETE;
842 * The cononical presence allows constructed URIs to be string compared.
844 * requestUri must be a char array of size CA_MAX_URI_LENGTH
846 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
849 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
850 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
851 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
853 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
855 if (ep->adapter == CA_ADAPTER_IP)
857 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
859 if ('\0' == ep->addr[0]) // multicast
861 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
865 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
866 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
871 if ('\0' == ep->addr[0]) // multicast
873 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
874 ep->port = OC_MULTICAST_PORT;
876 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
877 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
881 // might work for other adapters (untested, but better than nothing)
882 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
883 OC_RSRVD_PRESENCE_URI);
887 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
888 const CAResponseInfo_t *responseInfo)
890 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
891 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
893 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
894 ClientCB * cbNode = NULL;
895 char *resourceTypeName = NULL;
896 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
897 OCStackResult result = OC_STACK_ERROR;
900 char presenceUri[CA_MAX_URI_LENGTH];
902 int presenceSubscribe = 0;
903 int multicastPresenceSubscribe = 0;
905 if (responseInfo->result != CA_CONTENT)
907 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
908 return OC_STACK_ERROR;
911 // check for unicast presence
912 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
913 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
915 return OC_STACK_INVALID_URI;
918 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
921 presenceSubscribe = 1;
925 // check for multiicast presence
926 CAEndpoint_t ep = { .adapter = endpoint->adapter,
927 .flags = endpoint->flags };
929 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
931 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
934 multicastPresenceSubscribe = 1;
938 if (!presenceSubscribe && !multicastPresenceSubscribe)
940 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
944 response.payload = NULL;
945 response.result = OC_STACK_OK;
947 CopyEndpointToDevAddr(endpoint, &response.devAddr);
948 FixUpClientResponse(&response);
950 if (responseInfo->info.payload)
952 result = OCParsePayload(&response.payload,
953 PAYLOAD_TYPE_PRESENCE,
954 responseInfo->info.payload,
955 responseInfo->info.payloadSize);
957 if(result != OC_STACK_OK)
959 OIC_LOG(ERROR, TAG, "Presence parse failed");
962 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
964 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
965 result = OC_STACK_ERROR;
968 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
969 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
970 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
973 if (presenceSubscribe)
975 if(cbNode->sequenceNumber == response.sequenceNumber)
977 OIC_LOG(INFO, TAG, "No presence change");
978 ResetPresenceTTL(cbNode, maxAge);
979 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
985 OIC_LOG(INFO, TAG, "Stopping presence");
986 response.result = OC_STACK_PRESENCE_STOPPED;
989 OICFree(cbNode->presence->timeOut);
990 OICFree(cbNode->presence);
991 cbNode->presence = NULL;
996 if(!cbNode->presence)
998 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1000 if(!(cbNode->presence))
1002 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1003 result = OC_STACK_NO_MEMORY;
1007 VERIFY_NON_NULL_V(cbNode->presence);
1008 cbNode->presence->timeOut = NULL;
1009 cbNode->presence->timeOut = (uint32_t *)
1010 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1011 if(!(cbNode->presence->timeOut)){
1013 "Could not allocate memory for cbNode->presence->timeOut");
1014 OICFree(cbNode->presence);
1015 result = OC_STACK_NO_MEMORY;
1020 ResetPresenceTTL(cbNode, maxAge);
1022 cbNode->sequenceNumber = response.sequenceNumber;
1024 // Ensure that a filter is actually applied.
1025 if( resourceTypeName && cbNode->filterResourceType)
1027 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1036 // This is the multicast case
1037 OCMulticastNode* mcNode = NULL;
1038 mcNode = GetMCPresenceNode(presenceUri);
1042 if(mcNode->nonce == response.sequenceNumber)
1044 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1047 mcNode->nonce = response.sequenceNumber;
1051 OIC_LOG(INFO, TAG, "Stopping presence");
1052 response.result = OC_STACK_PRESENCE_STOPPED;
1057 char* uri = OICStrdup(presenceUri);
1061 "No Memory for URI to store in the presence node");
1062 result = OC_STACK_NO_MEMORY;
1066 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1067 if(result == OC_STACK_NO_MEMORY)
1070 "No Memory for Multicast Presence Node");
1074 // presence node now owns uri
1077 // Ensure that a filter is actually applied.
1078 if(resourceTypeName && cbNode->filterResourceType)
1080 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1087 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1089 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1091 FindAndDeleteClientCB(cbNode);
1095 OCPayloadDestroy(response.payload);
1099 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1101 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1103 if(responseInfo->info.resourceUri &&
1104 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1106 HandlePresenceResponse(endPoint, responseInfo);
1110 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1111 responseInfo->info.tokenLength, NULL, NULL);
1113 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1114 responseInfo->info.tokenLength);
1118 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1119 if(responseInfo->result == CA_EMPTY)
1121 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1122 // We do not have a case for the client to receive a RESET
1123 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1125 //This is the case of receiving an ACK on a request to a slow resource!
1126 OIC_LOG(INFO, TAG, "This is a pure ACK");
1127 //TODO: should we inform the client
1128 // app that at least the request was received at the server?
1131 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1133 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1134 OIC_LOG(INFO, TAG, "Calling into application address space");
1136 OCClientResponse response =
1137 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1138 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1139 FixUpClientResponse(&response);
1140 response.resourceUri = responseInfo->info.resourceUri;
1141 memcpy(response.identity.id, responseInfo->info.identity.id,
1142 sizeof (response.identity.id));
1143 response.identity.id_length = responseInfo->info.identity.id_length;
1145 response.result = CAResponseToOCStackResult(responseInfo->result);
1146 cbNode->callBack(cbNode->context,
1147 cbNode->handle, &response);
1148 FindAndDeleteClientCB(cbNode);
1152 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1153 OIC_LOG(INFO, TAG, "Calling into application address space");
1155 OCClientResponse response =
1156 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1157 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1158 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1159 FixUpClientResponse(&response);
1160 response.resourceUri = responseInfo->info.resourceUri;
1161 memcpy(response.identity.id, responseInfo->info.identity.id,
1162 sizeof (response.identity.id));
1163 response.identity.id_length = responseInfo->info.identity.id_length;
1165 response.result = CAResponseToOCStackResult(responseInfo->result);
1167 if(responseInfo->info.payload &&
1168 responseInfo->info.payloadSize)
1170 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1171 // check the security resource
1172 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1174 type = PAYLOAD_TYPE_SECURITY;
1176 else if (cbNode->method == OC_REST_DISCOVER)
1178 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1179 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1181 type = PAYLOAD_TYPE_DISCOVERY;
1183 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1185 type = PAYLOAD_TYPE_DEVICE;
1187 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1189 type = PAYLOAD_TYPE_PLATFORM;
1191 #ifdef ROUTING_GATEWAY
1192 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1194 type = PAYLOAD_TYPE_REPRESENTATION;
1197 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1199 type = PAYLOAD_TYPE_RD;
1202 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1204 type = PAYLOAD_TYPE_REPRESENTATION;
1209 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1210 cbNode->method, cbNode->requestUri);
1214 else if (cbNode->method == OC_REST_GET ||
1215 cbNode->method == OC_REST_PUT ||
1216 cbNode->method == OC_REST_POST ||
1217 cbNode->method == OC_REST_OBSERVE ||
1218 cbNode->method == OC_REST_OBSERVE_ALL ||
1219 cbNode->method == OC_REST_DELETE)
1221 char targetUri[MAX_URI_LENGTH];
1222 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1223 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1224 if (strcmp(targetUri, cbNode->requestUri) == 0)
1226 type = PAYLOAD_TYPE_RD;
1228 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1230 type = PAYLOAD_TYPE_PLATFORM;
1232 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1234 type = PAYLOAD_TYPE_DEVICE;
1236 if (type == PAYLOAD_TYPE_INVALID)
1238 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1239 cbNode->method, cbNode->requestUri);
1240 type = PAYLOAD_TYPE_REPRESENTATION;
1245 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1246 cbNode->method, cbNode->requestUri);
1250 if(OC_STACK_OK != OCParsePayload(&response.payload,
1252 responseInfo->info.payload,
1253 responseInfo->info.payloadSize))
1255 OIC_LOG(ERROR, TAG, "Error converting payload");
1256 OCPayloadDestroy(response.payload);
1261 response.numRcvdVendorSpecificHeaderOptions = 0;
1262 if(responseInfo->info.numOptions > 0)
1265 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1266 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1269 uint32_t observationOption;
1270 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1271 for (observationOption=0, i=0;
1272 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1276 (observationOption << 8) | optionData[i];
1278 response.sequenceNumber = observationOption;
1280 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1285 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1288 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1290 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1291 OCPayloadDestroy(response.payload);
1295 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1297 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1298 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1302 if (cbNode->method == OC_REST_OBSERVE &&
1303 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1304 response.sequenceNumber <= cbNode->sequenceNumber)
1306 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1307 response.sequenceNumber);
1311 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1314 cbNode->sequenceNumber = response.sequenceNumber;
1316 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1318 FindAndDeleteClientCB(cbNode);
1322 // To keep discovery callbacks active.
1323 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1324 MILLISECONDS_PER_SECOND);
1328 //Need to send ACK when the response is CON
1329 if(responseInfo->info.type == CA_MSG_CONFIRM)
1331 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1332 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1335 OCPayloadDestroy(response.payload);
1342 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1343 if(responseInfo->result == CA_EMPTY)
1345 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1346 if(responseInfo->info.type == CA_MSG_RESET)
1348 OIC_LOG(INFO, TAG, "This is a RESET");
1349 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1350 OC_OBSERVER_NOT_INTERESTED);
1352 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1354 OIC_LOG(INFO, TAG, "This is a pure ACK");
1355 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1356 OC_OBSERVER_STILL_INTERESTED);
1359 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1361 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1362 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1363 OC_OBSERVER_FAILED_COMM);
1368 if(!cbNode && !observer)
1370 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1371 || myStackMode == OC_GATEWAY)
1373 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1374 if(responseInfo->result == CA_EMPTY)
1376 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1380 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1381 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1382 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1386 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1387 || myStackMode == OC_GATEWAY)
1389 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1390 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1392 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1393 responseInfo->info.messageId);
1395 if (responseInfo->info.type == CA_MSG_RESET)
1397 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1398 responseInfo->info.messageId);
1405 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1408 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1410 VERIFY_NON_NULL_NR(endPoint, FATAL);
1411 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1413 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1415 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1416 #ifdef ROUTING_GATEWAY
1417 bool needRIHandling = false;
1419 * Routing manager is going to update either of endpoint or response or both.
1420 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1421 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1424 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1426 if(ret != OC_STACK_OK || !needRIHandling)
1428 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1434 * Put source in sender endpoint so that the next packet from application can be routed to
1435 * proper destination and remove "RM" coap header option before passing request / response to
1436 * RI as this option will make no sense to either RI or application.
1438 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1439 (uint8_t *) &(responseInfo->info.numOptions),
1440 (CAEndpoint_t *) endPoint);
1443 OCHandleResponse(endPoint, responseInfo);
1445 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1449 * This function handles error response from CA
1450 * code shall be added to handle the errors
1452 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1454 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1456 if (NULL == endPoint)
1458 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1462 if (NULL == errorInfo)
1464 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1468 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1469 errorInfo->info.tokenLength, NULL, NULL);
1472 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1473 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1474 FixUpClientResponse(&response);
1475 response.resourceUri = errorInfo->info.resourceUri;
1476 memcpy(response.identity.id, errorInfo->info.identity.id,
1477 sizeof (response.identity.id));
1478 response.identity.id_length = errorInfo->info.identity.id_length;
1479 response.result = CAResultToOCStackResult(errorInfo->result);
1481 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1482 FindAndDeleteClientCB(cbNode);
1485 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1489 * This function sends out Direct Stack Responses. These are responses that are not coming
1490 * from the application entity handler. These responses have no payload and are usually ACKs,
1491 * RESETs or some error conditions that were caught by the stack.
1493 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1494 const CAResponseResult_t responseResult, const CAMessageType_t type,
1495 const uint8_t numOptions, const CAHeaderOption_t *options,
1496 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1498 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1499 CAResponseInfo_t respInfo = {
1500 .result = responseResult
1502 respInfo.info.messageId = coapID;
1503 respInfo.info.numOptions = numOptions;
1505 if (respInfo.info.numOptions)
1507 respInfo.info.options =
1508 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1509 memcpy (respInfo.info.options, options,
1510 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1514 respInfo.info.payload = NULL;
1515 respInfo.info.token = token;
1516 respInfo.info.tokenLength = tokenLength;
1517 respInfo.info.type = type;
1518 respInfo.info.resourceUri = OICStrdup (resourceUri);
1519 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1521 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1522 // Add the destination to route option from the endpoint->routeData.
1523 bool doPost = false;
1524 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1525 if(OC_STACK_OK != result)
1527 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1532 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1533 CARequestInfo_t reqInfo = {.method = CA_POST };
1534 /* The following initialization is not done in a single initializer block as in
1535 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1536 * does not have designated initalizers. This is a work-around for now.
1538 reqInfo.info.type = CA_MSG_NONCONFIRM;
1539 reqInfo.info.messageId = coapID;
1540 reqInfo.info.tokenLength = tokenLength;
1541 reqInfo.info.token = token;
1542 reqInfo.info.numOptions = respInfo.info.numOptions;
1543 reqInfo.info.payload = NULL;
1544 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1545 if (reqInfo.info.numOptions)
1547 reqInfo.info.options =
1548 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1549 if (NULL == reqInfo.info.options)
1551 OIC_LOG(ERROR, TAG, "Calloc failed");
1552 return OC_STACK_NO_MEMORY;
1554 memcpy (reqInfo.info.options, respInfo.info.options,
1555 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1558 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1559 OICFree (reqInfo.info.resourceUri);
1560 OICFree (reqInfo.info.options);
1561 OICFree (respInfo.info.resourceUri);
1562 OICFree (respInfo.info.options);
1563 if (CA_STATUS_OK != caResult)
1565 OIC_LOG(ERROR, TAG, "CASendRequest error");
1566 return CAResultToOCResult(caResult);
1572 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1574 // resourceUri in the info field is cloned in the CA layer and
1575 // thus ownership is still here.
1576 OICFree (respInfo.info.resourceUri);
1577 OICFree (respInfo.info.options);
1578 if(CA_STATUS_OK != caResult)
1580 OIC_LOG(ERROR, TAG, "CASendResponse error");
1581 return CAResultToOCResult(caResult);
1584 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1588 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1590 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1591 OCStackResult result = OC_STACK_ERROR;
1592 if(!protocolRequest)
1594 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1595 return OC_STACK_INVALID_PARAM;
1598 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1599 protocolRequest->tokenLength);
1602 OIC_LOG(INFO, TAG, "This is a new Server Request");
1603 result = AddServerRequest(&request, protocolRequest->coapID,
1604 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1605 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1606 protocolRequest->observationOption, protocolRequest->qos,
1607 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1608 protocolRequest->payload, protocolRequest->requestToken,
1609 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1610 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1611 &protocolRequest->devAddr);
1612 if (OC_STACK_OK != result)
1614 OIC_LOG(ERROR, TAG, "Error adding server request");
1620 OIC_LOG(ERROR, TAG, "Out of Memory");
1621 return OC_STACK_NO_MEMORY;
1624 if(!protocolRequest->reqMorePacket)
1626 request->requestComplete = 1;
1631 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1634 if(request->requestComplete)
1636 OIC_LOG(INFO, TAG, "This Server Request is complete");
1637 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1638 OCResource *resource = NULL;
1639 result = DetermineResourceHandling (request, &resHandling, &resource);
1640 if (result == OC_STACK_OK)
1642 result = ProcessRequest(resHandling, resource, request);
1647 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1648 result = OC_STACK_CONTINUE;
1653 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1655 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1658 if (requestInfo->info.resourceUri &&
1659 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1661 HandleKeepAliveRequest(endPoint, requestInfo);
1666 OCStackResult requestResult = OC_STACK_ERROR;
1668 if(myStackMode == OC_CLIENT)
1670 //TODO: should the client be responding to requests?
1674 OCServerProtocolRequest serverRequest = {0};
1676 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1678 char * uriWithoutQuery = NULL;
1679 char * query = NULL;
1681 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1683 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1685 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1688 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1689 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1691 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1693 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1694 OICFree(uriWithoutQuery);
1698 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1699 OICFree(uriWithoutQuery);
1706 if(strlen(query) < MAX_QUERY_LENGTH)
1708 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1713 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1719 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1721 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1722 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1723 if (!serverRequest.payload)
1725 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1728 memcpy (serverRequest.payload, requestInfo->info.payload,
1729 requestInfo->info.payloadSize);
1733 serverRequest.reqTotalSize = 0;
1736 switch (requestInfo->method)
1739 serverRequest.method = OC_REST_GET;
1742 serverRequest.method = OC_REST_PUT;
1745 serverRequest.method = OC_REST_POST;
1748 serverRequest.method = OC_REST_DELETE;
1751 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1752 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1753 requestInfo->info.type, requestInfo->info.numOptions,
1754 requestInfo->info.options, requestInfo->info.token,
1755 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1756 OICFree(serverRequest.payload);
1760 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1761 requestInfo->info.tokenLength);
1763 serverRequest.tokenLength = requestInfo->info.tokenLength;
1764 if (serverRequest.tokenLength) {
1766 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1768 if (!serverRequest.requestToken)
1770 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1771 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1772 requestInfo->info.type, requestInfo->info.numOptions,
1773 requestInfo->info.options, requestInfo->info.token,
1774 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1775 OICFree(serverRequest.payload);
1778 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1781 switch (requestInfo->info.acceptFormat)
1783 case CA_FORMAT_APPLICATION_CBOR:
1784 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1786 case CA_FORMAT_UNDEFINED:
1787 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1790 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1793 if (requestInfo->info.type == CA_MSG_CONFIRM)
1795 serverRequest.qos = OC_HIGH_QOS;
1799 serverRequest.qos = OC_LOW_QOS;
1801 // CA does not need the following field
1802 // Are we sure CA does not need them? how is it responding to multicast
1803 serverRequest.delayedResNeeded = 0;
1805 serverRequest.coapID = requestInfo->info.messageId;
1807 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1809 // copy vendor specific header options
1810 uint8_t tempNum = (requestInfo->info.numOptions);
1812 // Assume no observation requested and it is a pure GET.
1813 // If obs registration/de-registration requested it'll be fetched from the
1814 // options in GetObserveHeaderOption()
1815 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1817 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1818 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1821 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1822 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1823 requestInfo->info.type, requestInfo->info.numOptions,
1824 requestInfo->info.options, requestInfo->info.token,
1825 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1826 OICFree(serverRequest.payload);
1827 OICFree(serverRequest.requestToken);
1830 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1831 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1833 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1834 sizeof(CAHeaderOption_t)*tempNum);
1837 requestResult = HandleStackRequests (&serverRequest);
1839 // Send ACK to client as precursor to slow response
1840 if (requestResult == OC_STACK_SLOW_RESOURCE)
1842 if (requestInfo->info.type == CA_MSG_CONFIRM)
1844 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1845 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1848 else if(requestResult != OC_STACK_OK)
1850 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1852 CAResponseResult_t stackResponse =
1853 OCToCAStackResult(requestResult, serverRequest.method);
1855 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1856 requestInfo->info.type, requestInfo->info.numOptions,
1857 requestInfo->info.options, requestInfo->info.token,
1858 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1860 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1861 // The token is copied in there, and is thus still owned by this function.
1862 OICFree(serverRequest.payload);
1863 OICFree(serverRequest.requestToken);
1864 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1867 //This function will be called back by CA layer when a request is received
1868 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1870 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1873 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1879 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1883 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1884 #ifdef ROUTING_GATEWAY
1885 bool needRIHandling = false;
1886 bool isEmptyMsg = false;
1888 * Routing manager is going to update either of endpoint or request or both.
1889 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1890 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1891 * destination. It can also remove "RM" coap header option before passing request / response to
1892 * RI as this option will make no sense to either RI or application.
1894 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1895 &needRIHandling, &isEmptyMsg);
1896 if(OC_STACK_OK != ret || !needRIHandling)
1898 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1904 * Put source in sender endpoint so that the next packet from application can be routed to
1905 * proper destination and remove RM header option.
1907 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1908 (uint8_t *) &(requestInfo->info.numOptions),
1909 (CAEndpoint_t *) endPoint);
1911 #ifdef ROUTING_GATEWAY
1915 * In Gateways, the MSGType in route option is used to check if the actual
1916 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
1917 * EMPTY response is sent in the form of POST request which need to be changed
1918 * to a EMPTY response by RM. This translation is done in this part of the code.
1920 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1921 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1922 .info.messageId = requestInfo->info.messageId,
1923 .info.type = CA_MSG_ACKNOWLEDGE};
1924 OCHandleResponse(endPoint, &respInfo);
1930 // Normal handling of the packet
1931 OCHandleRequests(endPoint, requestInfo);
1933 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1936 bool validatePlatformInfo(OCPlatformInfo info)
1939 if (!info.platformID)
1941 OIC_LOG(ERROR, TAG, "No platform ID found.");
1945 if (info.manufacturerName)
1947 size_t lenManufacturerName = strlen(info.manufacturerName);
1949 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1951 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1957 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1961 if (info.manufacturerUrl)
1963 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1965 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1972 //-----------------------------------------------------------------------------
1974 //-----------------------------------------------------------------------------
1976 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1979 !raInfo->username ||
1980 !raInfo->hostname ||
1981 !raInfo->xmpp_domain)
1984 return OC_STACK_INVALID_PARAM;
1986 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1987 gRASetInfo = (result == OC_STACK_OK)? true : false;
1993 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1997 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2000 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2002 if(stackState == OC_STACK_INITIALIZED)
2004 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2005 OCStop() between them are ignored.");
2009 #ifndef ROUTING_GATEWAY
2010 if (OC_GATEWAY == mode)
2012 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2013 return OC_STACK_INVALID_PARAM;
2020 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2021 return OC_STACK_ERROR;
2025 OCStackResult result = OC_STACK_ERROR;
2026 OIC_LOG(INFO, TAG, "Entering OCInit");
2029 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2030 || (mode == OC_GATEWAY)))
2032 OIC_LOG(ERROR, TAG, "Invalid mode");
2033 return OC_STACK_ERROR;
2037 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2039 caglobals.client = true;
2041 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2043 caglobals.server = true;
2046 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2047 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2049 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2051 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2052 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2054 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2057 defaultDeviceHandler = NULL;
2058 defaultDeviceHandlerCallbackParameter = NULL;
2060 result = CAResultToOCResult(CAInitialize());
2061 VERIFY_SUCCESS(result, OC_STACK_OK);
2063 result = CAResultToOCResult(OCSelectNetwork());
2064 VERIFY_SUCCESS(result, OC_STACK_OK);
2066 switch (myStackMode)
2069 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2070 result = CAResultToOCResult(CAStartDiscoveryServer());
2071 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2074 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2075 result = CAResultToOCResult(CAStartListeningServer());
2076 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2078 case OC_CLIENT_SERVER:
2080 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2081 result = CAResultToOCResult(CAStartListeningServer());
2082 if(result == OC_STACK_OK)
2084 result = CAResultToOCResult(CAStartDiscoveryServer());
2088 VERIFY_SUCCESS(result, OC_STACK_OK);
2091 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2094 #ifdef WITH_PRESENCE
2095 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2096 #endif // WITH_PRESENCE
2098 //Update Stack state to initialized
2099 stackState = OC_STACK_INITIALIZED;
2101 // Initialize resource
2102 if(myStackMode != OC_CLIENT)
2104 result = initResources();
2107 // Initialize the SRM Policy Engine
2108 if(result == OC_STACK_OK)
2110 result = SRMInitPolicyEngine();
2111 // TODO after BeachHead delivery: consolidate into single SRMInit()
2113 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2114 RMSetStackMode(mode);
2115 #ifdef ROUTING_GATEWAY
2116 if (OC_GATEWAY == myStackMode)
2118 result = RMInitialize();
2124 if (result == OC_STACK_OK)
2126 result = InitializeKeepAlive(myStackMode);
2131 if(result != OC_STACK_OK)
2133 OIC_LOG(ERROR, TAG, "Stack initialization error");
2134 deleteAllResources();
2136 stackState = OC_STACK_UNINITIALIZED;
2141 OCStackResult OCStop()
2143 OIC_LOG(INFO, TAG, "Entering OCStop");
2145 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2147 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2150 else if (stackState != OC_STACK_INITIALIZED)
2152 OIC_LOG(ERROR, TAG, "Stack not initialized");
2153 return OC_STACK_ERROR;
2156 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2158 #ifdef WITH_PRESENCE
2159 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2160 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2161 presenceResource.presenceTTL = 0;
2162 #endif // WITH_PRESENCE
2164 #ifdef ROUTING_GATEWAY
2165 if (OC_GATEWAY == myStackMode)
2172 TerminateKeepAlive(myStackMode);
2175 // Free memory dynamically allocated for resources
2176 deleteAllResources();
2178 DeletePlatformInfo();
2180 // Remove all observers
2181 DeleteObserverList();
2182 // Remove all the client callbacks
2183 DeleteClientCBList();
2185 // De-init the SRM Policy Engine
2186 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2187 SRMDeInitPolicyEngine();
2190 stackState = OC_STACK_UNINITIALIZED;
2194 OCStackResult OCStartMulticastServer()
2196 if(stackState != OC_STACK_INITIALIZED)
2198 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2199 return OC_STACK_ERROR;
2201 CAResult_t ret = CAStartListeningServer();
2202 if (CA_STATUS_OK != ret)
2204 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2205 return OC_STACK_ERROR;
2210 OCStackResult OCStopMulticastServer()
2212 CAResult_t ret = CAStopListeningServer();
2213 if (CA_STATUS_OK != ret)
2215 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2216 return OC_STACK_ERROR;
2221 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2226 return CA_MSG_CONFIRM;
2231 return CA_MSG_NONCONFIRM;
2236 * A request uri consists of the following components in order:
2239 * CoAP over UDP prefix "coap://"
2240 * CoAP over TCP prefix "coap+tcp://"
2242 * IPv6 address "[1234::5678]"
2243 * IPv4 address "192.168.1.1"
2244 * optional port ":5683"
2245 * resource uri "/oc/core..."
2247 * for PRESENCE requests, extract resource type.
2249 static OCStackResult ParseRequestUri(const char *fullUri,
2250 OCTransportAdapter adapter,
2251 OCTransportFlags flags,
2252 OCDevAddr **devAddr,
2254 char **resourceType)
2256 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2258 OCStackResult result = OC_STACK_OK;
2259 OCDevAddr *da = NULL;
2263 // provide defaults for all returned values
2270 *resourceUri = NULL;
2274 *resourceType = NULL;
2277 // delimit url prefix, if any
2278 const char *start = fullUri;
2279 char *slash2 = strstr(start, "//");
2284 char *slash = strchr(start, '/');
2287 return OC_STACK_INVALID_URI;
2290 // process url scheme
2291 size_t prefixLen = slash2 - fullUri;
2295 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2301 // TODO: this logic should come in with unit tests exercising the various strings
2302 // processs url prefix, if any
2303 size_t urlLen = slash - start;
2307 if (urlLen && devAddr)
2308 { // construct OCDevAddr
2309 if (start[0] == '[')
2311 char *close = strchr(++start, ']');
2312 if (!close || close > slash)
2314 return OC_STACK_INVALID_URI;
2317 if (close[1] == ':')
2324 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2328 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2330 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2334 char *dot = strchr(start, '.');
2335 if (dot && dot < slash)
2337 colon = strchr(start, ':');
2338 end = (colon && colon < slash) ? colon : slash;
2343 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2347 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2349 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2357 if (len >= sizeof(da->addr))
2359 return OC_STACK_INVALID_URI;
2361 // collect port, if any
2362 if (colon && colon < slash)
2364 for (colon++; colon < slash; colon++)
2367 if (c < '0' || c > '9')
2369 return OC_STACK_INVALID_URI;
2371 port = 10 * port + c - '0';
2376 if (len >= sizeof(da->addr))
2378 return OC_STACK_INVALID_URI;
2381 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2384 return OC_STACK_NO_MEMORY;
2386 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2388 da->adapter = adapter;
2390 if (!strncmp(fullUri, "coaps:", 6))
2392 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2397 // process resource uri, if any
2399 { // request uri and query
2400 size_t ulen = strlen(slash); // resource uri length
2401 size_t tlen = 0; // resource type length
2404 static const char strPresence[] = "/oic/ad?rt=";
2405 static const size_t lenPresence = sizeof(strPresence) - 1;
2406 if (!strncmp(slash, strPresence, lenPresence))
2408 type = slash + lenPresence;
2409 tlen = ulen - lenPresence;
2414 *resourceUri = (char *)OICMalloc(ulen + 1);
2417 result = OC_STACK_NO_MEMORY;
2420 strcpy(*resourceUri, slash);
2423 if (type && resourceType)
2425 *resourceType = (char *)OICMalloc(tlen + 1);
2428 result = OC_STACK_NO_MEMORY;
2432 OICStrcpy(*resourceType, (tlen+1), type);
2439 // free all returned values
2446 OICFree(*resourceUri);
2450 OICFree(*resourceType);
2455 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2456 char *resourceUri, char **requestUri)
2458 char uri[CA_MAX_URI_LENGTH];
2460 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2462 *requestUri = OICStrdup(uri);
2465 return OC_STACK_NO_MEMORY;
2472 * Discover or Perform requests on a specified resource
2474 OCStackResult OCDoResource(OCDoHandle *handle,
2476 const char *requestUri,
2477 const OCDevAddr *destination,
2479 OCConnectivityType connectivityType,
2480 OCQualityOfService qos,
2481 OCCallbackData *cbData,
2482 OCHeaderOption *options,
2485 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2487 // Validate input parameters
2488 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2489 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2490 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2492 OCStackResult result = OC_STACK_ERROR;
2493 CAResult_t caResult;
2494 CAToken_t token = NULL;
2495 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2496 ClientCB *clientCB = NULL;
2497 OCDoHandle resHandle = NULL;
2498 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2499 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2501 OCTransportAdapter adapter;
2502 OCTransportFlags flags;
2503 // the request contents are put here
2504 CARequestInfo_t requestInfo = {.method = CA_GET};
2505 // requestUri will be parsed into the following three variables
2506 OCDevAddr *devAddr = NULL;
2507 char *resourceUri = NULL;
2508 char *resourceType = NULL;
2511 * Support original behavior with address on resourceUri argument.
2513 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2514 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2516 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2518 if (result != OC_STACK_OK)
2520 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2527 case OC_REST_OBSERVE:
2528 case OC_REST_OBSERVE_ALL:
2529 case OC_REST_CANCEL_OBSERVE:
2530 requestInfo.method = CA_GET;
2533 requestInfo.method = CA_PUT;
2536 requestInfo.method = CA_POST;
2538 case OC_REST_DELETE:
2539 requestInfo.method = CA_DELETE;
2541 case OC_REST_DISCOVER:
2543 if (destination || devAddr)
2545 requestInfo.isMulticast = false;
2549 tmpDevAddr.adapter = adapter;
2550 tmpDevAddr.flags = flags;
2551 destination = &tmpDevAddr;
2552 requestInfo.isMulticast = true;
2554 // CA_DISCOVER will become GET and isMulticast
2555 requestInfo.method = CA_GET;
2557 #ifdef WITH_PRESENCE
2558 case OC_REST_PRESENCE:
2559 // Replacing method type with GET because "presence"
2560 // is a stack layer only implementation.
2561 requestInfo.method = CA_GET;
2565 result = OC_STACK_INVALID_METHOD;
2569 if (!devAddr && !destination)
2571 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2572 result = OC_STACK_INVALID_PARAM;
2576 /* If not original behavior, use destination argument */
2577 if (destination && !devAddr)
2579 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2582 result = OC_STACK_NO_MEMORY;
2585 *devAddr = *destination;
2588 resHandle = GenerateInvocationHandle();
2591 result = OC_STACK_NO_MEMORY;
2595 caResult = CAGenerateToken(&token, tokenLength);
2596 if (caResult != CA_STATUS_OK)
2598 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2599 result= OC_STACK_ERROR;
2603 // fill in request data
2604 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2605 requestInfo.info.token = token;
2606 requestInfo.info.tokenLength = tokenLength;
2607 requestInfo.info.resourceUri = resourceUri;
2609 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2611 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2612 options, numOptions, OC_OBSERVE_REGISTER);
2613 if (result != OC_STACK_OK)
2617 requestInfo.info.numOptions = numOptions + 1;
2621 requestInfo.info.numOptions = numOptions;
2622 requestInfo.info.options =
2623 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2624 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2625 numOptions * sizeof(CAHeaderOption_t));
2628 CopyDevAddrToEndpoint(devAddr, &endpoint);
2633 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2636 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2639 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2643 requestInfo.info.payload = NULL;
2644 requestInfo.info.payloadSize = 0;
2645 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2648 if (result != OC_STACK_OK)
2650 OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2654 // prepare for response
2655 #ifdef WITH_PRESENCE
2656 if (method == OC_REST_PRESENCE)
2658 char *presenceUri = NULL;
2659 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2660 if (OC_STACK_OK != result)
2665 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2666 // Presence notification will form a canonical uri to
2667 // look for callbacks into the application.
2668 resourceUri = presenceUri;
2672 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2673 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2674 method, devAddr, resourceUri, resourceType, ttl);
2675 if (OC_STACK_OK != result)
2680 devAddr = NULL; // Client CB list entry now owns it
2681 resourceUri = NULL; // Client CB list entry now owns it
2682 resourceType = NULL; // Client CB list entry now owns it
2685 result = OCSendRequest(&endpoint, &requestInfo);
2686 if (OC_STACK_OK != result)
2693 *handle = resHandle;
2697 if (result != OC_STACK_OK)
2699 OIC_LOG(ERROR, TAG, "OCDoResource error");
2700 FindAndDeleteClientCB(clientCB);
2701 CADestroyToken(token);
2709 // This is the owner of the payload object, so we free it
2710 OCPayloadDestroy(payload);
2711 OICFree(requestInfo.info.payload);
2713 OICFree(resourceUri);
2714 OICFree(resourceType);
2715 OICFree(requestInfo.info.options);
2719 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2723 * This ftn is implemented one of two ways in the case of observation:
2725 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2726 * Remove the callback associated on client side.
2727 * When the next notification comes in from server,
2728 * reply with RESET message to server.
2729 * Keep in mind that the server will react to RESET only
2730 * if the last notification was sent as CON
2732 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2733 * and it is associated with an observe request
2734 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2735 * Send CON Observe request to server with
2736 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2737 * Remove the callback associated on client side.
2739 OCStackResult ret = OC_STACK_OK;
2740 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2741 CARequestInfo_t requestInfo = {.method = CA_GET};
2745 return OC_STACK_INVALID_PARAM;
2748 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2751 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2752 return OC_STACK_ERROR;
2755 switch (clientCB->method)
2757 case OC_REST_OBSERVE:
2758 case OC_REST_OBSERVE_ALL:
2760 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2762 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2764 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2766 FindAndDeleteClientCB(clientCB);
2770 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2772 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2773 requestInfo.info.token = clientCB->token;
2774 requestInfo.info.tokenLength = clientCB->tokenLength;
2776 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2777 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2779 return OC_STACK_ERROR;
2781 requestInfo.info.numOptions = numOptions + 1;
2782 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2785 ret = OCSendRequest(&endpoint, &requestInfo);
2787 if (requestInfo.info.options)
2789 OICFree (requestInfo.info.options);
2791 if (requestInfo.info.resourceUri)
2793 OICFree (requestInfo.info.resourceUri);
2798 case OC_REST_DISCOVER:
2799 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2800 clientCB->requestUri);
2801 FindAndDeleteClientCB(clientCB);
2804 #ifdef WITH_PRESENCE
2805 case OC_REST_PRESENCE:
2806 FindAndDeleteClientCB(clientCB);
2811 ret = OC_STACK_INVALID_METHOD;
2819 * @brief Register Persistent storage callback.
2820 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2822 * OC_STACK_OK - No errors; Success
2823 * OC_STACK_INVALID_PARAM - Invalid parameter
2825 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2827 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2828 if(!persistentStorageHandler)
2830 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2831 return OC_STACK_INVALID_PARAM;
2835 if( !persistentStorageHandler->open ||
2836 !persistentStorageHandler->close ||
2837 !persistentStorageHandler->read ||
2838 !persistentStorageHandler->unlink ||
2839 !persistentStorageHandler->write)
2841 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2842 return OC_STACK_INVALID_PARAM;
2845 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2848 #ifdef WITH_PRESENCE
2850 OCStackResult OCProcessPresence()
2852 OCStackResult result = OC_STACK_OK;
2854 // the following line floods the log with messages that are irrelevant
2855 // to most purposes. Uncomment as needed.
2856 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2857 ClientCB* cbNode = NULL;
2858 OCClientResponse clientResponse;
2859 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2861 LL_FOREACH(cbList, cbNode)
2863 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2868 uint32_t now = GetTicks(0);
2869 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2870 cbNode->presence->TTLlevel);
2871 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2873 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2878 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2880 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2881 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2883 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2885 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2887 clientResponse.sequenceNumber = 0;
2888 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2889 clientResponse.devAddr = *cbNode->devAddr;
2890 FixUpClientResponse(&clientResponse);
2891 clientResponse.payload = NULL;
2893 // Increment the TTLLevel (going to a next state), so we don't keep
2894 // sending presence notification to client.
2895 cbNode->presence->TTLlevel++;
2896 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2897 cbNode->presence->TTLlevel);
2899 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2900 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2902 FindAndDeleteClientCB(cbNode);
2906 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2911 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2912 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2913 CARequestInfo_t requestInfo = {.method = CA_GET};
2915 OIC_LOG(DEBUG, TAG, "time to test server presence");
2917 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2919 requestData.type = CA_MSG_NONCONFIRM;
2920 requestData.token = cbNode->token;
2921 requestData.tokenLength = cbNode->tokenLength;
2922 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2923 requestInfo.method = CA_GET;
2924 requestInfo.info = requestData;
2926 result = OCSendRequest(&endpoint, &requestInfo);
2927 if (OC_STACK_OK != result)
2932 cbNode->presence->TTLlevel++;
2933 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2936 if (result != OC_STACK_OK)
2938 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2943 #endif // WITH_PRESENCE
2945 OCStackResult OCProcess()
2947 #ifdef WITH_PRESENCE
2948 OCProcessPresence();
2950 CAHandleRequestResponse();
2952 #ifdef ROUTING_GATEWAY
2962 #ifdef WITH_PRESENCE
2963 OCStackResult OCStartPresence(const uint32_t ttl)
2965 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2966 OCChangeResourceProperty(
2967 &(((OCResource *)presenceResource.handle)->resourceProperties),
2970 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2972 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2973 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2977 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2978 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2982 presenceResource.presenceTTL = ttl;
2984 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2986 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2988 presenceState = OC_PRESENCE_INITIALIZED;
2990 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2992 CAToken_t caToken = NULL;
2993 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2994 if (caResult != CA_STATUS_OK)
2996 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2997 CADestroyToken(caToken);
2998 return OC_STACK_ERROR;
3001 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3002 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3003 CADestroyToken(caToken);
3006 // Each time OCStartPresence is called
3007 // a different random 32-bit integer number is used
3008 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3010 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3011 OC_PRESENCE_TRIGGER_CREATE);
3014 OCStackResult OCStopPresence()
3016 OCStackResult result = OC_STACK_ERROR;
3018 if(presenceResource.handle)
3020 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3022 // make resource inactive
3023 result = OCChangeResourceProperty(
3024 &(((OCResource *) presenceResource.handle)->resourceProperties),
3028 if(result != OC_STACK_OK)
3031 "Changing the presence resource properties to ACTIVE not successful");
3035 return SendStopNotification();
3039 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3040 void* callbackParameter)
3042 defaultDeviceHandler = entityHandler;
3043 defaultDeviceHandlerCallbackParameter = callbackParameter;
3048 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3050 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3052 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3054 if (validatePlatformInfo(platformInfo))
3056 return SavePlatformInfo(platformInfo);
3060 return OC_STACK_INVALID_PARAM;
3065 return OC_STACK_ERROR;
3069 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3071 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3073 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3075 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3076 return OC_STACK_INVALID_PARAM;
3079 if (deviceInfo.types)
3081 OCStringLL *type = deviceInfo.types;
3082 OCResource *resource = findResource((OCResource *) deviceResource);
3085 return OC_STACK_INVALID_PARAM;
3087 deleteResourceType(resource->rsrcType);
3088 resource->rsrcType = NULL;
3092 OCBindResourceTypeToResource(deviceResource, type->value);
3096 return SaveDeviceInfo(deviceInfo);
3099 OCStackResult OCCreateResource(OCResourceHandle *handle,
3100 const char *resourceTypeName,
3101 const char *resourceInterfaceName,
3102 const char *uri, OCEntityHandler entityHandler,
3103 void* callbackParam,
3104 uint8_t resourceProperties)
3107 OCResource *pointer = NULL;
3108 OCStackResult result = OC_STACK_ERROR;
3110 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3112 if(myStackMode == OC_CLIENT)
3114 return OC_STACK_INVALID_PARAM;
3116 // Validate parameters
3117 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3119 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3120 return OC_STACK_INVALID_URI;
3122 // Is it presented during resource discovery?
3123 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3125 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3126 return OC_STACK_INVALID_PARAM;
3129 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3131 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3134 // Make sure resourceProperties bitmask has allowed properties specified
3135 if (resourceProperties
3136 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3137 OC_EXPLICIT_DISCOVERABLE))
3139 OIC_LOG(ERROR, TAG, "Invalid property");
3140 return OC_STACK_INVALID_PARAM;
3143 // If the headResource is NULL, then no resources have been created...
3144 pointer = headResource;
3147 // At least one resources is in the resource list, so we need to search for
3148 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3151 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3153 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3154 return OC_STACK_INVALID_PARAM;
3156 pointer = pointer->next;
3159 // Create the pointer and insert it into the resource list
3160 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3163 result = OC_STACK_NO_MEMORY;
3166 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3168 insertResource(pointer);
3171 pointer->uri = OICStrdup(uri);
3174 result = OC_STACK_NO_MEMORY;
3178 // Set properties. Set OC_ACTIVE
3179 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3182 // Add the resourcetype to the resource
3183 result = BindResourceTypeToResource(pointer, resourceTypeName);
3184 if (result != OC_STACK_OK)
3186 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3190 // Add the resourceinterface to the resource
3191 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3192 if (result != OC_STACK_OK)
3194 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3198 // If an entity handler has been passed, attach it to the newly created
3199 // resource. Otherwise, set the default entity handler.
3202 pointer->entityHandler = entityHandler;
3203 pointer->entityHandlerCallbackParam = callbackParam;
3207 pointer->entityHandler = defaultResourceEHandler;
3208 pointer->entityHandlerCallbackParam = NULL;
3211 // Initialize a pointer indicating child resources in case of collection
3212 pointer->rsrcChildResourcesHead = NULL;
3215 result = OC_STACK_OK;
3217 #ifdef WITH_PRESENCE
3218 if (presenceResource.handle)
3220 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3221 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3225 if (result != OC_STACK_OK)
3227 // Deep delete of resource and other dynamic elements that it contains
3228 deleteResource(pointer);
3233 OCStackResult OCBindResource(
3234 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3236 OCResource *resource = NULL;
3237 OCChildResource *tempChildResource = NULL;
3238 OCChildResource *newChildResource = NULL;
3240 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3242 // Validate parameters
3243 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3244 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3245 // Container cannot contain itself
3246 if (collectionHandle == resourceHandle)
3248 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3249 return OC_STACK_INVALID_PARAM;
3252 // Use the handle to find the resource in the resource linked list
3253 resource = findResource((OCResource *) collectionHandle);
3256 OIC_LOG(ERROR, TAG, "Collection handle not found");
3257 return OC_STACK_INVALID_PARAM;
3260 // Look for an open slot to add add the child resource.
3261 // If found, add it and return success
3263 tempChildResource = resource->rsrcChildResourcesHead;
3265 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3267 // TODO: what if one of child resource was deregistered without unbinding?
3268 tempChildResource = tempChildResource->next;
3271 // Do memory allocation for child resource
3272 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3273 if(!newChildResource)
3275 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3276 return OC_STACK_ERROR;
3279 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3280 newChildResource->next = NULL;
3282 if(!resource->rsrcChildResourcesHead)
3284 resource->rsrcChildResourcesHead = newChildResource;
3287 tempChildResource->next = newChildResource;
3290 OIC_LOG(INFO, TAG, "resource bound");
3292 #ifdef WITH_PRESENCE
3293 if (presenceResource.handle)
3295 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3296 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3297 OC_PRESENCE_TRIGGER_CHANGE);
3304 OCStackResult OCUnBindResource(
3305 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3307 OCResource *resource = NULL;
3308 OCChildResource *tempChildResource = NULL;
3309 OCChildResource *tempLastChildResource = NULL;
3311 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3313 // Validate parameters
3314 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3315 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3316 // Container cannot contain itself
3317 if (collectionHandle == resourceHandle)
3319 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3320 return OC_STACK_INVALID_PARAM;
3323 // Use the handle to find the resource in the resource linked list
3324 resource = findResource((OCResource *) collectionHandle);
3327 OIC_LOG(ERROR, TAG, "Collection handle not found");
3328 return OC_STACK_INVALID_PARAM;
3331 // Look for an open slot to add add the child resource.
3332 // If found, add it and return success
3333 if(!resource->rsrcChildResourcesHead)
3335 OIC_LOG(INFO, TAG, "resource not found in collection");
3337 // Unable to add resourceHandle, so return error
3338 return OC_STACK_ERROR;
3342 tempChildResource = resource->rsrcChildResourcesHead;
3344 while (tempChildResource)
3346 if(tempChildResource->rsrcResource == resourceHandle)
3348 // if resource going to be unbinded is the head one.
3349 if( tempChildResource == resource->rsrcChildResourcesHead )
3351 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3352 OICFree(resource->rsrcChildResourcesHead);
3353 resource->rsrcChildResourcesHead = temp;
3358 OCChildResource *temp = tempChildResource->next;
3359 OICFree(tempChildResource);
3360 tempLastChildResource->next = temp;
3364 OIC_LOG(INFO, TAG, "resource unbound");
3366 // Send notification when resource is unbounded successfully.
3367 #ifdef WITH_PRESENCE
3368 if (presenceResource.handle)
3370 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3371 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3372 OC_PRESENCE_TRIGGER_CHANGE);
3375 tempChildResource = NULL;
3376 tempLastChildResource = NULL;
3382 tempLastChildResource = tempChildResource;
3383 tempChildResource = tempChildResource->next;
3386 OIC_LOG(INFO, TAG, "resource not found in collection");
3388 tempChildResource = NULL;
3389 tempLastChildResource = NULL;
3391 // Unable to add resourceHandle, so return error
3392 return OC_STACK_ERROR;
3395 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3397 if (!resourceItemName)
3401 // Per RFC 6690 only registered values must follow the first rule below.
3402 // At this point in time the only values registered begin with "core", and
3403 // all other values are specified as opaque strings where multiple values
3404 // are separated by a space.
3405 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3407 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3409 if (resourceItemName[index] != '.'
3410 && resourceItemName[index] != '-'
3411 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3412 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3420 for (size_t index = 0; resourceItemName[index]; ++index)
3422 if (resourceItemName[index] == ' '
3423 || resourceItemName[index] == '\t'
3424 || resourceItemName[index] == '\r'
3425 || resourceItemName[index] == '\n')
3435 OCStackResult BindResourceTypeToResource(OCResource* resource,
3436 const char *resourceTypeName)
3438 OCResourceType *pointer = NULL;
3440 OCStackResult result = OC_STACK_ERROR;
3442 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3444 if (!ValidateResourceTypeInterface(resourceTypeName))
3446 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3447 return OC_STACK_INVALID_PARAM;
3450 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3453 result = OC_STACK_NO_MEMORY;
3457 str = OICStrdup(resourceTypeName);
3460 result = OC_STACK_NO_MEMORY;
3463 pointer->resourcetypename = str;
3464 pointer->next = NULL;
3466 insertResourceType(resource, pointer);
3467 result = OC_STACK_OK;
3470 if (result != OC_STACK_OK)
3479 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3480 const char *resourceInterfaceName)
3482 OCResourceInterface *pointer = NULL;
3484 OCStackResult result = OC_STACK_ERROR;
3486 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3488 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3490 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3491 return OC_STACK_INVALID_PARAM;
3494 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3496 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3499 result = OC_STACK_NO_MEMORY;
3503 str = OICStrdup(resourceInterfaceName);
3506 result = OC_STACK_NO_MEMORY;
3509 pointer->name = str;
3511 // Bind the resourceinterface to the resource
3512 insertResourceInterface(resource, pointer);
3514 result = OC_STACK_OK;
3517 if (result != OC_STACK_OK)
3526 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3527 const char *resourceTypeName)
3530 OCStackResult result = OC_STACK_ERROR;
3531 OCResource *resource = NULL;
3533 resource = findResource((OCResource *) handle);
3536 OIC_LOG(ERROR, TAG, "Resource not found");
3537 return OC_STACK_ERROR;
3540 result = BindResourceTypeToResource(resource, resourceTypeName);
3542 #ifdef WITH_PRESENCE
3543 if(presenceResource.handle)
3545 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3546 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3553 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3554 const char *resourceInterfaceName)
3557 OCStackResult result = OC_STACK_ERROR;
3558 OCResource *resource = NULL;
3560 resource = findResource((OCResource *) handle);
3563 OIC_LOG(ERROR, TAG, "Resource not found");
3564 return OC_STACK_ERROR;
3567 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3569 #ifdef WITH_PRESENCE
3570 if (presenceResource.handle)
3572 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3573 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3580 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3582 OCResource *pointer = headResource;
3584 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3588 *numResources = *numResources + 1;
3589 pointer = pointer->next;
3594 OCResourceHandle OCGetResourceHandle(uint8_t index)
3596 OCResource *pointer = headResource;
3598 for( uint8_t i = 0; i < index && pointer; ++i)
3600 pointer = pointer->next;
3602 return (OCResourceHandle) pointer;
3605 OCStackResult OCDeleteResource(OCResourceHandle handle)
3609 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3610 return OC_STACK_INVALID_PARAM;
3613 OCResource *resource = findResource((OCResource *) handle);
3614 if (resource == NULL)
3616 OIC_LOG(ERROR, TAG, "Resource not found");
3617 return OC_STACK_NO_RESOURCE;
3620 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3622 OIC_LOG(ERROR, TAG, "Error deleting resource");
3623 return OC_STACK_ERROR;
3629 const char *OCGetResourceUri(OCResourceHandle handle)
3631 OCResource *resource = NULL;
3633 resource = findResource((OCResource *) handle);
3636 return resource->uri;
3638 return (const char *) NULL;
3641 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3643 OCResource *resource = NULL;
3645 resource = findResource((OCResource *) handle);
3648 return resource->resourceProperties;
3650 return (OCResourceProperty)-1;
3653 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3654 uint8_t *numResourceTypes)
3656 OCResource *resource = NULL;
3657 OCResourceType *pointer = NULL;
3659 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3660 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3662 *numResourceTypes = 0;
3664 resource = findResource((OCResource *) handle);
3667 pointer = resource->rsrcType;
3670 *numResourceTypes = *numResourceTypes + 1;
3671 pointer = pointer->next;
3677 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3679 OCResourceType *resourceType = NULL;
3681 resourceType = findResourceTypeAtIndex(handle, index);
3684 return resourceType->resourcetypename;
3686 return (const char *) NULL;
3689 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3690 uint8_t *numResourceInterfaces)
3692 OCResourceInterface *pointer = NULL;
3693 OCResource *resource = NULL;
3695 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3696 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3698 *numResourceInterfaces = 0;
3699 resource = findResource((OCResource *) handle);
3702 pointer = resource->rsrcInterface;
3705 *numResourceInterfaces = *numResourceInterfaces + 1;
3706 pointer = pointer->next;
3712 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3714 OCResourceInterface *resourceInterface = NULL;
3716 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3717 if (resourceInterface)
3719 return resourceInterface->name;
3721 return (const char *) NULL;
3724 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3727 OCResource *resource = NULL;
3728 OCChildResource *tempChildResource = NULL;
3731 resource = findResource((OCResource *) collectionHandle);
3737 tempChildResource = resource->rsrcChildResourcesHead;
3739 while(tempChildResource)
3743 return tempChildResource->rsrcResource;
3746 tempChildResource = tempChildResource->next;
3749 // In this case, the number of resource handles in the collection exceeds the index
3750 tempChildResource = NULL;
3754 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3755 OCEntityHandler entityHandler,
3756 void* callbackParam)
3758 OCResource *resource = NULL;
3760 // Validate parameters
3761 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3763 // Use the handle to find the resource in the resource linked list
3764 resource = findResource((OCResource *)handle);
3767 OIC_LOG(ERROR, TAG, "Resource not found");
3768 return OC_STACK_ERROR;
3772 resource->entityHandler = entityHandler;
3773 resource->entityHandlerCallbackParam = callbackParam;
3775 #ifdef WITH_PRESENCE
3776 if (presenceResource.handle)
3778 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3779 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3786 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3788 OCResource *resource = NULL;
3790 resource = findResource((OCResource *)handle);
3793 OIC_LOG(ERROR, TAG, "Resource not found");
3798 return resource->entityHandler;
3801 void incrementSequenceNumber(OCResource * resPtr)
3803 // Increment the sequence number
3804 resPtr->sequenceNum += 1;
3805 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3807 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3812 #ifdef WITH_PRESENCE
3813 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3814 OCPresenceTrigger trigger)
3816 OCResource *resPtr = NULL;
3817 OCStackResult result = OC_STACK_ERROR;
3818 OCMethod method = OC_REST_PRESENCE;
3819 uint32_t maxAge = 0;
3820 resPtr = findResource((OCResource *) presenceResource.handle);
3823 return OC_STACK_NO_RESOURCE;
3826 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3828 maxAge = presenceResource.presenceTTL;
3830 result = SendAllObserverNotification(method, resPtr, maxAge,
3831 trigger, resourceType, OC_LOW_QOS);
3837 OCStackResult SendStopNotification()
3839 OCResource *resPtr = NULL;
3840 OCStackResult result = OC_STACK_ERROR;
3841 OCMethod method = OC_REST_PRESENCE;
3842 resPtr = findResource((OCResource *) presenceResource.handle);
3845 return OC_STACK_NO_RESOURCE;
3848 // maxAge is 0. ResourceType is NULL.
3849 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3855 #endif // WITH_PRESENCE
3856 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3858 OCResource *resPtr = NULL;
3859 OCStackResult result = OC_STACK_ERROR;
3860 OCMethod method = OC_REST_NOMETHOD;
3861 uint32_t maxAge = 0;
3863 OIC_LOG(INFO, TAG, "Notifying all observers");
3864 #ifdef WITH_PRESENCE
3865 if(handle == presenceResource.handle)
3869 #endif // WITH_PRESENCE
3870 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3872 // Verify that the resource exists
3873 resPtr = findResource ((OCResource *) handle);
3876 return OC_STACK_NO_RESOURCE;
3880 //only increment in the case of regular observing (not presence)
3881 incrementSequenceNumber(resPtr);
3882 method = OC_REST_OBSERVE;
3883 maxAge = MAX_OBSERVE_AGE;
3884 #ifdef WITH_PRESENCE
3885 result = SendAllObserverNotification (method, resPtr, maxAge,
3886 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3888 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3895 OCNotifyListOfObservers (OCResourceHandle handle,
3896 OCObservationId *obsIdList,
3897 uint8_t numberOfIds,
3898 const OCRepPayload *payload,
3899 OCQualityOfService qos)
3901 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3903 OCResource *resPtr = NULL;
3904 //TODO: we should allow the server to define this
3905 uint32_t maxAge = MAX_OBSERVE_AGE;
3907 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3908 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3909 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3911 resPtr = findResource ((OCResource *) handle);
3912 if (NULL == resPtr || myStackMode == OC_CLIENT)
3914 return OC_STACK_NO_RESOURCE;
3918 incrementSequenceNumber(resPtr);
3920 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3921 payload, maxAge, qos));
3924 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3926 OCStackResult result = OC_STACK_ERROR;
3927 OCServerRequest *serverRequest = NULL;
3929 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3931 // Validate input parameters
3932 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3933 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3936 // Get pointer to request info
3937 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3940 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3941 result = serverRequest->ehResponseHandler(ehResponse);
3947 //#ifdef DIRECT_PAIRING
3948 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3950 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3951 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3953 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3957 return (const OCDPDev_t*)DPGetDiscoveredDevices();
3960 const OCDPDev_t* OCGetDirectPairedDevices()
3962 return (const OCDPDev_t*)DPGetPairedDevices();
3965 void DirectPairingCB (OCDirectPairingDev_t * peer, OCStackResult result)
3967 if (gDirectpairingCallback)
3969 gDirectpairingCallback((OCDPDev_t*)peer, result);
3970 gDirectpairingCallback = NULL;
3974 OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3975 OCDirectPairingCB resultCallback)
3977 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3978 if(NULL == peer || NULL == pinNumber)
3980 OIC_LOG(ERROR, TAG, "Invalid parameters");
3981 return OC_STACK_INVALID_PARAM;
3983 if (NULL == resultCallback)
3985 OIC_LOG(ERROR, TAG, "Invalid callback");
3986 return OC_STACK_INVALID_CALLBACK;
3989 gDirectpairingCallback = resultCallback;
3990 return DPDirectPairing((OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3991 pinNumber, DirectPairingCB);
3993 //#endif // DIRECT_PAIRING
3995 //-----------------------------------------------------------------------------
3996 // Private internal function definitions
3997 //-----------------------------------------------------------------------------
3998 static OCDoHandle GenerateInvocationHandle()
4000 OCDoHandle handle = NULL;
4001 // Generate token here, it will be deleted when the transaction is deleted
4002 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4005 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4011 #ifdef WITH_PRESENCE
4012 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4013 OCResourceProperty resourceProperties, uint8_t enable)
4017 return OC_STACK_INVALID_PARAM;
4019 if (resourceProperties
4020 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4022 OIC_LOG(ERROR, TAG, "Invalid property");
4023 return OC_STACK_INVALID_PARAM;
4027 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4031 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4037 OCStackResult initResources()
4039 OCStackResult result = OC_STACK_OK;
4041 headResource = NULL;
4042 tailResource = NULL;
4043 // Init Virtual Resources
4044 #ifdef WITH_PRESENCE
4045 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4047 result = OCCreateResource(&presenceResource.handle,
4048 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4050 OC_RSRVD_PRESENCE_URI,
4054 //make resource inactive
4055 result = OCChangeResourceProperty(
4056 &(((OCResource *) presenceResource.handle)->resourceProperties),
4059 #ifndef WITH_ARDUINO
4060 if (result == OC_STACK_OK)
4062 result = SRMInitSecureResources();
4066 if(result == OC_STACK_OK)
4068 result = OCCreateResource(&deviceResource,
4069 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4070 OC_RSRVD_INTERFACE_DEFAULT,
4071 OC_RSRVD_DEVICE_URI,
4075 if(result == OC_STACK_OK)
4077 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4078 OC_RSRVD_INTERFACE_READ);
4082 if(result == OC_STACK_OK)
4084 result = OCCreateResource(&platformResource,
4085 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4086 OC_RSRVD_INTERFACE_DEFAULT,
4087 OC_RSRVD_PLATFORM_URI,
4091 if(result == OC_STACK_OK)
4093 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4094 OC_RSRVD_INTERFACE_READ);
4101 void insertResource(OCResource *resource)
4105 headResource = resource;
4106 tailResource = resource;
4110 tailResource->next = resource;
4111 tailResource = resource;
4113 resource->next = NULL;
4116 OCResource *findResource(OCResource *resource)
4118 OCResource *pointer = headResource;
4122 if (pointer == resource)
4126 pointer = pointer->next;
4131 void deleteAllResources()
4133 OCResource *pointer = headResource;
4134 OCResource *temp = NULL;
4138 temp = pointer->next;
4139 #ifdef WITH_PRESENCE
4140 if (pointer != (OCResource *) presenceResource.handle)
4142 #endif // WITH_PRESENCE
4143 deleteResource(pointer);
4144 #ifdef WITH_PRESENCE
4146 #endif // WITH_PRESENCE
4150 SRMDeInitSecureResources();
4152 #ifdef WITH_PRESENCE
4153 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4154 // presence notification attributed to their deletion to be processed.
4155 deleteResource((OCResource *) presenceResource.handle);
4156 #endif // WITH_PRESENCE
4159 OCStackResult deleteResource(OCResource *resource)
4161 OCResource *prev = NULL;
4162 OCResource *temp = NULL;
4165 OIC_LOG(DEBUG,TAG,"resource is NULL");
4166 return OC_STACK_INVALID_PARAM;
4169 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4171 temp = headResource;
4174 if (temp == resource)
4176 // Invalidate all Resource Properties.
4177 resource->resourceProperties = (OCResourceProperty) 0;
4178 #ifdef WITH_PRESENCE
4179 if(resource != (OCResource *) presenceResource.handle)
4181 #endif // WITH_PRESENCE
4182 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4183 #ifdef WITH_PRESENCE
4186 if(presenceResource.handle)
4188 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4189 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4192 // Only resource in list.
4193 if (temp == headResource && temp == tailResource)
4195 headResource = NULL;
4196 tailResource = NULL;
4199 else if (temp == headResource)
4201 headResource = temp->next;
4204 else if (temp == tailResource)
4206 tailResource = prev;
4207 tailResource->next = NULL;
4211 prev->next = temp->next;
4214 deleteResourceElements(temp);
4225 return OC_STACK_ERROR;
4228 void deleteResourceElements(OCResource *resource)
4235 OICFree(resource->uri);
4236 deleteResourceType(resource->rsrcType);
4237 deleteResourceInterface(resource->rsrcInterface);
4240 void deleteResourceType(OCResourceType *resourceType)
4242 OCResourceType *pointer = resourceType;
4243 OCResourceType *next = NULL;
4247 next = pointer->next;
4248 OICFree(pointer->resourcetypename);
4254 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4256 OCResourceInterface *pointer = resourceInterface;
4257 OCResourceInterface *next = NULL;
4261 next = pointer->next;
4262 OICFree(pointer->name);
4268 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4270 OCResourceType *pointer = NULL;
4271 OCResourceType *previous = NULL;
4272 if (!resource || !resourceType)
4276 // resource type list is empty.
4277 else if (!resource->rsrcType)
4279 resource->rsrcType = resourceType;
4283 pointer = resource->rsrcType;
4287 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4289 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4290 OICFree(resourceType->resourcetypename);
4291 OICFree(resourceType);
4295 pointer = pointer->next;
4300 previous->next = resourceType;
4303 resourceType->next = NULL;
4305 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4308 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4310 OCResource *resource = NULL;
4311 OCResourceType *pointer = NULL;
4313 // Find the specified resource
4314 resource = findResource((OCResource *) handle);
4320 // Make sure a resource has a resourcetype
4321 if (!resource->rsrcType)
4326 // Iterate through the list
4327 pointer = resource->rsrcType;
4328 for(uint8_t i = 0; i< index && pointer; ++i)
4330 pointer = pointer->next;
4335 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4337 if(resourceTypeList && resourceTypeName)
4339 OCResourceType * rtPointer = resourceTypeList;
4340 while(resourceTypeName && rtPointer)
4342 if(rtPointer->resourcetypename &&
4343 strcmp(resourceTypeName, (const char *)
4344 (rtPointer->resourcetypename)) == 0)
4348 rtPointer = rtPointer->next;
4356 * Insert a new interface into interface linked list only if not already present.
4357 * If alredy present, 2nd arg is free'd.
4358 * Default interface will always be first if present.
4360 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4362 OCResourceInterface *pointer = NULL;
4363 OCResourceInterface *previous = NULL;
4365 newInterface->next = NULL;
4367 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4369 if (!*firstInterface)
4371 // If first interface is not oic.if.baseline, by default add it as first interface type.
4372 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4374 *firstInterface = newInterface;
4378 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4379 if (result != OC_STACK_OK)
4381 OICFree(newInterface->name);
4382 OICFree(newInterface);
4385 if (*firstInterface)
4387 (*firstInterface)->next = newInterface;
4391 // If once add oic.if.baseline, later too below code take care of freeing memory.
4392 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4394 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4396 OICFree(newInterface->name);
4397 OICFree(newInterface);
4400 // This code will not hit anymore, keeping
4403 newInterface->next = *firstInterface;
4404 *firstInterface = newInterface;
4409 pointer = *firstInterface;
4412 if (strcmp(newInterface->name, pointer->name) == 0)
4414 OICFree(newInterface->name);
4415 OICFree(newInterface);
4419 pointer = pointer->next;
4421 previous->next = newInterface;
4425 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4428 OCResource *resource = NULL;
4429 OCResourceInterface *pointer = NULL;
4431 // Find the specified resource
4432 resource = findResource((OCResource *) handle);
4438 // Make sure a resource has a resourceinterface
4439 if (!resource->rsrcInterface)
4444 // Iterate through the list
4445 pointer = resource->rsrcInterface;
4447 for (uint8_t i = 0; i < index && pointer; ++i)
4449 pointer = pointer->next;
4455 * This function splits the uri using the '?' delimiter.
4456 * "uriWithoutQuery" is the block of characters between the beginning
4457 * till the delimiter or '\0' which ever comes first.
4458 * "query" is whatever is to the right of the delimiter if present.
4459 * No delimiter sets the query to NULL.
4460 * If either are present, they will be malloc'ed into the params 2, 3.
4461 * The first param, *uri is left untouched.
4463 * NOTE: This function does not account for whitespace at the end of the uri NOR
4464 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4465 * part of the query.
4467 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4471 return OC_STACK_INVALID_URI;
4473 if(!query || !uriWithoutQuery)
4475 return OC_STACK_INVALID_PARAM;
4479 *uriWithoutQuery = NULL;
4481 size_t uriWithoutQueryLen = 0;
4482 size_t queryLen = 0;
4483 size_t uriLen = strlen(uri);
4485 char *pointerToDelimiter = strstr(uri, "?");
4487 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4488 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4490 if (uriWithoutQueryLen)
4492 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4493 if (!*uriWithoutQuery)
4497 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4501 *query = (char *) OICCalloc(queryLen + 1, 1);
4504 OICFree(*uriWithoutQuery);
4505 *uriWithoutQuery = NULL;
4508 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4514 return OC_STACK_NO_MEMORY;
4517 static const OicUuid_t* OCGetServerInstanceID(void)
4519 static bool generated = false;
4520 static OicUuid_t sid;
4526 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4528 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4535 const char* OCGetServerInstanceIDString(void)
4537 static bool generated = false;
4538 static char sidStr[UUID_STRING_SIZE];
4545 const OicUuid_t *sid = OCGetServerInstanceID();
4546 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4548 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4556 CAResult_t OCSelectNetwork()
4558 CAResult_t retResult = CA_STATUS_FAILED;
4559 CAResult_t caResult = CA_STATUS_OK;
4561 CATransportAdapter_t connTypes[] = {
4563 CA_ADAPTER_RFCOMM_BTEDR,
4564 CA_ADAPTER_GATT_BTLE,
4567 ,CA_ADAPTER_REMOTE_ACCESS
4574 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4576 for(int i = 0; i<numConnTypes; i++)
4578 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4579 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4581 caResult = CASelectNetwork(connTypes[i]);
4582 if(caResult == CA_STATUS_OK)
4584 retResult = CA_STATUS_OK;
4589 if(retResult != CA_STATUS_OK)
4591 return caResult; // Returns error of appropriate transport that failed fatally.
4597 OCStackResult CAResultToOCResult(CAResult_t caResult)
4603 case CA_STATUS_INVALID_PARAM:
4604 return OC_STACK_INVALID_PARAM;
4605 case CA_ADAPTER_NOT_ENABLED:
4606 return OC_STACK_ADAPTER_NOT_ENABLED;
4607 case CA_SERVER_STARTED_ALREADY:
4609 case CA_SERVER_NOT_STARTED:
4610 return OC_STACK_ERROR;
4611 case CA_DESTINATION_NOT_REACHABLE:
4612 return OC_STACK_COMM_ERROR;
4613 case CA_SOCKET_OPERATION_FAILED:
4614 return OC_STACK_COMM_ERROR;
4615 case CA_SEND_FAILED:
4616 return OC_STACK_COMM_ERROR;
4617 case CA_RECEIVE_FAILED:
4618 return OC_STACK_COMM_ERROR;
4619 case CA_MEMORY_ALLOC_FAILED:
4620 return OC_STACK_NO_MEMORY;
4621 case CA_REQUEST_TIMEOUT:
4622 return OC_STACK_TIMEOUT;
4623 case CA_DESTINATION_DISCONNECTED:
4624 return OC_STACK_COMM_ERROR;
4625 case CA_STATUS_FAILED:
4626 return OC_STACK_ERROR;
4627 case CA_NOT_SUPPORTED:
4628 return OC_STACK_NOTIMPL;
4630 return OC_STACK_ERROR;