A friend's server works out the peaks of a track in a shared library and gives
them to a signed friend (GET /peer/tracks/{id}/peaks). This server asks for them
and passes them on to the listener after checking them: 1 to 1000 levels from 0
to 255, as many as the count says (GET /friends/{friend}/tracks/{id}/peaks). The
player uses it for a friend's track, so its bar is no longer flat.
869 lines
27 KiB
Go
869 lines
27 KiB
Go
package federation
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ed25519"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"mime"
|
|
"net"
|
|
"net/http"
|
|
"net/netip"
|
|
"net/url"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
const (
|
|
inviteTTL = 24 * time.Hour
|
|
invitePrefix = "sonda1."
|
|
maxNameRunes = 60
|
|
maxAddressLen = 300
|
|
maxCodeLen = 64
|
|
pairAttempts = 10 // pairing requests allowed in one window, from anyone
|
|
pairWindow = time.Minute
|
|
keyIDHexLength = 16
|
|
|
|
clockSkew = 2 * time.Minute // how far a friend's clock may be from this one
|
|
minNonceLen = 16
|
|
maxNonceLen = 64
|
|
requestPruneEvery = 100 // the log is tidied every this many requests
|
|
requestKeep = 7 * 24 * time.Hour
|
|
requestsShown = 50
|
|
)
|
|
|
|
// Sends is what an admin is told before turning federation on.
|
|
const Sends = "Nothing is sent until an admin makes an invite or uses one. A friend's server is then sent: this " +
|
|
"server's name and address, its public key, and the id of each track or cover its listeners open. It never " +
|
|
"learns who listens. Shared libraries can be played, and in practice copied, by the friend's listeners."
|
|
|
|
// PairRequest is what the server that uses an invite sends to the one that made it.
|
|
type PairRequest struct {
|
|
Code string
|
|
Name string
|
|
Address string
|
|
PublicKey ed25519.PublicKey
|
|
}
|
|
|
|
// PairReply is what the server that made the invite answers.
|
|
type PairReply struct {
|
|
Name string
|
|
Address string
|
|
PublicKey ed25519.PublicKey
|
|
}
|
|
|
|
// Remote talks to another Sonda server. It is only asked when an admin pastes an invite.
|
|
type Remote interface {
|
|
// Pair sends the request to the server at address. It returns ErrRefused when that server turned the invite down,
|
|
// and ErrUnreachable when it did not answer as a Sonda server with federation on.
|
|
Pair(ctx context.Context, address string, req PairRequest) (PairReply, error)
|
|
// Info asks the server at address who it is, with a request signed by this server. It returns ErrNotApproved
|
|
// when the other admin has not approved yet, ErrNotFriend when that server does not take this one for a friend,
|
|
// and ErrUnreachable when it did not answer as a Sonda server.
|
|
Info(ctx context.Context, address string, auth Auth) (Info, error)
|
|
// Get sends a signed GET of uri (the path from /api/v1/peer on, and the query) to the server at address and
|
|
// returns its status and body, whatever the status. An error means no answer was had.
|
|
Get(ctx context.Context, address, uri string, auth Auth) (status int, body []byte, err error)
|
|
// Open sends a signed GET like Get, with these request headers, and returns the answer with its body still open
|
|
// for the caller to read and close: it is for audio and pictures, which are too big to read whole. There is no
|
|
// overall time limit (a song takes as long as it takes), only one for the friend to start answering.
|
|
Open(ctx context.Context, address, uri string, auth Auth, header http.Header) (*http.Response, error)
|
|
}
|
|
|
|
// Auth is what signs a request to a friend: this server's key.
|
|
type Auth struct {
|
|
KeyID string
|
|
Key ed25519.PrivateKey
|
|
}
|
|
|
|
// Info is what a server says of itself to a friend.
|
|
type Info struct {
|
|
Name string
|
|
SharedLibraries int
|
|
}
|
|
|
|
// Status is what an admin sees: the settings without the private key, and the friends.
|
|
type Status struct {
|
|
Enabled bool
|
|
Name string // the one saved, or the host name
|
|
Address string
|
|
KeyID string // empty until federation was first turned on
|
|
Friends []Friend
|
|
Sends string
|
|
|
|
MaxStreams int // parallel streams one friend may have
|
|
MaxKiBPerSec int // KiB a second one friend may take; 0 means no limit
|
|
}
|
|
|
|
// Patch changes some settings. A nil field is left alone; an empty Address clears it and an empty Name goes back to the host name.
|
|
type Patch struct {
|
|
Enabled *bool
|
|
Name *string
|
|
Address *string
|
|
|
|
MaxStreams *int
|
|
MaxKiBPerSec *int
|
|
}
|
|
|
|
// Invite is what an admin gives to the other one, once.
|
|
type Invite struct {
|
|
Text string
|
|
ExpiresAt time.Time
|
|
}
|
|
|
|
// Service holds the rules of federation.
|
|
type Service struct {
|
|
store Store
|
|
remote Remote
|
|
now func() time.Time
|
|
host func() string
|
|
|
|
sleep func(context.Context, time.Duration) error
|
|
|
|
mu sync.Mutex // an update reads then writes; the lists below are shared
|
|
attempts []time.Time
|
|
seen map[string]time.Time // nonces of signed requests, until they could not be replayed any more
|
|
streams map[int64]int // streams open for each friend
|
|
pacers map[int64]*pacer
|
|
logged int
|
|
}
|
|
|
|
// NewService builds a Service. remote may be nil in a server that never pastes an invite (tests).
|
|
func NewService(store Store, remote Remote) *Service {
|
|
return &Service{
|
|
store: store, remote: remote, now: time.Now, host: hostName, sleep: sleepFor,
|
|
seen: map[string]time.Time{}, streams: map[int64]int{}, pacers: map[int64]*pacer{},
|
|
}
|
|
}
|
|
|
|
func hostName() string {
|
|
if h, err := os.Hostname(); err == nil && strings.TrimSpace(h) != "" {
|
|
return h
|
|
}
|
|
return "sonda"
|
|
}
|
|
|
|
func (s *Service) load(ctx context.Context) (Settings, error) {
|
|
set, found, err := s.store.Settings(ctx)
|
|
if err != nil {
|
|
return Settings{}, fmt.Errorf("read federation settings: %w", err)
|
|
}
|
|
if !found {
|
|
set.MaxStreams, set.MaxKiBPerSec = DefaultMaxStreams, DefaultMaxKiBPerSec
|
|
}
|
|
return set, nil
|
|
}
|
|
|
|
func (s *Service) name(set Settings) string {
|
|
if set.Name != "" {
|
|
return set.Name
|
|
}
|
|
return s.host()
|
|
}
|
|
|
|
// Status returns the settings and the friends.
|
|
func (s *Service) Status(ctx context.Context) (Status, error) {
|
|
set, err := s.load(ctx)
|
|
if err != nil {
|
|
return Status{}, err
|
|
}
|
|
friends, err := s.store.Friends(ctx)
|
|
if err != nil {
|
|
return Status{}, fmt.Errorf("list friends: %w", err)
|
|
}
|
|
st := Status{
|
|
Enabled: set.Enabled, Name: s.name(set), Address: set.Address, Friends: friends, Sends: Sends,
|
|
MaxStreams: set.MaxStreams, MaxKiBPerSec: set.MaxKiBPerSec,
|
|
}
|
|
if set.PublicKey != nil {
|
|
st.KeyID = KeyID(set.PublicKey)
|
|
}
|
|
return st, nil
|
|
}
|
|
|
|
// Update changes the settings. The key pair is made the first time federation is turned on and is kept after that.
|
|
func (s *Service) Update(ctx context.Context, p Patch) (Status, error) {
|
|
s.mu.Lock()
|
|
set, err := s.load(ctx)
|
|
if err != nil {
|
|
s.mu.Unlock()
|
|
return Status{}, err
|
|
}
|
|
if p.Name != nil {
|
|
name := strings.TrimSpace(*p.Name)
|
|
if err := checkText(name, true); err != nil {
|
|
s.mu.Unlock()
|
|
return Status{}, err
|
|
}
|
|
set.Name = name
|
|
}
|
|
if p.Address != nil {
|
|
addr := strings.TrimSpace(*p.Address)
|
|
if addr != "" {
|
|
if addr, err = normalizeAddress(addr); err != nil {
|
|
s.mu.Unlock()
|
|
return Status{}, err
|
|
}
|
|
}
|
|
set.Address = addr
|
|
}
|
|
if p.MaxStreams != nil {
|
|
if *p.MaxStreams < 1 || *p.MaxStreams > maxStreamsCap {
|
|
s.mu.Unlock()
|
|
return Status{}, fmt.Errorf("%w: streams are 1 to %d", ErrInvalidInput, maxStreamsCap)
|
|
}
|
|
set.MaxStreams = *p.MaxStreams
|
|
}
|
|
if p.MaxKiBPerSec != nil {
|
|
if k := *p.MaxKiBPerSec; k != 0 && (k < minKiBPerSec || k > maxKiBPerSec) {
|
|
s.mu.Unlock()
|
|
return Status{}, fmt.Errorf("%w: the rate is 0 (no limit) or %d to %d KiB a second", ErrInvalidInput, minKiBPerSec, maxKiBPerSec)
|
|
}
|
|
set.MaxKiBPerSec = *p.MaxKiBPerSec
|
|
}
|
|
if p.Enabled != nil {
|
|
set.Enabled = *p.Enabled
|
|
if set.Enabled && set.PublicKey == nil {
|
|
if set.PublicKey, set.PrivateKey, err = ed25519.GenerateKey(rand.Reader); err != nil {
|
|
s.mu.Unlock()
|
|
return Status{}, fmt.Errorf("make the server key: %w", err)
|
|
}
|
|
}
|
|
}
|
|
set.UpdatedAt = s.now()
|
|
err = s.store.SaveSettings(ctx, set)
|
|
s.mu.Unlock()
|
|
if err != nil {
|
|
return Status{}, fmt.Errorf("save federation settings: %w", err)
|
|
}
|
|
return s.Status(ctx)
|
|
}
|
|
|
|
// ready returns the settings of a server that can pair: on, with a key and an address.
|
|
func (s *Service) ready(ctx context.Context) (Settings, error) {
|
|
set, err := s.load(ctx)
|
|
if err != nil {
|
|
return Settings{}, err
|
|
}
|
|
if !set.Enabled || set.PublicKey == nil {
|
|
return Settings{}, ErrOff
|
|
}
|
|
if set.Address == "" {
|
|
return Settings{}, ErrNoAddress
|
|
}
|
|
return set, nil
|
|
}
|
|
|
|
func hashCode(code string) string {
|
|
sum := sha256.Sum256([]byte(code))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
type invitePayload struct {
|
|
Address string `json:"a"`
|
|
Code string `json:"c"`
|
|
KeyID string `json:"k"`
|
|
}
|
|
|
|
// CreateInvite makes an invite that works once, for 24 hours. Only a hash of its code is kept.
|
|
func (s *Service) CreateInvite(ctx context.Context) (Invite, error) {
|
|
set, err := s.ready(ctx)
|
|
if err != nil {
|
|
return Invite{}, err
|
|
}
|
|
raw := make([]byte, 20)
|
|
if _, err := rand.Read(raw); err != nil {
|
|
return Invite{}, fmt.Errorf("make an invite code: %w", err)
|
|
}
|
|
code := base64.RawURLEncoding.EncodeToString(raw)
|
|
now := s.now()
|
|
expires := now.Add(inviteTTL)
|
|
if err := s.store.AddInvite(ctx, hashCode(code), now, expires); err != nil {
|
|
return Invite{}, fmt.Errorf("store the invite: %w", err)
|
|
}
|
|
body, err := json.Marshal(invitePayload{Address: set.Address, Code: code, KeyID: KeyID(set.PublicKey)})
|
|
if err != nil {
|
|
return Invite{}, err
|
|
}
|
|
return Invite{Text: invitePrefix + base64.RawURLEncoding.EncodeToString(body), ExpiresAt: expires}, nil
|
|
}
|
|
|
|
func parseInvite(text string) (invitePayload, error) {
|
|
var p invitePayload
|
|
rest, ok := strings.CutPrefix(strings.TrimSpace(text), invitePrefix)
|
|
if !ok {
|
|
return p, ErrInvalidInvite
|
|
}
|
|
body, err := base64.RawURLEncoding.DecodeString(rest)
|
|
if err != nil || json.Unmarshal(body, &p) != nil {
|
|
return p, ErrInvalidInvite
|
|
}
|
|
if p.Code == "" || len(p.Code) > maxCodeLen || len(p.KeyID) != keyIDHexLength {
|
|
return p, ErrInvalidInvite
|
|
}
|
|
if _, err := hex.DecodeString(p.KeyID); err != nil {
|
|
return p, ErrInvalidInvite
|
|
}
|
|
if p.Address, err = normalizeAddress(p.Address); err != nil {
|
|
return p, ErrInvalidInvite
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// Redeem uses an invite made by another server: it asks that server to pair, checks that the key that comes back
|
|
// is the one the invite names, and keeps it as a friend that waits for the other admin's approval.
|
|
func (s *Service) Redeem(ctx context.Context, text string) (Friend, error) {
|
|
set, err := s.ready(ctx)
|
|
if err != nil {
|
|
return Friend{}, err
|
|
}
|
|
inv, err := parseInvite(text)
|
|
if err != nil {
|
|
return Friend{}, err
|
|
}
|
|
if inv.KeyID == KeyID(set.PublicKey) {
|
|
return Friend{}, fmt.Errorf("%w: that is an invite of this server", ErrInvalidInput)
|
|
}
|
|
reply, err := s.remote.Pair(ctx, inv.Address, PairRequest{
|
|
Code: inv.Code, Name: s.name(set), Address: set.Address, PublicKey: set.PublicKey,
|
|
})
|
|
if err != nil {
|
|
return Friend{}, err
|
|
}
|
|
if len(reply.PublicKey) != ed25519.PublicKeySize || KeyID(reply.PublicKey) != inv.KeyID {
|
|
return Friend{}, ErrKeyMismatch
|
|
}
|
|
name := strings.TrimSpace(reply.Name)
|
|
if checkText(name, false) != nil {
|
|
return Friend{}, fmt.Errorf("%w: the other server sent no usable name", ErrUnreachable)
|
|
}
|
|
// The address is the one the invite was made for: that is where it answered.
|
|
return s.store.AddFriend(ctx, Friend{
|
|
Name: name, Address: inv.Address, PublicKey: reply.PublicKey, State: Outgoing, CreatedAt: s.now(),
|
|
})
|
|
}
|
|
|
|
func (s *Service) tooMany() bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
now := s.now()
|
|
kept := s.attempts[:0]
|
|
for _, t := range s.attempts {
|
|
if now.Sub(t) < pairWindow {
|
|
kept = append(kept, t)
|
|
}
|
|
}
|
|
s.attempts = kept
|
|
if len(s.attempts) >= pairAttempts {
|
|
return true
|
|
}
|
|
s.attempts = append(s.attempts, now)
|
|
return false
|
|
}
|
|
|
|
// Pair answers another server that used an invite of this one. The friend is kept as incoming: an admin of this
|
|
// server still has to approve it.
|
|
func (s *Service) Pair(ctx context.Context, req PairRequest) (PairReply, error) {
|
|
set, err := s.load(ctx)
|
|
if err != nil {
|
|
return PairReply{}, err
|
|
}
|
|
if !set.Enabled || set.PublicKey == nil {
|
|
return PairReply{}, ErrOff
|
|
}
|
|
if s.tooMany() {
|
|
return PairReply{}, ErrTooMany
|
|
}
|
|
name := strings.TrimSpace(req.Name)
|
|
if err := checkText(name, false); err != nil {
|
|
return PairReply{}, err
|
|
}
|
|
addr, err := normalizeAddress(req.Address)
|
|
if err != nil {
|
|
return PairReply{}, err
|
|
}
|
|
if len(req.PublicKey) != ed25519.PublicKeySize || req.PublicKey.Equal(set.PublicKey) {
|
|
return PairReply{}, fmt.Errorf("%w: not a key of another server", ErrInvalidInput)
|
|
}
|
|
if set.Address == "" {
|
|
return PairReply{}, ErrNoAddress
|
|
}
|
|
if _, known, err := s.store.FriendByKey(ctx, req.PublicKey); err != nil {
|
|
return PairReply{}, fmt.Errorf("look up the friend: %w", err)
|
|
} else if known {
|
|
return PairReply{}, ErrAlreadyFriend
|
|
}
|
|
if req.Code == "" || len(req.Code) > maxCodeLen {
|
|
return PairReply{}, ErrInvalidInvite
|
|
}
|
|
used, err := s.store.UseInvite(ctx, hashCode(req.Code), s.now())
|
|
if err != nil {
|
|
return PairReply{}, fmt.Errorf("use the invite: %w", err)
|
|
}
|
|
if !used {
|
|
return PairReply{}, ErrInvalidInvite
|
|
}
|
|
if _, err := s.store.AddFriend(ctx, Friend{
|
|
Name: name, Address: addr, PublicKey: req.PublicKey, State: Incoming, CreatedAt: s.now(),
|
|
}); err != nil {
|
|
return PairReply{}, err
|
|
}
|
|
return PairReply{Name: s.name(set), Address: set.Address, PublicKey: set.PublicKey}, nil
|
|
}
|
|
|
|
// Approve is the second confirmation: a friend that used an invite of this server becomes active.
|
|
func (s *Service) Approve(ctx context.Context, id int64) (Friend, error) {
|
|
if err := s.store.Approve(ctx, id, s.now()); err != nil {
|
|
return Friend{}, err
|
|
}
|
|
return s.store.Friend(ctx, id)
|
|
}
|
|
|
|
// Remove declines a request, withdraws one, or ends a friendship. The other server is not told: its requests
|
|
// are simply no longer answered.
|
|
func (s *Service) Remove(ctx context.Context, id int64) error { return s.store.DeleteFriend(ctx, id) }
|
|
|
|
// checkText accepts a name: at most 60 characters, none of them a control character. An own name may be empty (it
|
|
// then is the host name); a friend's may not.
|
|
func checkText(name string, allowEmpty bool) error {
|
|
switch {
|
|
case name == "" && allowEmpty:
|
|
return nil
|
|
case name == "", utf8.RuneCountInString(name) > maxNameRunes, !utf8.ValidString(name):
|
|
return fmt.Errorf("%w: a name is 1 to %d characters", ErrInvalidInput, maxNameRunes)
|
|
}
|
|
for _, r := range name {
|
|
if unicode.IsControl(r) {
|
|
return fmt.Errorf("%w: a name has no control characters", ErrInvalidInput)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// normalizeAddress checks the address of a server and writes it one way: scheme and host in lower case, no trailing
|
|
// slash. It must be https; plain http is accepted only on a network of one's own (a private, loopback or link-local
|
|
// address, or a local name), for two servers in one house.
|
|
func normalizeAddress(s string) (string, error) {
|
|
bad := func(why string) (string, error) { return "", fmt.Errorf("%w: address %s", ErrInvalidInput, why) }
|
|
if s == "" || len(s) > maxAddressLen {
|
|
return bad("is empty or too long")
|
|
}
|
|
u, err := url.Parse(s)
|
|
if err != nil || u.Host == "" {
|
|
return bad("is not an http(s) address")
|
|
}
|
|
scheme := strings.ToLower(u.Scheme)
|
|
if scheme != "http" && scheme != "https" {
|
|
return bad("must start with https://")
|
|
}
|
|
if u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
|
|
return bad("has no user, query or fragment")
|
|
}
|
|
host := strings.ToLower(u.Hostname())
|
|
if host == "" {
|
|
return bad("has no host")
|
|
}
|
|
if scheme == "http" && !onOwnNetwork(host) {
|
|
return bad("must be https, unless it is on your own network")
|
|
}
|
|
hostPort := host
|
|
if strings.Contains(host, ":") {
|
|
hostPort = "[" + host + "]"
|
|
}
|
|
if port := u.Port(); port != "" {
|
|
hostPort = net.JoinHostPort(host, port)
|
|
}
|
|
return scheme + "://" + hostPort + strings.TrimRight(u.Path, "/"), nil
|
|
}
|
|
|
|
func onOwnNetwork(host string) bool {
|
|
if ip, err := netip.ParseAddr(host); err == nil {
|
|
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
|
|
}
|
|
if !strings.Contains(host, ".") {
|
|
return true // nas, localhost
|
|
}
|
|
for _, suffix := range []string{".local", ".lan", ".home.arpa"} {
|
|
if strings.HasSuffix(host, suffix) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func validNonce(n string) bool {
|
|
if len(n) < minNonceLen || len(n) > maxNonceLen {
|
|
return false
|
|
}
|
|
for _, r := range n {
|
|
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_') {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// remember says whether a nonce is new, and keeps it for as long as a request made with it would still be accepted.
|
|
func (s *Service) remember(keyID, nonce string, now time.Time) bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for k, until := range s.seen {
|
|
if !now.Before(until) {
|
|
delete(s.seen, k)
|
|
}
|
|
}
|
|
key := keyID + ":" + nonce
|
|
if _, again := s.seen[key]; again {
|
|
return false
|
|
}
|
|
s.seen[key] = now.Add(2*clockSkew + time.Second)
|
|
return true
|
|
}
|
|
|
|
// Authenticate tells which friend made a request, or why none did. It answers ErrOff while federation is off,
|
|
// ErrUnauthorized for every kind of request that is not properly signed (the same answer, so that a stranger learns
|
|
// nothing), and ErrNotApproved when the signature is good but this server's admin has not approved the friend yet.
|
|
// A friend this server is waiting for (outgoing) that calls has approved, so it becomes active.
|
|
func (s *Service) Authenticate(ctx context.Context, in Signed) (Friend, error) {
|
|
set, err := s.load(ctx)
|
|
if err != nil {
|
|
return Friend{}, err
|
|
}
|
|
if !set.Enabled || set.PublicKey == nil {
|
|
return Friend{}, ErrOff
|
|
}
|
|
date, err := strconv.ParseInt(in.Date, 10, 64)
|
|
if err != nil || len(in.KeyID) != keyIDHexLength || !validNonce(in.Nonce) || in.Signature == "" {
|
|
return Friend{}, ErrUnauthorized
|
|
}
|
|
now := s.now()
|
|
if skew := now.Sub(time.Unix(date, 0)); skew > clockSkew || skew < -clockSkew {
|
|
return Friend{}, ErrUnauthorized
|
|
}
|
|
friends, err := s.store.Friends(ctx)
|
|
if err != nil {
|
|
return Friend{}, fmt.Errorf("list friends: %w", err)
|
|
}
|
|
var friend Friend
|
|
found := false
|
|
for _, f := range friends {
|
|
if KeyID(f.PublicKey) == in.KeyID {
|
|
friend, found = f, true
|
|
break
|
|
}
|
|
}
|
|
if !found || !verify(friend.PublicKey, in.Method, in.URI, in.Date, in.Nonce, in.Signature) {
|
|
return Friend{}, ErrUnauthorized
|
|
}
|
|
if friend.State == Incoming {
|
|
return Friend{}, ErrNotApproved
|
|
}
|
|
if !s.remember(in.KeyID, in.Nonce, now) {
|
|
return Friend{}, ErrUnauthorized
|
|
}
|
|
if friend.State == Outgoing {
|
|
if err := s.store.Activate(ctx, friend.ID, now); err == nil {
|
|
friend.State, friend.ApprovedAt = Active, now
|
|
}
|
|
}
|
|
return friend, nil
|
|
}
|
|
|
|
// Check asks a friend that this server is waiting for, or already has, who it is, signed. An answer means it
|
|
// approved, so a friend that was outgoing becomes active. ErrNotApproved means it has not approved yet.
|
|
func (s *Service) Check(ctx context.Context, id int64) (Friend, error) {
|
|
f, err := s.store.Friend(ctx, id)
|
|
if err != nil {
|
|
return Friend{}, err
|
|
}
|
|
if f.State == Incoming {
|
|
return f, ErrWrongState
|
|
}
|
|
set, err := s.load(ctx)
|
|
if err != nil {
|
|
return f, err
|
|
}
|
|
if !set.Enabled || set.PublicKey == nil {
|
|
return f, ErrOff
|
|
}
|
|
if _, err := s.remote.Info(ctx, f.Address, Auth{KeyID: KeyID(set.PublicKey), Key: set.PrivateKey}); err != nil {
|
|
return f, err
|
|
}
|
|
if f.State == Outgoing {
|
|
now := s.now()
|
|
if err := s.store.Activate(ctx, f.ID, now); err != nil && !errors.Is(err, ErrWrongState) {
|
|
return f, err
|
|
}
|
|
f.State, f.ApprovedAt = Active, now
|
|
}
|
|
return f, nil
|
|
}
|
|
|
|
// Record logs a request a friend made. A failure to log is not a reason to fail the request, so it is not returned.
|
|
func (s *Service) Record(ctx context.Context, r FriendRequest) {
|
|
now := s.now()
|
|
if r.At.IsZero() {
|
|
r.At = now
|
|
}
|
|
_ = s.store.LogRequest(ctx, r)
|
|
s.mu.Lock()
|
|
s.logged++
|
|
tidy := s.logged%requestPruneEvery == 0
|
|
s.mu.Unlock()
|
|
if tidy {
|
|
_ = s.store.PruneRequests(ctx, now.Add(-requestKeep))
|
|
}
|
|
}
|
|
|
|
// Requests lists the last requests friends made, newest first.
|
|
func (s *Service) Requests(ctx context.Context) ([]FriendRequest, error) {
|
|
return s.store.Requests(ctx, requestsShown)
|
|
}
|
|
|
|
// ActiveFriends lists the friends a listener may browse. While federation is off there are none.
|
|
func (s *Service) ActiveFriends(ctx context.Context) ([]Friend, error) {
|
|
set, err := s.load(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !set.Enabled || set.PublicKey == nil {
|
|
return nil, nil
|
|
}
|
|
all, err := s.store.Friends(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list friends: %w", err)
|
|
}
|
|
var out []Friend
|
|
for _, f := range all {
|
|
if f.State == Active {
|
|
out = append(out, f)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// What a listener may ask a friend: the three lists and their items, with the few parameters those take.
|
|
var (
|
|
browseResources = map[string]bool{"artists": true, "albums": true, "tracks": true}
|
|
browseParams = []string{"q", "limit", "offset", "artist_id", "album_id"}
|
|
)
|
|
|
|
// Browse asks an active friend, with a signed request, for a list (id 0) or one item of what it shares, and
|
|
// returns the answer as the friend gave it, to be checked by whoever uses it. Nothing is kept. Anything else than
|
|
// the three kinds of thing, and any parameter a route does not take, is dropped before the friend is asked, so a
|
|
// listener cannot make this server ask for anything but the catalogue. A friend that is not active, does not
|
|
// exist or is not reachable while federation is off is ErrFriendMissing.
|
|
func (s *Service) Browse(ctx context.Context, friendID int64, resource string, id int64, query url.Values) ([]byte, error) {
|
|
if !browseResources[resource] || id < 0 {
|
|
return nil, fmt.Errorf("%w: there is no such thing to browse", ErrInvalidInput)
|
|
}
|
|
uri := "/api/v1/peer/" + resource
|
|
if id > 0 {
|
|
uri += "/" + strconv.FormatInt(id, 10)
|
|
} else {
|
|
keep := url.Values{}
|
|
for _, k := range browseParams {
|
|
if v := query.Get(k); v != "" {
|
|
keep.Set(k, v)
|
|
}
|
|
}
|
|
if len(keep) > 0 {
|
|
uri += "?" + keep.Encode()
|
|
}
|
|
}
|
|
status, body, err := s.ask(ctx, friendID, uri)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if status == http.StatusOK {
|
|
return body, nil
|
|
}
|
|
return nil, errorFor(status, body)
|
|
}
|
|
|
|
// ask sends an active friend a signed GET and gives back what it answered.
|
|
func (s *Service) ask(ctx context.Context, friendID int64, uri string) (int, []byte, error) {
|
|
set, err := s.load(ctx)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
if !set.Enabled || set.PublicKey == nil {
|
|
return 0, nil, ErrFriendMissing
|
|
}
|
|
f, err := s.store.Friend(ctx, friendID)
|
|
if err != nil || f.State != Active {
|
|
return 0, nil, ErrFriendMissing
|
|
}
|
|
return s.remote.Get(ctx, f.Address, uri, Auth{KeyID: KeyID(set.PublicKey), Key: set.PrivateKey})
|
|
}
|
|
|
|
// Peaks asks an active friend for the shape of one of its tracks (how loud it is along its length, for the seek bar).
|
|
// The friend works it out the first time it is asked, and says so: ErrWorking, and the page asks again.
|
|
// ErrNoWaveform when the friend cannot read the file.
|
|
func (s *Service) Peaks(ctx context.Context, friendID, trackID int64) ([]byte, error) {
|
|
if trackID <= 0 {
|
|
return nil, fmt.Errorf("%w: there is no such track", ErrInvalidInput)
|
|
}
|
|
status, body, err := s.ask(ctx, friendID, "/api/v1/peer/tracks/"+strconv.FormatInt(trackID, 10)+"/peaks")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
switch status {
|
|
case http.StatusOK:
|
|
return body, nil
|
|
case http.StatusAccepted:
|
|
return nil, ErrWorking
|
|
case http.StatusNotFound:
|
|
if codeOf(body) == "waveform_unavailable" {
|
|
return nil, ErrNoWaveform
|
|
}
|
|
}
|
|
return nil, errorFor(status, body)
|
|
}
|
|
|
|
// codeOf is the error code in the body of a friend's answer, or nothing when it has none.
|
|
func codeOf(body []byte) string {
|
|
var e struct {
|
|
Error struct {
|
|
Code string `json:"code"`
|
|
} `json:"error"`
|
|
}
|
|
if json.Unmarshal(body, &e) != nil {
|
|
return ""
|
|
}
|
|
return e.Error.Code
|
|
}
|
|
|
|
// errorFor tells what a friend's answer other than a success means, in this server's own terms.
|
|
func errorFor(status int, body []byte) error {
|
|
switch status {
|
|
case http.StatusBadRequest:
|
|
return fmt.Errorf("%w: the friend did not take the question", ErrInvalidInput)
|
|
case http.StatusForbidden:
|
|
return ErrNotApproved
|
|
case http.StatusUnauthorized:
|
|
return ErrNotFriend
|
|
case http.StatusNotFound:
|
|
if strings.HasSuffix(codeOf(body), "_not_found") {
|
|
return ErrNotFoundThere
|
|
}
|
|
return ErrNotFriend // federation is off there, or it is not a Sonda server that knows us
|
|
case http.StatusTooManyRequests:
|
|
return ErrTooMany
|
|
default:
|
|
return fmt.Errorf("%w: it answered %d", ErrUnreachable, status)
|
|
}
|
|
}
|
|
|
|
// The two things that are passed on whole.
|
|
const (
|
|
MediaStream = "stream" // the audio of a track
|
|
MediaCover = "cover" // the cover of an album
|
|
)
|
|
|
|
// What goes to a friend from the request of a listener, and what comes back to the listener from the friend's
|
|
// answer: a short list each way, so that nothing a listener or a friend sends decides anything on the other side.
|
|
var (
|
|
mediaRequestHeaders = []string{"Range", "If-Range", "If-Modified-Since", "If-Unmodified-Since", "If-None-Match"}
|
|
mediaResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag"}
|
|
)
|
|
|
|
// Media is a friend's answer to a request for a stream or a cover, ready to be passed on. Close the Body.
|
|
type Media struct {
|
|
Status int
|
|
Header http.Header
|
|
Body io.ReadCloser
|
|
}
|
|
|
|
// OpenMedia asks an active friend, signed, for the audio of a track or the cover of an album, forwarding the headers
|
|
// a player uses to seek and to ask again. Only audio (for a stream) and a JPEG (for a cover) are passed on, with
|
|
// a fixed set of headers, so a friend cannot make this server serve anything else. The friend sees this server's
|
|
// request and nothing of the listener.
|
|
func (s *Service) OpenMedia(ctx context.Context, friendID int64, kind string, id int64, query url.Values, in http.Header) (*Media, error) {
|
|
if id <= 0 || (kind != MediaStream && kind != MediaCover) {
|
|
return nil, fmt.Errorf("%w: there is no such thing to open", ErrInvalidInput)
|
|
}
|
|
uri := "/api/v1/peer/tracks/" + strconv.FormatInt(id, 10) + "/stream"
|
|
if kind == MediaCover {
|
|
uri = "/api/v1/peer/albums/" + strconv.FormatInt(id, 10) + "/cover"
|
|
switch size := query.Get("size"); size {
|
|
case "":
|
|
case "small", "large":
|
|
uri += "?size=" + size
|
|
default:
|
|
return nil, fmt.Errorf("%w: size is small or large", ErrInvalidInput)
|
|
}
|
|
}
|
|
set, err := s.load(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !set.Enabled || set.PublicKey == nil {
|
|
return nil, ErrFriendMissing
|
|
}
|
|
f, err := s.store.Friend(ctx, friendID)
|
|
if err != nil || f.State != Active {
|
|
return nil, ErrFriendMissing
|
|
}
|
|
out := http.Header{}
|
|
for _, k := range mediaRequestHeaders {
|
|
if v := in.Get(k); v != "" {
|
|
out.Set(k, v)
|
|
}
|
|
}
|
|
resp, err := s.remote.Open(ctx, f.Address, uri, Auth{KeyID: KeyID(set.PublicKey), Key: set.PrivateKey}, out)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
switch resp.StatusCode {
|
|
case http.StatusOK, http.StatusPartialContent:
|
|
if !mediaTypeOK(kind, resp.Header.Get("Content-Type")) {
|
|
_ = resp.Body.Close()
|
|
return nil, fmt.Errorf("%w: the answer is not what was asked for", ErrUnreachable)
|
|
}
|
|
return &Media{Status: resp.StatusCode, Header: passed(resp.Header, true), Body: resp.Body}, nil
|
|
case http.StatusNotModified, http.StatusRequestedRangeNotSatisfiable:
|
|
_ = resp.Body.Close()
|
|
return &Media{Status: resp.StatusCode, Header: passed(resp.Header, false), Body: http.NoBody}, nil
|
|
}
|
|
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxReplyBytes))
|
|
_ = resp.Body.Close()
|
|
return nil, errorFor(resp.StatusCode, body)
|
|
}
|
|
|
|
func mediaTypeOK(kind, contentType string) bool {
|
|
mt, _, err := mime.ParseMediaType(contentType)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if kind == MediaStream {
|
|
return strings.HasPrefix(mt, "audio/")
|
|
}
|
|
return mt == "image/jpeg"
|
|
}
|
|
|
|
// passed copies the headers of a friend's answer that go on to the listener.
|
|
func passed(from http.Header, withType bool) http.Header {
|
|
out := http.Header{}
|
|
for _, k := range mediaResponseHeaders {
|
|
if !withType && (k == "Content-Type" || k == "Content-Length") {
|
|
continue
|
|
}
|
|
if v := from.Get(k); v != "" {
|
|
out.Set(k, v)
|
|
}
|
|
}
|
|
return out
|
|
}
|