| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "net" |
| 7 | "net/http" |
| 8 | "net/netip" |
| 9 | "sync" |
| 10 | "syscall" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | var errBlockedAddress = errors |
| 15 | |
| 16 | var ( |
| 17 | thisNetwork = netip. |
| 18 | sharedCGNAT = netip. |
| 19 | ) |
| 20 | |
| 21 | // blocked reports whether a webhook may not connect to a. Link-local covers |
| 22 | // the cloud metadata address 169.254.169.254 and stays blocked even when |
| 23 | // private networks are allowed. |
| 24 | func blocked(a netip |
| 25 | a = a. |
| 26 | if a.IsLinkLocalUnicast() |
| 27 | a.IsUnspecified() || |
| 28 | return true |
| 29 | } |
| 30 | if allowPrivate { |
| 31 | return false |
| 32 | } |
| 33 | return a.IsLoopback() |
| 34 | } |
| 35 | |
| 36 | // newWebhookClient returns a client that checks the IP it actually dials, |
| 37 | // after DNS, so a hostname that resolves or rebinds to an internal address |
| 38 | // is refused. It never uses a proxy (the check would see the proxy's IP) and |
| 39 | // never follows redirects (a redirect could point anywhere). |
| 40 | func newWebhookClient(allowPrivate bool |
| 41 | dialer := &net |
| 42 | Timeout: 5 * |
| 43 | Control: func(network |
| 44 | ap, err := |
| 45 | if err != nil |
| 46 | return err |
| 47 | } |
| 48 | if blocked(ap. |
| 49 | return fmt.Errorf( |
| 50 | } |
| 51 | return nil |
| 52 | }, |
| 53 | } |
| 54 | return &http.Client |
| 55 | Transport: &http |
| 56 | Proxy: nil, |
| 57 | DialContext: dialer.DialContext |
| 58 | TLSHandshakeTimeout: 5 * |
| 59 | MaxIdleConnsPerHost: 2, |
| 60 | IdleConnTimeout: 90 * |
| 61 | }, |
| 62 | CheckRedirect: func(*http |
| 63 | return http.ErrUseLastResponse |
| 64 | }, |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | // hostLimiter caps sends in flight per host, so one slow receiver cannot hold |
| 69 | // every worker while other endpoints wait. A nil limiter allows everything. |
| 70 | // |
| 71 | // ponytail: per process; with several delivery instances the real cap is |
| 72 | // instances x max. Move it to Postgres if that matters. |
| 73 | type hostLimiter struct { |
| 74 | mu sync. |
| 75 | max int |
| 76 | inUse map[string] |
| 77 | } |
| 78 | |
| 79 | func newHostLimiter(max int |
| 80 | return &hostLimiter{max |
| 81 | } |
| 82 | |
| 83 | func (h *hostLimiter |
| 84 | if h == nil |
| 85 | return true |
| 86 | } |
| 87 | h.mu.Lock |
| 88 | defer h.mu. |
| 89 | if h.inUse[ |
| 90 | return false |
| 91 | } |
| 92 | h.inUse[host |
| 93 | return true |
| 94 | } |
| 95 | |
| 96 | func (h *hostLimiter |
| 97 | if h == nil |
| 98 | return |
| 99 | } |
| 100 | h.mu.Lock |
| 101 | defer h.mu. |
| 102 | if h.inUse[ |
| 103 | delete(h.inUse |
| 104 | } |
| 105 | } |