Files
mctf/delamain/guard/slices.go
T

170 lines
4.9 KiB
Go

package main
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"time"
)
type noteHandle struct {
Slot uint64 `json:"base_slot"`
Generation uint64 `json:"base_generation"`
}
type exportedNote struct {
tripID string
data string
created time.Time
}
const noteLifetime = 2 * time.Minute
const poolSlots = 32
func (g *apiGuard) rememberExport(response *http.Response) error {
if response.Request.URL.Path != "/api/packages" || response.StatusCode != http.StatusOK {
return nil
}
const maxExport = 1 << 20
body, err := io.ReadAll(io.LimitReader(response.Body, maxExport+1))
response.Body.Close()
if err != nil {
return err
}
if len(body) > maxExport {
return errors.New("export response too large")
}
response.Body = io.NopCloser(bytes.NewReader(body))
var result struct {
Slot *uint64 `json:"note_slot"`
Generation uint64 `json:"note_generation"`
Size int `json:"note_size"`
Data string `json:"data"`
}
tripID, _ := response.Request.Context().Value(exportSourceKey{}).(string)
if json.Unmarshal(body, &result) != nil || !manifestTripID.MatchString(tripID) || result.Slot == nil || *result.Slot >= poolSlots ||
result.Generation == 0 || result.Size != len(result.Data) || result.Size > 16<<10 {
return nil
}
key := noteHandle{Slot: *result.Slot, Generation: result.Generation}
now := time.Now()
g.notesMu.Lock()
defer g.notesMu.Unlock()
if len(g.notes) >= 1024 {
var oldestKey noteHandle
var oldest time.Time
for k, note := range g.notes {
if now.Sub(note.created) >= noteLifetime {
delete(g.notes, k)
} else if oldest.IsZero() || note.created.Before(oldest) {
oldestKey, oldest = k, note.created
}
}
if len(g.notes) >= 1024 {
delete(g.notes, oldestKey)
}
}
g.notes[key] = exportedNote{tripID: tripID, data: result.Data, created: now}
return nil
}
func (g *apiGuard) readSlice(w http.ResponseWriter, r *http.Request) {
var request struct {
noteHandle
Offset uint64 `json:"offset"`
Length uint64 `json:"length"`
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4096))
if err != nil || json.Unmarshal(body, &request) != nil || request.Generation == 0 {
writeError(w, http.StatusBadRequest, "invalid slice request")
return
}
if r.Header.Get("Authorization") == "" {
writeError(w, http.StatusUnauthorized, "authentication required")
return
}
if request.Slot >= poolSlots {
writeJSON(w, http.StatusOK, map[string]any{"status": -1, "error": "invalid-slot"})
return
}
g.notesMu.Lock()
note, found := g.notes[request.noteHandle]
g.notesMu.Unlock()
if !found || time.Since(note.created) >= noteLifetime {
writeJSON(w, http.StatusOK, map[string]any{"status": -2, "error": "stale-generation"})
return
}
if !g.requireTripOwner(w, r, note.tripID) {
return
}
size := uint64(len(note.data))
if request.Length == 0 || request.Offset >= size || request.Length > size-request.Offset {
writeJSON(w, http.StatusOK, map[string]any{"status": -4, "error": "out-of-bounds"})
return
}
data := note.data[request.Offset : request.Offset+request.Length]
writeJSON(w, http.StatusOK, struct {
Status int `json:"status"`
Generation uint64 `json:"generation"`
Data string `json:"data,omitempty"`
}{Status: 0, Generation: request.Generation, Data: data})
}
func (g *apiGuard) poolMetadata(w http.ResponseWriter, r *http.Request) {
target := *g.upstream
target.Path = "/api/trips"
request, err := http.NewRequestWithContext(r.Context(), http.MethodGet, target.String(), nil)
if err != nil {
writeError(w, http.StatusBadGateway, "service unavailable")
return
}
request.Header.Set("Authorization", r.Header.Get("Authorization"))
response, err := g.client.Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "service unavailable")
return
}
defer response.Body.Close()
if response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden {
writeError(w, response.StatusCode, "authentication required")
return
}
var owned struct {
Trips []struct {
ID string `json:"id"`
} `json:"trips"`
}
if response.StatusCode != http.StatusOK || json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&owned) != nil {
writeError(w, http.StatusBadGateway, "service unavailable")
return
}
tripIDs := make(map[string]bool, len(owned.Trips))
for _, trip := range owned.Trips {
tripIDs[trip.ID] = true
}
type slotMetadata struct {
Slot int `json:"slot"`
Type string `json:"type"`
InUse bool `json:"in_use"`
}
pool := make([]slotMetadata, poolSlots)
for i := range pool {
pool[i] = slotMetadata{Slot: i, Type: "free"}
}
// Report only slots associated with the caller's recent exports.
g.notesMu.Lock()
for handle, note := range g.notes {
if tripIDs[note.tripID] && time.Since(note.created) < noteLifetime {
pool[handle.Slot].Type = "note"
}
}
g.notesMu.Unlock()
writeJSON(w, http.StatusOK, struct {
Pool []slotMetadata `json:"pool"`
}{Pool: pool})
}