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 //-----------------------------------------------------------------------------
25 #define _POSIX_C_SOURCE 200112L
30 #include "ocstackinternal.h"
31 #include "ocresourcehandler.h"
32 #include "occlientcb.h"
33 #include "ocobserve.h"
36 #include "ocserverrequest.h"
37 #include "ocsecurityinternal.h"
40 #include "cainterface.h"
47 #include "coap_time.h"
52 #include <arpa/inet.h>
55 //-----------------------------------------------------------------------------
57 //-----------------------------------------------------------------------------
59 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
63 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
67 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
70 static OCStackState stackState = OC_STACK_UNINITIALIZED;
72 OCResource *headResource = NULL;
74 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
75 static PresenceResource presenceResource;
76 uint8_t PresenceTimeOutSize = 0;
77 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
81 OCDeviceEntityHandler defaultDeviceHandler;
82 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
84 //-----------------------------------------------------------------------------
86 //-----------------------------------------------------------------------------
87 #define TAG PCF("OCStack")
88 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
89 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
90 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
91 TAG, PCF(#arg " is NULL")); return (retVal); } }
92 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
95 //TODO: we should allow the server to define this
96 #define MAX_OBSERVE_AGE (0x2FFFFUL)
98 //=============================================================================
100 //=============================================================================
101 static uint32_t GetTime(float afterSeconds)
105 return now + (uint32_t)(afterSeconds * COAP_TICKS_PER_SECOND);
108 static OCStackResult FormOCResponse(OCResponse * * responseLoc,
111 unsigned char * fullUri,
112 unsigned char * rcvdUri,
113 CAToken_t * rcvdToken,
114 OCClientResponse * clientResponse,
115 unsigned char * bufRes)
117 OCResponse * response = (OCResponse *) OCMalloc(sizeof(OCResponse));
120 return OC_STACK_NO_MEMORY;
122 response->cbNode = cbNode;
123 response->maxAge = maxAge;
124 response->fullUri = fullUri;
125 response->rcvdUri = rcvdUri;
126 response->rcvdToken = rcvdToken;
127 response->clientResponse = clientResponse;
128 response->bufRes = bufRes;
130 *responseLoc = response;
134 //-----------------------------------------------------------------------------
135 // Internal API function
136 //-----------------------------------------------------------------------------
138 // This internal function is called to update the stack with the status of
139 // observers and communication failures
140 OCStackResult OCStackFeedBack(CAToken_t * token, uint8_t status)
142 OCStackResult result = OC_STACK_ERROR;
143 ResourceObserver * observer = NULL;
144 OCEntityHandlerRequest ehRequest = {0};
148 case OC_OBSERVER_NOT_INTERESTED:
149 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
150 observer = GetObserverUsingToken (token);
153 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
154 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
155 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
156 if(result != OC_STACK_OK)
160 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
162 //observer is not observing anymore
163 result = DeleteObserverUsingToken (token);
164 if(result == OC_STACK_OK)
166 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
170 result = OC_STACK_OK;
171 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
174 case OC_OBSERVER_STILL_INTERESTED:
175 //observer is still interested
176 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
177 notifications, reset the failedCount"));
178 observer = GetObserverUsingToken (token);
181 observer->forceHighQos = 0;
182 observer->failedCommCount = 0;
183 result = OC_STACK_OK;
187 result = OC_STACK_OBSERVER_NOT_FOUND;
190 case OC_OBSERVER_FAILED_COMM:
191 //observer is not reachable
192 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
193 observer = GetObserverUsingToken (token);
196 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
198 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
199 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
200 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
201 if(result != OC_STACK_OK)
203 return OC_STACK_ERROR;
205 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
206 //observer is unreachable
207 result = DeleteObserverUsingToken (token);
208 if(result == OC_STACK_OK)
210 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
214 result = OC_STACK_OK;
215 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
220 observer->failedCommCount++;
221 result = OC_STACK_CONTINUE;
223 observer->forceHighQos = 1;
224 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
228 OC_LOG(ERROR, TAG, PCF("Unknown status"));
229 result = OC_STACK_ERROR;
235 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
237 OCStackResult ret = OC_STACK_ERROR;
245 ret = OC_STACK_RESOURCE_CREATED;
248 ret = OC_STACK_RESOURCE_DELETED;
251 ret = OC_STACK_INVALID_QUERY;
254 ret = OC_STACK_INVALID_OPTION;
257 ret = OC_STACK_NO_RESOURCE;
265 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
267 OCStackResult ret = OC_STACK_OK;
272 *caConType = CA_ETHERNET;
275 *caConType = CA_WIFI;
284 // Currently OC_ALL represents WIFI and ETHERNET
285 // Add other connectivity types as they are enabled in future
286 *caConType = (CAConnectivityType_t) (CA_WIFI|CA_ETHERNET);
289 ret = OC_STACK_INVALID_PARAM;
295 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
297 OCStackResult ret = OC_STACK_OK;
302 *ocConType = OC_ETHERNET;
305 *ocConType = OC_WIFI;
314 ret = OC_STACK_INVALID_PARAM;
320 // update response.addr appropriately from endPoint.addressInfo
321 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
323 OCStackResult ret = OC_STACK_ERROR;
324 static OCDevAddr address = {0};
326 char * savePtr = NULL;
327 char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
330 ret = OC_STACK_NO_MEMORY;
333 memcpy(cpAddress, endPoint->addressInfo.IP.ipAddress,
334 strlen(endPoint->addressInfo.IP.ipAddress) + 1);
336 // Grabs the first three numbers from the IPv4 address and replaces dots
337 for(int i=0; i<4; i++)
339 tok = strtok_r(i==0 ? cpAddress : NULL, ".", &savePtr);
343 ret = OC_STACK_ERROR;
346 address.addr[i] = atoi(tok);
349 memcpy(&address.addr[4], &endPoint->addressInfo.IP.port, sizeof(uint32_t));
353 response->addr = &address;
354 ret = CAToOCConnectivityType(endPoint->connectivityType, &(response->connType));
358 OC_LOG(ERROR, TAG, PCF("OCClientResponse is NULL!"));
365 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
369 // The format of the payload is {"oc":[%u:%u:%s]}
370 // %u : sequence number,
372 // %s : Resource Type (Optional)
373 tok = strtok_r(payload, "[:]}", &savePtr);
374 payload[strlen(payload)] = ':';
375 tok = strtok_r(NULL, "[:]}", &savePtr);
376 payload[strlen((char *)payload)] = ':';
377 *seqNum = (uint32_t) atoi(tok);
378 tok = strtok_r(NULL, "[:]}", &savePtr);
379 *maxAge = (uint32_t) atoi(tok);
380 tok = strtok_r(NULL, "[:]}",&savePtr);
384 *resType = (char *)OCMalloc(strlen(tok));
389 payload[strlen((char *)payload)] = ':';
390 strcpy(*resType, tok);
391 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
393 payload[strlen((char *)payload)] = ']';
396 OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
397 const CAResponseInfo_t* responseInfo)
399 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
400 ClientCB * cbNode = NULL;
401 char *resourceTypeName = NULL;
402 OCClientResponse response;
403 OCStackResult result = OC_STACK_ERROR;
404 uint32_t lowerBound = 0;
405 uint32_t higherBound = 0;
408 char *fullUri = NULL;
409 char *ipAddress = NULL;
410 int presenceSubscribe = 0;
411 int multicastPresenceSubscribe = 0;
413 if (responseInfo->result != CA_SUCCESS)
415 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
416 return OC_STACK_ERROR;
419 fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
423 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
424 result = OC_STACK_NO_MEMORY;
428 ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
430 if(NULL == ipAddress)
432 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
433 result = OC_STACK_NO_MEMORY;
437 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
438 strlen(endPoint->addressInfo.IP.ipAddress));
439 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
441 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
444 cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
448 presenceSubscribe = 1;
452 snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
453 cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
456 multicastPresenceSubscribe = 1;
460 if(!presenceSubscribe && !multicastPresenceSubscribe)
462 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
463 ------------ ignoring"));
467 // No payload to the application in case of presence
468 response.resJSONPayload = NULL;
469 response.result = OC_STACK_OK;
471 result = UpdateResponseAddr(&response, endPoint);
472 if(result != OC_STACK_OK)
477 if(responseInfo->info.payload)
479 parsePresencePayload(responseInfo->info.payload,
480 &(response.sequenceNumber),
487 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
488 response.result = OC_STACK_PRESENCE_STOPPED;
491 OCFree(cbNode->presence->timeOut);
492 OCFree(cbNode->presence);
493 cbNode->presence = NULL;
496 else if(presenceSubscribe)
498 if(!cbNode->presence)
500 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
501 VERIFY_NON_NULL_V(cbNode->presence);
502 cbNode->presence->timeOut = NULL;
503 cbNode->presence->timeOut = (uint32_t *)
504 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
505 if(!(cbNode->presence->timeOut)){
506 OCFree(cbNode->presence);
507 result = OC_STACK_NO_MEMORY;
511 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %u", GetTime(0));
512 cbNode->presence->TTL = maxAge;
513 for(int index = 0; index < PresenceTimeOutSize; index++)
515 lowerBound = GetTime(((float)(PresenceTimeOut[index])
516 /(float)100)*(float)cbNode->presence->TTL);
517 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
518 /(float)100)*(float)cbNode->presence->TTL);
519 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
520 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
521 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
522 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
523 cbNode->presence->timeOut[index]);
525 cbNode->presence->TTLlevel = 0;
526 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
527 if(cbNode->sequenceNumber == response.sequenceNumber)
529 OC_LOG(INFO, TAG, PCF("===============No presence change"));
532 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
533 cbNode->sequenceNumber = response.sequenceNumber;
535 // Ensure that a filter is actually applied.
536 if(resourceTypeName && cbNode->filterResourceType)
538 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
546 // This is the multicast case
548 OCMulticastNode* mcNode = NULL;
549 mcNode = GetMCPresenceNode((const unsigned char *)fullUri);
553 if(mcNode->nonce == response.sequenceNumber)
555 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
558 mcNode->nonce = response.sequenceNumber;
562 uint32_t uriLen = strlen((char*)fullUri);
563 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
566 memcpy(uri, fullUri, (uriLen + 1));
571 PCF("===============No Memory for URI to store in the presence node"));
572 result = OC_STACK_NO_MEMORY;
575 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
576 if(result == OC_STACK_NO_MEMORY)
579 PCF("===============No Memory for Multicast Presence Node"));
580 result = OC_STACK_NO_MEMORY;
585 // Ensure that a filter is actually applied.
586 if(resourceTypeName && cbNode->filterResourceType)
588 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
595 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
597 if (cbResult == OC_STACK_DELETE_TRANSACTION)
599 FindAndDeleteClientCB(cbNode);
605 OCFree(resourceTypeName);
610 //This function will be called back by CA layer when a response is received
611 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
613 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
615 OCStackApplicationResult appResult = OC_STACK_DELETE_TRANSACTION;
619 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
623 if(NULL == responseInfo)
625 OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
629 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
631 HandlePresenceResponse(endPoint, responseInfo);
635 ClientCB *cbNode = GetClientCB((CAToken_t *)&(responseInfo->info.token), NULL, NULL);
639 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
640 OCClientResponse response;
642 OCStackResult result = UpdateResponseAddr(&response, endPoint);
643 if(result != OC_STACK_OK)
645 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
649 response.result = CAToOCStackResult(responseInfo->result);
650 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
651 response.numRcvdVendorSpecificHeaderOptions = 0;
652 if(responseInfo->info.numOptions > 0)
655 //First option always with option ID is OC_COAP_OPTION_OBSERVE if it is available.
656 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
658 memcpy (&(response.sequenceNumber),
659 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
660 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
665 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
668 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
670 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
674 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
676 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
677 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
680 appResult = cbNode->callBack(cbNode->context,
681 cbNode->handle, &response);
682 if (appResult == OC_STACK_DELETE_TRANSACTION)
684 FindAndDeleteClientCB(cbNode);
687 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
688 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
691 //This function will be called back by CA layer when a request is received
692 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
694 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
697 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
703 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
707 OCStackResult requestResult = OC_STACK_ERROR;
709 if(myStackMode == OC_CLIENT)
711 //TODO: should the client be responding to requests?
715 OCServerProtocolRequest serverRequest;
717 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
718 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
720 char * newUri = (char *)endPoint->resourceUri;
721 unsigned char * query = NULL;
722 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
723 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
724 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
726 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
730 memcpy (&(serverRequest.query), query, strlen((char*)query));
732 //copy request payload
733 if (requestInfo->info.payload)
735 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
736 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
737 strlen(requestInfo->info.payload));
738 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
742 serverRequest.reqTotalSize = 1;
745 switch (requestInfo->method)
749 serverRequest.method = OC_REST_GET;
754 serverRequest.method = OC_REST_PUT;
759 serverRequest.method = OC_REST_POST;
764 serverRequest.method = OC_REST_DELETE;
769 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
774 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
775 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
777 serverRequest.requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
779 if (!serverRequest.requestToken)
781 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
784 memset(serverRequest.requestToken, 0, CA_MAX_TOKEN_LEN + 1);
785 memcpy(serverRequest.requestToken, requestInfo->info.token, CA_MAX_TOKEN_LEN);
787 if (requestInfo->info.type == CA_MSG_CONFIRM)
789 serverRequest.qos = OC_HIGH_QOS;
791 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
793 serverRequest.qos = OC_LOW_QOS;
795 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
797 // TODO-CA: Need to handle this
799 else if (requestInfo->info.type == CA_MSG_RESET)
801 // TODO-CA: Need to handle this
803 // CA does not need the following 3 fields
804 serverRequest.coapID = 0;
805 serverRequest.delayedResNeeded = 0;
806 serverRequest.secured = endPoint->isSecured;
809 serverRequest.addressInfo = endPoint->addressInfo;
810 serverRequest.connectivityType = endPoint->connectivityType;
812 // copy vendor specific header options
813 // TODO-CA: CA is including non-vendor header options as well, like observe.
814 // Need to filter those out
815 uint8_t tempNum = (requestInfo->info.numOptions);
816 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
817 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
820 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
821 OCFree(serverRequest.requestToken);
824 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
825 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
827 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
828 sizeof(CAHeaderOption_t)*tempNum);
831 requestResult = HandleStackRequests (&serverRequest);
832 if(requestResult != OC_STACK_OK)
834 OC_LOG(ERROR, TAG, PCF("HandleStackRequests failed"));
836 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
839 //This function will be called back by occoap layer when a request is received
840 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
842 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
843 OCStackResult result = OC_STACK_ERROR;
844 ResourceHandling resHandling;
845 OCResource *resource;
848 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
849 return OC_STACK_INVALID_PARAM;
852 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
855 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
856 result = AddServerRequest(&request, protocolRequest->coapID,
857 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
858 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
859 protocolRequest->observationOption, protocolRequest->qos,
860 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
861 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
862 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
863 protocolRequest->reqTotalSize,
864 &protocolRequest->addressInfo, protocolRequest->connectivityType);
865 if (OC_STACK_OK != result)
867 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
870 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
872 if(!protocolRequest->reqMorePacket)
874 request->requestComplete = 1;
879 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
882 if(request->requestComplete)
884 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
885 result = DetermineResourceHandling (request, &resHandling, &resource);
886 if (result == OC_STACK_OK)
888 result = ProcessRequest(resHandling, resource, request);
892 result = OC_STACK_ERROR;
897 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
898 result = OC_STACK_CONTINUE;
903 //This function will be called back by occoap layer when a response is received
904 OCStackResult HandleStackResponses(OCResponse * response)
906 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
907 OCStackResult result = OC_STACK_OK;
908 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
909 uint8_t isObserveNotification = 0;
910 ClientCB * cbNode = NULL;
913 OC_LOG(ERROR, TAG, PCF("response is NULL"));
914 return OC_STACK_INVALID_PARAM;
917 uint8_t isPresenceNotification = 0;
918 uint8_t isMulticastPresence = 0;
919 char * resourceTypeName = NULL;
920 uint32_t lowerBound = 0;
921 uint32_t higherBound = 0;
923 unsigned char * bufRes = response->bufRes;
924 #endif // WITH_PRESENCE
926 cbNode = response->cbNode;
929 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
932 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
934 isObserveNotification = 1;
935 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
938 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
939 response->clientResponse->sequenceNumber);
940 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
941 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
944 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
945 isPresenceNotification = 1;
948 result = OC_STACK_INVALID_PARAM;
952 tok = strtok_r((char *)bufRes, "[:]}", &savePtr);
953 bufRes[strlen((char *)bufRes)] = ':';
954 tok = strtok_r(NULL, "[:]}", &savePtr);
955 bufRes[strlen((char *)bufRes)] = ':';
956 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
957 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
958 tok = strtok_r(NULL, "[:]}", &savePtr);
959 response->maxAge = (uint32_t )atoi(tok);
960 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
961 tok = strtok_r(NULL, "[:]}", &savePtr);
964 resourceTypeName = (char *)OCMalloc(strlen(tok));
965 if(!resourceTypeName)
969 bufRes[strlen((char *)bufRes)] = ':';
970 strcpy(resourceTypeName, tok);
971 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
974 bufRes[strlen((char *)bufRes)] = ']';
977 // Check if the application subcribed for presence
980 cbNode = GetClientCB(NULL, NULL, response->fullUri);
983 // Check if application subscribed for multicast presence
986 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
987 OC_MULTICAST_IP, response->rcvdUri);
988 cbNode = GetClientCB(NULL, NULL, response->fullUri);
991 isMulticastPresence = 1;
992 isPresenceNotification = 0;
996 if(cbNode && isPresenceNotification)
998 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
999 if(!cbNode->presence)
1001 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
1002 VERIFY_NON_NULL_V(cbNode->presence);
1003 cbNode->presence->timeOut = NULL;
1004 cbNode->presence->timeOut = (uint32_t *)
1005 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1006 if(!(cbNode->presence->timeOut)){
1007 OCFree(cbNode->presence);
1008 result = OC_STACK_NO_MEMORY;
1011 if(response->maxAge == 0)
1013 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
1014 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
1015 if(cbNode->presence)
1017 OCFree(cbNode->presence->timeOut);
1018 OCFree(cbNode->presence);
1019 cbNode->presence = NULL;
1024 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
1025 cbNode->presence->TTL = response->maxAge;
1026 for(int index = 0; index < PresenceTimeOutSize; index++)
1028 lowerBound = GetTime(((float)(PresenceTimeOut[index])
1029 /(float)100)*(float)cbNode->presence->TTL);
1030 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
1031 /(float)100)*(float)cbNode->presence->TTL);
1032 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
1033 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
1034 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
1035 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
1036 cbNode->presence->timeOut[index]);
1038 cbNode->presence->TTLlevel = 0;
1039 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1040 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
1042 OC_LOG(INFO, TAG, PCF("===============No presence change"));
1045 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
1046 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
1049 // Ensure that a filter is actually applied.
1050 if(resourceTypeName && cbNode->filterResourceType)
1052 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1058 else if(cbNode && isMulticastPresence)
1060 // Check if the same nonce for a given host
1061 OCMulticastNode* mcNode = NULL;
1062 mcNode = GetMCPresenceNode(response->fullUri);
1064 if(response->maxAge == 0)
1066 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
1067 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
1068 if(cbNode->presence)
1070 OCFree(cbNode->presence->timeOut);
1071 OCFree(cbNode->presence);
1072 cbNode->presence = NULL;
1075 else if(mcNode != NULL)
1077 if(mcNode->nonce == response->clientResponse->sequenceNumber)
1079 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
1080 result = OC_STACK_NO_MEMORY;
1083 mcNode->nonce = response->clientResponse->sequenceNumber;
1087 uint32_t uriLen = strlen((char*)response->fullUri);
1088 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
1091 memcpy(uri, response->fullUri, (uriLen + 1));
1096 PCF("===============No Memory for URI to store in the presence node"));
1097 result = OC_STACK_NO_MEMORY;
1100 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
1101 response->clientResponse->sequenceNumber);
1102 if(result == OC_STACK_NO_MEMORY)
1105 PCF("===============No Memory for Multicast Presence Node"));
1106 result = OC_STACK_NO_MEMORY;
1111 // Ensure that a filter is actually applied.
1112 if(resourceTypeName && cbNode->filterResourceType)
1114 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1121 else if(!cbNode && isPresenceNotification)
1123 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
1124 ------------ ignoring"));
1126 #endif // WITH_PRESENCE
1130 if(isObserveNotification)
1132 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
1133 //TODO: check the standard for methods to detect wrap around condition
1134 if(cbNode->method == OC_REST_OBSERVE &&
1135 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
1136 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
1137 response->clientResponse->sequenceNumber ==
1138 MAX_SEQUENCE_NUMBER)))
1140 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
1141 Ignoring Incoming:%d Against Current:%d.",
1142 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
1145 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
1146 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
1150 response->clientResponse->resJSONPayload = bufRes;
1152 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
1154 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
1155 response->clientResponse->result == OC_STACK_COMM_ERROR ||
1156 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
1157 !isPresenceNotification && !isMulticastPresence))
1159 FindAndDeleteClientCB(cbNode);
1164 result = OC_STACK_ERROR;
1168 #ifdef WITH_PRESENCE
1169 OCFree(resourceTypeName);
1174 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
1177 unsigned char *itr, *coap;
1178 uint8_t dotCount = 0;
1182 /* search for scheme */
1184 if (!isdigit((unsigned char) *ipAddrStr))
1186 coap = (unsigned char *) OC_COAP_SCHEME;
1187 while (*coap && tolower(*itr) == *coap)
1195 while (*ipAddrStr) {
1196 if (isdigit((unsigned char) *ipAddrStr))
1198 ipAddr[index] *= 10;
1199 ipAddr[index] += *ipAddrStr - '0';
1201 else if ((unsigned char) *ipAddrStr == '.')
1213 if(*ipAddrStr == ':')
1217 if (isdigit((unsigned char) *ipAddrStr))
1220 *port += *ipAddrStr - '0';
1231 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
1242 //-----------------------------------------------------------------------------
1243 // Private internal function prototypes
1244 //-----------------------------------------------------------------------------
1246 static OCDoHandle GenerateInvocationHandle();
1247 static OCStackResult initResources();
1248 static void insertResource(OCResource *resource);
1249 static OCResource *findResource(OCResource *resource);
1250 static void insertResourceType(OCResource *resource,
1251 OCResourceType *resourceType);
1252 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
1254 static void insertResourceInterface(OCResource *resource,
1255 OCResourceInterface *resourceInterface);
1256 static OCResourceInterface *findResourceInterfaceAtIndex(
1257 OCResourceHandle handle, uint8_t index);
1258 static void deleteResourceType(OCResourceType *resourceType);
1259 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
1260 static void deleteResourceElements(OCResource *resource);
1261 static int deleteResource(OCResource *resource);
1262 static void deleteAllResources();
1263 static void incrementSequenceNumber(OCResource * resPtr);
1264 static OCStackResult verifyUriQueryLength(const char * inputUri,
1266 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
1267 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
1269 //-----------------------------------------------------------------------------
1271 //-----------------------------------------------------------------------------
1274 * Initialize the OC Stack. Must be called prior to starting the stack.
1277 * IP Address of host device
1279 * Port of host device
1281 * Host device is client, server, or client-server
1284 * OC_STACK_OK - no errors
1285 * OC_STACK_ERROR - stack init error
1287 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1289 OCStackResult result = OC_STACK_ERROR;
1290 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1293 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1295 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1296 return OC_STACK_ERROR;
1301 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
1306 //It is ok to select network to CA_WIFI for now
1308 CAResult_t caResult = CASelectNetwork(CA_ETHERNET);
1310 CAResult_t caResult = CASelectNetwork(CA_WIFI|CA_ETHERNET);
1312 if(caResult == CA_STATUS_OK)
1314 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
1315 CARegisterHandler(HandleCARequests, HandleCAResponses);
1317 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
1318 stackState = OC_STACK_INITIALIZED;
1319 result = OC_STACK_OK;
1323 caResult = CAStartDiscoveryServer();
1324 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1327 caResult = CAStartListeningServer();
1328 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1330 case OC_CLIENT_SERVER:
1331 caResult = CAStartListeningServer();
1332 if(caResult == CA_STATUS_OK)
1334 caResult = CAStartDiscoveryServer();
1336 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1339 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1340 return OC_STACK_ERROR;
1345 if (caResult == CA_STATUS_OK)
1347 result = OC_STACK_OK;
1351 result = OC_STACK_ERROR;
1356 defaultDeviceHandler = NULL;
1358 #if defined(__WITH_DTLS__)
1359 caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
1360 result = (caResult == CA_STATUS_OK) ? OC_STACK_OK : OC_STACK_ERROR;
1361 #endif // (__WITH_DTLS__)
1363 #ifdef WITH_PRESENCE
1364 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1365 #endif // WITH_PRESENCE
1367 if (result == OC_STACK_OK)
1369 stackState = OC_STACK_INITIALIZED;
1371 // Initialize resource
1372 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1374 result = initResources();
1376 if(result != OC_STACK_OK)
1378 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1384 * Stop the OC stack. Use for a controlled shutdown.
1386 * OC_STACK_OK - no errors
1387 * OC_STACK_ERROR - stack not initialized
1389 OCStackResult OCStop()
1391 OCStackResult result = OC_STACK_ERROR;
1393 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1395 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1397 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1400 else if (stackState != OC_STACK_INITIALIZED)
1402 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1403 return OC_STACK_ERROR;
1406 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1408 #ifdef WITH_PRESENCE
1409 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1410 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1411 presenceResource.presenceTTL = 0;
1412 #endif // WITH_PRESENCE
1414 // Free memory dynamically allocated for resources
1415 deleteAllResources();
1418 //CATerminate does not return any error code. It is OK to assign result to OC_STACK_OK.
1419 result = OC_STACK_OK;
1421 if (result == OC_STACK_OK)
1423 // Remove all observers
1424 DeleteObserverList();
1425 // Remove all the client callbacks
1426 DeleteClientCBList();
1427 stackState = OC_STACK_UNINITIALIZED;
1428 result = OC_STACK_OK;
1430 stackState = OC_STACK_INITIALIZED;
1431 result = OC_STACK_ERROR;
1434 // Deinit security blob
1435 DeinitOCSecurityInfo();
1437 if (result != OC_STACK_OK) {
1438 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1445 * Map OCQualityOfService to CAMessageType
1447 * @param OCQualityOfService - Input qos.
1449 * Returns CA message type for a given qos.
1451 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1456 return CA_MSG_CONFIRM;
1461 return CA_MSG_NONCONFIRM;
1466 * Verify the lengths of the URI and the query separately
1468 * @param inputUri - Input URI and query.
1469 * @param uriLen - The length of the initial URI with query.
1471 * Note: The '?' that appears after the URI is not considered as
1472 * a part of the query.
1474 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1478 query = strchr (inputUri, '?');
1482 if((query - inputUri) > MAX_URI_LENGTH)
1484 return OC_STACK_INVALID_URI;
1487 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1489 return OC_STACK_INVALID_QUERY;
1492 else if(uriLen > MAX_URI_LENGTH)
1494 return OC_STACK_INVALID_URI;
1500 * Discover or Perform requests on a specified resource
1501 * (specified by that Resource's respective URI).
1503 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of
1505 * @param method - @ref OCMethod to perform on the resource
1506 * @param requiredUri - URI of the resource to interact with
1507 * @param referenceUri - URI of the reference resource
1508 * @param request - JSON encoded request
1509 * @param qos - quality of service
1510 * @param cbData - struct that contains asynchronous callback function that is invoked
1511 * by the stack when discovery or resource interaction is complete
1512 * @param options - The address of an array containing the vendor specific header
1513 * header options to be sent with the request
1514 * @param numOptions - Number of vendor specific header options to be included
1517 * OC_STACK_OK - no errors
1518 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1519 * OC_STACK_INVALID_METHOD - invalid resource method
1520 * OC_STACK_INVALID_URI - invalid required or reference URI
1522 * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
1523 * Instead, it just contains the URI to the resource such as "/oc/core".
1525 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1526 const char *referenceUri, const char *request, OCConnectivityType conType,
1527 OCQualityOfService qos, OCCallbackData *cbData,
1528 OCHeaderOption * options, uint8_t numOptions)
1530 OCStackResult result = OC_STACK_ERROR;
1531 ClientCB *clientCB = NULL;
1532 unsigned char * requestUri = NULL;
1533 unsigned char * resourceType = NULL;
1534 unsigned char * query = NULL;
1535 char * newUri = (char *)requiredUri;
1536 (void) referenceUri;
1537 CARemoteEndpoint_t* endpoint = NULL;
1538 CAResult_t caResult;
1539 CAToken_t token = NULL;
1540 CAInfo_t requestData;
1541 CARequestInfo_t requestInfo;
1542 CAGroupEndpoint_t grpEnd = {0};
1544 // To track if memory is allocated for additional header options
1545 uint8_t hdrOptionMemAlloc = 0;
1547 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1549 // Validate input parameters
1550 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1551 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1553 //TODO ("Need to form the final query by concatenating require and reference URI's");
1554 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1556 uint16_t uriLen = strlen(requiredUri);
1558 // ToDo: We should also check if the requiredUri has a mutlicast address,
1559 // then qos has to be OC_Low_QOS
1565 case OC_REST_DELETE:
1566 case OC_REST_OBSERVE:
1567 case OC_REST_OBSERVE_ALL:
1568 case OC_REST_CANCEL_OBSERVE:
1570 #ifdef WITH_PRESENCE
1571 case OC_REST_PRESENCE:
1575 result = OC_STACK_INVALID_METHOD;
1579 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1584 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1586 result = OC_STACK_INVALID_PARAM;
1590 #ifdef WITH_PRESENCE
1591 if(method == OC_REST_PRESENCE)
1593 result = getQueryFromUri(requiredUri, &query, &newUri);
1596 result = getResourceType((char *) query, &resourceType);
1599 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1603 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1608 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1610 if(result != OC_STACK_OK)
1615 #endif // WITH_PRESENCE
1617 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1620 memcpy(requestUri, newUri, (uriLen + 1));
1624 result = OC_STACK_NO_MEMORY;
1628 *handle = GenerateInvocationHandle();
1631 result = OC_STACK_NO_MEMORY;
1635 memset(&requestData, 0, sizeof(CAInfo_t));
1636 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1640 case OC_REST_OBSERVE:
1641 case OC_REST_OBSERVE_ALL:
1642 case OC_REST_CANCEL_OBSERVE:
1644 requestInfo.method = CA_GET;
1649 requestInfo.method = CA_PUT;
1654 requestInfo.method = CA_POST;
1657 case OC_REST_DELETE:
1659 requestInfo.method = CA_DELETE;
1662 #ifdef WITH_PRESENCE
1663 case OC_REST_PRESENCE:
1665 // Replacing method type with GET because "presence"
1666 // is a stack layer only implementation.
1667 requestInfo.method = CA_GET;
1672 result = OC_STACK_INVALID_METHOD;
1676 //High QoS is not supported
1677 if(qos == OC_HIGH_QOS)
1679 result = OC_STACK_INVALID_PARAM;
1684 caResult = CAGenerateToken(&token);
1685 if (caResult != CA_STATUS_OK)
1687 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1688 CADestroyToken(token);
1692 requestData.type = qualityOfServiceToMessageType(qos);
1693 requestData.token = token;
1694 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1696 result = CreateObserveHeaderOption (&(requestData.options), options,
1697 numOptions, OC_OBSERVE_REGISTER);
1698 if (result != OC_STACK_OK)
1702 hdrOptionMemAlloc = 1;
1703 requestData.numOptions = numOptions + 1;
1707 requestData.options = (CAHeaderOption_t*)options;
1708 requestData.numOptions = numOptions;
1710 requestData.payload = (char *)request;
1712 requestInfo.info = requestData;
1714 CAConnectivityType_t caConType;
1716 result = OCToCAConnectivityType((OCConnectivityType) conType, &caConType);
1717 if (result != OC_STACK_OK)
1719 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1724 if(conType == OC_ALL)
1726 grpEnd.connectivityType = caConType;
1728 grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1729 if(!grpEnd.resourceUri)
1731 result = OC_STACK_NO_MEMORY;
1734 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1736 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1740 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1742 if (caResult != CA_STATUS_OK)
1744 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1748 caResult = CASendRequest(endpoint, &requestInfo);
1751 if (caResult != CA_STATUS_OK)
1753 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1757 if((result = AddClientCB(&clientCB, cbData, &token, handle, method,
1758 requestUri, resourceType)) != OC_STACK_OK)
1760 result = OC_STACK_NO_MEMORY;
1765 if(newUri != requiredUri)
1769 if (result != OC_STACK_OK)
1771 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1772 FindAndDeleteClientCB(clientCB);
1774 CADestroyRemoteEndpoint(endpoint);
1775 OCFree(grpEnd.resourceUri);
1776 if (hdrOptionMemAlloc)
1778 OCFree(requestData.options);
1784 * Cancel a request associated with a specific @ref OCDoResource invocation.
1786 * @param handle - Used to identify a specific OCDoResource invocation.
1787 * @param qos - used to specify Quality of Service (read below for more info)
1788 * @param options- used to specify vendor specific header options when sending
1789 * explicit observe cancellation
1790 * @param numOptions- Number of header options to be included
1793 * OC_STACK_OK - No errors; Success
1794 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1796 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1800 * This ftn is implemented one of two ways in the case of observation:
1802 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1803 * Remove the callback associated on client side.
1804 * When the next notification comes in from server,
1805 * reply with RESET message to server.
1806 * Keep in mind that the server will react to RESET only
1807 * if the last notification was sent ans CON
1809 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1810 * and it is associated with an observe request
1811 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1812 * Send CON Observe request to server with
1813 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1814 * Remove the callback associated on client side.
1816 OCStackResult ret = OC_STACK_OK;
1817 CARemoteEndpoint_t* endpoint = NULL;
1818 CAResult_t caResult;
1819 CAInfo_t requestData;
1820 CARequestInfo_t requestInfo;
1821 // Track if memory is allocated for additional header options
1822 uint8_t hdrOptionMemAlloc = 0;
1825 return OC_STACK_INVALID_PARAM;
1828 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1830 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1833 switch (clientCB->method)
1835 case OC_REST_OBSERVE:
1836 case OC_REST_OBSERVE_ALL:
1837 //TODO-CA : Why CA_WIFI alone?
1838 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1840 if (caResult != CA_STATUS_OK)
1842 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1843 return OC_STACK_ERROR;
1846 memset(&requestData, 0, sizeof(CAInfo_t));
1847 requestData.type = qualityOfServiceToMessageType(qos);
1848 requestData.token = clientCB->token;
1849 if (CreateObserveHeaderOption (&(requestData.options),
1850 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1852 return OC_STACK_ERROR;
1854 hdrOptionMemAlloc = 1;
1855 requestData.numOptions = numOptions + 1;
1856 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1857 requestInfo.method = CA_GET;
1858 requestInfo.info = requestData;
1860 caResult = CASendRequest(endpoint, &requestInfo);
1861 if (caResult != CA_STATUS_OK)
1863 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1865 if(caResult == CA_STATUS_OK)
1869 #ifdef WITH_PRESENCE
1870 case OC_REST_PRESENCE:
1871 FindAndDeleteClientCB(clientCB);
1875 return OC_STACK_INVALID_METHOD;
1878 CADestroyRemoteEndpoint(endpoint);
1879 if (hdrOptionMemAlloc)
1881 OCFree(requestData.options);
1887 #ifdef WITH_PRESENCE
1888 OCStackResult OCProcessPresence()
1890 OCStackResult result = OC_STACK_OK;
1891 uint8_t ipAddr[4] = { 0 };
1894 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1895 ClientCB* cbNode = NULL;
1897 OCClientResponse clientResponse;
1898 OCResponse * response = NULL;
1899 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1901 LL_FOREACH(cbList, cbNode) {
1902 if(OC_REST_PRESENCE == cbNode->method)
1904 if(cbNode->presence)
1906 uint32_t now = GetTime(0);
1907 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
1908 cbNode->presence->TTLlevel);
1909 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1912 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1917 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1918 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1919 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1922 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1924 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1925 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1927 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1930 clientResponse.sequenceNumber = 0;
1931 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
1932 clientResponse.addr = (OCDevAddr *) &dst;
1933 clientResponse.resJSONPayload = NULL;
1935 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1936 &cbNode->token, &clientResponse, NULL);
1937 if(result != OC_STACK_OK)
1942 // Increment the TTLLevel (going to a next state), so we don't keep
1943 // sending presence notification to client.
1944 cbNode->presence->TTLlevel++;
1945 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1946 cbNode->presence->TTLlevel);
1950 result = OC_STACK_INVALID_IP;
1954 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1955 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1957 FindAndDeleteClientCB(cbNode);
1961 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1963 CAResult_t caResult;
1964 CARemoteEndpoint_t* endpoint = NULL;
1965 CAInfo_t requestData;
1966 CARequestInfo_t requestInfo;
1968 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1970 //TODO-CA : Why CA_WIFI alone?
1971 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
1974 if (caResult != CA_STATUS_OK)
1976 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1980 memset(&requestData, 0, sizeof(CAInfo_t));
1981 requestData.type = CA_MSG_NONCONFIRM;
1982 requestData.token = cbNode->token;
1984 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1985 requestInfo.method = CA_GET;
1986 requestInfo.info = requestData;
1988 caResult = CASendRequest(endpoint, &requestInfo);
1990 if (caResult != CA_STATUS_OK)
1992 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1996 cbNode->presence->TTLlevel++;
1997 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1998 cbNode->presence->TTLlevel);
2004 if (result != OC_STACK_OK)
2006 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2010 #endif // WITH_PRESENCE
2013 * Called in main loop of OC client or server. Allows low-level processing of
2017 * OC_STACK_OK - no errors
2018 * OC_STACK_ERROR - stack process error
2020 OCStackResult OCProcess()
2022 #ifdef WITH_PRESENCE
2023 OCProcessPresence();
2025 CAHandleRequestResponse();
2030 #ifdef WITH_PRESENCE
2032 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
2033 * presence notifications to clients via multicast. Once this API has been called with a success,
2034 * clients may query for this server's presence and this server's stack will respond via multicast.
2036 * Server can call this function when it comes online for the first time, or when it comes back
2037 * online from offline mode, or when it re enters network.
2039 * @param ttl - Time To Live in seconds
2040 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
2043 * OC_STACK_OK - No errors; Success
2045 OCStackResult OCStartPresence(const uint32_t ttl)
2047 OCChangeResourceProperty(
2048 &(((OCResource *)presenceResource.handle)->resourceProperties),
2053 presenceResource.presenceTTL = ttl;
2056 if(OC_PRESENCE_UNINITIALIZED == presenceState)
2058 OCDevAddr multiCastAddr;
2059 presenceState = OC_PRESENCE_INITIALIZED;
2061 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
2063 CAAddress_t addressInfo;
2064 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
2065 addressInfo.IP.port = 5683;
2067 //TODO make sure there is no memory leak here since another copy
2068 //of token is being created inside AddObserver
2069 CAToken_t caToken = NULL;
2070 CAResult_t caResult = CAGenerateToken(&caToken);
2071 if (caResult != CA_STATUS_OK)
2073 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2074 CADestroyToken(caToken);
2075 return OC_STACK_ERROR;
2078 AddObserver(OC_PRESENCE_URI, NULL, 0, &caToken,
2079 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
2080 &addressInfo, CA_WIFI);
2083 // Each time OCStartPresence is called
2084 // a different random 32-bit integer number is used
2085 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2087 return SendPresenceNotification(NULL);
2091 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
2092 * presence notifications to clients via multicast. Once this API has been called with a success,
2093 * this server's stack will not respond to clients querying for this server's presence.
2095 * Server can call this function when it is terminating, going offline, or when going
2096 * away from network.
2099 * OC_STACK_OK - No errors; Success
2101 OCStackResult OCStopPresence()
2103 OCStackResult result = OC_STACK_ERROR;
2104 //make resource inactive
2105 result = OCChangeResourceProperty(
2106 &(((OCResource *) presenceResource.handle)->resourceProperties),
2108 result = SendPresenceNotification(NULL);
2115 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
2117 defaultDeviceHandler = entityHandler;
2122 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2124 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2126 if(myStackMode == OC_CLIENT)
2128 return OC_STACK_ERROR;
2131 return SaveDeviceInfo(deviceInfo);
2137 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2138 * Used to refer to resource
2139 * @param resourceTypeName - name of resource type. Example: "core.led"
2140 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2141 * @param uri - URI of the resource. Example: "/a/led"
2142 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2143 * NULL for default entity handler
2144 * @param resourceProperties - properties supported by resource.
2145 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2148 * OC_STACK_OK - no errors
2149 * OC_STACK_ERROR - stack process error
2151 OCStackResult OCCreateResource(OCResourceHandle *handle,
2152 const char *resourceTypeName,
2153 const char *resourceInterfaceName,
2154 const char *uri, OCEntityHandler entityHandler,
2155 uint8_t resourceProperties) {
2157 OCResource *pointer = NULL;
2160 OCStackResult result = OC_STACK_ERROR;
2162 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2164 if(myStackMode == OC_CLIENT)
2168 // Validate parameters
2169 if(!uri || (strlen(uri) == 0))
2171 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2172 return OC_STACK_INVALID_URI;
2174 // Is it presented during resource discovery?
2175 if (!handle || !resourceTypeName) {
2176 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2177 return OC_STACK_INVALID_PARAM;
2180 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
2181 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2184 // Make sure resourceProperties bitmask has allowed properties specified
2185 if (resourceProperties
2186 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
2187 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2188 return OC_STACK_INVALID_PARAM;
2191 // If the headResource is NULL, then no resources have been created...
2192 pointer = headResource;
2194 // At least one resources is in the resource list, so we need to search for
2195 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2197 if (strcmp(uri, pointer->uri) == 0) {
2198 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2199 return OC_STACK_INVALID_PARAM;
2201 pointer = pointer->next;
2204 // Create the pointer and insert it into the resource list
2205 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2209 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2211 insertResource(pointer);
2214 size = strlen(uri) + 1;
2215 str = (char *) OCMalloc(size);
2219 strncpy(str, uri, size);
2222 // Set properties. Set OC_ACTIVE
2223 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2226 // Add the resourcetype to the resource
2227 result = BindResourceTypeToResource(pointer, resourceTypeName);
2228 if (result != OC_STACK_OK) {
2229 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2233 // Add the resourceinterface to the resource
2234 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2235 if (result != OC_STACK_OK) {
2236 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2240 // If an entity handler has been passed, attach it to the newly created
2241 // resource. Otherwise, set the default entity handler.
2244 pointer->entityHandler = entityHandler;
2248 pointer->entityHandler = defaultResourceEHandler;
2252 result = OC_STACK_OK;
2254 #ifdef WITH_PRESENCE
2255 if(presenceResource.handle)
2257 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2258 SendPresenceNotification(pointer->rsrcType);
2262 if (result != OC_STACK_OK)
2264 // Deep delete of resource and other dynamic elements that it contains
2265 deleteResource(pointer);
2274 * Create a resource. with host ip address for remote resource
2276 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2277 * Used to refer to resource
2278 * @param resourceTypeName - name of resource type. Example: "core.led"
2279 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2280 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2281 * @param uri - URI of the resource. Example: "/a/led"
2282 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2283 * NULL for default entity handler
2284 * @param resourceProperties - properties supported by resource.
2285 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2288 * OC_STACK_OK - no errors
2289 * OC_STACK_ERROR - stack process error
2292 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2293 const char *resourceTypeName,
2294 const char *resourceInterfaceName,
2297 OCEntityHandler entityHandler,
2298 uint8_t resourceProperties)
2302 OCStackResult result = OC_STACK_ERROR;
2304 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2305 uri, entityHandler, resourceProperties);
2307 if (result != OC_STACK_ERROR)
2310 size = strlen(host) + 1;
2311 str = (char *) OCMalloc(size);
2314 return OC_STACK_ERROR;
2316 strncpy(str, host, size);
2317 ((OCResource *) *handle)->host = str;
2324 * Add a resource to a collection resource.
2326 * @param collectionHandle - handle to the collection resource
2327 * @param resourceHandle - handle to resource to be added to the collection resource
2330 * OC_STACK_OK - no errors
2331 * OC_STACK_ERROR - stack process error
2332 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2334 OCStackResult OCBindResource(
2335 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2336 OCResource *resource;
2339 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2341 // Validate parameters
2342 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2343 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2344 // Container cannot contain itself
2345 if (collectionHandle == resourceHandle) {
2346 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2347 return OC_STACK_INVALID_PARAM;
2350 // Use the handle to find the resource in the resource linked list
2351 resource = findResource((OCResource *) collectionHandle);
2353 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2354 return OC_STACK_INVALID_PARAM;
2357 // Look for an open slot to add add the child resource.
2358 // If found, add it and return success
2359 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2360 if (!resource->rsrcResources[i]) {
2361 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2362 OC_LOG(INFO, TAG, PCF("resource bound"));
2367 #ifdef WITH_PRESENCE
2368 if(presenceResource.handle)
2370 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2371 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2375 // Unable to add resourceHandle, so return error
2376 return OC_STACK_ERROR;
2380 * Remove a resource from a collection resource.
2382 * @param collectionHandle - handle to the collection resource
2383 * @param resourceHandle - handle to resource to be added to the collection resource
2386 * OC_STACK_OK - no errors
2387 * OC_STACK_ERROR - stack process error
2388 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2390 OCStackResult OCUnBindResource(
2391 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2392 OCResource *resource;
2395 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2397 // Validate parameters
2398 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2399 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2400 // Container cannot contain itself
2401 if (collectionHandle == resourceHandle) {
2402 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2403 return OC_STACK_INVALID_PARAM;
2406 // Use the handle to find the resource in the resource linked list
2407 resource = findResource((OCResource *) collectionHandle);
2409 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2410 return OC_STACK_INVALID_PARAM;
2413 // Look for an open slot to add add the child resource.
2414 // If found, add it and return success
2415 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2416 if (resourceHandle == resource->rsrcResources[i]) {
2417 resource->rsrcResources[i] = (OCResource *) NULL;
2418 OC_LOG(INFO, TAG, PCF("resource unbound"));
2423 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2425 #ifdef WITH_PRESENCE
2426 if(presenceResource.handle)
2428 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2429 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2433 // Unable to add resourceHandle, so return error
2434 return OC_STACK_ERROR;
2437 OCStackResult BindResourceTypeToResource(OCResource* resource,
2438 const char *resourceTypeName)
2440 OCResourceType *pointer = NULL;
2443 OCStackResult result = OC_STACK_ERROR;
2445 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2447 // Validate parameters
2448 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2449 // TODO: Does resource attribute resentation really have to be maintained in stack?
2450 // Is it presented during resource discovery?
2452 //TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2454 // Create the resourcetype and insert it into the resource list
2455 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2460 // Set the resourceTypeName
2461 size = strlen(resourceTypeName) + 1;
2462 str = (char *) OCMalloc(size);
2466 strncpy(str, resourceTypeName, size);
2467 pointer->resourcetypename = str;
2469 insertResourceType(resource, pointer);
2470 result = OC_STACK_OK;
2472 exit: if (result != OC_STACK_OK) {
2480 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2481 const char *resourceInterfaceName)
2483 OCResourceInterface *pointer = NULL;
2486 OCStackResult result = OC_STACK_ERROR;
2488 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2490 // Validate parameters
2491 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2493 //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2495 // Create the resourceinterface and insert it into the resource list
2496 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2501 // Set the resourceinterface name
2502 size = strlen(resourceInterfaceName) + 1;
2503 str = (char *) OCMalloc(size);
2507 strncpy(str, resourceInterfaceName, size);
2508 pointer->name = str;
2510 // Bind the resourceinterface to the resource
2511 insertResourceInterface(resource, pointer);
2513 result = OC_STACK_OK;
2515 exit: if (result != OC_STACK_OK) {
2524 * Bind a resourcetype to a resource.
2526 * @param handle - handle to the resource
2527 * @param resourceTypeName - name of resource type. Example: "core.led"
2530 * OC_STACK_OK - no errors
2531 * OC_STACK_ERROR - stack process error
2533 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2534 const char *resourceTypeName) {
2536 OCStackResult result = OC_STACK_ERROR;
2537 OCResource *resource;
2539 // Make sure resource exists
2540 resource = findResource((OCResource *) handle);
2542 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2543 return OC_STACK_ERROR;
2546 // call internal function
2547 result = BindResourceTypeToResource(resource, resourceTypeName);
2549 #ifdef WITH_PRESENCE
2550 if(presenceResource.handle)
2552 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2553 SendPresenceNotification(resource->rsrcType);
2561 * Bind a resourceinterface to a resource.
2563 * @param handle - handle to the resource
2564 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2567 * OC_STACK_OK - no errors
2568 * OC_STACK_ERROR - stack process error
2571 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2572 const char *resourceInterfaceName) {
2574 OCStackResult result = OC_STACK_ERROR;
2575 OCResource *resource;
2577 // Make sure resource exists
2578 resource = findResource((OCResource *) handle);
2580 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2581 return OC_STACK_ERROR;
2584 // call internal function
2585 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2587 #ifdef WITH_PRESENCE
2588 if(presenceResource.handle)
2590 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2591 SendPresenceNotification(resource->rsrcType);
2599 * Get the number of resources that have been created in the stack.
2601 * @param numResources - pointer to count variable
2604 * OC_STACK_OK - no errors
2605 * OC_STACK_ERROR - stack process error
2608 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2609 OCResource *pointer = headResource;
2611 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2612 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2615 *numResources = *numResources + 1;
2616 pointer = pointer->next;
2622 * Get a resource handle by index.
2624 * @param index - index of resource, 0 to Count - 1
2627 * Resource handle - if found
2628 * NULL - if not found
2630 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2631 OCResource *pointer = headResource;
2634 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2636 // Iterate through the list
2637 while ((i < index) && pointer) {
2639 pointer = pointer->next;
2641 return (OCResourceHandle) pointer;
2645 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2648 * @param handle - handle of resource to be deleted
2651 * OC_STACK_OK - no errors
2652 * OC_STACK_ERROR - stack process error
2653 * OC_STACK_NO_RESOURCE - resource not found
2654 * OC_STACK_INVALID_PARAM - invalid param
2656 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2657 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2660 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2661 return OC_STACK_INVALID_PARAM;
2664 OCResource *resource = findResource((OCResource *) handle);
2665 if (resource == NULL) {
2666 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2667 return OC_STACK_NO_RESOURCE;
2670 if (deleteResource((OCResource *) handle) == 0) {
2671 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2672 return OC_STACK_ERROR;
2679 * Get the URI of the resource specified by handle.
2681 * @param handle - handle of resource
2683 * URI string - if resource found
2684 * NULL - resource not found
2686 const char *OCGetResourceUri(OCResourceHandle handle) {
2687 OCResource *resource;
2688 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2690 resource = findResource((OCResource *) handle);
2692 return resource->uri;
2694 return (const char *) NULL;
2698 * Get the properties of the resource specified by handle.
2699 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2700 * for the resource by the stack.
2702 * @param handle - handle of resource
2704 * property bitmap - if resource found
2705 * NULL - resource not found
2707 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2708 OCResource *resource;
2709 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2711 resource = findResource((OCResource *) handle);
2713 return resource->resourceProperties;
2719 * Get the number of resource types of the resource.
2721 * @param handle - handle of resource
2722 * @param numResourceTypes - pointer to count variable
2725 * OC_STACK_OK - no errors
2726 * OC_STACK_ERROR - stack process error
2728 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2729 uint8_t *numResourceTypes) {
2730 OCResource *resource;
2731 OCResourceType *pointer;
2733 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2734 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2735 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2737 *numResourceTypes = 0;
2739 resource = findResource((OCResource *) handle);
2741 pointer = resource->rsrcType;
2743 *numResourceTypes = *numResourceTypes + 1;
2744 pointer = pointer->next;
2751 * Get name of resource type of the resource.
2753 * @param handle - handle of resource
2754 * @param index - index of resource, 0 to Count - 1
2757 * resource type name - if resource found
2758 * NULL - resource not found
2760 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2761 OCResourceType *resourceType;
2763 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2765 resourceType = findResourceTypeAtIndex(handle, index);
2767 return resourceType->resourcetypename;
2769 return (const char *) NULL;
2775 * Get the number of resource interfaces of the resource.
2777 * @param handle - handle of resource
2778 * @param numResources - pointer to count variable
2781 * OC_STACK_OK - no errors
2782 * OC_STACK_ERROR - stack process error
2784 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2785 uint8_t *numResourceInterfaces) {
2786 OCResourceInterface *pointer;
2787 OCResource *resource;
2789 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2791 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2792 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2794 *numResourceInterfaces = 0;
2795 resource = findResource((OCResource *) handle);
2797 pointer = resource->rsrcInterface;
2799 *numResourceInterfaces = *numResourceInterfaces + 1;
2800 pointer = pointer->next;
2807 * Get name of resource interface of the resource.
2809 * @param handle - handle of resource
2810 * @param index - index of resource, 0 to Count - 1
2813 * resource interface name - if resource found
2814 * NULL - resource not found
2816 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2817 OCResourceInterface *resourceInterface;
2819 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2821 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2822 if (resourceInterface) {
2823 return resourceInterface->name;
2825 return (const char *) NULL;
2829 * Get resource handle from the collection resource by index.
2831 * @param collectionHandle - handle of collection resource
2832 * @param index - index of contained resource, 0 to Count - 1
2835 * handle to resource - if resource found
2836 * NULL - resource not found
2838 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2840 OCResource *resource;
2842 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2844 if (index >= MAX_CONTAINED_RESOURCES) {
2848 resource = findResource((OCResource *) collectionHandle);
2853 return resource->rsrcResources[index];
2857 * Bind an entity handler to the resource.
2859 * @param handle - handle to the resource that the contained resource is to be bound
2860 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2862 * OC_STACK_OK - no errors
2863 * OC_STACK_ERROR - stack process error
2865 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2866 OCEntityHandler entityHandler) {
2867 OCResource *resource;
2869 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2871 // Validate parameters
2872 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2873 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2875 // Use the handle to find the resource in the resource linked list
2876 resource = findResource((OCResource *)handle);
2878 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2879 return OC_STACK_ERROR;
2883 resource->entityHandler = entityHandler;
2885 #ifdef WITH_PRESENCE
2886 if(presenceResource.handle)
2888 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2889 SendPresenceNotification(resource->rsrcType);
2897 * Get the entity handler for a resource.
2899 * @param handle - handle of resource
2902 * entity handler - if resource found
2903 * NULL - resource not found
2905 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2906 OCResource *resource;
2908 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2910 // Use the handle to find the resource in the resource linked list
2911 resource = findResource((OCResource *)handle);
2913 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2918 return resource->entityHandler;
2921 void incrementSequenceNumber(OCResource * resPtr)
2923 // Increment the sequence number
2924 resPtr->sequenceNum += 1;
2925 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2927 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2933 * Notify Presence subscribers that a resource has been modified
2935 * @param resourceType - Handle to the resourceType linked list of resource
2936 * that was modified.
2937 * @param qos - Quality Of Service
2940 #ifdef WITH_PRESENCE
2941 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2943 OCResource *resPtr = NULL;
2944 OCStackResult result;
2945 OCMethod method = OC_REST_PRESENCE;
2946 uint32_t maxAge = 0;
2947 resPtr = findResource((OCResource *) presenceResource.handle);
2950 return OC_STACK_NO_RESOURCE;
2952 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2954 maxAge = presenceResource.presenceTTL;
2961 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2965 #endif // WITH_PRESENCE
2967 * Notify observers that an observed value has changed.
2969 * @param handle - handle of resource
2972 * OC_STACK_OK - no errors
2973 * OC_STACK_NO_RESOURCE - invalid resource handle
2974 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2976 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2978 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2980 OCResource *resPtr = NULL;
2981 OCStackResult result;
2982 OCMethod method = OC_REST_NOMETHOD;
2983 uint32_t maxAge = 0;
2985 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2986 #ifdef WITH_PRESENCE
2987 if(handle == presenceResource.handle)
2991 #endif // WITH_PRESENCE
2992 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2994 // Verify that the resource exists
2995 resPtr = findResource ((OCResource *) handle);
2998 return OC_STACK_NO_RESOURCE;
3002 //only increment in the case of regular observing (not presence)
3003 incrementSequenceNumber(resPtr);
3004 method = OC_REST_OBSERVE;
3005 maxAge = MAX_OBSERVE_AGE;
3006 #ifdef WITH_PRESENCE
3007 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
3009 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3016 OCNotifyListOfObservers (OCResourceHandle handle,
3017 OCObservationId *obsIdList,
3018 uint8_t numberOfIds,
3019 unsigned char *notificationJSONPayload,
3020 OCQualityOfService qos)
3022 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3024 OCResource *resPtr = NULL;
3025 //TODO: we should allow the server to define this
3026 uint32_t maxAge = MAX_OBSERVE_AGE;
3028 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3029 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3030 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3032 // Verify that the resource exists
3033 resPtr = findResource ((OCResource *) handle);
3034 if (NULL == resPtr || myStackMode == OC_CLIENT)
3036 return OC_STACK_NO_RESOURCE;
3040 incrementSequenceNumber(resPtr);
3042 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3043 notificationJSONPayload, maxAge, qos));
3047 * Send a response to a request.
3048 * The response can be a regular, slow, or block (i.e. a response that
3049 * is too large to be sent in a single PDU and must span multiple transmissions)
3051 * @param response - pointer to structure that contains response parameters
3054 * OC_STACK_OK - No errors; Success
3055 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
3056 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
3057 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
3058 * persistent response buffer is necessary
3060 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3062 OCStackResult result = OC_STACK_ERROR;
3063 OCServerRequest *serverRequest = NULL;
3065 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3067 // Validate input parameters
3068 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3069 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3071 // TODO: Placeholder for creating a response entry when implementing
3072 // block transfer feature
3074 // If a response payload is present, check if block transfer is required
3075 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3076 (const char *)ehResponse->payload, ehResponse->payloadSize))
3078 OC_LOG(INFO, TAG, PCF("Block transfer required"));
3080 // Persistent response buffer is needed for block transfer
3081 if (!ehResponse->persistentBufferFlag)
3083 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3084 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3086 // TODO: Placeholder for block transfer handling
3087 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3088 // when implementing the block transfer feature
3093 // Get pointer to request info
3094 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3097 result = serverRequest->ehResponseHandler(ehResponse);
3104 * Cancel a response. Applies to a block response
3106 * @param responseHandle - response handle set by stack in OCServerResponse after
3107 * OCDoResponse is called
3110 * OC_STACK_OK - No errors; Success
3111 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
3113 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
3115 OCStackResult result = OC_STACK_NOTIMPL;
3117 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
3119 // TODO: validate response handle
3124 //-----------------------------------------------------------------------------
3125 // Private internal function definitions
3126 //-----------------------------------------------------------------------------
3128 * Generate handle of OCDoResource invocation for callback management.
3130 static OCDoHandle GenerateInvocationHandle()
3132 OCDoHandle handle = NULL;
3133 // Generate token here, it will be deleted when the transaction is deleted
3134 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3137 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3142 #ifdef WITH_PRESENCE
3143 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3144 OCResourceProperty resourceProperties, uint8_t enable)
3146 if (resourceProperties
3147 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
3148 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3149 return OC_STACK_INVALID_PARAM;
3153 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3157 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3164 * Initialize resource data structures, variables, etc.
3166 OCStackResult initResources() {
3167 OCStackResult result = OC_STACK_OK;
3168 // Init application resource vars
3169 headResource = NULL;
3170 // Init Virtual Resources
3171 #ifdef WITH_PRESENCE
3172 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3173 //presenceResource.token = OCGenerateCoAPToken();
3174 result = OCCreateResource(&presenceResource.handle,
3175 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3180 //make resource inactive
3181 result = OCChangeResourceProperty(
3182 &(((OCResource *) presenceResource.handle)->resourceProperties),
3189 * Add a resource to the end of the linked list of resources.
3191 * @param resource - resource to be added
3193 void insertResource(OCResource *resource) {
3194 OCResource *pointer;
3196 if (!headResource) {
3197 headResource = resource;
3199 pointer = headResource;
3201 while (pointer->next) {
3202 pointer = pointer->next;
3204 pointer->next = resource;
3206 resource->next = NULL;
3210 * Find a resource in the linked list of resources.
3212 * @param resource - resource to be found
3214 * NULL - resource not found
3215 * pointer to resource - pointer to resource that was found in the linked list
3217 OCResource *findResource(OCResource *resource) {
3218 OCResource *pointer = headResource;
3221 if (pointer == resource) {
3224 pointer = pointer->next;
3229 void deleteAllResources()
3231 OCResource *pointer = headResource;
3236 temp = pointer->next;
3237 #ifdef WITH_PRESENCE
3238 if(pointer != (OCResource *) presenceResource.handle)
3240 #endif // WITH_PRESENCE
3241 deleteResource(pointer);
3242 #ifdef WITH_PRESENCE
3244 #endif // WITH_PRESENCE
3248 #ifdef WITH_PRESENCE
3249 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3250 // presence notification attributed to their deletion to be processed.
3251 deleteResource((OCResource *) presenceResource.handle);
3252 #endif // WITH_PRESENCE
3256 * Delete the resource from the linked list.
3258 * @param resource - resource to be deleted
3263 int deleteResource(OCResource *resource) {
3264 OCResource *prev = NULL;
3267 temp = headResource;
3269 if (temp == resource) {
3270 // Invalidate all Resource Properties.
3271 resource->resourceProperties = (OCResourceProperty) 0;
3272 #ifdef WITH_PRESENCE
3273 if(resource != (OCResource *) presenceResource.handle)
3275 #endif // WITH_PRESENCE
3276 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3277 #ifdef WITH_PRESENCE
3280 if(presenceResource.handle)
3282 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3283 if(resource != (OCResource *) presenceResource.handle)
3285 SendPresenceNotification(resource->rsrcType);
3289 SendPresenceNotification(NULL);
3294 if (temp == headResource) {
3295 headResource = temp->next;
3297 prev->next = temp->next;
3300 deleteResourceElements(temp);
3313 * Delete all of the dynamically allocated elements that were created for the resource.
3315 * @param resource - specified resource
3317 void deleteResourceElements(OCResource *resource) {
3323 OCFree(resource->uri);
3325 // Delete resourcetype linked list
3326 deleteResourceType(resource->rsrcType);
3328 // Delete resourceinterface linked list
3329 deleteResourceInterface(resource->rsrcInterface);
3333 * Delete all of the dynamically allocated elements that were created for the resource type.
3335 * @param resourceType - specified resource type
3337 void deleteResourceType(OCResourceType *resourceType) {
3338 OCResourceType *pointer = resourceType;
3339 OCResourceType *next;
3342 next = pointer->next;
3343 OCFree(pointer->resourcetypename);
3350 * Delete all of the dynamically allocated elements that were created for the resource interface.
3352 * @param resourceInterface - specified resource interface
3354 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3355 OCResourceInterface *pointer = resourceInterface;
3356 OCResourceInterface *next;
3359 next = pointer->next;
3360 OCFree(pointer->name);
3367 * Insert a resource type into a resource's resource type linked list.
3369 * @param resource - resource where resource type is to be inserted
3370 * @param resourceType - resource type to be inserted
3372 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3373 OCResourceType *pointer;
3375 if (resource && !resource->rsrcType) {
3376 resource->rsrcType = resourceType;
3380 pointer = resource->rsrcType;
3384 pointer = resourceType;
3386 while (pointer->next) {
3387 pointer = pointer->next;
3389 pointer->next = resourceType;
3391 resourceType->next = NULL;
3395 * Get a resource type at the specified index within a resource.
3397 * @param handle - handle of resource
3398 * @param index - index of resource type
3401 * resourcetype - if found
3404 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3405 OCResource *resource;
3406 OCResourceType *pointer;
3409 // Find the specified resource
3410 resource = findResource((OCResource *) handle);
3415 // Make sure a resource has a resourcetype
3416 if (!resource->rsrcType) {
3420 // Iterate through the list
3421 pointer = resource->rsrcType;
3423 while ((i < index) && pointer) {
3425 pointer = pointer->next;
3431 * Finds a resource type in an OCResourceType link-list.
3433 * @param resourceTypeList - the link-list to be searched through
3434 * @param resourceTypeName - the key to search for
3437 * resourceType that matches the key (ie. resourceTypeName)
3438 * NULL - either an invalid parameter or this function was unable to find the key.
3440 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3442 if(resourceTypeList && resourceTypeName)
3444 OCResourceType * rtPointer = resourceTypeList;
3445 while(resourceTypeName && rtPointer)
3447 if(rtPointer->resourcetypename &&
3448 strcmp(resourceTypeName, (const char *)
3449 (rtPointer->resourcetypename)) == 0)
3453 rtPointer = rtPointer->next;
3460 * Insert a resource interface into a resource's resource interface linked list.
3462 * @param resource - resource where resource interface is to be inserted
3463 * @param resourceInterface - resource interface to be inserted
3465 void insertResourceInterface(OCResource *resource,
3466 OCResourceInterface *resourceInterface) {
3467 OCResourceInterface *pointer;
3469 if (!resource->rsrcInterface) {
3470 resource->rsrcInterface = resourceInterface;
3472 pointer = resource->rsrcInterface;
3473 while (pointer->next) {
3474 pointer = pointer->next;
3476 pointer->next = resourceInterface;
3478 resourceInterface->next = NULL;
3482 * Get a resource interface at the specified index within a resource.
3484 * @param handle - handle of resource
3485 * @param index - index of resource interface
3488 * resourceinterface - if found
3491 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3493 OCResource *resource;
3494 OCResourceInterface *pointer;
3497 // Find the specified resource
3498 resource = findResource((OCResource *) handle);
3503 // Make sure a resource has a resourceinterface
3504 if (!resource->rsrcInterface) {
3508 // Iterate through the list
3509 pointer = resource->rsrcInterface;
3511 while ((i < index) && pointer) {
3513 pointer = pointer->next;
3519 * Determine if a request/response must be sent in a block transfer because it is too large to be
3520 * sent in a single PDU. This function can be used for either a request or a response
3522 * @param request - NULL or pointer to request
3523 * @param response - NULL or pointer to response
3524 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3525 * the length of the request/response
3528 * 0 - packet transfer NOT required (i.e. normal request/response)
3529 * 1 - packet transfer required (i.e. block transfer needed)
3531 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3535 // Determine if we are checking a request or a response
3538 // If size is greater than 0, use it for the request size value, otherwise
3539 // assume request is null terminated and use strlen for size value
3540 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3547 // If size is greater than 0, use it for the response size value, otherwise
3548 // assume response is null terminated and use strlen for size value
3549 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3558 * Retrieves a resource type based upon a query ontains only just one
3559 * resource attribute (and that has to be of type "rt").
3561 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3562 * before passing in.
3564 * @param query - The quert part of the URI
3565 * @param resourceType - The resource type to be populated; pass by reference.
3568 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3569 * OC_STACK_OK - Success
3571 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3575 return OC_STACK_INVALID_PARAM;
3578 OCStackResult result = OC_STACK_ERROR;
3580 if(strncmp(query, "rt=", 3) == 0)
3582 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3585 result = OC_STACK_NO_MEMORY;
3588 strcpy((char *)*resourceType, ((const char *)&query[3]));
3589 result = OC_STACK_OK;
3595 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3599 return OC_STACK_INVALID_URI;
3601 if(!query || !newURI)
3603 return OC_STACK_INVALID_PARAM;
3605 char * leftToken = NULL;
3606 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3611 strcpy(tempURI, uri);
3613 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3615 //TODO-CA: This could be simplified. Clean up required.
3616 while(leftToken != NULL)
3618 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3620 *query = (unsigned char *) OCMalloc(strlen(leftToken) + 1);
3626 strcpy((char *)*query, ((const char *)&leftToken[0]));
3629 leftToken = strtok_r(NULL, "?", &strTokPtr);
3637 return OC_STACK_NO_MEMORY;
3640 const ServerID OCGetServerInstanceID(void)
3642 static bool generated = false;
3643 static ServerID sid;
3650 sid = OCGetRandom();
3655 const char* OCGetServerInstanceIDString(void)
3657 // max printed length of a base 10
3658 // uint32 is 10 characters, so 11 includes null.
3659 // This will change as the representation gets switched
3661 static char buffer[11];
3662 int n = sprintf(buffer, "%u", OCGetServerInstanceID());