| 1 |
//go:build darwin && !ios && !e2e_testing |
| 2 |
// +build darwin,!ios,!e2e_testing |
| 3 |
|
| 4 |
package udp |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"encoding/binary" |
| 9 |
"errors" |
| 10 |
"log/slog" |
| 11 |
"os" |
| 12 |
"time" |
| 13 |
|
| 14 |
"golang.org/x/sys/unix" |
| 15 |
) |
| 16 |
|
| 17 |
const ( |
| 18 |
// netChangeSettleWindow is how long we keep swallowing routing messages after the first interesting one. A |
| 19 |
// single network change is never a single message, it is a burst: the link drops, addresses go away, new ones |
| 20 |
// arrive, routes get rewritten. Reporting part way through that just means reporting again. |
| 21 |
netChangeSettleWindow = time.Second |
| 22 |
|
| 23 |
// netChangeReadBuffer is sized well past any rt_msghdr plus its addresses. A short read would be discarded by |
| 24 |
// the kernel, so being generous here is how we avoid missing a message. |
| 25 |
netChangeReadBuffer = 4096 |
| 26 |
) |
| 27 |
|
| 28 |
// watchNetworkChanges reports when the local network moves out from under us, so the listener can be rebound. |
| 29 |
// |
| 30 |
// Darwin scopes a udp socket to whatever interface it came up on. Move between networks and we keep sending out an |
| 31 |
// interface that no longer has a route, which surfaces as an instant "no route to host" with no packet ever leaving |
| 32 |
// the box. Rebind clears that, but only if something notices the change and calls it. iOS has always been told by |
| 33 |
// the host app off NWPathMonitor. This is the equivalent for everything else that runs on darwin. |
| 34 |
// |
| 35 |
// The returned channel is buffered and coalescing: a send is dropped if one is already pending, since both mean the |
| 36 |
// same thing to a reader. It is closed when ctx is cancelled or the routing socket fails, so a caller can simply |
| 37 |
// range over it. Platforms whose sockets do not need rebinding return a nil channel and no error. |
| 38 |
func watchNetworkChanges(ctx context.Context, l *slog.Logger) (<-chan struct{}, error) { |
| 39 |
sock, err := openRouteSocket() |
| 40 |
if err != nil { |
| 41 |
return nil, err |
| 42 |
} |
| 43 |
|
| 44 |
changes := make(chan struct{}, 1) |
| 45 |
|
| 46 |
go func() { |
| 47 |
defer close(changes) |
| 48 |
defer func() { _ = sock.Close() }() |
| 49 |
|
| 50 |
// Closing the socket is what unblocks the read in watchRouteSocket, so this turns cancellation into a |
| 51 |
// close. It is scoped to this call so it cannot outlive the watch it belongs to. |
| 52 |
done := make(chan struct{}) |
| 53 |
defer close(done) |
| 54 |
go func() { |
| 55 |
select { |
| 56 |
case <-ctx.Done(): |
| 57 |
_ = sock.Close() |
| 58 |
case <-done: |
| 59 |
} |
| 60 |
}() |
| 61 |
|
| 62 |
watchRouteSocket(l, sock, changes) |
| 63 |
}() |
| 64 |
|
| 65 |
return changes, nil |
| 66 |
} |
| 67 |
|
| 68 |
// watchRouteSocket blocks reading the routing socket, reporting once per settled burst of changes. It returns when |
| 69 |
// the socket is closed, which is how cancellation gets us out of here. |
| 70 |
func watchRouteSocket(l *slog.Logger, sock *os.File, changes chan<- struct{}) { |
| 71 |
buf := make([]byte, netChangeReadBuffer) |
| 72 |
|
| 73 |
for { |
| 74 |
n, err := sock.Read(buf) |
| 75 |
if err != nil { |
| 76 |
logRouteSocketError(l, err) |
| 77 |
return |
| 78 |
} |
| 79 |
|
| 80 |
if !isNetworkChange(buf[:n]) { |
| 81 |
continue |
| 82 |
} |
| 83 |
|
| 84 |
// Swallow the rest of the burst. The deadline is absolute and not extended by what arrives, so this always |
| 85 |
// ends after the settle window no matter how chatty the socket is. Changes that land after the window |
| 86 |
// simply produce another report, which is the correct outcome anyway. |
| 87 |
deadline := time.Now().Add(netChangeSettleWindow) |
| 88 |
for { |
| 89 |
if err = sock.SetReadDeadline(deadline); err != nil { |
| 90 |
logRouteSocketError(l, err) |
| 91 |
return |
| 92 |
} |
| 93 |
|
| 94 |
if _, err = sock.Read(buf); err != nil { |
| 95 |
if os.IsTimeout(err) { |
| 96 |
break |
| 97 |
} |
| 98 |
logRouteSocketError(l, err) |
| 99 |
return |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
if err = sock.SetReadDeadline(time.Time{}); err != nil { |
| 104 |
logRouteSocketError(l, err) |
| 105 |
return |
| 106 |
} |
| 107 |
|
| 108 |
select { |
| 109 |
case changes <- struct{}{}: |
| 110 |
default: |
| 111 |
// One already pending, and a second "the network moved" tells the reader nothing new. |
| 112 |
} |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
// logRouteSocketError reports a routing socket failure unless it is just us shutting the socket down. |
| 117 |
func logRouteSocketError(l *slog.Logger, err error) { |
| 118 |
if errors.Is(err, os.ErrClosed) { |
| 119 |
return |
| 120 |
} |
| 121 |
|
| 122 |
l.Error("Error reading the routing socket, will no longer notice local network changes", "error", err) |
| 123 |
} |
| 124 |
|
| 125 |
// openRouteSocket returns the routing socket as a non blocking os.File. Going through os.File puts reads on the go |
| 126 |
// poller, which buys us both a working read deadline and a Close that unblocks a read in progress. |
| 127 |
func openRouteSocket() (*os.File, error) { |
| 128 |
fd, err := unix.Socket(unix.AF_ROUTE, unix.SOCK_RAW, unix.AF_UNSPEC) |
| 129 |
if err != nil { |
| 130 |
return nil, err |
| 131 |
} |
| 132 |
|
| 133 |
if err = unix.SetNonblock(fd, true); err != nil { |
| 134 |
_ = unix.Close(fd) |
| 135 |
return nil, err |
| 136 |
} |
| 137 |
|
| 138 |
return os.NewFile(uintptr(fd), "route"), nil |
| 139 |
} |
| 140 |
|
| 141 |
// isNetworkChange reports whether a routing message means our local addressing may have moved out from under us. |
| 142 |
// |
| 143 |
// We read the header instead of parsing the message because the type is the only part we need, and a full parse can |
| 144 |
// fail on shapes we don't care about, which would turn "a message I can't parse" into "a change I missed". |
| 145 |
// rt_msghdr, if_msghdr and ifa_msghdr all begin with the same three fields, so this is the same for every type. |
| 146 |
func isNetworkChange(msg []byte) bool { |
| 147 |
if len(msg) < 4 { |
| 148 |
return false |
| 149 |
} |
| 150 |
|
| 151 |
// u_short msglen, u_char version, u_char type |
| 152 |
if int(binary.NativeEndian.Uint16(msg[0:2])) > len(msg) || msg[2] != unix.RTM_VERSION { |
| 153 |
return false |
| 154 |
} |
| 155 |
|
| 156 |
switch msg[3] { |
| 157 |
case unix.RTM_NEWADDR, unix.RTM_DELADDR, unix.RTM_IFINFO: |
| 158 |
// An address arrived or left, or a link changed state. Anything else on this socket is either a route |
| 159 |
// churning underneath us, which a rebind doesn't help with, or unrelated traffic. |
| 160 |
return true |
| 161 |
default: |
| 162 |
return false |
| 163 |
} |
| 164 |
} |