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:";
135 //#ifdef DIRECT_PAIRING
136 OCDirectPairingCB gDirectpairingCallback = NULL;
139 //-----------------------------------------------------------------------------
141 //-----------------------------------------------------------------------------
142 #define TAG "OIC_RI_STACK"
143 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
144 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
145 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
146 TAG, #arg " is NULL"); return (retVal); } }
147 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
148 TAG, #arg " is NULL"); return; } }
149 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
152 //TODO: we should allow the server to define this
153 #define MAX_OBSERVE_AGE (0x2FFFFUL)
155 #define MILLISECONDS_PER_SECOND (1000)
157 //-----------------------------------------------------------------------------
158 // Private internal function prototypes
159 //-----------------------------------------------------------------------------
162 * Generate handle of OCDoResource invocation for callback management.
164 * @return Generated OCDoResource handle.
166 static OCDoHandle GenerateInvocationHandle();
169 * Initialize resource data structures, variables, etc.
171 * @return ::OC_STACK_OK on success, some other value upon failure.
173 static OCStackResult initResources();
176 * Add a resource to the end of the linked list of resources.
178 * @param resource Resource to be added
180 static void insertResource(OCResource *resource);
183 * Find a resource in the linked list of resources.
185 * @param resource Resource to be found.
186 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
189 static OCResource *findResource(OCResource *resource);
192 * Insert a resource type into a resource's resource type linked list.
193 * If resource type already exists, it will not be inserted and the
194 * resourceType will be free'd.
195 * resourceType->next should be null to avoid memory leaks.
196 * Function returns silently for null args.
198 * @param resource Resource where resource type is to be inserted.
199 * @param resourceType Resource type to be inserted.
201 static void insertResourceType(OCResource *resource,
202 OCResourceType *resourceType);
205 * Get a resource type at the specified index within a resource.
207 * @param handle Handle of resource.
208 * @param index Index of resource type.
210 * @return Pointer to resource type if found, NULL otherwise.
212 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
216 * Insert a resource interface into a resource's resource interface linked list.
217 * If resource interface already exists, it will not be inserted and the
218 * resourceInterface will be free'd.
219 * resourceInterface->next should be null to avoid memory leaks.
221 * @param resource Resource where resource interface is to be inserted.
222 * @param resourceInterface Resource interface to be inserted.
224 static void insertResourceInterface(OCResource *resource,
225 OCResourceInterface *resourceInterface);
228 * Get a resource interface at the specified index within a resource.
230 * @param handle Handle of resource.
231 * @param index Index of resource interface.
233 * @return Pointer to resource interface if found, NULL otherwise.
235 static OCResourceInterface *findResourceInterfaceAtIndex(
236 OCResourceHandle handle, uint8_t index);
239 * Delete all of the dynamically allocated elements that were created for the resource type.
241 * @param resourceType Specified resource type.
243 static void deleteResourceType(OCResourceType *resourceType);
246 * Delete all of the dynamically allocated elements that were created for the resource interface.
248 * @param resourceInterface Specified resource interface.
250 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
253 * Delete all of the dynamically allocated elements that were created for the resource.
255 * @param resource Specified resource.
257 static void deleteResourceElements(OCResource *resource);
260 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
263 * @param handle Handle of resource to be deleted.
265 * @return ::OC_STACK_OK on success, some other value upon failure.
267 static OCStackResult deleteResource(OCResource *resource);
270 * Delete all of the resources in the resource list.
272 static void deleteAllResources();
275 * Increment resource sequence number. Handles rollover.
277 * @param resPtr Pointer to resource.
279 static void incrementSequenceNumber(OCResource * resPtr);
282 * Verify the lengths of the URI and the query separately.
284 * @param inputUri Input URI and query.
285 * @param uriLen The length of the initial URI with query.
286 * @return ::OC_STACK_OK on success, some other value upon failure.
288 static OCStackResult verifyUriQueryLength(const char * inputUri,
292 * Attempts to initialize every network interface that the CA Layer might have compiled in.
294 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
295 * return something other than @ref CA_STATUS_OK, then this function fails.
297 * @return ::CA_STATUS_OK on success, some other value upon failure.
299 static CAResult_t OCSelectNetwork();
302 * Get the CoAP ticks after the specified number of milli-seconds.
304 * @param afterMilliSeconds Milli-seconds.
308 static uint32_t GetTicks(uint32_t afterMilliSeconds);
311 * Convert CAResponseResult_t to OCStackResult.
313 * @param caCode CAResponseResult_t code.
314 * @return ::OC_STACK_OK on success, some other value upon failure.
316 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
319 * Convert OCStackResult to CAResponseResult_t.
321 * @param caCode OCStackResult code.
322 * @param method OCMethod method the return code replies to.
323 * @return ::CA_CONTENT on OK, some other value upon failure.
325 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
328 * Convert OCTransportFlags_t to CATransportModifiers_t.
330 * @param ocConType OCTransportFlags_t input.
331 * @return CATransportFlags
333 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
336 * Convert CATransportFlags_t to OCTransportModifiers_t.
338 * @param caConType CATransportFlags_t input.
339 * @return OCTransportFlags
341 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
344 * Handle response from presence request.
346 * @param endPoint CA remote endpoint.
347 * @param responseInfo CA response info.
348 * @return ::OC_STACK_OK on success, some other value upon failure.
350 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
351 const CAResponseInfo_t *responseInfo);
354 * This function will be called back by CA layer when a response is received.
356 * @param endPoint CA remote endpoint.
357 * @param responseInfo CA response info.
359 static void HandleCAResponses(const CAEndpoint_t* endPoint,
360 const CAResponseInfo_t* responseInfo);
363 * This function will be called back by CA layer when a request is received.
365 * @param endPoint CA remote endpoint.
366 * @param requestInfo CA request info.
368 static void HandleCARequests(const CAEndpoint_t* endPoint,
369 const CARequestInfo_t* requestInfo);
372 * Extract query from a URI.
374 * @param uri Full URI with query.
375 * @param query Pointer to string that will contain query.
376 * @param newURI Pointer to string that will contain URI.
377 * @return ::OC_STACK_OK on success, some other value upon failure.
379 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
382 * Finds a resource type in an OCResourceType link-list.
384 * @param resourceTypeList The link-list to be searched through.
385 * @param resourceTypeName The key to search for.
387 * @return Resource type that matches the key (ie. resourceTypeName) or
388 * NULL if there is either an invalid parameter or this function was unable to find the key.
390 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
391 const char * resourceTypeName);
394 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
395 * TTL will be set to maxAge.
397 * @param cbNode Callback Node for which presence ttl is to be reset.
398 * @param maxAge New value of ttl in seconds.
400 * @return ::OC_STACK_OK on success, some other value upon failure.
402 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
405 * Ensure the accept header option is set appropriatly before sending the requests and routing
406 * header option is updated with destination.
408 * @param object CA remote endpoint.
409 * @param requestInfo CA request info.
411 * @return ::OC_STACK_OK on success, some other value upon failure.
413 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
415 //-----------------------------------------------------------------------------
416 // Internal functions
417 //-----------------------------------------------------------------------------
419 uint32_t GetTicks(uint32_t afterMilliSeconds)
424 // Guard against overflow of uint32_t
425 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
426 COAP_TICKS_PER_SECOND)
428 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
436 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
438 VERIFY_NON_NULL_NR(in, FATAL);
439 VERIFY_NON_NULL_NR(out, FATAL);
441 out->adapter = (OCTransportAdapter)in->adapter;
442 out->flags = CAToOCTransportFlags(in->flags);
443 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
444 out->port = in->port;
445 out->interface = in->interface;
446 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
447 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
451 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
453 VERIFY_NON_NULL_NR(in, FATAL);
454 VERIFY_NON_NULL_NR(out, FATAL);
456 out->adapter = (CATransportAdapter_t)in->adapter;
457 out->flags = OCToCATransportFlags(in->flags);
458 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
459 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
460 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
462 out->port = in->port;
463 out->interface = in->interface;
466 void FixUpClientResponse(OCClientResponse *cr)
468 VERIFY_NON_NULL_NR(cr, FATAL);
470 cr->addr = &cr->devAddr;
471 cr->connType = (OCConnectivityType)
472 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
475 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
477 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
478 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
480 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
481 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
482 if (OC_STACK_OK != rmResult)
484 OIC_LOG(ERROR, TAG, "Add destination option failed");
489 // OC stack prefer CBOR encoded payloads.
490 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
491 CAResult_t result = CASendRequest(object, requestInfo);
492 if(CA_STATUS_OK != result)
494 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
495 return CAResultToOCResult(result);
499 //-----------------------------------------------------------------------------
500 // Internal API function
501 //-----------------------------------------------------------------------------
503 // This internal function is called to update the stack with the status of
504 // observers and communication failures
505 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
507 OCStackResult result = OC_STACK_ERROR;
508 ResourceObserver * observer = NULL;
509 OCEntityHandlerRequest ehRequest = {0};
513 case OC_OBSERVER_NOT_INTERESTED:
514 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
515 observer = GetObserverUsingToken (token, tokenLength);
518 result = FormOCEntityHandlerRequest(&ehRequest,
519 (OCRequestHandle)NULL,
522 (OCResourceHandle)NULL,
523 NULL, PAYLOAD_TYPE_REPRESENTATION,
525 OC_OBSERVE_DEREGISTER,
526 observer->observeId);
527 if(result != OC_STACK_OK)
531 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
532 observer->resource->entityHandlerCallbackParam);
535 result = DeleteObserverUsingToken (token, tokenLength);
536 if(result == OC_STACK_OK)
538 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
542 result = OC_STACK_OK;
543 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
547 case OC_OBSERVER_STILL_INTERESTED:
548 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
549 observer = GetObserverUsingToken (token, tokenLength);
552 observer->forceHighQos = 0;
553 observer->failedCommCount = 0;
554 result = OC_STACK_OK;
558 result = OC_STACK_OBSERVER_NOT_FOUND;
562 case OC_OBSERVER_FAILED_COMM:
563 OIC_LOG(DEBUG, TAG, "observer is unreachable");
564 observer = GetObserverUsingToken (token, tokenLength);
567 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
569 result = FormOCEntityHandlerRequest(&ehRequest,
570 (OCRequestHandle)NULL,
573 (OCResourceHandle)NULL,
574 NULL, PAYLOAD_TYPE_REPRESENTATION,
576 OC_OBSERVE_DEREGISTER,
577 observer->observeId);
578 if(result != OC_STACK_OK)
580 return OC_STACK_ERROR;
582 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
583 observer->resource->entityHandlerCallbackParam);
585 result = DeleteObserverUsingToken (token, tokenLength);
586 if(result == OC_STACK_OK)
588 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
592 result = OC_STACK_OK;
593 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
598 observer->failedCommCount++;
599 result = OC_STACK_CONTINUE;
601 observer->forceHighQos = 1;
602 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
606 OIC_LOG(ERROR, TAG, "Unknown status");
607 result = OC_STACK_ERROR;
612 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
614 OCStackResult ret = OC_STACK_ERROR;
619 ret = OC_STACK_RESOURCE_CREATED;
622 ret = OC_STACK_RESOURCE_DELETED;
630 ret = OC_STACK_INVALID_QUERY;
632 case CA_UNAUTHORIZED_REQ:
633 ret = OC_STACK_UNAUTHORIZED_REQ;
636 ret = OC_STACK_INVALID_OPTION;
639 ret = OC_STACK_NO_RESOURCE;
641 case CA_RETRANSMIT_TIMEOUT:
642 ret = OC_STACK_COMM_ERROR;
650 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
652 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
661 // This Response Code is like HTTP 204 "No Content" but only used in
662 // response to POST and PUT requests.
666 // This Response Code is like HTTP 200 "OK" but only used in response to
671 // This should not happen but,
672 // give it a value just in case but output an error
674 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
677 case OC_STACK_RESOURCE_CREATED:
680 case OC_STACK_RESOURCE_DELETED:
683 case OC_STACK_INVALID_QUERY:
686 case OC_STACK_INVALID_OPTION:
689 case OC_STACK_NO_RESOURCE:
692 case OC_STACK_COMM_ERROR:
693 ret = CA_RETRANSMIT_TIMEOUT;
695 case OC_STACK_UNAUTHORIZED_REQ:
696 ret = CA_UNAUTHORIZED_REQ;
704 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
706 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
708 // supply default behavior.
709 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
711 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
713 if ((caFlags & OC_MASK_SCOPE) == 0)
715 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
720 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
722 return (OCTransportFlags)caFlags;
725 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
727 uint32_t lowerBound = 0;
728 uint32_t higherBound = 0;
730 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
732 return OC_STACK_INVALID_PARAM;
735 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
737 cbNode->presence->TTL = maxAgeSeconds;
739 for (int index = 0; index < PresenceTimeOutSize; index++)
741 // Guard against overflow
742 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
745 lowerBound = GetTicks((PresenceTimeOut[index] *
746 cbNode->presence->TTL *
747 MILLISECONDS_PER_SECOND)/100);
751 lowerBound = GetTicks(UINT32_MAX);
754 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
757 higherBound = GetTicks((PresenceTimeOut[index + 1] *
758 cbNode->presence->TTL *
759 MILLISECONDS_PER_SECOND)/100);
763 higherBound = GetTicks(UINT32_MAX);
766 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
768 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
769 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
770 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
773 cbNode->presence->TTLlevel = 0;
775 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
779 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
781 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
783 return OC_RSRVD_TRIGGER_CREATE;
785 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
787 return OC_RSRVD_TRIGGER_CHANGE;
791 return OC_RSRVD_TRIGGER_DELETE;
795 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
799 return OC_PRESENCE_TRIGGER_CREATE;
801 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
803 return OC_PRESENCE_TRIGGER_CREATE;
805 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
807 return OC_PRESENCE_TRIGGER_CHANGE;
811 return OC_PRESENCE_TRIGGER_DELETE;
816 * The cononical presence allows constructed URIs to be string compared.
818 * requestUri must be a char array of size CA_MAX_URI_LENGTH
820 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
823 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
824 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
825 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
827 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
829 if (ep->adapter == CA_ADAPTER_IP)
831 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
833 if ('\0' == ep->addr[0]) // multicast
835 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
839 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
840 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
845 if ('\0' == ep->addr[0]) // multicast
847 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
848 ep->port = OC_MULTICAST_PORT;
850 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
851 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
855 // might work for other adapters (untested, but better than nothing)
856 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
857 OC_RSRVD_PRESENCE_URI);
861 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
862 const CAResponseInfo_t *responseInfo)
864 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
865 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
867 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
868 ClientCB * cbNode = NULL;
869 char *resourceTypeName = NULL;
870 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
871 OCStackResult result = OC_STACK_ERROR;
874 char presenceUri[CA_MAX_URI_LENGTH];
876 int presenceSubscribe = 0;
877 int multicastPresenceSubscribe = 0;
879 if (responseInfo->result != CA_CONTENT)
881 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
882 return OC_STACK_ERROR;
885 // check for unicast presence
886 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
887 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
889 return OC_STACK_INVALID_URI;
892 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
895 presenceSubscribe = 1;
899 // check for multiicast presence
900 CAEndpoint_t ep = { .adapter = endpoint->adapter,
901 .flags = endpoint->flags };
903 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
905 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
908 multicastPresenceSubscribe = 1;
912 if (!presenceSubscribe && !multicastPresenceSubscribe)
914 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
918 response.payload = NULL;
919 response.result = OC_STACK_OK;
921 CopyEndpointToDevAddr(endpoint, &response.devAddr);
922 FixUpClientResponse(&response);
924 if (responseInfo->info.payload)
926 result = OCParsePayload(&response.payload,
927 PAYLOAD_TYPE_PRESENCE,
928 responseInfo->info.payload,
929 responseInfo->info.payloadSize);
931 if(result != OC_STACK_OK)
933 OIC_LOG(ERROR, TAG, "Presence parse failed");
936 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
938 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
939 result = OC_STACK_ERROR;
942 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
943 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
944 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
947 if (presenceSubscribe)
949 if(cbNode->sequenceNumber == response.sequenceNumber)
951 OIC_LOG(INFO, TAG, "No presence change");
952 ResetPresenceTTL(cbNode, maxAge);
953 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
959 OIC_LOG(INFO, TAG, "Stopping presence");
960 response.result = OC_STACK_PRESENCE_STOPPED;
963 OICFree(cbNode->presence->timeOut);
964 OICFree(cbNode->presence);
965 cbNode->presence = NULL;
970 if(!cbNode->presence)
972 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
974 if(!(cbNode->presence))
976 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
977 result = OC_STACK_NO_MEMORY;
981 VERIFY_NON_NULL_V(cbNode->presence);
982 cbNode->presence->timeOut = NULL;
983 cbNode->presence->timeOut = (uint32_t *)
984 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
985 if(!(cbNode->presence->timeOut)){
987 "Could not allocate memory for cbNode->presence->timeOut");
988 OICFree(cbNode->presence);
989 result = OC_STACK_NO_MEMORY;
994 ResetPresenceTTL(cbNode, maxAge);
996 cbNode->sequenceNumber = response.sequenceNumber;
998 // Ensure that a filter is actually applied.
999 if( resourceTypeName && cbNode->filterResourceType)
1001 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1010 // This is the multicast case
1011 OCMulticastNode* mcNode = NULL;
1012 mcNode = GetMCPresenceNode(presenceUri);
1016 if(mcNode->nonce == response.sequenceNumber)
1018 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1021 mcNode->nonce = response.sequenceNumber;
1025 OIC_LOG(INFO, TAG, "Stopping presence");
1026 response.result = OC_STACK_PRESENCE_STOPPED;
1031 char* uri = OICStrdup(presenceUri);
1035 "No Memory for URI to store in the presence node");
1036 result = OC_STACK_NO_MEMORY;
1040 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1041 if(result == OC_STACK_NO_MEMORY)
1044 "No Memory for Multicast Presence Node");
1048 // presence node now owns uri
1051 // Ensure that a filter is actually applied.
1052 if(resourceTypeName && cbNode->filterResourceType)
1054 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1061 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1063 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1065 FindAndDeleteClientCB(cbNode);
1069 OCPayloadDestroy(response.payload);
1073 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1075 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1077 if(responseInfo->info.resourceUri &&
1078 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1080 HandlePresenceResponse(endPoint, responseInfo);
1084 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1085 responseInfo->info.tokenLength, NULL, NULL);
1087 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1088 responseInfo->info.tokenLength);
1092 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1093 if(responseInfo->result == CA_EMPTY)
1095 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1096 // We do not have a case for the client to receive a RESET
1097 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1099 //This is the case of receiving an ACK on a request to a slow resource!
1100 OIC_LOG(INFO, TAG, "This is a pure ACK");
1101 //TODO: should we inform the client
1102 // app that at least the request was received at the server?
1105 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1107 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1108 OIC_LOG(INFO, TAG, "Calling into application address space");
1110 OCClientResponse response =
1111 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1112 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1113 FixUpClientResponse(&response);
1114 response.resourceUri = responseInfo->info.resourceUri;
1115 memcpy(response.identity.id, responseInfo->info.identity.id,
1116 sizeof (response.identity.id));
1117 response.identity.id_length = responseInfo->info.identity.id_length;
1119 response.result = CAToOCStackResult(responseInfo->result);
1120 cbNode->callBack(cbNode->context,
1121 cbNode->handle, &response);
1122 FindAndDeleteClientCB(cbNode);
1126 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1127 OIC_LOG(INFO, TAG, "Calling into application address space");
1129 OCClientResponse response =
1130 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1131 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1132 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1133 FixUpClientResponse(&response);
1134 response.resourceUri = responseInfo->info.resourceUri;
1135 memcpy(response.identity.id, responseInfo->info.identity.id,
1136 sizeof (response.identity.id));
1137 response.identity.id_length = responseInfo->info.identity.id_length;
1139 response.result = CAToOCStackResult(responseInfo->result);
1141 if(responseInfo->info.payload &&
1142 responseInfo->info.payloadSize)
1144 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1145 // check the security resource
1146 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1148 type = PAYLOAD_TYPE_SECURITY;
1150 else if (cbNode->method == OC_REST_DISCOVER)
1152 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1153 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1155 type = PAYLOAD_TYPE_DISCOVERY;
1157 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1159 type = PAYLOAD_TYPE_DEVICE;
1161 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1163 type = PAYLOAD_TYPE_PLATFORM;
1165 #ifdef ROUTING_GATEWAY
1166 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1168 type = PAYLOAD_TYPE_REPRESENTATION;
1171 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1173 type = PAYLOAD_TYPE_RD;
1176 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1178 type = PAYLOAD_TYPE_REPRESENTATION;
1183 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1184 cbNode->method, cbNode->requestUri);
1188 else if (cbNode->method == OC_REST_GET ||
1189 cbNode->method == OC_REST_PUT ||
1190 cbNode->method == OC_REST_POST ||
1191 cbNode->method == OC_REST_OBSERVE ||
1192 cbNode->method == OC_REST_OBSERVE_ALL ||
1193 cbNode->method == OC_REST_DELETE)
1195 char targetUri[MAX_URI_LENGTH];
1196 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1197 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1198 if (strcmp(targetUri, cbNode->requestUri) == 0)
1200 type = PAYLOAD_TYPE_RD;
1202 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1204 type = PAYLOAD_TYPE_PLATFORM;
1206 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1208 type = PAYLOAD_TYPE_DEVICE;
1210 if (type == PAYLOAD_TYPE_INVALID)
1212 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1213 cbNode->method, cbNode->requestUri);
1214 type = PAYLOAD_TYPE_REPRESENTATION;
1219 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1220 cbNode->method, cbNode->requestUri);
1224 if(OC_STACK_OK != OCParsePayload(&response.payload,
1226 responseInfo->info.payload,
1227 responseInfo->info.payloadSize))
1229 OIC_LOG(ERROR, TAG, "Error converting payload");
1230 OCPayloadDestroy(response.payload);
1235 response.numRcvdVendorSpecificHeaderOptions = 0;
1236 if(responseInfo->info.numOptions > 0)
1239 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1240 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1243 uint32_t observationOption;
1244 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1245 for (observationOption=0, i=0;
1246 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1250 (observationOption << 8) | optionData[i];
1252 response.sequenceNumber = observationOption;
1254 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1259 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1262 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1264 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1265 OCPayloadDestroy(response.payload);
1269 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1271 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1272 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1276 if (cbNode->method == OC_REST_OBSERVE &&
1277 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1278 response.sequenceNumber <= cbNode->sequenceNumber)
1280 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1281 response.sequenceNumber);
1285 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1288 cbNode->sequenceNumber = response.sequenceNumber;
1290 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1292 FindAndDeleteClientCB(cbNode);
1296 // To keep discovery callbacks active.
1297 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1298 MILLISECONDS_PER_SECOND);
1302 //Need to send ACK when the response is CON
1303 if(responseInfo->info.type == CA_MSG_CONFIRM)
1305 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1306 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1309 OCPayloadDestroy(response.payload);
1316 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1317 if(responseInfo->result == CA_EMPTY)
1319 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1320 if(responseInfo->info.type == CA_MSG_RESET)
1322 OIC_LOG(INFO, TAG, "This is a RESET");
1323 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1324 OC_OBSERVER_NOT_INTERESTED);
1326 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1328 OIC_LOG(INFO, TAG, "This is a pure ACK");
1329 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1330 OC_OBSERVER_STILL_INTERESTED);
1333 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1335 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1336 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1337 OC_OBSERVER_FAILED_COMM);
1342 if(!cbNode && !observer)
1344 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1345 || myStackMode == OC_GATEWAY)
1347 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1348 if(responseInfo->result == CA_EMPTY)
1350 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1354 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1355 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1356 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1360 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1361 || myStackMode == OC_GATEWAY)
1363 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1364 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1366 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1367 responseInfo->info.messageId);
1369 if (responseInfo->info.type == CA_MSG_RESET)
1371 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1372 responseInfo->info.messageId);
1379 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1382 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1384 VERIFY_NON_NULL_NR(endPoint, FATAL);
1385 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1387 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1389 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1390 #ifdef ROUTING_GATEWAY
1391 bool needRIHandling = false;
1393 * Routing manager is going to update either of endpoint or response or both.
1394 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1395 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1398 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1400 if(ret != OC_STACK_OK || !needRIHandling)
1402 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1408 * Put source in sender endpoint so that the next packet from application can be routed to
1409 * proper destination and remove "RM" coap header option before passing request / response to
1410 * RI as this option will make no sense to either RI or application.
1412 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1413 (uint8_t *) &(responseInfo->info.numOptions),
1414 (CAEndpoint_t *) endPoint);
1417 OCHandleResponse(endPoint, responseInfo);
1419 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1423 * This function handles error response from CA
1424 * code shall be added to handle the errors
1426 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1428 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1430 if(NULL == endPoint)
1432 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1436 if(NULL == errrorInfo)
1438 OIC_LOG(ERROR, TAG, "errrorInfo is NULL");
1441 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1445 * This function sends out Direct Stack Responses. These are responses that are not coming
1446 * from the application entity handler. These responses have no payload and are usually ACKs,
1447 * RESETs or some error conditions that were caught by the stack.
1449 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1450 const CAResponseResult_t responseResult, const CAMessageType_t type,
1451 const uint8_t numOptions, const CAHeaderOption_t *options,
1452 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1454 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1455 CAResponseInfo_t respInfo = {
1456 .result = responseResult
1458 respInfo.info.messageId = coapID;
1459 respInfo.info.numOptions = numOptions;
1461 if (respInfo.info.numOptions)
1463 respInfo.info.options =
1464 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1465 memcpy (respInfo.info.options, options,
1466 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1470 respInfo.info.payload = NULL;
1471 respInfo.info.token = token;
1472 respInfo.info.tokenLength = tokenLength;
1473 respInfo.info.type = type;
1474 respInfo.info.resourceUri = OICStrdup (resourceUri);
1475 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1477 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1478 // Add the destination to route option from the endpoint->routeData.
1479 bool doPost = false;
1480 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1481 if(OC_STACK_OK != result)
1483 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1488 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1489 CARequestInfo_t reqInfo = {.method = CA_POST };
1490 /* The following initialization is not done in a single initializer block as in
1491 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1492 * does not have designated initalizers. This is a work-around for now.
1494 reqInfo.info.type = CA_MSG_NONCONFIRM;
1495 reqInfo.info.messageId = coapID;
1496 reqInfo.info.tokenLength = tokenLength;
1497 reqInfo.info.token = token;
1498 reqInfo.info.numOptions = respInfo.info.numOptions;
1499 reqInfo.info.payload = NULL;
1500 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1501 if (reqInfo.info.numOptions)
1503 reqInfo.info.options =
1504 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1505 if (NULL == reqInfo.info.options)
1507 OIC_LOG(ERROR, TAG, "Calloc failed");
1508 return OC_STACK_NO_MEMORY;
1510 memcpy (reqInfo.info.options, respInfo.info.options,
1511 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1514 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1515 OICFree (reqInfo.info.resourceUri);
1516 OICFree (reqInfo.info.options);
1517 OICFree (respInfo.info.resourceUri);
1518 OICFree (respInfo.info.options);
1519 if (CA_STATUS_OK != caResult)
1521 OIC_LOG(ERROR, TAG, "CASendRequest error");
1522 return CAResultToOCResult(caResult);
1528 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1530 // resourceUri in the info field is cloned in the CA layer and
1531 // thus ownership is still here.
1532 OICFree (respInfo.info.resourceUri);
1533 OICFree (respInfo.info.options);
1534 if(CA_STATUS_OK != caResult)
1536 OIC_LOG(ERROR, TAG, "CASendResponse error");
1537 return CAResultToOCResult(caResult);
1540 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1544 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1546 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1547 OCStackResult result = OC_STACK_ERROR;
1548 if(!protocolRequest)
1550 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1551 return OC_STACK_INVALID_PARAM;
1554 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1555 protocolRequest->tokenLength);
1558 OIC_LOG(INFO, TAG, "This is a new Server Request");
1559 result = AddServerRequest(&request, protocolRequest->coapID,
1560 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1561 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1562 protocolRequest->observationOption, protocolRequest->qos,
1563 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1564 protocolRequest->payload, protocolRequest->requestToken,
1565 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1566 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1567 &protocolRequest->devAddr);
1568 if (OC_STACK_OK != result)
1570 OIC_LOG(ERROR, TAG, "Error adding server request");
1576 OIC_LOG(ERROR, TAG, "Out of Memory");
1577 return OC_STACK_NO_MEMORY;
1580 if(!protocolRequest->reqMorePacket)
1582 request->requestComplete = 1;
1587 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1590 if(request->requestComplete)
1592 OIC_LOG(INFO, TAG, "This Server Request is complete");
1593 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1594 OCResource *resource = NULL;
1595 result = DetermineResourceHandling (request, &resHandling, &resource);
1596 if (result == OC_STACK_OK)
1598 result = ProcessRequest(resHandling, resource, request);
1603 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1604 result = OC_STACK_CONTINUE;
1609 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1611 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1614 if (requestInfo->info.resourceUri &&
1615 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1617 HandleKeepAliveRequest(endPoint, requestInfo);
1622 OCStackResult requestResult = OC_STACK_ERROR;
1624 if(myStackMode == OC_CLIENT)
1626 //TODO: should the client be responding to requests?
1630 OCServerProtocolRequest serverRequest = {0};
1632 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1634 char * uriWithoutQuery = NULL;
1635 char * query = NULL;
1637 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1639 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1641 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1644 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1645 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1647 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1649 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1650 OICFree(uriWithoutQuery);
1654 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1655 OICFree(uriWithoutQuery);
1662 if(strlen(query) < MAX_QUERY_LENGTH)
1664 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1669 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1675 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1677 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1678 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1679 if (!serverRequest.payload)
1681 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1684 memcpy (serverRequest.payload, requestInfo->info.payload,
1685 requestInfo->info.payloadSize);
1689 serverRequest.reqTotalSize = 0;
1692 switch (requestInfo->method)
1695 serverRequest.method = OC_REST_GET;
1698 serverRequest.method = OC_REST_PUT;
1701 serverRequest.method = OC_REST_POST;
1704 serverRequest.method = OC_REST_DELETE;
1707 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1708 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1709 requestInfo->info.type, requestInfo->info.numOptions,
1710 requestInfo->info.options, requestInfo->info.token,
1711 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1712 OICFree(serverRequest.payload);
1716 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1717 requestInfo->info.tokenLength);
1719 serverRequest.tokenLength = requestInfo->info.tokenLength;
1720 if (serverRequest.tokenLength) {
1722 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1724 if (!serverRequest.requestToken)
1726 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1727 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1728 requestInfo->info.type, requestInfo->info.numOptions,
1729 requestInfo->info.options, requestInfo->info.token,
1730 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1731 OICFree(serverRequest.payload);
1734 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1737 switch (requestInfo->info.acceptFormat)
1739 case CA_FORMAT_APPLICATION_CBOR:
1740 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1742 case CA_FORMAT_UNDEFINED:
1743 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1746 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1749 if (requestInfo->info.type == CA_MSG_CONFIRM)
1751 serverRequest.qos = OC_HIGH_QOS;
1755 serverRequest.qos = OC_LOW_QOS;
1757 // CA does not need the following field
1758 // Are we sure CA does not need them? how is it responding to multicast
1759 serverRequest.delayedResNeeded = 0;
1761 serverRequest.coapID = requestInfo->info.messageId;
1763 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1765 // copy vendor specific header options
1766 uint8_t tempNum = (requestInfo->info.numOptions);
1768 // Assume no observation requested and it is a pure GET.
1769 // If obs registration/de-registration requested it'll be fetched from the
1770 // options in GetObserveHeaderOption()
1771 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1773 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1774 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1777 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1778 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1779 requestInfo->info.type, requestInfo->info.numOptions,
1780 requestInfo->info.options, requestInfo->info.token,
1781 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1782 OICFree(serverRequest.payload);
1783 OICFree(serverRequest.requestToken);
1786 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1787 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1789 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1790 sizeof(CAHeaderOption_t)*tempNum);
1793 requestResult = HandleStackRequests (&serverRequest);
1795 // Send ACK to client as precursor to slow response
1796 if(requestResult == OC_STACK_SLOW_RESOURCE)
1798 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1799 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1801 else if(requestResult != OC_STACK_OK)
1803 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1805 CAResponseResult_t stackResponse =
1806 OCToCAStackResult(requestResult, serverRequest.method);
1808 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1809 requestInfo->info.type, requestInfo->info.numOptions,
1810 requestInfo->info.options, requestInfo->info.token,
1811 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1813 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1814 // The token is copied in there, and is thus still owned by this function.
1815 OICFree(serverRequest.payload);
1816 OICFree(serverRequest.requestToken);
1817 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1820 //This function will be called back by CA layer when a request is received
1821 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1823 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1826 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1832 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1836 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1837 #ifdef ROUTING_GATEWAY
1838 bool needRIHandling = false;
1839 bool isEmptyMsg = false;
1841 * Routing manager is going to update either of endpoint or request or both.
1842 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1843 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1844 * destination. It can also remove "RM" coap header option before passing request / response to
1845 * RI as this option will make no sense to either RI or application.
1847 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1848 &needRIHandling, &isEmptyMsg);
1849 if(OC_STACK_OK != ret || !needRIHandling)
1851 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1857 * Put source in sender endpoint so that the next packet from application can be routed to
1858 * proper destination and remove RM header option.
1860 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1861 (uint8_t *) &(requestInfo->info.numOptions),
1862 (CAEndpoint_t *) endPoint);
1864 #ifdef ROUTING_GATEWAY
1868 * In Gateways, the MSGType in route option is used to check if the actual
1869 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
1870 * EMPTY response is sent in the form of POST request which need to be changed
1871 * to a EMPTY response by RM. This translation is done in this part of the code.
1873 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1874 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1875 .info.messageId = requestInfo->info.messageId,
1876 .info.type = CA_MSG_ACKNOWLEDGE};
1877 OCHandleResponse(endPoint, &respInfo);
1883 // Normal handling of the packet
1884 OCHandleRequests(endPoint, requestInfo);
1886 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1889 bool validatePlatformInfo(OCPlatformInfo info)
1892 if (!info.platformID)
1894 OIC_LOG(ERROR, TAG, "No platform ID found.");
1898 if (info.manufacturerName)
1900 size_t lenManufacturerName = strlen(info.manufacturerName);
1902 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1904 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1910 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1914 if (info.manufacturerUrl)
1916 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1918 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1925 //-----------------------------------------------------------------------------
1927 //-----------------------------------------------------------------------------
1929 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1932 !raInfo->username ||
1933 !raInfo->hostname ||
1934 !raInfo->xmpp_domain)
1937 return OC_STACK_INVALID_PARAM;
1939 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1940 gRASetInfo = (result == OC_STACK_OK)? true : false;
1946 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1950 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1953 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1955 if(stackState == OC_STACK_INITIALIZED)
1957 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1958 OCStop() between them are ignored.");
1962 #ifndef ROUTING_GATEWAY
1963 if (OC_GATEWAY == mode)
1965 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
1966 return OC_STACK_INVALID_PARAM;
1973 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1974 return OC_STACK_ERROR;
1978 OCStackResult result = OC_STACK_ERROR;
1979 OIC_LOG(INFO, TAG, "Entering OCInit");
1982 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1983 || (mode == OC_GATEWAY)))
1985 OIC_LOG(ERROR, TAG, "Invalid mode");
1986 return OC_STACK_ERROR;
1990 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1992 caglobals.client = true;
1994 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1996 caglobals.server = true;
1999 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2000 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2002 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2004 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2005 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2007 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2010 defaultDeviceHandler = NULL;
2011 defaultDeviceHandlerCallbackParameter = NULL;
2013 result = CAResultToOCResult(CAInitialize());
2014 VERIFY_SUCCESS(result, OC_STACK_OK);
2016 result = CAResultToOCResult(OCSelectNetwork());
2017 VERIFY_SUCCESS(result, OC_STACK_OK);
2019 switch (myStackMode)
2022 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2023 result = CAResultToOCResult(CAStartDiscoveryServer());
2024 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2027 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2028 result = CAResultToOCResult(CAStartListeningServer());
2029 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2031 case OC_CLIENT_SERVER:
2033 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2034 result = CAResultToOCResult(CAStartListeningServer());
2035 if(result == OC_STACK_OK)
2037 result = CAResultToOCResult(CAStartDiscoveryServer());
2041 VERIFY_SUCCESS(result, OC_STACK_OK);
2044 CARegisterKeepAliveHandler(HandleKeepAliveConnCB, HandleKeepAliveDisconnCB);
2047 #ifdef WITH_PRESENCE
2048 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2049 #endif // WITH_PRESENCE
2051 //Update Stack state to initialized
2052 stackState = OC_STACK_INITIALIZED;
2054 // Initialize resource
2055 if(myStackMode != OC_CLIENT)
2057 result = initResources();
2060 // Initialize the SRM Policy Engine
2061 if(result == OC_STACK_OK)
2063 result = SRMInitPolicyEngine();
2064 // TODO after BeachHead delivery: consolidate into single SRMInit()
2066 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2067 RMSetStackMode(mode);
2068 #ifdef ROUTING_GATEWAY
2069 if (OC_GATEWAY == myStackMode)
2071 result = RMInitialize();
2077 if (result == OC_STACK_OK)
2079 result = InitializeKeepAlive(myStackMode);
2084 if(result != OC_STACK_OK)
2086 OIC_LOG(ERROR, TAG, "Stack initialization error");
2087 deleteAllResources();
2089 stackState = OC_STACK_UNINITIALIZED;
2094 OCStackResult OCStop()
2096 OIC_LOG(INFO, TAG, "Entering OCStop");
2098 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2100 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2103 else if (stackState != OC_STACK_INITIALIZED)
2105 OIC_LOG(ERROR, TAG, "Stack not initialized");
2106 return OC_STACK_ERROR;
2109 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2111 #ifdef WITH_PRESENCE
2112 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2113 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2114 presenceResource.presenceTTL = 0;
2115 #endif // WITH_PRESENCE
2117 #ifdef ROUTING_GATEWAY
2118 if (OC_GATEWAY == myStackMode)
2125 TerminateKeepAlive(myStackMode);
2128 // Free memory dynamically allocated for resources
2129 deleteAllResources();
2131 DeletePlatformInfo();
2133 // Remove all observers
2134 DeleteObserverList();
2135 // Remove all the client callbacks
2136 DeleteClientCBList();
2138 // De-init the SRM Policy Engine
2139 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2140 SRMDeInitPolicyEngine();
2143 stackState = OC_STACK_UNINITIALIZED;
2147 OCStackResult OCStartMulticastServer()
2149 if(stackState != OC_STACK_INITIALIZED)
2151 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2152 return OC_STACK_ERROR;
2154 CAResult_t ret = CAStartListeningServer();
2155 if (CA_STATUS_OK != ret)
2157 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2158 return OC_STACK_ERROR;
2163 OCStackResult OCStopMulticastServer()
2165 CAResult_t ret = CAStopListeningServer();
2166 if (CA_STATUS_OK != ret)
2168 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2169 return OC_STACK_ERROR;
2174 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2179 return CA_MSG_CONFIRM;
2184 return CA_MSG_NONCONFIRM;
2188 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2192 query = strchr (inputUri, '?');
2196 if((query - inputUri) > MAX_URI_LENGTH)
2198 return OC_STACK_INVALID_URI;
2201 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2203 return OC_STACK_INVALID_QUERY;
2206 else if(uriLen > MAX_URI_LENGTH)
2208 return OC_STACK_INVALID_URI;
2214 * A request uri consists of the following components in order:
2217 * CoAP over UDP prefix "coap://"
2218 * CoAP over TCP prefix "coap+tcp://"
2220 * IPv6 address "[1234::5678]"
2221 * IPv4 address "192.168.1.1"
2222 * optional port ":5683"
2223 * resource uri "/oc/core..."
2225 * for PRESENCE requests, extract resource type.
2227 static OCStackResult ParseRequestUri(const char *fullUri,
2228 OCTransportAdapter adapter,
2229 OCTransportFlags flags,
2230 OCDevAddr **devAddr,
2232 char **resourceType)
2234 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2236 OCStackResult result = OC_STACK_OK;
2237 OCDevAddr *da = NULL;
2241 // provide defaults for all returned values
2248 *resourceUri = NULL;
2252 *resourceType = NULL;
2255 // delimit url prefix, if any
2256 const char *start = fullUri;
2257 char *slash2 = strstr(start, "//");
2262 char *slash = strchr(start, '/');
2265 return OC_STACK_INVALID_URI;
2268 // process url scheme
2269 size_t prefixLen = slash2 - fullUri;
2273 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2279 // TODO: this logic should come in with unit tests exercising the various strings
2280 // processs url prefix, if any
2281 size_t urlLen = slash - start;
2285 if (urlLen && devAddr)
2286 { // construct OCDevAddr
2287 if (start[0] == '[')
2289 char *close = strchr(++start, ']');
2290 if (!close || close > slash)
2292 return OC_STACK_INVALID_URI;
2295 if (close[1] == ':')
2299 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2300 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2304 char *dot = strchr(start, '.');
2305 if (dot && dot < slash)
2307 colon = strchr(start, ':');
2308 end = (colon && colon < slash) ? colon : slash;
2312 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2316 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2317 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2326 if (len >= sizeof(da->addr))
2328 return OC_STACK_INVALID_URI;
2330 // collect port, if any
2331 if (colon && colon < slash)
2333 for (colon++; colon < slash; colon++)
2336 if (c < '0' || c > '9')
2338 return OC_STACK_INVALID_URI;
2340 port = 10 * port + c - '0';
2345 if (len >= sizeof(da->addr))
2347 return OC_STACK_INVALID_URI;
2350 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2353 return OC_STACK_NO_MEMORY;
2355 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2357 da->adapter = adapter;
2359 if (!strncmp(fullUri, "coaps:", 6))
2361 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2366 // process resource uri, if any
2368 { // request uri and query
2369 size_t ulen = strlen(slash); // resource uri length
2370 size_t tlen = 0; // resource type length
2373 static const char strPresence[] = "/oic/ad?rt=";
2374 static const size_t lenPresence = sizeof(strPresence) - 1;
2375 if (!strncmp(slash, strPresence, lenPresence))
2377 type = slash + lenPresence;
2378 tlen = ulen - lenPresence;
2383 *resourceUri = (char *)OICMalloc(ulen + 1);
2386 result = OC_STACK_NO_MEMORY;
2389 strcpy(*resourceUri, slash);
2392 if (type && resourceType)
2394 *resourceType = (char *)OICMalloc(tlen + 1);
2397 result = OC_STACK_NO_MEMORY;
2401 OICStrcpy(*resourceType, (tlen+1), type);
2408 // free all returned values
2415 OICFree(*resourceUri);
2419 OICFree(*resourceType);
2424 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2425 char *resourceUri, char **requestUri)
2427 char uri[CA_MAX_URI_LENGTH];
2429 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2431 *requestUri = OICStrdup(uri);
2434 return OC_STACK_NO_MEMORY;
2441 * Discover or Perform requests on a specified resource
2443 OCStackResult OCDoResource(OCDoHandle *handle,
2445 const char *requestUri,
2446 const OCDevAddr *destination,
2448 OCConnectivityType connectivityType,
2449 OCQualityOfService qos,
2450 OCCallbackData *cbData,
2451 OCHeaderOption *options,
2454 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2456 // Validate input parameters
2457 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2458 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2459 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2461 OCStackResult result = OC_STACK_ERROR;
2462 CAResult_t caResult;
2463 CAToken_t token = NULL;
2464 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2465 ClientCB *clientCB = NULL;
2466 OCDoHandle resHandle = NULL;
2467 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2468 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2470 OCTransportAdapter adapter;
2471 OCTransportFlags flags;
2472 // the request contents are put here
2473 CARequestInfo_t requestInfo = {.method = CA_GET};
2474 // requestUri will be parsed into the following three variables
2475 OCDevAddr *devAddr = NULL;
2476 char *resourceUri = NULL;
2477 char *resourceType = NULL;
2479 // This validation is broken, but doesn't cause harm
2480 size_t uriLen = strlen(requestUri );
2481 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2487 * Support original behavior with address on resourceUri argument.
2489 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2490 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2492 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2494 if (result != OC_STACK_OK)
2496 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2503 case OC_REST_OBSERVE:
2504 case OC_REST_OBSERVE_ALL:
2505 case OC_REST_CANCEL_OBSERVE:
2506 requestInfo.method = CA_GET;
2509 requestInfo.method = CA_PUT;
2512 requestInfo.method = CA_POST;
2514 case OC_REST_DELETE:
2515 requestInfo.method = CA_DELETE;
2517 case OC_REST_DISCOVER:
2519 if (destination || devAddr)
2521 requestInfo.isMulticast = false;
2525 tmpDevAddr.adapter = adapter;
2526 tmpDevAddr.flags = flags;
2527 destination = &tmpDevAddr;
2528 requestInfo.isMulticast = true;
2530 // CA_DISCOVER will become GET and isMulticast
2531 requestInfo.method = CA_GET;
2533 #ifdef WITH_PRESENCE
2534 case OC_REST_PRESENCE:
2535 // Replacing method type with GET because "presence"
2536 // is a stack layer only implementation.
2537 requestInfo.method = CA_GET;
2541 result = OC_STACK_INVALID_METHOD;
2545 if (!devAddr && !destination)
2547 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2548 result = OC_STACK_INVALID_PARAM;
2552 /* If not original behavior, use destination argument */
2553 if (destination && !devAddr)
2555 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2558 result = OC_STACK_NO_MEMORY;
2561 *devAddr = *destination;
2564 resHandle = GenerateInvocationHandle();
2567 result = OC_STACK_NO_MEMORY;
2571 caResult = CAGenerateToken(&token, tokenLength);
2572 if (caResult != CA_STATUS_OK)
2574 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2575 result= OC_STACK_ERROR;
2579 // fill in request data
2580 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2581 requestInfo.info.token = token;
2582 requestInfo.info.tokenLength = tokenLength;
2583 requestInfo.info.resourceUri = resourceUri;
2585 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2587 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2588 options, numOptions, OC_OBSERVE_REGISTER);
2589 if (result != OC_STACK_OK)
2593 requestInfo.info.numOptions = numOptions + 1;
2597 requestInfo.info.numOptions = numOptions;
2598 requestInfo.info.options =
2599 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2600 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2601 numOptions * sizeof(CAHeaderOption_t));
2604 CopyDevAddrToEndpoint(devAddr, &endpoint);
2609 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2612 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2615 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2619 requestInfo.info.payload = NULL;
2620 requestInfo.info.payloadSize = 0;
2621 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2624 if (result != OC_STACK_OK)
2626 OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2630 // prepare for response
2631 #ifdef WITH_PRESENCE
2632 if (method == OC_REST_PRESENCE)
2634 char *presenceUri = NULL;
2635 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2636 if (OC_STACK_OK != result)
2641 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2642 // Presence notification will form a canonical uri to
2643 // look for callbacks into the application.
2644 resourceUri = presenceUri;
2648 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2649 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2650 method, devAddr, resourceUri, resourceType, ttl);
2651 if (OC_STACK_OK != result)
2656 devAddr = NULL; // Client CB list entry now owns it
2657 resourceUri = NULL; // Client CB list entry now owns it
2658 resourceType = NULL; // Client CB list entry now owns it
2661 result = OCSendRequest(&endpoint, &requestInfo);
2662 if (OC_STACK_OK != result)
2669 *handle = resHandle;
2673 if (result != OC_STACK_OK)
2675 OIC_LOG(ERROR, TAG, "OCDoResource error");
2676 FindAndDeleteClientCB(clientCB);
2677 CADestroyToken(token);
2685 // This is the owner of the payload object, so we free it
2686 OCPayloadDestroy(payload);
2687 OICFree(requestInfo.info.payload);
2689 OICFree(resourceUri);
2690 OICFree(resourceType);
2691 OICFree(requestInfo.info.options);
2695 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2699 * This ftn is implemented one of two ways in the case of observation:
2701 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2702 * Remove the callback associated on client side.
2703 * When the next notification comes in from server,
2704 * reply with RESET message to server.
2705 * Keep in mind that the server will react to RESET only
2706 * if the last notification was sent as CON
2708 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2709 * and it is associated with an observe request
2710 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2711 * Send CON Observe request to server with
2712 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2713 * Remove the callback associated on client side.
2715 OCStackResult ret = OC_STACK_OK;
2716 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2717 CARequestInfo_t requestInfo = {.method = CA_GET};
2721 return OC_STACK_INVALID_PARAM;
2724 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2727 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2728 return OC_STACK_ERROR;
2731 switch (clientCB->method)
2733 case OC_REST_OBSERVE:
2734 case OC_REST_OBSERVE_ALL:
2736 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2737 clientCB->requestUri);
2738 if (qos != OC_HIGH_QOS)
2740 FindAndDeleteClientCB(clientCB);
2744 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2746 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2747 requestInfo.info.token = clientCB->token;
2748 requestInfo.info.tokenLength = clientCB->tokenLength;
2750 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2751 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2753 return OC_STACK_ERROR;
2755 requestInfo.info.numOptions = numOptions + 1;
2756 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2758 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2760 ret = OCSendRequest(&endpoint, &requestInfo);
2762 if (requestInfo.info.options)
2764 OICFree (requestInfo.info.options);
2766 if (requestInfo.info.resourceUri)
2768 OICFree (requestInfo.info.resourceUri);
2773 case OC_REST_DISCOVER:
2774 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2775 clientCB->requestUri);
2776 FindAndDeleteClientCB(clientCB);
2779 #ifdef WITH_PRESENCE
2780 case OC_REST_PRESENCE:
2781 FindAndDeleteClientCB(clientCB);
2786 ret = OC_STACK_INVALID_METHOD;
2794 * @brief Register Persistent storage callback.
2795 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2797 * OC_STACK_OK - No errors; Success
2798 * OC_STACK_INVALID_PARAM - Invalid parameter
2800 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2802 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2803 if(!persistentStorageHandler)
2805 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2806 return OC_STACK_INVALID_PARAM;
2810 if( !persistentStorageHandler->open ||
2811 !persistentStorageHandler->close ||
2812 !persistentStorageHandler->read ||
2813 !persistentStorageHandler->unlink ||
2814 !persistentStorageHandler->write)
2816 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2817 return OC_STACK_INVALID_PARAM;
2820 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2823 #ifdef WITH_PRESENCE
2825 OCStackResult OCProcessPresence()
2827 OCStackResult result = OC_STACK_OK;
2829 // the following line floods the log with messages that are irrelevant
2830 // to most purposes. Uncomment as needed.
2831 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2832 ClientCB* cbNode = NULL;
2833 OCClientResponse clientResponse;
2834 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2836 LL_FOREACH(cbList, cbNode)
2838 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2843 uint32_t now = GetTicks(0);
2844 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2845 cbNode->presence->TTLlevel);
2846 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2848 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2853 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2855 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2856 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2858 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2860 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2862 clientResponse.sequenceNumber = 0;
2863 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2864 clientResponse.devAddr = *cbNode->devAddr;
2865 FixUpClientResponse(&clientResponse);
2866 clientResponse.payload = NULL;
2868 // Increment the TTLLevel (going to a next state), so we don't keep
2869 // sending presence notification to client.
2870 cbNode->presence->TTLlevel++;
2871 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2872 cbNode->presence->TTLlevel);
2874 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2875 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2877 FindAndDeleteClientCB(cbNode);
2881 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2886 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2887 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2888 CARequestInfo_t requestInfo = {.method = CA_GET};
2890 OIC_LOG(DEBUG, TAG, "time to test server presence");
2892 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2894 requestData.type = CA_MSG_NONCONFIRM;
2895 requestData.token = cbNode->token;
2896 requestData.tokenLength = cbNode->tokenLength;
2897 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2898 requestInfo.method = CA_GET;
2899 requestInfo.info = requestData;
2901 result = OCSendRequest(&endpoint, &requestInfo);
2902 if (OC_STACK_OK != result)
2907 cbNode->presence->TTLlevel++;
2908 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2911 if (result != OC_STACK_OK)
2913 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2918 #endif // WITH_PRESENCE
2920 OCStackResult OCProcess()
2922 #ifdef WITH_PRESENCE
2923 OCProcessPresence();
2925 CAHandleRequestResponse();
2927 #ifdef ROUTING_GATEWAY
2937 #ifdef WITH_PRESENCE
2938 OCStackResult OCStartPresence(const uint32_t ttl)
2940 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2941 OCChangeResourceProperty(
2942 &(((OCResource *)presenceResource.handle)->resourceProperties),
2945 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2947 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2948 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2952 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2953 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2957 presenceResource.presenceTTL = ttl;
2959 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2961 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2963 presenceState = OC_PRESENCE_INITIALIZED;
2965 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2967 CAToken_t caToken = NULL;
2968 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2969 if (caResult != CA_STATUS_OK)
2971 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2972 CADestroyToken(caToken);
2973 return OC_STACK_ERROR;
2976 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2977 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2978 CADestroyToken(caToken);
2981 // Each time OCStartPresence is called
2982 // a different random 32-bit integer number is used
2983 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2985 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2986 OC_PRESENCE_TRIGGER_CREATE);
2989 OCStackResult OCStopPresence()
2991 OCStackResult result = OC_STACK_ERROR;
2993 if(presenceResource.handle)
2995 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2997 // make resource inactive
2998 result = OCChangeResourceProperty(
2999 &(((OCResource *) presenceResource.handle)->resourceProperties),
3003 if(result != OC_STACK_OK)
3006 "Changing the presence resource properties to ACTIVE not successful");
3010 return SendStopNotification();
3014 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3015 void* callbackParameter)
3017 defaultDeviceHandler = entityHandler;
3018 defaultDeviceHandlerCallbackParameter = callbackParameter;
3023 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3025 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3027 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3029 if (validatePlatformInfo(platformInfo))
3031 return SavePlatformInfo(platformInfo);
3035 return OC_STACK_INVALID_PARAM;
3040 return OC_STACK_ERROR;
3044 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3046 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3048 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3050 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3051 return OC_STACK_INVALID_PARAM;
3054 if (deviceInfo.types)
3056 OCStringLL *type = deviceInfo.types;
3057 OCResource *resource = findResource((OCResource *) deviceResource);
3060 return OC_STACK_INVALID_PARAM;
3062 deleteResourceType(resource->rsrcType);
3063 resource->rsrcType = NULL;
3067 OCBindResourceTypeToResource(deviceResource, type->value);
3071 return SaveDeviceInfo(deviceInfo);
3074 OCStackResult OCCreateResource(OCResourceHandle *handle,
3075 const char *resourceTypeName,
3076 const char *resourceInterfaceName,
3077 const char *uri, OCEntityHandler entityHandler,
3078 void* callbackParam,
3079 uint8_t resourceProperties)
3082 OCResource *pointer = NULL;
3083 OCStackResult result = OC_STACK_ERROR;
3085 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3087 if(myStackMode == OC_CLIENT)
3089 return OC_STACK_INVALID_PARAM;
3091 // Validate parameters
3092 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3094 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3095 return OC_STACK_INVALID_URI;
3097 // Is it presented during resource discovery?
3098 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3100 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3101 return OC_STACK_INVALID_PARAM;
3104 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3106 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3109 // Make sure resourceProperties bitmask has allowed properties specified
3110 if (resourceProperties
3111 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3112 OC_EXPLICIT_DISCOVERABLE))
3114 OIC_LOG(ERROR, TAG, "Invalid property");
3115 return OC_STACK_INVALID_PARAM;
3118 // If the headResource is NULL, then no resources have been created...
3119 pointer = headResource;
3122 // At least one resources is in the resource list, so we need to search for
3123 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3126 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3128 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3129 return OC_STACK_INVALID_PARAM;
3131 pointer = pointer->next;
3134 // Create the pointer and insert it into the resource list
3135 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3138 result = OC_STACK_NO_MEMORY;
3141 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3143 insertResource(pointer);
3146 pointer->uri = OICStrdup(uri);
3149 result = OC_STACK_NO_MEMORY;
3153 // Set properties. Set OC_ACTIVE
3154 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3157 // Add the resourcetype to the resource
3158 result = BindResourceTypeToResource(pointer, resourceTypeName);
3159 if (result != OC_STACK_OK)
3161 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3165 // Add the resourceinterface to the resource
3166 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3167 if (result != OC_STACK_OK)
3169 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3173 // If an entity handler has been passed, attach it to the newly created
3174 // resource. Otherwise, set the default entity handler.
3177 pointer->entityHandler = entityHandler;
3178 pointer->entityHandlerCallbackParam = callbackParam;
3182 pointer->entityHandler = defaultResourceEHandler;
3183 pointer->entityHandlerCallbackParam = NULL;
3186 // Initialize a pointer indicating child resources in case of collection
3187 pointer->rsrcChildResourcesHead = NULL;
3190 result = OC_STACK_OK;
3192 #ifdef WITH_PRESENCE
3193 if (presenceResource.handle)
3195 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3196 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3200 if (result != OC_STACK_OK)
3202 // Deep delete of resource and other dynamic elements that it contains
3203 deleteResource(pointer);
3208 OCStackResult OCBindResource(
3209 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3211 OCResource *resource = NULL;
3212 OCChildResource *tempChildResource = NULL;
3213 OCChildResource *newChildResource = NULL;
3215 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3217 // Validate parameters
3218 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3219 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3220 // Container cannot contain itself
3221 if (collectionHandle == resourceHandle)
3223 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3224 return OC_STACK_INVALID_PARAM;
3227 // Use the handle to find the resource in the resource linked list
3228 resource = findResource((OCResource *) collectionHandle);
3231 OIC_LOG(ERROR, TAG, "Collection handle not found");
3232 return OC_STACK_INVALID_PARAM;
3235 // Look for an open slot to add add the child resource.
3236 // If found, add it and return success
3238 tempChildResource = resource->rsrcChildResourcesHead;
3240 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3242 // TODO: what if one of child resource was deregistered without unbinding?
3243 tempChildResource = tempChildResource->next;
3246 // Do memory allocation for child resource
3247 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3248 if(!newChildResource)
3250 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3251 return OC_STACK_ERROR;
3254 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3255 newChildResource->next = NULL;
3257 if(!resource->rsrcChildResourcesHead)
3259 resource->rsrcChildResourcesHead = newChildResource;
3262 tempChildResource->next = newChildResource;
3265 OIC_LOG(INFO, TAG, "resource bound");
3267 #ifdef WITH_PRESENCE
3268 if (presenceResource.handle)
3270 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3271 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3272 OC_PRESENCE_TRIGGER_CHANGE);
3279 OCStackResult OCUnBindResource(
3280 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3282 OCResource *resource = NULL;
3283 OCChildResource *tempChildResource = NULL;
3284 OCChildResource *tempLastChildResource = NULL;
3286 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3288 // Validate parameters
3289 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3290 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3291 // Container cannot contain itself
3292 if (collectionHandle == resourceHandle)
3294 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3295 return OC_STACK_INVALID_PARAM;
3298 // Use the handle to find the resource in the resource linked list
3299 resource = findResource((OCResource *) collectionHandle);
3302 OIC_LOG(ERROR, TAG, "Collection handle not found");
3303 return OC_STACK_INVALID_PARAM;
3306 // Look for an open slot to add add the child resource.
3307 // If found, add it and return success
3308 if(!resource->rsrcChildResourcesHead)
3310 OIC_LOG(INFO, TAG, "resource not found in collection");
3312 // Unable to add resourceHandle, so return error
3313 return OC_STACK_ERROR;
3317 tempChildResource = resource->rsrcChildResourcesHead;
3319 while (tempChildResource)
3321 if(tempChildResource->rsrcResource == resourceHandle)
3323 // if resource going to be unbinded is the head one.
3324 if( tempChildResource == resource->rsrcChildResourcesHead )
3326 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3327 OICFree(resource->rsrcChildResourcesHead);
3328 resource->rsrcChildResourcesHead = temp;
3333 OCChildResource *temp = tempChildResource->next;
3334 OICFree(tempChildResource);
3335 tempLastChildResource->next = temp;
3339 OIC_LOG(INFO, TAG, "resource unbound");
3341 // Send notification when resource is unbounded successfully.
3342 #ifdef WITH_PRESENCE
3343 if (presenceResource.handle)
3345 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3346 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3347 OC_PRESENCE_TRIGGER_CHANGE);
3350 tempChildResource = NULL;
3351 tempLastChildResource = NULL;
3357 tempLastChildResource = tempChildResource;
3358 tempChildResource = tempChildResource->next;
3361 OIC_LOG(INFO, TAG, "resource not found in collection");
3363 tempChildResource = NULL;
3364 tempLastChildResource = NULL;
3366 // Unable to add resourceHandle, so return error
3367 return OC_STACK_ERROR;
3370 // Precondition is that the parameter has been checked to not equal NULL.
3371 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3373 if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
3379 while (resourceItemName[index] != '\0')
3381 if (resourceItemName[index] != '.' &&
3382 resourceItemName[index] != '-' &&
3383 (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
3384 (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3393 OCStackResult BindResourceTypeToResource(OCResource* resource,
3394 const char *resourceTypeName)
3396 OCResourceType *pointer = NULL;
3398 OCStackResult result = OC_STACK_ERROR;
3400 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3402 if (!ValidateResourceTypeInterface(resourceTypeName))
3404 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3405 return OC_STACK_INVALID_PARAM;
3408 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3411 result = OC_STACK_NO_MEMORY;
3415 str = OICStrdup(resourceTypeName);
3418 result = OC_STACK_NO_MEMORY;
3421 pointer->resourcetypename = str;
3422 pointer->next = NULL;
3424 insertResourceType(resource, pointer);
3425 result = OC_STACK_OK;
3428 if (result != OC_STACK_OK)
3437 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3438 const char *resourceInterfaceName)
3440 OCResourceInterface *pointer = NULL;
3442 OCStackResult result = OC_STACK_ERROR;
3444 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3446 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3448 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3449 return OC_STACK_INVALID_PARAM;
3452 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3454 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3457 result = OC_STACK_NO_MEMORY;
3461 str = OICStrdup(resourceInterfaceName);
3464 result = OC_STACK_NO_MEMORY;
3467 pointer->name = str;
3469 // Bind the resourceinterface to the resource
3470 insertResourceInterface(resource, pointer);
3472 result = OC_STACK_OK;
3475 if (result != OC_STACK_OK)
3484 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3485 const char *resourceTypeName)
3488 OCStackResult result = OC_STACK_ERROR;
3489 OCResource *resource = NULL;
3491 resource = findResource((OCResource *) handle);
3494 OIC_LOG(ERROR, TAG, "Resource not found");
3495 return OC_STACK_ERROR;
3498 result = BindResourceTypeToResource(resource, resourceTypeName);
3500 #ifdef WITH_PRESENCE
3501 if(presenceResource.handle)
3503 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3504 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3511 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3512 const char *resourceInterfaceName)
3515 OCStackResult result = OC_STACK_ERROR;
3516 OCResource *resource = NULL;
3518 resource = findResource((OCResource *) handle);
3521 OIC_LOG(ERROR, TAG, "Resource not found");
3522 return OC_STACK_ERROR;
3525 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3527 #ifdef WITH_PRESENCE
3528 if (presenceResource.handle)
3530 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3531 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3538 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3540 OCResource *pointer = headResource;
3542 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3546 *numResources = *numResources + 1;
3547 pointer = pointer->next;
3552 OCResourceHandle OCGetResourceHandle(uint8_t index)
3554 OCResource *pointer = headResource;
3556 for( uint8_t i = 0; i < index && pointer; ++i)
3558 pointer = pointer->next;
3560 return (OCResourceHandle) pointer;
3563 OCStackResult OCDeleteResource(OCResourceHandle handle)
3567 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3568 return OC_STACK_INVALID_PARAM;
3571 OCResource *resource = findResource((OCResource *) handle);
3572 if (resource == NULL)
3574 OIC_LOG(ERROR, TAG, "Resource not found");
3575 return OC_STACK_NO_RESOURCE;
3578 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3580 OIC_LOG(ERROR, TAG, "Error deleting resource");
3581 return OC_STACK_ERROR;
3587 const char *OCGetResourceUri(OCResourceHandle handle)
3589 OCResource *resource = NULL;
3591 resource = findResource((OCResource *) handle);
3594 return resource->uri;
3596 return (const char *) NULL;
3599 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3601 OCResource *resource = NULL;
3603 resource = findResource((OCResource *) handle);
3606 return resource->resourceProperties;
3608 return (OCResourceProperty)-1;
3611 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3612 uint8_t *numResourceTypes)
3614 OCResource *resource = NULL;
3615 OCResourceType *pointer = NULL;
3617 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3618 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3620 *numResourceTypes = 0;
3622 resource = findResource((OCResource *) handle);
3625 pointer = resource->rsrcType;
3628 *numResourceTypes = *numResourceTypes + 1;
3629 pointer = pointer->next;
3635 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3637 OCResourceType *resourceType = NULL;
3639 resourceType = findResourceTypeAtIndex(handle, index);
3642 return resourceType->resourcetypename;
3644 return (const char *) NULL;
3647 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3648 uint8_t *numResourceInterfaces)
3650 OCResourceInterface *pointer = NULL;
3651 OCResource *resource = NULL;
3653 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3654 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3656 *numResourceInterfaces = 0;
3657 resource = findResource((OCResource *) handle);
3660 pointer = resource->rsrcInterface;
3663 *numResourceInterfaces = *numResourceInterfaces + 1;
3664 pointer = pointer->next;
3670 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3672 OCResourceInterface *resourceInterface = NULL;
3674 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3675 if (resourceInterface)
3677 return resourceInterface->name;
3679 return (const char *) NULL;
3682 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3685 OCResource *resource = NULL;
3686 OCChildResource *tempChildResource = NULL;
3689 resource = findResource((OCResource *) collectionHandle);
3695 tempChildResource = resource->rsrcChildResourcesHead;
3697 while(tempChildResource)
3701 return tempChildResource->rsrcResource;
3704 tempChildResource = tempChildResource->next;
3707 // In this case, the number of resource handles in the collection exceeds the index
3708 tempChildResource = NULL;
3712 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3713 OCEntityHandler entityHandler,
3714 void* callbackParam)
3716 OCResource *resource = NULL;
3718 // Validate parameters
3719 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3721 // Use the handle to find the resource in the resource linked list
3722 resource = findResource((OCResource *)handle);
3725 OIC_LOG(ERROR, TAG, "Resource not found");
3726 return OC_STACK_ERROR;
3730 resource->entityHandler = entityHandler;
3731 resource->entityHandlerCallbackParam = callbackParam;
3733 #ifdef WITH_PRESENCE
3734 if (presenceResource.handle)
3736 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3737 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3744 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3746 OCResource *resource = NULL;
3748 resource = findResource((OCResource *)handle);
3751 OIC_LOG(ERROR, TAG, "Resource not found");
3756 return resource->entityHandler;
3759 void incrementSequenceNumber(OCResource * resPtr)
3761 // Increment the sequence number
3762 resPtr->sequenceNum += 1;
3763 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3765 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3770 #ifdef WITH_PRESENCE
3771 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3772 OCPresenceTrigger trigger)
3774 OCResource *resPtr = NULL;
3775 OCStackResult result = OC_STACK_ERROR;
3776 OCMethod method = OC_REST_PRESENCE;
3777 uint32_t maxAge = 0;
3778 resPtr = findResource((OCResource *) presenceResource.handle);
3781 return OC_STACK_NO_RESOURCE;
3784 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3786 maxAge = presenceResource.presenceTTL;
3788 result = SendAllObserverNotification(method, resPtr, maxAge,
3789 trigger, resourceType, OC_LOW_QOS);
3795 OCStackResult SendStopNotification()
3797 OCResource *resPtr = NULL;
3798 OCStackResult result = OC_STACK_ERROR;
3799 OCMethod method = OC_REST_PRESENCE;
3800 resPtr = findResource((OCResource *) presenceResource.handle);
3803 return OC_STACK_NO_RESOURCE;
3806 // maxAge is 0. ResourceType is NULL.
3807 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3813 #endif // WITH_PRESENCE
3814 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3816 OCResource *resPtr = NULL;
3817 OCStackResult result = OC_STACK_ERROR;
3818 OCMethod method = OC_REST_NOMETHOD;
3819 uint32_t maxAge = 0;
3821 OIC_LOG(INFO, TAG, "Notifying all observers");
3822 #ifdef WITH_PRESENCE
3823 if(handle == presenceResource.handle)
3827 #endif // WITH_PRESENCE
3828 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3830 // Verify that the resource exists
3831 resPtr = findResource ((OCResource *) handle);
3834 return OC_STACK_NO_RESOURCE;
3838 //only increment in the case of regular observing (not presence)
3839 incrementSequenceNumber(resPtr);
3840 method = OC_REST_OBSERVE;
3841 maxAge = MAX_OBSERVE_AGE;
3842 #ifdef WITH_PRESENCE
3843 result = SendAllObserverNotification (method, resPtr, maxAge,
3844 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3846 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3853 OCNotifyListOfObservers (OCResourceHandle handle,
3854 OCObservationId *obsIdList,
3855 uint8_t numberOfIds,
3856 const OCRepPayload *payload,
3857 OCQualityOfService qos)
3859 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3861 OCResource *resPtr = NULL;
3862 //TODO: we should allow the server to define this
3863 uint32_t maxAge = MAX_OBSERVE_AGE;
3865 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3866 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3867 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3869 resPtr = findResource ((OCResource *) handle);
3870 if (NULL == resPtr || myStackMode == OC_CLIENT)
3872 return OC_STACK_NO_RESOURCE;
3876 incrementSequenceNumber(resPtr);
3878 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3879 payload, maxAge, qos));
3882 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3884 OCStackResult result = OC_STACK_ERROR;
3885 OCServerRequest *serverRequest = NULL;
3887 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3889 // Validate input parameters
3890 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3891 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3894 // Get pointer to request info
3895 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3898 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3899 result = serverRequest->ehResponseHandler(ehResponse);
3905 //#ifdef DIRECT_PAIRING
3906 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3908 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3909 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3911 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3915 return (const OCDPDev_t*)DPGetDiscoveredDevices();
3918 const OCDPDev_t* OCGetDirectPairedDevices()
3920 return (const OCDPDev_t*)DPGetPairedDevices();
3923 void DirectPairingCB (OCDirectPairingDev_t * peer, OCStackResult result)
3925 if (gDirectpairingCallback)
3927 gDirectpairingCallback((OCDPDev_t*)peer, result);
3928 gDirectpairingCallback = NULL;
3932 OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3933 OCDirectPairingCB resultCallback)
3935 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3938 OIC_LOG(ERROR, TAG, "Invalid parameters");
3939 return OC_STACK_INVALID_PARAM;
3942 if(NULL == resultCallback)
3944 OIC_LOG(ERROR, TAG, "Invalid parameters");
3945 return OC_STACK_INVALID_CALLBACK;
3947 gDirectpairingCallback = resultCallback;
3948 return DPDirectPairing((OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3949 pinNumber, DirectPairingCB);
3951 //#endif // DIRECT_PAIRING
3953 //-----------------------------------------------------------------------------
3954 // Private internal function definitions
3955 //-----------------------------------------------------------------------------
3956 static OCDoHandle GenerateInvocationHandle()
3958 OCDoHandle handle = NULL;
3959 // Generate token here, it will be deleted when the transaction is deleted
3960 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3963 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3969 #ifdef WITH_PRESENCE
3970 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3971 OCResourceProperty resourceProperties, uint8_t enable)
3975 return OC_STACK_INVALID_PARAM;
3977 if (resourceProperties
3978 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3980 OIC_LOG(ERROR, TAG, "Invalid property");
3981 return OC_STACK_INVALID_PARAM;
3985 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3989 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3995 OCStackResult initResources()
3997 OCStackResult result = OC_STACK_OK;
3999 headResource = NULL;
4000 tailResource = NULL;
4001 // Init Virtual Resources
4002 #ifdef WITH_PRESENCE
4003 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4005 result = OCCreateResource(&presenceResource.handle,
4006 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4008 OC_RSRVD_PRESENCE_URI,
4012 //make resource inactive
4013 result = OCChangeResourceProperty(
4014 &(((OCResource *) presenceResource.handle)->resourceProperties),
4017 #ifndef WITH_ARDUINO
4018 if (result == OC_STACK_OK)
4020 result = SRMInitSecureResources();
4024 if(result == OC_STACK_OK)
4026 result = OCCreateResource(&deviceResource,
4027 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4028 OC_RSRVD_INTERFACE_DEFAULT,
4029 OC_RSRVD_DEVICE_URI,
4033 if(result == OC_STACK_OK)
4035 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4036 OC_RSRVD_INTERFACE_READ);
4040 if(result == OC_STACK_OK)
4042 result = OCCreateResource(&platformResource,
4043 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4044 OC_RSRVD_INTERFACE_DEFAULT,
4045 OC_RSRVD_PLATFORM_URI,
4049 if(result == OC_STACK_OK)
4051 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4052 OC_RSRVD_INTERFACE_READ);
4059 void insertResource(OCResource *resource)
4063 headResource = resource;
4064 tailResource = resource;
4068 tailResource->next = resource;
4069 tailResource = resource;
4071 resource->next = NULL;
4074 OCResource *findResource(OCResource *resource)
4076 OCResource *pointer = headResource;
4080 if (pointer == resource)
4084 pointer = pointer->next;
4089 void deleteAllResources()
4091 OCResource *pointer = headResource;
4092 OCResource *temp = NULL;
4096 temp = pointer->next;
4097 #ifdef WITH_PRESENCE
4098 if (pointer != (OCResource *) presenceResource.handle)
4100 #endif // WITH_PRESENCE
4101 deleteResource(pointer);
4102 #ifdef WITH_PRESENCE
4104 #endif // WITH_PRESENCE
4108 SRMDeInitSecureResources();
4110 #ifdef WITH_PRESENCE
4111 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4112 // presence notification attributed to their deletion to be processed.
4113 deleteResource((OCResource *) presenceResource.handle);
4114 #endif // WITH_PRESENCE
4117 OCStackResult deleteResource(OCResource *resource)
4119 OCResource *prev = NULL;
4120 OCResource *temp = NULL;
4123 OIC_LOG(DEBUG,TAG,"resource is NULL");
4124 return OC_STACK_INVALID_PARAM;
4127 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4129 temp = headResource;
4132 if (temp == resource)
4134 // Invalidate all Resource Properties.
4135 resource->resourceProperties = (OCResourceProperty) 0;
4136 #ifdef WITH_PRESENCE
4137 if(resource != (OCResource *) presenceResource.handle)
4139 #endif // WITH_PRESENCE
4140 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4141 #ifdef WITH_PRESENCE
4144 if(presenceResource.handle)
4146 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4147 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4150 // Only resource in list.
4151 if (temp == headResource && temp == tailResource)
4153 headResource = NULL;
4154 tailResource = NULL;
4157 else if (temp == headResource)
4159 headResource = temp->next;
4162 else if (temp == tailResource)
4164 tailResource = prev;
4165 tailResource->next = NULL;
4169 prev->next = temp->next;
4172 deleteResourceElements(temp);
4183 return OC_STACK_ERROR;
4186 void deleteResourceElements(OCResource *resource)
4193 OICFree(resource->uri);
4194 deleteResourceType(resource->rsrcType);
4195 deleteResourceInterface(resource->rsrcInterface);
4198 void deleteResourceType(OCResourceType *resourceType)
4200 OCResourceType *pointer = resourceType;
4201 OCResourceType *next = NULL;
4205 next = pointer->next;
4206 OICFree(pointer->resourcetypename);
4212 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4214 OCResourceInterface *pointer = resourceInterface;
4215 OCResourceInterface *next = NULL;
4219 next = pointer->next;
4220 OICFree(pointer->name);
4226 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4228 OCResourceType *pointer = NULL;
4229 OCResourceType *previous = NULL;
4230 if (!resource || !resourceType)
4234 // resource type list is empty.
4235 else if (!resource->rsrcType)
4237 resource->rsrcType = resourceType;
4241 pointer = resource->rsrcType;
4245 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4247 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4248 OICFree(resourceType->resourcetypename);
4249 OICFree(resourceType);
4253 pointer = pointer->next;
4258 previous->next = resourceType;
4261 resourceType->next = NULL;
4263 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4266 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4268 OCResource *resource = NULL;
4269 OCResourceType *pointer = NULL;
4271 // Find the specified resource
4272 resource = findResource((OCResource *) handle);
4278 // Make sure a resource has a resourcetype
4279 if (!resource->rsrcType)
4284 // Iterate through the list
4285 pointer = resource->rsrcType;
4286 for(uint8_t i = 0; i< index && pointer; ++i)
4288 pointer = pointer->next;
4293 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4295 if(resourceTypeList && resourceTypeName)
4297 OCResourceType * rtPointer = resourceTypeList;
4298 while(resourceTypeName && rtPointer)
4300 if(rtPointer->resourcetypename &&
4301 strcmp(resourceTypeName, (const char *)
4302 (rtPointer->resourcetypename)) == 0)
4306 rtPointer = rtPointer->next;
4314 * Insert a new interface into interface linked list only if not already present.
4315 * If alredy present, 2nd arg is free'd.
4316 * Default interface will always be first if present.
4318 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4320 OCResourceInterface *pointer = NULL;
4321 OCResourceInterface *previous = NULL;
4323 newInterface->next = NULL;
4325 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4327 if (!*firstInterface)
4329 // If first interface is not oic.if.baseline, by default add it as first interface type.
4330 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4332 *firstInterface = newInterface;
4336 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4337 if (result != OC_STACK_OK)
4339 OICFree(newInterface->name);
4340 OICFree(newInterface);
4343 if (*firstInterface)
4345 (*firstInterface)->next = newInterface;
4349 // If once add oic.if.baseline, later too below code take care of freeing memory.
4350 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4352 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4354 OICFree(newInterface->name);
4355 OICFree(newInterface);
4358 // This code will not hit anymore, keeping
4361 newInterface->next = *firstInterface;
4362 *firstInterface = newInterface;
4367 pointer = *firstInterface;
4370 if (strcmp(newInterface->name, pointer->name) == 0)
4372 OICFree(newInterface->name);
4373 OICFree(newInterface);
4377 pointer = pointer->next;
4379 previous->next = newInterface;
4383 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4386 OCResource *resource = NULL;
4387 OCResourceInterface *pointer = NULL;
4389 // Find the specified resource
4390 resource = findResource((OCResource *) handle);
4396 // Make sure a resource has a resourceinterface
4397 if (!resource->rsrcInterface)
4402 // Iterate through the list
4403 pointer = resource->rsrcInterface;
4405 for (uint8_t i = 0; i < index && pointer; ++i)
4407 pointer = pointer->next;
4413 * This function splits the uri using the '?' delimiter.
4414 * "uriWithoutQuery" is the block of characters between the beginning
4415 * till the delimiter or '\0' which ever comes first.
4416 * "query" is whatever is to the right of the delimiter if present.
4417 * No delimiter sets the query to NULL.
4418 * If either are present, they will be malloc'ed into the params 2, 3.
4419 * The first param, *uri is left untouched.
4421 * NOTE: This function does not account for whitespace at the end of the uri NOR
4422 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4423 * part of the query.
4425 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4429 return OC_STACK_INVALID_URI;
4431 if(!query || !uriWithoutQuery)
4433 return OC_STACK_INVALID_PARAM;
4437 *uriWithoutQuery = NULL;
4439 size_t uriWithoutQueryLen = 0;
4440 size_t queryLen = 0;
4441 size_t uriLen = strlen(uri);
4443 char *pointerToDelimiter = strstr(uri, "?");
4445 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4446 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4448 if (uriWithoutQueryLen)
4450 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4451 if (!*uriWithoutQuery)
4455 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4459 *query = (char *) OICCalloc(queryLen + 1, 1);
4462 OICFree(*uriWithoutQuery);
4463 *uriWithoutQuery = NULL;
4466 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4472 return OC_STACK_NO_MEMORY;
4475 static const OicUuid_t* OCGetServerInstanceID(void)
4477 static bool generated = false;
4478 static OicUuid_t sid;
4484 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4486 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4493 const char* OCGetServerInstanceIDString(void)
4495 static bool generated = false;
4496 static char sidStr[UUID_STRING_SIZE];
4503 const OicUuid_t *sid = OCGetServerInstanceID();
4504 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4506 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4514 CAResult_t OCSelectNetwork()
4516 CAResult_t retResult = CA_STATUS_FAILED;
4517 CAResult_t caResult = CA_STATUS_OK;
4519 CATransportAdapter_t connTypes[] = {
4521 CA_ADAPTER_RFCOMM_BTEDR,
4522 CA_ADAPTER_GATT_BTLE,
4525 ,CA_ADAPTER_REMOTE_ACCESS
4532 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4534 for(int i = 0; i<numConnTypes; i++)
4536 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4537 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4539 caResult = CASelectNetwork(connTypes[i]);
4540 if(caResult == CA_STATUS_OK)
4542 retResult = CA_STATUS_OK;
4547 if(retResult != CA_STATUS_OK)
4549 return caResult; // Returns error of appropriate transport that failed fatally.
4555 OCStackResult CAResultToOCResult(CAResult_t caResult)
4561 case CA_STATUS_INVALID_PARAM:
4562 return OC_STACK_INVALID_PARAM;
4563 case CA_ADAPTER_NOT_ENABLED:
4564 return OC_STACK_ADAPTER_NOT_ENABLED;
4565 case CA_SERVER_STARTED_ALREADY:
4567 case CA_SERVER_NOT_STARTED:
4568 return OC_STACK_ERROR;
4569 case CA_DESTINATION_NOT_REACHABLE:
4570 return OC_STACK_COMM_ERROR;
4571 case CA_SOCKET_OPERATION_FAILED:
4572 return OC_STACK_COMM_ERROR;
4573 case CA_SEND_FAILED:
4574 return OC_STACK_COMM_ERROR;
4575 case CA_RECEIVE_FAILED:
4576 return OC_STACK_COMM_ERROR;
4577 case CA_MEMORY_ALLOC_FAILED:
4578 return OC_STACK_NO_MEMORY;
4579 case CA_REQUEST_TIMEOUT:
4580 return OC_STACK_TIMEOUT;
4581 case CA_DESTINATION_DISCONNECTED:
4582 return OC_STACK_COMM_ERROR;
4583 case CA_STATUS_FAILED:
4584 return OC_STACK_ERROR;
4585 case CA_NOT_SUPPORTED:
4586 return OC_STACK_NOTIMPL;
4588 return OC_STACK_ERROR;