weblug/cmd/weblug/weblug.go
Felix Niederwanger 03cb62aba7
Add timeouts
Adds read and write timeout configuration settings and allows to
configure a maximum acceptable header size.
2023-06-06 16:33:00 +02:00

237 lines
6.6 KiB
Go

/*
* weblug main program
*/
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
var cf Config
type Handler func(http.ResponseWriter, *http.Request)
func usage() {
fmt.Println("weblug is a webhook receiver")
fmt.Printf("Usage: %s [OPTIONS] YAML1[,YAML2...]\n\n", os.Args[0])
fmt.Println("OPTIONS")
fmt.Println(" -h, --help Print this help message")
fmt.Println()
fmt.Println("The program loads the given yaml files for webhook definitions")
}
// awaits SIGINT or SIGTERM
func awaitTerminationSignal() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
fmt.Println(sig)
os.Exit(1)
}()
}
// Perform sanity check on hooks
func sanityCheckHooks(hooks []Hook) error {
// Check UID and GID settings. When hooks have their own UID and GID settings, we need the main program to run as root (required for setgid/setuid)
uid := cf.Settings.UID
if uid == 0 {
uid = os.Getuid()
}
for _, hook := range hooks {
// If a hook sets a custom uid or gid, ensure we're running as root, otherwise print a warning
if hook.UID != 0 && uid != 0 {
fmt.Fprintf(os.Stderr, "Warning: Hook '%s' sets 'uid = %d' but we're not running as root\n", hook.Name, hook.UID)
}
if hook.GID != 0 && uid != 0 {
fmt.Fprintf(os.Stderr, "Warning: Hook '%s' sets 'gid = %d' but we're not running as root\n", hook.Name, hook.GID)
}
}
return nil
}
func main() {
cf.SetDefaults()
if len(os.Args) < 2 {
usage()
}
for _, arg := range os.Args[1:] {
if arg == "" {
continue
} else if arg == "-h" || arg == "--help" {
usage()
os.Exit(0)
} else {
if err := cf.LoadYAML((arg)); err != nil {
fmt.Fprintf(os.Stderr, "yaml error: %s\n", err)
os.Exit(1)
}
}
}
if len(cf.Hooks) == 0 {
fmt.Fprintf(os.Stderr, "error: no webhooks defined\n")
os.Exit(2)
}
// Sanity check
if err := sanityCheckHooks(cf.Hooks); err != nil {
fmt.Fprintf(os.Stderr, "hook sanity check failed: %s\n", err)
os.Exit(3)
}
// Drop privileges?
if cf.Settings.GID != 0 {
if err := syscall.Setgid(cf.Settings.GID); err != nil {
fmt.Fprintf(os.Stderr, "setgid failed: %s\n", err)
os.Exit(1)
}
}
if cf.Settings.UID != 0 {
if err := syscall.Setuid(cf.Settings.UID); err != nil {
fmt.Fprintf(os.Stderr, "setuid failed: %s\n", err)
os.Exit(1)
}
}
// Create default handlers
http.HandleFunc("/health", createHealthHandler())
http.HandleFunc("/health.json", createHealthHandler())
http.HandleFunc("/index", createDefaultHandler())
http.HandleFunc("/index.htm", createDefaultHandler())
http.HandleFunc("/index.html", createDefaultHandler())
http.HandleFunc("/robots.txt", createRobotsHandler())
// Register hooks
for i, hook := range cf.Hooks {
if hook.Route == "" {
fmt.Fprintf(os.Stderr, "Invalid hook %s: No route defined\n", hook.Name)
}
if hook.Concurrency < 1 {
hook.Concurrency = 1
}
log.Printf("Webhook %d: '%s' [%s] \"%s\"\n", i, hook.Name, hook.Route, hook.Command)
http.HandleFunc(hook.Route, createHandler(hook))
}
awaitTerminationSignal()
log.Printf("Launching webserver on %s", cf.Settings.BindAddress)
server := &http.Server{
Addr: cf.Settings.BindAddress,
ReadTimeout: time.Duration(cf.Settings.ReadTimeout) * time.Second,
WriteTimeout: time.Duration(cf.Settings.WriteTimeout) * time.Second,
MaxHeaderBytes: cf.Settings.MaxHeaderBytes,
}
err := server.ListenAndServe()
log.Fatal(err)
os.Exit(1)
}
// create a http handler function from the given hook
func createHandler(hook Hook) Handler {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("GET %s %s", r.RemoteAddr, hook.Name)
// Check if adresses are allowed or blocked
allowed, err := hook.IsAddressAllowed(r.RemoteAddr)
if err != nil {
log.Printf("ERR: Error checking for address permissions for hook \"%s\": %s", hook.Name, err)
w.WriteHeader(500)
fmt.Fprintf(w, "{\"status\":\"fail\",\"reason\":\"server error\"}")
return
}
if !allowed {
log.Printf("Blocked: '%s' for not allowed remote end %s", hook.Name, r.RemoteAddr)
// Return a 403 - Forbidden
w.WriteHeader(403)
fmt.Fprintf(w, "{\"status\":\"blocked\",\"reason\":\"address not allowed\"}")
return
}
// Check for basic auth, if enabled
if hook.HttpBasicAuth.Password != "" {
username, password, ok := r.BasicAuth()
if !ok {
// Return a 403 - Forbidden
w.WriteHeader(401)
fmt.Fprintf(w, "{\"status\":\"unauthorized\",\"message\":\"webhook requires authentication\"}")
return
}
if hook.HttpBasicAuth.Password != password || (hook.HttpBasicAuth.Username != "" && hook.HttpBasicAuth.Username != username) {
// Return a 403 - Forbidden
w.WriteHeader(403)
fmt.Fprintf(w, "{\"status\":\"blocked\",\"reason\":\"not authenticated\"}")
return
}
}
// Check for available slots
if !hook.TryLock() {
log.Printf("ERR: \"%s\" max concurrency reached", hook.Name)
// Return a 503 - Service Unavailable error
w.Header().Add("Content-Type", "application/json")
w.Header().Add("Retry-After", "120") // Suggest to retry after 2 minutes
w.WriteHeader(503)
fmt.Fprintf(w, "{\"status\":\"fail\",\"reason\":\"max concurrency reached\"}")
return
}
if hook.Background { // Execute command in background
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "{\"status\":\"ok\"}")
go func() {
defer hook.Unlock()
if err := hook.Run(); err != nil {
log.Printf("Hook \"%s\" failed: %s", hook.Name, err)
} else {
log.Printf("Hook \"%s\" completed", hook.Name)
}
}()
} else {
defer hook.Unlock()
if err := hook.Run(); err != nil {
log.Printf("ERR: \"%s\" exec failure: %s", hook.Name, err)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(500)
fmt.Fprintf(w, "{\"status\":\"fail\",\"reason\":\"program error\"}")
} else {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "{\"status\":\"ok\"}")
}
}
}
}
func createHealthHandler() Handler {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "{\"status\":\"ok\"}")
}
}
func createDefaultHandler() Handler {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
fmt.Fprintf(w, "weblug - webhook receiver program\nSee https://codeberg.org/grisu48/weblug\n")
}
}
func createRobotsHandler() Handler {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
fmt.Fprintf(w, "User-agent: *\nDisallow: /")
}
}