db-sql.c revision f968e62caa52a8924bd05ebf76ff515b5c18e17b
2N/A/* Copyright (C) 2003-2004 Timo Sirainen */
2N/A
2N/A#include "common.h"
2N/A
2N/A#if defined(PASSDB_SQL) || defined(USERDB_SQL)
2N/A
2N/A#include "settings.h"
2N/A#include "auth-request.h"
2N/A#include "db-sql.h"
2N/A
2N/A#include <stddef.h>
2N/A#include <stdlib.h>
2N/A
2N/A#define DEF_STR(name) DEF_STRUCT_STR(name, sql_settings)
2N/A#define DEF_INT(name) DEF_STRUCT_INT(name, sql_settings)
2N/A#define DEF_BOOL(name) DEF_STRUCT_BOOL(name, sql_settings)
2N/A
2N/Astatic struct setting_def setting_defs[] = {
2N/A DEF_STR(driver),
2N/A DEF_STR(connect),
2N/A DEF_STR(password_query),
2N/A DEF_STR(user_query),
2N/A DEF_STR(update_query),
2N/A DEF_STR(default_pass_scheme),
2N/A
2N/A { 0, NULL, 0 }
2N/A};
2N/A
2N/Astruct sql_settings default_sql_settings = {
2N/A MEMBER(driver) NULL,
2N/A MEMBER(connect) NULL,
2N/A MEMBER(password_query) "SELECT password FROM users WHERE userid = '%u'",
2N/A MEMBER(user_query) "SELECT home, uid, gid FROM users WHERE userid = '%u'",
2N/A MEMBER(update_query) "UPDATE users SET password = '%w' WHERE userid = '%u'",
2N/A MEMBER(default_pass_scheme) "PLAIN-MD5"
2N/A};
2N/A
2N/Astatic struct sql_connection *connections = NULL;
2N/A
2N/Astatic struct sql_connection *sql_conn_find(const char *config_path)
2N/A{
2N/A struct sql_connection *conn;
2N/A
2N/A for (conn = connections; conn != NULL; conn = conn->next) {
2N/A if (strcmp(conn->config_path, config_path) == 0)
2N/A return conn;
2N/A }
2N/A
2N/A return NULL;
2N/A}
2N/A
2N/Astatic const char *parse_setting(const char *key, const char *value,
struct sql_connection *conn)
{
return parse_setting_from_defs(conn->pool, setting_defs,
&conn->set, key, value);
}
struct sql_connection *db_sql_init(const char *config_path)
{
struct sql_connection *conn;
pool_t pool;
conn = sql_conn_find(config_path);
if (conn != NULL) {
conn->refcount++;
return conn;
}
if (*config_path == '\0')
i_fatal("sql: Configuration file path not given");
pool = pool_alloconly_create("sql_connection", 1024);
conn = p_new(pool, struct sql_connection, 1);
conn->pool = pool;
conn->refcount = 1;
conn->config_path = p_strdup(pool, config_path);
conn->set = default_sql_settings;
if (!settings_read(config_path, NULL, parse_setting,
null_settings_section_callback, conn))
exit(FATAL_DEFAULT);
if (conn->set.driver == NULL) {
i_fatal("sql: driver not set in configuration file %s",
config_path);
}
if (conn->set.connect == NULL) {
i_fatal("sql: connect string not set in configuration file %s",
config_path);
}
conn->db = sql_init(conn->set.driver, conn->set.connect);
conn->next = connections;
connections = conn;
return conn;
}
void db_sql_unref(struct sql_connection **_conn)
{
struct sql_connection *conn = *_conn;
*_conn = NULL;
if (--conn->refcount > 0)
return;
sql_deinit(&conn->db);
pool_unref(conn->pool);
}
#endif