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 //-----------------------------------------------------------------------------
139 //-----------------------------------------------------------------------------
140 #define TAG "OIC_RI_STACK"
141 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
142 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
143 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
144 TAG, #arg " is NULL"); return (retVal); } }
145 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
146 TAG, #arg " is NULL"); return; } }
147 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
150 //TODO: we should allow the server to define this
151 #define MAX_OBSERVE_AGE (0x2FFFFUL)
153 #define MILLISECONDS_PER_SECOND (1000)
155 //-----------------------------------------------------------------------------
156 // Private internal function prototypes
157 //-----------------------------------------------------------------------------
160 * Generate handle of OCDoResource invocation for callback management.
162 * @return Generated OCDoResource handle.
164 static OCDoHandle GenerateInvocationHandle();
167 * Initialize resource data structures, variables, etc.
169 * @return ::OC_STACK_OK on success, some other value upon failure.
171 static OCStackResult initResources();
174 * Add a resource to the end of the linked list of resources.
176 * @param resource Resource to be added
178 static void insertResource(OCResource *resource);
181 * Find a resource in the linked list of resources.
183 * @param resource Resource to be found.
184 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
187 static OCResource *findResource(OCResource *resource);
190 * Insert a resource type into a resource's resource type linked list.
191 * If resource type already exists, it will not be inserted and the
192 * resourceType will be free'd.
193 * resourceType->next should be null to avoid memory leaks.
194 * Function returns silently for null args.
196 * @param resource Resource where resource type is to be inserted.
197 * @param resourceType Resource type to be inserted.
199 static void insertResourceType(OCResource *resource,
200 OCResourceType *resourceType);
203 * Get a resource type at the specified index within a resource.
205 * @param handle Handle of resource.
206 * @param index Index of resource type.
208 * @return Pointer to resource type if found, NULL otherwise.
210 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
214 * Insert a resource interface into a resource's resource interface linked list.
215 * If resource interface already exists, it will not be inserted and the
216 * resourceInterface will be free'd.
217 * resourceInterface->next should be null to avoid memory leaks.
219 * @param resource Resource where resource interface is to be inserted.
220 * @param resourceInterface Resource interface to be inserted.
222 static void insertResourceInterface(OCResource *resource,
223 OCResourceInterface *resourceInterface);
226 * Get a resource interface at the specified index within a resource.
228 * @param handle Handle of resource.
229 * @param index Index of resource interface.
231 * @return Pointer to resource interface if found, NULL otherwise.
233 static OCResourceInterface *findResourceInterfaceAtIndex(
234 OCResourceHandle handle, uint8_t index);
237 * Delete all of the dynamically allocated elements that were created for the resource type.
239 * @param resourceType Specified resource type.
241 static void deleteResourceType(OCResourceType *resourceType);
244 * Delete all of the dynamically allocated elements that were created for the resource interface.
246 * @param resourceInterface Specified resource interface.
248 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
251 * Delete all of the dynamically allocated elements that were created for the resource.
253 * @param resource Specified resource.
255 static void deleteResourceElements(OCResource *resource);
258 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
261 * @param handle Handle of resource to be deleted.
263 * @return ::OC_STACK_OK on success, some other value upon failure.
265 static OCStackResult deleteResource(OCResource *resource);
268 * Delete all of the resources in the resource list.
270 static void deleteAllResources();
273 * Increment resource sequence number. Handles rollover.
275 * @param resPtr Pointer to resource.
277 static void incrementSequenceNumber(OCResource * resPtr);
280 * Attempts to initialize every network interface that the CA Layer might have compiled in.
282 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
283 * return something other than @ref CA_STATUS_OK, then this function fails.
285 * @return ::CA_STATUS_OK on success, some other value upon failure.
287 static CAResult_t OCSelectNetwork();
290 * Get the CoAP ticks after the specified number of milli-seconds.
292 * @param afterMilliSeconds Milli-seconds.
296 static uint32_t GetTicks(uint32_t afterMilliSeconds);
299 * Convert CAResult_t to OCStackResult.
301 * @param caResult CAResult_t code.
302 * @return ::OC_STACK_OK on success, some other value upon failure.
304 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
307 * Convert CAResponseResult_t to OCStackResult.
309 * @param caCode CAResponseResult_t code.
310 * @return ::OC_STACK_OK on success, some other value upon failure.
312 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
315 * Convert OCStackResult to CAResponseResult_t.
317 * @param caCode OCStackResult code.
318 * @param method OCMethod method the return code replies to.
319 * @return ::CA_CONTENT on OK, some other value upon failure.
321 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
324 * Convert OCTransportFlags_t to CATransportModifiers_t.
326 * @param ocConType OCTransportFlags_t input.
327 * @return CATransportFlags
329 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
332 * Convert CATransportFlags_t to OCTransportModifiers_t.
334 * @param caConType CATransportFlags_t input.
335 * @return OCTransportFlags
337 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
340 * Handle response from presence request.
342 * @param endPoint CA remote endpoint.
343 * @param responseInfo CA response info.
344 * @return ::OC_STACK_OK on success, some other value upon failure.
346 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
347 const CAResponseInfo_t *responseInfo);
350 * This function will be called back by CA layer when a response is received.
352 * @param endPoint CA remote endpoint.
353 * @param responseInfo CA response info.
355 static void HandleCAResponses(const CAEndpoint_t* endPoint,
356 const CAResponseInfo_t* responseInfo);
359 * This function will be called back by CA layer when a request is received.
361 * @param endPoint CA remote endpoint.
362 * @param requestInfo CA request info.
364 static void HandleCARequests(const CAEndpoint_t* endPoint,
365 const CARequestInfo_t* requestInfo);
368 * Extract query from a URI.
370 * @param uri Full URI with query.
371 * @param query Pointer to string that will contain query.
372 * @param newURI Pointer to string that will contain URI.
373 * @return ::OC_STACK_OK on success, some other value upon failure.
375 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
378 * Finds a resource type in an OCResourceType link-list.
380 * @param resourceTypeList The link-list to be searched through.
381 * @param resourceTypeName The key to search for.
383 * @return Resource type that matches the key (ie. resourceTypeName) or
384 * NULL if there is either an invalid parameter or this function was unable to find the key.
386 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
387 const char * resourceTypeName);
390 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
391 * TTL will be set to maxAge.
393 * @param cbNode Callback Node for which presence ttl is to be reset.
394 * @param maxAge New value of ttl in seconds.
396 * @return ::OC_STACK_OK on success, some other value upon failure.
398 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
401 * Ensure the accept header option is set appropriatly before sending the requests and routing
402 * header option is updated with destination.
404 * @param object CA remote endpoint.
405 * @param requestInfo CA request info.
407 * @return ::OC_STACK_OK on success, some other value upon failure.
409 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
411 //-----------------------------------------------------------------------------
412 // Internal functions
413 //-----------------------------------------------------------------------------
415 uint32_t GetTicks(uint32_t afterMilliSeconds)
420 // Guard against overflow of uint32_t
421 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
422 COAP_TICKS_PER_SECOND)
424 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
432 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
434 VERIFY_NON_NULL_NR(in, FATAL);
435 VERIFY_NON_NULL_NR(out, FATAL);
437 out->adapter = (OCTransportAdapter)in->adapter;
438 out->flags = CAToOCTransportFlags(in->flags);
439 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
440 out->port = in->port;
441 out->ifindex = in->ifindex;
442 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
443 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
447 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
449 VERIFY_NON_NULL_NR(in, FATAL);
450 VERIFY_NON_NULL_NR(out, FATAL);
452 out->adapter = (CATransportAdapter_t)in->adapter;
453 out->flags = OCToCATransportFlags(in->flags);
454 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
455 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
456 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
458 out->port = in->port;
459 out->ifindex = in->ifindex;
462 void FixUpClientResponse(OCClientResponse *cr)
464 VERIFY_NON_NULL_NR(cr, FATAL);
466 cr->addr = &cr->devAddr;
467 cr->connType = (OCConnectivityType)
468 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
471 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
473 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
474 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
476 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
477 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
478 if (OC_STACK_OK != rmResult)
480 OIC_LOG(ERROR, TAG, "Add destination option failed");
485 // OC stack prefer CBOR encoded payloads.
486 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
487 CAResult_t result = CASendRequest(object, requestInfo);
488 if(CA_STATUS_OK != result)
490 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
491 return CAResultToOCResult(result);
495 //-----------------------------------------------------------------------------
496 // Internal API function
497 //-----------------------------------------------------------------------------
499 // This internal function is called to update the stack with the status of
500 // observers and communication failures
501 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
503 OCStackResult result = OC_STACK_ERROR;
504 ResourceObserver * observer = NULL;
505 OCEntityHandlerRequest ehRequest = {0};
509 case OC_OBSERVER_NOT_INTERESTED:
510 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
511 observer = GetObserverUsingToken (token, tokenLength);
514 result = FormOCEntityHandlerRequest(&ehRequest,
515 (OCRequestHandle)NULL,
518 (OCResourceHandle)NULL,
519 NULL, PAYLOAD_TYPE_REPRESENTATION,
521 OC_OBSERVE_DEREGISTER,
522 observer->observeId);
523 if(result != OC_STACK_OK)
527 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
528 observer->resource->entityHandlerCallbackParam);
531 result = DeleteObserverUsingToken (token, tokenLength);
532 if(result == OC_STACK_OK)
534 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
538 result = OC_STACK_OK;
539 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
543 case OC_OBSERVER_STILL_INTERESTED:
544 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
545 observer = GetObserverUsingToken (token, tokenLength);
548 observer->forceHighQos = 0;
549 observer->failedCommCount = 0;
550 result = OC_STACK_OK;
554 result = OC_STACK_OBSERVER_NOT_FOUND;
558 case OC_OBSERVER_FAILED_COMM:
559 OIC_LOG(DEBUG, TAG, "observer is unreachable");
560 observer = GetObserverUsingToken (token, tokenLength);
563 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
565 result = FormOCEntityHandlerRequest(&ehRequest,
566 (OCRequestHandle)NULL,
569 (OCResourceHandle)NULL,
570 NULL, PAYLOAD_TYPE_REPRESENTATION,
572 OC_OBSERVE_DEREGISTER,
573 observer->observeId);
574 if(result != OC_STACK_OK)
576 return OC_STACK_ERROR;
578 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
579 observer->resource->entityHandlerCallbackParam);
581 result = DeleteObserverUsingToken (token, tokenLength);
582 if(result == OC_STACK_OK)
584 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
588 result = OC_STACK_OK;
589 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
594 observer->failedCommCount++;
595 result = OC_STACK_CONTINUE;
597 observer->forceHighQos = 1;
598 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
602 OIC_LOG(ERROR, TAG, "Unknown status");
603 result = OC_STACK_ERROR;
609 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
611 OCStackResult ret = OC_STACK_ERROR;
615 case CA_ADAPTER_NOT_ENABLED:
616 case CA_SERVER_NOT_STARTED:
617 ret = OC_STACK_ADAPTER_NOT_ENABLED;
619 case CA_MEMORY_ALLOC_FAILED:
620 ret = OC_STACK_NO_MEMORY;
622 case CA_STATUS_INVALID_PARAM:
623 ret = OC_STACK_INVALID_PARAM;
631 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
633 OCStackResult ret = OC_STACK_ERROR;
638 ret = OC_STACK_RESOURCE_CREATED;
641 ret = OC_STACK_RESOURCE_DELETED;
649 ret = OC_STACK_INVALID_QUERY;
651 case CA_UNAUTHORIZED_REQ:
652 ret = OC_STACK_UNAUTHORIZED_REQ;
655 ret = OC_STACK_INVALID_OPTION;
658 ret = OC_STACK_NO_RESOURCE;
660 case CA_RETRANSMIT_TIMEOUT:
661 ret = OC_STACK_COMM_ERROR;
663 case CA_REQUEST_ENTITY_TOO_LARGE:
664 ret = OC_STACK_TOO_LARGE_REQ;
672 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
674 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
683 // This Response Code is like HTTP 204 "No Content" but only used in
684 // response to POST and PUT requests.
688 // This Response Code is like HTTP 200 "OK" but only used in response to
693 // This should not happen but,
694 // give it a value just in case but output an error
696 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
699 case OC_STACK_RESOURCE_CREATED:
702 case OC_STACK_RESOURCE_DELETED:
705 case OC_STACK_INVALID_QUERY:
708 case OC_STACK_INVALID_OPTION:
711 case OC_STACK_NO_RESOURCE:
714 case OC_STACK_COMM_ERROR:
715 ret = CA_RETRANSMIT_TIMEOUT;
717 case OC_STACK_UNAUTHORIZED_REQ:
718 ret = CA_UNAUTHORIZED_REQ;
726 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
728 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
730 // supply default behavior.
731 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
733 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
735 if ((caFlags & OC_MASK_SCOPE) == 0)
737 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
742 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
744 return (OCTransportFlags)caFlags;
747 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
749 uint32_t lowerBound = 0;
750 uint32_t higherBound = 0;
752 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
754 return OC_STACK_INVALID_PARAM;
757 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
759 cbNode->presence->TTL = maxAgeSeconds;
761 for (int index = 0; index < PresenceTimeOutSize; index++)
763 // Guard against overflow
764 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
767 lowerBound = GetTicks((PresenceTimeOut[index] *
768 cbNode->presence->TTL *
769 MILLISECONDS_PER_SECOND)/100);
773 lowerBound = GetTicks(UINT32_MAX);
776 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
779 higherBound = GetTicks((PresenceTimeOut[index + 1] *
780 cbNode->presence->TTL *
781 MILLISECONDS_PER_SECOND)/100);
785 higherBound = GetTicks(UINT32_MAX);
788 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
790 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
791 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
792 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
795 cbNode->presence->TTLlevel = 0;
797 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
801 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
803 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
805 return OC_RSRVD_TRIGGER_CREATE;
807 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
809 return OC_RSRVD_TRIGGER_CHANGE;
813 return OC_RSRVD_TRIGGER_DELETE;
817 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
821 return OC_PRESENCE_TRIGGER_CREATE;
823 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
825 return OC_PRESENCE_TRIGGER_CREATE;
827 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
829 return OC_PRESENCE_TRIGGER_CHANGE;
833 return OC_PRESENCE_TRIGGER_DELETE;
838 * The cononical presence allows constructed URIs to be string compared.
840 * requestUri must be a char array of size CA_MAX_URI_LENGTH
842 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
845 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
846 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
847 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
849 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
851 if (ep->adapter == CA_ADAPTER_IP)
853 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
855 if ('\0' == ep->addr[0]) // multicast
857 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
861 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
862 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
867 if ('\0' == ep->addr[0]) // multicast
869 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
870 ep->port = OC_MULTICAST_PORT;
872 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
873 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
877 // might work for other adapters (untested, but better than nothing)
878 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
879 OC_RSRVD_PRESENCE_URI);
883 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
884 const CAResponseInfo_t *responseInfo)
886 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
887 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
889 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
890 ClientCB * cbNode = NULL;
891 char *resourceTypeName = NULL;
892 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
893 OCStackResult result = OC_STACK_ERROR;
896 char presenceUri[CA_MAX_URI_LENGTH];
898 int presenceSubscribe = 0;
899 int multicastPresenceSubscribe = 0;
901 if (responseInfo->result != CA_CONTENT)
903 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
904 return OC_STACK_ERROR;
907 // check for unicast presence
908 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
909 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
911 return OC_STACK_INVALID_URI;
914 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
917 presenceSubscribe = 1;
921 // check for multiicast presence
922 CAEndpoint_t ep = { .adapter = endpoint->adapter,
923 .flags = endpoint->flags };
925 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
927 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
930 multicastPresenceSubscribe = 1;
934 if (!presenceSubscribe && !multicastPresenceSubscribe)
936 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
940 response.payload = NULL;
941 response.result = OC_STACK_OK;
943 CopyEndpointToDevAddr(endpoint, &response.devAddr);
944 FixUpClientResponse(&response);
946 if (responseInfo->info.payload)
948 result = OCParsePayload(&response.payload,
949 PAYLOAD_TYPE_PRESENCE,
950 responseInfo->info.payload,
951 responseInfo->info.payloadSize);
953 if(result != OC_STACK_OK)
955 OIC_LOG(ERROR, TAG, "Presence parse failed");
958 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
960 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
961 result = OC_STACK_ERROR;
964 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
965 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
966 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
969 if (presenceSubscribe)
971 if(cbNode->sequenceNumber == response.sequenceNumber)
973 OIC_LOG(INFO, TAG, "No presence change");
974 ResetPresenceTTL(cbNode, maxAge);
975 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
981 OIC_LOG(INFO, TAG, "Stopping presence");
982 response.result = OC_STACK_PRESENCE_STOPPED;
985 OICFree(cbNode->presence->timeOut);
986 OICFree(cbNode->presence);
987 cbNode->presence = NULL;
992 if(!cbNode->presence)
994 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
996 if(!(cbNode->presence))
998 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
999 result = OC_STACK_NO_MEMORY;
1003 VERIFY_NON_NULL_V(cbNode->presence);
1004 cbNode->presence->timeOut = NULL;
1005 cbNode->presence->timeOut = (uint32_t *)
1006 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1007 if(!(cbNode->presence->timeOut)){
1009 "Could not allocate memory for cbNode->presence->timeOut");
1010 OICFree(cbNode->presence);
1011 result = OC_STACK_NO_MEMORY;
1016 ResetPresenceTTL(cbNode, maxAge);
1018 cbNode->sequenceNumber = response.sequenceNumber;
1020 // Ensure that a filter is actually applied.
1021 if( resourceTypeName && cbNode->filterResourceType)
1023 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1032 // This is the multicast case
1033 OCMulticastNode* mcNode = NULL;
1034 mcNode = GetMCPresenceNode(presenceUri);
1038 if(mcNode->nonce == response.sequenceNumber)
1040 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1043 mcNode->nonce = response.sequenceNumber;
1047 OIC_LOG(INFO, TAG, "Stopping presence");
1048 response.result = OC_STACK_PRESENCE_STOPPED;
1053 char* uri = OICStrdup(presenceUri);
1057 "No Memory for URI to store in the presence node");
1058 result = OC_STACK_NO_MEMORY;
1062 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1063 if(result == OC_STACK_NO_MEMORY)
1066 "No Memory for Multicast Presence Node");
1070 // presence node now owns uri
1073 // Ensure that a filter is actually applied.
1074 if(resourceTypeName && cbNode->filterResourceType)
1076 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1083 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1085 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1087 FindAndDeleteClientCB(cbNode);
1091 OCPayloadDestroy(response.payload);
1095 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1097 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1099 if(responseInfo->info.resourceUri &&
1100 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1102 HandlePresenceResponse(endPoint, responseInfo);
1106 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1107 responseInfo->info.tokenLength, NULL, NULL);
1109 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1110 responseInfo->info.tokenLength);
1114 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1115 if(responseInfo->result == CA_EMPTY)
1117 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1118 // We do not have a case for the client to receive a RESET
1119 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1121 //This is the case of receiving an ACK on a request to a slow resource!
1122 OIC_LOG(INFO, TAG, "This is a pure ACK");
1123 //TODO: should we inform the client
1124 // app that at least the request was received at the server?
1127 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1129 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1130 OIC_LOG(INFO, TAG, "Calling into application address space");
1132 OCClientResponse response =
1133 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1134 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1135 FixUpClientResponse(&response);
1136 response.resourceUri = responseInfo->info.resourceUri;
1137 memcpy(response.identity.id, responseInfo->info.identity.id,
1138 sizeof (response.identity.id));
1139 response.identity.id_length = responseInfo->info.identity.id_length;
1141 response.result = CAResponseToOCStackResult(responseInfo->result);
1142 cbNode->callBack(cbNode->context,
1143 cbNode->handle, &response);
1144 FindAndDeleteClientCB(cbNode);
1148 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1149 OIC_LOG(INFO, TAG, "Calling into application address space");
1151 OCClientResponse response =
1152 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1153 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1154 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1155 FixUpClientResponse(&response);
1156 response.resourceUri = responseInfo->info.resourceUri;
1157 memcpy(response.identity.id, responseInfo->info.identity.id,
1158 sizeof (response.identity.id));
1159 response.identity.id_length = responseInfo->info.identity.id_length;
1161 response.result = CAResponseToOCStackResult(responseInfo->result);
1163 if(responseInfo->info.payload &&
1164 responseInfo->info.payloadSize)
1166 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1167 // check the security resource
1168 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1170 type = PAYLOAD_TYPE_SECURITY;
1172 else if (cbNode->method == OC_REST_DISCOVER)
1174 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1175 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1177 type = PAYLOAD_TYPE_DISCOVERY;
1179 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1181 type = PAYLOAD_TYPE_DEVICE;
1183 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1185 type = PAYLOAD_TYPE_PLATFORM;
1187 #ifdef ROUTING_GATEWAY
1188 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1190 type = PAYLOAD_TYPE_REPRESENTATION;
1193 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1195 type = PAYLOAD_TYPE_RD;
1198 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1200 type = PAYLOAD_TYPE_REPRESENTATION;
1205 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1206 cbNode->method, cbNode->requestUri);
1210 else if (cbNode->method == OC_REST_GET ||
1211 cbNode->method == OC_REST_PUT ||
1212 cbNode->method == OC_REST_POST ||
1213 cbNode->method == OC_REST_OBSERVE ||
1214 cbNode->method == OC_REST_OBSERVE_ALL ||
1215 cbNode->method == OC_REST_DELETE)
1217 char targetUri[MAX_URI_LENGTH];
1218 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1219 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1220 if (strcmp(targetUri, cbNode->requestUri) == 0)
1222 type = PAYLOAD_TYPE_RD;
1224 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1226 type = PAYLOAD_TYPE_PLATFORM;
1228 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1230 type = PAYLOAD_TYPE_DEVICE;
1232 if (type == PAYLOAD_TYPE_INVALID)
1234 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1235 cbNode->method, cbNode->requestUri);
1236 type = PAYLOAD_TYPE_REPRESENTATION;
1241 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1242 cbNode->method, cbNode->requestUri);
1246 if(OC_STACK_OK != OCParsePayload(&response.payload,
1248 responseInfo->info.payload,
1249 responseInfo->info.payloadSize))
1251 OIC_LOG(ERROR, TAG, "Error converting payload");
1252 OCPayloadDestroy(response.payload);
1257 response.numRcvdVendorSpecificHeaderOptions = 0;
1258 if(responseInfo->info.numOptions > 0)
1261 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1262 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1265 uint32_t observationOption;
1266 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1267 for (observationOption=0, i=0;
1268 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1272 (observationOption << 8) | optionData[i];
1274 response.sequenceNumber = observationOption;
1276 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1281 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1284 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1286 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1287 OCPayloadDestroy(response.payload);
1291 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1293 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1294 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1298 if (cbNode->method == OC_REST_OBSERVE &&
1299 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1300 response.sequenceNumber <= cbNode->sequenceNumber)
1302 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1303 response.sequenceNumber);
1307 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1310 cbNode->sequenceNumber = response.sequenceNumber;
1312 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1314 FindAndDeleteClientCB(cbNode);
1318 // To keep discovery callbacks active.
1319 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1320 MILLISECONDS_PER_SECOND);
1324 //Need to send ACK when the response is CON
1325 if(responseInfo->info.type == CA_MSG_CONFIRM)
1327 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1328 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1331 OCPayloadDestroy(response.payload);
1338 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1339 if(responseInfo->result == CA_EMPTY)
1341 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1342 if(responseInfo->info.type == CA_MSG_RESET)
1344 OIC_LOG(INFO, TAG, "This is a RESET");
1345 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1346 OC_OBSERVER_NOT_INTERESTED);
1348 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1350 OIC_LOG(INFO, TAG, "This is a pure ACK");
1351 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1352 OC_OBSERVER_STILL_INTERESTED);
1355 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1357 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1358 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1359 OC_OBSERVER_FAILED_COMM);
1364 if(!cbNode && !observer)
1366 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1367 || myStackMode == OC_GATEWAY)
1369 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1370 if(responseInfo->result == CA_EMPTY)
1372 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1376 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1377 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1378 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1382 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1383 || myStackMode == OC_GATEWAY)
1385 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1386 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1388 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1389 responseInfo->info.messageId);
1391 if (responseInfo->info.type == CA_MSG_RESET)
1393 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1394 responseInfo->info.messageId);
1401 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1404 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1406 VERIFY_NON_NULL_NR(endPoint, FATAL);
1407 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1409 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1411 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1412 #ifdef ROUTING_GATEWAY
1413 bool needRIHandling = false;
1415 * Routing manager is going to update either of endpoint or response or both.
1416 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1417 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1420 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1422 if(ret != OC_STACK_OK || !needRIHandling)
1424 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1430 * Put source in sender endpoint so that the next packet from application can be routed to
1431 * proper destination and remove "RM" coap header option before passing request / response to
1432 * RI as this option will make no sense to either RI or application.
1434 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1435 (uint8_t *) &(responseInfo->info.numOptions),
1436 (CAEndpoint_t *) endPoint);
1439 OCHandleResponse(endPoint, responseInfo);
1441 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1445 * This function handles error response from CA
1446 * code shall be added to handle the errors
1448 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1450 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1452 if (NULL == endPoint)
1454 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1458 if (NULL == errorInfo)
1460 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1464 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1465 errorInfo->info.tokenLength, NULL, NULL);
1468 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1469 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1470 FixUpClientResponse(&response);
1471 response.resourceUri = errorInfo->info.resourceUri;
1472 memcpy(response.identity.id, errorInfo->info.identity.id,
1473 sizeof (response.identity.id));
1474 response.identity.id_length = errorInfo->info.identity.id_length;
1475 response.result = CAResultToOCStackResult(errorInfo->result);
1477 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1478 FindAndDeleteClientCB(cbNode);
1481 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1485 * This function sends out Direct Stack Responses. These are responses that are not coming
1486 * from the application entity handler. These responses have no payload and are usually ACKs,
1487 * RESETs or some error conditions that were caught by the stack.
1489 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1490 const CAResponseResult_t responseResult, const CAMessageType_t type,
1491 const uint8_t numOptions, const CAHeaderOption_t *options,
1492 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1494 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1495 CAResponseInfo_t respInfo = {
1496 .result = responseResult
1498 respInfo.info.messageId = coapID;
1499 respInfo.info.numOptions = numOptions;
1501 if (respInfo.info.numOptions)
1503 respInfo.info.options =
1504 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1505 memcpy (respInfo.info.options, options,
1506 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1510 respInfo.info.payload = NULL;
1511 respInfo.info.token = token;
1512 respInfo.info.tokenLength = tokenLength;
1513 respInfo.info.type = type;
1514 respInfo.info.resourceUri = OICStrdup (resourceUri);
1515 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1517 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1518 // Add the destination to route option from the endpoint->routeData.
1519 bool doPost = false;
1520 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1521 if(OC_STACK_OK != result)
1523 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1528 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1529 CARequestInfo_t reqInfo = {.method = CA_POST };
1530 /* The following initialization is not done in a single initializer block as in
1531 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1532 * does not have designated initalizers. This is a work-around for now.
1534 reqInfo.info.type = CA_MSG_NONCONFIRM;
1535 reqInfo.info.messageId = coapID;
1536 reqInfo.info.tokenLength = tokenLength;
1537 reqInfo.info.token = token;
1538 reqInfo.info.numOptions = respInfo.info.numOptions;
1539 reqInfo.info.payload = NULL;
1540 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1541 if (reqInfo.info.numOptions)
1543 reqInfo.info.options =
1544 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1545 if (NULL == reqInfo.info.options)
1547 OIC_LOG(ERROR, TAG, "Calloc failed");
1548 return OC_STACK_NO_MEMORY;
1550 memcpy (reqInfo.info.options, respInfo.info.options,
1551 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1554 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1555 OICFree (reqInfo.info.resourceUri);
1556 OICFree (reqInfo.info.options);
1557 OICFree (respInfo.info.resourceUri);
1558 OICFree (respInfo.info.options);
1559 if (CA_STATUS_OK != caResult)
1561 OIC_LOG(ERROR, TAG, "CASendRequest error");
1562 return CAResultToOCResult(caResult);
1568 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1570 // resourceUri in the info field is cloned in the CA layer and
1571 // thus ownership is still here.
1572 OICFree (respInfo.info.resourceUri);
1573 OICFree (respInfo.info.options);
1574 if(CA_STATUS_OK != caResult)
1576 OIC_LOG(ERROR, TAG, "CASendResponse error");
1577 return CAResultToOCResult(caResult);
1580 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1584 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1586 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1587 OCStackResult result = OC_STACK_ERROR;
1588 if(!protocolRequest)
1590 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1591 return OC_STACK_INVALID_PARAM;
1594 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1595 protocolRequest->tokenLength);
1598 OIC_LOG(INFO, TAG, "This is a new Server Request");
1599 result = AddServerRequest(&request, protocolRequest->coapID,
1600 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1601 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1602 protocolRequest->observationOption, protocolRequest->qos,
1603 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1604 protocolRequest->payload, protocolRequest->requestToken,
1605 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1606 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1607 &protocolRequest->devAddr);
1608 if (OC_STACK_OK != result)
1610 OIC_LOG(ERROR, TAG, "Error adding server request");
1616 OIC_LOG(ERROR, TAG, "Out of Memory");
1617 return OC_STACK_NO_MEMORY;
1620 if(!protocolRequest->reqMorePacket)
1622 request->requestComplete = 1;
1627 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1630 if(request->requestComplete)
1632 OIC_LOG(INFO, TAG, "This Server Request is complete");
1633 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1634 OCResource *resource = NULL;
1635 result = DetermineResourceHandling (request, &resHandling, &resource);
1636 if (result == OC_STACK_OK)
1638 result = ProcessRequest(resHandling, resource, request);
1643 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1644 result = OC_STACK_CONTINUE;
1649 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1651 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1654 if (requestInfo->info.resourceUri &&
1655 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1657 HandleKeepAliveRequest(endPoint, requestInfo);
1662 OCStackResult requestResult = OC_STACK_ERROR;
1664 if(myStackMode == OC_CLIENT)
1666 //TODO: should the client be responding to requests?
1670 OCServerProtocolRequest serverRequest = {0};
1672 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1674 char * uriWithoutQuery = NULL;
1675 char * query = NULL;
1677 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1679 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1681 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1684 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1685 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1687 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1689 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1690 OICFree(uriWithoutQuery);
1694 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1695 OICFree(uriWithoutQuery);
1702 if(strlen(query) < MAX_QUERY_LENGTH)
1704 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1709 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1715 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1717 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1718 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1719 if (!serverRequest.payload)
1721 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1724 memcpy (serverRequest.payload, requestInfo->info.payload,
1725 requestInfo->info.payloadSize);
1729 serverRequest.reqTotalSize = 0;
1732 switch (requestInfo->method)
1735 serverRequest.method = OC_REST_GET;
1738 serverRequest.method = OC_REST_PUT;
1741 serverRequest.method = OC_REST_POST;
1744 serverRequest.method = OC_REST_DELETE;
1747 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1748 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1749 requestInfo->info.type, requestInfo->info.numOptions,
1750 requestInfo->info.options, requestInfo->info.token,
1751 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1752 OICFree(serverRequest.payload);
1756 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1757 requestInfo->info.tokenLength);
1759 serverRequest.tokenLength = requestInfo->info.tokenLength;
1760 if (serverRequest.tokenLength) {
1762 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1764 if (!serverRequest.requestToken)
1766 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1767 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1768 requestInfo->info.type, requestInfo->info.numOptions,
1769 requestInfo->info.options, requestInfo->info.token,
1770 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1771 OICFree(serverRequest.payload);
1774 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1777 switch (requestInfo->info.acceptFormat)
1779 case CA_FORMAT_APPLICATION_CBOR:
1780 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1782 case CA_FORMAT_UNDEFINED:
1783 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1786 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1789 if (requestInfo->info.type == CA_MSG_CONFIRM)
1791 serverRequest.qos = OC_HIGH_QOS;
1795 serverRequest.qos = OC_LOW_QOS;
1797 // CA does not need the following field
1798 // Are we sure CA does not need them? how is it responding to multicast
1799 serverRequest.delayedResNeeded = 0;
1801 serverRequest.coapID = requestInfo->info.messageId;
1803 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1805 // copy vendor specific header options
1806 uint8_t tempNum = (requestInfo->info.numOptions);
1808 // Assume no observation requested and it is a pure GET.
1809 // If obs registration/de-registration requested it'll be fetched from the
1810 // options in GetObserveHeaderOption()
1811 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1813 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1814 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1817 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1818 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1819 requestInfo->info.type, requestInfo->info.numOptions,
1820 requestInfo->info.options, requestInfo->info.token,
1821 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1822 OICFree(serverRequest.payload);
1823 OICFree(serverRequest.requestToken);
1826 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1827 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1829 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1830 sizeof(CAHeaderOption_t)*tempNum);
1833 requestResult = HandleStackRequests (&serverRequest);
1835 // Send ACK to client as precursor to slow response
1836 if (requestResult == OC_STACK_SLOW_RESOURCE)
1838 if (requestInfo->info.type == CA_MSG_CONFIRM)
1840 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1841 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1844 else if(requestResult != OC_STACK_OK)
1846 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1848 CAResponseResult_t stackResponse =
1849 OCToCAStackResult(requestResult, serverRequest.method);
1851 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1852 requestInfo->info.type, requestInfo->info.numOptions,
1853 requestInfo->info.options, requestInfo->info.token,
1854 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1856 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1857 // The token is copied in there, and is thus still owned by this function.
1858 OICFree(serverRequest.payload);
1859 OICFree(serverRequest.requestToken);
1860 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1863 //This function will be called back by CA layer when a request is received
1864 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1866 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1869 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1875 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1879 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1880 #ifdef ROUTING_GATEWAY
1881 bool needRIHandling = false;
1882 bool isEmptyMsg = false;
1884 * Routing manager is going to update either of endpoint or request or both.
1885 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1886 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1887 * destination. It can also remove "RM" coap header option before passing request / response to
1888 * RI as this option will make no sense to either RI or application.
1890 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1891 &needRIHandling, &isEmptyMsg);
1892 if(OC_STACK_OK != ret || !needRIHandling)
1894 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1900 * Put source in sender endpoint so that the next packet from application can be routed to
1901 * proper destination and remove RM header option.
1903 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1904 (uint8_t *) &(requestInfo->info.numOptions),
1905 (CAEndpoint_t *) endPoint);
1907 #ifdef ROUTING_GATEWAY
1911 * In Gateways, the MSGType in route option is used to check if the actual
1912 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
1913 * EMPTY response is sent in the form of POST request which need to be changed
1914 * to a EMPTY response by RM. This translation is done in this part of the code.
1916 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1917 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1918 .info.messageId = requestInfo->info.messageId,
1919 .info.type = CA_MSG_ACKNOWLEDGE};
1920 OCHandleResponse(endPoint, &respInfo);
1926 // Normal handling of the packet
1927 OCHandleRequests(endPoint, requestInfo);
1929 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1932 bool validatePlatformInfo(OCPlatformInfo info)
1935 if (!info.platformID)
1937 OIC_LOG(ERROR, TAG, "No platform ID found.");
1941 if (info.manufacturerName)
1943 size_t lenManufacturerName = strlen(info.manufacturerName);
1945 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1947 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1953 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1957 if (info.manufacturerUrl)
1959 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1961 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1968 //-----------------------------------------------------------------------------
1970 //-----------------------------------------------------------------------------
1972 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1975 !raInfo->username ||
1976 !raInfo->hostname ||
1977 !raInfo->xmpp_domain)
1980 return OC_STACK_INVALID_PARAM;
1982 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1983 gRASetInfo = (result == OC_STACK_OK)? true : false;
1989 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1993 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1996 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1998 if(stackState == OC_STACK_INITIALIZED)
2000 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2001 OCStop() between them are ignored.");
2005 #ifndef ROUTING_GATEWAY
2006 if (OC_GATEWAY == mode)
2008 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2009 return OC_STACK_INVALID_PARAM;
2016 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2017 return OC_STACK_ERROR;
2021 OCStackResult result = OC_STACK_ERROR;
2022 OIC_LOG(INFO, TAG, "Entering OCInit");
2025 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2026 || (mode == OC_GATEWAY)))
2028 OIC_LOG(ERROR, TAG, "Invalid mode");
2029 return OC_STACK_ERROR;
2033 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2035 caglobals.client = true;
2037 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2039 caglobals.server = true;
2042 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2043 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2045 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2047 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2048 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2050 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2053 defaultDeviceHandler = NULL;
2054 defaultDeviceHandlerCallbackParameter = NULL;
2056 result = CAResultToOCResult(CAInitialize());
2057 VERIFY_SUCCESS(result, OC_STACK_OK);
2059 result = CAResultToOCResult(OCSelectNetwork());
2060 VERIFY_SUCCESS(result, OC_STACK_OK);
2062 switch (myStackMode)
2065 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2066 result = CAResultToOCResult(CAStartDiscoveryServer());
2067 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2070 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2071 result = CAResultToOCResult(CAStartListeningServer());
2072 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2074 case OC_CLIENT_SERVER:
2076 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2077 result = CAResultToOCResult(CAStartListeningServer());
2078 if(result == OC_STACK_OK)
2080 result = CAResultToOCResult(CAStartDiscoveryServer());
2084 VERIFY_SUCCESS(result, OC_STACK_OK);
2087 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2090 #ifdef WITH_PRESENCE
2091 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2092 #endif // WITH_PRESENCE
2094 //Update Stack state to initialized
2095 stackState = OC_STACK_INITIALIZED;
2097 // Initialize resource
2098 if(myStackMode != OC_CLIENT)
2100 result = initResources();
2103 // Initialize the SRM Policy Engine
2104 if(result == OC_STACK_OK)
2106 result = SRMInitPolicyEngine();
2107 // TODO after BeachHead delivery: consolidate into single SRMInit()
2109 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2110 RMSetStackMode(mode);
2111 #ifdef ROUTING_GATEWAY
2112 if (OC_GATEWAY == myStackMode)
2114 result = RMInitialize();
2120 if (result == OC_STACK_OK)
2122 result = InitializeKeepAlive(myStackMode);
2127 if(result != OC_STACK_OK)
2129 OIC_LOG(ERROR, TAG, "Stack initialization error");
2130 deleteAllResources();
2132 stackState = OC_STACK_UNINITIALIZED;
2137 OCStackResult OCStop()
2139 OIC_LOG(INFO, TAG, "Entering OCStop");
2141 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2143 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2146 else if (stackState != OC_STACK_INITIALIZED)
2148 OIC_LOG(ERROR, TAG, "Stack not initialized");
2149 return OC_STACK_ERROR;
2152 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2154 #ifdef WITH_PRESENCE
2155 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2156 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2157 presenceResource.presenceTTL = 0;
2158 #endif // WITH_PRESENCE
2160 #ifdef ROUTING_GATEWAY
2161 if (OC_GATEWAY == myStackMode)
2168 TerminateKeepAlive(myStackMode);
2171 // Free memory dynamically allocated for resources
2172 deleteAllResources();
2174 DeletePlatformInfo();
2176 // Remove all observers
2177 DeleteObserverList();
2178 // Remove all the client callbacks
2179 DeleteClientCBList();
2181 // De-init the SRM Policy Engine
2182 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2183 SRMDeInitPolicyEngine();
2186 stackState = OC_STACK_UNINITIALIZED;
2190 OCStackResult OCStartMulticastServer()
2192 if(stackState != OC_STACK_INITIALIZED)
2194 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2195 return OC_STACK_ERROR;
2197 CAResult_t ret = CAStartListeningServer();
2198 if (CA_STATUS_OK != ret)
2200 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2201 return OC_STACK_ERROR;
2206 OCStackResult OCStopMulticastServer()
2208 CAResult_t ret = CAStopListeningServer();
2209 if (CA_STATUS_OK != ret)
2211 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2212 return OC_STACK_ERROR;
2217 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2222 return CA_MSG_CONFIRM;
2227 return CA_MSG_NONCONFIRM;
2232 * A request uri consists of the following components in order:
2235 * CoAP over UDP prefix "coap://"
2236 * CoAP over TCP prefix "coap+tcp://"
2238 * IPv6 address "[1234::5678]"
2239 * IPv4 address "192.168.1.1"
2240 * optional port ":5683"
2241 * resource uri "/oc/core..."
2243 * for PRESENCE requests, extract resource type.
2245 static OCStackResult ParseRequestUri(const char *fullUri,
2246 OCTransportAdapter adapter,
2247 OCTransportFlags flags,
2248 OCDevAddr **devAddr,
2250 char **resourceType)
2252 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2254 OCStackResult result = OC_STACK_OK;
2255 OCDevAddr *da = NULL;
2259 // provide defaults for all returned values
2266 *resourceUri = NULL;
2270 *resourceType = NULL;
2273 // delimit url prefix, if any
2274 const char *start = fullUri;
2275 char *slash2 = strstr(start, "//");
2280 char *slash = strchr(start, '/');
2283 return OC_STACK_INVALID_URI;
2286 // process url scheme
2287 size_t prefixLen = slash2 - fullUri;
2291 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2297 // TODO: this logic should come in with unit tests exercising the various strings
2298 // processs url prefix, if any
2299 size_t urlLen = slash - start;
2303 if (urlLen && devAddr)
2304 { // construct OCDevAddr
2305 if (start[0] == '[')
2307 char *close = strchr(++start, ']');
2308 if (!close || close > slash)
2310 return OC_STACK_INVALID_URI;
2313 if (close[1] == ':')
2320 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2324 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2326 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2330 char *dot = strchr(start, '.');
2331 if (dot && dot < slash)
2333 colon = strchr(start, ':');
2334 end = (colon && colon < slash) ? colon : slash;
2339 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2343 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2345 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2353 if (len >= sizeof(da->addr))
2355 return OC_STACK_INVALID_URI;
2357 // collect port, if any
2358 if (colon && colon < slash)
2360 for (colon++; colon < slash; colon++)
2363 if (c < '0' || c > '9')
2365 return OC_STACK_INVALID_URI;
2367 port = 10 * port + c - '0';
2372 if (len >= sizeof(da->addr))
2374 return OC_STACK_INVALID_URI;
2377 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2380 return OC_STACK_NO_MEMORY;
2382 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2384 da->adapter = adapter;
2386 if (!strncmp(fullUri, "coaps:", 6))
2388 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2393 // process resource uri, if any
2395 { // request uri and query
2396 size_t ulen = strlen(slash); // resource uri length
2397 size_t tlen = 0; // resource type length
2400 static const char strPresence[] = "/oic/ad?rt=";
2401 static const size_t lenPresence = sizeof(strPresence) - 1;
2402 if (!strncmp(slash, strPresence, lenPresence))
2404 type = slash + lenPresence;
2405 tlen = ulen - lenPresence;
2410 *resourceUri = (char *)OICMalloc(ulen + 1);
2413 result = OC_STACK_NO_MEMORY;
2416 strcpy(*resourceUri, slash);
2419 if (type && resourceType)
2421 *resourceType = (char *)OICMalloc(tlen + 1);
2424 result = OC_STACK_NO_MEMORY;
2428 OICStrcpy(*resourceType, (tlen+1), type);
2435 // free all returned values
2442 OICFree(*resourceUri);
2446 OICFree(*resourceType);
2451 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2452 char *resourceUri, char **requestUri)
2454 char uri[CA_MAX_URI_LENGTH];
2456 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2458 *requestUri = OICStrdup(uri);
2461 return OC_STACK_NO_MEMORY;
2468 * Discover or Perform requests on a specified resource
2470 OCStackResult OCDoResource(OCDoHandle *handle,
2472 const char *requestUri,
2473 const OCDevAddr *destination,
2475 OCConnectivityType connectivityType,
2476 OCQualityOfService qos,
2477 OCCallbackData *cbData,
2478 OCHeaderOption *options,
2481 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2483 // Validate input parameters
2484 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2485 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2486 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2488 OCStackResult result = OC_STACK_ERROR;
2489 CAResult_t caResult;
2490 CAToken_t token = NULL;
2491 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2492 ClientCB *clientCB = NULL;
2493 OCDoHandle resHandle = NULL;
2494 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2495 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2497 OCTransportAdapter adapter;
2498 OCTransportFlags flags;
2499 // the request contents are put here
2500 CARequestInfo_t requestInfo = {.method = CA_GET};
2501 // requestUri will be parsed into the following three variables
2502 OCDevAddr *devAddr = NULL;
2503 char *resourceUri = NULL;
2504 char *resourceType = NULL;
2507 * Support original behavior with address on resourceUri argument.
2509 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2510 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2512 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2514 if (result != OC_STACK_OK)
2516 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2523 case OC_REST_OBSERVE:
2524 case OC_REST_OBSERVE_ALL:
2525 case OC_REST_CANCEL_OBSERVE:
2526 requestInfo.method = CA_GET;
2529 requestInfo.method = CA_PUT;
2532 requestInfo.method = CA_POST;
2534 case OC_REST_DELETE:
2535 requestInfo.method = CA_DELETE;
2537 case OC_REST_DISCOVER:
2539 if (destination || devAddr)
2541 requestInfo.isMulticast = false;
2545 tmpDevAddr.adapter = adapter;
2546 tmpDevAddr.flags = flags;
2547 destination = &tmpDevAddr;
2548 requestInfo.isMulticast = true;
2550 // CA_DISCOVER will become GET and isMulticast
2551 requestInfo.method = CA_GET;
2553 #ifdef WITH_PRESENCE
2554 case OC_REST_PRESENCE:
2555 // Replacing method type with GET because "presence"
2556 // is a stack layer only implementation.
2557 requestInfo.method = CA_GET;
2561 result = OC_STACK_INVALID_METHOD;
2565 if (!devAddr && !destination)
2567 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2568 result = OC_STACK_INVALID_PARAM;
2572 /* If not original behavior, use destination argument */
2573 if (destination && !devAddr)
2575 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2578 result = OC_STACK_NO_MEMORY;
2581 *devAddr = *destination;
2584 resHandle = GenerateInvocationHandle();
2587 result = OC_STACK_NO_MEMORY;
2591 caResult = CAGenerateToken(&token, tokenLength);
2592 if (caResult != CA_STATUS_OK)
2594 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2595 result= OC_STACK_ERROR;
2599 // fill in request data
2600 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2601 requestInfo.info.token = token;
2602 requestInfo.info.tokenLength = tokenLength;
2603 requestInfo.info.resourceUri = resourceUri;
2605 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2607 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2608 options, numOptions, OC_OBSERVE_REGISTER);
2609 if (result != OC_STACK_OK)
2613 requestInfo.info.numOptions = numOptions + 1;
2617 requestInfo.info.numOptions = numOptions;
2618 requestInfo.info.options =
2619 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2620 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2621 numOptions * sizeof(CAHeaderOption_t));
2624 CopyDevAddrToEndpoint(devAddr, &endpoint);
2629 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2632 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2635 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2639 requestInfo.info.payload = NULL;
2640 requestInfo.info.payloadSize = 0;
2641 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2644 if (result != OC_STACK_OK)
2646 OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2650 // prepare for response
2651 #ifdef WITH_PRESENCE
2652 if (method == OC_REST_PRESENCE)
2654 char *presenceUri = NULL;
2655 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2656 if (OC_STACK_OK != result)
2661 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2662 // Presence notification will form a canonical uri to
2663 // look for callbacks into the application.
2664 resourceUri = presenceUri;
2668 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2669 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2670 method, devAddr, resourceUri, resourceType, ttl);
2671 if (OC_STACK_OK != result)
2676 devAddr = NULL; // Client CB list entry now owns it
2677 resourceUri = NULL; // Client CB list entry now owns it
2678 resourceType = NULL; // Client CB list entry now owns it
2681 result = OCSendRequest(&endpoint, &requestInfo);
2682 if (OC_STACK_OK != result)
2689 *handle = resHandle;
2693 if (result != OC_STACK_OK)
2695 OIC_LOG(ERROR, TAG, "OCDoResource error");
2696 FindAndDeleteClientCB(clientCB);
2697 CADestroyToken(token);
2705 // This is the owner of the payload object, so we free it
2706 OCPayloadDestroy(payload);
2707 OICFree(requestInfo.info.payload);
2709 OICFree(resourceUri);
2710 OICFree(resourceType);
2711 OICFree(requestInfo.info.options);
2715 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2719 * This ftn is implemented one of two ways in the case of observation:
2721 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2722 * Remove the callback associated on client side.
2723 * When the next notification comes in from server,
2724 * reply with RESET message to server.
2725 * Keep in mind that the server will react to RESET only
2726 * if the last notification was sent as CON
2728 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2729 * and it is associated with an observe request
2730 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2731 * Send CON Observe request to server with
2732 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2733 * Remove the callback associated on client side.
2735 OCStackResult ret = OC_STACK_OK;
2736 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2737 CARequestInfo_t requestInfo = {.method = CA_GET};
2741 return OC_STACK_INVALID_PARAM;
2744 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2747 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2748 return OC_STACK_ERROR;
2751 switch (clientCB->method)
2753 case OC_REST_OBSERVE:
2754 case OC_REST_OBSERVE_ALL:
2756 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2758 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2760 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2762 FindAndDeleteClientCB(clientCB);
2766 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2768 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2769 requestInfo.info.token = clientCB->token;
2770 requestInfo.info.tokenLength = clientCB->tokenLength;
2772 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2773 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2775 return OC_STACK_ERROR;
2777 requestInfo.info.numOptions = numOptions + 1;
2778 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2781 ret = OCSendRequest(&endpoint, &requestInfo);
2783 if (requestInfo.info.options)
2785 OICFree (requestInfo.info.options);
2787 if (requestInfo.info.resourceUri)
2789 OICFree (requestInfo.info.resourceUri);
2794 case OC_REST_DISCOVER:
2795 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2796 clientCB->requestUri);
2797 FindAndDeleteClientCB(clientCB);
2800 #ifdef WITH_PRESENCE
2801 case OC_REST_PRESENCE:
2802 FindAndDeleteClientCB(clientCB);
2807 ret = OC_STACK_INVALID_METHOD;
2815 * @brief Register Persistent storage callback.
2816 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2818 * OC_STACK_OK - No errors; Success
2819 * OC_STACK_INVALID_PARAM - Invalid parameter
2821 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2823 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2824 if(!persistentStorageHandler)
2826 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2827 return OC_STACK_INVALID_PARAM;
2831 if( !persistentStorageHandler->open ||
2832 !persistentStorageHandler->close ||
2833 !persistentStorageHandler->read ||
2834 !persistentStorageHandler->unlink ||
2835 !persistentStorageHandler->write)
2837 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2838 return OC_STACK_INVALID_PARAM;
2841 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2844 #ifdef WITH_PRESENCE
2846 OCStackResult OCProcessPresence()
2848 OCStackResult result = OC_STACK_OK;
2850 // the following line floods the log with messages that are irrelevant
2851 // to most purposes. Uncomment as needed.
2852 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2853 ClientCB* cbNode = NULL;
2854 OCClientResponse clientResponse;
2855 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2857 LL_FOREACH(cbList, cbNode)
2859 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2864 uint32_t now = GetTicks(0);
2865 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2866 cbNode->presence->TTLlevel);
2867 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2869 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2874 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2876 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2877 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2879 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2881 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2883 clientResponse.sequenceNumber = 0;
2884 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2885 clientResponse.devAddr = *cbNode->devAddr;
2886 FixUpClientResponse(&clientResponse);
2887 clientResponse.payload = NULL;
2889 // Increment the TTLLevel (going to a next state), so we don't keep
2890 // sending presence notification to client.
2891 cbNode->presence->TTLlevel++;
2892 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2893 cbNode->presence->TTLlevel);
2895 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2896 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2898 FindAndDeleteClientCB(cbNode);
2902 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2907 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2908 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2909 CARequestInfo_t requestInfo = {.method = CA_GET};
2911 OIC_LOG(DEBUG, TAG, "time to test server presence");
2913 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2915 requestData.type = CA_MSG_NONCONFIRM;
2916 requestData.token = cbNode->token;
2917 requestData.tokenLength = cbNode->tokenLength;
2918 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2919 requestInfo.method = CA_GET;
2920 requestInfo.info = requestData;
2922 result = OCSendRequest(&endpoint, &requestInfo);
2923 if (OC_STACK_OK != result)
2928 cbNode->presence->TTLlevel++;
2929 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2932 if (result != OC_STACK_OK)
2934 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2939 #endif // WITH_PRESENCE
2941 OCStackResult OCProcess()
2943 #ifdef WITH_PRESENCE
2944 OCProcessPresence();
2946 CAHandleRequestResponse();
2948 #ifdef ROUTING_GATEWAY
2958 #ifdef WITH_PRESENCE
2959 OCStackResult OCStartPresence(const uint32_t ttl)
2961 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2962 OCChangeResourceProperty(
2963 &(((OCResource *)presenceResource.handle)->resourceProperties),
2966 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2968 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2969 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2973 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2974 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2978 presenceResource.presenceTTL = ttl;
2980 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2982 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2984 presenceState = OC_PRESENCE_INITIALIZED;
2986 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2988 CAToken_t caToken = NULL;
2989 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2990 if (caResult != CA_STATUS_OK)
2992 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2993 CADestroyToken(caToken);
2994 return OC_STACK_ERROR;
2997 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2998 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2999 CADestroyToken(caToken);
3002 // Each time OCStartPresence is called
3003 // a different random 32-bit integer number is used
3004 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3006 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3007 OC_PRESENCE_TRIGGER_CREATE);
3010 OCStackResult OCStopPresence()
3012 OCStackResult result = OC_STACK_ERROR;
3014 if(presenceResource.handle)
3016 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3018 // make resource inactive
3019 result = OCChangeResourceProperty(
3020 &(((OCResource *) presenceResource.handle)->resourceProperties),
3024 if(result != OC_STACK_OK)
3027 "Changing the presence resource properties to ACTIVE not successful");
3031 return SendStopNotification();
3035 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3036 void* callbackParameter)
3038 defaultDeviceHandler = entityHandler;
3039 defaultDeviceHandlerCallbackParameter = callbackParameter;
3044 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3046 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3048 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3050 if (validatePlatformInfo(platformInfo))
3052 return SavePlatformInfo(platformInfo);
3056 return OC_STACK_INVALID_PARAM;
3061 return OC_STACK_ERROR;
3065 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3067 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3069 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3071 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3072 return OC_STACK_INVALID_PARAM;
3075 if (deviceInfo.types)
3077 OCStringLL *type = deviceInfo.types;
3078 OCResource *resource = findResource((OCResource *) deviceResource);
3081 return OC_STACK_INVALID_PARAM;
3083 deleteResourceType(resource->rsrcType);
3084 resource->rsrcType = NULL;
3088 OCBindResourceTypeToResource(deviceResource, type->value);
3092 return SaveDeviceInfo(deviceInfo);
3095 OCStackResult OCCreateResource(OCResourceHandle *handle,
3096 const char *resourceTypeName,
3097 const char *resourceInterfaceName,
3098 const char *uri, OCEntityHandler entityHandler,
3099 void* callbackParam,
3100 uint8_t resourceProperties)
3103 OCResource *pointer = NULL;
3104 OCStackResult result = OC_STACK_ERROR;
3106 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3108 if(myStackMode == OC_CLIENT)
3110 return OC_STACK_INVALID_PARAM;
3112 // Validate parameters
3113 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3115 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3116 return OC_STACK_INVALID_URI;
3118 // Is it presented during resource discovery?
3119 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3121 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3122 return OC_STACK_INVALID_PARAM;
3125 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3127 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3130 // Make sure resourceProperties bitmask has allowed properties specified
3131 if (resourceProperties
3132 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3133 OC_EXPLICIT_DISCOVERABLE))
3135 OIC_LOG(ERROR, TAG, "Invalid property");
3136 return OC_STACK_INVALID_PARAM;
3139 // If the headResource is NULL, then no resources have been created...
3140 pointer = headResource;
3143 // At least one resources is in the resource list, so we need to search for
3144 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3147 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3149 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3150 return OC_STACK_INVALID_PARAM;
3152 pointer = pointer->next;
3155 // Create the pointer and insert it into the resource list
3156 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3159 result = OC_STACK_NO_MEMORY;
3162 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3164 insertResource(pointer);
3167 pointer->uri = OICStrdup(uri);
3170 result = OC_STACK_NO_MEMORY;
3174 // Set properties. Set OC_ACTIVE
3175 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3178 // Add the resourcetype to the resource
3179 result = BindResourceTypeToResource(pointer, resourceTypeName);
3180 if (result != OC_STACK_OK)
3182 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3186 // Add the resourceinterface to the resource
3187 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3188 if (result != OC_STACK_OK)
3190 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3194 // If an entity handler has been passed, attach it to the newly created
3195 // resource. Otherwise, set the default entity handler.
3198 pointer->entityHandler = entityHandler;
3199 pointer->entityHandlerCallbackParam = callbackParam;
3203 pointer->entityHandler = defaultResourceEHandler;
3204 pointer->entityHandlerCallbackParam = NULL;
3207 // Initialize a pointer indicating child resources in case of collection
3208 pointer->rsrcChildResourcesHead = NULL;
3211 result = OC_STACK_OK;
3213 #ifdef WITH_PRESENCE
3214 if (presenceResource.handle)
3216 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3217 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3221 if (result != OC_STACK_OK)
3223 // Deep delete of resource and other dynamic elements that it contains
3224 deleteResource(pointer);
3229 OCStackResult OCBindResource(
3230 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3232 OCResource *resource = NULL;
3233 OCChildResource *tempChildResource = NULL;
3234 OCChildResource *newChildResource = NULL;
3236 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3238 // Validate parameters
3239 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3240 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3241 // Container cannot contain itself
3242 if (collectionHandle == resourceHandle)
3244 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3245 return OC_STACK_INVALID_PARAM;
3248 // Use the handle to find the resource in the resource linked list
3249 resource = findResource((OCResource *) collectionHandle);
3252 OIC_LOG(ERROR, TAG, "Collection handle not found");
3253 return OC_STACK_INVALID_PARAM;
3256 // Look for an open slot to add add the child resource.
3257 // If found, add it and return success
3259 tempChildResource = resource->rsrcChildResourcesHead;
3261 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3263 // TODO: what if one of child resource was deregistered without unbinding?
3264 tempChildResource = tempChildResource->next;
3267 // Do memory allocation for child resource
3268 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3269 if(!newChildResource)
3271 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3272 return OC_STACK_ERROR;
3275 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3276 newChildResource->next = NULL;
3278 if(!resource->rsrcChildResourcesHead)
3280 resource->rsrcChildResourcesHead = newChildResource;
3283 tempChildResource->next = newChildResource;
3286 OIC_LOG(INFO, TAG, "resource bound");
3288 #ifdef WITH_PRESENCE
3289 if (presenceResource.handle)
3291 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3292 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3293 OC_PRESENCE_TRIGGER_CHANGE);
3300 OCStackResult OCUnBindResource(
3301 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3303 OCResource *resource = NULL;
3304 OCChildResource *tempChildResource = NULL;
3305 OCChildResource *tempLastChildResource = NULL;
3307 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3309 // Validate parameters
3310 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3311 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3312 // Container cannot contain itself
3313 if (collectionHandle == resourceHandle)
3315 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3316 return OC_STACK_INVALID_PARAM;
3319 // Use the handle to find the resource in the resource linked list
3320 resource = findResource((OCResource *) collectionHandle);
3323 OIC_LOG(ERROR, TAG, "Collection handle not found");
3324 return OC_STACK_INVALID_PARAM;
3327 // Look for an open slot to add add the child resource.
3328 // If found, add it and return success
3329 if(!resource->rsrcChildResourcesHead)
3331 OIC_LOG(INFO, TAG, "resource not found in collection");
3333 // Unable to add resourceHandle, so return error
3334 return OC_STACK_ERROR;
3338 tempChildResource = resource->rsrcChildResourcesHead;
3340 while (tempChildResource)
3342 if(tempChildResource->rsrcResource == resourceHandle)
3344 // if resource going to be unbinded is the head one.
3345 if( tempChildResource == resource->rsrcChildResourcesHead )
3347 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3348 OICFree(resource->rsrcChildResourcesHead);
3349 resource->rsrcChildResourcesHead = temp;
3354 OCChildResource *temp = tempChildResource->next;
3355 OICFree(tempChildResource);
3356 tempLastChildResource->next = temp;
3360 OIC_LOG(INFO, TAG, "resource unbound");
3362 // Send notification when resource is unbounded successfully.
3363 #ifdef WITH_PRESENCE
3364 if (presenceResource.handle)
3366 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3367 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3368 OC_PRESENCE_TRIGGER_CHANGE);
3371 tempChildResource = NULL;
3372 tempLastChildResource = NULL;
3378 tempLastChildResource = tempChildResource;
3379 tempChildResource = tempChildResource->next;
3382 OIC_LOG(INFO, TAG, "resource not found in collection");
3384 tempChildResource = NULL;
3385 tempLastChildResource = NULL;
3387 // Unable to add resourceHandle, so return error
3388 return OC_STACK_ERROR;
3391 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3393 if (!resourceItemName)
3397 // Per RFC 6690 only registered values must follow the first rule below.
3398 // At this point in time the only values registered begin with "core", and
3399 // all other values are specified as opaque strings where multiple values
3400 // are separated by a space.
3401 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3403 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3405 if (resourceItemName[index] != '.'
3406 && resourceItemName[index] != '-'
3407 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3408 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3416 for (size_t index = 0; resourceItemName[index]; ++index)
3418 if (resourceItemName[index] == ' '
3419 || resourceItemName[index] == '\t'
3420 || resourceItemName[index] == '\r'
3421 || resourceItemName[index] == '\n')
3431 OCStackResult BindResourceTypeToResource(OCResource* resource,
3432 const char *resourceTypeName)
3434 OCResourceType *pointer = NULL;
3436 OCStackResult result = OC_STACK_ERROR;
3438 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3440 if (!ValidateResourceTypeInterface(resourceTypeName))
3442 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3443 return OC_STACK_INVALID_PARAM;
3446 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3449 result = OC_STACK_NO_MEMORY;
3453 str = OICStrdup(resourceTypeName);
3456 result = OC_STACK_NO_MEMORY;
3459 pointer->resourcetypename = str;
3460 pointer->next = NULL;
3462 insertResourceType(resource, pointer);
3463 result = OC_STACK_OK;
3466 if (result != OC_STACK_OK)
3475 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3476 const char *resourceInterfaceName)
3478 OCResourceInterface *pointer = NULL;
3480 OCStackResult result = OC_STACK_ERROR;
3482 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3484 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3486 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3487 return OC_STACK_INVALID_PARAM;
3490 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3492 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3495 result = OC_STACK_NO_MEMORY;
3499 str = OICStrdup(resourceInterfaceName);
3502 result = OC_STACK_NO_MEMORY;
3505 pointer->name = str;
3507 // Bind the resourceinterface to the resource
3508 insertResourceInterface(resource, pointer);
3510 result = OC_STACK_OK;
3513 if (result != OC_STACK_OK)
3522 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3523 const char *resourceTypeName)
3526 OCStackResult result = OC_STACK_ERROR;
3527 OCResource *resource = NULL;
3529 resource = findResource((OCResource *) handle);
3532 OIC_LOG(ERROR, TAG, "Resource not found");
3533 return OC_STACK_ERROR;
3536 result = BindResourceTypeToResource(resource, resourceTypeName);
3538 #ifdef WITH_PRESENCE
3539 if(presenceResource.handle)
3541 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3542 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3549 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3550 const char *resourceInterfaceName)
3553 OCStackResult result = OC_STACK_ERROR;
3554 OCResource *resource = NULL;
3556 resource = findResource((OCResource *) handle);
3559 OIC_LOG(ERROR, TAG, "Resource not found");
3560 return OC_STACK_ERROR;
3563 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3565 #ifdef WITH_PRESENCE
3566 if (presenceResource.handle)
3568 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3569 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3576 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3578 OCResource *pointer = headResource;
3580 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3584 *numResources = *numResources + 1;
3585 pointer = pointer->next;
3590 OCResourceHandle OCGetResourceHandle(uint8_t index)
3592 OCResource *pointer = headResource;
3594 for( uint8_t i = 0; i < index && pointer; ++i)
3596 pointer = pointer->next;
3598 return (OCResourceHandle) pointer;
3601 OCStackResult OCDeleteResource(OCResourceHandle handle)
3605 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3606 return OC_STACK_INVALID_PARAM;
3609 OCResource *resource = findResource((OCResource *) handle);
3610 if (resource == NULL)
3612 OIC_LOG(ERROR, TAG, "Resource not found");
3613 return OC_STACK_NO_RESOURCE;
3616 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3618 OIC_LOG(ERROR, TAG, "Error deleting resource");
3619 return OC_STACK_ERROR;
3625 const char *OCGetResourceUri(OCResourceHandle handle)
3627 OCResource *resource = NULL;
3629 resource = findResource((OCResource *) handle);
3632 return resource->uri;
3634 return (const char *) NULL;
3637 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3639 OCResource *resource = NULL;
3641 resource = findResource((OCResource *) handle);
3644 return resource->resourceProperties;
3646 return (OCResourceProperty)-1;
3649 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3650 uint8_t *numResourceTypes)
3652 OCResource *resource = NULL;
3653 OCResourceType *pointer = NULL;
3655 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3656 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3658 *numResourceTypes = 0;
3660 resource = findResource((OCResource *) handle);
3663 pointer = resource->rsrcType;
3666 *numResourceTypes = *numResourceTypes + 1;
3667 pointer = pointer->next;
3673 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3675 OCResourceType *resourceType = NULL;
3677 resourceType = findResourceTypeAtIndex(handle, index);
3680 return resourceType->resourcetypename;
3682 return (const char *) NULL;
3685 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3686 uint8_t *numResourceInterfaces)
3688 OCResourceInterface *pointer = NULL;
3689 OCResource *resource = NULL;
3691 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3692 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3694 *numResourceInterfaces = 0;
3695 resource = findResource((OCResource *) handle);
3698 pointer = resource->rsrcInterface;
3701 *numResourceInterfaces = *numResourceInterfaces + 1;
3702 pointer = pointer->next;
3708 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3710 OCResourceInterface *resourceInterface = NULL;
3712 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3713 if (resourceInterface)
3715 return resourceInterface->name;
3717 return (const char *) NULL;
3720 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3723 OCResource *resource = NULL;
3724 OCChildResource *tempChildResource = NULL;
3727 resource = findResource((OCResource *) collectionHandle);
3733 tempChildResource = resource->rsrcChildResourcesHead;
3735 while(tempChildResource)
3739 return tempChildResource->rsrcResource;
3742 tempChildResource = tempChildResource->next;
3745 // In this case, the number of resource handles in the collection exceeds the index
3746 tempChildResource = NULL;
3750 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3751 OCEntityHandler entityHandler,
3752 void* callbackParam)
3754 OCResource *resource = NULL;
3756 // Validate parameters
3757 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3759 // Use the handle to find the resource in the resource linked list
3760 resource = findResource((OCResource *)handle);
3763 OIC_LOG(ERROR, TAG, "Resource not found");
3764 return OC_STACK_ERROR;
3768 resource->entityHandler = entityHandler;
3769 resource->entityHandlerCallbackParam = callbackParam;
3771 #ifdef WITH_PRESENCE
3772 if (presenceResource.handle)
3774 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3775 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3782 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3784 OCResource *resource = NULL;
3786 resource = findResource((OCResource *)handle);
3789 OIC_LOG(ERROR, TAG, "Resource not found");
3794 return resource->entityHandler;
3797 void incrementSequenceNumber(OCResource * resPtr)
3799 // Increment the sequence number
3800 resPtr->sequenceNum += 1;
3801 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3803 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3808 #ifdef WITH_PRESENCE
3809 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3810 OCPresenceTrigger trigger)
3812 OCResource *resPtr = NULL;
3813 OCStackResult result = OC_STACK_ERROR;
3814 OCMethod method = OC_REST_PRESENCE;
3815 uint32_t maxAge = 0;
3816 resPtr = findResource((OCResource *) presenceResource.handle);
3819 return OC_STACK_NO_RESOURCE;
3822 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3824 maxAge = presenceResource.presenceTTL;
3826 result = SendAllObserverNotification(method, resPtr, maxAge,
3827 trigger, resourceType, OC_LOW_QOS);
3833 OCStackResult SendStopNotification()
3835 OCResource *resPtr = NULL;
3836 OCStackResult result = OC_STACK_ERROR;
3837 OCMethod method = OC_REST_PRESENCE;
3838 resPtr = findResource((OCResource *) presenceResource.handle);
3841 return OC_STACK_NO_RESOURCE;
3844 // maxAge is 0. ResourceType is NULL.
3845 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3851 #endif // WITH_PRESENCE
3852 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3854 OCResource *resPtr = NULL;
3855 OCStackResult result = OC_STACK_ERROR;
3856 OCMethod method = OC_REST_NOMETHOD;
3857 uint32_t maxAge = 0;
3859 OIC_LOG(INFO, TAG, "Notifying all observers");
3860 #ifdef WITH_PRESENCE
3861 if(handle == presenceResource.handle)
3865 #endif // WITH_PRESENCE
3866 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3868 // Verify that the resource exists
3869 resPtr = findResource ((OCResource *) handle);
3872 return OC_STACK_NO_RESOURCE;
3876 //only increment in the case of regular observing (not presence)
3877 incrementSequenceNumber(resPtr);
3878 method = OC_REST_OBSERVE;
3879 maxAge = MAX_OBSERVE_AGE;
3880 #ifdef WITH_PRESENCE
3881 result = SendAllObserverNotification (method, resPtr, maxAge,
3882 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3884 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3891 OCNotifyListOfObservers (OCResourceHandle handle,
3892 OCObservationId *obsIdList,
3893 uint8_t numberOfIds,
3894 const OCRepPayload *payload,
3895 OCQualityOfService qos)
3897 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3899 OCResource *resPtr = NULL;
3900 //TODO: we should allow the server to define this
3901 uint32_t maxAge = MAX_OBSERVE_AGE;
3903 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3904 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3905 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3907 resPtr = findResource ((OCResource *) handle);
3908 if (NULL == resPtr || myStackMode == OC_CLIENT)
3910 return OC_STACK_NO_RESOURCE;
3914 incrementSequenceNumber(resPtr);
3916 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3917 payload, maxAge, qos));
3920 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3922 OCStackResult result = OC_STACK_ERROR;
3923 OCServerRequest *serverRequest = NULL;
3925 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3927 // Validate input parameters
3928 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3929 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3932 // Get pointer to request info
3933 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3936 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3937 result = serverRequest->ehResponseHandler(ehResponse);
3943 //#ifdef DIRECT_PAIRING
3944 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3946 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3947 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3949 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3953 return (const OCDPDev_t*)DPGetDiscoveredDevices();
3956 const OCDPDev_t* OCGetDirectPairedDevices()
3958 return (const OCDPDev_t*)DPGetPairedDevices();
3961 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3962 OCDirectPairingCB resultCallback)
3964 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3965 if(NULL == peer || NULL == pinNumber)
3967 OIC_LOG(ERROR, TAG, "Invalid parameters");
3968 return OC_STACK_INVALID_PARAM;
3970 if (NULL == resultCallback)
3972 OIC_LOG(ERROR, TAG, "Invalid callback");
3973 return OC_STACK_INVALID_CALLBACK;
3976 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3977 pinNumber, (OCDirectPairingResultCB)resultCallback);
3979 //#endif // DIRECT_PAIRING
3981 //-----------------------------------------------------------------------------
3982 // Private internal function definitions
3983 //-----------------------------------------------------------------------------
3984 static OCDoHandle GenerateInvocationHandle()
3986 OCDoHandle handle = NULL;
3987 // Generate token here, it will be deleted when the transaction is deleted
3988 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3991 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3997 #ifdef WITH_PRESENCE
3998 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3999 OCResourceProperty resourceProperties, uint8_t enable)
4003 return OC_STACK_INVALID_PARAM;
4005 if (resourceProperties
4006 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4008 OIC_LOG(ERROR, TAG, "Invalid property");
4009 return OC_STACK_INVALID_PARAM;
4013 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4017 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4023 OCStackResult initResources()
4025 OCStackResult result = OC_STACK_OK;
4027 headResource = NULL;
4028 tailResource = NULL;
4029 // Init Virtual Resources
4030 #ifdef WITH_PRESENCE
4031 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4033 result = OCCreateResource(&presenceResource.handle,
4034 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4036 OC_RSRVD_PRESENCE_URI,
4040 //make resource inactive
4041 result = OCChangeResourceProperty(
4042 &(((OCResource *) presenceResource.handle)->resourceProperties),
4045 #ifndef WITH_ARDUINO
4046 if (result == OC_STACK_OK)
4048 result = SRMInitSecureResources();
4052 if(result == OC_STACK_OK)
4054 result = OCCreateResource(&deviceResource,
4055 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4056 OC_RSRVD_INTERFACE_DEFAULT,
4057 OC_RSRVD_DEVICE_URI,
4061 if(result == OC_STACK_OK)
4063 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4064 OC_RSRVD_INTERFACE_READ);
4068 if(result == OC_STACK_OK)
4070 result = OCCreateResource(&platformResource,
4071 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4072 OC_RSRVD_INTERFACE_DEFAULT,
4073 OC_RSRVD_PLATFORM_URI,
4077 if(result == OC_STACK_OK)
4079 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4080 OC_RSRVD_INTERFACE_READ);
4087 void insertResource(OCResource *resource)
4091 headResource = resource;
4092 tailResource = resource;
4096 tailResource->next = resource;
4097 tailResource = resource;
4099 resource->next = NULL;
4102 OCResource *findResource(OCResource *resource)
4104 OCResource *pointer = headResource;
4108 if (pointer == resource)
4112 pointer = pointer->next;
4117 void deleteAllResources()
4119 OCResource *pointer = headResource;
4120 OCResource *temp = NULL;
4124 temp = pointer->next;
4125 #ifdef WITH_PRESENCE
4126 if (pointer != (OCResource *) presenceResource.handle)
4128 #endif // WITH_PRESENCE
4129 deleteResource(pointer);
4130 #ifdef WITH_PRESENCE
4132 #endif // WITH_PRESENCE
4136 SRMDeInitSecureResources();
4138 #ifdef WITH_PRESENCE
4139 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4140 // presence notification attributed to their deletion to be processed.
4141 deleteResource((OCResource *) presenceResource.handle);
4142 #endif // WITH_PRESENCE
4145 OCStackResult deleteResource(OCResource *resource)
4147 OCResource *prev = NULL;
4148 OCResource *temp = NULL;
4151 OIC_LOG(DEBUG,TAG,"resource is NULL");
4152 return OC_STACK_INVALID_PARAM;
4155 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4157 temp = headResource;
4160 if (temp == resource)
4162 // Invalidate all Resource Properties.
4163 resource->resourceProperties = (OCResourceProperty) 0;
4164 #ifdef WITH_PRESENCE
4165 if(resource != (OCResource *) presenceResource.handle)
4167 #endif // WITH_PRESENCE
4168 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4169 #ifdef WITH_PRESENCE
4172 if(presenceResource.handle)
4174 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4175 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4178 // Only resource in list.
4179 if (temp == headResource && temp == tailResource)
4181 headResource = NULL;
4182 tailResource = NULL;
4185 else if (temp == headResource)
4187 headResource = temp->next;
4190 else if (temp == tailResource)
4192 tailResource = prev;
4193 tailResource->next = NULL;
4197 prev->next = temp->next;
4200 deleteResourceElements(temp);
4211 return OC_STACK_ERROR;
4214 void deleteResourceElements(OCResource *resource)
4221 OICFree(resource->uri);
4222 deleteResourceType(resource->rsrcType);
4223 deleteResourceInterface(resource->rsrcInterface);
4226 void deleteResourceType(OCResourceType *resourceType)
4228 OCResourceType *pointer = resourceType;
4229 OCResourceType *next = NULL;
4233 next = pointer->next;
4234 OICFree(pointer->resourcetypename);
4240 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4242 OCResourceInterface *pointer = resourceInterface;
4243 OCResourceInterface *next = NULL;
4247 next = pointer->next;
4248 OICFree(pointer->name);
4254 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4256 OCResourceType *pointer = NULL;
4257 OCResourceType *previous = NULL;
4258 if (!resource || !resourceType)
4262 // resource type list is empty.
4263 else if (!resource->rsrcType)
4265 resource->rsrcType = resourceType;
4269 pointer = resource->rsrcType;
4273 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4275 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4276 OICFree(resourceType->resourcetypename);
4277 OICFree(resourceType);
4281 pointer = pointer->next;
4286 previous->next = resourceType;
4289 resourceType->next = NULL;
4291 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4294 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4296 OCResource *resource = NULL;
4297 OCResourceType *pointer = NULL;
4299 // Find the specified resource
4300 resource = findResource((OCResource *) handle);
4306 // Make sure a resource has a resourcetype
4307 if (!resource->rsrcType)
4312 // Iterate through the list
4313 pointer = resource->rsrcType;
4314 for(uint8_t i = 0; i< index && pointer; ++i)
4316 pointer = pointer->next;
4321 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4323 if(resourceTypeList && resourceTypeName)
4325 OCResourceType * rtPointer = resourceTypeList;
4326 while(resourceTypeName && rtPointer)
4328 if(rtPointer->resourcetypename &&
4329 strcmp(resourceTypeName, (const char *)
4330 (rtPointer->resourcetypename)) == 0)
4334 rtPointer = rtPointer->next;
4342 * Insert a new interface into interface linked list only if not already present.
4343 * If alredy present, 2nd arg is free'd.
4344 * Default interface will always be first if present.
4346 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4348 OCResourceInterface *pointer = NULL;
4349 OCResourceInterface *previous = NULL;
4351 newInterface->next = NULL;
4353 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4355 if (!*firstInterface)
4357 // If first interface is not oic.if.baseline, by default add it as first interface type.
4358 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4360 *firstInterface = newInterface;
4364 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4365 if (result != OC_STACK_OK)
4367 OICFree(newInterface->name);
4368 OICFree(newInterface);
4371 if (*firstInterface)
4373 (*firstInterface)->next = newInterface;
4377 // If once add oic.if.baseline, later too below code take care of freeing memory.
4378 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4380 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4382 OICFree(newInterface->name);
4383 OICFree(newInterface);
4386 // This code will not hit anymore, keeping
4389 newInterface->next = *firstInterface;
4390 *firstInterface = newInterface;
4395 pointer = *firstInterface;
4398 if (strcmp(newInterface->name, pointer->name) == 0)
4400 OICFree(newInterface->name);
4401 OICFree(newInterface);
4405 pointer = pointer->next;
4407 previous->next = newInterface;
4411 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4414 OCResource *resource = NULL;
4415 OCResourceInterface *pointer = NULL;
4417 // Find the specified resource
4418 resource = findResource((OCResource *) handle);
4424 // Make sure a resource has a resourceinterface
4425 if (!resource->rsrcInterface)
4430 // Iterate through the list
4431 pointer = resource->rsrcInterface;
4433 for (uint8_t i = 0; i < index && pointer; ++i)
4435 pointer = pointer->next;
4441 * This function splits the uri using the '?' delimiter.
4442 * "uriWithoutQuery" is the block of characters between the beginning
4443 * till the delimiter or '\0' which ever comes first.
4444 * "query" is whatever is to the right of the delimiter if present.
4445 * No delimiter sets the query to NULL.
4446 * If either are present, they will be malloc'ed into the params 2, 3.
4447 * The first param, *uri is left untouched.
4449 * NOTE: This function does not account for whitespace at the end of the uri NOR
4450 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4451 * part of the query.
4453 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4457 return OC_STACK_INVALID_URI;
4459 if(!query || !uriWithoutQuery)
4461 return OC_STACK_INVALID_PARAM;
4465 *uriWithoutQuery = NULL;
4467 size_t uriWithoutQueryLen = 0;
4468 size_t queryLen = 0;
4469 size_t uriLen = strlen(uri);
4471 char *pointerToDelimiter = strstr(uri, "?");
4473 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4474 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4476 if (uriWithoutQueryLen)
4478 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4479 if (!*uriWithoutQuery)
4483 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4487 *query = (char *) OICCalloc(queryLen + 1, 1);
4490 OICFree(*uriWithoutQuery);
4491 *uriWithoutQuery = NULL;
4494 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4500 return OC_STACK_NO_MEMORY;
4503 static const OicUuid_t* OCGetServerInstanceID(void)
4505 static bool generated = false;
4506 static OicUuid_t sid;
4512 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4514 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4521 const char* OCGetServerInstanceIDString(void)
4523 static bool generated = false;
4524 static char sidStr[UUID_STRING_SIZE];
4531 const OicUuid_t *sid = OCGetServerInstanceID();
4532 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4534 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4542 CAResult_t OCSelectNetwork()
4544 CAResult_t retResult = CA_STATUS_FAILED;
4545 CAResult_t caResult = CA_STATUS_OK;
4547 CATransportAdapter_t connTypes[] = {
4549 CA_ADAPTER_RFCOMM_BTEDR,
4550 CA_ADAPTER_GATT_BTLE,
4553 ,CA_ADAPTER_REMOTE_ACCESS
4560 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4562 for(int i = 0; i<numConnTypes; i++)
4564 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4565 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4567 caResult = CASelectNetwork(connTypes[i]);
4568 if(caResult == CA_STATUS_OK)
4570 retResult = CA_STATUS_OK;
4575 if(retResult != CA_STATUS_OK)
4577 return caResult; // Returns error of appropriate transport that failed fatally.
4583 OCStackResult CAResultToOCResult(CAResult_t caResult)
4589 case CA_STATUS_INVALID_PARAM:
4590 return OC_STACK_INVALID_PARAM;
4591 case CA_ADAPTER_NOT_ENABLED:
4592 return OC_STACK_ADAPTER_NOT_ENABLED;
4593 case CA_SERVER_STARTED_ALREADY:
4595 case CA_SERVER_NOT_STARTED:
4596 return OC_STACK_ERROR;
4597 case CA_DESTINATION_NOT_REACHABLE:
4598 return OC_STACK_COMM_ERROR;
4599 case CA_SOCKET_OPERATION_FAILED:
4600 return OC_STACK_COMM_ERROR;
4601 case CA_SEND_FAILED:
4602 return OC_STACK_COMM_ERROR;
4603 case CA_RECEIVE_FAILED:
4604 return OC_STACK_COMM_ERROR;
4605 case CA_MEMORY_ALLOC_FAILED:
4606 return OC_STACK_NO_MEMORY;
4607 case CA_REQUEST_TIMEOUT:
4608 return OC_STACK_TIMEOUT;
4609 case CA_DESTINATION_DISCONNECTED:
4610 return OC_STACK_COMM_ERROR;
4611 case CA_STATUS_FAILED:
4612 return OC_STACK_ERROR;
4613 case CA_NOT_SUPPORTED:
4614 return OC_STACK_NOTIMPL;
4616 return OC_STACK_ERROR;