#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
|