Use RAII idiom
[platform/core/appfw/rpc-port.git] / src / ac-internal.cc
index f2e728b..f8be409 100644 (file)
 namespace rpc_port {
 namespace internal {
 
-AccessController::~AccessController() {}
-
-void AccessController::AddPrivilege(const std::string& privilege) {
-  privileges_.push_back(privilege);
+void AccessController::AddPrivilege(std::string privilege) {
+  privileges_.push_back(std::move(privilege));
 }
 
 void AccessController::SetTrusted(const bool trusted) {
@@ -106,62 +104,47 @@ int AccessController::SetCache(const std::string& sender) {
   return -1;
 }
 
-AccessController::Cynara::Cynara() {
-  cynara_ = nullptr;
-  client_ = nullptr;
-  user_ = nullptr;
+AccessController::Cynara::Cynara()
+    : cynara_(nullptr, cynara_finish), client_(nullptr, std::free),
+    user_(nullptr, std::free) {
+  cynara* cynara_inst = nullptr;
 
-  if (cynara_initialize(&cynara_, NULL) != CYNARA_API_SUCCESS) {
+  if (cynara_initialize(&cynara_inst, NULL) != CYNARA_API_SUCCESS) {
     LOGE("cynara_initialize() is failed");
+  } else {
+    cynara_.reset(cynara_inst);
   }
 }
 
-AccessController::Cynara::~Cynara() {
-  if (client_)
-    free(client_);
-  if (user_)
-    free(user_);
-  if (cynara_)
-    cynara_finish(cynara_);
-}
-
 int AccessController::Cynara::FetchCredsFromDBus(GDBusConnection* connection,
     const char* sender) {
-  int ret;
-
-  if (client_) {
-    free(client_);
-     client_ = nullptr;
-  }
-
-  if (user_) {
-    free(user_);
-    user_ = nullptr;
-  }
-
-  ret = cynara_creds_gdbus_get_user(connection, sender, USER_METHOD_DEFAULT,
-                                    &user_);
+  char* user = nullptr;
+  int ret = cynara_creds_gdbus_get_user(connection, sender, USER_METHOD_DEFAULT,
+                                    &user);
   if (ret != CYNARA_API_SUCCESS) {
     LOGE("cynara_creds_gdbus_get_user() is failed : %d", ret);
     return -1;
   }
+  user_.reset(user);
 
+  char* client = nullptr;
   ret = cynara_creds_gdbus_get_client(connection, sender, CLIENT_METHOD_DEFAULT,
-                                      &client_);
+                                      &client);
   if (ret != CYNARA_API_SUCCESS) {
     LOGE("cynara_creds_gdbus_get_client() is failed : %d", ret);
     return -1;
   }
+  client_.reset(client);
 
-  LOGD("cred client : %s, cred user : %s", client_, user_);
+  LOGD("cred client : %s, cred user : %s", client_.get(), user_.get());
   return 0;
 }
 
 int AccessController::Cynara::Check(const std::string& privilege) const {
   LOGD("check privilege %s", privilege.c_str());
-  if (cynara_check(cynara_, client_, "", user_, privilege.c_str()) !=
-      CYNARA_API_ACCESS_ALLOWED) {
-    LOGD("cynara_check() is not allowed : %s", privilege.c_str());
+  if (cynara_check(cynara_.get(), client_.get(), "", user_.get(),
+      privilege.c_str()) != CYNARA_API_ACCESS_ALLOWED) {
+    LOGE("cynara_check() is not allowed : %s", privilege.c_str());
     return -1;
   }