--- lbbs/src/database.c 2025/04/28 12:45:57 1.8 +++ lbbs/src/database.c 2025/11/21 02:28:15 1.24 @@ -1,29 +1,35 @@ -/*************************************************************************** - database.c - description - ------------------- - begin : Mon Oct 11 2004 - copyright : (C) 2004 by Leaflet - email : leaflet@leafok.com - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* + * database + * - configuration and function of DB connection + * + * Copyright (C) 2004-2025 Leaflet + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif #include "common.h" +#include "database.h" +#include "log.h" #include #include +#include -MYSQL * -db_open() +// Global declaration for database +char DB_ca_cert[FILE_PATH_LEN] = "conf/ca_cert.pem"; +char DB_host[DB_host_max_len + 1]; +char DB_username[DB_username_max_len + 1]; +char DB_password[DB_password_max_len + 1]; +char DB_database[DB_database_max_len + 1]; +char DB_timezone[DB_timezone_max_len + 1]; + +MYSQL *db_open() { - MYSQL *db; - char sql[1024]; + MYSQL *db = NULL; + unsigned int ssl_mode = SSL_MODE_VERIFY_CA; + char sql[SQL_BUFFER_LEN]; db = mysql_init(NULL); if (db == NULL) @@ -32,27 +38,41 @@ db_open() return NULL; } - db = mysql_real_connect(db, DB_host, DB_username, DB_password, DB_database, - 0, NULL, 0); - if (db == NULL) + if (mysql_ssl_set(db, NULL, NULL, DB_ca_cert, NULL, NULL) != 0) + { + log_error("mysql_ssl_set() error\n"); + return NULL; + } + + if (mysql_options(db, MYSQL_OPT_SSL_MODE, &ssl_mode) != 0) + { + log_error("mysql_options() error\n"); + return NULL; + } + + if (mysql_real_connect(db, DB_host, DB_username, DB_password, DB_database, + 0, NULL, 0) == NULL) { - log_error("mysql_connect() failed\n"); + log_error("mysql_real_connect() error: %s\n", mysql_error(db)); + mysql_close(db); return NULL; } - if (mysql_set_character_set(db, "gb2312") != 0) + if (mysql_set_character_set(db, "utf8") != 0) { - log_error("Set character set failed\n"); + log_error("Set character set error: %s\n", mysql_error(db)); + mysql_close(db); return NULL; } - sprintf(sql, - "SET time_zone = '%s'", - DB_timezone); + snprintf(sql, sizeof(sql), + "SET time_zone = '%s'", + DB_timezone); if (mysql_query(db, sql) != 0) { - log_error("Set timezone failed\n"); + log_error("Set timezone error: %s\n", mysql_error(db)); + mysql_close(db); return NULL; }