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"
80 #include "coap_time.h"
85 #include <arpa/inet.h>
89 #define UINT32_MAX (0xFFFFFFFFUL)
92 //-----------------------------------------------------------------------------
94 //-----------------------------------------------------------------------------
97 OC_STACK_UNINITIALIZED = 0,
99 OC_STACK_UNINIT_IN_PROGRESS
105 OC_PRESENCE_UNINITIALIZED = 0,
106 OC_PRESENCE_INITIALIZED
110 //-----------------------------------------------------------------------------
112 //-----------------------------------------------------------------------------
113 static OCStackState stackState = OC_STACK_UNINITIALIZED;
115 OCResource *headResource = NULL;
116 static OCResource *tailResource = NULL;
117 static OCResourceHandle platformResource = {0};
118 static OCResourceHandle deviceResource = {0};
120 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
121 static PresenceResource presenceResource;
122 static uint8_t PresenceTimeOutSize = 0;
123 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
126 static OCMode myStackMode;
128 //TODO: revisit this design
129 static bool gRASetInfo = false;
131 OCDeviceEntityHandler defaultDeviceHandler;
132 void* defaultDeviceHandlerCallbackParameter = NULL;
133 static const char COAP_TCP[] = "coap+tcp:";
134 static const char CORESPEC[] = "core";
136 //#ifdef DIRECT_PAIRING
137 OCDirectPairingCB gDirectpairingCallback = NULL;
140 //-----------------------------------------------------------------------------
142 //-----------------------------------------------------------------------------
143 #define TAG "OIC_RI_STACK"
144 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
145 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
146 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
147 TAG, #arg " is NULL"); return (retVal); } }
148 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
149 TAG, #arg " is NULL"); return; } }
150 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
153 //TODO: we should allow the server to define this
154 #define MAX_OBSERVE_AGE (0x2FFFFUL)
156 #define MILLISECONDS_PER_SECOND (1000)
158 //-----------------------------------------------------------------------------
159 // Private internal function prototypes
160 //-----------------------------------------------------------------------------
163 * Generate handle of OCDoResource invocation for callback management.
165 * @return Generated OCDoResource handle.
167 static OCDoHandle GenerateInvocationHandle();
170 * Initialize resource data structures, variables, etc.
172 * @return ::OC_STACK_OK on success, some other value upon failure.
174 static OCStackResult initResources();
177 * Add a resource to the end of the linked list of resources.
179 * @param resource Resource to be added
181 static void insertResource(OCResource *resource);
184 * Find a resource in the linked list of resources.
186 * @param resource Resource to be found.
187 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
190 static OCResource *findResource(OCResource *resource);
193 * Insert a resource type into a resource's resource type linked list.
194 * If resource type already exists, it will not be inserted and the
195 * resourceType will be free'd.
196 * resourceType->next should be null to avoid memory leaks.
197 * Function returns silently for null args.
199 * @param resource Resource where resource type is to be inserted.
200 * @param resourceType Resource type to be inserted.
202 static void insertResourceType(OCResource *resource,
203 OCResourceType *resourceType);
206 * Get a resource type at the specified index within a resource.
208 * @param handle Handle of resource.
209 * @param index Index of resource type.
211 * @return Pointer to resource type if found, NULL otherwise.
213 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
217 * Insert a resource interface into a resource's resource interface linked list.
218 * If resource interface already exists, it will not be inserted and the
219 * resourceInterface will be free'd.
220 * resourceInterface->next should be null to avoid memory leaks.
222 * @param resource Resource where resource interface is to be inserted.
223 * @param resourceInterface Resource interface to be inserted.
225 static void insertResourceInterface(OCResource *resource,
226 OCResourceInterface *resourceInterface);
229 * Get a resource interface at the specified index within a resource.
231 * @param handle Handle of resource.
232 * @param index Index of resource interface.
234 * @return Pointer to resource interface if found, NULL otherwise.
236 static OCResourceInterface *findResourceInterfaceAtIndex(
237 OCResourceHandle handle, uint8_t index);
240 * Delete all of the dynamically allocated elements that were created for the resource type.
242 * @param resourceType Specified resource type.
244 static void deleteResourceType(OCResourceType *resourceType);
247 * Delete all of the dynamically allocated elements that were created for the resource interface.
249 * @param resourceInterface Specified resource interface.
251 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
254 * Delete all of the dynamically allocated elements that were created for the resource.
256 * @param resource Specified resource.
258 static void deleteResourceElements(OCResource *resource);
261 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
264 * @param handle Handle of resource to be deleted.
266 * @return ::OC_STACK_OK on success, some other value upon failure.
268 static OCStackResult deleteResource(OCResource *resource);
271 * Delete all of the resources in the resource list.
273 static void deleteAllResources();
276 * Increment resource sequence number. Handles rollover.
278 * @param resPtr Pointer to resource.
280 static void incrementSequenceNumber(OCResource * resPtr);
283 * Verify the lengths of the URI and the query separately.
285 * @param inputUri Input URI and query.
286 * @param uriLen The length of the initial URI with query.
287 * @return ::OC_STACK_OK on success, some other value upon failure.
289 static OCStackResult verifyUriQueryLength(const char * inputUri,
293 * Attempts to initialize every network interface that the CA Layer might have compiled in.
295 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
296 * return something other than @ref CA_STATUS_OK, then this function fails.
298 * @return ::CA_STATUS_OK on success, some other value upon failure.
300 static CAResult_t OCSelectNetwork();
303 * Get the CoAP ticks after the specified number of milli-seconds.
305 * @param afterMilliSeconds Milli-seconds.
309 static uint32_t GetTicks(uint32_t afterMilliSeconds);
312 * Convert CAResponseResult_t to OCStackResult.
314 * @param caCode CAResponseResult_t code.
315 * @return ::OC_STACK_OK on success, some other value upon failure.
317 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
320 * Convert OCStackResult to CAResponseResult_t.
322 * @param caCode OCStackResult code.
323 * @param method OCMethod method the return code replies to.
324 * @return ::CA_CONTENT on OK, some other value upon failure.
326 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
329 * Convert OCTransportFlags_t to CATransportModifiers_t.
331 * @param ocConType OCTransportFlags_t input.
332 * @return CATransportFlags
334 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
337 * Convert CATransportFlags_t to OCTransportModifiers_t.
339 * @param caConType CATransportFlags_t input.
340 * @return OCTransportFlags
342 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
345 * Handle response from presence request.
347 * @param endPoint CA remote endpoint.
348 * @param responseInfo CA response info.
349 * @return ::OC_STACK_OK on success, some other value upon failure.
351 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
352 const CAResponseInfo_t *responseInfo);
355 * This function will be called back by CA layer when a response is received.
357 * @param endPoint CA remote endpoint.
358 * @param responseInfo CA response info.
360 static void HandleCAResponses(const CAEndpoint_t* endPoint,
361 const CAResponseInfo_t* responseInfo);
364 * This function will be called back by CA layer when a request is received.
366 * @param endPoint CA remote endpoint.
367 * @param requestInfo CA request info.
369 static void HandleCARequests(const CAEndpoint_t* endPoint,
370 const CARequestInfo_t* requestInfo);
373 * Extract query from a URI.
375 * @param uri Full URI with query.
376 * @param query Pointer to string that will contain query.
377 * @param newURI Pointer to string that will contain URI.
378 * @return ::OC_STACK_OK on success, some other value upon failure.
380 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
383 * Finds a resource type in an OCResourceType link-list.
385 * @param resourceTypeList The link-list to be searched through.
386 * @param resourceTypeName The key to search for.
388 * @return Resource type that matches the key (ie. resourceTypeName) or
389 * NULL if there is either an invalid parameter or this function was unable to find the key.
391 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
392 const char * resourceTypeName);
395 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
396 * TTL will be set to maxAge.
398 * @param cbNode Callback Node for which presence ttl is to be reset.
399 * @param maxAge New value of ttl in seconds.
401 * @return ::OC_STACK_OK on success, some other value upon failure.
403 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
406 * Ensure the accept header option is set appropriatly before sending the requests and routing
407 * header option is updated with destination.
409 * @param object CA remote endpoint.
410 * @param requestInfo CA request info.
412 * @return ::OC_STACK_OK on success, some other value upon failure.
414 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
416 //-----------------------------------------------------------------------------
417 // Internal functions
418 //-----------------------------------------------------------------------------
420 uint32_t GetTicks(uint32_t afterMilliSeconds)
425 // Guard against overflow of uint32_t
426 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
427 COAP_TICKS_PER_SECOND)
429 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
437 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
439 VERIFY_NON_NULL_NR(in, FATAL);
440 VERIFY_NON_NULL_NR(out, FATAL);
442 out->adapter = (OCTransportAdapter)in->adapter;
443 out->flags = CAToOCTransportFlags(in->flags);
444 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
445 out->port = in->port;
446 out->interface = in->interface;
447 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
448 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
452 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
454 VERIFY_NON_NULL_NR(in, FATAL);
455 VERIFY_NON_NULL_NR(out, FATAL);
457 out->adapter = (CATransportAdapter_t)in->adapter;
458 out->flags = OCToCATransportFlags(in->flags);
459 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
460 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
461 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
463 out->port = in->port;
464 out->interface = in->interface;
467 void FixUpClientResponse(OCClientResponse *cr)
469 VERIFY_NON_NULL_NR(cr, FATAL);
471 cr->addr = &cr->devAddr;
472 cr->connType = (OCConnectivityType)
473 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
476 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
478 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
479 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
481 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
482 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
483 if (OC_STACK_OK != rmResult)
485 OIC_LOG(ERROR, TAG, "Add destination option failed");
490 // OC stack prefer CBOR encoded payloads.
491 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
492 CAResult_t result = CASendRequest(object, requestInfo);
493 if(CA_STATUS_OK != result)
495 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
496 return CAResultToOCResult(result);
500 //-----------------------------------------------------------------------------
501 // Internal API function
502 //-----------------------------------------------------------------------------
504 // This internal function is called to update the stack with the status of
505 // observers and communication failures
506 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
508 OCStackResult result = OC_STACK_ERROR;
509 ResourceObserver * observer = NULL;
510 OCEntityHandlerRequest ehRequest = {0};
514 case OC_OBSERVER_NOT_INTERESTED:
515 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
516 observer = GetObserverUsingToken (token, tokenLength);
519 result = FormOCEntityHandlerRequest(&ehRequest,
520 (OCRequestHandle)NULL,
523 (OCResourceHandle)NULL,
524 NULL, PAYLOAD_TYPE_REPRESENTATION,
526 OC_OBSERVE_DEREGISTER,
527 observer->observeId);
528 if(result != OC_STACK_OK)
532 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
533 observer->resource->entityHandlerCallbackParam);
536 result = DeleteObserverUsingToken (token, tokenLength);
537 if(result == OC_STACK_OK)
539 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
543 result = OC_STACK_OK;
544 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
548 case OC_OBSERVER_STILL_INTERESTED:
549 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
550 observer = GetObserverUsingToken (token, tokenLength);
553 observer->forceHighQos = 0;
554 observer->failedCommCount = 0;
555 result = OC_STACK_OK;
559 result = OC_STACK_OBSERVER_NOT_FOUND;
563 case OC_OBSERVER_FAILED_COMM:
564 OIC_LOG(DEBUG, TAG, "observer is unreachable");
565 observer = GetObserverUsingToken (token, tokenLength);
568 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
570 result = FormOCEntityHandlerRequest(&ehRequest,
571 (OCRequestHandle)NULL,
574 (OCResourceHandle)NULL,
575 NULL, PAYLOAD_TYPE_REPRESENTATION,
577 OC_OBSERVE_DEREGISTER,
578 observer->observeId);
579 if(result != OC_STACK_OK)
581 return OC_STACK_ERROR;
583 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
584 observer->resource->entityHandlerCallbackParam);
586 result = DeleteObserverUsingToken (token, tokenLength);
587 if(result == OC_STACK_OK)
589 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
593 result = OC_STACK_OK;
594 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
599 observer->failedCommCount++;
600 result = OC_STACK_CONTINUE;
602 observer->forceHighQos = 1;
603 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
607 OIC_LOG(ERROR, TAG, "Unknown status");
608 result = OC_STACK_ERROR;
613 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
615 OCStackResult ret = OC_STACK_ERROR;
620 ret = OC_STACK_RESOURCE_CREATED;
623 ret = OC_STACK_RESOURCE_DELETED;
631 ret = OC_STACK_INVALID_QUERY;
633 case CA_UNAUTHORIZED_REQ:
634 ret = OC_STACK_UNAUTHORIZED_REQ;
637 ret = OC_STACK_INVALID_OPTION;
640 ret = OC_STACK_NO_RESOURCE;
642 case CA_RETRANSMIT_TIMEOUT:
643 ret = OC_STACK_COMM_ERROR;
651 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
653 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
662 // This Response Code is like HTTP 204 "No Content" but only used in
663 // response to POST and PUT requests.
667 // This Response Code is like HTTP 200 "OK" but only used in response to
672 // This should not happen but,
673 // give it a value just in case but output an error
675 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
678 case OC_STACK_RESOURCE_CREATED:
681 case OC_STACK_RESOURCE_DELETED:
684 case OC_STACK_INVALID_QUERY:
687 case OC_STACK_INVALID_OPTION:
690 case OC_STACK_NO_RESOURCE:
693 case OC_STACK_COMM_ERROR:
694 ret = CA_RETRANSMIT_TIMEOUT;
696 case OC_STACK_UNAUTHORIZED_REQ:
697 ret = CA_UNAUTHORIZED_REQ;
705 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
707 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
709 // supply default behavior.
710 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
712 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
714 if ((caFlags & OC_MASK_SCOPE) == 0)
716 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
721 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
723 return (OCTransportFlags)caFlags;
726 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
728 uint32_t lowerBound = 0;
729 uint32_t higherBound = 0;
731 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
733 return OC_STACK_INVALID_PARAM;
736 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
738 cbNode->presence->TTL = maxAgeSeconds;
740 for (int index = 0; index < PresenceTimeOutSize; index++)
742 // Guard against overflow
743 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
746 lowerBound = GetTicks((PresenceTimeOut[index] *
747 cbNode->presence->TTL *
748 MILLISECONDS_PER_SECOND)/100);
752 lowerBound = GetTicks(UINT32_MAX);
755 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
758 higherBound = GetTicks((PresenceTimeOut[index + 1] *
759 cbNode->presence->TTL *
760 MILLISECONDS_PER_SECOND)/100);
764 higherBound = GetTicks(UINT32_MAX);
767 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
769 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
770 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
771 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
774 cbNode->presence->TTLlevel = 0;
776 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
780 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
782 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
784 return OC_RSRVD_TRIGGER_CREATE;
786 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
788 return OC_RSRVD_TRIGGER_CHANGE;
792 return OC_RSRVD_TRIGGER_DELETE;
796 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
800 return OC_PRESENCE_TRIGGER_CREATE;
802 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
804 return OC_PRESENCE_TRIGGER_CREATE;
806 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
808 return OC_PRESENCE_TRIGGER_CHANGE;
812 return OC_PRESENCE_TRIGGER_DELETE;
817 * The cononical presence allows constructed URIs to be string compared.
819 * requestUri must be a char array of size CA_MAX_URI_LENGTH
821 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
824 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
825 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
826 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
828 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
830 if (ep->adapter == CA_ADAPTER_IP)
832 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
834 if ('\0' == ep->addr[0]) // multicast
836 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
840 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
841 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
846 if ('\0' == ep->addr[0]) // multicast
848 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
849 ep->port = OC_MULTICAST_PORT;
851 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
852 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
856 // might work for other adapters (untested, but better than nothing)
857 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
858 OC_RSRVD_PRESENCE_URI);
862 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
863 const CAResponseInfo_t *responseInfo)
865 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
866 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
868 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
869 ClientCB * cbNode = NULL;
870 char *resourceTypeName = NULL;
871 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
872 OCStackResult result = OC_STACK_ERROR;
875 char presenceUri[CA_MAX_URI_LENGTH];
877 int presenceSubscribe = 0;
878 int multicastPresenceSubscribe = 0;
880 if (responseInfo->result != CA_CONTENT)
882 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
883 return OC_STACK_ERROR;
886 // check for unicast presence
887 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
888 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
890 return OC_STACK_INVALID_URI;
893 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
896 presenceSubscribe = 1;
900 // check for multiicast presence
901 CAEndpoint_t ep = { .adapter = endpoint->adapter,
902 .flags = endpoint->flags };
904 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
906 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
909 multicastPresenceSubscribe = 1;
913 if (!presenceSubscribe && !multicastPresenceSubscribe)
915 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
919 response.payload = NULL;
920 response.result = OC_STACK_OK;
922 CopyEndpointToDevAddr(endpoint, &response.devAddr);
923 FixUpClientResponse(&response);
925 if (responseInfo->info.payload)
927 result = OCParsePayload(&response.payload,
928 PAYLOAD_TYPE_PRESENCE,
929 responseInfo->info.payload,
930 responseInfo->info.payloadSize);
932 if(result != OC_STACK_OK)
934 OIC_LOG(ERROR, TAG, "Presence parse failed");
937 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
939 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
940 result = OC_STACK_ERROR;
943 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
944 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
945 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
948 if (presenceSubscribe)
950 if(cbNode->sequenceNumber == response.sequenceNumber)
952 OIC_LOG(INFO, TAG, "No presence change");
953 ResetPresenceTTL(cbNode, maxAge);
954 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
960 OIC_LOG(INFO, TAG, "Stopping presence");
961 response.result = OC_STACK_PRESENCE_STOPPED;
964 OICFree(cbNode->presence->timeOut);
965 OICFree(cbNode->presence);
966 cbNode->presence = NULL;
971 if(!cbNode->presence)
973 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
975 if(!(cbNode->presence))
977 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
978 result = OC_STACK_NO_MEMORY;
982 VERIFY_NON_NULL_V(cbNode->presence);
983 cbNode->presence->timeOut = NULL;
984 cbNode->presence->timeOut = (uint32_t *)
985 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
986 if(!(cbNode->presence->timeOut)){
988 "Could not allocate memory for cbNode->presence->timeOut");
989 OICFree(cbNode->presence);
990 result = OC_STACK_NO_MEMORY;
995 ResetPresenceTTL(cbNode, maxAge);
997 cbNode->sequenceNumber = response.sequenceNumber;
999 // Ensure that a filter is actually applied.
1000 if( resourceTypeName && cbNode->filterResourceType)
1002 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1011 // This is the multicast case
1012 OCMulticastNode* mcNode = NULL;
1013 mcNode = GetMCPresenceNode(presenceUri);
1017 if(mcNode->nonce == response.sequenceNumber)
1019 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1022 mcNode->nonce = response.sequenceNumber;
1026 OIC_LOG(INFO, TAG, "Stopping presence");
1027 response.result = OC_STACK_PRESENCE_STOPPED;
1032 char* uri = OICStrdup(presenceUri);
1036 "No Memory for URI to store in the presence node");
1037 result = OC_STACK_NO_MEMORY;
1041 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1042 if(result == OC_STACK_NO_MEMORY)
1045 "No Memory for Multicast Presence Node");
1049 // presence node now owns uri
1052 // Ensure that a filter is actually applied.
1053 if(resourceTypeName && cbNode->filterResourceType)
1055 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1062 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1064 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1066 FindAndDeleteClientCB(cbNode);
1070 OCPayloadDestroy(response.payload);
1074 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1076 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1078 if(responseInfo->info.resourceUri &&
1079 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1081 HandlePresenceResponse(endPoint, responseInfo);
1085 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1086 responseInfo->info.tokenLength, NULL, NULL);
1088 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1089 responseInfo->info.tokenLength);
1093 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1094 if(responseInfo->result == CA_EMPTY)
1096 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1097 // We do not have a case for the client to receive a RESET
1098 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1100 //This is the case of receiving an ACK on a request to a slow resource!
1101 OIC_LOG(INFO, TAG, "This is a pure ACK");
1102 //TODO: should we inform the client
1103 // app that at least the request was received at the server?
1106 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1108 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1109 OIC_LOG(INFO, TAG, "Calling into application address space");
1111 OCClientResponse response =
1112 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1113 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1114 FixUpClientResponse(&response);
1115 response.resourceUri = responseInfo->info.resourceUri;
1116 memcpy(response.identity.id, responseInfo->info.identity.id,
1117 sizeof (response.identity.id));
1118 response.identity.id_length = responseInfo->info.identity.id_length;
1120 response.result = CAToOCStackResult(responseInfo->result);
1121 cbNode->callBack(cbNode->context,
1122 cbNode->handle, &response);
1123 FindAndDeleteClientCB(cbNode);
1127 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1128 OIC_LOG(INFO, TAG, "Calling into application address space");
1130 OCClientResponse response =
1131 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1132 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1133 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1134 FixUpClientResponse(&response);
1135 response.resourceUri = responseInfo->info.resourceUri;
1136 memcpy(response.identity.id, responseInfo->info.identity.id,
1137 sizeof (response.identity.id));
1138 response.identity.id_length = responseInfo->info.identity.id_length;
1140 response.result = CAToOCStackResult(responseInfo->result);
1142 if(responseInfo->info.payload &&
1143 responseInfo->info.payloadSize)
1145 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1146 // check the security resource
1147 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1149 type = PAYLOAD_TYPE_SECURITY;
1151 else if (cbNode->method == OC_REST_DISCOVER)
1153 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1154 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1156 type = PAYLOAD_TYPE_DISCOVERY;
1158 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1160 type = PAYLOAD_TYPE_DEVICE;
1162 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1164 type = PAYLOAD_TYPE_PLATFORM;
1166 #ifdef ROUTING_GATEWAY
1167 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1169 type = PAYLOAD_TYPE_REPRESENTATION;
1172 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1174 type = PAYLOAD_TYPE_RD;
1177 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1179 type = PAYLOAD_TYPE_REPRESENTATION;
1184 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1185 cbNode->method, cbNode->requestUri);
1189 else if (cbNode->method == OC_REST_GET ||
1190 cbNode->method == OC_REST_PUT ||
1191 cbNode->method == OC_REST_POST ||
1192 cbNode->method == OC_REST_OBSERVE ||
1193 cbNode->method == OC_REST_OBSERVE_ALL ||
1194 cbNode->method == OC_REST_DELETE)
1196 char targetUri[MAX_URI_LENGTH];
1197 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1198 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1199 if (strcmp(targetUri, cbNode->requestUri) == 0)
1201 type = PAYLOAD_TYPE_RD;
1203 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1205 type = PAYLOAD_TYPE_PLATFORM;
1207 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1209 type = PAYLOAD_TYPE_DEVICE;
1211 if (type == PAYLOAD_TYPE_INVALID)
1213 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1214 cbNode->method, cbNode->requestUri);
1215 type = PAYLOAD_TYPE_REPRESENTATION;
1220 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1221 cbNode->method, cbNode->requestUri);
1225 if(OC_STACK_OK != OCParsePayload(&response.payload,
1227 responseInfo->info.payload,
1228 responseInfo->info.payloadSize))
1230 OIC_LOG(ERROR, TAG, "Error converting payload");
1231 OCPayloadDestroy(response.payload);
1236 response.numRcvdVendorSpecificHeaderOptions = 0;
1237 if(responseInfo->info.numOptions > 0)
1240 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1241 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1244 uint32_t observationOption;
1245 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1246 for (observationOption=0, i=0;
1247 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1251 (observationOption << 8) | optionData[i];
1253 response.sequenceNumber = observationOption;
1255 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1260 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1263 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1265 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1266 OCPayloadDestroy(response.payload);
1270 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1272 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1273 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1277 if (cbNode->method == OC_REST_OBSERVE &&
1278 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1279 response.sequenceNumber <= cbNode->sequenceNumber)
1281 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1282 response.sequenceNumber);
1286 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1289 cbNode->sequenceNumber = response.sequenceNumber;
1291 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1293 FindAndDeleteClientCB(cbNode);
1297 // To keep discovery callbacks active.
1298 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1299 MILLISECONDS_PER_SECOND);
1303 //Need to send ACK when the response is CON
1304 if(responseInfo->info.type == CA_MSG_CONFIRM)
1306 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1307 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1310 OCPayloadDestroy(response.payload);
1317 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1318 if(responseInfo->result == CA_EMPTY)
1320 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1321 if(responseInfo->info.type == CA_MSG_RESET)
1323 OIC_LOG(INFO, TAG, "This is a RESET");
1324 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1325 OC_OBSERVER_NOT_INTERESTED);
1327 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1329 OIC_LOG(INFO, TAG, "This is a pure ACK");
1330 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1331 OC_OBSERVER_STILL_INTERESTED);
1334 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1336 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1337 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1338 OC_OBSERVER_FAILED_COMM);
1343 if(!cbNode && !observer)
1345 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1346 || myStackMode == OC_GATEWAY)
1348 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1349 if(responseInfo->result == CA_EMPTY)
1351 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1355 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1356 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1357 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1361 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1362 || myStackMode == OC_GATEWAY)
1364 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1365 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1367 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1368 responseInfo->info.messageId);
1370 if (responseInfo->info.type == CA_MSG_RESET)
1372 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1373 responseInfo->info.messageId);
1380 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1383 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1385 VERIFY_NON_NULL_NR(endPoint, FATAL);
1386 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1388 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1390 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1391 #ifdef ROUTING_GATEWAY
1392 bool needRIHandling = false;
1394 * Routing manager is going to update either of endpoint or response or both.
1395 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1396 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1399 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1401 if(ret != OC_STACK_OK || !needRIHandling)
1403 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1409 * Put source in sender endpoint so that the next packet from application can be routed to
1410 * proper destination and remove "RM" coap header option before passing request / response to
1411 * RI as this option will make no sense to either RI or application.
1413 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1414 (uint8_t *) &(responseInfo->info.numOptions),
1415 (CAEndpoint_t *) endPoint);
1418 OCHandleResponse(endPoint, responseInfo);
1420 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1424 * This function handles error response from CA
1425 * code shall be added to handle the errors
1427 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1429 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1431 if(NULL == endPoint)
1433 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1437 if(NULL == errrorInfo)
1439 OIC_LOG(ERROR, TAG, "errrorInfo is NULL");
1442 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1446 * This function sends out Direct Stack Responses. These are responses that are not coming
1447 * from the application entity handler. These responses have no payload and are usually ACKs,
1448 * RESETs or some error conditions that were caught by the stack.
1450 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1451 const CAResponseResult_t responseResult, const CAMessageType_t type,
1452 const uint8_t numOptions, const CAHeaderOption_t *options,
1453 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1455 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1456 CAResponseInfo_t respInfo = {
1457 .result = responseResult
1459 respInfo.info.messageId = coapID;
1460 respInfo.info.numOptions = numOptions;
1462 if (respInfo.info.numOptions)
1464 respInfo.info.options =
1465 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1466 memcpy (respInfo.info.options, options,
1467 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1471 respInfo.info.payload = NULL;
1472 respInfo.info.token = token;
1473 respInfo.info.tokenLength = tokenLength;
1474 respInfo.info.type = type;
1475 respInfo.info.resourceUri = OICStrdup (resourceUri);
1476 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1478 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1479 // Add the destination to route option from the endpoint->routeData.
1480 bool doPost = false;
1481 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1482 if(OC_STACK_OK != result)
1484 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1489 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1490 CARequestInfo_t reqInfo = {.method = CA_POST };
1491 /* The following initialization is not done in a single initializer block as in
1492 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1493 * does not have designated initalizers. This is a work-around for now.
1495 reqInfo.info.type = CA_MSG_NONCONFIRM;
1496 reqInfo.info.messageId = coapID;
1497 reqInfo.info.tokenLength = tokenLength;
1498 reqInfo.info.token = token;
1499 reqInfo.info.numOptions = respInfo.info.numOptions;
1500 reqInfo.info.payload = NULL;
1501 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1502 if (reqInfo.info.numOptions)
1504 reqInfo.info.options =
1505 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1506 if (NULL == reqInfo.info.options)
1508 OIC_LOG(ERROR, TAG, "Calloc failed");
1509 return OC_STACK_NO_MEMORY;
1511 memcpy (reqInfo.info.options, respInfo.info.options,
1512 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1515 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1516 OICFree (reqInfo.info.resourceUri);
1517 OICFree (reqInfo.info.options);
1518 OICFree (respInfo.info.resourceUri);
1519 OICFree (respInfo.info.options);
1520 if (CA_STATUS_OK != caResult)
1522 OIC_LOG(ERROR, TAG, "CASendRequest error");
1523 return CAResultToOCResult(caResult);
1529 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1531 // resourceUri in the info field is cloned in the CA layer and
1532 // thus ownership is still here.
1533 OICFree (respInfo.info.resourceUri);
1534 OICFree (respInfo.info.options);
1535 if(CA_STATUS_OK != caResult)
1537 OIC_LOG(ERROR, TAG, "CASendResponse error");
1538 return CAResultToOCResult(caResult);
1541 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1545 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1547 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1548 OCStackResult result = OC_STACK_ERROR;
1549 if(!protocolRequest)
1551 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1552 return OC_STACK_INVALID_PARAM;
1555 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1556 protocolRequest->tokenLength);
1559 OIC_LOG(INFO, TAG, "This is a new Server Request");
1560 result = AddServerRequest(&request, protocolRequest->coapID,
1561 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1562 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1563 protocolRequest->observationOption, protocolRequest->qos,
1564 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1565 protocolRequest->payload, protocolRequest->requestToken,
1566 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1567 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1568 &protocolRequest->devAddr);
1569 if (OC_STACK_OK != result)
1571 OIC_LOG(ERROR, TAG, "Error adding server request");
1577 OIC_LOG(ERROR, TAG, "Out of Memory");
1578 return OC_STACK_NO_MEMORY;
1581 if(!protocolRequest->reqMorePacket)
1583 request->requestComplete = 1;
1588 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1591 if(request->requestComplete)
1593 OIC_LOG(INFO, TAG, "This Server Request is complete");
1594 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1595 OCResource *resource = NULL;
1596 result = DetermineResourceHandling (request, &resHandling, &resource);
1597 if (result == OC_STACK_OK)
1599 result = ProcessRequest(resHandling, resource, request);
1604 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1605 result = OC_STACK_CONTINUE;
1610 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1612 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1615 if (requestInfo->info.resourceUri &&
1616 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1618 HandleKeepAliveRequest(endPoint, requestInfo);
1623 OCStackResult requestResult = OC_STACK_ERROR;
1625 if(myStackMode == OC_CLIENT)
1627 //TODO: should the client be responding to requests?
1631 OCServerProtocolRequest serverRequest = {0};
1633 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1635 char * uriWithoutQuery = NULL;
1636 char * query = NULL;
1638 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1640 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1642 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1645 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1646 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1648 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1650 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1651 OICFree(uriWithoutQuery);
1655 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1656 OICFree(uriWithoutQuery);
1663 if(strlen(query) < MAX_QUERY_LENGTH)
1665 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1670 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1676 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1678 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1679 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1680 if (!serverRequest.payload)
1682 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1685 memcpy (serverRequest.payload, requestInfo->info.payload,
1686 requestInfo->info.payloadSize);
1690 serverRequest.reqTotalSize = 0;
1693 switch (requestInfo->method)
1696 serverRequest.method = OC_REST_GET;
1699 serverRequest.method = OC_REST_PUT;
1702 serverRequest.method = OC_REST_POST;
1705 serverRequest.method = OC_REST_DELETE;
1708 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1709 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1710 requestInfo->info.type, requestInfo->info.numOptions,
1711 requestInfo->info.options, requestInfo->info.token,
1712 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1713 OICFree(serverRequest.payload);
1717 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1718 requestInfo->info.tokenLength);
1720 serverRequest.tokenLength = requestInfo->info.tokenLength;
1721 if (serverRequest.tokenLength) {
1723 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1725 if (!serverRequest.requestToken)
1727 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1728 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1729 requestInfo->info.type, requestInfo->info.numOptions,
1730 requestInfo->info.options, requestInfo->info.token,
1731 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1732 OICFree(serverRequest.payload);
1735 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1738 switch (requestInfo->info.acceptFormat)
1740 case CA_FORMAT_APPLICATION_CBOR:
1741 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1743 case CA_FORMAT_UNDEFINED:
1744 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1747 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1750 if (requestInfo->info.type == CA_MSG_CONFIRM)
1752 serverRequest.qos = OC_HIGH_QOS;
1756 serverRequest.qos = OC_LOW_QOS;
1758 // CA does not need the following field
1759 // Are we sure CA does not need them? how is it responding to multicast
1760 serverRequest.delayedResNeeded = 0;
1762 serverRequest.coapID = requestInfo->info.messageId;
1764 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1766 // copy vendor specific header options
1767 uint8_t tempNum = (requestInfo->info.numOptions);
1769 // Assume no observation requested and it is a pure GET.
1770 // If obs registration/de-registration requested it'll be fetched from the
1771 // options in GetObserveHeaderOption()
1772 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1774 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1775 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1778 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1779 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1780 requestInfo->info.type, requestInfo->info.numOptions,
1781 requestInfo->info.options, requestInfo->info.token,
1782 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1783 OICFree(serverRequest.payload);
1784 OICFree(serverRequest.requestToken);
1787 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1788 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1790 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1791 sizeof(CAHeaderOption_t)*tempNum);
1794 requestResult = HandleStackRequests (&serverRequest);
1796 // Send ACK to client as precursor to slow response
1797 if (requestResult == OC_STACK_SLOW_RESOURCE)
1799 if (requestInfo->info.type == CA_MSG_CONFIRM)
1801 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1802 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1805 else if(requestResult != OC_STACK_OK)
1807 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1809 CAResponseResult_t stackResponse =
1810 OCToCAStackResult(requestResult, serverRequest.method);
1812 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1813 requestInfo->info.type, requestInfo->info.numOptions,
1814 requestInfo->info.options, requestInfo->info.token,
1815 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1817 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1818 // The token is copied in there, and is thus still owned by this function.
1819 OICFree(serverRequest.payload);
1820 OICFree(serverRequest.requestToken);
1821 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1824 //This function will be called back by CA layer when a request is received
1825 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1827 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1830 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1836 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1840 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1841 #ifdef ROUTING_GATEWAY
1842 bool needRIHandling = false;
1843 bool isEmptyMsg = false;
1845 * Routing manager is going to update either of endpoint or request or both.
1846 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1847 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1848 * destination. It can also remove "RM" coap header option before passing request / response to
1849 * RI as this option will make no sense to either RI or application.
1851 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1852 &needRIHandling, &isEmptyMsg);
1853 if(OC_STACK_OK != ret || !needRIHandling)
1855 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1861 * Put source in sender endpoint so that the next packet from application can be routed to
1862 * proper destination and remove RM header option.
1864 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1865 (uint8_t *) &(requestInfo->info.numOptions),
1866 (CAEndpoint_t *) endPoint);
1868 #ifdef ROUTING_GATEWAY
1872 * In Gateways, the MSGType in route option is used to check if the actual
1873 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
1874 * EMPTY response is sent in the form of POST request which need to be changed
1875 * to a EMPTY response by RM. This translation is done in this part of the code.
1877 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1878 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1879 .info.messageId = requestInfo->info.messageId,
1880 .info.type = CA_MSG_ACKNOWLEDGE};
1881 OCHandleResponse(endPoint, &respInfo);
1887 // Normal handling of the packet
1888 OCHandleRequests(endPoint, requestInfo);
1890 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1893 bool validatePlatformInfo(OCPlatformInfo info)
1896 if (!info.platformID)
1898 OIC_LOG(ERROR, TAG, "No platform ID found.");
1902 if (info.manufacturerName)
1904 size_t lenManufacturerName = strlen(info.manufacturerName);
1906 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1908 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1914 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1918 if (info.manufacturerUrl)
1920 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1922 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1929 //-----------------------------------------------------------------------------
1931 //-----------------------------------------------------------------------------
1933 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1936 !raInfo->username ||
1937 !raInfo->hostname ||
1938 !raInfo->xmpp_domain)
1941 return OC_STACK_INVALID_PARAM;
1943 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1944 gRASetInfo = (result == OC_STACK_OK)? true : false;
1950 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1954 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1957 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1959 if(stackState == OC_STACK_INITIALIZED)
1961 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1962 OCStop() between them are ignored.");
1966 #ifndef ROUTING_GATEWAY
1967 if (OC_GATEWAY == mode)
1969 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
1970 return OC_STACK_INVALID_PARAM;
1977 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1978 return OC_STACK_ERROR;
1982 OCStackResult result = OC_STACK_ERROR;
1983 OIC_LOG(INFO, TAG, "Entering OCInit");
1986 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1987 || (mode == OC_GATEWAY)))
1989 OIC_LOG(ERROR, TAG, "Invalid mode");
1990 return OC_STACK_ERROR;
1994 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1996 caglobals.client = true;
1998 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2000 caglobals.server = true;
2003 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2004 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2006 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2008 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2009 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2011 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2014 defaultDeviceHandler = NULL;
2015 defaultDeviceHandlerCallbackParameter = NULL;
2017 result = CAResultToOCResult(CAInitialize());
2018 VERIFY_SUCCESS(result, OC_STACK_OK);
2020 result = CAResultToOCResult(OCSelectNetwork());
2021 VERIFY_SUCCESS(result, OC_STACK_OK);
2023 switch (myStackMode)
2026 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2027 result = CAResultToOCResult(CAStartDiscoveryServer());
2028 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2031 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2032 result = CAResultToOCResult(CAStartListeningServer());
2033 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2035 case OC_CLIENT_SERVER:
2037 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2038 result = CAResultToOCResult(CAStartListeningServer());
2039 if(result == OC_STACK_OK)
2041 result = CAResultToOCResult(CAStartDiscoveryServer());
2045 VERIFY_SUCCESS(result, OC_STACK_OK);
2048 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2051 #ifdef WITH_PRESENCE
2052 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2053 #endif // WITH_PRESENCE
2055 //Update Stack state to initialized
2056 stackState = OC_STACK_INITIALIZED;
2058 // Initialize resource
2059 if(myStackMode != OC_CLIENT)
2061 result = initResources();
2064 // Initialize the SRM Policy Engine
2065 if(result == OC_STACK_OK)
2067 result = SRMInitPolicyEngine();
2068 // TODO after BeachHead delivery: consolidate into single SRMInit()
2070 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2071 RMSetStackMode(mode);
2072 #ifdef ROUTING_GATEWAY
2073 if (OC_GATEWAY == myStackMode)
2075 result = RMInitialize();
2081 if (result == OC_STACK_OK)
2083 result = InitializeKeepAlive(myStackMode);
2088 if(result != OC_STACK_OK)
2090 OIC_LOG(ERROR, TAG, "Stack initialization error");
2091 deleteAllResources();
2093 stackState = OC_STACK_UNINITIALIZED;
2098 OCStackResult OCStop()
2100 OIC_LOG(INFO, TAG, "Entering OCStop");
2102 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2104 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2107 else if (stackState != OC_STACK_INITIALIZED)
2109 OIC_LOG(ERROR, TAG, "Stack not initialized");
2110 return OC_STACK_ERROR;
2113 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2115 #ifdef WITH_PRESENCE
2116 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2117 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2118 presenceResource.presenceTTL = 0;
2119 #endif // WITH_PRESENCE
2121 #ifdef ROUTING_GATEWAY
2122 if (OC_GATEWAY == myStackMode)
2129 TerminateKeepAlive(myStackMode);
2132 // Free memory dynamically allocated for resources
2133 deleteAllResources();
2135 DeletePlatformInfo();
2137 // Remove all observers
2138 DeleteObserverList();
2139 // Remove all the client callbacks
2140 DeleteClientCBList();
2142 // De-init the SRM Policy Engine
2143 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2144 SRMDeInitPolicyEngine();
2147 stackState = OC_STACK_UNINITIALIZED;
2151 OCStackResult OCStartMulticastServer()
2153 if(stackState != OC_STACK_INITIALIZED)
2155 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2156 return OC_STACK_ERROR;
2158 CAResult_t ret = CAStartListeningServer();
2159 if (CA_STATUS_OK != ret)
2161 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2162 return OC_STACK_ERROR;
2167 OCStackResult OCStopMulticastServer()
2169 CAResult_t ret = CAStopListeningServer();
2170 if (CA_STATUS_OK != ret)
2172 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2173 return OC_STACK_ERROR;
2178 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2183 return CA_MSG_CONFIRM;
2188 return CA_MSG_NONCONFIRM;
2192 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2196 query = strchr (inputUri, '?');
2200 if((query - inputUri) > MAX_URI_LENGTH)
2202 return OC_STACK_INVALID_URI;
2205 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2207 return OC_STACK_INVALID_QUERY;
2210 else if(uriLen > MAX_URI_LENGTH)
2212 return OC_STACK_INVALID_URI;
2218 * A request uri consists of the following components in order:
2221 * CoAP over UDP prefix "coap://"
2222 * CoAP over TCP prefix "coap+tcp://"
2224 * IPv6 address "[1234::5678]"
2225 * IPv4 address "192.168.1.1"
2226 * optional port ":5683"
2227 * resource uri "/oc/core..."
2229 * for PRESENCE requests, extract resource type.
2231 static OCStackResult ParseRequestUri(const char *fullUri,
2232 OCTransportAdapter adapter,
2233 OCTransportFlags flags,
2234 OCDevAddr **devAddr,
2236 char **resourceType)
2238 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2240 OCStackResult result = OC_STACK_OK;
2241 OCDevAddr *da = NULL;
2245 // provide defaults for all returned values
2252 *resourceUri = NULL;
2256 *resourceType = NULL;
2259 // delimit url prefix, if any
2260 const char *start = fullUri;
2261 char *slash2 = strstr(start, "//");
2266 char *slash = strchr(start, '/');
2269 return OC_STACK_INVALID_URI;
2272 // process url scheme
2273 size_t prefixLen = slash2 - fullUri;
2277 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2283 // TODO: this logic should come in with unit tests exercising the various strings
2284 // processs url prefix, if any
2285 size_t urlLen = slash - start;
2289 if (urlLen && devAddr)
2290 { // construct OCDevAddr
2291 if (start[0] == '[')
2293 char *close = strchr(++start, ']');
2294 if (!close || close > slash)
2296 return OC_STACK_INVALID_URI;
2299 if (close[1] == ':')
2306 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2310 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2312 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2316 char *dot = strchr(start, '.');
2317 if (dot && dot < slash)
2319 colon = strchr(start, ':');
2320 end = (colon && colon < slash) ? colon : slash;
2325 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2329 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2331 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2339 if (len >= sizeof(da->addr))
2341 return OC_STACK_INVALID_URI;
2343 // collect port, if any
2344 if (colon && colon < slash)
2346 for (colon++; colon < slash; colon++)
2349 if (c < '0' || c > '9')
2351 return OC_STACK_INVALID_URI;
2353 port = 10 * port + c - '0';
2358 if (len >= sizeof(da->addr))
2360 return OC_STACK_INVALID_URI;
2363 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2366 return OC_STACK_NO_MEMORY;
2368 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2370 da->adapter = adapter;
2372 if (!strncmp(fullUri, "coaps:", 6))
2374 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2379 // process resource uri, if any
2381 { // request uri and query
2382 size_t ulen = strlen(slash); // resource uri length
2383 size_t tlen = 0; // resource type length
2386 static const char strPresence[] = "/oic/ad?rt=";
2387 static const size_t lenPresence = sizeof(strPresence) - 1;
2388 if (!strncmp(slash, strPresence, lenPresence))
2390 type = slash + lenPresence;
2391 tlen = ulen - lenPresence;
2396 *resourceUri = (char *)OICMalloc(ulen + 1);
2399 result = OC_STACK_NO_MEMORY;
2402 strcpy(*resourceUri, slash);
2405 if (type && resourceType)
2407 *resourceType = (char *)OICMalloc(tlen + 1);
2410 result = OC_STACK_NO_MEMORY;
2414 OICStrcpy(*resourceType, (tlen+1), type);
2421 // free all returned values
2428 OICFree(*resourceUri);
2432 OICFree(*resourceType);
2437 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2438 char *resourceUri, char **requestUri)
2440 char uri[CA_MAX_URI_LENGTH];
2442 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2444 *requestUri = OICStrdup(uri);
2447 return OC_STACK_NO_MEMORY;
2454 * Discover or Perform requests on a specified resource
2456 OCStackResult OCDoResource(OCDoHandle *handle,
2458 const char *requestUri,
2459 const OCDevAddr *destination,
2461 OCConnectivityType connectivityType,
2462 OCQualityOfService qos,
2463 OCCallbackData *cbData,
2464 OCHeaderOption *options,
2467 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2469 // Validate input parameters
2470 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2471 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2472 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2474 OCStackResult result = OC_STACK_ERROR;
2475 CAResult_t caResult;
2476 CAToken_t token = NULL;
2477 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2478 ClientCB *clientCB = NULL;
2479 OCDoHandle resHandle = NULL;
2480 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2481 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2483 OCTransportAdapter adapter;
2484 OCTransportFlags flags;
2485 // the request contents are put here
2486 CARequestInfo_t requestInfo = {.method = CA_GET};
2487 // requestUri will be parsed into the following three variables
2488 OCDevAddr *devAddr = NULL;
2489 char *resourceUri = NULL;
2490 char *resourceType = NULL;
2493 * Support original behavior with address on resourceUri argument.
2495 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2496 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2498 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2500 if (result != OC_STACK_OK)
2502 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2509 case OC_REST_OBSERVE:
2510 case OC_REST_OBSERVE_ALL:
2511 case OC_REST_CANCEL_OBSERVE:
2512 requestInfo.method = CA_GET;
2515 requestInfo.method = CA_PUT;
2518 requestInfo.method = CA_POST;
2520 case OC_REST_DELETE:
2521 requestInfo.method = CA_DELETE;
2523 case OC_REST_DISCOVER:
2525 if (destination || devAddr)
2527 requestInfo.isMulticast = false;
2531 tmpDevAddr.adapter = adapter;
2532 tmpDevAddr.flags = flags;
2533 destination = &tmpDevAddr;
2534 requestInfo.isMulticast = true;
2536 // CA_DISCOVER will become GET and isMulticast
2537 requestInfo.method = CA_GET;
2539 #ifdef WITH_PRESENCE
2540 case OC_REST_PRESENCE:
2541 // Replacing method type with GET because "presence"
2542 // is a stack layer only implementation.
2543 requestInfo.method = CA_GET;
2547 result = OC_STACK_INVALID_METHOD;
2551 if (!devAddr && !destination)
2553 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2554 result = OC_STACK_INVALID_PARAM;
2558 /* If not original behavior, use destination argument */
2559 if (destination && !devAddr)
2561 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2564 result = OC_STACK_NO_MEMORY;
2567 *devAddr = *destination;
2570 resHandle = GenerateInvocationHandle();
2573 result = OC_STACK_NO_MEMORY;
2577 caResult = CAGenerateToken(&token, tokenLength);
2578 if (caResult != CA_STATUS_OK)
2580 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2581 result= OC_STACK_ERROR;
2585 // fill in request data
2586 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2587 requestInfo.info.token = token;
2588 requestInfo.info.tokenLength = tokenLength;
2589 requestInfo.info.resourceUri = resourceUri;
2591 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2593 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2594 options, numOptions, OC_OBSERVE_REGISTER);
2595 if (result != OC_STACK_OK)
2599 requestInfo.info.numOptions = numOptions + 1;
2603 requestInfo.info.numOptions = numOptions;
2604 requestInfo.info.options =
2605 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2606 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2607 numOptions * sizeof(CAHeaderOption_t));
2610 CopyDevAddrToEndpoint(devAddr, &endpoint);
2615 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2618 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2621 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2625 requestInfo.info.payload = NULL;
2626 requestInfo.info.payloadSize = 0;
2627 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2630 if (result != OC_STACK_OK)
2632 OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2636 // prepare for response
2637 #ifdef WITH_PRESENCE
2638 if (method == OC_REST_PRESENCE)
2640 char *presenceUri = NULL;
2641 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2642 if (OC_STACK_OK != result)
2647 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2648 // Presence notification will form a canonical uri to
2649 // look for callbacks into the application.
2650 resourceUri = presenceUri;
2654 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2655 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2656 method, devAddr, resourceUri, resourceType, ttl);
2657 if (OC_STACK_OK != result)
2662 devAddr = NULL; // Client CB list entry now owns it
2663 resourceUri = NULL; // Client CB list entry now owns it
2664 resourceType = NULL; // Client CB list entry now owns it
2667 result = OCSendRequest(&endpoint, &requestInfo);
2668 if (OC_STACK_OK != result)
2675 *handle = resHandle;
2679 if (result != OC_STACK_OK)
2681 OIC_LOG(ERROR, TAG, "OCDoResource error");
2682 FindAndDeleteClientCB(clientCB);
2683 CADestroyToken(token);
2691 // This is the owner of the payload object, so we free it
2692 OCPayloadDestroy(payload);
2693 OICFree(requestInfo.info.payload);
2695 OICFree(resourceUri);
2696 OICFree(resourceType);
2697 OICFree(requestInfo.info.options);
2701 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2705 * This ftn is implemented one of two ways in the case of observation:
2707 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2708 * Remove the callback associated on client side.
2709 * When the next notification comes in from server,
2710 * reply with RESET message to server.
2711 * Keep in mind that the server will react to RESET only
2712 * if the last notification was sent as CON
2714 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2715 * and it is associated with an observe request
2716 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2717 * Send CON Observe request to server with
2718 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2719 * Remove the callback associated on client side.
2721 OCStackResult ret = OC_STACK_OK;
2722 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2723 CARequestInfo_t requestInfo = {.method = CA_GET};
2727 return OC_STACK_INVALID_PARAM;
2730 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2733 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2734 return OC_STACK_ERROR;
2737 switch (clientCB->method)
2739 case OC_REST_OBSERVE:
2740 case OC_REST_OBSERVE_ALL:
2742 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2744 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2746 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2748 FindAndDeleteClientCB(clientCB);
2752 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2754 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2755 requestInfo.info.token = clientCB->token;
2756 requestInfo.info.tokenLength = clientCB->tokenLength;
2758 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2759 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2761 return OC_STACK_ERROR;
2763 requestInfo.info.numOptions = numOptions + 1;
2764 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2767 ret = OCSendRequest(&endpoint, &requestInfo);
2769 if (requestInfo.info.options)
2771 OICFree (requestInfo.info.options);
2773 if (requestInfo.info.resourceUri)
2775 OICFree (requestInfo.info.resourceUri);
2780 case OC_REST_DISCOVER:
2781 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2782 clientCB->requestUri);
2783 FindAndDeleteClientCB(clientCB);
2786 #ifdef WITH_PRESENCE
2787 case OC_REST_PRESENCE:
2788 FindAndDeleteClientCB(clientCB);
2793 ret = OC_STACK_INVALID_METHOD;
2801 * @brief Register Persistent storage callback.
2802 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2804 * OC_STACK_OK - No errors; Success
2805 * OC_STACK_INVALID_PARAM - Invalid parameter
2807 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2809 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2810 if(!persistentStorageHandler)
2812 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2813 return OC_STACK_INVALID_PARAM;
2817 if( !persistentStorageHandler->open ||
2818 !persistentStorageHandler->close ||
2819 !persistentStorageHandler->read ||
2820 !persistentStorageHandler->unlink ||
2821 !persistentStorageHandler->write)
2823 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2824 return OC_STACK_INVALID_PARAM;
2827 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2830 #ifdef WITH_PRESENCE
2832 OCStackResult OCProcessPresence()
2834 OCStackResult result = OC_STACK_OK;
2836 // the following line floods the log with messages that are irrelevant
2837 // to most purposes. Uncomment as needed.
2838 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2839 ClientCB* cbNode = NULL;
2840 OCClientResponse clientResponse;
2841 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2843 LL_FOREACH(cbList, cbNode)
2845 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2850 uint32_t now = GetTicks(0);
2851 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2852 cbNode->presence->TTLlevel);
2853 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2855 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2860 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2862 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2863 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2865 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2867 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2869 clientResponse.sequenceNumber = 0;
2870 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2871 clientResponse.devAddr = *cbNode->devAddr;
2872 FixUpClientResponse(&clientResponse);
2873 clientResponse.payload = NULL;
2875 // Increment the TTLLevel (going to a next state), so we don't keep
2876 // sending presence notification to client.
2877 cbNode->presence->TTLlevel++;
2878 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2879 cbNode->presence->TTLlevel);
2881 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2882 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2884 FindAndDeleteClientCB(cbNode);
2888 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2893 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2894 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2895 CARequestInfo_t requestInfo = {.method = CA_GET};
2897 OIC_LOG(DEBUG, TAG, "time to test server presence");
2899 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2901 requestData.type = CA_MSG_NONCONFIRM;
2902 requestData.token = cbNode->token;
2903 requestData.tokenLength = cbNode->tokenLength;
2904 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2905 requestInfo.method = CA_GET;
2906 requestInfo.info = requestData;
2908 result = OCSendRequest(&endpoint, &requestInfo);
2909 if (OC_STACK_OK != result)
2914 cbNode->presence->TTLlevel++;
2915 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2918 if (result != OC_STACK_OK)
2920 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2925 #endif // WITH_PRESENCE
2927 OCStackResult OCProcess()
2929 #ifdef WITH_PRESENCE
2930 OCProcessPresence();
2932 CAHandleRequestResponse();
2934 #ifdef ROUTING_GATEWAY
2944 #ifdef WITH_PRESENCE
2945 OCStackResult OCStartPresence(const uint32_t ttl)
2947 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2948 OCChangeResourceProperty(
2949 &(((OCResource *)presenceResource.handle)->resourceProperties),
2952 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2954 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2955 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2959 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2960 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2964 presenceResource.presenceTTL = ttl;
2966 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2968 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2970 presenceState = OC_PRESENCE_INITIALIZED;
2972 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2974 CAToken_t caToken = NULL;
2975 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2976 if (caResult != CA_STATUS_OK)
2978 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2979 CADestroyToken(caToken);
2980 return OC_STACK_ERROR;
2983 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2984 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2985 CADestroyToken(caToken);
2988 // Each time OCStartPresence is called
2989 // a different random 32-bit integer number is used
2990 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2992 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2993 OC_PRESENCE_TRIGGER_CREATE);
2996 OCStackResult OCStopPresence()
2998 OCStackResult result = OC_STACK_ERROR;
3000 if(presenceResource.handle)
3002 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3004 // make resource inactive
3005 result = OCChangeResourceProperty(
3006 &(((OCResource *) presenceResource.handle)->resourceProperties),
3010 if(result != OC_STACK_OK)
3013 "Changing the presence resource properties to ACTIVE not successful");
3017 return SendStopNotification();
3021 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3022 void* callbackParameter)
3024 defaultDeviceHandler = entityHandler;
3025 defaultDeviceHandlerCallbackParameter = callbackParameter;
3030 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3032 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3034 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3036 if (validatePlatformInfo(platformInfo))
3038 return SavePlatformInfo(platformInfo);
3042 return OC_STACK_INVALID_PARAM;
3047 return OC_STACK_ERROR;
3051 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3053 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3055 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3057 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3058 return OC_STACK_INVALID_PARAM;
3061 if (deviceInfo.types)
3063 OCStringLL *type = deviceInfo.types;
3064 OCResource *resource = findResource((OCResource *) deviceResource);
3067 return OC_STACK_INVALID_PARAM;
3069 deleteResourceType(resource->rsrcType);
3070 resource->rsrcType = NULL;
3074 OCBindResourceTypeToResource(deviceResource, type->value);
3078 return SaveDeviceInfo(deviceInfo);
3081 OCStackResult OCCreateResource(OCResourceHandle *handle,
3082 const char *resourceTypeName,
3083 const char *resourceInterfaceName,
3084 const char *uri, OCEntityHandler entityHandler,
3085 void* callbackParam,
3086 uint8_t resourceProperties)
3089 OCResource *pointer = NULL;
3090 OCStackResult result = OC_STACK_ERROR;
3092 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3094 if(myStackMode == OC_CLIENT)
3096 return OC_STACK_INVALID_PARAM;
3098 // Validate parameters
3099 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3101 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3102 return OC_STACK_INVALID_URI;
3104 // Is it presented during resource discovery?
3105 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3107 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3108 return OC_STACK_INVALID_PARAM;
3111 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3113 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3116 // Make sure resourceProperties bitmask has allowed properties specified
3117 if (resourceProperties
3118 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3119 OC_EXPLICIT_DISCOVERABLE))
3121 OIC_LOG(ERROR, TAG, "Invalid property");
3122 return OC_STACK_INVALID_PARAM;
3125 // If the headResource is NULL, then no resources have been created...
3126 pointer = headResource;
3129 // At least one resources is in the resource list, so we need to search for
3130 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3133 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3135 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3136 return OC_STACK_INVALID_PARAM;
3138 pointer = pointer->next;
3141 // Create the pointer and insert it into the resource list
3142 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3145 result = OC_STACK_NO_MEMORY;
3148 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3150 insertResource(pointer);
3153 pointer->uri = OICStrdup(uri);
3156 result = OC_STACK_NO_MEMORY;
3160 // Set properties. Set OC_ACTIVE
3161 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3164 // Add the resourcetype to the resource
3165 result = BindResourceTypeToResource(pointer, resourceTypeName);
3166 if (result != OC_STACK_OK)
3168 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3172 // Add the resourceinterface to the resource
3173 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3174 if (result != OC_STACK_OK)
3176 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3180 // If an entity handler has been passed, attach it to the newly created
3181 // resource. Otherwise, set the default entity handler.
3184 pointer->entityHandler = entityHandler;
3185 pointer->entityHandlerCallbackParam = callbackParam;
3189 pointer->entityHandler = defaultResourceEHandler;
3190 pointer->entityHandlerCallbackParam = NULL;
3193 // Initialize a pointer indicating child resources in case of collection
3194 pointer->rsrcChildResourcesHead = NULL;
3197 result = OC_STACK_OK;
3199 #ifdef WITH_PRESENCE
3200 if (presenceResource.handle)
3202 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3203 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3207 if (result != OC_STACK_OK)
3209 // Deep delete of resource and other dynamic elements that it contains
3210 deleteResource(pointer);
3215 OCStackResult OCBindResource(
3216 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3218 OCResource *resource = NULL;
3219 OCChildResource *tempChildResource = NULL;
3220 OCChildResource *newChildResource = NULL;
3222 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3224 // Validate parameters
3225 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3226 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3227 // Container cannot contain itself
3228 if (collectionHandle == resourceHandle)
3230 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3231 return OC_STACK_INVALID_PARAM;
3234 // Use the handle to find the resource in the resource linked list
3235 resource = findResource((OCResource *) collectionHandle);
3238 OIC_LOG(ERROR, TAG, "Collection handle not found");
3239 return OC_STACK_INVALID_PARAM;
3242 // Look for an open slot to add add the child resource.
3243 // If found, add it and return success
3245 tempChildResource = resource->rsrcChildResourcesHead;
3247 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3249 // TODO: what if one of child resource was deregistered without unbinding?
3250 tempChildResource = tempChildResource->next;
3253 // Do memory allocation for child resource
3254 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3255 if(!newChildResource)
3257 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3258 return OC_STACK_ERROR;
3261 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3262 newChildResource->next = NULL;
3264 if(!resource->rsrcChildResourcesHead)
3266 resource->rsrcChildResourcesHead = newChildResource;
3269 tempChildResource->next = newChildResource;
3272 OIC_LOG(INFO, TAG, "resource bound");
3274 #ifdef WITH_PRESENCE
3275 if (presenceResource.handle)
3277 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3278 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3279 OC_PRESENCE_TRIGGER_CHANGE);
3286 OCStackResult OCUnBindResource(
3287 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3289 OCResource *resource = NULL;
3290 OCChildResource *tempChildResource = NULL;
3291 OCChildResource *tempLastChildResource = NULL;
3293 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3295 // Validate parameters
3296 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3297 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3298 // Container cannot contain itself
3299 if (collectionHandle == resourceHandle)
3301 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3302 return OC_STACK_INVALID_PARAM;
3305 // Use the handle to find the resource in the resource linked list
3306 resource = findResource((OCResource *) collectionHandle);
3309 OIC_LOG(ERROR, TAG, "Collection handle not found");
3310 return OC_STACK_INVALID_PARAM;
3313 // Look for an open slot to add add the child resource.
3314 // If found, add it and return success
3315 if(!resource->rsrcChildResourcesHead)
3317 OIC_LOG(INFO, TAG, "resource not found in collection");
3319 // Unable to add resourceHandle, so return error
3320 return OC_STACK_ERROR;
3324 tempChildResource = resource->rsrcChildResourcesHead;
3326 while (tempChildResource)
3328 if(tempChildResource->rsrcResource == resourceHandle)
3330 // if resource going to be unbinded is the head one.
3331 if( tempChildResource == resource->rsrcChildResourcesHead )
3333 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3334 OICFree(resource->rsrcChildResourcesHead);
3335 resource->rsrcChildResourcesHead = temp;
3340 OCChildResource *temp = tempChildResource->next;
3341 OICFree(tempChildResource);
3342 tempLastChildResource->next = temp;
3346 OIC_LOG(INFO, TAG, "resource unbound");
3348 // Send notification when resource is unbounded successfully.
3349 #ifdef WITH_PRESENCE
3350 if (presenceResource.handle)
3352 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3353 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3354 OC_PRESENCE_TRIGGER_CHANGE);
3357 tempChildResource = NULL;
3358 tempLastChildResource = NULL;
3364 tempLastChildResource = tempChildResource;
3365 tempChildResource = tempChildResource->next;
3368 OIC_LOG(INFO, TAG, "resource not found in collection");
3370 tempChildResource = NULL;
3371 tempLastChildResource = NULL;
3373 // Unable to add resourceHandle, so return error
3374 return OC_STACK_ERROR;
3377 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3379 if (!resourceItemName)
3383 // Per RFC 6690 only registered values must follow the first rule below.
3384 // At this point in time the only values registered begin with "core", and
3385 // all other values are specified as opaque strings where multiple values
3386 // are separated by a space.
3387 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3389 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3391 if (resourceItemName[index] != '.'
3392 && resourceItemName[index] != '-'
3393 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3394 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3402 for (size_t index = 0; resourceItemName[index]; ++index)
3404 if (resourceItemName[index] == ' '
3405 || resourceItemName[index] == '\t'
3406 || resourceItemName[index] == '\r'
3407 || resourceItemName[index] == '\n')
3417 OCStackResult BindResourceTypeToResource(OCResource* resource,
3418 const char *resourceTypeName)
3420 OCResourceType *pointer = NULL;
3422 OCStackResult result = OC_STACK_ERROR;
3424 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3426 if (!ValidateResourceTypeInterface(resourceTypeName))
3428 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3429 return OC_STACK_INVALID_PARAM;
3432 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3435 result = OC_STACK_NO_MEMORY;
3439 str = OICStrdup(resourceTypeName);
3442 result = OC_STACK_NO_MEMORY;
3445 pointer->resourcetypename = str;
3446 pointer->next = NULL;
3448 insertResourceType(resource, pointer);
3449 result = OC_STACK_OK;
3452 if (result != OC_STACK_OK)
3461 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3462 const char *resourceInterfaceName)
3464 OCResourceInterface *pointer = NULL;
3466 OCStackResult result = OC_STACK_ERROR;
3468 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3470 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3472 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3473 return OC_STACK_INVALID_PARAM;
3476 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3478 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3481 result = OC_STACK_NO_MEMORY;
3485 str = OICStrdup(resourceInterfaceName);
3488 result = OC_STACK_NO_MEMORY;
3491 pointer->name = str;
3493 // Bind the resourceinterface to the resource
3494 insertResourceInterface(resource, pointer);
3496 result = OC_STACK_OK;
3499 if (result != OC_STACK_OK)
3508 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3509 const char *resourceTypeName)
3512 OCStackResult result = OC_STACK_ERROR;
3513 OCResource *resource = NULL;
3515 resource = findResource((OCResource *) handle);
3518 OIC_LOG(ERROR, TAG, "Resource not found");
3519 return OC_STACK_ERROR;
3522 result = BindResourceTypeToResource(resource, resourceTypeName);
3524 #ifdef WITH_PRESENCE
3525 if(presenceResource.handle)
3527 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3528 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3535 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3536 const char *resourceInterfaceName)
3539 OCStackResult result = OC_STACK_ERROR;
3540 OCResource *resource = NULL;
3542 resource = findResource((OCResource *) handle);
3545 OIC_LOG(ERROR, TAG, "Resource not found");
3546 return OC_STACK_ERROR;
3549 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3551 #ifdef WITH_PRESENCE
3552 if (presenceResource.handle)
3554 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3555 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3562 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3564 OCResource *pointer = headResource;
3566 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3570 *numResources = *numResources + 1;
3571 pointer = pointer->next;
3576 OCResourceHandle OCGetResourceHandle(uint8_t index)
3578 OCResource *pointer = headResource;
3580 for( uint8_t i = 0; i < index && pointer; ++i)
3582 pointer = pointer->next;
3584 return (OCResourceHandle) pointer;
3587 OCStackResult OCDeleteResource(OCResourceHandle handle)
3591 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3592 return OC_STACK_INVALID_PARAM;
3595 OCResource *resource = findResource((OCResource *) handle);
3596 if (resource == NULL)
3598 OIC_LOG(ERROR, TAG, "Resource not found");
3599 return OC_STACK_NO_RESOURCE;
3602 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3604 OIC_LOG(ERROR, TAG, "Error deleting resource");
3605 return OC_STACK_ERROR;
3611 const char *OCGetResourceUri(OCResourceHandle handle)
3613 OCResource *resource = NULL;
3615 resource = findResource((OCResource *) handle);
3618 return resource->uri;
3620 return (const char *) NULL;
3623 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3625 OCResource *resource = NULL;
3627 resource = findResource((OCResource *) handle);
3630 return resource->resourceProperties;
3632 return (OCResourceProperty)-1;
3635 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3636 uint8_t *numResourceTypes)
3638 OCResource *resource = NULL;
3639 OCResourceType *pointer = NULL;
3641 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3642 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3644 *numResourceTypes = 0;
3646 resource = findResource((OCResource *) handle);
3649 pointer = resource->rsrcType;
3652 *numResourceTypes = *numResourceTypes + 1;
3653 pointer = pointer->next;
3659 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3661 OCResourceType *resourceType = NULL;
3663 resourceType = findResourceTypeAtIndex(handle, index);
3666 return resourceType->resourcetypename;
3668 return (const char *) NULL;
3671 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3672 uint8_t *numResourceInterfaces)
3674 OCResourceInterface *pointer = NULL;
3675 OCResource *resource = NULL;
3677 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3678 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3680 *numResourceInterfaces = 0;
3681 resource = findResource((OCResource *) handle);
3684 pointer = resource->rsrcInterface;
3687 *numResourceInterfaces = *numResourceInterfaces + 1;
3688 pointer = pointer->next;
3694 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3696 OCResourceInterface *resourceInterface = NULL;
3698 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3699 if (resourceInterface)
3701 return resourceInterface->name;
3703 return (const char *) NULL;
3706 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3709 OCResource *resource = NULL;
3710 OCChildResource *tempChildResource = NULL;
3713 resource = findResource((OCResource *) collectionHandle);
3719 tempChildResource = resource->rsrcChildResourcesHead;
3721 while(tempChildResource)
3725 return tempChildResource->rsrcResource;
3728 tempChildResource = tempChildResource->next;
3731 // In this case, the number of resource handles in the collection exceeds the index
3732 tempChildResource = NULL;
3736 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3737 OCEntityHandler entityHandler,
3738 void* callbackParam)
3740 OCResource *resource = NULL;
3742 // Validate parameters
3743 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3745 // Use the handle to find the resource in the resource linked list
3746 resource = findResource((OCResource *)handle);
3749 OIC_LOG(ERROR, TAG, "Resource not found");
3750 return OC_STACK_ERROR;
3754 resource->entityHandler = entityHandler;
3755 resource->entityHandlerCallbackParam = callbackParam;
3757 #ifdef WITH_PRESENCE
3758 if (presenceResource.handle)
3760 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3761 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3768 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3770 OCResource *resource = NULL;
3772 resource = findResource((OCResource *)handle);
3775 OIC_LOG(ERROR, TAG, "Resource not found");
3780 return resource->entityHandler;
3783 void incrementSequenceNumber(OCResource * resPtr)
3785 // Increment the sequence number
3786 resPtr->sequenceNum += 1;
3787 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3789 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3794 #ifdef WITH_PRESENCE
3795 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3796 OCPresenceTrigger trigger)
3798 OCResource *resPtr = NULL;
3799 OCStackResult result = OC_STACK_ERROR;
3800 OCMethod method = OC_REST_PRESENCE;
3801 uint32_t maxAge = 0;
3802 resPtr = findResource((OCResource *) presenceResource.handle);
3805 return OC_STACK_NO_RESOURCE;
3808 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3810 maxAge = presenceResource.presenceTTL;
3812 result = SendAllObserverNotification(method, resPtr, maxAge,
3813 trigger, resourceType, OC_LOW_QOS);
3819 OCStackResult SendStopNotification()
3821 OCResource *resPtr = NULL;
3822 OCStackResult result = OC_STACK_ERROR;
3823 OCMethod method = OC_REST_PRESENCE;
3824 resPtr = findResource((OCResource *) presenceResource.handle);
3827 return OC_STACK_NO_RESOURCE;
3830 // maxAge is 0. ResourceType is NULL.
3831 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3837 #endif // WITH_PRESENCE
3838 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3840 OCResource *resPtr = NULL;
3841 OCStackResult result = OC_STACK_ERROR;
3842 OCMethod method = OC_REST_NOMETHOD;
3843 uint32_t maxAge = 0;
3845 OIC_LOG(INFO, TAG, "Notifying all observers");
3846 #ifdef WITH_PRESENCE
3847 if(handle == presenceResource.handle)
3851 #endif // WITH_PRESENCE
3852 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3854 // Verify that the resource exists
3855 resPtr = findResource ((OCResource *) handle);
3858 return OC_STACK_NO_RESOURCE;
3862 //only increment in the case of regular observing (not presence)
3863 incrementSequenceNumber(resPtr);
3864 method = OC_REST_OBSERVE;
3865 maxAge = MAX_OBSERVE_AGE;
3866 #ifdef WITH_PRESENCE
3867 result = SendAllObserverNotification (method, resPtr, maxAge,
3868 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3870 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3877 OCNotifyListOfObservers (OCResourceHandle handle,
3878 OCObservationId *obsIdList,
3879 uint8_t numberOfIds,
3880 const OCRepPayload *payload,
3881 OCQualityOfService qos)
3883 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3885 OCResource *resPtr = NULL;
3886 //TODO: we should allow the server to define this
3887 uint32_t maxAge = MAX_OBSERVE_AGE;
3889 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3890 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3891 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3893 resPtr = findResource ((OCResource *) handle);
3894 if (NULL == resPtr || myStackMode == OC_CLIENT)
3896 return OC_STACK_NO_RESOURCE;
3900 incrementSequenceNumber(resPtr);
3902 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3903 payload, maxAge, qos));
3906 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3908 OCStackResult result = OC_STACK_ERROR;
3909 OCServerRequest *serverRequest = NULL;
3911 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3913 // Validate input parameters
3914 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3915 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3918 // Get pointer to request info
3919 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3922 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3923 result = serverRequest->ehResponseHandler(ehResponse);
3929 //#ifdef DIRECT_PAIRING
3930 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3932 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3933 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3935 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3939 return (const OCDPDev_t*)DPGetDiscoveredDevices();
3942 const OCDPDev_t* OCGetDirectPairedDevices()
3944 return (const OCDPDev_t*)DPGetPairedDevices();
3947 void DirectPairingCB (OCDirectPairingDev_t * peer, OCStackResult result)
3949 if (gDirectpairingCallback)
3951 gDirectpairingCallback((OCDPDev_t*)peer, result);
3952 gDirectpairingCallback = NULL;
3956 OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3957 OCDirectPairingCB resultCallback)
3959 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3960 if(NULL == peer || NULL == pinNumber)
3962 OIC_LOG(ERROR, TAG, "Invalid parameters");
3963 return OC_STACK_INVALID_PARAM;
3965 if (NULL == resultCallback)
3967 OIC_LOG(ERROR, TAG, "Invalid callback");
3968 return OC_STACK_INVALID_CALLBACK;
3971 gDirectpairingCallback = resultCallback;
3972 return DPDirectPairing((OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3973 pinNumber, DirectPairingCB);
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
4132 SRMDeInitSecureResources();
4134 #ifdef WITH_PRESENCE
4135 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4136 // presence notification attributed to their deletion to be processed.
4137 deleteResource((OCResource *) presenceResource.handle);
4138 #endif // WITH_PRESENCE
4141 OCStackResult deleteResource(OCResource *resource)
4143 OCResource *prev = NULL;
4144 OCResource *temp = NULL;
4147 OIC_LOG(DEBUG,TAG,"resource is NULL");
4148 return OC_STACK_INVALID_PARAM;
4151 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4153 temp = headResource;
4156 if (temp == resource)
4158 // Invalidate all Resource Properties.
4159 resource->resourceProperties = (OCResourceProperty) 0;
4160 #ifdef WITH_PRESENCE
4161 if(resource != (OCResource *) presenceResource.handle)
4163 #endif // WITH_PRESENCE
4164 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4165 #ifdef WITH_PRESENCE
4168 if(presenceResource.handle)
4170 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4171 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4174 // Only resource in list.
4175 if (temp == headResource && temp == tailResource)
4177 headResource = NULL;
4178 tailResource = NULL;
4181 else if (temp == headResource)
4183 headResource = temp->next;
4186 else if (temp == tailResource)
4188 tailResource = prev;
4189 tailResource->next = NULL;
4193 prev->next = temp->next;
4196 deleteResourceElements(temp);
4207 return OC_STACK_ERROR;
4210 void deleteResourceElements(OCResource *resource)
4217 OICFree(resource->uri);
4218 deleteResourceType(resource->rsrcType);
4219 deleteResourceInterface(resource->rsrcInterface);
4222 void deleteResourceType(OCResourceType *resourceType)
4224 OCResourceType *pointer = resourceType;
4225 OCResourceType *next = NULL;
4229 next = pointer->next;
4230 OICFree(pointer->resourcetypename);
4236 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4238 OCResourceInterface *pointer = resourceInterface;
4239 OCResourceInterface *next = NULL;
4243 next = pointer->next;
4244 OICFree(pointer->name);
4250 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4252 OCResourceType *pointer = NULL;
4253 OCResourceType *previous = NULL;
4254 if (!resource || !resourceType)
4258 // resource type list is empty.
4259 else if (!resource->rsrcType)
4261 resource->rsrcType = resourceType;
4265 pointer = resource->rsrcType;
4269 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4271 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4272 OICFree(resourceType->resourcetypename);
4273 OICFree(resourceType);
4277 pointer = pointer->next;
4282 previous->next = resourceType;
4285 resourceType->next = NULL;
4287 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4290 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4292 OCResource *resource = NULL;
4293 OCResourceType *pointer = NULL;
4295 // Find the specified resource
4296 resource = findResource((OCResource *) handle);
4302 // Make sure a resource has a resourcetype
4303 if (!resource->rsrcType)
4308 // Iterate through the list
4309 pointer = resource->rsrcType;
4310 for(uint8_t i = 0; i< index && pointer; ++i)
4312 pointer = pointer->next;
4317 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4319 if(resourceTypeList && resourceTypeName)
4321 OCResourceType * rtPointer = resourceTypeList;
4322 while(resourceTypeName && rtPointer)
4324 if(rtPointer->resourcetypename &&
4325 strcmp(resourceTypeName, (const char *)
4326 (rtPointer->resourcetypename)) == 0)
4330 rtPointer = rtPointer->next;
4338 * Insert a new interface into interface linked list only if not already present.
4339 * If alredy present, 2nd arg is free'd.
4340 * Default interface will always be first if present.
4342 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4344 OCResourceInterface *pointer = NULL;
4345 OCResourceInterface *previous = NULL;
4347 newInterface->next = NULL;
4349 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4351 if (!*firstInterface)
4353 // If first interface is not oic.if.baseline, by default add it as first interface type.
4354 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4356 *firstInterface = newInterface;
4360 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4361 if (result != OC_STACK_OK)
4363 OICFree(newInterface->name);
4364 OICFree(newInterface);
4367 if (*firstInterface)
4369 (*firstInterface)->next = newInterface;
4373 // If once add oic.if.baseline, later too below code take care of freeing memory.
4374 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4376 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4378 OICFree(newInterface->name);
4379 OICFree(newInterface);
4382 // This code will not hit anymore, keeping
4385 newInterface->next = *firstInterface;
4386 *firstInterface = newInterface;
4391 pointer = *firstInterface;
4394 if (strcmp(newInterface->name, pointer->name) == 0)
4396 OICFree(newInterface->name);
4397 OICFree(newInterface);
4401 pointer = pointer->next;
4403 previous->next = newInterface;
4407 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4410 OCResource *resource = NULL;
4411 OCResourceInterface *pointer = NULL;
4413 // Find the specified resource
4414 resource = findResource((OCResource *) handle);
4420 // Make sure a resource has a resourceinterface
4421 if (!resource->rsrcInterface)
4426 // Iterate through the list
4427 pointer = resource->rsrcInterface;
4429 for (uint8_t i = 0; i < index && pointer; ++i)
4431 pointer = pointer->next;
4437 * This function splits the uri using the '?' delimiter.
4438 * "uriWithoutQuery" is the block of characters between the beginning
4439 * till the delimiter or '\0' which ever comes first.
4440 * "query" is whatever is to the right of the delimiter if present.
4441 * No delimiter sets the query to NULL.
4442 * If either are present, they will be malloc'ed into the params 2, 3.
4443 * The first param, *uri is left untouched.
4445 * NOTE: This function does not account for whitespace at the end of the uri NOR
4446 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4447 * part of the query.
4449 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4453 return OC_STACK_INVALID_URI;
4455 if(!query || !uriWithoutQuery)
4457 return OC_STACK_INVALID_PARAM;
4461 *uriWithoutQuery = NULL;
4463 size_t uriWithoutQueryLen = 0;
4464 size_t queryLen = 0;
4465 size_t uriLen = strlen(uri);
4467 char *pointerToDelimiter = strstr(uri, "?");
4469 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4470 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4472 if (uriWithoutQueryLen)
4474 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4475 if (!*uriWithoutQuery)
4479 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4483 *query = (char *) OICCalloc(queryLen + 1, 1);
4486 OICFree(*uriWithoutQuery);
4487 *uriWithoutQuery = NULL;
4490 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4496 return OC_STACK_NO_MEMORY;
4499 static const OicUuid_t* OCGetServerInstanceID(void)
4501 static bool generated = false;
4502 static OicUuid_t sid;
4508 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4510 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4517 const char* OCGetServerInstanceIDString(void)
4519 static bool generated = false;
4520 static char sidStr[UUID_STRING_SIZE];
4527 const OicUuid_t *sid = OCGetServerInstanceID();
4528 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4530 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4538 CAResult_t OCSelectNetwork()
4540 CAResult_t retResult = CA_STATUS_FAILED;
4541 CAResult_t caResult = CA_STATUS_OK;
4543 CATransportAdapter_t connTypes[] = {
4545 CA_ADAPTER_RFCOMM_BTEDR,
4546 CA_ADAPTER_GATT_BTLE,
4549 ,CA_ADAPTER_REMOTE_ACCESS
4556 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4558 for(int i = 0; i<numConnTypes; i++)
4560 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4561 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4563 caResult = CASelectNetwork(connTypes[i]);
4564 if(caResult == CA_STATUS_OK)
4566 retResult = CA_STATUS_OK;
4571 if(retResult != CA_STATUS_OK)
4573 return caResult; // Returns error of appropriate transport that failed fatally.
4579 OCStackResult CAResultToOCResult(CAResult_t caResult)
4585 case CA_STATUS_INVALID_PARAM:
4586 return OC_STACK_INVALID_PARAM;
4587 case CA_ADAPTER_NOT_ENABLED:
4588 return OC_STACK_ADAPTER_NOT_ENABLED;
4589 case CA_SERVER_STARTED_ALREADY:
4591 case CA_SERVER_NOT_STARTED:
4592 return OC_STACK_ERROR;
4593 case CA_DESTINATION_NOT_REACHABLE:
4594 return OC_STACK_COMM_ERROR;
4595 case CA_SOCKET_OPERATION_FAILED:
4596 return OC_STACK_COMM_ERROR;
4597 case CA_SEND_FAILED:
4598 return OC_STACK_COMM_ERROR;
4599 case CA_RECEIVE_FAILED:
4600 return OC_STACK_COMM_ERROR;
4601 case CA_MEMORY_ALLOC_FAILED:
4602 return OC_STACK_NO_MEMORY;
4603 case CA_REQUEST_TIMEOUT:
4604 return OC_STACK_TIMEOUT;
4605 case CA_DESTINATION_DISCONNECTED:
4606 return OC_STACK_COMM_ERROR;
4607 case CA_STATUS_FAILED:
4608 return OC_STACK_ERROR;
4609 case CA_NOT_SUPPORTED:
4610 return OC_STACK_NOTIMPL;
4612 return OC_STACK_ERROR;