Skip to content

Commit

Permalink
WIP rewrite progress, config loading broken atm
Browse files Browse the repository at this point in the history
  • Loading branch information
yunginnanet committed Jun 26, 2024
1 parent da2fadd commit ee11dd3
Show file tree
Hide file tree
Showing 11 changed files with 401 additions and 68 deletions.
152 changes: 121 additions & 31 deletions cmd/HellPot/HellPot.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"errors"
"fmt"
"io"
"os"
"os/signal"
Expand All @@ -9,6 +11,8 @@ import (
"syscall"
"time"

"github.com/rs/zerolog"

"github.com/yunginnanet/HellPot/internal/config"
"github.com/yunginnanet/HellPot/internal/extra"
"github.com/yunginnanet/HellPot/internal/http"
Expand Down Expand Up @@ -39,66 +43,110 @@ func writeConfig(target string) bool {
return true
}

func main() {
conf := config.CLIFlags.Lookup("config").Value
if conf.String() == "" {
conf = config.CLIFlags.Lookup("c").Value
}

usingDefaults := true
resolvedConf := conf.String()

func searchConfig() string {
var resolvedConf string
uconf, _ := os.UserConfigDir()
if uconf == "" && os.Getenv("HOME") != "" {
uconf = filepath.Join(os.Getenv("HOME"), ".config")
}

if resolvedConf == "" {
for _, path := range []string{
"/etc/HellPot/config.toml",
"/usr/local/etc/HellPot/config.toml",
"./config.toml",
filepath.Join(uconf, "HellPot", "config.toml"),
} {
if _, err := os.Stat(path); err == nil {
resolvedConf = path
break
}
for _, path := range []string{
"/etc/HellPot/config.toml",
"/usr/local/etc/HellPot/config.toml",
"./config.toml",
filepath.Join(uconf, "HellPot", "config.toml"),
} {
if _, err := os.Stat(path); err == nil {
resolvedConf = path
break
}
}
return resolvedConf
}

var setupErr error
func readConfig(resolvedConf string) error {
var err error
var setupErr error
var f *os.File

if resolvedConf == "" {
return fmt.Errorf("%w: provided config file is an empty string", io.EOF)
}

f, err = os.Open(resolvedConf) // #nosec G304 go home gosec, you're drunk
if err == nil {
runningConfig, setupErr = config.Setup(f)
}
switch {
case setupErr != nil:
println("failed to setup config: " + setupErr.Error())
err = setupErr
case err != nil:
println("failed to open config file for reading: " + err.Error())
println("trying to create it....")
wroteOK := writeConfig(resolvedConf)
if wroteOK {
break
}
println("failed to create config file, cannot continue")
return fmt.Errorf("failed to create config file: %w", err)
case runningConfig != nil:
usingDefaults = false
_ = f.Close()
}

return err
}

func resolveConfig() (usingDefaults bool, resolvedConf string, err error) {
if config.CLIFlags != nil {
confRoot := config.CLIFlags.Lookup("config")
if confRoot != nil && confRoot.Value.String() != "" {
resolvedConf = confRoot.Value.String()
}
}

if resolvedConf == "" && os.Getenv("HELLPOT_CONFIG_FILE") != "" {
resolvedConf = os.Getenv("HELLPOT_CONFIG_FILE")
}

if resolvedConf == "" {
resolvedConf = searchConfig()
}

if err = readConfig(resolvedConf); err != nil && !errors.Is(err, io.EOF) {
return false, "", err
}

if runningConfig == nil {
println("still no config, trying defaults...")
if runningConfig, err = config.Setup(nil); err != nil || runningConfig == nil {
panic("failed to setup default config...\n" + err.Error())
if err == nil {
err = errors.New("unknown failure resulting in missing configuration, cannot continue")
}
return false, "", err
}
return true, "", nil
}

log, _ := logger.New(runningConfig.Logger)
return false, resolvedConf, nil
}

func setup(stopChan chan os.Signal) (log zerolog.Logger, logFile string, resolvedConf string, err error) {
var usingDefaults bool

if usingDefaults, resolvedConf, err = resolveConfig(); err != nil {
return
}

//goland:noinspection GoNilness // we check for nil above
if log, err = logger.New(runningConfig.Logger); err != nil {
return
}

logFile = runningConfig.Logger.ActiveLogFileName

if usingDefaults {
runningConfig.UsingDefaults = true
log.Warn().Msg("continuing with default configuration in ")
for i := 5; i > 0; i-- {
print(strconv.Itoa(i))
Expand All @@ -109,27 +157,69 @@ func main() {
}
}

if !runningConfig.Logger.NoColor {
if //goland:noinspection GoNilness
!runningConfig.Logger.NoColor {
extra.Banner()
}

signal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM)
return
}

func testMain(t interface{ Error(...any) }) (string, string, chan os.Signal, error) {
stopChan := make(chan os.Signal, 1)
log, logFile, resolvedConf, err := setup(stopChan)
if err == nil {
log.Info().Msg("🔥 Starting HellPot 🔥")
go func() {
terr := http.Serve(runningConfig)
if terr != nil {
t.Error("failed to serve HTTP: " + terr.Error())
close(stopChan)
}
}()
}
//goland:noinspection GoNilness
return resolvedConf, logFile, stopChan, err
}

func main() {
stopChan := make(chan os.Signal, 1)
log, _, resolvedConf, err := setup(stopChan)

if err != nil {
println("failed to start: " + err.Error())
os.Exit(1)
}

log.Info().Msg("🔥 Starting HellPot 🔥")
log.Info().Msg("Version: " + version.Version)
log.Info().Msg("PID: " + strconv.Itoa(os.Getpid()))
log.Info().Msg("Using config file: " + resolvedConf)
if usingDefaults {
if runningConfig.UsingDefaults {
log.Warn().Msg("Using default configuration")
}
if runningConfig.Logger.RSyslog != "" {
log.Info().Msg("Logging to syslog: " + runningConfig.Logger.RSyslog)
}
if runningConfig.Logger.ActiveLogFileName != "" {
log.Info().Msg("Logging to file: " + runningConfig.Logger.ActiveLogFileName)
}
if runningConfig.Logger.DockerLogging &&
runningConfig.Logger.File == "" &&
runningConfig.Logger.Directory == "" &&
runningConfig.Logger.RSyslog == "" {
log.Info().Msg("Only logging to standard output")
}

log.Debug().Msg("Debug logging enabled")
log.Trace().Msg("Trace logging enabled")

stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM)

go func() {
log.Fatal().Err(http.Serve(runningConfig)).Msg("HTTP error")
}()

<-stopChan // wait for SIGINT
log.Warn().Msg("Shutting down server...")
sig := <-stopChan // wait for SIGINT
log.Warn().Interface("signal_received", sig).
Msg("Shutting down server...")
}
21 changes: 21 additions & 0 deletions cmd/HellPot/HellPot_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

import (
"os"
"testing"
"time"
)

func TestHellPot(t *testing.T) {
resolvedConf, logFile, stopChan, err := testMain(t)
if err != nil {
t.Fatal(err)
}
if stopChan == nil {
t.Fatal("stopChan is nil")
}
t.Log("resolvedConf: ", resolvedConf)
t.Log("logFile: ", logFile)
time.Sleep(100 * time.Millisecond)
stopChan <- os.Interrupt
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.19
require (
git.tcp.direct/kayos/common v0.9.7
github.com/fasthttp/router v1.5.1
github.com/google/go-cmdtest v0.4.0
github.com/knadh/koanf/parsers/toml v0.1.0
github.com/knadh/koanf/providers/env v0.1.0
github.com/knadh/koanf/v2 v2.1.1
Expand All @@ -15,6 +16,8 @@ require (
require (
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1 // indirect
github.com/google/go-cmp v0.3.1 // indirect
github.com/google/renameio v0.1.0 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/knadh/koanf/maps v0.1.1 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ github.com/fasthttp/router v1.5.1/go.mod h1:WrmsLo3mrerZP2VEXRV1E8nL8ymJFYCDTr4H
github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1 h1:TQcrn6Wq+sKGkpyPvppOz99zsMBaUOKXq6HSv655U1c=
github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmdtest v0.4.0 h1:ToXh6W5spLp3npJV92tk6d5hIpUPYEzHLkD+rncbyhI=
github.com/google/go-cmdtest v0.4.0/go.mod h1:apVn/GCasLZUVpAJ6oWAuyP7Ne7CEsQbTnc0plM3m+o=
github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/knadh/koanf/maps v0.1.1 h1:G5TjmUh2D7G2YWf5SQQqSiHRJEjaicvU0KpypqB3NIs=
Expand Down
9 changes: 6 additions & 3 deletions heffalump/heffalump.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package heffalump

import (
"bufio"
"fmt"
"io"
"sync"
)
Expand All @@ -31,8 +32,7 @@ func NewHeffalump(mm MarkovMap, buffsize int) *Heffalump {
}
}

// NewDefaultHeffalump instantiates a new default Heffalump from a MarkovMap created using
// using the default source text.
// NewDefaultHeffalump instantiates a new default Heffalump from a MarkovMap created using using the default source text.
func NewDefaultHeffalump() *Heffalump {
return NewHeffalump(NewDefaultMarkovMap(), DefaultBuffSize)
}
Expand All @@ -50,7 +50,10 @@ func (h *Heffalump) WriteHell(bw *bufio.Writer, cType ContentType) (int64, error
var n int64
var err error

buf := h.pool.Get().([]byte)
buf, ok := h.pool.Get().([]byte)
if !ok {
panic("buffer pool type assertion failed, retrieved type is a " + fmt.Sprintf("%T", buf))
}

switch cType {
case PlainText:
Expand Down
2 changes: 1 addition & 1 deletion internal/config/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ var defOpts = map[string]interface{}{
"debug": true,
"trace": false,
"nocolor": runtime.GOOS == "windows",
"use_date_filename": true,
"use_date_filename": false,
"docker_logging": false,
"console_time_format": time.Kitchen,
},
Expand Down
9 changes: 6 additions & 3 deletions internal/config/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@ type Parameters struct {
Perf Performance `koanf:"performance"`
Liar Deception `koanf:"deception"`

source *koanf.Koanf `koanf:"-"`
logger *zerolog.Logger
IdleHands DevilsPlaythings `koanf:"experimental"`

source *koanf.Koanf `koanf:"-"`
logger *zerolog.Logger `koanf:"-"`
UsingDefaults bool `koanf:"-"`
}

var once = &sync.Once{}
Expand Down Expand Up @@ -63,7 +66,7 @@ type Router struct {
// HTTP represents the configuration for the HTTP server.
type HTTP struct {
Bind string `koanf:"bind_addr"`
Port int64 `koanf:"port"`
Port int64 `koanf:"bind_port"`
// ProxiedIPHeader is the HTTP Header containing the original IP of the client
// for usage by traditional reverse Proxy deployments.
ProxiedIPHeader string `koanf:"proxied_ip_header"`
Expand Down
Loading

0 comments on commit ee11dd3

Please sign in to comment.