sacrebleu-dns/utils/sql.go

88 lines
2.2 KiB
Go
Raw Normal View History

2020-12-13 04:01:04 +01:00
package utils
import (
"database/sql"
"fmt"
"time"
"github.com/go-redis/redis"
_ "github.com/go-sql-driver/mysql"
"github.com/sirupsen/logrus"
)
var DB *sql.DB
func SqlDatabase(conf *Conf) {
logrus.WithFields(logrus.Fields{"database": conf.Database.Db}).Infof("SQL : Connection to DB")
//db conn
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", conf.Database.Username, conf.Database.Password, conf.Database.Ip, conf.Database.Port, conf.Database.Db))
CheckErr(err)
DB = db
2020-12-14 01:58:01 +01:00
SqlTest() //Test SQL conn
2020-12-13 04:01:04 +01:00
// if there is an error opening the connection, handle it
CheckErr(err)
}
func SqlTest() {
results, err := DB.Query("SELECT name, content FROM records")
CheckErr(err)
for results.Next() {
var record Record
err = results.Scan(&record.Fqdn, &record.Content)
CheckErr(err)
logrus.Debugf(record.Content)
}
}
func sqlCheckForRecord(redisKey string, dKey string, entry Record) (Record, int) {
dbg := DB.QueryRow(
2020-12-13 19:30:29 +01:00
"SELECT id, content, ttl FROM records WHERE `name` = ? AND `type` = ?;", dKey, entry.Qtype).Scan(
2020-12-13 04:01:04 +01:00
&entry.Id,
&entry.Content,
&entry.TTL,
)
//logrus.WithFields(logrus.Fields{"name": dKey, "type": entry.Qtype}).Debugf("SQL : ")
if dbg != nil {
logrus.Debugf("SQL : %v", dbg)
}
logrus.Debugf("SQL : %s => %s", entry.Fqdn, entry.Content)
if entry.Content != "" {
//Cache the request in Redis if any result
logrus.Debugf("REDIS : Set entry for %s", redisKey)
_ = redisSet(redisDb, redisKey, 30*time.Second, entry)
return entry, 0
} else {
//Else return nil
return entry, 1
}
}
func sqlCheckForReverse6Wildcard(redisKey string, dKey string, entry Record) (Record, error) {
returnedEntry := entry
2020-12-13 19:30:29 +01:00
results, err := DB.Query("SELECT id, content, name FROM records WHERE name LIKE '*%.ip6.arpa.';")
2020-12-13 19:43:31 +01:00
DbgErr(err)
2020-12-13 04:01:04 +01:00
for results.Next() {
err = results.Scan(&returnedEntry.Id, &returnedEntry.Content, &returnedEntry.Fqdn)
CheckErr(err)
if checkReverse6(entry, returnedEntry) {
logrus.Debug("REVERSE : Correct wildcard reverse.")
//Cache the request in Redis if any result
_ = redisSet(redisDb, redisKey, 10*time.Second, returnedEntry)
return returnedEntry, err
} else {
logrus.Debug("REVERSE : WRONG wildcard reverse .")
}
}
return entry, redis.Nil
}