Add a tool for accessing encrypted database
[platform/core/security/key-manager.git] / tools / ckm_db_tool / ckm-logic-ext.cpp
1 /*
2  *  Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License
15  */
16 /*
17  * @file       ckm-logic-ext.cpp
18  * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
19  * @version    1.0
20  */
21
22 #include <ckm-logic-ext.h>
23 #include <db-crypto-ext.h>
24
25 namespace CKM {
26
27 DB::SqlConnection::Output CKMLogicExt::Execute(uid_t user, const std::string& cmd) {
28     if(user < 5000 && !m_systemDbUnlocked) {
29         if(CKM_API_SUCCESS != unlockSystemDB())
30             ThrowErr(Exc::DatabaseLocked, "can not unlock system database");
31         m_systemDbUnlocked = true;
32     }
33
34     DB::SqlConnection::Output output;
35
36     /*
37      * We need to access to DB::Crypto::m_connection to call Execute() on it. We don't want to mess
38      * with DB::Crypto too much so adding a friend and extending public interface was not an option.
39      * That's why we need a derived class DB::CryptoExt. m_userDataMap must be left unchanged after
40      * this operation but DB::Crypto can't be copied. According to C++ standard static casting
41      * DB::Crypto pointer to DB::CryptoExt pointer is UB. Therefore DB::Crypto is temporarily moved
42      * into DB::CryptoExt and moved back to m_userDataMap after the call to Execute().
43      */
44     DB::CryptoExt db(std::move(m_userDataMap[user].database));
45     try {
46         output = db.Execute(cmd);
47         m_userDataMap[user].database = std::move(*static_cast<DB::Crypto*>(&db));
48         return output;
49     } catch (const DB::SqlConnection::Exception::Base& e) {
50         m_userDataMap[user].database = std::move(*static_cast<DB::Crypto*>(&db));
51         throw;
52     }
53 }
54
55 } // namespace CKM
56
57