ctstats/database.c

95 lines
3.4 KiB
C

/***************************************************************************
* Copyright (C) 07/2007 by Olaf Rempel *
* razzor@kopf-tisch.de *
* *
* 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; version 2 of the License *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <mysql/mysql.h>
#include "configfile.h"
#include "conntrack.h"
#include "database.h"
#include "hashtable.h"
#include "logging.h"
static MYSQL *dbh;
static void purge_hash_cb(const struct hash_entry *entry, void *privdata)
{
int long *now = (long *)privdata;
char query[256];
int len = snprintf(query, sizeof(query),
"INSERT INTO stats SET timestamp='%lu', srcip='%u', proto='%u', dport='%u', flags='%u', srcbytes='%llu', dstbytes='%llu', count='%u'",
*now, ntohl(entry->src_ip), entry->protonum, ntohs(entry->dst_port),
entry->flags, entry->src_bytes, entry->dst_bytes, entry->count);
if (mysql_real_query(dbh, query, len +1) != 0)
log_print(LOG_WARN, "purge_hash_cb: mysql_real_query(): %s", mysql_error(dbh));
}
int database_analyse(void)
{
struct hash_table *hash = conntrack_get_hash();
if (mysql_ping(dbh) != 0) {
log_print(LOG_WARN, "database_analyse: mysql_ping(): %s", mysql_error(dbh));
purge_hash(hash, NULL, NULL);
return 0;
}
long now = time(NULL);
purge_hash(hash, purge_hash_cb, (void *)&now);
return 0;
}
int database_init(void)
{
dbh = mysql_init(NULL);
if (dbh == NULL) {
log_print(LOG_ERROR, "database_init: mysql_init(): %s", mysql_error(dbh));
return -1;
}
const char *hostname = config_get_string("mysql", "hostname", NULL);
const char *username = config_get_string("mysql", "username", NULL);
const char *password = config_get_string("mysql", "password", NULL);
MYSQL *ret = mysql_real_connect(dbh, hostname, username, password, NULL, 0, NULL, 0);
if (ret != dbh) {
log_print(LOG_ERROR, "database_init: mysql_real_connect(): %s", mysql_error(dbh));
mysql_close(dbh);
return -1;
}
const char *database = config_get_string("mysql", "database", NULL);
if (mysql_select_db(dbh, database) != 0) {
log_print(LOG_ERROR, "database_init: mysql_select_db(): %s", mysql_error(dbh));
mysql_close(dbh);
return -1;
}
return 0;
}
int database_close(void)
{
mysql_close(dbh);
return 0;
}