2016-06-15 13:50:56 +02:00
|
|
|
// Copyright (c) 2012-2014 Jeremy Latt
|
|
|
|
// released under the MIT license
|
|
|
|
|
2014-03-02 00:02:24 +01:00
|
|
|
package irc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2016-09-05 10:45:42 +02:00
|
|
|
"encoding/base64"
|
2014-03-08 03:14:02 +01:00
|
|
|
"fmt"
|
2014-03-02 00:02:24 +01:00
|
|
|
"log"
|
|
|
|
"os"
|
2016-06-15 13:50:56 +02:00
|
|
|
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
2016-09-05 10:45:42 +02:00
|
|
|
"github.com/tidwall/buntdb"
|
2014-03-02 00:02:24 +01:00
|
|
|
)
|
|
|
|
|
2016-09-05 10:45:42 +02:00
|
|
|
const (
|
|
|
|
// key for the primary salt used by the ircd
|
|
|
|
keySalt = "crypto.salt"
|
|
|
|
)
|
|
|
|
|
|
|
|
func InitDB(buntpath string, path string) {
|
|
|
|
// prepare kvstore db
|
|
|
|
os.Remove(buntpath)
|
|
|
|
store, err := buntdb.Open(buntpath)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(fmt.Sprintf("Failed to open datastore: %s", err.Error()))
|
|
|
|
}
|
|
|
|
defer store.Close()
|
|
|
|
|
|
|
|
err = store.Update(func(tx *buntdb.Tx) error {
|
|
|
|
salt, err := NewSalt()
|
|
|
|
encodedSalt := base64.StdEncoding.EncodeToString(salt)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("Could not generate cryptographically-secure salt for the user:", err.Error())
|
|
|
|
}
|
|
|
|
tx.Set(keySalt, encodedSalt, nil)
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("Could not save bunt store:", err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
// prepare SQLite db
|
2014-03-02 00:02:24 +01:00
|
|
|
os.Remove(path)
|
|
|
|
db := OpenDB(path)
|
|
|
|
defer db.Close()
|
2016-09-05 10:45:42 +02:00
|
|
|
_, err = db.Exec(`
|
2014-03-02 00:02:24 +01:00
|
|
|
CREATE TABLE channel (
|
|
|
|
name TEXT NOT NULL UNIQUE,
|
2014-03-08 03:14:02 +01:00
|
|
|
flags TEXT DEFAULT '',
|
|
|
|
key TEXT DEFAULT '',
|
|
|
|
topic TEXT DEFAULT '',
|
|
|
|
user_limit INTEGER DEFAULT 0,
|
|
|
|
ban_list TEXT DEFAULT '',
|
|
|
|
except_list TEXT DEFAULT '',
|
|
|
|
invite_list TEXT DEFAULT '')`)
|
2014-03-02 00:02:24 +01:00
|
|
|
if err != nil {
|
2014-03-06 08:07:55 +01:00
|
|
|
log.Fatal("initdb error: ", err)
|
2014-03-02 00:02:24 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-08 03:14:02 +01:00
|
|
|
func UpgradeDB(path string) {
|
|
|
|
db := OpenDB(path)
|
|
|
|
alter := `ALTER TABLE channel ADD COLUMN %s TEXT DEFAULT ''`
|
|
|
|
cols := []string{"ban_list", "except_list", "invite_list"}
|
|
|
|
for _, col := range cols {
|
|
|
|
_, err := db.Exec(fmt.Sprintf(alter, col))
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("updatedb error: ", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-02 00:02:24 +01:00
|
|
|
func OpenDB(path string) *sql.DB {
|
|
|
|
db, err := sql.Open("sqlite3", path)
|
|
|
|
if err != nil {
|
2014-03-06 08:07:55 +01:00
|
|
|
log.Fatal("open db error: ", err)
|
2014-03-02 00:02:24 +01:00
|
|
|
}
|
|
|
|
return db
|
|
|
|
}
|