1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
44 #include "ocstackinternal.h"
45 #include "ocresourcehandler.h"
46 #include "occlientcb.h"
47 #include "ocobserve.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
52 #include "ocserverrequest.h"
53 #include "secureresourcemanager.h"
54 #include "doxmresource.h"
56 #include "cainterface.h"
57 #include "ocpayload.h"
58 #include "ocpayloadcbor.h"
60 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
61 #include "routingutility.h"
62 #ifdef ROUTING_GATEWAY
63 #include "routingmanager.h"
68 #include "oickeepalive.h"
71 //#ifdef DIRECT_PAIRING
72 #include "directpairing.h"
75 #ifdef HAVE_ARDUINO_TIME_H
78 #ifdef HAVE_SYS_TIME_H
81 #include "coap_time.h"
85 #ifdef HAVE_ARPA_INET_H
86 #include <arpa/inet.h>
90 #define UINT32_MAX (0xFFFFFFFFUL)
93 //-----------------------------------------------------------------------------
95 //-----------------------------------------------------------------------------
98 OC_STACK_UNINITIALIZED = 0,
100 OC_STACK_UNINIT_IN_PROGRESS
106 OC_PRESENCE_UNINITIALIZED = 0,
107 OC_PRESENCE_INITIALIZED
111 //-----------------------------------------------------------------------------
113 //-----------------------------------------------------------------------------
114 static OCStackState stackState = OC_STACK_UNINITIALIZED;
116 OCResource *headResource = NULL;
117 static OCResource *tailResource = NULL;
118 static OCResourceHandle platformResource = {0};
119 static OCResourceHandle deviceResource = {0};
121 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
122 static PresenceResource presenceResource = {0};
123 static uint8_t PresenceTimeOutSize = 0;
124 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
127 static OCMode myStackMode;
129 //TODO: revisit this design
130 static bool gRASetInfo = false;
132 OCDeviceEntityHandler defaultDeviceHandler;
133 void* defaultDeviceHandlerCallbackParameter = NULL;
134 static const char COAP_TCP[] = "coap+tcp:";
135 static const char CORESPEC[] = "core";
137 //-----------------------------------------------------------------------------
139 //-----------------------------------------------------------------------------
140 #define TAG "OIC_RI_STACK"
141 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
142 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
143 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
144 TAG, #arg " is NULL"); return (retVal); } }
145 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
146 TAG, #arg " is NULL"); return; } }
147 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
150 //TODO: we should allow the server to define this
151 #define MAX_OBSERVE_AGE (0x2FFFFUL)
153 #define MILLISECONDS_PER_SECOND (1000)
155 //-----------------------------------------------------------------------------
156 // Private internal function prototypes
157 //-----------------------------------------------------------------------------
160 * Generate handle of OCDoResource invocation for callback management.
162 * @return Generated OCDoResource handle.
164 static OCDoHandle GenerateInvocationHandle();
167 * Initialize resource data structures, variables, etc.
169 * @return ::OC_STACK_OK on success, some other value upon failure.
171 static OCStackResult initResources();
174 * Add a resource to the end of the linked list of resources.
176 * @param resource Resource to be added
178 static void insertResource(OCResource *resource);
181 * Find a resource in the linked list of resources.
183 * @param resource Resource to be found.
184 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
187 static OCResource *findResource(OCResource *resource);
190 * Insert a resource type into a resource's resource type linked list.
191 * If resource type already exists, it will not be inserted and the
192 * resourceType will be free'd.
193 * resourceType->next should be null to avoid memory leaks.
194 * Function returns silently for null args.
196 * @param resource Resource where resource type is to be inserted.
197 * @param resourceType Resource type to be inserted.
199 static void insertResourceType(OCResource *resource,
200 OCResourceType *resourceType);
203 * Get a resource type at the specified index within a resource.
205 * @param handle Handle of resource.
206 * @param index Index of resource type.
208 * @return Pointer to resource type if found, NULL otherwise.
210 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
214 * Insert a resource interface into a resource's resource interface linked list.
215 * If resource interface already exists, it will not be inserted and the
216 * resourceInterface will be free'd.
217 * resourceInterface->next should be null to avoid memory leaks.
219 * @param resource Resource where resource interface is to be inserted.
220 * @param resourceInterface Resource interface to be inserted.
222 static void insertResourceInterface(OCResource *resource,
223 OCResourceInterface *resourceInterface);
226 * Get a resource interface at the specified index within a resource.
228 * @param handle Handle of resource.
229 * @param index Index of resource interface.
231 * @return Pointer to resource interface if found, NULL otherwise.
233 static OCResourceInterface *findResourceInterfaceAtIndex(
234 OCResourceHandle handle, uint8_t index);
237 * Delete all of the dynamically allocated elements that were created for the resource type.
239 * @param resourceType Specified resource type.
241 static void deleteResourceType(OCResourceType *resourceType);
244 * Delete all of the dynamically allocated elements that were created for the resource interface.
246 * @param resourceInterface Specified resource interface.
248 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
251 * Delete all of the dynamically allocated elements that were created for the resource.
253 * @param resource Specified resource.
255 static void deleteResourceElements(OCResource *resource);
258 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
261 * @param handle Handle of resource to be deleted.
263 * @return ::OC_STACK_OK on success, some other value upon failure.
265 static OCStackResult deleteResource(OCResource *resource);
268 * Delete all of the resources in the resource list.
270 static void deleteAllResources();
273 * Increment resource sequence number. Handles rollover.
275 * @param resPtr Pointer to resource.
277 static void incrementSequenceNumber(OCResource * resPtr);
280 * Attempts to initialize every network interface that the CA Layer might have compiled in.
282 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
283 * return something other than @ref CA_STATUS_OK, then this function fails.
285 * @return ::CA_STATUS_OK on success, some other value upon failure.
287 static CAResult_t OCSelectNetwork();
290 * Get the CoAP ticks after the specified number of milli-seconds.
292 * @param afterMilliSeconds Milli-seconds.
296 static uint32_t GetTicks(uint32_t afterMilliSeconds);
299 * Convert CAResult_t to OCStackResult.
301 * @param caResult CAResult_t code.
302 * @return ::OC_STACK_OK on success, some other value upon failure.
304 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
307 * Convert CAResponseResult_t to OCStackResult.
309 * @param caCode CAResponseResult_t code.
310 * @return ::OC_STACK_OK on success, some other value upon failure.
312 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
315 * Convert OCStackResult to CAResponseResult_t.
317 * @param caCode OCStackResult code.
318 * @param method OCMethod method the return code replies to.
319 * @return ::CA_CONTENT on OK, some other value upon failure.
321 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
324 * Convert OCTransportFlags_t to CATransportModifiers_t.
326 * @param ocConType OCTransportFlags_t input.
327 * @return CATransportFlags
329 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
332 * Convert CATransportFlags_t to OCTransportModifiers_t.
334 * @param caConType CATransportFlags_t input.
335 * @return OCTransportFlags
337 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
340 * Handle response from presence request.
342 * @param endPoint CA remote endpoint.
343 * @param responseInfo CA response info.
344 * @return ::OC_STACK_OK on success, some other value upon failure.
346 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
347 const CAResponseInfo_t *responseInfo);
350 * This function will be called back by CA layer when a response is received.
352 * @param endPoint CA remote endpoint.
353 * @param responseInfo CA response info.
355 static void HandleCAResponses(const CAEndpoint_t* endPoint,
356 const CAResponseInfo_t* responseInfo);
359 * This function will be called back by CA layer when a request is received.
361 * @param endPoint CA remote endpoint.
362 * @param requestInfo CA request info.
364 static void HandleCARequests(const CAEndpoint_t* endPoint,
365 const CARequestInfo_t* requestInfo);
368 * Extract query from a URI.
370 * @param uri Full URI with query.
371 * @param query Pointer to string that will contain query.
372 * @param newURI Pointer to string that will contain URI.
373 * @return ::OC_STACK_OK on success, some other value upon failure.
375 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
378 * Finds a resource type in an OCResourceType link-list.
380 * @param resourceTypeList The link-list to be searched through.
381 * @param resourceTypeName The key to search for.
383 * @return Resource type that matches the key (ie. resourceTypeName) or
384 * NULL if there is either an invalid parameter or this function was unable to find the key.
386 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
387 const char * resourceTypeName);
390 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
391 * TTL will be set to maxAge.
393 * @param cbNode Callback Node for which presence ttl is to be reset.
394 * @param maxAge New value of ttl in seconds.
396 * @return ::OC_STACK_OK on success, some other value upon failure.
398 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
401 * Ensure the accept header option is set appropriatly before sending the requests and routing
402 * header option is updated with destination.
404 * @param object CA remote endpoint.
405 * @param requestInfo CA request info.
407 * @return ::OC_STACK_OK on success, some other value upon failure.
409 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
411 //-----------------------------------------------------------------------------
412 // Internal functions
413 //-----------------------------------------------------------------------------
415 uint32_t GetTicks(uint32_t afterMilliSeconds)
420 // Guard against overflow of uint32_t
421 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
422 COAP_TICKS_PER_SECOND)
424 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
432 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
434 VERIFY_NON_NULL_NR(in, FATAL);
435 VERIFY_NON_NULL_NR(out, FATAL);
437 out->adapter = (OCTransportAdapter)in->adapter;
438 out->flags = CAToOCTransportFlags(in->flags);
439 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
440 out->port = in->port;
441 out->ifindex = in->ifindex;
442 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
443 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
447 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
449 VERIFY_NON_NULL_NR(in, FATAL);
450 VERIFY_NON_NULL_NR(out, FATAL);
452 out->adapter = (CATransportAdapter_t)in->adapter;
453 out->flags = OCToCATransportFlags(in->flags);
454 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
455 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
456 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
458 out->port = in->port;
459 out->ifindex = in->ifindex;
462 void FixUpClientResponse(OCClientResponse *cr)
464 VERIFY_NON_NULL_NR(cr, FATAL);
466 cr->addr = &cr->devAddr;
467 cr->connType = (OCConnectivityType)
468 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
471 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
473 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
474 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
476 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
477 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
478 if (OC_STACK_OK != rmResult)
480 OIC_LOG(ERROR, TAG, "Add destination option failed");
485 // OC stack prefer CBOR encoded payloads.
486 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
487 CAResult_t result = CASendRequest(object, requestInfo);
488 if(CA_STATUS_OK != result)
490 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
491 return CAResultToOCResult(result);
495 //-----------------------------------------------------------------------------
496 // Internal API function
497 //-----------------------------------------------------------------------------
499 // This internal function is called to update the stack with the status of
500 // observers and communication failures
501 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
503 OCStackResult result = OC_STACK_ERROR;
504 ResourceObserver * observer = NULL;
505 OCEntityHandlerRequest ehRequest = {0};
509 case OC_OBSERVER_NOT_INTERESTED:
510 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
511 observer = GetObserverUsingToken (token, tokenLength);
514 result = FormOCEntityHandlerRequest(&ehRequest,
515 (OCRequestHandle)NULL,
518 (OCResourceHandle)NULL,
519 NULL, PAYLOAD_TYPE_REPRESENTATION,
521 OC_OBSERVE_DEREGISTER,
524 if(result != OC_STACK_OK)
528 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
529 observer->resource->entityHandlerCallbackParam);
532 result = DeleteObserverUsingToken (token, tokenLength);
533 if(result == OC_STACK_OK)
535 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
539 result = OC_STACK_OK;
540 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
544 case OC_OBSERVER_STILL_INTERESTED:
545 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
546 observer = GetObserverUsingToken (token, tokenLength);
549 observer->forceHighQos = 0;
550 observer->failedCommCount = 0;
551 result = OC_STACK_OK;
555 result = OC_STACK_OBSERVER_NOT_FOUND;
559 case OC_OBSERVER_FAILED_COMM:
560 OIC_LOG(DEBUG, TAG, "observer is unreachable");
561 observer = GetObserverUsingToken (token, tokenLength);
564 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
566 result = FormOCEntityHandlerRequest(&ehRequest,
567 (OCRequestHandle)NULL,
570 (OCResourceHandle)NULL,
571 NULL, PAYLOAD_TYPE_REPRESENTATION,
573 OC_OBSERVE_DEREGISTER,
576 if(result != OC_STACK_OK)
578 return OC_STACK_ERROR;
580 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
581 observer->resource->entityHandlerCallbackParam);
583 result = DeleteObserverUsingToken (token, tokenLength);
584 if(result == OC_STACK_OK)
586 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
590 result = OC_STACK_OK;
591 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
596 observer->failedCommCount++;
597 result = OC_STACK_CONTINUE;
599 observer->forceHighQos = 1;
600 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
604 OIC_LOG(ERROR, TAG, "Unknown status");
605 result = OC_STACK_ERROR;
611 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
613 OCStackResult ret = OC_STACK_ERROR;
617 case CA_ADAPTER_NOT_ENABLED:
618 case CA_SERVER_NOT_STARTED:
619 ret = OC_STACK_ADAPTER_NOT_ENABLED;
621 case CA_MEMORY_ALLOC_FAILED:
622 ret = OC_STACK_NO_MEMORY;
624 case CA_STATUS_INVALID_PARAM:
625 ret = OC_STACK_INVALID_PARAM;
633 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
635 OCStackResult ret = OC_STACK_ERROR;
640 ret = OC_STACK_RESOURCE_CREATED;
643 ret = OC_STACK_RESOURCE_DELETED;
646 ret = OC_STACK_RESOURCE_CHANGED;
653 ret = OC_STACK_INVALID_QUERY;
655 case CA_UNAUTHORIZED_REQ:
656 ret = OC_STACK_UNAUTHORIZED_REQ;
659 ret = OC_STACK_INVALID_OPTION;
662 ret = OC_STACK_NO_RESOURCE;
664 case CA_RETRANSMIT_TIMEOUT:
665 ret = OC_STACK_COMM_ERROR;
667 case CA_REQUEST_ENTITY_TOO_LARGE:
668 ret = OC_STACK_TOO_LARGE_REQ;
676 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
678 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
687 // This Response Code is like HTTP 204 "No Content" but only used in
688 // response to POST and PUT requests.
692 // This Response Code is like HTTP 200 "OK" but only used in response to
697 // This should not happen but,
698 // give it a value just in case but output an error
700 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
703 case OC_STACK_RESOURCE_CREATED:
706 case OC_STACK_RESOURCE_DELETED:
709 case OC_STACK_INVALID_QUERY:
712 case OC_STACK_INVALID_OPTION:
715 case OC_STACK_NO_RESOURCE:
718 case OC_STACK_COMM_ERROR:
719 ret = CA_RETRANSMIT_TIMEOUT;
721 case OC_STACK_UNAUTHORIZED_REQ:
722 ret = CA_UNAUTHORIZED_REQ;
730 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
732 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
734 // supply default behavior.
735 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
737 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
739 if ((caFlags & OC_MASK_SCOPE) == 0)
741 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
746 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
748 return (OCTransportFlags)caFlags;
751 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
753 uint32_t lowerBound = 0;
754 uint32_t higherBound = 0;
756 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
758 return OC_STACK_INVALID_PARAM;
761 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
763 cbNode->presence->TTL = maxAgeSeconds;
765 for (int index = 0; index < PresenceTimeOutSize; index++)
767 // Guard against overflow
768 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
771 lowerBound = GetTicks((PresenceTimeOut[index] *
772 cbNode->presence->TTL *
773 MILLISECONDS_PER_SECOND)/100);
777 lowerBound = GetTicks(UINT32_MAX);
780 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
783 higherBound = GetTicks((PresenceTimeOut[index + 1] *
784 cbNode->presence->TTL *
785 MILLISECONDS_PER_SECOND)/100);
789 higherBound = GetTicks(UINT32_MAX);
792 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
794 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
795 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
796 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
799 cbNode->presence->TTLlevel = 0;
801 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
805 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
807 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
809 return OC_RSRVD_TRIGGER_CREATE;
811 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
813 return OC_RSRVD_TRIGGER_CHANGE;
817 return OC_RSRVD_TRIGGER_DELETE;
821 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
825 return OC_PRESENCE_TRIGGER_CREATE;
827 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
829 return OC_PRESENCE_TRIGGER_CREATE;
831 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
833 return OC_PRESENCE_TRIGGER_CHANGE;
837 return OC_PRESENCE_TRIGGER_DELETE;
842 * The cononical presence allows constructed URIs to be string compared.
844 * requestUri must be a char array of size CA_MAX_URI_LENGTH
846 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
849 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
850 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
851 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
853 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
855 if (ep->adapter == CA_ADAPTER_IP)
857 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
859 if ('\0' == ep->addr[0]) // multicast
861 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
865 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
866 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
871 if ('\0' == ep->addr[0]) // multicast
873 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
874 ep->port = OC_MULTICAST_PORT;
876 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
877 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
881 // might work for other adapters (untested, but better than nothing)
882 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
883 OC_RSRVD_PRESENCE_URI);
887 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
888 const CAResponseInfo_t *responseInfo)
890 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
891 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
893 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
894 ClientCB * cbNode = NULL;
895 char *resourceTypeName = NULL;
896 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
897 OCStackResult result = OC_STACK_ERROR;
900 char presenceUri[CA_MAX_URI_LENGTH];
902 int presenceSubscribe = 0;
903 int multicastPresenceSubscribe = 0;
905 if (responseInfo->result != CA_CONTENT)
907 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
908 return OC_STACK_ERROR;
911 // check for unicast presence
912 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
913 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
915 return OC_STACK_INVALID_URI;
918 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
921 presenceSubscribe = 1;
925 // check for multiicast presence
926 CAEndpoint_t ep = { .adapter = endpoint->adapter,
927 .flags = endpoint->flags };
929 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
931 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
934 multicastPresenceSubscribe = 1;
938 if (!presenceSubscribe && !multicastPresenceSubscribe)
940 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
944 response.payload = NULL;
945 response.result = OC_STACK_OK;
947 CopyEndpointToDevAddr(endpoint, &response.devAddr);
948 FixUpClientResponse(&response);
950 if (responseInfo->info.payload)
952 result = OCParsePayload(&response.payload,
953 PAYLOAD_TYPE_PRESENCE,
954 responseInfo->info.payload,
955 responseInfo->info.payloadSize);
957 if(result != OC_STACK_OK)
959 OIC_LOG(ERROR, TAG, "Presence parse failed");
962 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
964 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
965 result = OC_STACK_ERROR;
968 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
969 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
970 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
973 if (presenceSubscribe)
975 if(cbNode->sequenceNumber == response.sequenceNumber)
977 OIC_LOG(INFO, TAG, "No presence change");
978 ResetPresenceTTL(cbNode, maxAge);
979 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
985 OIC_LOG(INFO, TAG, "Stopping presence");
986 response.result = OC_STACK_PRESENCE_STOPPED;
989 OICFree(cbNode->presence->timeOut);
990 OICFree(cbNode->presence);
991 cbNode->presence = NULL;
996 if(!cbNode->presence)
998 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1000 if(!(cbNode->presence))
1002 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1003 result = OC_STACK_NO_MEMORY;
1007 VERIFY_NON_NULL_V(cbNode->presence);
1008 cbNode->presence->timeOut = NULL;
1009 cbNode->presence->timeOut = (uint32_t *)
1010 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1011 if(!(cbNode->presence->timeOut)){
1013 "Could not allocate memory for cbNode->presence->timeOut");
1014 OICFree(cbNode->presence);
1015 result = OC_STACK_NO_MEMORY;
1020 ResetPresenceTTL(cbNode, maxAge);
1022 cbNode->sequenceNumber = response.sequenceNumber;
1024 // Ensure that a filter is actually applied.
1025 if( resourceTypeName && cbNode->filterResourceType)
1027 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1036 // This is the multicast case
1037 OCMulticastNode* mcNode = NULL;
1038 mcNode = GetMCPresenceNode(presenceUri);
1042 if(mcNode->nonce == response.sequenceNumber)
1044 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1047 mcNode->nonce = response.sequenceNumber;
1051 OIC_LOG(INFO, TAG, "Stopping presence");
1052 response.result = OC_STACK_PRESENCE_STOPPED;
1057 char* uri = OICStrdup(presenceUri);
1061 "No Memory for URI to store in the presence node");
1062 result = OC_STACK_NO_MEMORY;
1066 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1067 if(result == OC_STACK_NO_MEMORY)
1070 "No Memory for Multicast Presence Node");
1074 // presence node now owns uri
1077 // Ensure that a filter is actually applied.
1078 if(resourceTypeName && cbNode->filterResourceType)
1080 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1087 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1089 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1091 FindAndDeleteClientCB(cbNode);
1095 OCPayloadDestroy(response.payload);
1099 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1101 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1103 if(responseInfo->info.resourceUri &&
1104 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1106 HandlePresenceResponse(endPoint, responseInfo);
1110 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1111 responseInfo->info.tokenLength, NULL, NULL);
1113 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1114 responseInfo->info.tokenLength);
1118 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1119 if(responseInfo->result == CA_EMPTY)
1121 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1122 // We do not have a case for the client to receive a RESET
1123 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1125 //This is the case of receiving an ACK on a request to a slow resource!
1126 OIC_LOG(INFO, TAG, "This is a pure ACK");
1127 //TODO: should we inform the client
1128 // app that at least the request was received at the server?
1131 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1133 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1134 OIC_LOG(INFO, TAG, "Calling into application address space");
1136 OCClientResponse response =
1137 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1138 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1139 FixUpClientResponse(&response);
1140 response.resourceUri = responseInfo->info.resourceUri;
1141 memcpy(response.identity.id, responseInfo->info.identity.id,
1142 sizeof (response.identity.id));
1143 response.identity.id_length = responseInfo->info.identity.id_length;
1145 response.result = CAResponseToOCStackResult(responseInfo->result);
1146 cbNode->callBack(cbNode->context,
1147 cbNode->handle, &response);
1148 FindAndDeleteClientCB(cbNode);
1152 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1153 OIC_LOG(INFO, TAG, "Calling into application address space");
1155 OCClientResponse response =
1156 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1157 response.sequenceNumber = -1;
1158 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1159 FixUpClientResponse(&response);
1160 response.resourceUri = responseInfo->info.resourceUri;
1161 memcpy(response.identity.id, responseInfo->info.identity.id,
1162 sizeof (response.identity.id));
1163 response.identity.id_length = responseInfo->info.identity.id_length;
1165 response.result = CAResponseToOCStackResult(responseInfo->result);
1167 if(responseInfo->info.payload &&
1168 responseInfo->info.payloadSize)
1170 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1171 // check the security resource
1172 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1174 type = PAYLOAD_TYPE_SECURITY;
1176 else if (cbNode->method == OC_REST_DISCOVER)
1178 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1179 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1181 type = PAYLOAD_TYPE_DISCOVERY;
1183 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1185 type = PAYLOAD_TYPE_DEVICE;
1187 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1189 type = PAYLOAD_TYPE_PLATFORM;
1191 #ifdef ROUTING_GATEWAY
1192 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1194 type = PAYLOAD_TYPE_REPRESENTATION;
1197 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1199 type = PAYLOAD_TYPE_RD;
1202 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1204 type = PAYLOAD_TYPE_REPRESENTATION;
1209 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1210 cbNode->method, cbNode->requestUri);
1214 else if (cbNode->method == OC_REST_GET ||
1215 cbNode->method == OC_REST_PUT ||
1216 cbNode->method == OC_REST_POST ||
1217 cbNode->method == OC_REST_OBSERVE ||
1218 cbNode->method == OC_REST_OBSERVE_ALL ||
1219 cbNode->method == OC_REST_DELETE)
1221 char targetUri[MAX_URI_LENGTH];
1222 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1223 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1224 if (strcmp(targetUri, cbNode->requestUri) == 0)
1226 type = PAYLOAD_TYPE_RD;
1228 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1230 type = PAYLOAD_TYPE_PLATFORM;
1232 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1234 type = PAYLOAD_TYPE_DEVICE;
1236 if (type == PAYLOAD_TYPE_INVALID)
1238 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1239 cbNode->method, cbNode->requestUri);
1240 type = PAYLOAD_TYPE_REPRESENTATION;
1245 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1246 cbNode->method, cbNode->requestUri);
1250 if(OC_STACK_OK != OCParsePayload(&response.payload,
1252 responseInfo->info.payload,
1253 responseInfo->info.payloadSize))
1255 OIC_LOG(ERROR, TAG, "Error converting payload");
1256 OCPayloadDestroy(response.payload);
1261 response.numRcvdVendorSpecificHeaderOptions = 0;
1262 if(responseInfo->info.numOptions > 0)
1265 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1266 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1269 uint32_t observationOption;
1270 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1271 for (observationOption=0, i=0;
1272 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1276 (observationOption << 8) | optionData[i];
1278 response.sequenceNumber = observationOption;
1280 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1285 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1288 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1290 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1291 OCPayloadDestroy(response.payload);
1295 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1297 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1298 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1302 if (cbNode->method == OC_REST_OBSERVE &&
1303 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1304 response.sequenceNumber <= cbNode->sequenceNumber)
1306 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1307 response.sequenceNumber);
1311 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1314 cbNode->sequenceNumber = response.sequenceNumber;
1316 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1318 FindAndDeleteClientCB(cbNode);
1322 // To keep discovery callbacks active.
1323 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1324 MILLISECONDS_PER_SECOND);
1328 //Need to send ACK when the response is CON
1329 if(responseInfo->info.type == CA_MSG_CONFIRM)
1331 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1332 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1335 OCPayloadDestroy(response.payload);
1342 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1343 if(responseInfo->result == CA_EMPTY)
1345 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1346 if(responseInfo->info.type == CA_MSG_RESET)
1348 OIC_LOG(INFO, TAG, "This is a RESET");
1349 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1350 OC_OBSERVER_NOT_INTERESTED);
1352 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1354 OIC_LOG(INFO, TAG, "This is a pure ACK");
1355 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1356 OC_OBSERVER_STILL_INTERESTED);
1359 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1361 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1362 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1363 OC_OBSERVER_FAILED_COMM);
1368 if(!cbNode && !observer)
1370 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1371 || myStackMode == OC_GATEWAY)
1373 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1374 if(responseInfo->result == CA_EMPTY)
1376 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1380 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1381 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1382 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1386 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1387 || myStackMode == OC_GATEWAY)
1389 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1390 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1392 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1393 responseInfo->info.messageId);
1395 if (responseInfo->info.type == CA_MSG_RESET)
1397 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1398 responseInfo->info.messageId);
1405 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1408 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1410 VERIFY_NON_NULL_NR(endPoint, FATAL);
1411 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1413 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1415 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1416 #ifdef ROUTING_GATEWAY
1417 bool needRIHandling = false;
1419 * Routing manager is going to update either of endpoint or response or both.
1420 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1421 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1424 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1426 if(ret != OC_STACK_OK || !needRIHandling)
1428 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1434 * Put source in sender endpoint so that the next packet from application can be routed to
1435 * proper destination and remove "RM" coap header option before passing request / response to
1436 * RI as this option will make no sense to either RI or application.
1438 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1439 (uint8_t *) &(responseInfo->info.numOptions),
1440 (CAEndpoint_t *) endPoint);
1443 OCHandleResponse(endPoint, responseInfo);
1445 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1449 * This function handles error response from CA
1450 * code shall be added to handle the errors
1452 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1454 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1456 if (NULL == endPoint)
1458 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1462 if (NULL == errorInfo)
1464 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1468 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1469 errorInfo->info.tokenLength, NULL, NULL);
1472 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1473 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1474 FixUpClientResponse(&response);
1475 response.resourceUri = errorInfo->info.resourceUri;
1476 memcpy(response.identity.id, errorInfo->info.identity.id,
1477 sizeof (response.identity.id));
1478 response.identity.id_length = errorInfo->info.identity.id_length;
1479 response.result = CAResultToOCStackResult(errorInfo->result);
1481 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1482 FindAndDeleteClientCB(cbNode);
1485 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1489 * This function sends out Direct Stack Responses. These are responses that are not coming
1490 * from the application entity handler. These responses have no payload and are usually ACKs,
1491 * RESETs or some error conditions that were caught by the stack.
1493 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1494 const CAResponseResult_t responseResult, const CAMessageType_t type,
1495 const uint8_t numOptions, const CAHeaderOption_t *options,
1496 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1498 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1499 CAResponseInfo_t respInfo = {
1500 .result = responseResult
1502 respInfo.info.messageId = coapID;
1503 respInfo.info.numOptions = numOptions;
1505 if (respInfo.info.numOptions)
1507 respInfo.info.options =
1508 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1509 memcpy (respInfo.info.options, options,
1510 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1514 respInfo.info.payload = NULL;
1515 respInfo.info.token = token;
1516 respInfo.info.tokenLength = tokenLength;
1517 respInfo.info.type = type;
1518 respInfo.info.resourceUri = OICStrdup (resourceUri);
1519 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1521 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1522 // Add the destination to route option from the endpoint->routeData.
1523 bool doPost = false;
1524 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1525 if(OC_STACK_OK != result)
1527 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1532 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1533 CARequestInfo_t reqInfo = {.method = CA_POST };
1534 /* The following initialization is not done in a single initializer block as in
1535 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1536 * does not have designated initalizers. This is a work-around for now.
1538 reqInfo.info.type = CA_MSG_NONCONFIRM;
1539 reqInfo.info.messageId = coapID;
1540 reqInfo.info.tokenLength = tokenLength;
1541 reqInfo.info.token = token;
1542 reqInfo.info.numOptions = respInfo.info.numOptions;
1543 reqInfo.info.payload = NULL;
1544 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1545 if (reqInfo.info.numOptions)
1547 reqInfo.info.options =
1548 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1549 if (NULL == reqInfo.info.options)
1551 OIC_LOG(ERROR, TAG, "Calloc failed");
1552 return OC_STACK_NO_MEMORY;
1554 memcpy (reqInfo.info.options, respInfo.info.options,
1555 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1558 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1559 OICFree (reqInfo.info.resourceUri);
1560 OICFree (reqInfo.info.options);
1561 OICFree (respInfo.info.resourceUri);
1562 OICFree (respInfo.info.options);
1563 if (CA_STATUS_OK != caResult)
1565 OIC_LOG(ERROR, TAG, "CASendRequest error");
1566 return CAResultToOCResult(caResult);
1572 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1574 // resourceUri in the info field is cloned in the CA layer and
1575 // thus ownership is still here.
1576 OICFree (respInfo.info.resourceUri);
1577 OICFree (respInfo.info.options);
1578 if(CA_STATUS_OK != caResult)
1580 OIC_LOG(ERROR, TAG, "CASendResponse error");
1581 return CAResultToOCResult(caResult);
1584 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1588 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1590 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1591 OCStackResult result = OC_STACK_ERROR;
1592 if(!protocolRequest)
1594 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1595 return OC_STACK_INVALID_PARAM;
1598 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1599 protocolRequest->tokenLength);
1602 OIC_LOG(INFO, TAG, "This is a new Server Request");
1603 result = AddServerRequest(&request, protocolRequest->coapID,
1604 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1605 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1606 protocolRequest->observationOption, protocolRequest->qos,
1607 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1608 protocolRequest->payload, protocolRequest->requestToken,
1609 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1610 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1611 &protocolRequest->devAddr);
1612 if (OC_STACK_OK != result)
1614 OIC_LOG(ERROR, TAG, "Error adding server request");
1620 OIC_LOG(ERROR, TAG, "Out of Memory");
1621 return OC_STACK_NO_MEMORY;
1624 if(!protocolRequest->reqMorePacket)
1626 request->requestComplete = 1;
1631 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1634 if(request->requestComplete)
1636 OIC_LOG(INFO, TAG, "This Server Request is complete");
1637 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1638 OCResource *resource = NULL;
1639 result = DetermineResourceHandling (request, &resHandling, &resource);
1640 if (result == OC_STACK_OK)
1642 result = ProcessRequest(resHandling, resource, request);
1647 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1648 result = OC_STACK_CONTINUE;
1653 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1655 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1658 if (requestInfo->info.resourceUri &&
1659 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1661 HandleKeepAliveRequest(endPoint, requestInfo);
1666 OCStackResult requestResult = OC_STACK_ERROR;
1668 if(myStackMode == OC_CLIENT)
1670 //TODO: should the client be responding to requests?
1674 OCServerProtocolRequest serverRequest = {0};
1676 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1678 char * uriWithoutQuery = NULL;
1679 char * query = NULL;
1681 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1683 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1685 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1688 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1689 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1691 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1693 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1694 OICFree(uriWithoutQuery);
1698 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1699 OICFree(uriWithoutQuery);
1706 if(strlen(query) < MAX_QUERY_LENGTH)
1708 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1713 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1719 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1721 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1722 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1723 if (!serverRequest.payload)
1725 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1728 memcpy (serverRequest.payload, requestInfo->info.payload,
1729 requestInfo->info.payloadSize);
1733 serverRequest.reqTotalSize = 0;
1736 switch (requestInfo->method)
1739 serverRequest.method = OC_REST_GET;
1742 serverRequest.method = OC_REST_PUT;
1745 serverRequest.method = OC_REST_POST;
1748 serverRequest.method = OC_REST_DELETE;
1751 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1752 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1753 requestInfo->info.type, requestInfo->info.numOptions,
1754 requestInfo->info.options, requestInfo->info.token,
1755 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1756 OICFree(serverRequest.payload);
1760 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1761 requestInfo->info.tokenLength);
1763 serverRequest.tokenLength = requestInfo->info.tokenLength;
1764 if (serverRequest.tokenLength) {
1766 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1768 if (!serverRequest.requestToken)
1770 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1771 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1772 requestInfo->info.type, requestInfo->info.numOptions,
1773 requestInfo->info.options, requestInfo->info.token,
1774 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1775 OICFree(serverRequest.payload);
1778 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1781 switch (requestInfo->info.acceptFormat)
1783 case CA_FORMAT_APPLICATION_CBOR:
1784 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1786 case CA_FORMAT_UNDEFINED:
1787 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1790 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1793 if (requestInfo->info.type == CA_MSG_CONFIRM)
1795 serverRequest.qos = OC_HIGH_QOS;
1799 serverRequest.qos = OC_LOW_QOS;
1801 // CA does not need the following field
1802 // Are we sure CA does not need them? how is it responding to multicast
1803 serverRequest.delayedResNeeded = 0;
1805 serverRequest.coapID = requestInfo->info.messageId;
1807 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1809 // copy vendor specific header options
1810 uint8_t tempNum = (requestInfo->info.numOptions);
1812 // Assume no observation requested and it is a pure GET.
1813 // If obs registration/de-registration requested it'll be fetched from the
1814 // options in GetObserveHeaderOption()
1815 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1817 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1818 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1821 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1822 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1823 requestInfo->info.type, requestInfo->info.numOptions,
1824 requestInfo->info.options, requestInfo->info.token,
1825 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1826 OICFree(serverRequest.payload);
1827 OICFree(serverRequest.requestToken);
1830 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1831 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1833 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1834 sizeof(CAHeaderOption_t)*tempNum);
1837 requestResult = HandleStackRequests (&serverRequest);
1839 // Send ACK to client as precursor to slow response
1840 if (requestResult == OC_STACK_SLOW_RESOURCE)
1842 if (requestInfo->info.type == CA_MSG_CONFIRM)
1844 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1845 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1848 else if(!OCResultToSuccess(requestResult))
1850 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1852 CAResponseResult_t stackResponse =
1853 OCToCAStackResult(requestResult, serverRequest.method);
1855 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1856 requestInfo->info.type, requestInfo->info.numOptions,
1857 requestInfo->info.options, requestInfo->info.token,
1858 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1860 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1861 // The token is copied in there, and is thus still owned by this function.
1862 OICFree(serverRequest.payload);
1863 OICFree(serverRequest.requestToken);
1864 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1867 //This function will be called back by CA layer when a request is received
1868 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1870 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1873 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1879 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1883 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1884 #ifdef ROUTING_GATEWAY
1885 bool needRIHandling = false;
1886 bool isEmptyMsg = false;
1888 * Routing manager is going to update either of endpoint or request or both.
1889 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1890 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1891 * destination. It can also remove "RM" coap header option before passing request / response to
1892 * RI as this option will make no sense to either RI or application.
1894 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1895 &needRIHandling, &isEmptyMsg);
1896 if(OC_STACK_OK != ret || !needRIHandling)
1898 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1904 * Put source in sender endpoint so that the next packet from application can be routed to
1905 * proper destination and remove RM header option.
1907 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1908 (uint8_t *) &(requestInfo->info.numOptions),
1909 (CAEndpoint_t *) endPoint);
1911 #ifdef ROUTING_GATEWAY
1915 * In Gateways, the MSGType in route option is used to check if the actual
1916 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
1917 * EMPTY response is sent in the form of POST request which need to be changed
1918 * to a EMPTY response by RM. This translation is done in this part of the code.
1920 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1921 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1922 .info.messageId = requestInfo->info.messageId,
1923 .info.type = CA_MSG_ACKNOWLEDGE};
1924 OCHandleResponse(endPoint, &respInfo);
1930 // Normal handling of the packet
1931 OCHandleRequests(endPoint, requestInfo);
1933 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1936 bool validatePlatformInfo(OCPlatformInfo info)
1939 if (!info.platformID)
1941 OIC_LOG(ERROR, TAG, "No platform ID found.");
1945 if (info.manufacturerName)
1947 size_t lenManufacturerName = strlen(info.manufacturerName);
1949 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1951 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1957 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1961 if (info.manufacturerUrl)
1963 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1965 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1972 //-----------------------------------------------------------------------------
1974 //-----------------------------------------------------------------------------
1976 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1979 !raInfo->username ||
1980 !raInfo->hostname ||
1981 !raInfo->xmpp_domain)
1984 return OC_STACK_INVALID_PARAM;
1986 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1987 gRASetInfo = (result == OC_STACK_OK)? true : false;
1993 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1997 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2000 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2002 if(stackState == OC_STACK_INITIALIZED)
2004 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2005 OCStop() between them are ignored.");
2009 #ifndef ROUTING_GATEWAY
2010 if (OC_GATEWAY == mode)
2012 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2013 return OC_STACK_INVALID_PARAM;
2020 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2021 return OC_STACK_ERROR;
2025 OCStackResult result = OC_STACK_ERROR;
2026 OIC_LOG(INFO, TAG, "Entering OCInit");
2029 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2030 || (mode == OC_GATEWAY)))
2032 OIC_LOG(ERROR, TAG, "Invalid mode");
2033 return OC_STACK_ERROR;
2037 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2039 caglobals.client = true;
2041 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2043 caglobals.server = true;
2046 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2047 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2049 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2051 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2052 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2054 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2057 defaultDeviceHandler = NULL;
2058 defaultDeviceHandlerCallbackParameter = NULL;
2060 result = CAResultToOCResult(CAInitialize());
2061 VERIFY_SUCCESS(result, OC_STACK_OK);
2063 result = CAResultToOCResult(OCSelectNetwork());
2064 VERIFY_SUCCESS(result, OC_STACK_OK);
2066 switch (myStackMode)
2069 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2070 result = CAResultToOCResult(CAStartDiscoveryServer());
2071 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2074 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2075 result = CAResultToOCResult(CAStartListeningServer());
2076 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2078 case OC_CLIENT_SERVER:
2080 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2081 result = CAResultToOCResult(CAStartListeningServer());
2082 if(result == OC_STACK_OK)
2084 result = CAResultToOCResult(CAStartDiscoveryServer());
2088 VERIFY_SUCCESS(result, OC_STACK_OK);
2091 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2094 #ifdef WITH_PRESENCE
2095 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2096 #endif // WITH_PRESENCE
2098 //Update Stack state to initialized
2099 stackState = OC_STACK_INITIALIZED;
2101 // Initialize resource
2102 if(myStackMode != OC_CLIENT)
2104 result = initResources();
2107 // Initialize the SRM Policy Engine
2108 if(result == OC_STACK_OK)
2110 result = SRMInitPolicyEngine();
2111 // TODO after BeachHead delivery: consolidate into single SRMInit()
2113 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2114 RMSetStackMode(mode);
2115 #ifdef ROUTING_GATEWAY
2116 if (OC_GATEWAY == myStackMode)
2118 result = RMInitialize();
2124 if (result == OC_STACK_OK)
2126 result = InitializeKeepAlive(myStackMode);
2131 if(result != OC_STACK_OK)
2133 OIC_LOG(ERROR, TAG, "Stack initialization error");
2134 deleteAllResources();
2136 stackState = OC_STACK_UNINITIALIZED;
2141 OCStackResult OCStop()
2143 OIC_LOG(INFO, TAG, "Entering OCStop");
2145 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2147 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2150 else if (stackState != OC_STACK_INITIALIZED)
2152 OIC_LOG(ERROR, TAG, "Stack not initialized");
2153 return OC_STACK_ERROR;
2156 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2158 #ifdef WITH_PRESENCE
2159 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2160 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2161 presenceResource.presenceTTL = 0;
2162 #endif // WITH_PRESENCE
2164 #ifdef ROUTING_GATEWAY
2165 if (OC_GATEWAY == myStackMode)
2172 TerminateKeepAlive(myStackMode);
2175 // Free memory dynamically allocated for resources
2176 deleteAllResources();
2178 DeletePlatformInfo();
2180 // Remove all observers
2181 DeleteObserverList();
2182 // Remove all the client callbacks
2183 DeleteClientCBList();
2185 // De-init the SRM Policy Engine
2186 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2187 SRMDeInitPolicyEngine();
2190 stackState = OC_STACK_UNINITIALIZED;
2194 OCStackResult OCStartMulticastServer()
2196 if(stackState != OC_STACK_INITIALIZED)
2198 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2199 return OC_STACK_ERROR;
2201 CAResult_t ret = CAStartListeningServer();
2202 if (CA_STATUS_OK != ret)
2204 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2205 return OC_STACK_ERROR;
2210 OCStackResult OCStopMulticastServer()
2212 CAResult_t ret = CAStopListeningServer();
2213 if (CA_STATUS_OK != ret)
2215 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2216 return OC_STACK_ERROR;
2221 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2226 return CA_MSG_CONFIRM;
2231 return CA_MSG_NONCONFIRM;
2236 * A request uri consists of the following components in order:
2239 * CoAP over UDP prefix "coap://"
2240 * CoAP over TCP prefix "coap+tcp://"
2242 * IPv6 address "[1234::5678]"
2243 * IPv4 address "192.168.1.1"
2244 * optional port ":5683"
2245 * resource uri "/oc/core..."
2247 * for PRESENCE requests, extract resource type.
2249 static OCStackResult ParseRequestUri(const char *fullUri,
2250 OCTransportAdapter adapter,
2251 OCTransportFlags flags,
2252 OCDevAddr **devAddr,
2254 char **resourceType)
2256 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2258 OCStackResult result = OC_STACK_OK;
2259 OCDevAddr *da = NULL;
2263 // provide defaults for all returned values
2270 *resourceUri = NULL;
2274 *resourceType = NULL;
2277 // delimit url prefix, if any
2278 const char *start = fullUri;
2279 char *slash2 = strstr(start, "//");
2284 char *slash = strchr(start, '/');
2287 return OC_STACK_INVALID_URI;
2290 // process url scheme
2291 size_t prefixLen = slash2 - fullUri;
2295 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2301 // TODO: this logic should come in with unit tests exercising the various strings
2302 // processs url prefix, if any
2303 size_t urlLen = slash - start;
2307 if (urlLen && devAddr)
2308 { // construct OCDevAddr
2309 if (start[0] == '[')
2311 char *close = strchr(++start, ']');
2312 if (!close || close > slash)
2314 return OC_STACK_INVALID_URI;
2317 if (close[1] == ':')
2324 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2328 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2330 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2334 char *dot = strchr(start, '.');
2335 if (dot && dot < slash)
2337 colon = strchr(start, ':');
2338 end = (colon && colon < slash) ? colon : slash;
2343 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2347 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2349 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2357 if (len >= sizeof(da->addr))
2359 return OC_STACK_INVALID_URI;
2361 // collect port, if any
2362 if (colon && colon < slash)
2364 for (colon++; colon < slash; colon++)
2367 if (c < '0' || c > '9')
2369 return OC_STACK_INVALID_URI;
2371 port = 10 * port + c - '0';
2376 if (len >= sizeof(da->addr))
2378 return OC_STACK_INVALID_URI;
2381 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2384 return OC_STACK_NO_MEMORY;
2386 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2388 da->adapter = adapter;
2390 if (!strncmp(fullUri, "coaps:", 6))
2392 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2397 // process resource uri, if any
2399 { // request uri and query
2400 size_t ulen = strlen(slash); // resource uri length
2401 size_t tlen = 0; // resource type length
2404 static const char strPresence[] = "/oic/ad?rt=";
2405 static const size_t lenPresence = sizeof(strPresence) - 1;
2406 if (!strncmp(slash, strPresence, lenPresence))
2408 type = slash + lenPresence;
2409 tlen = ulen - lenPresence;
2414 *resourceUri = (char *)OICMalloc(ulen + 1);
2417 result = OC_STACK_NO_MEMORY;
2420 strcpy(*resourceUri, slash);
2423 if (type && resourceType)
2425 *resourceType = (char *)OICMalloc(tlen + 1);
2428 result = OC_STACK_NO_MEMORY;
2432 OICStrcpy(*resourceType, (tlen+1), type);
2439 // free all returned values
2446 OICFree(*resourceUri);
2450 OICFree(*resourceType);
2455 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2456 char *resourceUri, char **requestUri)
2458 char uri[CA_MAX_URI_LENGTH];
2460 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2462 *requestUri = OICStrdup(uri);
2465 return OC_STACK_NO_MEMORY;
2472 * Discover or Perform requests on a specified resource
2474 OCStackResult OCDoResource(OCDoHandle *handle,
2476 const char *requestUri,
2477 const OCDevAddr *destination,
2479 OCConnectivityType connectivityType,
2480 OCQualityOfService qos,
2481 OCCallbackData *cbData,
2482 OCHeaderOption *options,
2485 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2487 // Validate input parameters
2488 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2489 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2490 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2492 OCStackResult result = OC_STACK_ERROR;
2493 CAResult_t caResult;
2494 CAToken_t token = NULL;
2495 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2496 ClientCB *clientCB = NULL;
2497 OCDoHandle resHandle = NULL;
2498 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2499 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2501 OCTransportAdapter adapter;
2502 OCTransportFlags flags;
2503 // the request contents are put here
2504 CARequestInfo_t requestInfo = {.method = CA_GET};
2505 // requestUri will be parsed into the following three variables
2506 OCDevAddr *devAddr = NULL;
2507 char *resourceUri = NULL;
2508 char *resourceType = NULL;
2511 * Support original behavior with address on resourceUri argument.
2513 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2514 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2516 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2518 if (result != OC_STACK_OK)
2520 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2527 case OC_REST_OBSERVE:
2528 case OC_REST_OBSERVE_ALL:
2529 case OC_REST_CANCEL_OBSERVE:
2530 requestInfo.method = CA_GET;
2533 requestInfo.method = CA_PUT;
2536 requestInfo.method = CA_POST;
2538 case OC_REST_DELETE:
2539 requestInfo.method = CA_DELETE;
2541 case OC_REST_DISCOVER:
2543 if (destination || devAddr)
2545 requestInfo.isMulticast = false;
2549 tmpDevAddr.adapter = adapter;
2550 tmpDevAddr.flags = flags;
2551 destination = &tmpDevAddr;
2552 requestInfo.isMulticast = true;
2554 // CA_DISCOVER will become GET and isMulticast
2555 requestInfo.method = CA_GET;
2557 #ifdef WITH_PRESENCE
2558 case OC_REST_PRESENCE:
2559 // Replacing method type with GET because "presence"
2560 // is a stack layer only implementation.
2561 requestInfo.method = CA_GET;
2565 result = OC_STACK_INVALID_METHOD;
2569 if (!devAddr && !destination)
2571 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2572 result = OC_STACK_INVALID_PARAM;
2576 /* If not original behavior, use destination argument */
2577 if (destination && !devAddr)
2579 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2582 result = OC_STACK_NO_MEMORY;
2585 *devAddr = *destination;
2588 resHandle = GenerateInvocationHandle();
2591 result = OC_STACK_NO_MEMORY;
2595 caResult = CAGenerateToken(&token, tokenLength);
2596 if (caResult != CA_STATUS_OK)
2598 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2599 result= OC_STACK_ERROR;
2603 // fill in request data
2604 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2605 requestInfo.info.token = token;
2606 requestInfo.info.tokenLength = tokenLength;
2607 requestInfo.info.resourceUri = resourceUri;
2609 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2611 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2612 options, numOptions, OC_OBSERVE_REGISTER);
2613 if (result != OC_STACK_OK)
2617 requestInfo.info.numOptions = numOptions + 1;
2621 requestInfo.info.numOptions = numOptions;
2622 requestInfo.info.options =
2623 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2624 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2625 numOptions * sizeof(CAHeaderOption_t));
2628 CopyDevAddrToEndpoint(devAddr, &endpoint);
2633 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2636 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2639 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2643 requestInfo.info.payload = NULL;
2644 requestInfo.info.payloadSize = 0;
2645 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2648 // prepare for response
2649 #ifdef WITH_PRESENCE
2650 if (method == OC_REST_PRESENCE)
2652 char *presenceUri = NULL;
2653 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2654 if (OC_STACK_OK != result)
2659 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2660 // Presence notification will form a canonical uri to
2661 // look for callbacks into the application.
2662 resourceUri = presenceUri;
2666 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2667 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2668 method, devAddr, resourceUri, resourceType, ttl);
2669 if (OC_STACK_OK != result)
2674 devAddr = NULL; // Client CB list entry now owns it
2675 resourceUri = NULL; // Client CB list entry now owns it
2676 resourceType = NULL; // Client CB list entry now owns it
2679 result = OCSendRequest(&endpoint, &requestInfo);
2680 if (OC_STACK_OK != result)
2687 *handle = resHandle;
2691 if (result != OC_STACK_OK)
2693 OIC_LOG(ERROR, TAG, "OCDoResource error");
2694 FindAndDeleteClientCB(clientCB);
2695 CADestroyToken(token);
2703 // This is the owner of the payload object, so we free it
2704 OCPayloadDestroy(payload);
2705 OICFree(requestInfo.info.payload);
2707 OICFree(resourceUri);
2708 OICFree(resourceType);
2709 OICFree(requestInfo.info.options);
2713 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2717 * This ftn is implemented one of two ways in the case of observation:
2719 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2720 * Remove the callback associated on client side.
2721 * When the next notification comes in from server,
2722 * reply with RESET message to server.
2723 * Keep in mind that the server will react to RESET only
2724 * if the last notification was sent as CON
2726 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2727 * and it is associated with an observe request
2728 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2729 * Send CON Observe request to server with
2730 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2731 * Remove the callback associated on client side.
2733 OCStackResult ret = OC_STACK_OK;
2734 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2735 CARequestInfo_t requestInfo = {.method = CA_GET};
2739 return OC_STACK_INVALID_PARAM;
2742 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2745 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2746 return OC_STACK_ERROR;
2749 switch (clientCB->method)
2751 case OC_REST_OBSERVE:
2752 case OC_REST_OBSERVE_ALL:
2754 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2756 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2758 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2760 FindAndDeleteClientCB(clientCB);
2764 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2766 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2767 requestInfo.info.token = clientCB->token;
2768 requestInfo.info.tokenLength = clientCB->tokenLength;
2770 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2771 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2773 return OC_STACK_ERROR;
2775 requestInfo.info.numOptions = numOptions + 1;
2776 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2779 ret = OCSendRequest(&endpoint, &requestInfo);
2781 if (requestInfo.info.options)
2783 OICFree (requestInfo.info.options);
2785 if (requestInfo.info.resourceUri)
2787 OICFree (requestInfo.info.resourceUri);
2792 case OC_REST_DISCOVER:
2793 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2794 clientCB->requestUri);
2795 FindAndDeleteClientCB(clientCB);
2798 #ifdef WITH_PRESENCE
2799 case OC_REST_PRESENCE:
2800 FindAndDeleteClientCB(clientCB);
2805 ret = OC_STACK_INVALID_METHOD;
2813 * @brief Register Persistent storage callback.
2814 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2816 * OC_STACK_OK - No errors; Success
2817 * OC_STACK_INVALID_PARAM - Invalid parameter
2819 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2821 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2822 if(!persistentStorageHandler)
2824 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2825 return OC_STACK_INVALID_PARAM;
2829 if( !persistentStorageHandler->open ||
2830 !persistentStorageHandler->close ||
2831 !persistentStorageHandler->read ||
2832 !persistentStorageHandler->unlink ||
2833 !persistentStorageHandler->write)
2835 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2836 return OC_STACK_INVALID_PARAM;
2839 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2842 #ifdef WITH_PRESENCE
2844 OCStackResult OCProcessPresence()
2846 OCStackResult result = OC_STACK_OK;
2848 // the following line floods the log with messages that are irrelevant
2849 // to most purposes. Uncomment as needed.
2850 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2851 ClientCB* cbNode = NULL;
2852 OCClientResponse clientResponse;
2853 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2855 LL_FOREACH(cbList, cbNode)
2857 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2862 uint32_t now = GetTicks(0);
2863 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2864 cbNode->presence->TTLlevel);
2865 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2867 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2872 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2874 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2875 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2877 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2879 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2881 clientResponse.sequenceNumber = 0;
2882 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2883 clientResponse.devAddr = *cbNode->devAddr;
2884 FixUpClientResponse(&clientResponse);
2885 clientResponse.payload = NULL;
2887 // Increment the TTLLevel (going to a next state), so we don't keep
2888 // sending presence notification to client.
2889 cbNode->presence->TTLlevel++;
2890 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2891 cbNode->presence->TTLlevel);
2893 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2894 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2896 FindAndDeleteClientCB(cbNode);
2900 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2905 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2906 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2907 CARequestInfo_t requestInfo = {.method = CA_GET};
2909 OIC_LOG(DEBUG, TAG, "time to test server presence");
2911 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2913 requestData.type = CA_MSG_NONCONFIRM;
2914 requestData.token = cbNode->token;
2915 requestData.tokenLength = cbNode->tokenLength;
2916 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2917 requestInfo.method = CA_GET;
2918 requestInfo.info = requestData;
2920 result = OCSendRequest(&endpoint, &requestInfo);
2921 if (OC_STACK_OK != result)
2926 cbNode->presence->TTLlevel++;
2927 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2930 if (result != OC_STACK_OK)
2932 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2937 #endif // WITH_PRESENCE
2939 OCStackResult OCProcess()
2941 #ifdef WITH_PRESENCE
2942 OCProcessPresence();
2944 CAHandleRequestResponse();
2946 #ifdef ROUTING_GATEWAY
2956 #ifdef WITH_PRESENCE
2957 OCStackResult OCStartPresence(const uint32_t ttl)
2959 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2960 OCChangeResourceProperty(
2961 &(((OCResource *)presenceResource.handle)->resourceProperties),
2964 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2966 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2967 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2971 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2972 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2976 presenceResource.presenceTTL = ttl;
2978 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2980 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2982 presenceState = OC_PRESENCE_INITIALIZED;
2984 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2986 CAToken_t caToken = NULL;
2987 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2988 if (caResult != CA_STATUS_OK)
2990 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2991 CADestroyToken(caToken);
2992 return OC_STACK_ERROR;
2995 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2996 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2997 CADestroyToken(caToken);
3000 // Each time OCStartPresence is called
3001 // a different random 32-bit integer number is used
3002 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3004 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3005 OC_PRESENCE_TRIGGER_CREATE);
3008 OCStackResult OCStopPresence()
3010 OCStackResult result = OC_STACK_ERROR;
3012 if(presenceResource.handle)
3014 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3016 // make resource inactive
3017 result = OCChangeResourceProperty(
3018 &(((OCResource *) presenceResource.handle)->resourceProperties),
3022 if(result != OC_STACK_OK)
3025 "Changing the presence resource properties to ACTIVE not successful");
3029 return SendStopNotification();
3033 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3034 void* callbackParameter)
3036 defaultDeviceHandler = entityHandler;
3037 defaultDeviceHandlerCallbackParameter = callbackParameter;
3042 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3044 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3046 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3048 if (validatePlatformInfo(platformInfo))
3050 return SavePlatformInfo(platformInfo);
3054 return OC_STACK_INVALID_PARAM;
3059 return OC_STACK_ERROR;
3063 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3065 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3067 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3069 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3070 return OC_STACK_INVALID_PARAM;
3073 if (deviceInfo.types)
3075 OCStringLL *type = deviceInfo.types;
3076 OCResource *resource = findResource((OCResource *) deviceResource);
3079 return OC_STACK_INVALID_PARAM;
3084 OCBindResourceTypeToResource(deviceResource, type->value);
3088 return SaveDeviceInfo(deviceInfo);
3091 OCStackResult OCCreateResource(OCResourceHandle *handle,
3092 const char *resourceTypeName,
3093 const char *resourceInterfaceName,
3094 const char *uri, OCEntityHandler entityHandler,
3095 void* callbackParam,
3096 uint8_t resourceProperties)
3099 OCResource *pointer = NULL;
3100 OCStackResult result = OC_STACK_ERROR;
3102 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3104 if(myStackMode == OC_CLIENT)
3106 return OC_STACK_INVALID_PARAM;
3108 // Validate parameters
3109 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3111 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3112 return OC_STACK_INVALID_URI;
3114 // Is it presented during resource discovery?
3115 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3117 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3118 return OC_STACK_INVALID_PARAM;
3121 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3123 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3126 // Make sure resourceProperties bitmask has allowed properties specified
3127 if (resourceProperties
3128 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3129 OC_EXPLICIT_DISCOVERABLE))
3131 OIC_LOG(ERROR, TAG, "Invalid property");
3132 return OC_STACK_INVALID_PARAM;
3135 // If the headResource is NULL, then no resources have been created...
3136 pointer = headResource;
3139 // At least one resources is in the resource list, so we need to search for
3140 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3143 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3145 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3146 return OC_STACK_INVALID_PARAM;
3148 pointer = pointer->next;
3151 // Create the pointer and insert it into the resource list
3152 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3155 result = OC_STACK_NO_MEMORY;
3158 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3160 insertResource(pointer);
3163 pointer->uri = OICStrdup(uri);
3166 result = OC_STACK_NO_MEMORY;
3170 // Set properties. Set OC_ACTIVE
3171 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3174 // Add the resourcetype to the resource
3175 result = BindResourceTypeToResource(pointer, resourceTypeName);
3176 if (result != OC_STACK_OK)
3178 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3182 // Add the resourceinterface to the resource
3183 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3184 if (result != OC_STACK_OK)
3186 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3190 // If an entity handler has been passed, attach it to the newly created
3191 // resource. Otherwise, set the default entity handler.
3194 pointer->entityHandler = entityHandler;
3195 pointer->entityHandlerCallbackParam = callbackParam;
3199 pointer->entityHandler = defaultResourceEHandler;
3200 pointer->entityHandlerCallbackParam = NULL;
3203 // Initialize a pointer indicating child resources in case of collection
3204 pointer->rsrcChildResourcesHead = NULL;
3207 result = OC_STACK_OK;
3209 #ifdef WITH_PRESENCE
3210 if (presenceResource.handle)
3212 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3213 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3217 if (result != OC_STACK_OK)
3219 // Deep delete of resource and other dynamic elements that it contains
3220 deleteResource(pointer);
3225 OCStackResult OCBindResource(
3226 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3228 OCResource *resource = NULL;
3229 OCChildResource *tempChildResource = NULL;
3230 OCChildResource *newChildResource = NULL;
3232 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3234 // Validate parameters
3235 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3236 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3237 // Container cannot contain itself
3238 if (collectionHandle == resourceHandle)
3240 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3241 return OC_STACK_INVALID_PARAM;
3244 // Use the handle to find the resource in the resource linked list
3245 resource = findResource((OCResource *) collectionHandle);
3248 OIC_LOG(ERROR, TAG, "Collection handle not found");
3249 return OC_STACK_INVALID_PARAM;
3252 // Look for an open slot to add add the child resource.
3253 // If found, add it and return success
3255 tempChildResource = resource->rsrcChildResourcesHead;
3257 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3259 // TODO: what if one of child resource was deregistered without unbinding?
3260 tempChildResource = tempChildResource->next;
3263 // Do memory allocation for child resource
3264 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3265 if(!newChildResource)
3267 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3268 return OC_STACK_ERROR;
3271 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3272 newChildResource->next = NULL;
3274 if(!resource->rsrcChildResourcesHead)
3276 resource->rsrcChildResourcesHead = newChildResource;
3279 tempChildResource->next = newChildResource;
3282 OIC_LOG(INFO, TAG, "resource bound");
3284 #ifdef WITH_PRESENCE
3285 if (presenceResource.handle)
3287 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3288 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3289 OC_PRESENCE_TRIGGER_CHANGE);
3296 OCStackResult OCUnBindResource(
3297 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3299 OCResource *resource = NULL;
3300 OCChildResource *tempChildResource = NULL;
3301 OCChildResource *tempLastChildResource = NULL;
3303 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3305 // Validate parameters
3306 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3307 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3308 // Container cannot contain itself
3309 if (collectionHandle == resourceHandle)
3311 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3312 return OC_STACK_INVALID_PARAM;
3315 // Use the handle to find the resource in the resource linked list
3316 resource = findResource((OCResource *) collectionHandle);
3319 OIC_LOG(ERROR, TAG, "Collection handle not found");
3320 return OC_STACK_INVALID_PARAM;
3323 // Look for an open slot to add add the child resource.
3324 // If found, add it and return success
3325 if(!resource->rsrcChildResourcesHead)
3327 OIC_LOG(INFO, TAG, "resource not found in collection");
3329 // Unable to add resourceHandle, so return error
3330 return OC_STACK_ERROR;
3334 tempChildResource = resource->rsrcChildResourcesHead;
3336 while (tempChildResource)
3338 if(tempChildResource->rsrcResource == resourceHandle)
3340 // if resource going to be unbinded is the head one.
3341 if( tempChildResource == resource->rsrcChildResourcesHead )
3343 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3344 OICFree(resource->rsrcChildResourcesHead);
3345 resource->rsrcChildResourcesHead = temp;
3350 OCChildResource *temp = tempChildResource->next;
3351 OICFree(tempChildResource);
3352 tempLastChildResource->next = temp;
3356 OIC_LOG(INFO, TAG, "resource unbound");
3358 // Send notification when resource is unbounded successfully.
3359 #ifdef WITH_PRESENCE
3360 if (presenceResource.handle)
3362 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3363 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3364 OC_PRESENCE_TRIGGER_CHANGE);
3367 tempChildResource = NULL;
3368 tempLastChildResource = NULL;
3374 tempLastChildResource = tempChildResource;
3375 tempChildResource = tempChildResource->next;
3378 OIC_LOG(INFO, TAG, "resource not found in collection");
3380 tempChildResource = NULL;
3381 tempLastChildResource = NULL;
3383 // Unable to add resourceHandle, so return error
3384 return OC_STACK_ERROR;
3387 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3389 if (!resourceItemName)
3393 // Per RFC 6690 only registered values must follow the first rule below.
3394 // At this point in time the only values registered begin with "core", and
3395 // all other values are specified as opaque strings where multiple values
3396 // are separated by a space.
3397 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3399 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3401 if (resourceItemName[index] != '.'
3402 && resourceItemName[index] != '-'
3403 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3404 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3412 for (size_t index = 0; resourceItemName[index]; ++index)
3414 if (resourceItemName[index] == ' '
3415 || resourceItemName[index] == '\t'
3416 || resourceItemName[index] == '\r'
3417 || resourceItemName[index] == '\n')
3427 OCStackResult BindResourceTypeToResource(OCResource* resource,
3428 const char *resourceTypeName)
3430 OCResourceType *pointer = NULL;
3432 OCStackResult result = OC_STACK_ERROR;
3434 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3436 if (!ValidateResourceTypeInterface(resourceTypeName))
3438 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3439 return OC_STACK_INVALID_PARAM;
3442 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3445 result = OC_STACK_NO_MEMORY;
3449 str = OICStrdup(resourceTypeName);
3452 result = OC_STACK_NO_MEMORY;
3455 pointer->resourcetypename = str;
3456 pointer->next = NULL;
3458 insertResourceType(resource, pointer);
3459 result = OC_STACK_OK;
3462 if (result != OC_STACK_OK)
3471 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3472 const char *resourceInterfaceName)
3474 OCResourceInterface *pointer = NULL;
3476 OCStackResult result = OC_STACK_ERROR;
3478 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3480 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3482 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3483 return OC_STACK_INVALID_PARAM;
3486 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3488 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3491 result = OC_STACK_NO_MEMORY;
3495 str = OICStrdup(resourceInterfaceName);
3498 result = OC_STACK_NO_MEMORY;
3501 pointer->name = str;
3503 // Bind the resourceinterface to the resource
3504 insertResourceInterface(resource, pointer);
3506 result = OC_STACK_OK;
3509 if (result != OC_STACK_OK)
3518 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3519 const char *resourceTypeName)
3522 OCStackResult result = OC_STACK_ERROR;
3523 OCResource *resource = NULL;
3525 resource = findResource((OCResource *) handle);
3528 OIC_LOG(ERROR, TAG, "Resource not found");
3529 return OC_STACK_ERROR;
3532 result = BindResourceTypeToResource(resource, resourceTypeName);
3534 #ifdef WITH_PRESENCE
3535 if(presenceResource.handle)
3537 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3538 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3545 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3546 const char *resourceInterfaceName)
3549 OCStackResult result = OC_STACK_ERROR;
3550 OCResource *resource = NULL;
3552 resource = findResource((OCResource *) handle);
3555 OIC_LOG(ERROR, TAG, "Resource not found");
3556 return OC_STACK_ERROR;
3559 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3561 #ifdef WITH_PRESENCE
3562 if (presenceResource.handle)
3564 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3565 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3572 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3574 OCResource *pointer = headResource;
3576 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3580 *numResources = *numResources + 1;
3581 pointer = pointer->next;
3586 OCResourceHandle OCGetResourceHandle(uint8_t index)
3588 OCResource *pointer = headResource;
3590 for( uint8_t i = 0; i < index && pointer; ++i)
3592 pointer = pointer->next;
3594 return (OCResourceHandle) pointer;
3597 OCStackResult OCDeleteResource(OCResourceHandle handle)
3601 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3602 return OC_STACK_INVALID_PARAM;
3605 OCResource *resource = findResource((OCResource *) handle);
3606 if (resource == NULL)
3608 OIC_LOG(ERROR, TAG, "Resource not found");
3609 return OC_STACK_NO_RESOURCE;
3612 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3614 OIC_LOG(ERROR, TAG, "Error deleting resource");
3615 return OC_STACK_ERROR;
3621 const char *OCGetResourceUri(OCResourceHandle handle)
3623 OCResource *resource = NULL;
3625 resource = findResource((OCResource *) handle);
3628 return resource->uri;
3630 return (const char *) NULL;
3633 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3635 OCResource *resource = NULL;
3637 resource = findResource((OCResource *) handle);
3640 return resource->resourceProperties;
3642 return (OCResourceProperty)-1;
3645 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3646 uint8_t *numResourceTypes)
3648 OCResource *resource = NULL;
3649 OCResourceType *pointer = NULL;
3651 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3652 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3654 *numResourceTypes = 0;
3656 resource = findResource((OCResource *) handle);
3659 pointer = resource->rsrcType;
3662 *numResourceTypes = *numResourceTypes + 1;
3663 pointer = pointer->next;
3669 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3671 OCResourceType *resourceType = NULL;
3673 resourceType = findResourceTypeAtIndex(handle, index);
3676 return resourceType->resourcetypename;
3678 return (const char *) NULL;
3681 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3682 uint8_t *numResourceInterfaces)
3684 OCResourceInterface *pointer = NULL;
3685 OCResource *resource = NULL;
3687 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3688 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3690 *numResourceInterfaces = 0;
3691 resource = findResource((OCResource *) handle);
3694 pointer = resource->rsrcInterface;
3697 *numResourceInterfaces = *numResourceInterfaces + 1;
3698 pointer = pointer->next;
3704 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3706 OCResourceInterface *resourceInterface = NULL;
3708 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3709 if (resourceInterface)
3711 return resourceInterface->name;
3713 return (const char *) NULL;
3716 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3719 OCResource *resource = NULL;
3720 OCChildResource *tempChildResource = NULL;
3723 resource = findResource((OCResource *) collectionHandle);
3729 tempChildResource = resource->rsrcChildResourcesHead;
3731 while(tempChildResource)
3735 return tempChildResource->rsrcResource;
3738 tempChildResource = tempChildResource->next;
3741 // In this case, the number of resource handles in the collection exceeds the index
3742 tempChildResource = NULL;
3746 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3747 OCEntityHandler entityHandler,
3748 void* callbackParam)
3750 OCResource *resource = NULL;
3752 // Validate parameters
3753 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3755 // Use the handle to find the resource in the resource linked list
3756 resource = findResource((OCResource *)handle);
3759 OIC_LOG(ERROR, TAG, "Resource not found");
3760 return OC_STACK_ERROR;
3764 resource->entityHandler = entityHandler;
3765 resource->entityHandlerCallbackParam = callbackParam;
3767 #ifdef WITH_PRESENCE
3768 if (presenceResource.handle)
3770 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3771 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3778 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3780 OCResource *resource = NULL;
3782 resource = findResource((OCResource *)handle);
3785 OIC_LOG(ERROR, TAG, "Resource not found");
3790 return resource->entityHandler;
3793 void incrementSequenceNumber(OCResource * resPtr)
3795 // Increment the sequence number
3796 resPtr->sequenceNum += 1;
3797 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3799 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3804 #ifdef WITH_PRESENCE
3805 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3806 OCPresenceTrigger trigger)
3808 OCResource *resPtr = NULL;
3809 OCStackResult result = OC_STACK_ERROR;
3810 OCMethod method = OC_REST_PRESENCE;
3811 uint32_t maxAge = 0;
3812 resPtr = findResource((OCResource *) presenceResource.handle);
3815 return OC_STACK_NO_RESOURCE;
3818 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3820 maxAge = presenceResource.presenceTTL;
3822 result = SendAllObserverNotification(method, resPtr, maxAge,
3823 trigger, resourceType, OC_LOW_QOS);
3829 OCStackResult SendStopNotification()
3831 OCResource *resPtr = NULL;
3832 OCStackResult result = OC_STACK_ERROR;
3833 OCMethod method = OC_REST_PRESENCE;
3834 resPtr = findResource((OCResource *) presenceResource.handle);
3837 return OC_STACK_NO_RESOURCE;
3840 // maxAge is 0. ResourceType is NULL.
3841 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3847 #endif // WITH_PRESENCE
3848 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3850 OCResource *resPtr = NULL;
3851 OCStackResult result = OC_STACK_ERROR;
3852 OCMethod method = OC_REST_NOMETHOD;
3853 uint32_t maxAge = 0;
3855 OIC_LOG(INFO, TAG, "Notifying all observers");
3856 #ifdef WITH_PRESENCE
3857 if(handle == presenceResource.handle)
3861 #endif // WITH_PRESENCE
3862 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3864 // Verify that the resource exists
3865 resPtr = findResource ((OCResource *) handle);
3868 return OC_STACK_NO_RESOURCE;
3872 //only increment in the case of regular observing (not presence)
3873 incrementSequenceNumber(resPtr);
3874 method = OC_REST_OBSERVE;
3875 maxAge = MAX_OBSERVE_AGE;
3876 #ifdef WITH_PRESENCE
3877 result = SendAllObserverNotification (method, resPtr, maxAge,
3878 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3880 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3887 OCNotifyListOfObservers (OCResourceHandle handle,
3888 OCObservationId *obsIdList,
3889 uint8_t numberOfIds,
3890 const OCRepPayload *payload,
3891 OCQualityOfService qos)
3893 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3895 OCResource *resPtr = NULL;
3896 //TODO: we should allow the server to define this
3897 uint32_t maxAge = MAX_OBSERVE_AGE;
3899 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3900 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3901 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3903 resPtr = findResource ((OCResource *) handle);
3904 if (NULL == resPtr || myStackMode == OC_CLIENT)
3906 return OC_STACK_NO_RESOURCE;
3910 incrementSequenceNumber(resPtr);
3912 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3913 payload, maxAge, qos));
3916 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3918 OCStackResult result = OC_STACK_ERROR;
3919 OCServerRequest *serverRequest = NULL;
3921 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3923 // Validate input parameters
3924 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3925 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3928 // Get pointer to request info
3929 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3932 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3933 result = serverRequest->ehResponseHandler(ehResponse);
3939 //#ifdef DIRECT_PAIRING
3940 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3942 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3943 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3945 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3949 return (const OCDPDev_t*)DPGetDiscoveredDevices();
3952 const OCDPDev_t* OCGetDirectPairedDevices()
3954 return (const OCDPDev_t*)DPGetPairedDevices();
3957 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3958 OCDirectPairingCB resultCallback)
3960 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3961 if(NULL == peer || NULL == pinNumber)
3963 OIC_LOG(ERROR, TAG, "Invalid parameters");
3964 return OC_STACK_INVALID_PARAM;
3966 if (NULL == resultCallback)
3968 OIC_LOG(ERROR, TAG, "Invalid callback");
3969 return OC_STACK_INVALID_CALLBACK;
3972 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3973 pinNumber, (OCDirectPairingResultCB)resultCallback);
3975 //#endif // DIRECT_PAIRING
3977 //-----------------------------------------------------------------------------
3978 // Private internal function definitions
3979 //-----------------------------------------------------------------------------
3980 static OCDoHandle GenerateInvocationHandle()
3982 OCDoHandle handle = NULL;
3983 // Generate token here, it will be deleted when the transaction is deleted
3984 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3987 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3993 #ifdef WITH_PRESENCE
3994 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3995 OCResourceProperty resourceProperties, uint8_t enable)
3999 return OC_STACK_INVALID_PARAM;
4001 if (resourceProperties
4002 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4004 OIC_LOG(ERROR, TAG, "Invalid property");
4005 return OC_STACK_INVALID_PARAM;
4009 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4013 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4019 OCStackResult initResources()
4021 OCStackResult result = OC_STACK_OK;
4023 headResource = NULL;
4024 tailResource = NULL;
4025 // Init Virtual Resources
4026 #ifdef WITH_PRESENCE
4027 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4029 result = OCCreateResource(&presenceResource.handle,
4030 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4032 OC_RSRVD_PRESENCE_URI,
4036 //make resource inactive
4037 result = OCChangeResourceProperty(
4038 &(((OCResource *) presenceResource.handle)->resourceProperties),
4041 #ifndef WITH_ARDUINO
4042 if (result == OC_STACK_OK)
4044 result = SRMInitSecureResources();
4048 if(result == OC_STACK_OK)
4050 result = OCCreateResource(&deviceResource,
4051 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4052 OC_RSRVD_INTERFACE_DEFAULT,
4053 OC_RSRVD_DEVICE_URI,
4057 if(result == OC_STACK_OK)
4059 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4060 OC_RSRVD_INTERFACE_READ);
4064 if(result == OC_STACK_OK)
4066 result = OCCreateResource(&platformResource,
4067 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4068 OC_RSRVD_INTERFACE_DEFAULT,
4069 OC_RSRVD_PLATFORM_URI,
4073 if(result == OC_STACK_OK)
4075 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4076 OC_RSRVD_INTERFACE_READ);
4083 void insertResource(OCResource *resource)
4087 headResource = resource;
4088 tailResource = resource;
4092 tailResource->next = resource;
4093 tailResource = resource;
4095 resource->next = NULL;
4098 OCResource *findResource(OCResource *resource)
4100 OCResource *pointer = headResource;
4104 if (pointer == resource)
4108 pointer = pointer->next;
4113 void deleteAllResources()
4115 OCResource *pointer = headResource;
4116 OCResource *temp = NULL;
4120 temp = pointer->next;
4121 #ifdef WITH_PRESENCE
4122 if (pointer != (OCResource *) presenceResource.handle)
4124 #endif // WITH_PRESENCE
4125 deleteResource(pointer);
4126 #ifdef WITH_PRESENCE
4128 #endif // WITH_PRESENCE
4131 memset(&platformResource, 0, sizeof(platformResource));
4132 memset(&deviceResource, 0, sizeof(deviceResource));
4134 SRMDeInitSecureResources();
4136 #ifdef WITH_PRESENCE
4137 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4138 // presence notification attributed to their deletion to be processed.
4139 deleteResource((OCResource *) presenceResource.handle);
4140 memset(&presenceResource, 0, sizeof(presenceResource));
4141 #endif // WITH_PRESENCE
4144 OCStackResult deleteResource(OCResource *resource)
4146 OCResource *prev = NULL;
4147 OCResource *temp = NULL;
4150 OIC_LOG(DEBUG,TAG,"resource is NULL");
4151 return OC_STACK_INVALID_PARAM;
4154 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4156 temp = headResource;
4159 if (temp == resource)
4161 // Invalidate all Resource Properties.
4162 resource->resourceProperties = (OCResourceProperty) 0;
4163 #ifdef WITH_PRESENCE
4164 if(resource != (OCResource *) presenceResource.handle)
4166 #endif // WITH_PRESENCE
4167 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4168 #ifdef WITH_PRESENCE
4171 if(presenceResource.handle)
4173 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4174 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4177 // Only resource in list.
4178 if (temp == headResource && temp == tailResource)
4180 headResource = NULL;
4181 tailResource = NULL;
4184 else if (temp == headResource)
4186 headResource = temp->next;
4189 else if (temp == tailResource)
4191 tailResource = prev;
4192 tailResource->next = NULL;
4196 prev->next = temp->next;
4199 deleteResourceElements(temp);
4210 return OC_STACK_ERROR;
4213 void deleteResourceElements(OCResource *resource)
4220 OICFree(resource->uri);
4221 deleteResourceType(resource->rsrcType);
4222 deleteResourceInterface(resource->rsrcInterface);
4225 void deleteResourceType(OCResourceType *resourceType)
4227 OCResourceType *pointer = resourceType;
4228 OCResourceType *next = NULL;
4232 next = pointer->next;
4233 OICFree(pointer->resourcetypename);
4239 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4241 OCResourceInterface *pointer = resourceInterface;
4242 OCResourceInterface *next = NULL;
4246 next = pointer->next;
4247 OICFree(pointer->name);
4253 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4255 OCResourceType *pointer = NULL;
4256 OCResourceType *previous = NULL;
4257 if (!resource || !resourceType)
4261 // resource type list is empty.
4262 else if (!resource->rsrcType)
4264 resource->rsrcType = resourceType;
4268 pointer = resource->rsrcType;
4272 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4274 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4275 OICFree(resourceType->resourcetypename);
4276 OICFree(resourceType);
4280 pointer = pointer->next;
4285 previous->next = resourceType;
4288 resourceType->next = NULL;
4290 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4293 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4295 OCResource *resource = NULL;
4296 OCResourceType *pointer = NULL;
4298 // Find the specified resource
4299 resource = findResource((OCResource *) handle);
4305 // Make sure a resource has a resourcetype
4306 if (!resource->rsrcType)
4311 // Iterate through the list
4312 pointer = resource->rsrcType;
4313 for(uint8_t i = 0; i< index && pointer; ++i)
4315 pointer = pointer->next;
4320 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4322 if(resourceTypeList && resourceTypeName)
4324 OCResourceType * rtPointer = resourceTypeList;
4325 while(resourceTypeName && rtPointer)
4327 if(rtPointer->resourcetypename &&
4328 strcmp(resourceTypeName, (const char *)
4329 (rtPointer->resourcetypename)) == 0)
4333 rtPointer = rtPointer->next;
4341 * Insert a new interface into interface linked list only if not already present.
4342 * If alredy present, 2nd arg is free'd.
4343 * Default interface will always be first if present.
4345 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4347 OCResourceInterface *pointer = NULL;
4348 OCResourceInterface *previous = NULL;
4350 newInterface->next = NULL;
4352 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4354 if (!*firstInterface)
4356 // If first interface is not oic.if.baseline, by default add it as first interface type.
4357 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4359 *firstInterface = newInterface;
4363 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4364 if (result != OC_STACK_OK)
4366 OICFree(newInterface->name);
4367 OICFree(newInterface);
4370 if (*firstInterface)
4372 (*firstInterface)->next = newInterface;
4376 // If once add oic.if.baseline, later too below code take care of freeing memory.
4377 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4379 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4381 OICFree(newInterface->name);
4382 OICFree(newInterface);
4385 // This code will not hit anymore, keeping
4388 newInterface->next = *firstInterface;
4389 *firstInterface = newInterface;
4394 pointer = *firstInterface;
4397 if (strcmp(newInterface->name, pointer->name) == 0)
4399 OICFree(newInterface->name);
4400 OICFree(newInterface);
4404 pointer = pointer->next;
4409 previous->next = newInterface;
4414 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4417 OCResource *resource = NULL;
4418 OCResourceInterface *pointer = NULL;
4420 // Find the specified resource
4421 resource = findResource((OCResource *) handle);
4427 // Make sure a resource has a resourceinterface
4428 if (!resource->rsrcInterface)
4433 // Iterate through the list
4434 pointer = resource->rsrcInterface;
4436 for (uint8_t i = 0; i < index && pointer; ++i)
4438 pointer = pointer->next;
4444 * This function splits the uri using the '?' delimiter.
4445 * "uriWithoutQuery" is the block of characters between the beginning
4446 * till the delimiter or '\0' which ever comes first.
4447 * "query" is whatever is to the right of the delimiter if present.
4448 * No delimiter sets the query to NULL.
4449 * If either are present, they will be malloc'ed into the params 2, 3.
4450 * The first param, *uri is left untouched.
4452 * NOTE: This function does not account for whitespace at the end of the uri NOR
4453 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4454 * part of the query.
4456 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4460 return OC_STACK_INVALID_URI;
4462 if(!query || !uriWithoutQuery)
4464 return OC_STACK_INVALID_PARAM;
4468 *uriWithoutQuery = NULL;
4470 size_t uriWithoutQueryLen = 0;
4471 size_t queryLen = 0;
4472 size_t uriLen = strlen(uri);
4474 char *pointerToDelimiter = strstr(uri, "?");
4476 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4477 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4479 if (uriWithoutQueryLen)
4481 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4482 if (!*uriWithoutQuery)
4486 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4490 *query = (char *) OICCalloc(queryLen + 1, 1);
4493 OICFree(*uriWithoutQuery);
4494 *uriWithoutQuery = NULL;
4497 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4503 return OC_STACK_NO_MEMORY;
4506 static const OicUuid_t* OCGetServerInstanceID(void)
4508 static bool generated = false;
4509 static OicUuid_t sid;
4515 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4517 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4524 const char* OCGetServerInstanceIDString(void)
4526 static bool generated = false;
4527 static char sidStr[UUID_STRING_SIZE];
4534 const OicUuid_t *sid = OCGetServerInstanceID();
4535 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4537 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4545 CAResult_t OCSelectNetwork()
4547 CAResult_t retResult = CA_STATUS_FAILED;
4548 CAResult_t caResult = CA_STATUS_OK;
4550 CATransportAdapter_t connTypes[] = {
4552 CA_ADAPTER_RFCOMM_BTEDR,
4553 CA_ADAPTER_GATT_BTLE,
4556 ,CA_ADAPTER_REMOTE_ACCESS
4563 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4565 for(int i = 0; i<numConnTypes; i++)
4567 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4568 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4570 caResult = CASelectNetwork(connTypes[i]);
4571 if(caResult == CA_STATUS_OK)
4573 retResult = CA_STATUS_OK;
4578 if(retResult != CA_STATUS_OK)
4580 return caResult; // Returns error of appropriate transport that failed fatally.
4586 OCStackResult CAResultToOCResult(CAResult_t caResult)
4592 case CA_STATUS_INVALID_PARAM:
4593 return OC_STACK_INVALID_PARAM;
4594 case CA_ADAPTER_NOT_ENABLED:
4595 return OC_STACK_ADAPTER_NOT_ENABLED;
4596 case CA_SERVER_STARTED_ALREADY:
4598 case CA_SERVER_NOT_STARTED:
4599 return OC_STACK_ERROR;
4600 case CA_DESTINATION_NOT_REACHABLE:
4601 return OC_STACK_COMM_ERROR;
4602 case CA_SOCKET_OPERATION_FAILED:
4603 return OC_STACK_COMM_ERROR;
4604 case CA_SEND_FAILED:
4605 return OC_STACK_COMM_ERROR;
4606 case CA_RECEIVE_FAILED:
4607 return OC_STACK_COMM_ERROR;
4608 case CA_MEMORY_ALLOC_FAILED:
4609 return OC_STACK_NO_MEMORY;
4610 case CA_REQUEST_TIMEOUT:
4611 return OC_STACK_TIMEOUT;
4612 case CA_DESTINATION_DISCONNECTED:
4613 return OC_STACK_COMM_ERROR;
4614 case CA_STATUS_FAILED:
4615 return OC_STACK_ERROR;
4616 case CA_NOT_SUPPORTED:
4617 return OC_STACK_NOTIMPL;
4619 return OC_STACK_ERROR;
4623 bool OCResultToSuccess(OCStackResult ocResult)
4628 case OC_STACK_RESOURCE_CREATED:
4629 case OC_STACK_RESOURCE_DELETED:
4630 case OC_STACK_CONTINUE:
4631 case OC_STACK_RESOURCE_CHANGED: