Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#include "dgrid_config.h"
#include "dgrid_logger.h"
#include "dgrid_auth.h"
#include <experimental/random>
#include <openssl/md5.h>
#if OPENSSL_VERSION_MAJOR >= 3
#include <openssl/evp.h>
#endif
#include "libpq/libpq-fe.h"
 
namespace DGrid {
namespace SQL {
 
pg_conn*   conn = nullptr;
std::mutex conn_mutex;
 
bool openDBconnection()
{
    std::lock_guard<std::mutex> lock(conn_mutex);
    if(conn)
        return true;
 
    std::string dbhost = Config::instance()->get("dbhost");
    std::string dbport = Config::instance()->get("dbport", "5432");
    std::string dbname = Config::instance()->get("dbname");
    std::string dbuser = Config::instance()->get("dbuser");
    std::string dbpass = Config::instance()->get("dbpass");
    if(dbhost.empty() || dbname.empty() || dbuser.empty() || dbpass.empty())
    {
        writeLog(LOG_ERR, "DB connection params missed in config");
        return false;
    }
 
    conn = PQsetdbLogin(dbhost.c_str(), dbport.c_str(), nullptr, nullptr, dbname.c_str(), dbuser.c_str(), dbpass.c_str());
    if (PQstatus(conn) != CONNECTION_OK && PQsetnonblocking(conn, 1) != 0)
    {
        std::string err(PQerrorMessage(conn));
        PQfinish(conn);
        conn = nullptr;
        writeLog(LOG_ERR, "DB connection error: %s", err.c_str());
        return false;
    }
    return true;
}
 
void cleanupDBconnection()
{
    std::lock_guard<std::mutex> lock(conn_mutex);
    if(conn) {
        PQfinish(conn);
        conn = nullptr;
    }
}
 
std::string quote_string(std::string s)
{
    size_t pos=0;
    while((pos = s.find_first_of("\'", pos)) != std::string::npos) {
        s.replace(pos, 1, "\'\'");
        pos+=2;
    }
    return std::move(s);
}
 
bool exec_query(const std::string& query, SQL_result* result)
{
    writeLog(LOG_DEBUG, "query: %s", query.c_str());
 
    if(!openDBconnection())
        return false;
    bool r = true;
    if(result)
        result->clear();
    conn_mutex.lock();
    PQsendQuery(conn, query.c_str());
    while (auto res = PQgetResult(conn))
    {
        const ExecStatusType pq_res = PQresultStatus(res);
        if (pq_res == PGRES_TUPLES_OK)
        {
            if(PQntuples(res) > 0 && result != nullptr) {
                const int rows = PQntuples(res);
                result->resize(rows);
                for(int row=0; row<rows; row++) {
                    const int nf = PQnfields(res);
                    for(int i=0; i<nf; i++) {
                        std::string field = PQfname(res, i);
                        std::string value = PQgetvalue(res, row, i);
                        (*result)[row].emplace(field, value);
                    }
                }
            }
        } else if (pq_res != PGRES_COMMAND_OK) {
            std::string err(PQerrorMessage(conn));
            writeLog(LOG_ERR, "SQL error: %s", err.c_str());
            r = false;
        }
        PQclear(res);
    }
    conn_mutex.unlock();
    writeLog(LOG_DEBUG, "exec_query result = %d", r ? 1 : 0);
    return r;
}
 
bool read_user(const std::string& username, std::string& hash, std::string& salt)
{
    std::string sql = "SELECT hash,salt FROM dgrid.users WHERE username='" + quote_string(username) + "'";
    SQL_result res;
    if(!exec_query(sql, &res) || res.empty())
        return false;
 
    hash = res[0]["hash"];
    salt = res[0]["salt"];
    return true;
}
 
bool save_user(const std::string username, const std::string& hash, const std::string& salt)
{
    std::string sql = "INSERT INTO dgrid.users (username, hash, salt) \
            VALUES ('" + quote_string(username) + "', '" + hash + "', '" + salt + "') \
                ON CONFLICT(username) DO \
            UPDATE SET (hash,salt,ts_update) = ('" + hash + "', '" + salt + "', now())";
 
    return exec_query(sql);
}
 
bool drop_user(const std::string username)
{
    std::string sql = "DELETE FROM dgrid.users WHERE username='" + SQL::quote_string(username) + "'";
    return exec_query(sql);
}
 
} // namespace SQL
 
std::string generate_salt()
{
    const int salt_size = 16;
    std::vector<char> salt(salt_size, 0);
    for(int i=0; i<salt_size; i++) {
        salt[i] = std::experimental::randint(0,0xF) << 4 | std::experimental::randint(0,0xF);
    }
    return raw_to_hexstring(salt);
}
 
std::string calc_passwd_hash(const std::string& user, const std::string& passwd, const std::string& salt)
{
    std::string md5_str;
    std::string s = "DGRID+" + salt + "&" + user + "-" + passwd;
    unsigned char data_md5[MD5_DIGEST_LENGTH];
#if OPENSSL_VERSION_MAJOR >= 3
    EVP_Q_digest(NULL, "MD5", NULL, s.c_str(), s.length(), data_md5, NULL);
#else
    MD5_CTX ctx;
    MD5_Init(&ctx);
    MD5_Update(&ctx,  s.c_str(), s.length());
    MD5_Final(data_md5, &ctx);
#endif
    return raw_to_hexstring(std::vector<char>((const char*)data_md5, (const char*)data_md5 + MD5_DIGEST_LENGTH));
}
 
bool checkUserPasswd(const std::string& user, const std::string& passwd, std::string& message)
{
    std::string db_hash;
    std::string salt;
    if(!DGrid::SQL::read_user(user, db_hash, salt)) {
        writeLog(LOG_ERR, "user not found: '%s'", user.c_str());
        return false;
    }
    std::string calc_hash = calc_passwd_hash(user, passwd, salt);
    if(calc_hash != db_hash) {
        writeLog(LOG_WARNING, "invalid password for user '%s'", user.c_str());
        return false;
    }
    return true;
}
 
DGridResult createUser(const std::string& user, const std::string& passwd, std::string& message)
{
    std::string salt = generate_salt();
    std::string hash = calc_passwd_hash(user, passwd, salt);
    if(!DGrid::SQL::save_user(user, hash, salt)) {
        return DGRID_FAIL;
    }
    writeLog(LOG_INFO, "User info updated: '%s'", user.c_str());
    return DGRID_OK;
}
 
DGridResult deleteUser(const std::string& user, std::string& message)
{
    if(!DGrid::SQL::drop_user(user)) {
        return DGRID_FAIL;
    }
    writeLog(LOG_INFO, "User deleted: '%s'", user.c_str());
    return DGRID_OK;
}
 
} // namespace DGrid