|
| 1 | +// Command piguard-gateway is a small HTTP front end for the PIGuard daemon. |
| 2 | +// It forwards requests to the daemon's Unix socket and returns the JSON |
| 3 | +// reply, so odek's HTTP-based guard client can reach the socket-only daemon |
| 4 | +// over the compose network. |
| 5 | +// |
| 6 | +// The daemon speaks newline-delimited JSON ({"text":...}, {"long":...}, |
| 7 | +// {"texts":[...]}), which is exactly what odek's piguard client sends, so |
| 8 | +// JSON bodies are forwarded verbatim. A non-JSON body is treated as raw text |
| 9 | +// and wrapped as {"text": <body>} for convenience (curl -d 'some text'). |
| 10 | +// |
| 11 | +// Endpoints: |
| 12 | +// |
| 13 | +// GET /healthz liveness — checks the daemon socket is reachable |
| 14 | +// POST /detect {"text": "..."} (or raw text) |
| 15 | +// POST /long {"long": "..."} (or raw text) |
| 16 | +// POST /raw {"texts": [...]} (batch; or any daemon JSON line) |
| 17 | +// |
| 18 | +// Note: the daemon dispatches on the JSON keys, not the HTTP path; the paths |
| 19 | +// exist only to mirror odek's client configuration. |
| 20 | +package main |
| 21 | + |
| 22 | +import ( |
| 23 | + "bufio" |
| 24 | + "bytes" |
| 25 | + "encoding/json" |
| 26 | + "flag" |
| 27 | + "io" |
| 28 | + "log" |
| 29 | + "net" |
| 30 | + "net/http" |
| 31 | + "time" |
| 32 | +) |
| 33 | + |
| 34 | +// maxBody caps a request body, mirroring the daemon's 1 MiB request limit |
| 35 | +// (with a little headroom for JSON framing). |
| 36 | +const maxBody = 1 << 20 |
| 37 | + |
| 38 | +type gateway struct { |
| 39 | + socket string |
| 40 | +} |
| 41 | + |
| 42 | +// forward sends one newline-delimited request to the daemon and returns its |
| 43 | +// single-line reply. |
| 44 | +func (g *gateway) forward(line []byte) ([]byte, error) { |
| 45 | + conn, err := net.DialTimeout("unix", g.socket, 2*time.Second) |
| 46 | + if err != nil { |
| 47 | + return nil, err |
| 48 | + } |
| 49 | + defer conn.Close() |
| 50 | + _ = conn.SetDeadline(time.Now().Add(60 * time.Second)) |
| 51 | + |
| 52 | + if _, err := conn.Write(append(bytes.TrimRight(line, "\n"), '\n')); err != nil { |
| 53 | + return nil, err |
| 54 | + } |
| 55 | + resp, err := bufio.NewReader(conn).ReadBytes('\n') |
| 56 | + if err != nil && len(resp) == 0 { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + return resp, nil |
| 60 | +} |
| 61 | + |
| 62 | +// daemonLine converts an HTTP request body into one daemon protocol line. |
| 63 | +// Bodies that already are daemon protocol JSON (carrying a text, long, or |
| 64 | +// texts key) pass through verbatim; anything else is wrapped as raw text. |
| 65 | +func daemonLine(body []byte) ([]byte, error) { |
| 66 | + trimmed := bytes.TrimSpace(body) |
| 67 | + var probe map[string]json.RawMessage |
| 68 | + if err := json.Unmarshal(trimmed, &probe); err == nil { |
| 69 | + for _, key := range []string{"text", "long", "texts"} { |
| 70 | + if _, ok := probe[key]; ok { |
| 71 | + return trimmed, nil |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + return json.Marshal(map[string]string{"text": string(body)}) |
| 76 | +} |
| 77 | + |
| 78 | +func (g *gateway) handleDetect(w http.ResponseWriter, r *http.Request) { |
| 79 | + if r.Method != http.MethodPost { |
| 80 | + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) |
| 81 | + return |
| 82 | + } |
| 83 | + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBody)) |
| 84 | + if err != nil { |
| 85 | + http.Error(w, "request too large", http.StatusRequestEntityTooLarge) |
| 86 | + return |
| 87 | + } |
| 88 | + line, err := daemonLine(body) |
| 89 | + if err != nil { |
| 90 | + http.Error(w, err.Error(), http.StatusBadRequest) |
| 91 | + return |
| 92 | + } |
| 93 | + resp, err := g.forward(line) |
| 94 | + if err != nil { |
| 95 | + http.Error(w, err.Error(), http.StatusBadGateway) |
| 96 | + return |
| 97 | + } |
| 98 | + w.Header().Set("Content-Type", "application/json") |
| 99 | + _, _ = w.Write(resp) |
| 100 | +} |
| 101 | + |
| 102 | +func (g *gateway) handleHealth(w http.ResponseWriter, r *http.Request) { |
| 103 | + conn, err := net.DialTimeout("unix", g.socket, 2*time.Second) |
| 104 | + if err != nil { |
| 105 | + http.Error(w, "daemon unreachable: "+err.Error(), http.StatusServiceUnavailable) |
| 106 | + return |
| 107 | + } |
| 108 | + conn.Close() |
| 109 | + _, _ = w.Write([]byte("ok\n")) |
| 110 | +} |
| 111 | + |
| 112 | +func main() { |
| 113 | + addr := flag.String("addr", ":8080", "HTTP listen address") |
| 114 | + socket := flag.String("socket", "/run/piguard/piguard.sock", "PIGuard daemon Unix socket") |
| 115 | + flag.Parse() |
| 116 | + |
| 117 | + g := &gateway{socket: *socket} |
| 118 | + mux := http.NewServeMux() |
| 119 | + mux.HandleFunc("/healthz", g.handleHealth) |
| 120 | + mux.HandleFunc("/detect", g.handleDetect) |
| 121 | + mux.HandleFunc("/long", g.handleDetect) |
| 122 | + mux.HandleFunc("/raw", g.handleDetect) |
| 123 | + |
| 124 | + log.Printf("piguard-gateway: listening on %s, daemon socket %s", *addr, *socket) |
| 125 | + log.Fatal(http.ListenAndServe(*addr, mux)) |
| 126 | +} |
0 commit comments