2021-02-06 12:45:46 +01:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"log"
|
|
|
|
)
|
|
|
|
|
2021-02-06 13:24:31 +01:00
|
|
|
const queryBadIpsPerJail = "SELECT j.name, (SELECT COUNT(1) FROM bips b WHERE j.name = b.jail) FROM jails j"
|
|
|
|
const queryBannedIpsPerJail = "SELECT j.name, (SELECT COUNT(1) FROM bans b WHERE j.name = b.jail) FROM jails j"
|
2021-02-06 12:45:46 +01:00
|
|
|
|
|
|
|
type Fail2BanDB struct {
|
|
|
|
DatabasePath string
|
2021-02-06 16:17:35 +01:00
|
|
|
sqliteDB *sql.DB
|
2021-02-06 12:45:46 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func MustConnectToDb(databasePath string) *Fail2BanDB {
|
|
|
|
db, err := sql.Open("sqlite3", databasePath)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
return &Fail2BanDB{
|
|
|
|
DatabasePath: databasePath,
|
|
|
|
sqliteDB: db,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-06 13:24:31 +01:00
|
|
|
func (db *Fail2BanDB) CountBannedIpsPerJail() (map[string]int, error) {
|
|
|
|
return db.RunJailNameToCountQuery(queryBannedIpsPerJail)
|
|
|
|
}
|
|
|
|
|
2021-02-06 13:12:01 +01:00
|
|
|
func (db *Fail2BanDB) CountBadIpsPerJail() (map[string]int, error) {
|
2021-02-06 13:24:31 +01:00
|
|
|
return db.RunJailNameToCountQuery(queryBadIpsPerJail)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *Fail2BanDB) RunJailNameToCountQuery(query string) (map[string]int, error) {
|
|
|
|
stmt, err := db.sqliteDB.Prepare(query)
|
2021-02-06 12:45:46 +01:00
|
|
|
defer db.mustCloseStatement(stmt)
|
|
|
|
|
|
|
|
if err != nil {
|
2021-02-06 13:12:01 +01:00
|
|
|
return nil, err
|
2021-02-06 12:45:46 +01:00
|
|
|
}
|
|
|
|
|
2021-02-06 13:12:01 +01:00
|
|
|
jailNameToCountMap := map[string]int{}
|
|
|
|
rows, err := stmt.Query()
|
2021-02-06 12:45:46 +01:00
|
|
|
if err != nil {
|
2021-02-06 13:12:01 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if rows == nil {
|
|
|
|
return jailNameToCountMap, nil
|
2021-02-06 12:45:46 +01:00
|
|
|
}
|
|
|
|
|
2021-02-06 13:12:01 +01:00
|
|
|
for rows.Next() {
|
|
|
|
if rows.Err() != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
jailName := ""
|
|
|
|
count := 0
|
|
|
|
err = rows.Scan(&jailName, &count)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
jailNameToCountMap[jailName] = count
|
|
|
|
}
|
|
|
|
return jailNameToCountMap, nil
|
2021-02-06 12:45:46 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (db *Fail2BanDB) mustCloseStatement(stmt *sql.Stmt) {
|
|
|
|
err := stmt.Close()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|