Refactoring of some vars and funcs name

Theses change breaks old configuration files but make the code readability better thanks to VSCode plugins.
This commit is contained in:
Mael G. 2020-12-21 23:12:02 -04:00
parent 7cf1ae926b
commit efffac8b0a
8 changed files with 51 additions and 52 deletions

View file

@ -2,9 +2,9 @@ package core
import "github.com/miekg/dns" import "github.com/miekg/dns"
//Handle the DNS request using miekg/dns //HandleDNSRequest : Handle the DNS request using miekg/dns
//Requires dns.ReponseWriter and dns.Msg args //Requires dns.ReponseWriter and dns.Msg args
func HandleDnsRequest(w dns.ResponseWriter, r *dns.Msg) { func HandleDNSRequest(w dns.ResponseWriter, r *dns.Msg) {
//dns.Msg object //dns.Msg object
//Will be passed to the parseQuery() function //Will be passed to the parseQuery() function

View file

@ -1,20 +1,20 @@
App_mode = "production" #Anything != production will show DEBUG messages App_mode = "production" #Anything != production will show DEBUG messages
[App] [App]
Ip = ":" IP = ":"
Port = 5353 Port = 5353
Logfile = true Logfile = true
Logdir = "/var/log/" Logdir = "/var/log/"
[Database] [Database]
Ip = "127.0.0.1" IP = "127.0.0.1"
Username = "sacrebleu" Username = "sacrebleu"
Password = "superSecretPassword" Password = "superSecretPassword"
Port = "3306" Port = "3306"
Db = "sacrebleudatabase" Db = "sacrebleudatabase"
[Redis] [Redis]
Ip = "127.0.0.1" IP = "127.0.0.1"
Port = 6379 Port = 6379
Password = "" Password = ""
Db = 0 Db = 0

11
main.go
View file

@ -13,7 +13,10 @@ import (
) )
//Global vars //Global vars
//conf Configuration
var conf *utils.Conf var conf *utils.Conf
//DB the SQL database
var DB *sql.DB var DB *sql.DB
//Main loop //Main loop
@ -31,17 +34,17 @@ func main() {
utils.InitLogger(conf) utils.InitLogger(conf)
//Attach DNS request handler func for all domains //Attach DNS request handler func for all domains
dns.HandleFunc(".", core.HandleDnsRequest) dns.HandleFunc(".", core.HandleDNSRequest)
//Initialize the redis database //Initialize the redis database
utils.RedisDatabase(conf) utils.RedisDatabase(conf)
//Initialize the sql database //Initialize the sql database
utils.SqlDatabase(conf) utils.SQLDatabase(conf)
//Start the DNS server //Start the DNS server
server := &dns.Server{Addr: conf.App.Ip + strconv.Itoa(conf.App.Port), Net: "udp"} //define the server server := &dns.Server{Addr: conf.App.IP + strconv.Itoa(conf.App.Port), Net: "udp"} //define the server
logrus.WithFields(logrus.Fields{"ip": conf.App.Ip, "port": conf.App.Port}).Infof("SERVER : Started") //log logrus.WithFields(logrus.Fields{"ip": conf.App.IP, "port": conf.App.Port}).Infof("SERVER : Started") //log
err = server.ListenAndServe() //start it err = server.ListenAndServe() //start it
utils.CheckErr(err) utils.CheckErr(err)

View file

@ -8,7 +8,7 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
//Check the SQL and REDIS database for a Record. //GetRecord : Check the SQL and REDIS database for a Record.
//A Record struct is used as input and output //A Record struct is used as input and output
func GetRecord(entry Record) Record { func GetRecord(entry Record) Record {
//Check for strict record in Redis cache //Check for strict record in Redis cache

View file

@ -16,13 +16,13 @@ var ctx = context.Background()
//Redis client as global var //Redis client as global var
var redisDb *redis.Client var redisDb *redis.Client
//Initialize the Redis Database //RedisDatabase : Initialize the Redis Database
//Requires a conf struct //Requires a conf struct
//Return a *redis.Client //Return a *redis.Client
func RedisDatabase(conf *Conf) *redis.Client { func RedisDatabase(conf *Conf) *redis.Client {
logrus.WithFields(logrus.Fields{"ip": conf.Redis.Ip, "port": conf.Redis.Port}).Infof("REDIS : Connection to DB") logrus.WithFields(logrus.Fields{"ip": conf.Redis.IP, "port": conf.Redis.Port}).Infof("REDIS : Connection to DB")
rdb := redis.NewClient(&redis.Options{ rdb := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%v", conf.Redis.Ip, conf.Redis.Port), Addr: fmt.Sprintf("%s:%v", conf.Redis.IP, conf.Redis.Port),
Password: conf.Redis.Password, Password: conf.Redis.Password,
DB: conf.Redis.Db, DB: conf.Redis.Db,
}) //Connect to the DB }) //Connect to the DB
@ -54,10 +54,8 @@ func redisCheckForRecord(redisKey string, entry Record) (Record, error) {
err := json.Unmarshal([]byte(val), &entry) err := json.Unmarshal([]byte(val), &entry)
logrus.Debugf("REDIS : %s => %s", redisKey, entry.Content) logrus.Debugf("REDIS : %s => %s", redisKey, entry.Content)
return entry, err return entry, err
} else {
//Else return nil
return entry, redis.Nil
} }
return entry, redis.Nil
} }
//Add a record in the Redis database //Add a record in the Redis database

View file

@ -6,26 +6,26 @@ import (
"time" "time"
"github.com/go-redis/redis" "github.com/go-redis/redis"
_ "github.com/go-sql-driver/mysql" _ "github.com/go-sql-driver/mysql" //MySQL driver
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
//SQL database as global var //DB SQL database as global var
var DB *sql.DB var DB *sql.DB
//Initialize the (My)SQL Database //SQLDatabase Initialize the (My)SQL Database
//Requires a conf struct //Requires a conf struct
func SqlDatabase(conf *Conf) { func SQLDatabase(conf *Conf) {
logrus.WithFields(logrus.Fields{"database": conf.Database.Db}).Infof("SQL : Connection to DB") logrus.WithFields(logrus.Fields{"database": conf.Database.Db}).Infof("SQL : Connection to DB")
//Connect to the Database //Connect to the Database
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)) 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) CheckErr(err)
DB = db DB = db
SqlTest() //Test SQL connexion SQLTest() //Test SQL connexion
} }
//Test the SQL connexion by selecting all records from the database //SQLTest : Test the SQL connexion by selecting all records from the database
func SqlTest() { func SQLTest() {
_, err := DB.Query("SELECT name, content FROM records") _, err := DB.Query("SELECT name, content FROM records")
CheckErr(err) //Panic if any error CheckErr(err) //Panic if any error
} }
@ -34,7 +34,7 @@ func SqlTest() {
func sqlCheckForRecord(redisKey string, dKey string, entry Record) (Record, int) { func sqlCheckForRecord(redisKey string, dKey string, entry Record) (Record, int) {
dbg := DB.QueryRow( dbg := DB.QueryRow(
"SELECT id, content, ttl FROM records WHERE `name` = ? AND `type` = ?;", dKey, entry.Qtype).Scan( "SELECT id, content, ttl FROM records WHERE `name` = ? AND `type` = ?;", dKey, entry.Qtype).Scan(
&entry.Id, &entry.ID,
&entry.Content, &entry.Content,
&entry.TTL, &entry.TTL,
) )
@ -50,10 +50,10 @@ func sqlCheckForRecord(redisKey string, dKey string, entry Record) (Record, int)
logrus.Debugf("REDIS : Set entry for %s", redisKey) logrus.Debugf("REDIS : Set entry for %s", redisKey)
_ = redisSet(redisDb, redisKey, 30*time.Second, entry) //Set it in the Redis database for 30sec _ = redisSet(redisDb, redisKey, 30*time.Second, entry) //Set it in the Redis database for 30sec
return entry, 0 return entry, 0
} else {
//Else return 1 for err
return entry, 1
} }
//Else return 1 for err
return entry, 1
} }
//Check for a wildcard record in the SQL database //Check for a wildcard record in the SQL database
@ -65,7 +65,7 @@ func sqlCheckForReverse6Wildcard(redisKey string, dKey string, entry Record) (Re
//For each result check if it match the reverse IP //For each result check if it match the reverse IP
for results.Next() { for results.Next() {
err = results.Scan(&returnedEntry.Id, &returnedEntry.Content, &returnedEntry.Fqdn) err = results.Scan(&returnedEntry.ID, &returnedEntry.Content, &returnedEntry.Fqdn)
CheckErr(err) CheckErr(err)
//Check if the record is matching the reversed IP //Check if the record is matching the reversed IP
@ -74,9 +74,8 @@ func sqlCheckForReverse6Wildcard(redisKey string, dKey string, entry Record) (Re
//Cache the request in Redis if any result //Cache the request in Redis if any result
_ = redisSet(redisDb, redisKey, 10*time.Second, returnedEntry) _ = redisSet(redisDb, redisKey, 10*time.Second, returnedEntry)
return returnedEntry, err return returnedEntry, err
} else {
logrus.Debug("REVERSE : WRONG wildcard reverse .")
} }
logrus.Debug("REVERSE : WRONG wildcard reverse .")
} }
return entry, redis.Nil return entry, redis.Nil

View file

@ -1,53 +1,53 @@
package utils package utils
//Struct for App (dns server) configuration in the config.ini file //App : Struct for App (dns server) configuration in the config.ini file
type App struct { type App struct {
Port int Port int
Ip string IP string
Logdir string Logdir string
Logfile bool Logfile bool
} }
//Struct for SQL Database configuration in the config.ini file //Database : Struct for SQL Database configuration in the config.ini file
type Database struct { type Database struct {
Ip string IP string
Port string Port string
Username string Username string
Password string Password string
Db string Db string
} }
//Struct for Redis Database configuration in the config.ini file //Redis : Struct for Redis Database configuration in the config.ini file
type Redis struct { type Redis struct {
Ip string IP string
Port int Port int
Password string Password string
Db int Db int
Ttl int TTL int
} }
//Struct for the whole config.ini file when it will be parsed by go-ini //Conf : Struct for the whole config.ini file when it will be parsed by go-ini
type Conf struct { type Conf struct {
App_mode string AppMode string
App App
Database Database
Redis Redis
} }
//Struct for a Domain (not used currently). //Domain : Struct for a Domain (not used currently).
type Domain struct { type Domain struct {
ID int `json:"id"` ID int `json:"id"`
FriendlyName string FriendlyName string
Fqdn string Fqdn string
OwnerId int OwnerID int
LastEdit string LastEdit string
} }
//Struct for a domain record //Record : Struct for a domain record
//Defined by it's ID, DomainID (parent domain), Fqdn (or name), Content (value of the record), Type (as Qtype/int), TTL (used only for the DNS response and not the Redis TTL) //Defined by it's ID, DomainID (parent domain), Fqdn (or name), Content (value of the record), Type (as Qtype/int), TTL (used only for the DNS response and not the Redis TTL)
type Record struct { type Record struct {
Id int ID int
DomainId int DomainID int
Fqdn string Fqdn string
Content string Content string
Type int Type int

View file

@ -10,26 +10,26 @@ import (
"github.com/snowzach/rotatefilehook" "github.com/snowzach/rotatefilehook"
) )
//If fatal error, log it and panic //CheckErr : If fatal error, log it and panic
func CheckErr(err error) { func CheckErr(err error) {
if err != nil { if err != nil {
log.Fatalf("%s\n ", err.Error()) log.Fatalf("%s\n ", err.Error())
} }
} }
//If basic error, log it as classic error but don't panic and keep kalm //DbgErr : If basic error, log it as classic error but don't panic and keep kalm
func DbgErr(err error) { func DbgErr(err error) {
if err != nil { if err != nil {
log.Errorf("%s\n ", err.Error()) log.Errorf("%s\n ", err.Error())
} }
} }
//Init the logrus logger with rotateFileHook. //InitLogger : Init the logrus logger with rotateFileHook.
//Conf struct passed to get informations about the logger (debug or not) //Conf struct passed to get informations about the logger (debug or not)
func InitLogger(conf *Conf) { func InitLogger(conf *Conf) {
var logLevel = logrus.InfoLevel //By default the level is Info. var logLevel = logrus.InfoLevel //By default the level is Info.
if conf.App_mode != "production" { //If the configuration contains anything different than "production"; the level is set to Debug if conf.AppMode != "production" { //If the configuration contains anything different than "production"; the level is set to Debug
logLevel = logrus.DebugLevel logLevel = logrus.DebugLevel
} }
@ -62,7 +62,7 @@ func InitLogger(conf *Conf) {
logrus.AddHook(rotateFileHook) logrus.AddHook(rotateFileHook)
} }
log.WithFields(log.Fields{"app_mode": conf.App_mode}).Info("Application mode") log.WithFields(log.Fields{"app_mode": conf.AppMode}).Info("Application mode")
log.WithFields(log.Fields{"logLevel": logLevel}).Debug("Log level") log.WithFields(log.Fields{"logLevel": logLevel}).Debug("Log level")
} }
@ -74,7 +74,6 @@ func checkReverse6(entry Record, result Record) bool {
logrus.Debugf("REVERSE checkReverse6 : %s", check) logrus.Debugf("REVERSE checkReverse6 : %s", check)
if strings.Contains(check, IP6arpa) { if strings.Contains(check, IP6arpa) {
return false return false
} else {
return true
} }
return true
} }