1 //******************************************************************
3 // Copyright 2015 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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 #include "cainterface.h"
24 #include "resourcemanager.h"
25 #include "credresource.h"
26 #include "policyengine.h"
27 #include "srmutility.h"
29 #include "oic_string.h"
30 #include "oic_malloc.h"
31 #include "securevirtualresourcetypes.h"
32 #include "secureresourcemanager.h"
37 //Request Callback handler
38 static CARequestCallback gRequestHandler = NULL;
39 //Response Callback handler
40 static CAResponseCallback gResponseHandler = NULL;
41 //Error Callback handler
42 static CAErrorCallback gErrorHandler = NULL;
43 //Persistent Storage callback handler for open/read/write/close/unlink
44 static OCPersistentStorage *gPersistentStorageHandler = NULL;
45 //Provisioning response callback
46 static SPResponseCallback gSPResponseHandler = NULL;
49 * A single global Policy Engine context will suffice as long
50 * as SRM is single-threaded.
52 PEContext_t g_policyEngineContext;
55 * @brief function to register provisoning API's response callback.
56 * @param respHandler response handler callback.
58 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
60 gSPResponseHandler = respHandler;
64 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
66 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
67 memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
68 sizeof(responseInfo.info));
69 responseInfo.info.payload = NULL;
70 responseInfo.result = CA_UNAUTHORIZED_REQ;
71 if (CA_STATUS_OK != CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
73 OC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
77 OC_LOG(INFO, TAG, "Succeed in sending response to a unauthorized request!");
82 void SRMSendResponse(SRMAccessResponse_t responseVal)
84 OC_LOG(INFO, TAG, "Sending response to remote device");
86 if (IsAccessGranted(responseVal) && gRequestHandler)
88 OC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
89 if (!g_policyEngineContext.amsMgrContext->endpoint ||
90 !g_policyEngineContext.amsMgrContext->requestInfo)
92 OC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
93 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
96 gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
97 g_policyEngineContext.amsMgrContext->requestInfo);
101 OC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
102 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
106 //Resting PE state to AWAITING_REQUEST
107 SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
112 * @brief Handle the request from the SRM.
113 * @param endPoint [IN] Endpoint object from which the response is received.
114 * @param requestInfo [IN] Information for the request.
117 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
119 OC_LOG(INFO, TAG, "Received request from remote device");
121 if (!endPoint || !requestInfo)
123 OC_LOG(ERROR, TAG, "Invalid arguments");
127 // Copy the subjectID
128 OicUuid_t subjectId = {.id = {0}};
129 memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
131 //Check the URI has the query and skip it before checking the permission
132 char *uri = strstr(requestInfo->info.resourceUri, "?");
136 //Skip query and pass the resource uri
137 position = uri - requestInfo->info.resourceUri;
141 position = strlen(requestInfo->info.resourceUri);
143 if (MAX_URI_LENGTH < position || 0 > position)
145 OC_LOG(ERROR, TAG, "Incorrect URI length");
148 SRMAccessResponse_t response = ACCESS_DENIED;
149 char newUri[MAX_URI_LENGTH + 1];
150 OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
152 //New request are only processed if the policy engine state is AWAITING_REQUEST.
153 if(AWAITING_REQUEST == g_policyEngineContext.state)
155 OC_LOG_V(INFO, TAG, "Processing request with uri, %s for method, %d",
156 requestInfo->info.resourceUri, requestInfo->method);
157 response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
158 GetPermissionFromCAMethod_t(requestInfo->method));
162 OC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
163 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
166 if (IsAccessGranted(response) && gRequestHandler)
168 return (gRequestHandler(endPoint, requestInfo));
171 // Form a 'Error', 'slow response' or 'access deny' response and send to peer
172 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
173 memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
174 responseInfo.info.payload = NULL;
176 VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
178 if(ACCESS_WAITING_FOR_AMS == response)
180 OC_LOG(INFO, TAG, "Sending slow response");
182 UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
183 responseInfo.result = CA_EMPTY;
184 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
189 * TODO Enhance this logic more to decide between
190 * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
191 * upon SRMAccessResponseReasonCode_t
193 OC_LOG(INFO, TAG, "Sending for regular response");
194 responseInfo.result = CA_UNAUTHORIZED_REQ;
197 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
199 OC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
203 responseInfo.result = CA_INTERNAL_SERVER_ERROR;
204 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
206 OC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
211 * @brief Handle the response from the SRM.
212 * @param endPoint [IN] The remote endpoint.
213 * @param responseInfo [IN] Response information from the endpoint.
216 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
218 OC_LOG(INFO, TAG, "Received response from remote device");
220 // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
221 // When token sent by CA response matches with token generated by provisioning request,
222 // gSPResponseHandler returns true and response is not sent to RI layer. In case
223 // gSPResponseHandler is null and isProvResponse is false response then the response is for
225 bool isProvResponse = false;
227 if (gSPResponseHandler)
229 isProvResponse = gSPResponseHandler(endPoint, responseInfo);
231 if (!isProvResponse && gResponseHandler)
233 gResponseHandler(endPoint, responseInfo);
239 * @brief Handle the error from the SRM.
240 * @param endPoint [IN] The remote endpoint.
241 * @param errorInfo [IN] Error information from the endpoint.
244 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
246 OC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
247 errorInfo->result, errorInfo->info.resourceUri);
250 gErrorHandler(endPoint, errorInfo);
256 * @brief Register request and response callbacks.
257 * Requests and responses are delivered in these callbacks.
258 * @param reqHandler [IN] Request handler callback ( for GET,PUT ..etc)
259 * @param respHandler [IN] Response handler callback.
261 * OC_STACK_OK - No errors; Success
262 * OC_STACK_INVALID_PARAM - invalid parameter
264 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
265 CAResponseCallback respHandler,
266 CAErrorCallback errHandler)
268 OC_LOG(INFO, TAG, "SRMRegisterHandler !!");
269 if( !reqHandler || !respHandler || !errHandler)
271 OC_LOG(ERROR, TAG, "Callback handlers are invalid");
272 return OC_STACK_INVALID_PARAM;
274 gRequestHandler = reqHandler;
275 gResponseHandler = respHandler;
276 gErrorHandler = errHandler;
279 #if defined(__WITH_DTLS__)
280 CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
282 CARegisterHandler(reqHandler, respHandler, errHandler);
283 #endif /* __WITH_DTLS__ */
288 * @brief Register Persistent storage callback.
289 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
291 * OC_STACK_OK - No errors; Success
292 * OC_STACK_INVALID_PARAM - Invalid parameter
294 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
296 OC_LOG(INFO, TAG, "SRMRegisterPersistentStorageHandler !!");
297 if(!persistentStorageHandler)
299 OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
300 return OC_STACK_INVALID_PARAM;
302 gPersistentStorageHandler = persistentStorageHandler;
307 * @brief Get Persistent storage handler pointer.
309 * The pointer to Persistent Storage callback handler
312 OCPersistentStorage* SRMGetPersistentStorageHandler()
314 return gPersistentStorageHandler;
319 * @brief Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
320 * @retval OC_STACK_OK for Success, otherwise some error value
322 OCStackResult SRMInitSecureResources()
324 // TODO: temporarily returning OC_STACK_OK every time until default
325 // behavior (for when SVR DB is missing) is settled.
326 InitSecureResources();
328 #if defined(__WITH_DTLS__)
329 CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
330 #endif // (__WITH_DTLS__)
336 * @brief Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
339 void SRMDeInitSecureResources()
341 DestroySecureResources();
345 * @brief Initialize Policy Engine.
346 * @return OC_STACK_OK for Success, otherwise some error value.
348 OCStackResult SRMInitPolicyEngine()
350 return InitPolicyEngine(&g_policyEngineContext);
354 * @brief Cleanup Policy Engine.
357 void SRMDeInitPolicyEngine()
359 return DeInitPolicyEngine(&g_policyEngineContext);