astraproxy/main.go

96 lines
2.6 KiB
Go
Raw Normal View History

2020-05-19 21:53:13 +02:00
package main
import (
"log"
"os"
"fmt"
"flag"
"time"
"net/http"
)
func perror(msg string) {
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, msg)
}
func arg_fail(msg string) {
perror(msg)
perror("Usage:")
flag.PrintDefaults()
os.Exit(2)
}
type CLIArgs struct {
bind_address string
2020-05-19 23:53:32 +02:00
auth string
2020-05-19 21:53:13 +02:00
verbosity int
timeout time.Duration
2020-05-24 23:16:56 +02:00
cert, key, cafile string
2020-05-19 21:53:13 +02:00
}
func parse_args() CLIArgs {
var args CLIArgs
flag.StringVar(&args.bind_address, "bind-address", ":8080", "HTTP proxy listen address")
2020-05-19 23:53:32 +02:00
flag.StringVar(&args.auth, "auth", "none://", "auth parameters")
2020-05-19 21:53:13 +02:00
flag.IntVar(&args.verbosity, "verbosity", 20, "logging verbosity " +
"(10 - debug, 20 - info, 30 - warning, 40 - error, 50 - critical)")
flag.DurationVar(&args.timeout, "timeout", 10 * time.Second, "timeout for network operations")
2020-05-24 00:18:01 +02:00
flag.StringVar(&args.cert, "cert", "", "enable TLS and use certificate")
flag.StringVar(&args.key, "key", "", "key for TLS certificate")
2020-05-24 23:16:56 +02:00
flag.StringVar(&args.cafile, "cafile", "", "CA file to authenticate clients with certificates")
2020-05-19 21:53:13 +02:00
flag.Parse()
return args
}
func run() int {
args := parse_args()
logWriter := NewLogWriter(os.Stderr)
defer logWriter.Close()
mainLogger := NewCondLogger(log.New(logWriter, "MAIN : ",
log.LstdFlags | log.Lshortfile),
args.verbosity)
proxyLogger := NewCondLogger(log.New(logWriter, "PROXY : ",
log.LstdFlags | log.Lshortfile),
args.verbosity)
2020-05-24 00:18:01 +02:00
2020-05-19 23:53:32 +02:00
auth, err := NewAuth(args.auth)
if err != nil {
mainLogger.Critical("Failed to instantiate auth provider: %v", err)
return 3
}
2020-05-24 00:18:01 +02:00
server := http.Server{
Addr: args.bind_address,
Handler: NewProxyHandler(args.timeout, auth, proxyLogger),
ErrorLog: log.New(logWriter, "HTTPSRV : ", log.LstdFlags | log.Lshortfile),
2020-05-24 13:45:49 +02:00
ReadTimeout: 0,
ReadHeaderTimeout: 0,
WriteTimeout: 0,
IdleTimeout: 0,
}
2020-05-24 00:18:01 +02:00
mainLogger.Info("Starting proxy server...")
if args.cert != "" {
2020-05-24 23:16:56 +02:00
cfg, err1 := makeServerTLSConfig(args.cert, args.key, args.cafile)
2020-05-24 00:18:01 +02:00
if err1 != nil {
mainLogger.Critical("TLS config construction failed: %v", err)
return 3
}
server.TLSConfig = cfg
err = server.ListenAndServeTLS("", "")
} else {
err = server.ListenAndServe()
}
2020-05-19 21:53:13 +02:00
mainLogger.Critical("Server terminated with a reason: %v", err)
mainLogger.Info("Shutting down...")
return 0
}
func main() {
os.Exit(run())
}