aboutsummaryrefslogtreecommitdiff
path: root/cmd
diff options
context:
space:
mode:
authorRuben Beltran del Rio <git@r.bdr.sh>2025-11-28 00:39:17 +0100
committerRuben Beltran del Rio <git@r.bdr.sh>2025-11-28 00:39:17 +0100
commit9f67542d8469db45c823e347b1868b3582d9e5a7 (patch)
tree88741b3d8633758e4f6f5cbc292f338bc99602a0 /cmd
parent8f9edf2f3bb18f7ab1a04ead182a1daf2cfd41d9 (diff)
parent8ddb9bb228389b198a76d6df21de005da4fad66b (diff)
Merge branch 'master' of https://github.com/jhalter/mobiusHEADmain
Diffstat (limited to 'cmd')
-rw-r--r--cmd/mobius-hotline-server/main.go162
-rw-r--r--cmd/mobius-hotline-server/main_test.go181
-rw-r--r--cmd/mobius-hotline-server/mobius/config/config.yaml2
3 files changed, 285 insertions, 60 deletions
diff --git a/cmd/mobius-hotline-server/main.go b/cmd/mobius-hotline-server/main.go
index e4e0954..cc24f5f 100644
--- a/cmd/mobius-hotline-server/main.go
+++ b/cmd/mobius-hotline-server/main.go
@@ -2,19 +2,20 @@ package main
import (
"context"
+ "crypto/tls"
"embed"
"flag"
"fmt"
- "github.com/jhalter/mobius/hotline"
- "github.com/jhalter/mobius/internal/mobius"
- "github.com/oleksandr/bonjour"
"io"
"log"
"os"
"os/signal"
"path"
- "path/filepath"
"syscall"
+
+ "github.com/jhalter/mobius/hotline"
+ "github.com/jhalter/mobius/internal/mobius"
+ "github.com/oleksandr/bonjour"
)
//go:embed mobius/config
@@ -35,11 +36,18 @@ func main() {
netInterface := flag.String("interface", "", "IP addr of interface to listen on. Defaults to all interfaces.")
basePort := flag.Int("bind", 5500, "Base Hotline server port. File transfer port is base port + 1.")
apiAddr := flag.String("api-addr", "", "Enable HTTP API endpoint on address and port")
- configDir := flag.String("config", configSearchPaths(), "Path to config root")
+ apiKey := flag.String("api-key", "", "API key required for HTTP API authentication")
+ redisAddr := flag.String("redis-addr", "", "Redis server address for API features")
+ redisPassword := flag.String("redis-password", "", "Redis password, if required")
+ redisDB := flag.Int("redis-db", 0, "Redis DB number, defaults to 0")
+ configDir := flag.String("config", findConfigPath(), "Path to config root")
printVersion := flag.Bool("version", false, "Print version and exit")
logLevel := flag.String("log-level", "info", "Log level")
logFile := flag.String("log-file", "", "Path to log file")
init := flag.Bool("init", false, "Populate the config dir with default configuration")
+ tlsCert := flag.String("tls-cert", "", "Path to TLS certificate file")
+ tlsKey := flag.String("tls-key", "", "Path to TLS key file")
+ tlsPort := flag.Int("tls-port", 5600, "Base TLS port. TLS file transfer port is base + 1.")
flag.Parse()
@@ -55,11 +63,11 @@ func main() {
if *init {
if _, err := os.Stat(path.Join(*configDir, "/config.yaml")); os.IsNotExist(err) {
if err := os.MkdirAll(*configDir, 0750); err != nil {
- slogger.Error(fmt.Sprintf("error creating config dir: %s", err))
+ slogger.Error("Error creating config dir", "err", err)
os.Exit(1)
}
if err := copyDir(path.Join("mobius", "config"), *configDir); err != nil {
- slogger.Error(fmt.Sprintf("error copying config dir: %s", err))
+ slogger.Error("Error copying config dir", "err", err)
os.Exit(1)
}
slogger.Info("Config dir initialized at " + *configDir)
@@ -70,55 +78,70 @@ func main() {
config, err := mobius.LoadConfig(path.Join(*configDir, "config.yaml"))
if err != nil {
- slogger.Error(fmt.Sprintf("Error loading config: %v", err))
+ slogger.Error("Error loading config", "err", err)
os.Exit(1)
}
- srv, err := hotline.NewServer(
+ var tlsConfig *tls.Config
+ if *tlsCert != "" && *tlsKey != "" {
+ cert, err := tls.LoadX509KeyPair(*tlsCert, *tlsKey)
+ if err != nil {
+ slogger.Error("Error loading TLS certificate", "err", err)
+ os.Exit(1)
+ }
+ tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
+ }
+
+ opts := []hotline.Option{
hotline.WithInterface(*netInterface),
hotline.WithLogger(slogger),
hotline.WithPort(*basePort),
hotline.WithConfig(*config),
- )
+ }
+ if tlsConfig != nil {
+ opts = append(opts, hotline.WithTLS(tlsConfig, *tlsPort))
+ }
+
+ srv, err := hotline.NewServer(opts...)
if err != nil {
- slogger.Error(fmt.Sprintf("Error starting server: %s", err))
+ slogger.Error("Error starting server", "err", err)
os.Exit(1)
}
srv.MessageBoard, err = mobius.NewFlatNews(path.Join(*configDir, "MessageBoard.txt"))
if err != nil {
- slogger.Error(fmt.Sprintf("Error loading message board: %v", err))
+ slogger.Error("Error loading message board", "err", err)
os.Exit(1)
}
srv.BanList, err = mobius.NewBanFile(path.Join(*configDir, "Banlist.yaml"))
if err != nil {
- slogger.Error(fmt.Sprintf("Error loading ban list: %v", err))
+ slogger.Error("Error loading ban list", "err", err)
os.Exit(1)
}
srv.ThreadedNewsMgr, err = mobius.NewThreadedNewsYAML(path.Join(*configDir, "ThreadedNews.yaml"))
if err != nil {
- slogger.Error(fmt.Sprintf("Error loading news: %v", err))
+ slogger.Error("Error loading news", "err", err)
os.Exit(1)
}
- srv.AccountManager, err = mobius.NewYAMLAccountManager(filepath.Join(*configDir, "Users/"))
+ srv.AccountManager, err = mobius.NewYAMLAccountManager(path.Join(*configDir, "Users/"))
if err != nil {
- slogger.Error(fmt.Sprintf("Error loading accounts: %v", err))
+ slogger.Error("Error loading accounts", "err", err)
os.Exit(1)
}
srv.Agreement, err = mobius.NewAgreement(*configDir, "\r")
if err != nil {
- slogger.Error(fmt.Sprintf("Error loading agreement: %v", err))
+ slogger.Error("Error loading agreement", "err", err)
os.Exit(1)
}
- bannerPath := filepath.Join(*configDir, config.BannerFile)
+ bannerPath := path.Join(*configDir, config.BannerFile)
srv.Banner, err = os.ReadFile(bannerPath)
if err != nil {
- slogger.Error(fmt.Sprintf("Error loading accounts: %v", err))
+ slogger.Error("Error loading banner", "err", err)
os.Exit(1)
}
@@ -136,13 +159,19 @@ func main() {
}
if err := srv.Agreement.(*mobius.Agreement).Reload(); err != nil {
- slogger.Error(fmt.Sprintf("Error reloading agreement: %v", err))
- os.Exit(1)
+ slogger.Error("Error reloading agreement", "err", err)
+ }
+
+ // Let's try to reload the banner
+ bannerPath := path.Join(*configDir, config.BannerFile)
+ srv.Banner, err = os.ReadFile(bannerPath)
+ if err != nil {
+ slogger.Error("Error reloading banner", "err", err)
}
}
if *apiAddr != "" {
- sh := mobius.NewAPIServer(srv, reloadFunc, slogger)
+ sh := mobius.NewAPIServer(srv, reloadFunc, slogger, *apiKey, *redisAddr, *redisPassword, *redisDB)
go sh.Serve(*apiAddr)
}
@@ -164,6 +193,9 @@ func main() {
}()
slogger.Info("Hotline server started", "version", version, "config", *configDir)
+ if tlsConfig != nil {
+ slogger.Info("TLS enabled", "port", *tlsPort, "fileTransferPort", *tlsPort+1)
+ }
// Assign functions to handle specific Hotline transaction types
mobius.RegisterHandlers(srv)
@@ -180,61 +212,73 @@ func main() {
log.Fatal(srv.ListenAndServe(ctx))
}
-func configSearchPaths() string {
+// findConfigPath searches for an existing config directory from the predefined search order.
+// Returns the first directory that exists, or falls back to "config" as the default.
+func findConfigPath() string {
for _, cfgPath := range mobius.ConfigSearchOrder {
- if _, err := os.Stat(cfgPath); err == nil {
+ if info, err := os.Stat(cfgPath); err == nil && info.IsDir() {
return cfgPath
}
}
+ // Default fallback - will be created by --init flag if needed
return "config"
}
-// copyDir recursively copies a directory tree, attempting to preserve permissions.
+// copyDir recursively copies a directory tree from embedded filesystem to local filesystem.
func copyDir(src, dst string) error {
+ return copyDirRecursive(src, dst)
+}
+
+// copyDirRecursive handles the recursive copying logic.
+func copyDirRecursive(src, dst string) error {
entries, err := cfgTemplate.ReadDir(src)
if err != nil {
- return err
+ return fmt.Errorf("failed to read source directory %s: %w", src, err)
}
- for _, dirEntry := range entries {
- if dirEntry.IsDir() {
- if err := os.MkdirAll(path.Join(dst, dirEntry.Name()), 0777); err != nil {
- panic(err)
- }
- subdirEntries, _ := cfgTemplate.ReadDir(path.Join(src, dirEntry.Name()))
- for _, subDirEntry := range subdirEntries {
- f, err := os.Create(path.Join(dst, dirEntry.Name(), subDirEntry.Name()))
- if err != nil {
- return err
- }
- srcFile, err := cfgTemplate.Open(path.Join(src, dirEntry.Name(), subDirEntry.Name()))
- if err != nil {
- return fmt.Errorf("error copying srcFile: %w", err)
- }
- _, err = io.Copy(f, srcFile)
- if err != nil {
- return err
- }
- _ = f.Close()
- }
- } else {
- f, err := os.Create(path.Join(dst, dirEntry.Name()))
- if err != nil {
- return err
- }
+ for _, entry := range entries {
+ srcPath := path.Join(src, entry.Name())
+ dstPath := path.Join(dst, entry.Name())
- srcFile, err := cfgTemplate.Open(path.Join(src, dirEntry.Name()))
- if err != nil {
- return err
+ if entry.IsDir() {
+ // Create directory with proper permissions
+ if err := os.MkdirAll(dstPath, 0755); err != nil {
+ return fmt.Errorf("failed to create directory %s: %w", dstPath, err)
+ }
+
+ // Recursively copy subdirectory
+ if err := copyDirRecursive(srcPath, dstPath); err != nil {
+ return fmt.Errorf("failed to copy subdirectory %s: %w", srcPath, err)
}
- _, err = io.Copy(f, srcFile)
- if err != nil {
- return err
+ } else {
+ // Copy file
+ if err := copyFile(srcPath, dstPath); err != nil {
+ return fmt.Errorf("failed to copy file %s to %s: %w", srcPath, dstPath, err)
}
- _ = f.Close()
}
}
return nil
}
+
+// copyFile copies a single file from embedded filesystem to local filesystem.
+func copyFile(src, dst string) error {
+ srcFile, err := cfgTemplate.Open(src)
+ if err != nil {
+ return fmt.Errorf("failed to open source file: %w", err)
+ }
+ defer func() { _ = srcFile.Close() }()
+
+ dstFile, err := os.Create(dst)
+ if err != nil {
+ return fmt.Errorf("failed to create destination file: %w", err)
+ }
+ defer func() { _ = dstFile.Close() }()
+
+ if _, err := io.Copy(dstFile, srcFile); err != nil {
+ return fmt.Errorf("failed to copy file contents: %w", err)
+ }
+
+ return nil
+}
diff --git a/cmd/mobius-hotline-server/main_test.go b/cmd/mobius-hotline-server/main_test.go
new file mode 100644
index 0000000..dec2ebf
--- /dev/null
+++ b/cmd/mobius-hotline-server/main_test.go
@@ -0,0 +1,181 @@
+package main
+
+import (
+ "os"
+ "path"
+ "testing"
+
+ "github.com/jhalter/mobius/internal/mobius"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestCopyDir(t *testing.T) {
+ // Test using the actual embedded config directory
+ dstDir := t.TempDir()
+
+ // Execute copyDir with the embedded mobius/config directory
+ err := copyDir("mobius/config", dstDir)
+ require.NoError(t, err)
+
+ // Verify some expected files exist (based on the embedded config)
+ expectedFiles := []string{
+ "config.yaml",
+ "Agreement.txt",
+ "MessageBoard.txt",
+ "ThreadedNews.yaml",
+ "Users/admin.yaml",
+ "Users/guest.yaml",
+ "banner.jpg",
+ }
+
+ for _, expectedFile := range expectedFiles {
+ fullPath := path.Join(dstDir, expectedFile)
+ assert.FileExists(t, fullPath, "Expected file %s to exist", expectedFile)
+
+ // Verify file is not empty
+ info, err := os.Stat(fullPath)
+ require.NoError(t, err)
+ assert.Greater(t, info.Size(), int64(0), "File %s should not be empty", expectedFile)
+ }
+
+ // Verify directories were created
+ expectedDirs := []string{
+ "Users",
+ "Files",
+ }
+
+ for _, expectedDir := range expectedDirs {
+ fullPath := path.Join(dstDir, expectedDir)
+ info, err := os.Stat(fullPath)
+ require.NoError(t, err)
+ assert.True(t, info.IsDir(), "Expected %s to be a directory", expectedDir)
+ }
+}
+
+func TestCopyDirNonexistentSource(t *testing.T) {
+ dstDir := t.TempDir()
+
+ err := copyDir("nonexistent/directory", dstDir)
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), "failed to read source directory")
+}
+
+func TestCopyDirRecursive(t *testing.T) {
+ // Test the recursive functionality using embedded config
+ dstDir := t.TempDir()
+
+ err := copyDirRecursive("mobius/config", dstDir)
+ require.NoError(t, err)
+
+ // Verify nested structure is copied correctly
+ nestedPath := path.Join(dstDir, "Users", "admin.yaml")
+ assert.FileExists(t, nestedPath)
+
+ // Verify nested Files directory
+ filesDir := path.Join(dstDir, "Files")
+ info, err := os.Stat(filesDir)
+ require.NoError(t, err)
+ assert.True(t, info.IsDir())
+}
+
+func TestCopyFile(t *testing.T) {
+ dstDir := t.TempDir()
+ dstFile := path.Join(dstDir, "copied.yaml")
+
+ // Copy a single file from embedded config
+ err := copyFile("mobius/config/config.yaml", dstFile)
+ require.NoError(t, err)
+
+ // Verify file was copied correctly
+ assert.FileExists(t, dstFile)
+
+ // Verify file is not empty
+ info, err := os.Stat(dstFile)
+ require.NoError(t, err)
+ assert.Greater(t, info.Size(), int64(0))
+}
+
+func TestCopyFileErrors(t *testing.T) {
+ t.Run("source file does not exist", func(t *testing.T) {
+ dstDir := t.TempDir()
+ err := copyFile("nonexistent.txt", path.Join(dstDir, "dest.txt"))
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), "failed to open source file")
+ })
+
+ t.Run("destination directory does not exist", func(t *testing.T) {
+ err := copyFile("mobius/config/config.yaml", "/nonexistent/directory/dest.txt")
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), "failed to create destination file")
+ })
+}
+
+func TestCopyDirPermissions(t *testing.T) {
+ dstDir := t.TempDir()
+
+ err := copyDir("mobius/config", dstDir)
+ require.NoError(t, err)
+
+ // Check directory permissions
+ info, err := os.Stat(path.Join(dstDir, "Users"))
+ require.NoError(t, err)
+ assert.True(t, info.IsDir())
+
+ // Check that directory has reasonable permissions (at least readable/executable)
+ mode := info.Mode()
+ assert.True(t, mode&0400 != 0, "Directory should be readable")
+ assert.True(t, mode&0100 != 0, "Directory should be executable")
+}
+
+func TestFindConfigPath(t *testing.T) {
+ // Test function behavior by checking it returns one of the expected paths or fallback
+ t.Run("returns valid path", func(t *testing.T) {
+ result := findConfigPath()
+
+ // Should return either one of the search paths that exists, or "config" fallback
+ validPaths := append([]string{"config"}, mobius.ConfigSearchOrder...)
+
+ found := false
+ for _, validPath := range validPaths {
+ if result == validPath {
+ found = true
+ break
+ }
+ }
+
+ assert.True(t, found, "findConfigPath should return one of the valid paths or fallback, got: %s", result)
+ })
+
+ // Test directory vs file validation
+ t.Run("validates directory vs file", func(t *testing.T) {
+ // This test verifies the function logic but can't control system directories
+ // The function correctly validates that only directories are returned
+ result := findConfigPath()
+
+ // Verify result is an actual directory if it exists
+ if result != "config" {
+ info, err := os.Stat(result)
+ require.NoError(t, err, "Returned path should exist")
+ assert.True(t, info.IsDir(), "Returned path should be a directory")
+ }
+ })
+
+ // Test with existing directory
+ t.Run("finds existing directory", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ originalDir, err := os.Getwd()
+ require.NoError(t, err)
+ defer func() { _ = os.Chdir(originalDir) }()
+
+ err = os.Chdir(tmpDir)
+ require.NoError(t, err)
+
+ // Create a config directory
+ err = os.Mkdir("config", 0755)
+ require.NoError(t, err)
+
+ result := findConfigPath()
+ assert.Equal(t, "config", result)
+ })
+} \ No newline at end of file
diff --git a/cmd/mobius-hotline-server/mobius/config/config.yaml b/cmd/mobius-hotline-server/mobius/config/config.yaml
index 7cb7412..71b7e65 100644
--- a/cmd/mobius-hotline-server/mobius/config/config.yaml
+++ b/cmd/mobius-hotline-server/mobius/config/config.yaml
@@ -8,7 +8,7 @@ Description: A default configured Hotline server running Mobius
# * The banner must be under 256K (262,140 bytes specifically)
# * The standard size for a banner is 468 pixels wide and 60 pixels tall.
# * The banner must be saved in the same folder this file.
-# * The banner must be a jpg
+# * The banner must be a jpg or gif
BannerFile: "banner.jpg"
# Path to the Files directory, by default in a subdirectory of the config root named Files