fork/gdu

git clone https://git.julia.blue/fork/gdu

Daniel Mildefeat: add web UI (#617)d672bf4

subvolume
2.4 KiB90 linesraw
1package webui
2
3import (
4	"context"
5	"errors"
6	"fmt"
7	"io"
8	"net"
9	"net/http"
10	"os"
11	"os/signal"
12	"strings"
13	"syscall"
14	"time"
15
16	log "github.com/sirupsen/logrus"
17)
18
19// StartUILoop binds the listener, prints the URL, optionally opens the browser,
20// and serves the SPA and API until interrupted. It blocks, mirroring the other
21// frontends' StartUILoop contract.
22func (ui *UI) StartUILoop() error {
23	listener, err := net.Listen("tcp", ui.listenAddr)
24	if err != nil {
25		return fmt.Errorf("binding %s: %w", ui.listenAddr, err)
26	}
27
28	url := "http://" + listener.Addr().String()
29	fmt.Fprintf(ui.output, "Gdu web UI running at %s\n", url)
30	warnIfRemote(ui.output, listener.Addr())
31
32	if ui.openBrowser {
33		if err := openBrowser(url, ui.browserCmd); err != nil {
34			log.Printf("webui: could not open browser: %s", err)
35			fmt.Fprintf(ui.output, "Open %s in your browser.\n", url)
36		}
37	}
38
39	srv := &http.Server{
40		Handler:           ui.routes(),
41		ReadHeaderTimeout: 10 * time.Second,
42	}
43
44	shutdownDone := make(chan struct{})
45	go func() {
46		sig := make(chan os.Signal, 1)
47		signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
48		<-sig
49		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
50		defer cancel()
51		if err := srv.Shutdown(ctx); err != nil {
52			log.Printf("webui: shutdown: %s", err)
53		}
54		close(shutdownDone)
55	}()
56
57	err = srv.Serve(listener)
58	if errors.Is(err, http.ErrServerClosed) {
59		<-shutdownDone
60		return nil
61	}
62	return err
63}
64
65// routes builds a dedicated mux (never the shared http.DefaultServeMux, which
66// is deliberately reset elsewhere to keep pprof handlers isolated).
67func (ui *UI) routes() *http.ServeMux {
68	mux := http.NewServeMux()
69	mux.HandleFunc("/api/v1/status", ui.handleStatus)
70	mux.HandleFunc("/api/v1/nodes", ui.handleNodes)
71	mux.HandleFunc("/api/v1/devices", ui.handleDevices)
72	mux.HandleFunc("/api/v1/events", ui.handleEvents)
73	mux.Handle("/", staticHandler())
74	return mux
75}
76
77// warnIfRemote prints a security warning when the server is not bound to a
78// loopback address, since directory names and sizes can be sensitive.
79func warnIfRemote(w io.Writer, addr net.Addr) {
80	host := addr.String()
81	if i := strings.LastIndex(host, ":"); i >= 0 {
82		host = host[:i]
83	}
84	ip := net.ParseIP(strings.Trim(host, "[]"))
85	if ip != nil && ip.IsLoopback() {
86		return
87	}
88	fmt.Fprintln(w, "WARNING: the web UI is reachable from other hosts on the network.")
89	fmt.Fprintln(w, "         It exposes file names and sizes with no authentication.")
90}