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>
56 //-----------------------------------------------------------------------------
58 //-----------------------------------------------------------------------------
60 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
64 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
68 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
71 static OCStackState stackState = OC_STACK_UNINITIALIZED;
73 OCResource *headResource = NULL;
75 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
76 static PresenceResource presenceResource;
77 uint8_t PresenceTimeOutSize = 0;
78 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
82 OCDeviceEntityHandler defaultDeviceHandler;
83 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
85 //-----------------------------------------------------------------------------
87 //-----------------------------------------------------------------------------
88 #define TAG PCF("OCStack")
89 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
90 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
91 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
92 TAG, PCF(#arg " is NULL")); return (retVal); } }
93 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
96 //TODO: we should allow the server to define this
97 #define MAX_OBSERVE_AGE (0x2FFFFUL)
99 //=============================================================================
101 //=============================================================================
102 static uint32_t GetTime(float afterSeconds)
106 return now + (uint32_t)(afterSeconds * COAP_TICKS_PER_SECOND);
109 static OCStackResult FormOCResponse(OCResponse * * responseLoc,
112 unsigned char * fullUri,
113 unsigned char * rcvdUri,
114 CAToken_t * rcvdToken,
115 OCClientResponse * clientResponse,
116 unsigned char * bufRes)
118 OCResponse * response = (OCResponse *) OCMalloc(sizeof(OCResponse));
121 return OC_STACK_NO_MEMORY;
123 response->cbNode = cbNode;
124 response->maxAge = maxAge;
125 response->fullUri = fullUri;
126 response->rcvdUri = rcvdUri;
127 response->rcvdToken = rcvdToken;
128 response->clientResponse = clientResponse;
129 response->bufRes = bufRes;
131 *responseLoc = response;
135 /// This method is used to create the IPv4 dev_addr structure.
136 /// TODO: Remove in future. Temporary helper function.
137 /// Builds a socket interface address using IP address and port number
138 static int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
139 uint16_t port, OCDevAddr *ipAddr)
142 OC_LOG(FATAL, TAG, "Invalid argument");
150 *((uint16_t*)&(ipAddr->addr[4])) = port;
155 //-----------------------------------------------------------------------------
156 // Internal API function
157 //-----------------------------------------------------------------------------
159 // This internal function is called to update the stack with the status of
160 // observers and communication failures
161 OCStackResult OCStackFeedBack(CAToken_t * token, uint8_t status)
163 OCStackResult result = OC_STACK_ERROR;
164 ResourceObserver * observer = NULL;
165 OCEntityHandlerRequest ehRequest = {0};
169 case OC_OBSERVER_NOT_INTERESTED:
170 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
171 observer = GetObserverUsingToken (token);
174 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
175 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
176 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
177 if(result != OC_STACK_OK)
181 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
183 //observer is not observing anymore
184 result = DeleteObserverUsingToken (token);
185 if(result == OC_STACK_OK)
187 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
191 result = OC_STACK_OK;
192 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
195 case OC_OBSERVER_STILL_INTERESTED:
196 //observer is still interested
197 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
198 notifications, reset the failedCount"));
199 observer = GetObserverUsingToken (token);
202 observer->forceHighQos = 0;
203 observer->failedCommCount = 0;
204 result = OC_STACK_OK;
208 result = OC_STACK_OBSERVER_NOT_FOUND;
211 case OC_OBSERVER_FAILED_COMM:
212 //observer is not reachable
213 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
214 observer = GetObserverUsingToken (token);
217 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
219 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
220 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
221 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
222 if(result != OC_STACK_OK)
224 return OC_STACK_ERROR;
226 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
227 //observer is unreachable
228 result = DeleteObserverUsingToken (token);
229 if(result == OC_STACK_OK)
231 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
235 result = OC_STACK_OK;
236 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
241 observer->failedCommCount++;
242 result = OC_STACK_CONTINUE;
244 observer->forceHighQos = 1;
245 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
249 OC_LOG(ERROR, TAG, PCF("Unknown status"));
250 result = OC_STACK_ERROR;
256 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
258 OCStackResult ret = OC_STACK_ERROR;
266 ret = OC_STACK_RESOURCE_CREATED;
269 ret = OC_STACK_RESOURCE_DELETED;
272 ret = OC_STACK_INVALID_QUERY;
275 ret = OC_STACK_INVALID_OPTION;
278 ret = OC_STACK_NO_RESOURCE;
286 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
288 OCStackResult ret = OC_STACK_OK;
293 *caConType = CA_ETHERNET;
296 *caConType = CA_WIFI;
305 // Currently OC_ALL represents WIFI and ETHERNET
306 // Add other connectivity types as they are enabled in future
307 *caConType = (CAConnectivityType_t) (CA_WIFI|CA_ETHERNET);
310 ret = OC_STACK_INVALID_PARAM;
316 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
318 OCStackResult ret = OC_STACK_OK;
323 *ocConType = OC_ETHERNET;
326 *ocConType = OC_WIFI;
335 ret = OC_STACK_INVALID_PARAM;
341 // update response.addr appropriately from endPoint.addressInfo
342 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
344 OCStackResult ret = OC_STACK_ERROR;
345 static OCDevAddr address = {0};
347 char * savePtr = NULL;
348 char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
351 ret = OC_STACK_NO_MEMORY;
354 memcpy(cpAddress, endPoint->addressInfo.IP.ipAddress,
355 strlen(endPoint->addressInfo.IP.ipAddress) + 1);
357 // Grabs the first three numbers from the IPv4 address and replaces dots
358 for(int i=0; i<4; i++)
360 tok = strtok_r(i==0 ? cpAddress : NULL, ".", &savePtr);
364 ret = OC_STACK_ERROR;
367 address.addr[i] = atoi(tok);
370 memcpy(&address.addr[4], &endPoint->addressInfo.IP.port, sizeof(uint32_t));
374 response->addr = &address;
375 ret = CAToOCConnectivityType(endPoint->connectivityType, &(response->connType));
379 OC_LOG(ERROR, TAG, PCF("OCClientResponse is NULL!"));
386 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
390 // The format of the payload is {"oc":[%u:%u:%s]}
391 // %u : sequence number,
393 // %s : Resource Type (Optional)
394 tok = strtok_r(payload, "[:]}", &savePtr);
395 payload[strlen(payload)] = ':';
396 tok = strtok_r(NULL, "[:]}", &savePtr);
397 payload[strlen((char *)payload)] = ':';
398 *seqNum = (uint32_t) atoi(tok);
399 tok = strtok_r(NULL, "[:]}", &savePtr);
400 *maxAge = (uint32_t) atoi(tok);
401 tok = strtok_r(NULL, "[:]}",&savePtr);
405 *resType = (char *)OCMalloc(strlen(tok));
410 payload[strlen((char *)payload)] = ':';
411 strcpy(*resType, tok);
412 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
414 payload[strlen((char *)payload)] = ']';
417 OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
418 const CAResponseInfo_t* responseInfo)
420 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
421 ClientCB * cbNode = NULL;
422 char *resourceTypeName = NULL;
423 OCClientResponse response;
424 OCStackResult result = OC_STACK_ERROR;
425 uint32_t lowerBound = 0;
426 uint32_t higherBound = 0;
429 char *fullUri = NULL;
430 char *ipAddress = NULL;
431 int presenceSubscribe = 0;
432 int multicastPresenceSubscribe = 0;
434 if (responseInfo->result != CA_SUCCESS)
436 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
437 return OC_STACK_ERROR;
440 fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
444 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
445 result = OC_STACK_NO_MEMORY;
449 ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
451 if(NULL == ipAddress)
453 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
454 result = OC_STACK_NO_MEMORY;
458 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
459 strlen(endPoint->addressInfo.IP.ipAddress));
460 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
462 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
465 cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
469 presenceSubscribe = 1;
473 snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
474 cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
477 multicastPresenceSubscribe = 1;
481 if(!presenceSubscribe && !multicastPresenceSubscribe)
483 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
484 ------------ ignoring"));
488 // No payload to the application in case of presence
489 response.resJSONPayload = NULL;
490 response.result = OC_STACK_OK;
492 result = UpdateResponseAddr(&response, endPoint);
493 if(result != OC_STACK_OK)
498 if(responseInfo->info.payload)
500 parsePresencePayload(responseInfo->info.payload,
501 &(response.sequenceNumber),
508 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
509 response.result = OC_STACK_PRESENCE_STOPPED;
512 OCFree(cbNode->presence->timeOut);
513 OCFree(cbNode->presence);
514 cbNode->presence = NULL;
517 else if(presenceSubscribe)
519 if(!cbNode->presence)
521 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
522 VERIFY_NON_NULL_V(cbNode->presence);
523 cbNode->presence->timeOut = NULL;
524 cbNode->presence->timeOut = (uint32_t *)
525 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
526 if(!(cbNode->presence->timeOut)){
527 OCFree(cbNode->presence);
528 result = OC_STACK_NO_MEMORY;
532 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %u", GetTime(0));
533 cbNode->presence->TTL = maxAge;
534 for(int index = 0; index < PresenceTimeOutSize; index++)
536 lowerBound = GetTime(((float)(PresenceTimeOut[index])
537 /(float)100)*(float)cbNode->presence->TTL);
538 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
539 /(float)100)*(float)cbNode->presence->TTL);
540 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
541 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
542 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
543 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
544 cbNode->presence->timeOut[index]);
546 cbNode->presence->TTLlevel = 0;
547 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
548 if(cbNode->sequenceNumber == response.sequenceNumber)
550 OC_LOG(INFO, TAG, PCF("===============No presence change"));
553 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
554 cbNode->sequenceNumber = response.sequenceNumber;
556 // Ensure that a filter is actually applied.
557 if(resourceTypeName && cbNode->filterResourceType)
559 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
567 // This is the multicast case
569 OCMulticastNode* mcNode = NULL;
570 mcNode = GetMCPresenceNode((const unsigned char *)fullUri);
574 if(mcNode->nonce == response.sequenceNumber)
576 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
579 mcNode->nonce = response.sequenceNumber;
583 uint32_t uriLen = strlen((char*)fullUri);
584 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
587 memcpy(uri, fullUri, (uriLen + 1));
592 PCF("===============No Memory for URI to store in the presence node"));
593 result = OC_STACK_NO_MEMORY;
596 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
597 if(result == OC_STACK_NO_MEMORY)
600 PCF("===============No Memory for Multicast Presence Node"));
601 result = OC_STACK_NO_MEMORY;
606 // Ensure that a filter is actually applied.
607 if(resourceTypeName && cbNode->filterResourceType)
609 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
616 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
618 if (cbResult == OC_STACK_DELETE_TRANSACTION)
620 FindAndDeleteClientCB(cbNode);
626 OCFree(resourceTypeName);
631 //This function will be called back by CA layer when a response is received
632 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
634 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
636 OCStackApplicationResult appResult = OC_STACK_DELETE_TRANSACTION;
640 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
644 if(NULL == responseInfo)
646 OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
650 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
652 HandlePresenceResponse(endPoint, responseInfo);
656 ClientCB *cbNode = GetClientCB((CAToken_t *)&(responseInfo->info.token), NULL, NULL);
660 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
661 OCClientResponse response;
663 OCStackResult result = UpdateResponseAddr(&response, endPoint);
664 if(result != OC_STACK_OK)
666 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
670 response.result = CAToOCStackResult(responseInfo->result);
671 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
672 response.numRcvdVendorSpecificHeaderOptions = 0;
673 if(responseInfo->info.numOptions > 0)
676 //First option always with option ID is OC_COAP_OPTION_OBSERVE if it is available.
677 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
679 memcpy (&(response.sequenceNumber),
680 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
681 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
686 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
689 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
691 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
695 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
697 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
698 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
701 appResult = cbNode->callBack(cbNode->context,
702 cbNode->handle, &response);
703 if (appResult == OC_STACK_DELETE_TRANSACTION)
705 FindAndDeleteClientCB(cbNode);
708 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
709 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
712 //This function will be called back by CA layer when a request is received
713 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
715 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
718 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
724 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
728 OCStackResult requestResult = OC_STACK_ERROR;
730 if(myStackMode == OC_CLIENT)
732 //TODO: should the client be responding to requests?
736 OCServerProtocolRequest serverRequest = {};
738 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
740 char * newUri = (char *)endPoint->resourceUri;
741 unsigned char * query = NULL;
742 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
743 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
744 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
745 if(strlen(newUri) < MAX_URI_LENGTH)
748 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
752 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
758 if(strlen((char*)query) < MAX_QUERY_LENGTH)
760 memcpy (&(serverRequest.query), query, strlen((char*)query));
764 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
768 //copy request payload
769 if (requestInfo->info.payload)
771 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
772 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
773 strlen(requestInfo->info.payload));
774 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
778 serverRequest.reqTotalSize = 1;
781 switch (requestInfo->method)
785 serverRequest.method = OC_REST_GET;
790 serverRequest.method = OC_REST_PUT;
795 serverRequest.method = OC_REST_POST;
800 serverRequest.method = OC_REST_DELETE;
805 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
810 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
811 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
813 serverRequest.requestToken = (CAToken_t)OCCalloc(1, CA_MAX_TOKEN_LEN+1);
815 if (!serverRequest.requestToken)
817 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
820 memcpy(serverRequest.requestToken, requestInfo->info.token, CA_MAX_TOKEN_LEN);
822 if (requestInfo->info.type == CA_MSG_CONFIRM)
824 serverRequest.qos = OC_HIGH_QOS;
826 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
828 serverRequest.qos = OC_LOW_QOS;
830 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
832 // TODO-CA: Need to handle this
834 else if (requestInfo->info.type == CA_MSG_RESET)
836 // TODO-CA: Need to handle this
838 // CA does not need the following 3 fields
839 serverRequest.coapID = 0;
840 serverRequest.delayedResNeeded = 0;
841 serverRequest.secured = endPoint->isSecured;
844 serverRequest.addressInfo = endPoint->addressInfo;
845 serverRequest.connectivityType = endPoint->connectivityType;
847 // copy vendor specific header options
848 // TODO-CA: CA is including non-vendor header options as well, like observe.
849 // Need to filter those out
850 uint8_t tempNum = (requestInfo->info.numOptions);
851 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
852 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
855 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
856 OCFree(serverRequest.requestToken);
859 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
860 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
862 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
863 sizeof(CAHeaderOption_t)*tempNum);
866 requestResult = HandleStackRequests (&serverRequest);
867 if(requestResult != OC_STACK_OK)
869 OC_LOG(ERROR, TAG, PCF("HandleStackRequests failed"));
871 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
874 //This function will be called back by occoap layer when a request is received
875 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
877 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
878 OCStackResult result = OC_STACK_ERROR;
879 ResourceHandling resHandling;
880 OCResource *resource;
883 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
884 return OC_STACK_INVALID_PARAM;
887 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
890 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
891 result = AddServerRequest(&request, protocolRequest->coapID,
892 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
893 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
894 protocolRequest->observationOption, protocolRequest->qos,
895 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
896 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
897 protocolRequest->resourceUrl,protocolRequest->reqTotalSize,
898 &protocolRequest->addressInfo, protocolRequest->connectivityType);
899 if (OC_STACK_OK != result)
901 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
904 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
906 if(!protocolRequest->reqMorePacket)
908 request->requestComplete = 1;
913 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
916 if(request->requestComplete)
918 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
919 result = DetermineResourceHandling (request, &resHandling, &resource);
920 if (result == OC_STACK_OK)
922 result = ProcessRequest(resHandling, resource, request);
926 result = OC_STACK_ERROR;
931 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
932 result = OC_STACK_CONTINUE;
937 //This function will be called back by occoap layer when a response is received
938 OCStackResult HandleStackResponses(OCResponse * response)
940 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
941 OCStackResult result = OC_STACK_OK;
942 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
943 uint8_t isObserveNotification = 0;
944 ClientCB * cbNode = NULL;
947 OC_LOG(ERROR, TAG, PCF("response is NULL"));
948 return OC_STACK_INVALID_PARAM;
951 uint8_t isPresenceNotification = 0;
952 uint8_t isMulticastPresence = 0;
953 char * resourceTypeName = NULL;
954 uint32_t lowerBound = 0;
955 uint32_t higherBound = 0;
957 unsigned char * bufRes = response->bufRes;
958 #endif // WITH_PRESENCE
960 cbNode = response->cbNode;
963 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
966 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
968 isObserveNotification = 1;
969 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
972 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
973 response->clientResponse->sequenceNumber);
974 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
975 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
978 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
979 isPresenceNotification = 1;
982 result = OC_STACK_INVALID_PARAM;
986 tok = strtok_r((char *)bufRes, "[:]}", &savePtr);
987 bufRes[strlen((char *)bufRes)] = ':';
988 tok = strtok_r(NULL, "[:]}", &savePtr);
989 bufRes[strlen((char *)bufRes)] = ':';
990 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
991 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
992 tok = strtok_r(NULL, "[:]}", &savePtr);
993 response->maxAge = (uint32_t )atoi(tok);
994 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
995 tok = strtok_r(NULL, "[:]}", &savePtr);
998 resourceTypeName = (char *)OCMalloc(strlen(tok));
999 if(!resourceTypeName)
1003 bufRes[strlen((char *)bufRes)] = ':';
1004 strcpy(resourceTypeName, tok);
1005 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
1008 bufRes[strlen((char *)bufRes)] = ']';
1011 // Check if the application subcribed for presence
1014 cbNode = GetClientCB(NULL, NULL, response->fullUri);
1017 // Check if application subscribed for multicast presence
1020 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
1021 OC_MULTICAST_IP, response->rcvdUri);
1022 cbNode = GetClientCB(NULL, NULL, response->fullUri);
1025 isMulticastPresence = 1;
1026 isPresenceNotification = 0;
1030 if(cbNode && isPresenceNotification)
1032 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
1033 if(!cbNode->presence)
1035 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
1036 VERIFY_NON_NULL_V(cbNode->presence);
1037 cbNode->presence->timeOut = NULL;
1038 cbNode->presence->timeOut = (uint32_t *)
1039 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1040 if(!(cbNode->presence->timeOut)){
1041 OCFree(cbNode->presence);
1042 result = OC_STACK_NO_MEMORY;
1045 if(response->maxAge == 0)
1047 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
1048 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
1049 if(cbNode->presence)
1051 OCFree(cbNode->presence->timeOut);
1052 OCFree(cbNode->presence);
1053 cbNode->presence = NULL;
1058 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
1059 cbNode->presence->TTL = response->maxAge;
1060 for(int index = 0; index < PresenceTimeOutSize; index++)
1062 lowerBound = GetTime(((float)(PresenceTimeOut[index])
1063 /(float)100)*(float)cbNode->presence->TTL);
1064 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
1065 /(float)100)*(float)cbNode->presence->TTL);
1066 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
1067 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
1068 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
1069 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
1070 cbNode->presence->timeOut[index]);
1072 cbNode->presence->TTLlevel = 0;
1073 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1074 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
1076 OC_LOG(INFO, TAG, PCF("===============No presence change"));
1079 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
1080 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
1083 // Ensure that a filter is actually applied.
1084 if(resourceTypeName && cbNode->filterResourceType)
1086 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1092 else if(cbNode && isMulticastPresence)
1094 // Check if the same nonce for a given host
1095 OCMulticastNode* mcNode = NULL;
1096 mcNode = GetMCPresenceNode(response->fullUri);
1098 if(response->maxAge == 0)
1100 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
1101 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
1102 if(cbNode->presence)
1104 OCFree(cbNode->presence->timeOut);
1105 OCFree(cbNode->presence);
1106 cbNode->presence = NULL;
1109 else if(mcNode != NULL)
1111 if(mcNode->nonce == response->clientResponse->sequenceNumber)
1113 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
1114 result = OC_STACK_NO_MEMORY;
1117 mcNode->nonce = response->clientResponse->sequenceNumber;
1121 uint32_t uriLen = strlen((char*)response->fullUri);
1122 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
1125 memcpy(uri, response->fullUri, (uriLen + 1));
1130 PCF("===============No Memory for URI to store in the presence node"));
1131 result = OC_STACK_NO_MEMORY;
1134 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
1135 response->clientResponse->sequenceNumber);
1136 if(result == OC_STACK_NO_MEMORY)
1139 PCF("===============No Memory for Multicast Presence Node"));
1140 result = OC_STACK_NO_MEMORY;
1145 // Ensure that a filter is actually applied.
1146 if(resourceTypeName && cbNode->filterResourceType)
1148 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1155 else if(!cbNode && isPresenceNotification)
1157 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
1158 ------------ ignoring"));
1160 #endif // WITH_PRESENCE
1164 if(isObserveNotification)
1166 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
1167 //TODO: check the standard for methods to detect wrap around condition
1168 if(cbNode->method == OC_REST_OBSERVE &&
1169 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
1170 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
1171 response->clientResponse->sequenceNumber ==
1172 MAX_SEQUENCE_NUMBER)))
1174 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
1175 Ignoring Incoming:%d Against Current:%d.",
1176 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
1179 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
1180 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
1184 response->clientResponse->resJSONPayload = bufRes;
1186 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
1188 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
1189 response->clientResponse->result == OC_STACK_COMM_ERROR ||
1190 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
1191 !isPresenceNotification && !isMulticastPresence))
1193 FindAndDeleteClientCB(cbNode);
1198 result = OC_STACK_ERROR;
1202 #ifdef WITH_PRESENCE
1203 OCFree(resourceTypeName);
1208 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
1211 unsigned char *itr, *coap;
1212 uint8_t dotCount = 0;
1216 /* search for scheme */
1218 if (!isdigit((unsigned char) *ipAddrStr))
1220 coap = (unsigned char *) OC_COAP_SCHEME;
1221 while (*coap && tolower(*itr) == *coap)
1229 while (*ipAddrStr) {
1230 if (isdigit((unsigned char) *ipAddrStr))
1232 ipAddr[index] *= 10;
1233 ipAddr[index] += *ipAddrStr - '0';
1235 else if ((unsigned char) *ipAddrStr == '.')
1247 if(*ipAddrStr == ':')
1251 if (isdigit((unsigned char) *ipAddrStr))
1254 *port += *ipAddrStr - '0';
1265 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
1276 //-----------------------------------------------------------------------------
1277 // Private internal function prototypes
1278 //-----------------------------------------------------------------------------
1280 static OCDoHandle GenerateInvocationHandle();
1281 static OCStackResult initResources();
1282 static void insertResource(OCResource *resource);
1283 static OCResource *findResource(OCResource *resource);
1284 static void insertResourceType(OCResource *resource,
1285 OCResourceType *resourceType);
1286 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
1288 static void insertResourceInterface(OCResource *resource,
1289 OCResourceInterface *resourceInterface);
1290 static OCResourceInterface *findResourceInterfaceAtIndex(
1291 OCResourceHandle handle, uint8_t index);
1292 static void deleteResourceType(OCResourceType *resourceType);
1293 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
1294 static void deleteResourceElements(OCResource *resource);
1295 static int deleteResource(OCResource *resource);
1296 static void deleteAllResources();
1297 static void incrementSequenceNumber(OCResource * resPtr);
1298 static OCStackResult verifyUriQueryLength(const char * inputUri,
1300 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
1301 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
1303 //-----------------------------------------------------------------------------
1305 //-----------------------------------------------------------------------------
1308 * Initialize the OC Stack. Must be called prior to starting the stack.
1311 * IP Address of host device
1313 * Port of host device
1315 * Host device is client, server, or client-server
1318 * OC_STACK_OK - no errors
1319 * OC_STACK_ERROR - stack init error
1321 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1323 OCStackResult result = OC_STACK_ERROR;
1324 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1327 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1329 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1330 return OC_STACK_ERROR;
1335 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
1340 //It is ok to select network to CA_WIFI for now
1342 CAResult_t caResult = CASelectNetwork(CA_ETHERNET);
1344 CAResult_t caResult = CASelectNetwork(CA_WIFI|CA_ETHERNET);
1346 if(caResult == CA_STATUS_OK)
1348 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
1349 CARegisterHandler(HandleCARequests, HandleCAResponses);
1351 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
1352 stackState = OC_STACK_INITIALIZED;
1353 result = OC_STACK_OK;
1357 caResult = CAStartDiscoveryServer();
1358 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1361 caResult = CAStartListeningServer();
1362 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1364 case OC_CLIENT_SERVER:
1365 caResult = CAStartListeningServer();
1366 if(caResult == CA_STATUS_OK)
1368 caResult = CAStartDiscoveryServer();
1370 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1373 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1374 return OC_STACK_ERROR;
1379 if (caResult == CA_STATUS_OK)
1381 result = OC_STACK_OK;
1385 result = OC_STACK_ERROR;
1390 defaultDeviceHandler = NULL;
1392 #if defined(__WITH_DTLS__)
1393 caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
1394 result = (caResult == CA_STATUS_OK) ? OC_STACK_OK : OC_STACK_ERROR;
1395 #endif // (__WITH_DTLS__)
1397 #ifdef WITH_PRESENCE
1398 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1399 #endif // WITH_PRESENCE
1401 if (result == OC_STACK_OK)
1403 stackState = OC_STACK_INITIALIZED;
1405 // Initialize resource
1406 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1408 result = initResources();
1410 if(result != OC_STACK_OK)
1412 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1418 * Stop the OC stack. Use for a controlled shutdown.
1420 * OC_STACK_OK - no errors
1421 * OC_STACK_ERROR - stack not initialized
1423 OCStackResult OCStop()
1425 OCStackResult result = OC_STACK_ERROR;
1427 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1429 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1431 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1434 else if (stackState != OC_STACK_INITIALIZED)
1436 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1437 return OC_STACK_ERROR;
1440 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1442 #ifdef WITH_PRESENCE
1443 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1444 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1445 presenceResource.presenceTTL = 0;
1446 #endif // WITH_PRESENCE
1448 // Free memory dynamically allocated for resources
1449 deleteAllResources();
1452 //CATerminate does not return any error code. It is OK to assign result to OC_STACK_OK.
1453 result = OC_STACK_OK;
1455 if (result == OC_STACK_OK)
1457 // Remove all observers
1458 DeleteObserverList();
1459 // Remove all the client callbacks
1460 DeleteClientCBList();
1461 stackState = OC_STACK_UNINITIALIZED;
1462 result = OC_STACK_OK;
1464 stackState = OC_STACK_INITIALIZED;
1465 result = OC_STACK_ERROR;
1468 // Deinit security blob
1469 DeinitOCSecurityInfo();
1471 if (result != OC_STACK_OK) {
1472 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1479 * Map OCQualityOfService to CAMessageType
1481 * @param OCQualityOfService - Input qos.
1483 * Returns CA message type for a given qos.
1485 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1490 return CA_MSG_CONFIRM;
1495 return CA_MSG_NONCONFIRM;
1500 * Verify the lengths of the URI and the query separately
1502 * @param inputUri - Input URI and query.
1503 * @param uriLen - The length of the initial URI with query.
1505 * Note: The '?' that appears after the URI is not considered as
1506 * a part of the query.
1508 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1512 query = strchr (inputUri, '?');
1516 if((query - inputUri) > MAX_URI_LENGTH)
1518 return OC_STACK_INVALID_URI;
1521 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1523 return OC_STACK_INVALID_QUERY;
1526 else if(uriLen > MAX_URI_LENGTH)
1528 return OC_STACK_INVALID_URI;
1534 * Discover or Perform requests on a specified resource
1535 * (specified by that Resource's respective URI).
1537 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of
1539 * @param method - @ref OCMethod to perform on the resource
1540 * @param requiredUri - URI of the resource to interact with
1541 * @param referenceUri - URI of the reference resource
1542 * @param request - JSON encoded request
1543 * @param qos - quality of service
1544 * @param cbData - struct that contains asynchronous callback function that is invoked
1545 * by the stack when discovery or resource interaction is complete
1546 * @param options - The address of an array containing the vendor specific header
1547 * header options to be sent with the request
1548 * @param numOptions - Number of vendor specific header options to be included
1551 * OC_STACK_OK - no errors
1552 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1553 * OC_STACK_INVALID_METHOD - invalid resource method
1554 * OC_STACK_INVALID_URI - invalid required or reference URI
1556 * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
1557 * Instead, it just contains the URI to the resource such as "/oc/core".
1559 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1560 const char *referenceUri, const char *request, OCConnectivityType conType,
1561 OCQualityOfService qos, OCCallbackData *cbData,
1562 OCHeaderOption * options, uint8_t numOptions)
1564 OCStackResult result = OC_STACK_ERROR;
1565 ClientCB *clientCB = NULL;
1566 unsigned char * requestUri = NULL;
1567 unsigned char * resourceType = NULL;
1568 unsigned char * query = NULL;
1569 char * newUri = (char *)requiredUri;
1570 (void) referenceUri;
1571 CARemoteEndpoint_t* endpoint = NULL;
1572 CAResult_t caResult;
1573 CAToken_t token = NULL;
1574 CAInfo_t requestData;
1575 CARequestInfo_t requestInfo;
1576 CAGroupEndpoint_t grpEnd = {0};
1578 // To track if memory is allocated for additional header options
1579 uint8_t hdrOptionMemAlloc = 0;
1581 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1583 // Validate input parameters
1584 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1585 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1587 //TODO ("Need to form the final query by concatenating require and reference URI's");
1588 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1590 uint16_t uriLen = strlen(requiredUri);
1592 // ToDo: We should also check if the requiredUri has a mutlicast address,
1593 // then qos has to be OC_Low_QOS
1599 case OC_REST_DELETE:
1600 case OC_REST_OBSERVE:
1601 case OC_REST_OBSERVE_ALL:
1602 case OC_REST_CANCEL_OBSERVE:
1604 #ifdef WITH_PRESENCE
1605 case OC_REST_PRESENCE:
1609 result = OC_STACK_INVALID_METHOD;
1613 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1618 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1620 result = OC_STACK_INVALID_PARAM;
1624 #ifdef WITH_PRESENCE
1625 if(method == OC_REST_PRESENCE)
1627 result = getQueryFromUri(requiredUri, &query, &newUri);
1630 result = getResourceType((char *) query, &resourceType);
1633 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1637 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1642 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1644 if(result != OC_STACK_OK)
1649 #endif // WITH_PRESENCE
1651 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1654 memcpy(requestUri, newUri, (uriLen + 1));
1658 result = OC_STACK_NO_MEMORY;
1662 *handle = GenerateInvocationHandle();
1665 result = OC_STACK_NO_MEMORY;
1669 memset(&requestData, 0, sizeof(CAInfo_t));
1670 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1674 case OC_REST_OBSERVE:
1675 case OC_REST_OBSERVE_ALL:
1676 case OC_REST_CANCEL_OBSERVE:
1678 requestInfo.method = CA_GET;
1683 requestInfo.method = CA_PUT;
1688 requestInfo.method = CA_POST;
1691 case OC_REST_DELETE:
1693 requestInfo.method = CA_DELETE;
1696 #ifdef WITH_PRESENCE
1697 case OC_REST_PRESENCE:
1699 // Replacing method type with GET because "presence"
1700 // is a stack layer only implementation.
1701 requestInfo.method = CA_GET;
1706 result = OC_STACK_INVALID_METHOD;
1710 //High QoS is not supported
1711 if(qos == OC_HIGH_QOS)
1713 result = OC_STACK_INVALID_PARAM;
1718 caResult = CAGenerateToken(&token);
1719 if (caResult != CA_STATUS_OK)
1721 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1722 CADestroyToken(token);
1726 requestData.type = qualityOfServiceToMessageType(qos);
1727 requestData.token = token;
1728 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1730 result = CreateObserveHeaderOption (&(requestData.options), options,
1731 numOptions, OC_OBSERVE_REGISTER);
1732 if (result != OC_STACK_OK)
1736 hdrOptionMemAlloc = 1;
1737 requestData.numOptions = numOptions + 1;
1741 requestData.options = (CAHeaderOption_t*)options;
1742 requestData.numOptions = numOptions;
1744 requestData.payload = (char *)request;
1746 requestInfo.info = requestData;
1748 CAConnectivityType_t caConType;
1750 result = OCToCAConnectivityType((OCConnectivityType) conType, &caConType);
1751 if (result != OC_STACK_OK)
1753 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1758 if(conType == OC_ALL)
1760 grpEnd.connectivityType = caConType;
1762 grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1763 if(!grpEnd.resourceUri)
1765 result = OC_STACK_NO_MEMORY;
1768 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1770 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1774 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1776 if (caResult != CA_STATUS_OK)
1778 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1782 caResult = CASendRequest(endpoint, &requestInfo);
1785 if (caResult != CA_STATUS_OK)
1787 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1791 if((result = AddClientCB(&clientCB, cbData, &token, handle, method,
1792 requestUri, resourceType)) != OC_STACK_OK)
1794 result = OC_STACK_NO_MEMORY;
1799 if(newUri != requiredUri)
1803 if (result != OC_STACK_OK)
1805 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1806 FindAndDeleteClientCB(clientCB);
1808 CADestroyRemoteEndpoint(endpoint);
1809 OCFree(grpEnd.resourceUri);
1810 if (hdrOptionMemAlloc)
1812 OCFree(requestData.options);
1818 * Cancel a request associated with a specific @ref OCDoResource invocation.
1820 * @param handle - Used to identify a specific OCDoResource invocation.
1821 * @param qos - used to specify Quality of Service (read below for more info)
1822 * @param options- used to specify vendor specific header options when sending
1823 * explicit observe cancellation
1824 * @param numOptions- Number of header options to be included
1827 * OC_STACK_OK - No errors; Success
1828 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1830 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1834 * This ftn is implemented one of two ways in the case of observation:
1836 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1837 * Remove the callback associated on client side.
1838 * When the next notification comes in from server,
1839 * reply with RESET message to server.
1840 * Keep in mind that the server will react to RESET only
1841 * if the last notification was sent ans CON
1843 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1844 * and it is associated with an observe request
1845 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1846 * Send CON Observe request to server with
1847 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1848 * Remove the callback associated on client side.
1850 OCStackResult ret = OC_STACK_OK;
1851 CARemoteEndpoint_t* endpoint = NULL;
1852 CAResult_t caResult;
1853 CAInfo_t requestData;
1854 CARequestInfo_t requestInfo;
1855 // Track if memory is allocated for additional header options
1856 uint8_t hdrOptionMemAlloc = 0;
1859 return OC_STACK_INVALID_PARAM;
1862 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1864 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1867 switch (clientCB->method)
1869 case OC_REST_OBSERVE:
1870 case OC_REST_OBSERVE_ALL:
1871 //TODO-CA : Why CA_WIFI alone?
1872 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1874 if (caResult != CA_STATUS_OK)
1876 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1877 return OC_STACK_ERROR;
1880 memset(&requestData, 0, sizeof(CAInfo_t));
1881 requestData.type = qualityOfServiceToMessageType(qos);
1882 requestData.token = clientCB->token;
1883 if (CreateObserveHeaderOption (&(requestData.options),
1884 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1886 return OC_STACK_ERROR;
1888 hdrOptionMemAlloc = 1;
1889 requestData.numOptions = numOptions + 1;
1890 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1891 requestInfo.method = CA_GET;
1892 requestInfo.info = requestData;
1894 caResult = CASendRequest(endpoint, &requestInfo);
1895 if (caResult != CA_STATUS_OK)
1897 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1899 if(caResult == CA_STATUS_OK)
1903 #ifdef WITH_PRESENCE
1904 case OC_REST_PRESENCE:
1905 FindAndDeleteClientCB(clientCB);
1909 return OC_STACK_INVALID_METHOD;
1912 CADestroyRemoteEndpoint(endpoint);
1913 if (hdrOptionMemAlloc)
1915 OCFree(requestData.options);
1921 #ifdef WITH_PRESENCE
1922 OCStackResult OCProcessPresence()
1924 OCStackResult result = OC_STACK_OK;
1925 uint8_t ipAddr[4] = { 0 };
1928 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1929 ClientCB* cbNode = NULL;
1931 OCClientResponse clientResponse;
1932 OCResponse * response = NULL;
1933 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1935 LL_FOREACH(cbList, cbNode) {
1936 if(OC_REST_PRESENCE == cbNode->method)
1938 if(cbNode->presence)
1940 uint32_t now = GetTime(0);
1941 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
1942 cbNode->presence->TTLlevel);
1943 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1946 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1951 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1952 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1953 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1956 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1958 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1959 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1961 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1964 clientResponse.sequenceNumber = 0;
1965 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
1966 clientResponse.addr = (OCDevAddr *) &dst;
1967 clientResponse.resJSONPayload = NULL;
1969 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1970 &cbNode->token, &clientResponse, NULL);
1971 if(result != OC_STACK_OK)
1976 // Increment the TTLLevel (going to a next state), so we don't keep
1977 // sending presence notification to client.
1978 cbNode->presence->TTLlevel++;
1979 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1980 cbNode->presence->TTLlevel);
1984 result = OC_STACK_INVALID_IP;
1988 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1989 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1991 FindAndDeleteClientCB(cbNode);
1995 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1997 CAResult_t caResult;
1998 CARemoteEndpoint_t* endpoint = NULL;
1999 CAInfo_t requestData;
2000 CARequestInfo_t requestInfo;
2002 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
2004 //TODO-CA : Why CA_WIFI alone?
2005 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
2008 if (caResult != CA_STATUS_OK)
2010 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
2014 memset(&requestData, 0, sizeof(CAInfo_t));
2015 requestData.type = CA_MSG_NONCONFIRM;
2016 requestData.token = cbNode->token;
2018 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
2019 requestInfo.method = CA_GET;
2020 requestInfo.info = requestData;
2022 caResult = CASendRequest(endpoint, &requestInfo);
2024 if (caResult != CA_STATUS_OK)
2026 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2030 cbNode->presence->TTLlevel++;
2031 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
2032 cbNode->presence->TTLlevel);
2038 if (result != OC_STACK_OK)
2040 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2044 #endif // WITH_PRESENCE
2047 * Called in main loop of OC client or server. Allows low-level processing of
2051 * OC_STACK_OK - no errors
2052 * OC_STACK_ERROR - stack process error
2054 OCStackResult OCProcess()
2056 #ifdef WITH_PRESENCE
2057 OCProcessPresence();
2059 CAHandleRequestResponse();
2064 #ifdef WITH_PRESENCE
2066 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
2067 * presence notifications to clients via multicast. Once this API has been called with a success,
2068 * clients may query for this server's presence and this server's stack will respond via multicast.
2070 * Server can call this function when it comes online for the first time, or when it comes back
2071 * online from offline mode, or when it re enters network.
2073 * @param ttl - Time To Live in seconds
2074 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
2077 * OC_STACK_OK - No errors; Success
2079 OCStackResult OCStartPresence(const uint32_t ttl)
2081 OCChangeResourceProperty(
2082 &(((OCResource *)presenceResource.handle)->resourceProperties),
2087 presenceResource.presenceTTL = ttl;
2090 if(OC_PRESENCE_UNINITIALIZED == presenceState)
2092 presenceState = OC_PRESENCE_INITIALIZED;
2094 CAAddress_t addressInfo;
2095 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
2096 addressInfo.IP.port = 5683;
2098 //TODO make sure there is no memory leak here since another copy
2099 //of token is being created inside AddObserver
2100 CAToken_t caToken = NULL;
2101 CAResult_t caResult = CAGenerateToken(&caToken);
2102 if (caResult != CA_STATUS_OK)
2104 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2105 CADestroyToken(caToken);
2106 return OC_STACK_ERROR;
2109 AddObserver(OC_PRESENCE_URI, NULL, 0, &caToken,
2110 (OCResource *)presenceResource.handle, OC_LOW_QOS,
2111 &addressInfo, CA_WIFI);
2114 // Each time OCStartPresence is called
2115 // a different random 32-bit integer number is used
2116 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2118 return SendPresenceNotification(NULL);
2122 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
2123 * presence notifications to clients via multicast. Once this API has been called with a success,
2124 * this server's stack will not respond to clients querying for this server's presence.
2126 * Server can call this function when it is terminating, going offline, or when going
2127 * away from network.
2130 * OC_STACK_OK - No errors; Success
2132 OCStackResult OCStopPresence()
2134 OCStackResult result = OC_STACK_ERROR;
2135 //make resource inactive
2136 result = OCChangeResourceProperty(
2137 &(((OCResource *) presenceResource.handle)->resourceProperties),
2139 result = SendPresenceNotification(NULL);
2146 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
2148 defaultDeviceHandler = entityHandler;
2153 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2155 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2157 if(myStackMode == OC_CLIENT)
2159 return OC_STACK_ERROR;
2162 return SaveDeviceInfo(deviceInfo);
2168 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2169 * Used to refer to resource
2170 * @param resourceTypeName - name of resource type. Example: "core.led"
2171 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2172 * @param uri - URI of the resource. Example: "/a/led"
2173 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2174 * NULL for default entity handler
2175 * @param resourceProperties - properties supported by resource.
2176 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2179 * OC_STACK_OK - no errors
2180 * OC_STACK_ERROR - stack process error
2182 OCStackResult OCCreateResource(OCResourceHandle *handle,
2183 const char *resourceTypeName,
2184 const char *resourceInterfaceName,
2185 const char *uri, OCEntityHandler entityHandler,
2186 uint8_t resourceProperties) {
2188 OCResource *pointer = NULL;
2191 OCStackResult result = OC_STACK_ERROR;
2193 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2195 if(myStackMode == OC_CLIENT)
2199 // Validate parameters
2200 if(!uri || (strlen(uri) == 0))
2202 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2203 return OC_STACK_INVALID_URI;
2205 // Is it presented during resource discovery?
2206 if (!handle || !resourceTypeName) {
2207 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2208 return OC_STACK_INVALID_PARAM;
2211 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
2212 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2215 // Make sure resourceProperties bitmask has allowed properties specified
2216 if (resourceProperties
2217 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
2218 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2219 return OC_STACK_INVALID_PARAM;
2222 // If the headResource is NULL, then no resources have been created...
2223 pointer = headResource;
2225 // At least one resources is in the resource list, so we need to search for
2226 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2228 if (strcmp(uri, pointer->uri) == 0) {
2229 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2230 return OC_STACK_INVALID_PARAM;
2232 pointer = pointer->next;
2235 // Create the pointer and insert it into the resource list
2236 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2240 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2242 insertResource(pointer);
2245 size = strlen(uri) + 1;
2246 str = (char *) OCMalloc(size);
2250 strncpy(str, uri, size);
2253 // Set properties. Set OC_ACTIVE
2254 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2257 // Add the resourcetype to the resource
2258 result = BindResourceTypeToResource(pointer, resourceTypeName);
2259 if (result != OC_STACK_OK) {
2260 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2264 // Add the resourceinterface to the resource
2265 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2266 if (result != OC_STACK_OK) {
2267 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2271 // If an entity handler has been passed, attach it to the newly created
2272 // resource. Otherwise, set the default entity handler.
2275 pointer->entityHandler = entityHandler;
2279 pointer->entityHandler = defaultResourceEHandler;
2283 result = OC_STACK_OK;
2285 #ifdef WITH_PRESENCE
2286 if(presenceResource.handle)
2288 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2289 SendPresenceNotification(pointer->rsrcType);
2293 if (result != OC_STACK_OK)
2295 // Deep delete of resource and other dynamic elements that it contains
2296 deleteResource(pointer);
2305 * Create a resource. with host ip address for remote resource
2307 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2308 * Used to refer to resource
2309 * @param resourceTypeName - name of resource type. Example: "core.led"
2310 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2311 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2312 * @param uri - URI of the resource. Example: "/a/led"
2313 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2314 * NULL for default entity handler
2315 * @param resourceProperties - properties supported by resource.
2316 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2319 * OC_STACK_OK - no errors
2320 * OC_STACK_ERROR - stack process error
2323 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2324 const char *resourceTypeName,
2325 const char *resourceInterfaceName,
2328 OCEntityHandler entityHandler,
2329 uint8_t resourceProperties)
2333 OCStackResult result = OC_STACK_ERROR;
2335 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2336 uri, entityHandler, resourceProperties);
2338 if (result != OC_STACK_ERROR)
2341 size = strlen(host) + 1;
2342 str = (char *) OCMalloc(size);
2345 return OC_STACK_ERROR;
2347 strncpy(str, host, size);
2348 ((OCResource *) *handle)->host = str;
2355 * Add a resource to a collection resource.
2357 * @param collectionHandle - handle to the collection resource
2358 * @param resourceHandle - handle to resource to be added to the collection resource
2361 * OC_STACK_OK - no errors
2362 * OC_STACK_ERROR - stack process error
2363 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2365 OCStackResult OCBindResource(
2366 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2367 OCResource *resource;
2370 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2372 // Validate parameters
2373 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2374 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2375 // Container cannot contain itself
2376 if (collectionHandle == resourceHandle) {
2377 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2378 return OC_STACK_INVALID_PARAM;
2381 // Use the handle to find the resource in the resource linked list
2382 resource = findResource((OCResource *) collectionHandle);
2384 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2385 return OC_STACK_INVALID_PARAM;
2388 // Look for an open slot to add add the child resource.
2389 // If found, add it and return success
2390 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2391 if (!resource->rsrcResources[i]) {
2392 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2393 OC_LOG(INFO, TAG, PCF("resource bound"));
2398 #ifdef WITH_PRESENCE
2399 if(presenceResource.handle)
2401 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2402 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2406 // Unable to add resourceHandle, so return error
2407 return OC_STACK_ERROR;
2411 * Remove a resource from a collection resource.
2413 * @param collectionHandle - handle to the collection resource
2414 * @param resourceHandle - handle to resource to be added to the collection resource
2417 * OC_STACK_OK - no errors
2418 * OC_STACK_ERROR - stack process error
2419 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2421 OCStackResult OCUnBindResource(
2422 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2423 OCResource *resource;
2426 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2428 // Validate parameters
2429 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2430 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2431 // Container cannot contain itself
2432 if (collectionHandle == resourceHandle) {
2433 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2434 return OC_STACK_INVALID_PARAM;
2437 // Use the handle to find the resource in the resource linked list
2438 resource = findResource((OCResource *) collectionHandle);
2440 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2441 return OC_STACK_INVALID_PARAM;
2444 // Look for an open slot to add add the child resource.
2445 // If found, add it and return success
2446 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2447 if (resourceHandle == resource->rsrcResources[i]) {
2448 resource->rsrcResources[i] = (OCResource *) NULL;
2449 OC_LOG(INFO, TAG, PCF("resource unbound"));
2454 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2456 #ifdef WITH_PRESENCE
2457 if(presenceResource.handle)
2459 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2460 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2464 // Unable to add resourceHandle, so return error
2465 return OC_STACK_ERROR;
2468 OCStackResult BindResourceTypeToResource(OCResource* resource,
2469 const char *resourceTypeName)
2471 OCResourceType *pointer = NULL;
2474 OCStackResult result = OC_STACK_ERROR;
2476 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2478 // Validate parameters
2479 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2480 // TODO: Does resource attribute resentation really have to be maintained in stack?
2481 // Is it presented during resource discovery?
2483 //TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2485 // Create the resourcetype and insert it into the resource list
2486 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2491 // Set the resourceTypeName
2492 size = strlen(resourceTypeName) + 1;
2493 str = (char *) OCMalloc(size);
2497 strncpy(str, resourceTypeName, size);
2498 pointer->resourcetypename = str;
2500 insertResourceType(resource, pointer);
2501 result = OC_STACK_OK;
2503 exit: if (result != OC_STACK_OK) {
2511 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2512 const char *resourceInterfaceName)
2514 OCResourceInterface *pointer = NULL;
2517 OCStackResult result = OC_STACK_ERROR;
2519 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2521 // Validate parameters
2522 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2524 //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2526 // Create the resourceinterface and insert it into the resource list
2527 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2532 // Set the resourceinterface name
2533 size = strlen(resourceInterfaceName) + 1;
2534 str = (char *) OCMalloc(size);
2538 strncpy(str, resourceInterfaceName, size);
2539 pointer->name = str;
2541 // Bind the resourceinterface to the resource
2542 insertResourceInterface(resource, pointer);
2544 result = OC_STACK_OK;
2546 exit: if (result != OC_STACK_OK) {
2555 * Bind a resourcetype to a resource.
2557 * @param handle - handle to the resource
2558 * @param resourceTypeName - name of resource type. Example: "core.led"
2561 * OC_STACK_OK - no errors
2562 * OC_STACK_ERROR - stack process error
2564 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2565 const char *resourceTypeName) {
2567 OCStackResult result = OC_STACK_ERROR;
2568 OCResource *resource;
2570 // Make sure resource exists
2571 resource = findResource((OCResource *) handle);
2573 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2574 return OC_STACK_ERROR;
2577 // call internal function
2578 result = BindResourceTypeToResource(resource, resourceTypeName);
2580 #ifdef WITH_PRESENCE
2581 if(presenceResource.handle)
2583 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2584 SendPresenceNotification(resource->rsrcType);
2592 * Bind a resourceinterface to a resource.
2594 * @param handle - handle to the resource
2595 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2598 * OC_STACK_OK - no errors
2599 * OC_STACK_ERROR - stack process error
2602 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2603 const char *resourceInterfaceName) {
2605 OCStackResult result = OC_STACK_ERROR;
2606 OCResource *resource;
2608 // Make sure resource exists
2609 resource = findResource((OCResource *) handle);
2611 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2612 return OC_STACK_ERROR;
2615 // call internal function
2616 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2618 #ifdef WITH_PRESENCE
2619 if(presenceResource.handle)
2621 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2622 SendPresenceNotification(resource->rsrcType);
2630 * Get the number of resources that have been created in the stack.
2632 * @param numResources - pointer to count variable
2635 * OC_STACK_OK - no errors
2636 * OC_STACK_ERROR - stack process error
2639 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2640 OCResource *pointer = headResource;
2642 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2643 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2646 *numResources = *numResources + 1;
2647 pointer = pointer->next;
2653 * Get a resource handle by index.
2655 * @param index - index of resource, 0 to Count - 1
2658 * Resource handle - if found
2659 * NULL - if not found
2661 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2662 OCResource *pointer = headResource;
2665 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2667 // Iterate through the list
2668 while ((i < index) && pointer) {
2670 pointer = pointer->next;
2672 return (OCResourceHandle) pointer;
2676 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2679 * @param handle - handle of resource to be deleted
2682 * OC_STACK_OK - no errors
2683 * OC_STACK_ERROR - stack process error
2684 * OC_STACK_NO_RESOURCE - resource not found
2685 * OC_STACK_INVALID_PARAM - invalid param
2687 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2688 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2691 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2692 return OC_STACK_INVALID_PARAM;
2695 OCResource *resource = findResource((OCResource *) handle);
2696 if (resource == NULL) {
2697 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2698 return OC_STACK_NO_RESOURCE;
2701 if (deleteResource((OCResource *) handle) == 0) {
2702 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2703 return OC_STACK_ERROR;
2710 * Get the URI of the resource specified by handle.
2712 * @param handle - handle of resource
2714 * URI string - if resource found
2715 * NULL - resource not found
2717 const char *OCGetResourceUri(OCResourceHandle handle) {
2718 OCResource *resource;
2719 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2721 resource = findResource((OCResource *) handle);
2723 return resource->uri;
2725 return (const char *) NULL;
2729 * Get the properties of the resource specified by handle.
2730 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2731 * for the resource by the stack.
2733 * @param handle - handle of resource
2735 * property bitmap - if resource found
2736 * NULL - resource not found
2738 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2739 OCResource *resource;
2740 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2742 resource = findResource((OCResource *) handle);
2744 return resource->resourceProperties;
2750 * Get the number of resource types of the resource.
2752 * @param handle - handle of resource
2753 * @param numResourceTypes - pointer to count variable
2756 * OC_STACK_OK - no errors
2757 * OC_STACK_ERROR - stack process error
2759 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2760 uint8_t *numResourceTypes) {
2761 OCResource *resource;
2762 OCResourceType *pointer;
2764 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2765 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2766 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2768 *numResourceTypes = 0;
2770 resource = findResource((OCResource *) handle);
2772 pointer = resource->rsrcType;
2774 *numResourceTypes = *numResourceTypes + 1;
2775 pointer = pointer->next;
2782 * Get name of resource type of the resource.
2784 * @param handle - handle of resource
2785 * @param index - index of resource, 0 to Count - 1
2788 * resource type name - if resource found
2789 * NULL - resource not found
2791 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2792 OCResourceType *resourceType;
2794 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2796 resourceType = findResourceTypeAtIndex(handle, index);
2798 return resourceType->resourcetypename;
2800 return (const char *) NULL;
2806 * Get the number of resource interfaces of the resource.
2808 * @param handle - handle of resource
2809 * @param numResources - pointer to count variable
2812 * OC_STACK_OK - no errors
2813 * OC_STACK_ERROR - stack process error
2815 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2816 uint8_t *numResourceInterfaces) {
2817 OCResourceInterface *pointer;
2818 OCResource *resource;
2820 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2822 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2823 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2825 *numResourceInterfaces = 0;
2826 resource = findResource((OCResource *) handle);
2828 pointer = resource->rsrcInterface;
2830 *numResourceInterfaces = *numResourceInterfaces + 1;
2831 pointer = pointer->next;
2838 * Get name of resource interface of the resource.
2840 * @param handle - handle of resource
2841 * @param index - index of resource, 0 to Count - 1
2844 * resource interface name - if resource found
2845 * NULL - resource not found
2847 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2848 OCResourceInterface *resourceInterface;
2850 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2852 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2853 if (resourceInterface) {
2854 return resourceInterface->name;
2856 return (const char *) NULL;
2860 * Get resource handle from the collection resource by index.
2862 * @param collectionHandle - handle of collection resource
2863 * @param index - index of contained resource, 0 to Count - 1
2866 * handle to resource - if resource found
2867 * NULL - resource not found
2869 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2871 OCResource *resource;
2873 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2875 if (index >= MAX_CONTAINED_RESOURCES) {
2879 resource = findResource((OCResource *) collectionHandle);
2884 return resource->rsrcResources[index];
2888 * Bind an entity handler to the resource.
2890 * @param handle - handle to the resource that the contained resource is to be bound
2891 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2893 * OC_STACK_OK - no errors
2894 * OC_STACK_ERROR - stack process error
2896 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2897 OCEntityHandler entityHandler) {
2898 OCResource *resource;
2900 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2902 // Validate parameters
2903 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2904 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2906 // Use the handle to find the resource in the resource linked list
2907 resource = findResource((OCResource *)handle);
2909 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2910 return OC_STACK_ERROR;
2914 resource->entityHandler = entityHandler;
2916 #ifdef WITH_PRESENCE
2917 if(presenceResource.handle)
2919 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2920 SendPresenceNotification(resource->rsrcType);
2928 * Get the entity handler for a resource.
2930 * @param handle - handle of resource
2933 * entity handler - if resource found
2934 * NULL - resource not found
2936 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2937 OCResource *resource;
2939 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2941 // Use the handle to find the resource in the resource linked list
2942 resource = findResource((OCResource *)handle);
2944 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2949 return resource->entityHandler;
2952 void incrementSequenceNumber(OCResource * resPtr)
2954 // Increment the sequence number
2955 resPtr->sequenceNum += 1;
2956 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2958 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2964 * Notify Presence subscribers that a resource has been modified
2966 * @param resourceType - Handle to the resourceType linked list of resource
2967 * that was modified.
2968 * @param qos - Quality Of Service
2971 #ifdef WITH_PRESENCE
2972 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2974 OCResource *resPtr = NULL;
2975 OCStackResult result;
2976 OCMethod method = OC_REST_PRESENCE;
2977 uint32_t maxAge = 0;
2978 resPtr = findResource((OCResource *) presenceResource.handle);
2981 return OC_STACK_NO_RESOURCE;
2983 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2985 maxAge = presenceResource.presenceTTL;
2992 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2996 #endif // WITH_PRESENCE
2998 * Notify observers that an observed value has changed.
3000 * @param handle - handle of resource
3003 * OC_STACK_OK - no errors
3004 * OC_STACK_NO_RESOURCE - invalid resource handle
3005 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
3007 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
3009 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3011 OCResource *resPtr = NULL;
3012 OCStackResult result;
3013 OCMethod method = OC_REST_NOMETHOD;
3014 uint32_t maxAge = 0;
3016 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3017 #ifdef WITH_PRESENCE
3018 if(handle == presenceResource.handle)
3022 #endif // WITH_PRESENCE
3023 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3025 // Verify that the resource exists
3026 resPtr = findResource ((OCResource *) handle);
3029 return OC_STACK_NO_RESOURCE;
3033 //only increment in the case of regular observing (not presence)
3034 incrementSequenceNumber(resPtr);
3035 method = OC_REST_OBSERVE;
3036 maxAge = MAX_OBSERVE_AGE;
3037 #ifdef WITH_PRESENCE
3038 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
3040 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3047 OCNotifyListOfObservers (OCResourceHandle handle,
3048 OCObservationId *obsIdList,
3049 uint8_t numberOfIds,
3050 unsigned char *notificationJSONPayload,
3051 OCQualityOfService qos)
3053 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3055 OCResource *resPtr = NULL;
3056 //TODO: we should allow the server to define this
3057 uint32_t maxAge = MAX_OBSERVE_AGE;
3059 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3060 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3061 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3063 // Verify that the resource exists
3064 resPtr = findResource ((OCResource *) handle);
3065 if (NULL == resPtr || myStackMode == OC_CLIENT)
3067 return OC_STACK_NO_RESOURCE;
3071 incrementSequenceNumber(resPtr);
3073 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3074 notificationJSONPayload, maxAge, qos));
3078 * Send a response to a request.
3079 * The response can be a regular, slow, or block (i.e. a response that
3080 * is too large to be sent in a single PDU and must span multiple transmissions)
3082 * @param response - pointer to structure that contains response parameters
3085 * OC_STACK_OK - No errors; Success
3086 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
3087 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
3088 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
3089 * persistent response buffer is necessary
3091 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3093 OCStackResult result = OC_STACK_ERROR;
3094 OCServerRequest *serverRequest = NULL;
3096 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3098 // Validate input parameters
3099 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3100 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3102 // TODO: Placeholder for creating a response entry when implementing
3103 // block transfer feature
3105 // If a response payload is present, check if block transfer is required
3106 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3107 (const char *)ehResponse->payload, ehResponse->payloadSize))
3109 OC_LOG(INFO, TAG, PCF("Block transfer required"));
3111 // Persistent response buffer is needed for block transfer
3112 if (!ehResponse->persistentBufferFlag)
3114 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3115 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3117 // TODO: Placeholder for block transfer handling
3118 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3119 // when implementing the block transfer feature
3124 // Get pointer to request info
3125 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3128 result = serverRequest->ehResponseHandler(ehResponse);
3135 * Cancel a response. Applies to a block response
3137 * @param responseHandle - response handle set by stack in OCServerResponse after
3138 * OCDoResponse is called
3141 * OC_STACK_OK - No errors; Success
3142 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
3144 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
3146 OCStackResult result = OC_STACK_NOTIMPL;
3148 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
3150 // TODO: validate response handle
3155 //-----------------------------------------------------------------------------
3156 // Private internal function definitions
3157 //-----------------------------------------------------------------------------
3159 * Generate handle of OCDoResource invocation for callback management.
3161 static OCDoHandle GenerateInvocationHandle()
3163 OCDoHandle handle = NULL;
3164 // Generate token here, it will be deleted when the transaction is deleted
3165 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3168 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3173 #ifdef WITH_PRESENCE
3174 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3175 OCResourceProperty resourceProperties, uint8_t enable)
3177 if (resourceProperties
3178 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
3179 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3180 return OC_STACK_INVALID_PARAM;
3184 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3188 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3195 * Initialize resource data structures, variables, etc.
3197 OCStackResult initResources() {
3198 OCStackResult result = OC_STACK_OK;
3199 // Init application resource vars
3200 headResource = NULL;
3201 // Init Virtual Resources
3202 #ifdef WITH_PRESENCE
3203 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3204 //presenceResource.token = OCGenerateCoAPToken();
3205 result = OCCreateResource(&presenceResource.handle,
3206 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3211 //make resource inactive
3212 result = OCChangeResourceProperty(
3213 &(((OCResource *) presenceResource.handle)->resourceProperties),
3220 * Add a resource to the end of the linked list of resources.
3222 * @param resource - resource to be added
3224 void insertResource(OCResource *resource) {
3225 OCResource *pointer;
3227 if (!headResource) {
3228 headResource = resource;
3230 pointer = headResource;
3232 while (pointer->next) {
3233 pointer = pointer->next;
3235 pointer->next = resource;
3237 resource->next = NULL;
3241 * Find a resource in the linked list of resources.
3243 * @param resource - resource to be found
3245 * NULL - resource not found
3246 * pointer to resource - pointer to resource that was found in the linked list
3248 OCResource *findResource(OCResource *resource) {
3249 OCResource *pointer = headResource;
3252 if (pointer == resource) {
3255 pointer = pointer->next;
3260 void deleteAllResources()
3262 OCResource *pointer = headResource;
3267 temp = pointer->next;
3268 #ifdef WITH_PRESENCE
3269 if(pointer != (OCResource *) presenceResource.handle)
3271 #endif // WITH_PRESENCE
3272 deleteResource(pointer);
3273 #ifdef WITH_PRESENCE
3275 #endif // WITH_PRESENCE
3279 #ifdef WITH_PRESENCE
3280 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3281 // presence notification attributed to their deletion to be processed.
3282 deleteResource((OCResource *) presenceResource.handle);
3283 #endif // WITH_PRESENCE
3287 * Delete the resource from the linked list.
3289 * @param resource - resource to be deleted
3294 int deleteResource(OCResource *resource) {
3295 OCResource *prev = NULL;
3298 temp = headResource;
3300 if (temp == resource) {
3301 // Invalidate all Resource Properties.
3302 resource->resourceProperties = (OCResourceProperty) 0;
3303 #ifdef WITH_PRESENCE
3304 if(resource != (OCResource *) presenceResource.handle)
3306 #endif // WITH_PRESENCE
3307 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3308 #ifdef WITH_PRESENCE
3311 if(presenceResource.handle)
3313 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3314 if(resource != (OCResource *) presenceResource.handle)
3316 SendPresenceNotification(resource->rsrcType);
3320 SendPresenceNotification(NULL);
3325 if (temp == headResource) {
3326 headResource = temp->next;
3328 prev->next = temp->next;
3331 deleteResourceElements(temp);
3344 * Delete all of the dynamically allocated elements that were created for the resource.
3346 * @param resource - specified resource
3348 void deleteResourceElements(OCResource *resource) {
3354 OCFree(resource->uri);
3356 // Delete resourcetype linked list
3357 deleteResourceType(resource->rsrcType);
3359 // Delete resourceinterface linked list
3360 deleteResourceInterface(resource->rsrcInterface);
3364 * Delete all of the dynamically allocated elements that were created for the resource type.
3366 * @param resourceType - specified resource type
3368 void deleteResourceType(OCResourceType *resourceType) {
3369 OCResourceType *pointer = resourceType;
3370 OCResourceType *next;
3373 next = pointer->next;
3374 OCFree(pointer->resourcetypename);
3381 * Delete all of the dynamically allocated elements that were created for the resource interface.
3383 * @param resourceInterface - specified resource interface
3385 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3386 OCResourceInterface *pointer = resourceInterface;
3387 OCResourceInterface *next;
3390 next = pointer->next;
3391 OCFree(pointer->name);
3398 * Insert a resource type into a resource's resource type linked list.
3400 * @param resource - resource where resource type is to be inserted
3401 * @param resourceType - resource type to be inserted
3403 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3404 OCResourceType *pointer;
3406 if (resource && !resource->rsrcType) {
3407 resource->rsrcType = resourceType;
3411 pointer = resource->rsrcType;
3415 pointer = resourceType;
3417 while (pointer->next) {
3418 pointer = pointer->next;
3420 pointer->next = resourceType;
3422 resourceType->next = NULL;
3426 * Get a resource type at the specified index within a resource.
3428 * @param handle - handle of resource
3429 * @param index - index of resource type
3432 * resourcetype - if found
3435 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3436 OCResource *resource;
3437 OCResourceType *pointer;
3440 // Find the specified resource
3441 resource = findResource((OCResource *) handle);
3446 // Make sure a resource has a resourcetype
3447 if (!resource->rsrcType) {
3451 // Iterate through the list
3452 pointer = resource->rsrcType;
3454 while ((i < index) && pointer) {
3456 pointer = pointer->next;
3462 * Finds a resource type in an OCResourceType link-list.
3464 * @param resourceTypeList - the link-list to be searched through
3465 * @param resourceTypeName - the key to search for
3468 * resourceType that matches the key (ie. resourceTypeName)
3469 * NULL - either an invalid parameter or this function was unable to find the key.
3471 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3473 if(resourceTypeList && resourceTypeName)
3475 OCResourceType * rtPointer = resourceTypeList;
3476 while(resourceTypeName && rtPointer)
3478 if(rtPointer->resourcetypename &&
3479 strcmp(resourceTypeName, (const char *)
3480 (rtPointer->resourcetypename)) == 0)
3484 rtPointer = rtPointer->next;
3491 * Insert a resource interface into a resource's resource interface linked list.
3493 * @param resource - resource where resource interface is to be inserted
3494 * @param resourceInterface - resource interface to be inserted
3496 void insertResourceInterface(OCResource *resource,
3497 OCResourceInterface *resourceInterface) {
3498 OCResourceInterface *pointer;
3500 if (!resource->rsrcInterface) {
3501 resource->rsrcInterface = resourceInterface;
3503 pointer = resource->rsrcInterface;
3504 while (pointer->next) {
3505 pointer = pointer->next;
3507 pointer->next = resourceInterface;
3509 resourceInterface->next = NULL;
3513 * Get a resource interface at the specified index within a resource.
3515 * @param handle - handle of resource
3516 * @param index - index of resource interface
3519 * resourceinterface - if found
3522 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3524 OCResource *resource;
3525 OCResourceInterface *pointer;
3528 // Find the specified resource
3529 resource = findResource((OCResource *) handle);
3534 // Make sure a resource has a resourceinterface
3535 if (!resource->rsrcInterface) {
3539 // Iterate through the list
3540 pointer = resource->rsrcInterface;
3542 while ((i < index) && pointer) {
3544 pointer = pointer->next;
3550 * Determine if a request/response must be sent in a block transfer because it is too large to be
3551 * sent in a single PDU. This function can be used for either a request or a response
3553 * @param request - NULL or pointer to request
3554 * @param response - NULL or pointer to response
3555 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3556 * the length of the request/response
3559 * 0 - packet transfer NOT required (i.e. normal request/response)
3560 * 1 - packet transfer required (i.e. block transfer needed)
3562 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3566 // Determine if we are checking a request or a response
3569 // If size is greater than 0, use it for the request size value, otherwise
3570 // assume request is null terminated and use strlen for size value
3571 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3578 // If size is greater than 0, use it for the response size value, otherwise
3579 // assume response is null terminated and use strlen for size value
3580 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3589 * Retrieves a resource type based upon a query ontains only just one
3590 * resource attribute (and that has to be of type "rt").
3592 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3593 * before passing in.
3595 * @param query - The quert part of the URI
3596 * @param resourceType - The resource type to be populated; pass by reference.
3599 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3600 * OC_STACK_OK - Success
3602 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3606 return OC_STACK_INVALID_PARAM;
3609 OCStackResult result = OC_STACK_ERROR;
3611 if(strncmp(query, "rt=", 3) == 0)
3613 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3616 result = OC_STACK_NO_MEMORY;
3619 strcpy((char *)*resourceType, ((const char *)&query[3]));
3620 result = OC_STACK_OK;
3626 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3630 return OC_STACK_INVALID_URI;
3632 if(!query || !newURI)
3634 return OC_STACK_INVALID_PARAM;
3636 char * leftToken = NULL;
3637 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3642 strcpy(tempURI, uri);
3644 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3646 //TODO-CA: This could be simplified. Clean up required.
3647 while(leftToken != NULL)
3649 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3651 *query = (unsigned char *) OCMalloc(strlen(leftToken) + 1);
3657 strcpy((char *)*query, ((const char *)&leftToken[0]));
3660 leftToken = strtok_r(NULL, "?", &strTokPtr);
3668 return OC_STACK_NO_MEMORY;
3671 const ServerID OCGetServerInstanceID(void)
3673 static bool generated = false;
3674 static ServerID sid;
3681 sid = OCGetRandom();
3686 const char* OCGetServerInstanceIDString(void)
3688 // max printed length of a base 10
3689 // uint32 is 10 characters, so 11 includes null.
3690 // This will change as the representation gets switched
3692 static char buffer[11];
3693 int n = sprintf(buffer, "%u", OCGetServerInstanceID());
3702 /// Retrieve the IPv4 address embedded inside OCDev address data structure
3703 int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
3704 uint8_t *c, uint8_t *d )
3706 if ( !ipAddr || !a || !b || !c || !d ) {
3707 OC_LOG(FATAL, TAG, "Invalid argument");
3708 return OC_STACK_INVALID_PARAM;
3711 *a = ipAddr->addr[0];
3712 *b = ipAddr->addr[1];
3713 *c = ipAddr->addr[2];
3714 *d = ipAddr->addr[3];
3720 /// Retrieve the IPv4 address embedded inside OCDev address data structure
3721 int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
3723 if ( !ipAddr || !port ) {
3724 OC_LOG(FATAL, TAG, "Invalid argument");
3725 return OC_STACK_INVALID_PARAM;
3728 *port = *((uint16_t*)&ipAddr->addr[4]);