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
37 #include "ocstackinternal.h"
38 #include "ocresourcehandler.h"
39 #include "occlientcb.h"
40 #include "ocobserve.h"
43 #include "ocserverrequest.h"
44 #include "ocsecurityinternal.h"
47 #include "cainterface.h"
54 #include "coap_time.h"
59 #include <arpa/inet.h>
62 //-----------------------------------------------------------------------------
64 //-----------------------------------------------------------------------------
66 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
70 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
74 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
77 static OCStackState stackState = OC_STACK_UNINITIALIZED;
79 OCResource *headResource = NULL;
80 static OCResource *tailResource = NULL;
82 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
83 static PresenceResource presenceResource;
84 static uint8_t PresenceTimeOutSize = 0;
85 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
88 static OCMode myStackMode;
89 OCDeviceEntityHandler defaultDeviceHandler;
92 //-----------------------------------------------------------------------------
94 //-----------------------------------------------------------------------------
95 #define TAG PCF("OCStack")
96 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
97 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
98 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
99 TAG, PCF(#arg " is NULL")); return (retVal); } }
100 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
103 //TODO: we should allow the server to define this
104 #define MAX_OBSERVE_AGE (0x2FFFFUL)
107 * Parse the presence payload and extract various parameters.
108 * Note: Caller should invoke OCFree after done with resType pointer.
110 * @param payload Presence payload.
111 * @param seqNum Sequence number.
112 * @param maxAge Time To Live (in seconds).
113 * @param resType Resource type.
115 // TODO: Not sure if I agree with this. I think it should be static but it is called in
116 // stack/test/stacktests.cpp, not included via a header file. If we intend to allow it
117 // to be called externally, we should change the name to OCParsePresencePayload and make
118 // it part of the official public API. But can't change now due to current API freeze.
119 // Another option might be to make non-API utility functions for doing stuff like this.
120 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType);
122 //-----------------------------------------------------------------------------
123 // Private internal function prototypes
124 //-----------------------------------------------------------------------------
127 * Generate handle of OCDoResource invocation for callback management.
129 * @return Generated OCDoResource handle.
131 static OCDoHandle GenerateInvocationHandle();
134 * Initialize resource data structures, variables, etc.
136 * @return ::OC_STACK_OK on success, some other value upon failure.
138 static OCStackResult initResources();
141 * Add a resource to the end of the linked list of resources.
143 * @param resource Resource to be added
145 static void insertResource(OCResource *resource);
148 * Find a resource in the linked list of resources.
150 * @param resource Resource to be found.
151 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
154 static OCResource *findResource(OCResource *resource);
157 * Insert a resource type into a resource's resource type linked list.
158 * If resource type already exists, it will not be inserted and the
159 * resourceType will be free'd.
160 * resourceType->next should be null to avoid memory leaks.
161 * Function returns silently for null args.
163 * @param resource Resource where resource type is to be inserted.
164 * @param resourceType Resource type to be inserted.
166 static void insertResourceType(OCResource *resource,
167 OCResourceType *resourceType);
170 * Get a resource type at the specified index within a resource.
172 * @param handle Handle of resource.
173 * @param index Index of resource type.
175 * @return Pointer to resource type if found, NULL otherwise.
177 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
181 * Insert a resource interface into a resource's resource interface linked list.
182 * If resource interface already exists, it will not be inserted and the
183 * resourceInterface will be free'd.
184 * resourceInterface->next should be null to avoid memory leaks.
186 * @param resource Resource where resource interface is to be inserted.
187 * @param resourceInterface Resource interface to be inserted.
189 static void insertResourceInterface(OCResource *resource,
190 OCResourceInterface *resourceInterface);
193 * Get a resource interface at the specified index within a resource.
195 * @param handle Handle of resource.
196 * @param index Index of resource interface.
198 * @return Pointer to resource interface if found, NULL otherwise.
200 static OCResourceInterface *findResourceInterfaceAtIndex(
201 OCResourceHandle handle, uint8_t index);
204 * Delete all of the dynamically allocated elements that were created for the resource type.
206 * @param resourceType Specified resource type.
208 static void deleteResourceType(OCResourceType *resourceType);
211 * Delete all of the dynamically allocated elements that were created for the resource interface.
213 * @param resourceInterface Specified resource interface.
215 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
218 * Delete all of the dynamically allocated elements that were created for the resource.
220 * @param resource Specified resource.
222 static void deleteResourceElements(OCResource *resource);
225 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
228 * @param handle Handle of resource to be deleted.
230 * @return ::OC_STACK_OK on success, some other value upon failure.
232 static OCStackResult deleteResource(OCResource *resource);
235 * Delete all of the resources in the resource list.
237 static void deleteAllResources();
240 * Increment resource sequence number. Handles rollover.
242 * @param resPtr Pointer to resource.
244 static void incrementSequenceNumber(OCResource * resPtr);
247 * Verify the lengths of the URI and the query separately.
249 * @param inputUri Input URI and query.
250 * @param uriLen The length of the initial URI with query.
251 * @return ::OC_STACK_OK on success, some other value upon failure.
253 static OCStackResult verifyUriQueryLength(const char * inputUri,
257 * Determine if a request/response must be sent in a block transfer because it is too large to be
258 * sent in a single PDU. This function can be used for either a request or a response.
259 * Note: Either the request or response parameter should be non-NULL (i.e. only one, not both).
261 * @param request NULL or pointer to request.
262 * @param response NULL or pointer to response.
263 * @param size 0 or size of the request/response. If 0, strlen is used for determining
264 * the length of the request/response.
267 * false - packet transfer NOT required (i.e. normal request/response).
268 * true - packet transfer required (i.e. block transfer needed).
270 static bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size);
273 * Retrieves a resource type based upon a query contains only just one
274 * resource attribute (and that has to be of type "rt").
276 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
279 * @param query The query part of the URI.
280 * @param resourceType The resource type to be populated; pass by reference.
282 * @return ::OC_STACK_OK on success, some other value upon failure.
284 static OCStackResult getResourceType(const char * query, char** resourceType);
287 * Attempts to initialize every network interface that the CA Layer might have compiled in.
289 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
290 * return something other than @ref CA_STATUS_OK, then this function fails.
292 * @return ::CA_STATUS_OK on success, some other value upon failure.
294 static CAResult_t OCSelectNetwork();
297 * Get the CoAP ticks after the specified number of seconds.
299 * @param afterSeconds Seconds.
303 static uint32_t GetTime(float afterSeconds);
306 * This method is used to create the IPv4 dev_addr structure.
307 * Builds a socket interface address using IP address and port number.
308 * TODO: Remove in future. Temporary helper function.
310 * @param a IPv4 octet 0.
311 * @param b IPv4 octet 1.
312 * @param c IPv4 octet 2.
313 * @param d IPv4 octet 3.
314 * @param port Port number.
315 * @param ipAddr - IPv4 address.
316 * @return ::OC_STACK_OK on success, some other value upon failure.
318 static OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
319 uint16_t port, OCDevAddr *ipAddr);
322 * Convert CAResponseResult_t to OCStackResult.
324 * @param caCode CAResponseResult_t code.
325 * @return ::OC_STACK_OK on success, some other value upon failure.
327 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
330 * Convert OCStackResult to CAResponseResult_t.
332 * @param caCode OCStackResult code.
333 * @return ::CA_SUCCESS on success, some other value upon failure.
335 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode);
338 * Convert OCConnectivityType to CAConnectivityType_t.
340 * @param ocConType OCConnectivityType input.
341 * @param caConType CAConnectivityType_t output.
342 * @return ::OC_STACK_OK on success, some other value upon failure.
344 static OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType,
345 CAConnectivityType_t* caConType);
348 * Convert CAConnectivityType_t to CAConnectivityType_t.
350 * @param caConType CAConnectivityType_t input.
351 * @param ocConType OCConnectivityType output.
352 * @return ::OC_STACK_OK on success, some other value upon failure.
354 static OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType,
355 OCConnectivityType *ocConType);
358 * Update response.addr appropriately from endPoint.addressInfo.
360 * @param address OCDevAddr output.
361 * @param endPoint CARemoteEndpoint_t input.
362 * @return ::OC_STACK_OK on success, some other value upon failure.
364 static OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* endPoint);
367 * Handle response from presence request.
369 * @param endPoint CA remote endpoint.
370 * @param responseInfo CA response info.
371 * @return ::OC_STACK_OK on success, some other value upon failure.
373 static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
374 const CAResponseInfo_t* responseInfo);
377 * This function will be called back by CA layer when a response is received.
379 * @param endPoint CA remote endpoint.
380 * @param responseInfo CA response info.
382 static void HandleCAResponses(const CARemoteEndpoint_t* endPoint,
383 const CAResponseInfo_t* responseInfo);
386 * This function will be called back by CA layer when a request is received.
388 * @param endPoint CA remote endpoint.
389 * @param requestInfo CA request info.
391 static void HandleCARequests(const CARemoteEndpoint_t* endPoint,
392 const CARequestInfo_t* requestInfo);
395 * Handle incoming requests.
397 * @param protocolRequest Incoming request from lower level stack.
398 * @return ::OC_STACK_OK on success, some other value upon failure.
402 * Parse IP address string into octets and port.
404 * @param ipAddrStr IPv4 address input string.
405 * @param ipAddr IPv4 address output.
406 * @param port Port number.
413 * Extract query from a URI.
415 * @param uri Full URI with query.
416 * @param query Pointer to string that will contain query.
417 * @param newURI Pointer to string that will contain URI.
418 * @return ::OC_STACK_OK on success, some other value upon failure.
420 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
423 * Finds a resource type in an OCResourceType link-list.
425 * @param resourceTypeList The link-list to be searched through.
426 * @param resourceTypeName The key to search for.
428 * @return Resource type that matches the key (ie. resourceTypeName) or
429 * NULL if there is either an invalid parameter or this function was unable to find the key.
431 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
432 const char * resourceTypeName);
435 * Return a server instance ID.
437 * @return Instance ID of the server.
439 static const ServerID OCGetServerInstanceID(void);
441 //-----------------------------------------------------------------------------
442 // Internal functions
443 //-----------------------------------------------------------------------------
445 uint32_t GetTime(float afterSeconds)
449 return now + (uint32_t)(afterSeconds * COAP_TICKS_PER_SECOND);
452 OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
453 uint16_t port, OCDevAddr *ipAddr)
457 OC_LOG(FATAL, TAG, PCF("Invalid argument"));
458 return OC_STACK_INVALID_PARAM;
465 ipAddr->addr[4] = (uint8_t)port;
466 ipAddr->addr[5] = (uint8_t)(port >> 8);
471 //-----------------------------------------------------------------------------
472 // Internal API function
473 //-----------------------------------------------------------------------------
475 // This internal function is called to update the stack with the status of
476 // observers and communication failures
477 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
479 OCStackResult result = OC_STACK_ERROR;
480 ResourceObserver * observer = NULL;
481 OCEntityHandlerRequest ehRequest = {};
485 case OC_OBSERVER_NOT_INTERESTED:
486 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
487 observer = GetObserverUsingToken (token, tokenLength);
490 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
491 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
492 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
493 if(result != OC_STACK_OK)
497 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
499 //observer is not observing anymore
500 result = DeleteObserverUsingToken (token, tokenLength);
501 if(result == OC_STACK_OK)
503 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
507 result = OC_STACK_OK;
508 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
511 case OC_OBSERVER_STILL_INTERESTED:
512 //observer is still interested
513 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
514 notifications, reset the failedCount"));
515 observer = GetObserverUsingToken (token, tokenLength);
518 observer->forceHighQos = 0;
519 observer->failedCommCount = 0;
520 result = OC_STACK_OK;
524 result = OC_STACK_OBSERVER_NOT_FOUND;
527 case OC_OBSERVER_FAILED_COMM:
528 //observer is not reachable
529 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
530 observer = GetObserverUsingToken (token, tokenLength);
533 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
535 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
536 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
537 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
538 if(result != OC_STACK_OK)
540 return OC_STACK_ERROR;
542 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
543 //observer is unreachable
544 result = DeleteObserverUsingToken (token, tokenLength);
545 if(result == OC_STACK_OK)
547 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
551 result = OC_STACK_OK;
552 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
557 observer->failedCommCount++;
558 result = OC_STACK_CONTINUE;
560 observer->forceHighQos = 1;
561 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
565 OC_LOG(ERROR, TAG, PCF("Unknown status"));
566 result = OC_STACK_ERROR;
571 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
573 OCStackResult ret = OC_STACK_ERROR;
581 ret = OC_STACK_RESOURCE_CREATED;
584 ret = OC_STACK_RESOURCE_DELETED;
587 ret = OC_STACK_INVALID_QUERY;
590 ret = OC_STACK_INVALID_OPTION;
593 ret = OC_STACK_NO_RESOURCE;
595 case CA_RETRANSMIT_TIMEOUT:
596 ret = OC_STACK_COMM_ERROR;
604 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode)
606 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
613 case OC_STACK_RESOURCE_CREATED:
616 case OC_STACK_RESOURCE_DELETED:
619 case OC_STACK_INVALID_QUERY:
622 case OC_STACK_INVALID_OPTION:
625 case OC_STACK_NO_RESOURCE:
628 case OC_STACK_COMM_ERROR:
629 ret = CA_RETRANSMIT_TIMEOUT;
637 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
639 OCStackResult ret = OC_STACK_OK;
644 *caConType = CA_ETHERNET;
647 *caConType = CA_WIFI;
656 // Currently OC_ALL represents WIFI and ETHERNET
657 // Add other connectivity types as they are enabled in future
658 *caConType = (CAConnectivityType_t) (CA_WIFI|CA_ETHERNET);
661 ret = OC_STACK_INVALID_PARAM;
667 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
669 OCStackResult ret = OC_STACK_OK;
674 *ocConType = OC_ETHERNET;
677 *ocConType = OC_WIFI;
686 ret = OC_STACK_INVALID_PARAM;
692 OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* endPoint)
694 OCStackResult ret = OC_STACK_ERROR;
696 char * savePtr = NULL;
697 char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
700 ret = OC_STACK_NO_MEMORY;
703 memcpy(cpAddress, endPoint->addressInfo.IP.ipAddress,
704 strlen(endPoint->addressInfo.IP.ipAddress) + 1);
706 // Grabs the first three numbers from the IPv4 address and replaces dots
707 for(int i=0; i<4; i++)
709 tok = strtok_r(i==0 ? cpAddress : NULL, ".", &savePtr);
713 ret = OC_STACK_ERROR;
716 address->addr[i] = atoi(tok);
719 memcpy(&address->addr[4], &endPoint->addressInfo.IP.port, sizeof(uint16_t));
727 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
730 char * savePtr = NULL;
731 // The format of the payload is {"oc":[%u:%u:%s]}
732 // %u : sequence number,
734 // %s : Resource Type (Optional)
736 if (!payload || !seqNum || !maxAge || !resType)
740 tok = strtok_r(payload, "[:]}", &savePtr);
741 payload[strlen(payload)] = ':';
743 //Retrieve sequence number
744 tok = strtok_r(NULL, "[:]}", &savePtr);
749 payload[strlen((char *)payload)] = ':';
750 *seqNum = (uint32_t) atoi(tok);
753 tok = strtok_r(NULL, "[:]}", &savePtr);
758 *maxAge = (uint32_t) atoi(tok);
760 //Retrieve ResourceType
761 tok = strtok_r(NULL, "[:]}",&savePtr);
767 *resType = (char *)OCMalloc(strlen(tok) + 1);
772 payload[strlen((char *)payload)] = ':';
773 strcpy(*resType, tok);
774 OC_LOG_V(DEBUG, TAG, "resourceTypeName %s", *resType);
776 payload[strlen((char *)payload)] = ']';
779 static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
780 const CAResponseInfo_t* responseInfo)
782 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
783 ClientCB * cbNode = NULL;
784 char *resourceTypeName = NULL;
785 OCClientResponse response = {};
786 OCDevAddr address = {};
787 OCStackResult result = OC_STACK_ERROR;
788 uint32_t lowerBound = 0;
789 uint32_t higherBound = 0;
792 char *fullUri = NULL;
793 char *ipAddress = NULL;
794 int presenceSubscribe = 0;
795 int multicastPresenceSubscribe = 0;
796 size_t addressLen = 0;
798 if (responseInfo->result != CA_SUCCESS)
800 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
801 return OC_STACK_ERROR;
804 fullUri = (char *) OCMalloc(MAX_URI_LENGTH);
808 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
809 result = OC_STACK_NO_MEMORY;
813 addressLen = strlen(endPoint->addressInfo.IP.ipAddress);
814 ipAddress = (char *) OCMalloc(addressLen + 1);
818 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
819 result = OC_STACK_NO_MEMORY;
823 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, addressLen);
824 ipAddress[addressLen] = '\0';
826 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
829 cbNode = GetClientCB(NULL, 0, NULL, fullUri);
833 presenceSubscribe = 1;
837 snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
838 cbNode = GetClientCB(NULL, 0, NULL, fullUri);
841 multicastPresenceSubscribe = 1;
845 if(!presenceSubscribe && !multicastPresenceSubscribe)
847 OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
851 // No payload to the application in case of presence
852 response.resJSONPayload = NULL;
853 response.result = OC_STACK_OK;
855 result = UpdateResponseAddr(&address, endPoint);
856 if(result != OC_STACK_OK)
861 response.addr = &address;
863 result = CAToOCConnectivityType(endPoint->connectivityType, &(response.connType));
864 if(result != OC_STACK_OK)
866 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
870 if(responseInfo->info.payload)
872 parsePresencePayload(responseInfo->info.payload,
873 &(response.sequenceNumber),
878 if(presenceSubscribe)
880 if(cbNode->sequenceNumber == response.sequenceNumber)
882 OC_LOG(INFO, TAG, PCF("No presence change"));
887 OC_LOG(INFO, TAG, PCF("Stopping presence"));
888 response.result = OC_STACK_PRESENCE_STOPPED;
891 OCFree(cbNode->presence->timeOut);
892 OCFree(cbNode->presence);
893 cbNode->presence = NULL;
898 if(!cbNode->presence)
900 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
901 if(!(cbNode->presence))
903 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
904 result = OC_STACK_NO_MEMORY;
908 VERIFY_NON_NULL_V(cbNode->presence);
909 cbNode->presence->timeOut = NULL;
910 cbNode->presence->timeOut = (uint32_t *)
911 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
912 if(!(cbNode->presence->timeOut)){
914 PCF("Could not allocate memory for cbNode->presence->timeOut"));
915 OCFree(cbNode->presence);
916 result = OC_STACK_NO_MEMORY;
921 OC_LOG_V(INFO, TAG, "Update presence TTL, now time is %u", GetTime(0));
922 cbNode->presence->TTL = maxAge;
923 for(int index = 0; index < PresenceTimeOutSize; index++)
925 lowerBound = GetTime(PresenceTimeOut[index]/ 100.0f*cbNode->presence->TTL);
926 higherBound = GetTime(PresenceTimeOut[index + 1]/100.0f*cbNode->presence->TTL);
927 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
928 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
929 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
930 OC_LOG_V(DEBUG, TAG, "timeOut entry %d",
931 cbNode->presence->timeOut[index]);
933 cbNode->presence->TTLlevel = 0;
934 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
937 OC_LOG(INFO, TAG, PCF("Presence changed, calling up the stack"));
938 cbNode->sequenceNumber = response.sequenceNumber;
940 // Ensure that a filter is actually applied.
941 if(resourceTypeName && cbNode->filterResourceType)
943 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
952 // This is the multicast case
954 OCMulticastNode* mcNode = NULL;
955 mcNode = GetMCPresenceNode(fullUri);
959 if(mcNode->nonce == response.sequenceNumber)
961 OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
964 mcNode->nonce = response.sequenceNumber;
968 OC_LOG(INFO, TAG, PCF("Stopping presence"));
969 response.result = OC_STACK_PRESENCE_STOPPED;
974 uint32_t uriLen = strlen(fullUri);
975 char* uri = (char *) OCMalloc(uriLen + 1);
978 memcpy(uri, fullUri, (uriLen + 1));
983 PCF("No Memory for URI to store in the presence node"));
984 result = OC_STACK_NO_MEMORY;
987 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
988 if(result != OC_STACK_OK)
991 PCF("Unable to add Multicast Presence Node"));
997 // Ensure that a filter is actually applied.
998 if(resourceTypeName && cbNode->filterResourceType)
1000 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1007 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1009 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1011 FindAndDeleteClientCB(cbNode);
1017 OCFree(resourceTypeName);
1021 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1023 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
1025 if(NULL == endPoint)
1027 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1031 if(NULL == responseInfo)
1033 OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
1037 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
1039 HandlePresenceResponse(endPoint, responseInfo);
1043 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1044 responseInfo->info.tokenLength, NULL, NULL);
1045 OC_LOG_V(DEBUG, TAG, "Response has the token %s", responseInfo->info.token);
1046 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1047 responseInfo->info.tokenLength);
1051 OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
1052 if(responseInfo->result == CA_EMPTY)
1054 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1055 // We do not have a case for the client to receive a RESET
1056 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1058 //This is the case of receiving an ACK on a request to a slow resource!
1059 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1060 //TODO: should we inform the client
1061 // app that at least the request was received at the server?
1064 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1066 OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
1067 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1068 OCClientResponse response = {};
1069 OCDevAddr address = {};
1070 OCStackResult result = UpdateResponseAddr(&address, endPoint);
1071 if(result != OC_STACK_OK)
1073 OC_LOG(ERROR, TAG, PCF("Error parsing IP address in UpdateResponseAddr"));
1077 result = UpdateResponseAddr(&address, endPoint);
1078 if(result != OC_STACK_OK)
1080 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
1083 response.addr = &address;
1085 response.result = CAToOCStackResult(responseInfo->result);
1086 cbNode->callBack(cbNode->context,
1087 cbNode->handle, &response);
1088 FindAndDeleteClientCB(cbNode);
1092 OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1093 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1094 OCClientResponse response = {};
1095 OCDevAddr address = {};
1097 OCStackResult result = UpdateResponseAddr(&address, endPoint);
1098 if(result != OC_STACK_OK)
1100 OC_LOG(ERROR, TAG, PCF("Error parsing IP address in UpdateResponseAddr"));
1103 response.addr = &address;
1104 // Populate the connectivity type. If this is a discovery response,
1105 // the resource that will be constructed from this response will make
1106 // further API calls from this interface.
1107 result = CAToOCConnectivityType(endPoint->connectivityType,
1108 &(response.connType));
1109 if(result != OC_STACK_OK)
1111 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
1115 response.result = CAToOCStackResult(responseInfo->result);
1116 response.resJSONPayload = (const char*)responseInfo->info.payload;
1117 response.numRcvdVendorSpecificHeaderOptions = 0;
1118 if(responseInfo->info.numOptions > 0)
1121 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1122 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1124 memcpy (&(response.sequenceNumber),
1125 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1126 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1131 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1134 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1136 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1140 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1142 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1143 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1146 if (cbNode->callBack(cbNode->context,
1147 cbNode->handle, &response) == OC_STACK_DELETE_TRANSACTION)
1149 FindAndDeleteClientCB(cbNode);
1152 //Need to send ACK when the response is CON
1153 if(responseInfo->info.type == CA_MSG_CONFIRM)
1155 SendResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1156 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1164 OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1165 if(responseInfo->result == CA_EMPTY)
1167 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1168 if(responseInfo->info.type == CA_MSG_RESET)
1170 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1171 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1172 OC_OBSERVER_NOT_INTERESTED);
1174 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1176 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1177 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1178 OC_OBSERVER_STILL_INTERESTED);
1181 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1183 OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1184 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1185 OC_OBSERVER_FAILED_COMM);
1190 if(!cbNode && !observer)
1192 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1194 OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1195 if(responseInfo->result == CA_EMPTY)
1197 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1201 OC_LOG(INFO, TAG, PCF("Received a response or notification,\
1202 but I do not have callback. Sending RESET"));
1203 SendResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1204 CA_MSG_RESET, 0, NULL, NULL, 0);
1208 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1210 OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1211 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1213 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1214 responseInfo->info.messageId);
1216 if (responseInfo->info.type == CA_MSG_RESET)
1218 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1219 responseInfo->info.messageId);
1225 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
1226 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1230 OCStackResult SendResponse(const CARemoteEndpoint_t* endPoint, const uint16_t coapID,
1231 const CAResponseResult_t responseResult, const CAMessageType_t type,
1232 const uint8_t numOptions, const CAHeaderOption_t *options,
1233 CAToken_t token, uint8_t tokenLength)
1235 CAResponseInfo_t respInfo = {};
1236 respInfo.result = responseResult;
1237 respInfo.info.messageId = coapID;
1238 respInfo.info.numOptions = numOptions;
1239 respInfo.info.options = (CAHeaderOption_t*)options;
1240 respInfo.info.payload = NULL;
1241 respInfo.info.token = token;
1242 respInfo.info.tokenLength = tokenLength;
1243 respInfo.info.type = type;
1245 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1246 if(caResult != CA_STATUS_OK)
1248 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1249 return OC_STACK_ERROR;
1254 //This function will be called back by CA layer when a request is received
1255 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1257 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1260 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1266 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1270 OCStackResult requestResult = OC_STACK_ERROR;
1272 if(myStackMode == OC_CLIENT)
1274 //TODO: should the client be responding to requests?
1278 OCServerProtocolRequest serverRequest = {};
1280 OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s\n"), (char*)endPoint->resourceUri);
1282 char * newUri = NULL;
1283 char * query = NULL;
1285 requestResult = getQueryFromUri(endPoint->resourceUri, &query, &newUri);
1287 if (requestResult != OC_STACK_OK)
1289 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1292 OC_LOG_V(INFO, TAG, PCF("URI without query: %s\n"), newUri);
1293 OC_LOG_V(INFO, TAG, PCF("Query : %s\n"), query);
1295 if(strlen(newUri) < MAX_URI_LENGTH)
1298 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
1303 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1311 if(strlen(query) < MAX_QUERY_LENGTH)
1313 memcpy (&(serverRequest.query), query, strlen(query));
1318 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1323 //copy request payload
1324 if (requestInfo->info.payload)
1326 size_t payloadLen = strlen(requestInfo->info.payload);
1327 serverRequest.reqTotalSize = payloadLen + 1;
1328 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
1333 serverRequest.reqTotalSize = 1;
1334 serverRequest.reqJSONPayload[0] = '\0';
1337 switch (requestInfo->method)
1341 serverRequest.method = OC_REST_GET;
1346 serverRequest.method = OC_REST_PUT;
1351 serverRequest.method = OC_REST_POST;
1356 serverRequest.method = OC_REST_DELETE;
1361 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
1362 SendResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1363 requestInfo->info.type, requestInfo->info.numOptions,
1364 requestInfo->info.options, requestInfo->info.token,
1365 requestInfo->info.tokenLength);
1370 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d",
1371 requestInfo->info.tokenLength);
1372 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1373 requestInfo->info.tokenLength);
1374 serverRequest.requestToken = (CAToken_t)OCMalloc(requestInfo->info.tokenLength);
1375 serverRequest.tokenLength = requestInfo->info.tokenLength;
1377 if (!serverRequest.requestToken)
1379 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
1380 SendResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1381 requestInfo->info.type, requestInfo->info.numOptions,
1382 requestInfo->info.options, requestInfo->info.token,
1383 requestInfo->info.tokenLength);
1386 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1388 if (requestInfo->info.type == CA_MSG_CONFIRM)
1390 serverRequest.qos = OC_HIGH_QOS;
1394 serverRequest.qos = OC_LOW_QOS;
1396 // CA does not need the following 2 fields
1397 // Are we sure CA does not need them? how is it responding to multicast
1398 serverRequest.delayedResNeeded = 0;
1399 serverRequest.secured = endPoint->isSecured;
1401 serverRequest.coapID = requestInfo->info.messageId;
1404 serverRequest.addressInfo = endPoint->addressInfo;
1405 serverRequest.connectivityType = endPoint->connectivityType;
1407 // copy vendor specific header options
1408 uint8_t tempNum = (requestInfo->info.numOptions);
1409 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1410 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1413 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1414 SendResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1415 requestInfo->info.type, requestInfo->info.numOptions,
1416 requestInfo->info.options, requestInfo->info.token,
1417 requestInfo->info.tokenLength);
1420 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1421 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1423 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1424 sizeof(CAHeaderOption_t)*tempNum);
1427 requestResult = HandleStackRequests (&serverRequest);
1429 // Send ACK to client as precursor to slow response
1430 if(requestResult == OC_STACK_SLOW_RESOURCE)
1432 SendResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1439 else if(requestResult != OC_STACK_OK)
1441 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1443 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1445 SendResponse(endPoint, requestInfo->info.messageId, stackResponse,
1446 requestInfo->info.type, requestInfo->info.numOptions,
1447 requestInfo->info.options, requestInfo->info.token,
1448 requestInfo->info.tokenLength);
1450 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1451 // The token is copied in there, and is thus still owned by this function.
1452 OCFree(serverRequest.requestToken);
1453 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1456 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1458 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1459 OCStackResult result = OC_STACK_ERROR;
1460 ResourceHandling resHandling;
1461 OCResource *resource;
1462 if(!protocolRequest)
1464 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1465 return OC_STACK_INVALID_PARAM;
1468 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1469 protocolRequest->tokenLength);
1472 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1473 result = AddServerRequest(&request, protocolRequest->coapID,
1474 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
1475 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1476 protocolRequest->observationOption, protocolRequest->qos,
1477 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1478 protocolRequest->reqJSONPayload, protocolRequest->requestToken,
1479 protocolRequest->tokenLength,
1480 protocolRequest->resourceUrl,protocolRequest->reqTotalSize,
1481 &protocolRequest->addressInfo, protocolRequest->connectivityType);
1482 if (OC_STACK_OK != result)
1484 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1490 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1491 return OC_STACK_NO_MEMORY;
1494 if(!protocolRequest->reqMorePacket)
1496 request->requestComplete = 1;
1502 PCF("This is either a repeated or blocked Server Request"));
1505 if(request->requestComplete)
1507 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1508 result = DetermineResourceHandling (request, &resHandling, &resource);
1509 if (result == OC_STACK_OK)
1511 result = ProcessRequest(resHandling, resource, request);
1516 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1517 result = OC_STACK_CONTINUE;
1522 bool ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
1526 uint8_t dotCount = 0;
1530 /* search for scheme */
1532 if (!isdigit((char) *ipAddrStr))
1534 coap = OC_COAP_SCHEME;
1535 while (*coap && tolower(*itr) == *coap)
1543 while (*ipAddrStr) {
1544 if (isdigit(*ipAddrStr))
1546 ipAddr[index] *= 10;
1547 ipAddr[index] += *ipAddrStr - '0';
1549 else if (*ipAddrStr == '.')
1561 if(*ipAddrStr == ':')
1565 if (isdigit(*ipAddrStr))
1568 *port += *ipAddrStr - '0';
1578 return (3 == dotCount);
1581 //-----------------------------------------------------------------------------
1583 //-----------------------------------------------------------------------------
1585 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1589 OCStackResult result = OC_STACK_ERROR;
1590 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1593 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1595 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1596 return OC_STACK_ERROR;
1600 defaultDeviceHandler = NULL;
1603 result = CAResultToOCResult(CAInitialize());
1604 VERIFY_SUCCESS(result, OC_STACK_OK);
1606 result = CAResultToOCResult(OCSelectNetwork());
1607 VERIFY_SUCCESS(result, OC_STACK_OK);
1609 CARegisterHandler(HandleCARequests, HandleCAResponses);
1610 switch (myStackMode)
1613 result = CAResultToOCResult(CAStartDiscoveryServer());
1614 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1617 result = CAResultToOCResult(CAStartListeningServer());
1618 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1620 case OC_CLIENT_SERVER:
1621 result = CAResultToOCResult(CAStartListeningServer());
1622 if(result == OC_STACK_OK)
1624 result = CAResultToOCResult(CAStartDiscoveryServer());
1628 VERIFY_SUCCESS(result, OC_STACK_OK);
1630 #if defined(__WITH_DTLS__)
1631 result = (CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials) == CA_STATUS_OK) ?
1632 OC_STACK_OK : OC_STACK_ERROR;
1633 VERIFY_SUCCESS(result, OC_STACK_OK);
1634 #endif // (__WITH_DTLS__)
1636 #ifdef WITH_PRESENCE
1637 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1638 #endif // WITH_PRESENCE
1640 //Update Stack state to initialized
1641 stackState = OC_STACK_INITIALIZED;
1643 // Initialize resource
1644 if(myStackMode != OC_CLIENT)
1646 result = initResources();
1650 if(result != OC_STACK_OK)
1652 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1653 deleteAllResources();
1655 stackState = OC_STACK_UNINITIALIZED;
1660 OCStackResult OCStop()
1662 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1664 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1666 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1669 else if (stackState != OC_STACK_INITIALIZED)
1671 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1672 return OC_STACK_ERROR;
1675 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1677 #ifdef WITH_PRESENCE
1678 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1679 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1680 presenceResource.presenceTTL = 0;
1681 #endif // WITH_PRESENCE
1683 // Free memory dynamically allocated for resources
1684 deleteAllResources();
1687 // Remove all observers
1688 DeleteObserverList();
1689 // Remove all the client callbacks
1690 DeleteClientCBList();
1691 // Deinit security blob
1692 DeinitOCSecurityInfo();
1693 stackState = OC_STACK_UNINITIALIZED;
1697 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1702 return CA_MSG_CONFIRM;
1707 return CA_MSG_NONCONFIRM;
1711 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1715 query = strchr (inputUri, '?');
1719 if((query - inputUri) > MAX_URI_LENGTH)
1721 return OC_STACK_INVALID_URI;
1724 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1726 return OC_STACK_INVALID_QUERY;
1729 else if(uriLen > MAX_URI_LENGTH)
1731 return OC_STACK_INVALID_URI;
1736 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1737 const char *referenceUri, const char *request, OCConnectivityType conType,
1738 OCQualityOfService qos, OCCallbackData *cbData,
1739 OCHeaderOption * options, uint8_t numOptions)
1741 OCStackResult result = OC_STACK_ERROR;
1742 ClientCB *clientCB = NULL;
1743 char * requestUri = NULL;
1744 char * resourceType = NULL;
1745 char * query = NULL;
1746 char * newUri = (char *)requiredUri;
1747 (void) referenceUri;
1748 CARemoteEndpoint_t* endpoint = NULL;
1749 CAResult_t caResult;
1750 CAToken_t token = NULL;
1751 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1752 OCDoHandle resHandle = NULL;
1753 CAInfo_t requestData ={};
1754 CARequestInfo_t requestInfo ={};
1755 CAGroupEndpoint_t grpEnd = {};
1757 // To track if memory is allocated for additional header options
1759 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1761 // Validate input parameters
1762 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1763 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1765 //TODO ("Need to form the final query by concatenating require and reference URI's");
1766 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1768 uint16_t uriLen = strlen(requiredUri);
1770 // ToDo: We should also check if the requiredUri has a mutlicast address,
1771 // then qos has to be OC_Low_QOS
1777 case OC_REST_DELETE:
1778 case OC_REST_OBSERVE:
1779 case OC_REST_OBSERVE_ALL:
1780 case OC_REST_CANCEL_OBSERVE:
1782 #ifdef WITH_PRESENCE
1783 case OC_REST_PRESENCE:
1787 result = OC_STACK_INVALID_METHOD;
1791 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1796 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1798 result = OC_STACK_INVALID_PARAM;
1802 #ifdef WITH_PRESENCE
1803 if(method == OC_REST_PRESENCE)
1805 result = getQueryFromUri(requiredUri, &query, &newUri);
1808 result = getResourceType((char *) query, &resourceType);
1812 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1816 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1821 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1823 if(result != OC_STACK_OK)
1828 #endif // WITH_PRESENCE
1830 requestUri = (char *) OCMalloc(uriLen + 1);
1833 memcpy(requestUri, newUri, (uriLen + 1));
1837 result = OC_STACK_NO_MEMORY;
1841 resHandle = GenerateInvocationHandle();
1844 result = OC_STACK_NO_MEMORY;
1851 case OC_REST_OBSERVE:
1852 case OC_REST_OBSERVE_ALL:
1853 case OC_REST_CANCEL_OBSERVE:
1855 requestInfo.method = CA_GET;
1860 requestInfo.method = CA_PUT;
1865 requestInfo.method = CA_POST;
1868 case OC_REST_DELETE:
1870 requestInfo.method = CA_DELETE;
1873 #ifdef WITH_PRESENCE
1874 case OC_REST_PRESENCE:
1876 // Replacing method type with GET because "presence"
1877 // is a stack layer only implementation.
1878 requestInfo.method = CA_GET;
1883 result = OC_STACK_INVALID_METHOD;
1888 caResult = CAGenerateToken(&token, tokenLength);
1889 if (caResult != CA_STATUS_OK)
1891 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1892 CADestroyToken(token);
1893 result = CAResultToOCResult (caResult);
1897 requestData.type = qualityOfServiceToMessageType(qos);
1898 requestData.token = token;
1899 requestData.tokenLength = tokenLength;
1900 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1902 result = CreateObserveHeaderOption (&(requestData.options), options,
1903 numOptions, OC_OBSERVE_REGISTER);
1904 if (result != OC_STACK_OK)
1908 requestData.numOptions = numOptions + 1;
1912 requestData.options = (CAHeaderOption_t*)options;
1913 requestData.numOptions = numOptions;
1915 requestData.payload = (char *)request;
1917 requestInfo.info = requestData;
1919 CAConnectivityType_t caConType;
1921 result = OCToCAConnectivityType((OCConnectivityType) conType, &caConType);
1922 if (result != OC_STACK_OK)
1924 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1929 if(conType == OC_ALL)
1931 grpEnd.connectivityType = caConType;
1933 grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1934 if(!grpEnd.resourceUri)
1936 result = OC_STACK_NO_MEMORY;
1939 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1941 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1945 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1947 if (caResult != CA_STATUS_OK)
1949 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1950 result = CAResultToOCResult (caResult);
1951 CADestroyToken(token);
1955 caResult = CASendRequest(endpoint, &requestInfo);
1958 if (caResult != CA_STATUS_OK)
1960 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1961 result = CAResultToOCResult (caResult);
1962 CADestroyToken(token);
1966 if((result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle, method,
1967 requestUri, resourceType, conType)) != OC_STACK_OK)
1969 result = OC_STACK_NO_MEMORY;
1975 *handle = resHandle;
1979 if(newUri != requiredUri)
1983 if (result != OC_STACK_OK)
1985 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1986 FindAndDeleteClientCB(clientCB);
1989 OCFree(resourceType);
1991 CADestroyRemoteEndpoint(endpoint);
1992 OCFree(grpEnd.resourceUri);
1993 if (requestData.options && requestData.numOptions > 0)
1995 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1997 OCFree(requestData.options);
2003 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2007 * This ftn is implemented one of two ways in the case of observation:
2009 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2010 * Remove the callback associated on client side.
2011 * When the next notification comes in from server,
2012 * reply with RESET message to server.
2013 * Keep in mind that the server will react to RESET only
2014 * if the last notification was sent as CON
2016 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2017 * and it is associated with an observe request
2018 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2019 * Send CON Observe request to server with
2020 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2021 * Remove the callback associated on client side.
2023 OCStackResult ret = OC_STACK_OK;
2024 CARemoteEndpoint_t* endpoint = NULL;
2025 CAResult_t caResult;
2026 CAInfo_t requestData = {};
2027 CARequestInfo_t requestInfo = {};
2031 return OC_STACK_INVALID_PARAM;
2034 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
2036 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2040 switch (clientCB->method)
2042 case OC_REST_OBSERVE:
2043 case OC_REST_OBSERVE_ALL:
2044 OC_LOG(INFO, TAG, PCF("Canceling observation"));
2045 if(qos == OC_HIGH_QOS)
2047 requestData.type = qualityOfServiceToMessageType(qos);
2048 requestData.token = clientCB->token;
2049 requestData.tokenLength = clientCB->tokenLength;
2050 if (CreateObserveHeaderOption (&(requestData.options),
2051 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2053 return OC_STACK_ERROR;
2055 requestData.numOptions = numOptions + 1;
2056 requestInfo.method = CA_GET;
2057 requestInfo.info = requestData;
2059 CAConnectivityType_t caConType;
2060 ret = OCToCAConnectivityType(clientCB->conType, &caConType);
2061 if(ret != OC_STACK_OK)
2066 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri,
2067 caConType, &endpoint);
2068 if (caResult != CA_STATUS_OK)
2070 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
2071 ret = OC_STACK_ERROR;
2076 caResult = CASendRequest(endpoint, &requestInfo);
2077 if (caResult != CA_STATUS_OK)
2079 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2080 ret = OC_STACK_ERROR;
2082 ret = CAResultToOCResult (caResult);
2086 FindAndDeleteClientCB(clientCB);
2089 #ifdef WITH_PRESENCE
2090 case OC_REST_PRESENCE:
2091 FindAndDeleteClientCB(clientCB);
2095 ret = OC_STACK_INVALID_METHOD;
2100 CADestroyRemoteEndpoint(endpoint);
2101 if (requestData.numOptions > 0)
2103 OCFree(requestData.options);
2109 #ifdef WITH_PRESENCE
2110 OCStackResult OCProcessPresence()
2112 OCStackResult result = OC_STACK_OK;
2113 uint8_t ipAddr[4] = { 0 };
2116 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2117 ClientCB* cbNode = NULL;
2119 OCClientResponse clientResponse ={};
2120 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2122 LL_FOREACH(cbList, cbNode)
2124 if(OC_REST_PRESENCE == cbNode->method)
2126 if(cbNode->presence)
2128 uint32_t now = GetTime(0);
2129 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2130 cbNode->presence->TTLlevel);
2131 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2134 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2139 if(cbNode->presence->TTLlevel < PresenceTimeOutSize)
2141 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2142 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2145 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2147 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2148 if (ParseIPv4Address(cbNode->requestUri, ipAddr, &port))
2150 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
2153 clientResponse.sequenceNumber = 0;
2154 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2155 clientResponse.addr = (OCDevAddr *) &dst;
2156 clientResponse.resJSONPayload = NULL;
2158 // Increment the TTLLevel (going to a next state), so we don't keep
2159 // sending presence notification to client.
2160 cbNode->presence->TTLlevel++;
2161 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2162 cbNode->presence->TTLlevel);
2166 result = OC_STACK_INVALID_IP;
2170 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2171 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2173 FindAndDeleteClientCB(cbNode);
2177 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2179 CAResult_t caResult = CA_STATUS_OK;
2180 CARemoteEndpoint_t* endpoint = NULL;
2181 CAInfo_t requestData ={};
2182 CARequestInfo_t requestInfo = {};
2184 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2187 CAConnectivityType_t caConType;
2188 result = OCToCAConnectivityType(cbNode->conType, &caConType);
2189 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, caConType,
2191 if (caResult != CA_STATUS_OK || result != OC_STACK_OK)
2193 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
2197 requestData.type = CA_MSG_NONCONFIRM;
2198 requestData.token = cbNode->token;
2200 requestInfo.method = CA_GET;
2201 requestInfo.info = requestData;
2203 caResult = CASendRequest(endpoint, &requestInfo);
2204 CADestroyRemoteEndpoint(endpoint);
2206 if (caResult != CA_STATUS_OK)
2208 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2212 cbNode->presence->TTLlevel++;
2213 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2214 cbNode->presence->TTLlevel);
2220 if (result != OC_STACK_OK)
2222 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2226 #endif // WITH_PRESENCE
2228 OCStackResult OCProcess()
2230 #ifdef WITH_PRESENCE
2231 OCProcessPresence();
2233 CAHandleRequestResponse();
2238 #ifdef WITH_PRESENCE
2239 OCStackResult OCStartPresence(const uint32_t ttl)
2241 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2242 OCChangeResourceProperty(
2243 &(((OCResource *)presenceResource.handle)->resourceProperties),
2248 presenceResource.presenceTTL = ttl;
2251 if(OC_PRESENCE_UNINITIALIZED == presenceState)
2253 presenceState = OC_PRESENCE_INITIALIZED;
2255 CAAddress_t addressInfo;
2256 strncpy(addressInfo.IP.ipAddress, OC_MULTICAST_IP, CA_IPADDR_SIZE);
2257 addressInfo.IP.port = OC_MULTICAST_PORT;
2259 CAToken_t caToken = NULL;
2260 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2261 if (caResult != CA_STATUS_OK)
2263 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2264 CADestroyToken(caToken);
2265 return OC_STACK_ERROR;
2268 CAConnectivityType_t connType;
2269 OCToCAConnectivityType(OC_ALL, &connType );
2270 AddObserver(OC_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2271 (OCResource *)presenceResource.handle, OC_LOW_QOS,
2272 &addressInfo, connType);
2273 CADestroyToken(caToken);
2276 // Each time OCStartPresence is called
2277 // a different random 32-bit integer number is used
2278 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2280 return SendPresenceNotification(NULL);
2283 OCStackResult OCStopPresence()
2285 OCStackResult result = OC_STACK_ERROR;
2287 if(presenceResource.handle)
2289 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2292 // make resource inactive
2293 result = OCChangeResourceProperty(
2294 &(((OCResource *) presenceResource.handle)->resourceProperties),
2297 if(result != OC_STACK_OK)
2300 PCF("Changing the presence resource properties to ACTIVE not successful"));
2304 return SendStopNotification();
2308 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
2310 defaultDeviceHandler = entityHandler;
2315 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2317 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2319 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2321 return SaveDeviceInfo(deviceInfo);
2325 return OC_STACK_ERROR;
2329 OCStackResult OCCreateResource(OCResourceHandle *handle,
2330 const char *resourceTypeName,
2331 const char *resourceInterfaceName,
2332 const char *uri, OCEntityHandler entityHandler,
2333 uint8_t resourceProperties)
2336 OCResource *pointer = NULL;
2339 OCStackResult result = OC_STACK_ERROR;
2341 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2343 if(myStackMode == OC_CLIENT)
2345 return OC_STACK_INVALID_PARAM;
2347 // Validate parameters
2348 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2350 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2351 return OC_STACK_INVALID_URI;
2353 // Is it presented during resource discovery?
2354 if (!handle || !resourceTypeName)
2356 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2357 return OC_STACK_INVALID_PARAM;
2360 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2362 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2365 // Make sure resourceProperties bitmask has allowed properties specified
2366 if (resourceProperties
2367 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
2368 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2369 return OC_STACK_INVALID_PARAM;
2372 // If the headResource is NULL, then no resources have been created...
2373 pointer = headResource;
2376 // At least one resources is in the resource list, so we need to search for
2377 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2380 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2382 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2383 return OC_STACK_INVALID_PARAM;
2385 pointer = pointer->next;
2388 // Create the pointer and insert it into the resource list
2389 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2392 result = OC_STACK_NO_MEMORY;
2395 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2397 insertResource(pointer);
2400 size = strlen(uri) + 1;
2401 str = (char *) OCMalloc(size);
2404 result = OC_STACK_NO_MEMORY;
2407 strncpy(str, uri, size);
2410 // Set properties. Set OC_ACTIVE
2411 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2414 // Add the resourcetype to the resource
2415 result = BindResourceTypeToResource(pointer, resourceTypeName);
2416 if (result != OC_STACK_OK)
2418 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2422 // Add the resourceinterface to the resource
2423 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2424 if (result != OC_STACK_OK)
2426 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2430 // If an entity handler has been passed, attach it to the newly created
2431 // resource. Otherwise, set the default entity handler.
2434 pointer->entityHandler = entityHandler;
2438 pointer->entityHandler = defaultResourceEHandler;
2442 result = OC_STACK_OK;
2444 #ifdef WITH_PRESENCE
2445 if(presenceResource.handle)
2447 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2448 SendPresenceNotification(pointer->rsrcType);
2452 if (result != OC_STACK_OK)
2454 // Deep delete of resource and other dynamic elements that it contains
2455 deleteResource(pointer);
2461 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2462 const char *resourceTypeName,
2463 const char *resourceInterfaceName,
2466 OCEntityHandler entityHandler,
2467 uint8_t resourceProperties)
2474 return OC_STACK_INVALID_PARAM;
2477 OCStackResult result = OC_STACK_ERROR;
2479 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2480 uri, entityHandler, resourceProperties);
2482 if (result != OC_STACK_ERROR)
2485 size = strlen(host) + 1;
2486 str = (char *) OCMalloc(size);
2489 return OC_STACK_NO_MEMORY;
2491 strncpy(str, host, size);
2492 ((OCResource *) *handle)->host = str;
2498 OCStackResult OCBindResource(
2499 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2501 OCResource *resource = NULL;
2504 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2506 // Validate parameters
2507 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2508 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2509 // Container cannot contain itself
2510 if (collectionHandle == resourceHandle)
2512 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2513 return OC_STACK_INVALID_PARAM;
2516 // Use the handle to find the resource in the resource linked list
2517 resource = findResource((OCResource *) collectionHandle);
2520 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2521 return OC_STACK_INVALID_PARAM;
2524 // Look for an open slot to add add the child resource.
2525 // If found, add it and return success
2526 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2528 if (!resource->rsrcResources[i])
2530 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2531 OC_LOG(INFO, TAG, PCF("resource bound"));
2533 #ifdef WITH_PRESENCE
2534 if(presenceResource.handle)
2536 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2537 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2545 // Unable to add resourceHandle, so return error
2546 return OC_STACK_ERROR;
2549 OCStackResult OCUnBindResource(
2550 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2552 OCResource *resource = NULL;
2555 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2557 // Validate parameters
2558 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2559 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2560 // Container cannot contain itself
2561 if (collectionHandle == resourceHandle)
2563 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2564 return OC_STACK_INVALID_PARAM;
2567 // Use the handle to find the resource in the resource linked list
2568 resource = findResource((OCResource *) collectionHandle);
2571 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2572 return OC_STACK_INVALID_PARAM;
2575 // Look for an open slot to add add the child resource.
2576 // If found, add it and return success
2577 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2579 if (resourceHandle == resource->rsrcResources[i])
2581 resource->rsrcResources[i] = (OCResource *) NULL;
2582 OC_LOG(INFO, TAG, PCF("resource unbound"));
2584 // Send notification when resource is unbounded successfully.
2585 #ifdef WITH_PRESENCE
2586 if(presenceResource.handle)
2588 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2589 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2596 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2598 // Unable to add resourceHandle, so return error
2599 return OC_STACK_ERROR;
2602 OCStackResult BindResourceTypeToResource(OCResource* resource,
2603 const char *resourceTypeName)
2605 OCResourceType *pointer = NULL;
2608 OCStackResult result = OC_STACK_ERROR;
2610 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2612 // Validate parameters
2613 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2614 // TODO: Does resource attribute representation really have to be maintained in stack?
2615 // Is it presented during resource discovery?
2617 // Create the resourcetype and insert it into the resource list
2618 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2621 result = OC_STACK_NO_MEMORY;
2625 // Set the resourceTypeName
2626 size = strlen(resourceTypeName) + 1;
2627 str = (char *) OCMalloc(size);
2630 result = OC_STACK_NO_MEMORY;
2633 strncpy(str, resourceTypeName, size);
2634 pointer->resourcetypename = str;
2636 insertResourceType(resource, pointer);
2637 result = OC_STACK_OK;
2640 if (result != OC_STACK_OK)
2649 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2650 const char *resourceInterfaceName)
2652 OCResourceInterface *pointer = NULL;
2655 OCStackResult result = OC_STACK_ERROR;
2657 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2659 // Validate parameters
2660 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2662 //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2664 // Create the resourceinterface and insert it into the resource list
2665 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2668 result = OC_STACK_NO_MEMORY;
2672 // Set the resourceinterface name
2673 size = strlen(resourceInterfaceName) + 1;
2674 str = (char *) OCMalloc(size);
2677 result = OC_STACK_NO_MEMORY;
2680 strncpy(str, resourceInterfaceName, size);
2681 pointer->name = str;
2683 // Bind the resourceinterface to the resource
2684 insertResourceInterface(resource, pointer);
2686 result = OC_STACK_OK;
2689 if (result != OC_STACK_OK)
2698 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2699 const char *resourceTypeName)
2702 OCStackResult result = OC_STACK_ERROR;
2703 OCResource *resource = NULL;
2705 // Make sure resource exists
2706 resource = findResource((OCResource *) handle);
2709 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2710 return OC_STACK_ERROR;
2713 // call internal function
2714 result = BindResourceTypeToResource(resource, resourceTypeName);
2716 #ifdef WITH_PRESENCE
2717 if(presenceResource.handle)
2719 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2720 SendPresenceNotification(resource->rsrcType);
2727 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2728 const char *resourceInterfaceName)
2731 OCStackResult result = OC_STACK_ERROR;
2732 OCResource *resource = NULL;
2734 // Make sure resource exists
2735 resource = findResource((OCResource *) handle);
2738 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2739 return OC_STACK_ERROR;
2742 // call internal function
2743 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2745 #ifdef WITH_PRESENCE
2746 if(presenceResource.handle)
2748 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2749 SendPresenceNotification(resource->rsrcType);
2756 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2758 OCResource *pointer = headResource;
2760 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2761 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2765 *numResources = *numResources + 1;
2766 pointer = pointer->next;
2771 OCResourceHandle OCGetResourceHandle(uint8_t index)
2773 OCResource *pointer = headResource;
2775 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2777 // Iterate through the list
2778 for( uint8_t i = 0; i < index && pointer; ++i)
2780 pointer = pointer->next;
2782 return (OCResourceHandle) pointer;
2785 OCStackResult OCDeleteResource(OCResourceHandle handle)
2787 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2791 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2792 return OC_STACK_INVALID_PARAM;
2795 OCResource *resource = findResource((OCResource *) handle);
2796 if (resource == NULL)
2798 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2799 return OC_STACK_NO_RESOURCE;
2802 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
2804 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2805 return OC_STACK_ERROR;
2811 const char *OCGetResourceUri(OCResourceHandle handle)
2813 OCResource *resource = NULL;
2814 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2816 resource = findResource((OCResource *) handle);
2819 return resource->uri;
2821 return (const char *) NULL;
2824 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
2826 OCResource *resource = NULL;
2827 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2829 resource = findResource((OCResource *) handle);
2832 return resource->resourceProperties;
2834 return (OCResourceProperty)-1;
2837 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2838 uint8_t *numResourceTypes)
2840 OCResource *resource = NULL;
2841 OCResourceType *pointer = NULL;
2843 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2844 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2845 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2847 *numResourceTypes = 0;
2849 resource = findResource((OCResource *) handle);
2852 pointer = resource->rsrcType;
2855 *numResourceTypes = *numResourceTypes + 1;
2856 pointer = pointer->next;
2862 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
2864 OCResourceType *resourceType = NULL;
2866 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2868 resourceType = findResourceTypeAtIndex(handle, index);
2871 return resourceType->resourcetypename;
2873 return (const char *) NULL;
2876 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2877 uint8_t *numResourceInterfaces)
2879 OCResourceInterface *pointer = NULL;
2880 OCResource *resource = NULL;
2882 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2884 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2885 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2887 *numResourceInterfaces = 0;
2888 resource = findResource((OCResource *) handle);
2891 pointer = resource->rsrcInterface;
2894 *numResourceInterfaces = *numResourceInterfaces + 1;
2895 pointer = pointer->next;
2901 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
2903 OCResourceInterface *resourceInterface = NULL;
2905 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2907 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2908 if (resourceInterface)
2910 return resourceInterface->name;
2912 return (const char *) NULL;
2915 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2918 OCResource *resource = NULL;
2920 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2922 if (index >= MAX_CONTAINED_RESOURCES)
2927 resource = findResource((OCResource *) collectionHandle);
2933 return resource->rsrcResources[index];
2936 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2937 OCEntityHandler entityHandler)
2939 OCResource *resource = NULL;
2941 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2943 // Validate parameters
2944 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2946 // Use the handle to find the resource in the resource linked list
2947 resource = findResource((OCResource *)handle);
2950 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2951 return OC_STACK_ERROR;
2955 resource->entityHandler = entityHandler;
2957 #ifdef WITH_PRESENCE
2958 if(presenceResource.handle)
2960 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2961 SendPresenceNotification(resource->rsrcType);
2968 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
2970 OCResource *resource = NULL;
2972 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2974 // Use the handle to find the resource in the resource linked list
2975 resource = findResource((OCResource *)handle);
2978 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2983 return resource->entityHandler;
2986 void incrementSequenceNumber(OCResource * resPtr)
2988 // Increment the sequence number
2989 resPtr->sequenceNum += 1;
2990 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2992 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2997 #ifdef WITH_PRESENCE
2998 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
3000 OCResource *resPtr = NULL;
3001 OCStackResult result = OC_STACK_ERROR;
3002 OCMethod method = OC_REST_PRESENCE;
3003 uint32_t maxAge = 0;
3004 resPtr = findResource((OCResource *) presenceResource.handle);
3007 return OC_STACK_NO_RESOURCE;
3010 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3012 maxAge = presenceResource.presenceTTL;
3014 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
3020 OCStackResult SendStopNotification()
3022 OCResource *resPtr = NULL;
3023 OCStackResult result = OC_STACK_ERROR;
3024 OCMethod method = OC_REST_PRESENCE;
3025 resPtr = findResource((OCResource *) presenceResource.handle);
3028 return OC_STACK_NO_RESOURCE;
3031 // maxAge is 0. ResourceType is NULL.
3032 result = SendAllObserverNotification(method, resPtr, 0, NULL, OC_LOW_QOS);
3037 #endif // WITH_PRESENCE
3038 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3041 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3043 OCResource *resPtr = NULL;
3044 OCStackResult result = OC_STACK_ERROR;
3045 OCMethod method = OC_REST_NOMETHOD;
3046 uint32_t maxAge = 0;
3048 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3049 #ifdef WITH_PRESENCE
3050 if(handle == presenceResource.handle)
3054 #endif // WITH_PRESENCE
3055 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3057 // Verify that the resource exists
3058 resPtr = findResource ((OCResource *) handle);
3061 return OC_STACK_NO_RESOURCE;
3065 //only increment in the case of regular observing (not presence)
3066 incrementSequenceNumber(resPtr);
3067 method = OC_REST_OBSERVE;
3068 maxAge = MAX_OBSERVE_AGE;
3069 #ifdef WITH_PRESENCE
3070 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
3072 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3079 OCNotifyListOfObservers (OCResourceHandle handle,
3080 OCObservationId *obsIdList,
3081 uint8_t numberOfIds,
3082 const char *notificationJSONPayload,
3083 OCQualityOfService qos)
3085 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3087 OCResource *resPtr = NULL;
3088 //TODO: we should allow the server to define this
3089 uint32_t maxAge = MAX_OBSERVE_AGE;
3091 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3092 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3093 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3095 // Verify that the resource exists
3096 resPtr = findResource ((OCResource *) handle);
3097 if (NULL == resPtr || myStackMode == OC_CLIENT)
3099 return OC_STACK_NO_RESOURCE;
3103 incrementSequenceNumber(resPtr);
3105 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3106 notificationJSONPayload, maxAge, qos));
3109 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3111 OCStackResult result = OC_STACK_ERROR;
3112 OCServerRequest *serverRequest = NULL;
3114 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3116 // Validate input parameters
3117 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3118 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3120 // TODO: Placeholder for creating a response entry when implementing
3121 // block transfer feature
3123 // If a response payload is present, check if block transfer is required
3124 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3125 (const char *)ehResponse->payload, ehResponse->payloadSize))
3127 OC_LOG(INFO, TAG, PCF("Block transfer required"));
3129 // Persistent response buffer is needed for block transfer
3130 if (!ehResponse->persistentBufferFlag)
3132 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3133 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3135 // TODO: Placeholder for block transfer handling
3136 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3137 // when implementing the block transfer feature
3142 // Get pointer to request info
3143 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3146 result = serverRequest->ehResponseHandler(ehResponse);
3152 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
3154 OCStackResult result = OC_STACK_NOTIMPL;
3156 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
3158 // TODO: validate response handle
3163 //-----------------------------------------------------------------------------
3164 // Private internal function definitions
3165 //-----------------------------------------------------------------------------
3166 static OCDoHandle GenerateInvocationHandle()
3168 OCDoHandle handle = NULL;
3169 // Generate token here, it will be deleted when the transaction is deleted
3170 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3173 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3179 #ifdef WITH_PRESENCE
3180 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3181 OCResourceProperty resourceProperties, uint8_t enable)
3185 return OC_STACK_INVALID_PARAM;
3187 if (resourceProperties
3188 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3190 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3191 return OC_STACK_INVALID_PARAM;
3195 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3199 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3205 OCStackResult initResources()
3207 OCStackResult result = OC_STACK_OK;
3208 // Init application resource vars
3209 headResource = NULL;
3210 tailResource = NULL;
3211 // Init Virtual Resources
3212 #ifdef WITH_PRESENCE
3213 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3214 //presenceResource.token = OCGenerateCoAPToken();
3215 result = OCCreateResource(&presenceResource.handle,
3216 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3221 //make resource inactive
3222 result = OCChangeResourceProperty(
3223 &(((OCResource *) presenceResource.handle)->resourceProperties),
3229 void insertResource(OCResource *resource)
3231 if (!headResource) {
3232 headResource = resource;
3233 tailResource = resource;
3237 tailResource->next = resource;
3238 tailResource = resource;
3240 resource->next = NULL;
3243 OCResource *findResource(OCResource *resource)
3245 OCResource *pointer = headResource;
3249 if (pointer == resource)
3253 pointer = pointer->next;
3258 void deleteAllResources()
3260 OCResource *pointer = headResource;
3261 OCResource *temp = NULL;
3265 temp = pointer->next;
3266 #ifdef WITH_PRESENCE
3267 if(pointer != (OCResource *) presenceResource.handle)
3269 #endif // WITH_PRESENCE
3270 deleteResource(pointer);
3271 #ifdef WITH_PRESENCE
3273 #endif // WITH_PRESENCE
3277 #ifdef WITH_PRESENCE
3278 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3279 // presence notification attributed to their deletion to be processed.
3280 deleteResource((OCResource *) presenceResource.handle);
3281 #endif // WITH_PRESENCE
3284 OCStackResult deleteResource(OCResource *resource)
3286 OCResource *prev = NULL;
3287 OCResource *temp = NULL;
3289 temp = headResource;
3292 if (temp == resource)
3294 // Invalidate all Resource Properties.
3295 resource->resourceProperties = (OCResourceProperty) 0;
3296 #ifdef WITH_PRESENCE
3297 if(resource != (OCResource *) presenceResource.handle)
3299 #endif // WITH_PRESENCE
3300 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3301 #ifdef WITH_PRESENCE
3304 if(presenceResource.handle)
3306 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3307 if(resource != (OCResource *) presenceResource.handle)
3309 SendPresenceNotification(resource->rsrcType);
3313 SendPresenceNotification(NULL);
3317 // Only resource in list.
3318 if (temp == headResource && temp == tailResource)
3320 headResource = NULL;
3321 tailResource = NULL;
3324 else if (temp == headResource)
3326 headResource = temp->next;
3329 else if (temp == tailResource)
3331 tailResource = prev;
3332 tailResource->next = NULL;
3336 prev->next = temp->next;
3339 deleteResourceElements(temp);
3350 return OC_STACK_ERROR;
3353 void deleteResourceElements(OCResource *resource)
3361 OCFree(resource->uri);
3363 // Delete resourcetype linked list
3364 deleteResourceType(resource->rsrcType);
3366 // Delete resourceinterface linked list
3367 deleteResourceInterface(resource->rsrcInterface);
3370 void deleteResourceType(OCResourceType *resourceType)
3372 OCResourceType *pointer = resourceType;
3373 OCResourceType *next = NULL;
3377 next = pointer->next;
3378 OCFree(pointer->resourcetypename);
3384 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3386 OCResourceInterface *pointer = resourceInterface;
3387 OCResourceInterface *next = NULL;
3391 next = pointer->next;
3392 OCFree(pointer->name);
3398 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3400 OCResourceType *pointer = NULL;
3401 OCResourceType *previous = NULL;
3402 if (!resource || !resourceType)
3406 // resource type list is empty.
3407 else if (!resource->rsrcType)
3409 resource->rsrcType = resourceType;
3413 pointer = resource->rsrcType;
3417 // resource type already exists. Free 2nd arg and return.
3418 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3420 OCFree(resourceType->resourcetypename);
3421 OCFree(resourceType);
3425 pointer = pointer->next;
3427 previous->next = resourceType;
3429 resourceType->next = NULL;
3432 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3434 OCResource *resource = NULL;
3435 OCResourceType *pointer = NULL;
3437 // Find the specified resource
3438 resource = findResource((OCResource *) handle);
3444 // Make sure a resource has a resourcetype
3445 if (!resource->rsrcType)
3450 // Iterate through the list
3451 pointer = resource->rsrcType;
3452 for(uint8_t i = 0; i< index && pointer; ++i)
3454 pointer = pointer->next;
3459 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3461 if(resourceTypeList && resourceTypeName)
3463 OCResourceType * rtPointer = resourceTypeList;
3464 while(resourceTypeName && rtPointer)
3466 if(rtPointer->resourcetypename &&
3467 strcmp(resourceTypeName, (const char *)
3468 (rtPointer->resourcetypename)) == 0)
3472 rtPointer = rtPointer->next;
3479 void insertResourceInterface(OCResource *resource,
3480 OCResourceInterface *resourceInterface)
3482 OCResourceInterface *pointer = NULL;
3483 OCResourceInterface *previous = NULL;
3485 if (!resource->rsrcInterface)
3487 resource->rsrcInterface = resourceInterface;
3491 pointer = resource->rsrcInterface;
3494 // resource type already exists. Free 2nd arg and return.
3495 if (!strcmp(resourceInterface->name, pointer->name))
3497 OCFree(resourceInterface->name);
3498 OCFree(resourceInterface);
3502 pointer = pointer->next;
3504 previous->next = resourceInterface;
3506 resourceInterface->next = NULL;
3509 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3512 OCResource *resource = NULL;
3513 OCResourceInterface *pointer = NULL;
3515 // Find the specified resource
3516 resource = findResource((OCResource *) handle);
3522 // Make sure a resource has a resourceinterface
3523 if (!resource->rsrcInterface)
3528 // Iterate through the list
3529 pointer = resource->rsrcInterface;
3531 for (uint8_t i = 0; i < index && pointer; ++i)
3533 pointer = pointer->next;
3538 bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size)
3540 bool result = false;
3542 // Determine if we are checking a request or a response
3545 // If size is greater than 0, use it for the request size value, otherwise
3546 // assume request is null terminated and use strlen for size value
3547 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3554 // If size is greater than 0, use it for the response size value, otherwise
3555 // assume response is null terminated and use strlen for size value
3556 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3564 OCStackResult getResourceType(const char * query, char** resourceType)
3568 return OC_STACK_INVALID_PARAM;
3571 OCStackResult result = OC_STACK_ERROR;
3573 if(strncmp(query, "rt=", 3) == 0)
3575 *resourceType = (char *) OCMalloc(strlen(query)-3 + 1);
3578 result = OC_STACK_NO_MEMORY;
3582 strcpy((char *)*resourceType, ((const char *)&query[3]));
3583 result = OC_STACK_OK;
3590 OCStackResult getQueryFromUri(const char * uri, char** query, char ** newURI)
3594 return OC_STACK_INVALID_URI;
3596 if(!query || !newURI)
3598 return OC_STACK_INVALID_PARAM;
3600 char* strTokPtr = NULL;
3601 char * leftToken = NULL;
3602 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3607 strcpy(tempURI, uri);
3609 leftToken = strtok_r(tempURI, "?", &strTokPtr);
3611 //TODO-CA: This could be simplified. Clean up required.
3612 while(leftToken != NULL)
3614 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3616 *query = (char *) OCMalloc(strlen(leftToken) + 1);
3622 strcpy(*query, leftToken);
3625 leftToken = strtok_r(NULL, "?", &strTokPtr);
3633 return OC_STACK_NO_MEMORY;
3636 const ServerID OCGetServerInstanceID(void)
3638 static bool generated = false;
3639 static ServerID sid;
3645 sid = OCGetRandom();
3650 const char* OCGetServerInstanceIDString(void)
3652 // max printed length of a base 10
3653 // uint32 is 10 characters, so 11 includes null.
3654 // This will change as the representation gets switched
3656 static char buffer[11];
3658 if (snprintf(buffer, sizeof(buffer),"%u", OCGetServerInstanceID()) < 0)
3666 int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
3667 uint8_t *c, uint8_t *d )
3669 if ( !ipAddr || !a || !b || !c || !d )
3671 OC_LOG(FATAL, TAG, PCF("Invalid argument"));
3672 return OC_STACK_INVALID_PARAM;
3675 *a = ipAddr->addr[0];
3676 *b = ipAddr->addr[1];
3677 *c = ipAddr->addr[2];
3678 *d = ipAddr->addr[3];
3683 int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
3685 if ( !ipAddr || !port )
3687 OC_LOG(FATAL, TAG, PCF("Invalid argument"));
3688 return OC_STACK_INVALID_PARAM;
3691 *port = (ipAddr->addr[5]<< 8) | ipAddr->addr[4];
3696 CAResult_t OCSelectNetwork()
3698 CAResult_t retResult = CA_STATUS_FAILED;
3699 CAResult_t caResult = CA_STATUS_OK;
3701 CAConnectivityType_t connTypes[] = {
3706 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3708 for(int i = 0; i<numConnTypes; i++)
3710 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3711 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3713 caResult = CASelectNetwork(connTypes[i]);
3714 if(caResult == CA_STATUS_OK)
3716 retResult = CA_STATUS_OK;
3721 if(retResult != CA_STATUS_OK)
3723 return caResult; // Returns error of appropriate transport that failed fatally.
3729 OCStackResult CAResultToOCResult(CAResult_t caResult)
3735 case CA_STATUS_INVALID_PARAM:
3736 return OC_STACK_INVALID_PARAM;
3737 case CA_ADAPTER_NOT_ENABLED:
3738 return OC_STACK_ADAPTER_NOT_ENABLED;
3739 case CA_SERVER_STARTED_ALREADY:
3741 case CA_SERVER_NOT_STARTED:
3742 return OC_STACK_ERROR;
3743 case CA_DESTINATION_NOT_REACHABLE:
3744 return OC_STACK_COMM_ERROR;
3745 case CA_SOCKET_OPERATION_FAILED:
3746 return OC_STACK_COMM_ERROR;
3747 case CA_SEND_FAILED:
3748 return OC_STACK_COMM_ERROR;
3749 case CA_RECEVIE_FAILED:
3750 return OC_STACK_COMM_ERROR;
3751 case CA_MEMORY_ALLOC_FAILED:
3752 return OC_STACK_NO_MEMORY;
3753 case CA_REQUEST_TIMEOUT:
3754 return OC_STACK_TIMEOUT;
3755 case CA_DESTINATION_DISCONNECTED:
3756 return OC_STACK_COMM_ERROR;
3757 case CA_STATUS_FAILED:
3758 return OC_STACK_ERROR;
3759 case CA_NOT_SUPPORTED:
3760 return OC_STACK_NOTIMPL;
3762 return OC_STACK_ERROR;