navid/veinsforge / a6e4a2c4dda7d505542765f593fbfc5a1644f5bc9f70483a480d45a39d8eca2c / internal/config/config.go
config.go
← internal/config · 6864 bytes · raw · download
package config
import (
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// Config holds the runtime configuration for veinsforge.
type Config struct {
Addr string
DataDir string
DBPath string
RepoRoot string
CacheDir string
AttachmentDir string
AvatarDir string
LogDir string
VNHome string
VNBin string
NativeListen string
NativeHost string
NativeCert string
NativeKey string
BaseURL string
TrustedProxies []string
SecureCookies bool
SessionTTL time.Duration
MaxUploadBytes int64
MaxAvatarBytes int64
UserQuotaBytes int64
ReadHeaderTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
MaxConcurrent int
RateLimitPerSec float64
RateLimitBurst int
AuthLimitPerMin int
WriteLimitPerMin int
RegistrationOpen bool
AdminUser string
AdminPassword string
}
// Load reads the environment, applies defaults, and normalizes paths. The
// optional command-line flags in overrides take precedence.
func Load(overrides map[string]string) (Config, error) {
c := Config{
Addr: env("VEINSFORGE_ADDR", "127.0.0.1:8080"),
DataDir: env("VEINSFORGE_DATA", "./data"),
VNBin: env("VEINSFORGE_VN_BIN", "vn"),
NativeListen: env("VEINSFORGE_NATIVE_LISTEN", "127.0.0.1:7419"),
NativeHost: env("VEINSFORGE_NATIVE_HOST", ""),
NativeCert: os.Getenv("VEINSFORGE_NATIVE_CERT"),
NativeKey: os.Getenv("VEINSFORGE_NATIVE_KEY"),
BaseURL: env("VEINSFORGE_BASE_URL", "http://127.0.0.1:8080"),
TrustedProxies: splitCSV(env("VEINSFORGE_TRUSTED_PROXIES", "127.0.0.1/32,::1/128")),
SessionTTL: time.Duration(envInt("VEINSFORGE_SESSION_DAYS", 30)) * 24 * time.Hour,
MaxUploadBytes: int64(envInt("VEINSFORGE_MAX_UPLOAD_MB", 10)) << 20,
MaxAvatarBytes: int64(envInt("VEINSFORGE_MAX_AVATAR_MB", 2)) << 20,
UserQuotaBytes: int64(envInt("VEINSFORGE_USER_QUOTA_MB", 50)) << 20,
ReadHeaderTimeout: time.Duration(envInt("VEINSFORGE_READ_HEADER_SECONDS", 5)) * time.Second,
ReadTimeout: time.Duration(envInt("VEINSFORGE_READ_SECONDS", 60)) * time.Second,
WriteTimeout: time.Duration(envInt("VEINSFORGE_WRITE_SECONDS", 60)) * time.Second,
IdleTimeout: time.Duration(envInt("VEINSFORGE_IDLE_SECONDS", 90)) * time.Second,
MaxConcurrent: envInt("VEINSFORGE_MAX_CONCURRENT", 256),
RateLimitPerSec: envFloat("VEINSFORGE_RATE_PER_SECOND", 25),
RateLimitBurst: envInt("VEINSFORGE_RATE_BURST", 60),
AuthLimitPerMin: envInt("VEINSFORGE_AUTH_PER_MINUTE", 12),
WriteLimitPerMin: envInt("VEINSFORGE_WRITE_PER_MINUTE", 40),
RegistrationOpen: envBool("VEINSFORGE_REGISTRATION_OPEN", true),
AdminUser: os.Getenv("VEINSFORGE_ADMIN_USER"),
AdminPassword: os.Getenv("VEINSFORGE_ADMIN_PASSWORD"),
}
for k, v := range overrides {
if v == "" {
continue
}
switch k {
case "addr":
c.Addr = v
case "data":
c.DataDir = v
case "base-url":
c.BaseURL = v
case "vn-bin":
c.VNBin = v
case "native-listen":
c.NativeListen = v
case "native-host":
c.NativeHost = v
case "native-cert":
c.NativeCert = v
case "native-key":
c.NativeKey = v
}
}
if err := c.finalize(); err != nil {
return Config{}, err
}
return c, nil
}
func (c *Config) finalize() error {
abs, err := filepath.Abs(c.DataDir)
if err != nil {
return err
}
c.DataDir = abs
c.DBPath = filepath.Join(abs, "veinsforge.db")
c.RepoRoot = filepath.Join(abs, "repos")
c.CacheDir = filepath.Join(abs, "cache")
c.AttachmentDir = filepath.Join(abs, "attachments")
c.AvatarDir = filepath.Join(abs, "avatars")
c.LogDir = filepath.Join(abs, "logs")
c.VNHome = filepath.Join(abs, "home")
if c.NativeCert == "" {
c.NativeCert = filepath.Join(abs, "native", "tls.crt")
}
if c.NativeKey == "" {
c.NativeKey = filepath.Join(abs, "native", "tls.key")
}
if c.SessionTTL <= 0 {
c.SessionTTL = 30 * 24 * time.Hour
}
if c.NativeHost == "" {
if u, err := url.Parse(c.BaseURL); err == nil && u.Hostname() != "" {
c.NativeHost = u.Hostname()
} else {
c.NativeHost = "localhost"
}
}
c.SecureCookies = strings.HasPrefix(strings.ToLower(c.BaseURL), "https://")
if v, ok := os.LookupEnv("VEINSFORGE_SECURE_COOKIES"); ok {
c.SecureCookies = envBoolValue(v, c.SecureCookies)
}
if c.MaxConcurrent < 16 {
c.MaxConcurrent = 16
}
if c.RateLimitPerSec <= 0 {
c.RateLimitPerSec = 25
}
if c.RateLimitBurst <= 0 {
c.RateLimitBurst = 60
}
if c.UserQuotaBytes < 0 {
c.UserQuotaBytes = 0
}
return nil
}
// EnsureDirs creates the service data directories with restrictive modes.
func (c Config) EnsureDirs() error {
dirs := []string{
c.DataDir, c.RepoRoot, c.CacheDir, c.AttachmentDir, c.AvatarDir,
c.LogDir, c.VNHome, filepath.Dir(c.NativeCert),
filepath.Join(c.VNHome, ".config", "veins", "keys"),
}
for _, d := range dirs {
if err := os.MkdirAll(d, 0o700); err != nil {
return fmt.Errorf("create %s: %w", d, err)
}
}
return nil
}
// NativeAddress returns the advertised host:port for the native protocol.
func (c Config) NativeAddress() string {
listen := c.NativeListen
host, port, err := net.SplitHostPort(listen)
if err != nil {
return listen
}
if host == "" || host == "0.0.0.0" || host == "::" {
host = c.NativeHost
}
return net.JoinHostPort(host, port)
}
// NativeURL returns the clone URL for a repository.
func (c Config) NativeURL(owner, name string) string {
return fmt.Sprintf("veins://%s/%s/%s", c.NativeAddress(), owner, name)
}
func env(key, def string) string {
if v, ok := os.LookupEnv(key); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
return def
}
func envInt(key string, def int) int {
v, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(v) == "" {
return def
}
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil {
return def
}
return n
}
func envFloat(key string, def float64) float64 {
v, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(v) == "" {
return def
}
n, err := strconv.ParseFloat(strings.TrimSpace(v), 64)
if err != nil {
return def
}
return n
}
func envBool(key string, def bool) bool {
v, ok := os.LookupEnv(key)
if !ok {
return def
}
return envBoolValue(v, def)
}
func envBoolValue(v string, def bool) bool {
switch strings.ToLower(strings.TrimSpace(v)) {
case "1", "true", "yes", "on":
return true
case "0", "false", "no", "off":
return false
default:
return def
}
}
func splitCSV(s string) []string {
var out []string
for _, part := range strings.Split(s, ",") {
if p := strings.TrimSpace(part); p != "" {
out = append(out, p)
}
}
return out
}