Files
dibs/internal/fetch/jar.go
T
Overlord 2175c0e5aa Add scheduler, rate limiting and headless mode.
Hard-coded 60s URL and 10s host floors with jitter and per-host
backoff, shared between dibs processes through a locked state file.
The scheduler shuffles due URLs each round and runs one worker per
host; 'dibs --headless' watches and logs JSON.
2026-10-14 09:04:15 +02:00

188 lines
4.5 KiB
Go

package fetch
import (
"encoding/json"
"errors"
"io/fs"
"maps"
"net/url"
"os"
"slices"
"strings"
"sync"
"time"
http "github.com/bogdanfinn/fhttp"
"github.com/bogdanfinn/fhttp/cookiejar"
"golang.org/x/net/publicsuffix"
"git.security-command.org/Overlord/dibs/internal/fsutil"
)
// Cookie is a stored cookie, in a form that survives a restart and can be
// handed to and from a browser.
type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
Domain string `json:"domain"` // the host for host-only cookies
HostOnly bool `json:"host_only,omitempty"`
Path string `json:"path"`
Expires time.Time `json:"expires,omitzero"` // zero for session cookies
Secure bool `json:"secure,omitempty"`
HTTPOnly bool `json:"http_only,omitempty"`
}
func (c Cookie) expired(now time.Time) bool {
return !c.Expires.IsZero() && !c.Expires.After(now)
}
// Jar is an RFC 6265 cookie jar that remembers every cookie by the host that
// set it, so the cookies can be saved, restored and exported per host.
type Jar struct {
mu sync.Mutex
jar *cookiejar.Jar
cookies map[string]map[string]Cookie // host -> domain|path|name -> cookie
now func() time.Time
}
func NewJar() *Jar {
jar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
return &Jar{
jar: jar,
cookies: map[string]map[string]Cookie{},
now: time.Now,
}
}
func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
j.mu.Lock()
defer j.mu.Unlock()
j.jar.SetCookies(u, cookies)
host := strings.ToLower(u.Hostname())
now := j.now()
for _, hc := range cookies {
c := Cookie{
Name: hc.Name,
Value: hc.Value,
Domain: strings.TrimPrefix(strings.ToLower(hc.Domain), "."),
Path: hc.Path,
Expires: hc.Expires,
Secure: hc.Secure,
HTTPOnly: hc.HttpOnly,
}
if c.Domain == "" { c.Domain, c.HostOnly = host, true }
if c.Path == "" || !strings.HasPrefix(c.Path, "/") { c.Path = defaultPath(u.Path) }
switch {
case hc.MaxAge < 0:
c.Expires = now
case hc.MaxAge > 0:
c.Expires = now.Add(time.Duration(hc.MaxAge) * time.Second)
default:
// No Max-Age: Expires decides.
}
j.store(host, c, now)
}
}
func (j *Jar) Cookies(u *url.URL) []*http.Cookie {
j.mu.Lock()
defer j.mu.Unlock()
return j.jar.Cookies(u)
}
// Export returns the live cookies of every host, sorted by name.
func (j *Jar) Export() map[string][]Cookie {
j.mu.Lock()
defer j.mu.Unlock()
now := j.now()
out := map[string][]Cookie{}
for host, byKey := range j.cookies {
for _, key := range slices.Sorted(maps.Keys(byKey)) {
if c := byKey[key]; !c.expired(now) { out[host] = append(out[host], c) }
}
}
return out
}
// Import adds cookies as if host had set them. Expired cookies are skipped.
func (j *Jar) Import(host string, cookies []Cookie) {
j.mu.Lock()
defer j.mu.Unlock()
host = strings.ToLower(host)
now := j.now()
for _, c := range cookies {
if c.expired(now) { continue }
hc := &http.Cookie{
Name: c.Name,
Value: c.Value,
Path: c.Path,
Expires: c.Expires,
Secure: c.Secure,
HttpOnly: c.HTTPOnly,
}
if !c.HostOnly { hc.Domain = c.Domain }
j.jar.SetCookies(&url.URL{Scheme: "https", Host: host, Path: c.Path}, []*http.Cookie{hc})
j.store(host, c, now)
}
}
// store records c for host, or forgets it when it has expired. Callers hold mu.
func (j *Jar) store(host string, c Cookie, now time.Time) {
key := c.Domain + "|" + c.Path + "|" + c.Name
if c.expired(now) {
delete(j.cookies[host], key)
return
}
if j.cookies[host] == nil { j.cookies[host] = map[string]Cookie{} }
j.cookies[host][key] = c
}
// Save writes the live cookies to path, readable only by the user.
func (j *Jar) Save(path string) error {
data, err := json.MarshalIndent(j.Export(), "", " ")
if err != nil { return err }
return fsutil.WriteFileAtomic(path, data, 0o600)
}
// Load imports the cookies saved at path. A missing file is not an error.
func (j *Jar) Load(path string) error {
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) { return nil }
if err != nil { return err }
var saved map[string][]Cookie
if err := json.Unmarshal(data, &saved); err != nil { return err }
for host, cookies := range saved { j.Import(host, cookies) }
return nil
}
// defaultPath is the RFC 6265 default-path of a request path.
func defaultPath(p string) string {
if p == "" || p[0] != '/' { return "/" }
i := strings.LastIndex(p, "/")
if i == 0 { return "/" }
return p[:i]
}