Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 27 additions & 7 deletions app/cmd/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -1499,7 +1499,7 @@ func (c *clientConfig) startMimic() *mimic.Instance {
if !c.Mimic.Enabled {
return nil
}
addr, err := c.mimicServerAddr()
addrs, err := c.mimicServerAddrs()
if err != nil {
logger.Fatal("failed to resolve server address for mimic", zap.Error(err))
}
Expand All @@ -1511,7 +1511,7 @@ func (c *clientConfig) startMimic() *mimic.Instance {
Path: c.Mimic.Path,
ExtraArgs: c.Mimic.ExtraArgs,
},
mimic.RoleClient, addr, logger,
mimic.RoleClient, addrs, logger,
func(err error) { logger.Fatal("mimic stopped", zap.Error(err)) },
)
if err != nil {
Expand All @@ -1520,9 +1520,29 @@ func (c *clientConfig) startMimic() *mimic.Instance {
return inst
}

// mimicServerAddr resolves the server address for Mimic's filter. Mimic needs a
// literal ip:port, so this resolves the name the same way the client will.
func (c *clientConfig) mimicServerAddr() (*net.UDPAddr, error) {
_, _, hostPort := parseServerAddrString(c.Server)
return net.ResolveUDPAddr("udp", hostPort)
// mimicServerAddrs resolves the server address for Mimic's filters. Mimic needs
// literal ip:port, and a name can resolve to several addresses across both
// families, so every one of them gets a filter: the client re-resolves on each
// reconnect and may pick a different one than it did at startup.
func (c *clientConfig) mimicServerAddrs() ([]*net.UDPAddr, error) {
host, portStr, hostPort := parseServerAddrString(c.Server)
port, err := strconv.Atoi(portStr)
if err != nil {
return nil, fmt.Errorf("invalid server port %q: %w", portStr, err)
}
if ip := net.ParseIP(host); ip != nil {
return []*net.UDPAddr{{IP: ip, Port: port}}, nil
}
ips, err := net.DefaultResolver.LookupIP(context.Background(), "ip", host)
if err != nil {
return nil, err
}
if len(ips) == 0 {
return nil, fmt.Errorf("no addresses for %s", hostPort)
}
addrs := make([]*net.UDPAddr, 0, len(ips))
for _, ip := range ips {
addrs = append(addrs, &net.UDPAddr{IP: ip, Port: port})
}
return addrs, nil
}
2 changes: 1 addition & 1 deletion app/cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1634,7 +1634,7 @@ func runServer(v *viper.Viper) {
Path: config.Mimic.Path,
ExtraArgs: config.Mimic.ExtraArgs,
},
mimic.RoleServer, listenUDPAddr(config.Listen), logger,
mimic.RoleServer, []*net.UDPAddr{listenUDPAddr(config.Listen)}, logger,
func(err error) { logger.Fatal("mimic stopped", zap.Error(err)) },
)
if err != nil {
Expand Down
128 changes: 91 additions & 37 deletions app/internal/mimic/mimic_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,47 +36,47 @@ type Instance struct {
exited chan struct{}
}

// Start launches Mimic for addr and waits for it to attach. addr is the peer's
// address for RoleClient and our listen address for RoleServer.
//
// Start launches Mimic for addrs and waits for it to attach. addrs holds every
// address the peer resolved to for RoleClient, and our listen address for
// RoleServer.
// onExit is called if Mimic stops on its own, which is fatal: the peer expects
// TCP-shaped packets, so the connection is already dead by then.
func Start(cfg Config, role Role, addr *net.UDPAddr, logger *zap.Logger, onExit func(error)) (*Instance, error) {
func Start(cfg Config, role Role, addrs []*net.UDPAddr, logger *zap.Logger, onExit func(error)) (*Instance, error) {
if !cfg.Enabled {
return nil, nil
}
if len(addrs) == 0 {
return nil, errors.New("mimic needs at least one address to filter")
}
bin, err := resolveBinary(cfg.Path)
if err != nil {
return nil, err
}
iface, err := resolveInterface(cfg.Interface, role, addr)
iface, err := resolveInterface(cfg.Interface, role, addrs[0])
if err != nil {
return nil, err
}
filter := filterFor(role, addr)
filters := filtersFor(role, addrs)
// Mimic attaches to the interface, so one instance serves every client on
// this machine reaching the same server.
// Reuse it only if its filters cover our address.
if pid, ok := runningOn(iface); ok {
covered, err := filtersCover(bin, iface, filter)
covered, err := filtersCover(bin, iface, filters)
if err != nil {
return nil, fmt.Errorf("mimic is already running on %s (pid %d) "+
"and its filters could not be read: %w", iface, pid, err)
}
if !covered {
return nil, fmt.Errorf("mimic is already running on %s (pid %d) but does "+
"not filter %s; stop it, or add that filter to it", iface, pid, filterAddr(filter))
"not cover the required filter set (%s); stop it, or update its filters",
iface, pid, strings.Join(filterAddrs(filters), ", "))
}
logger.Info("using the mimic already running on this interface",
zap.String("interface", iface), zap.Int("pid", pid))
return nil, nil
}

args := []string{"run", iface, "-f", filter}
if cfg.XDPMode != "" {
args = append(args, "--xdp-mode", cfg.XDPMode)
}
args = append(args, cfg.ExtraArgs...)
args := runArgs(iface, filters, cfg)

ctx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(ctx, bin, args...)
Expand Down Expand Up @@ -109,10 +109,21 @@ func Start(cfg Config, role Role, addr *net.UDPAddr, logger *zap.Logger, onExit
}
logger.Info("mimic started",
zap.String("interface", iface),
zap.String("filter", filter))
zap.Strings("filters", filters))
return i, nil
}

func runArgs(iface string, filters []string, cfg Config) []string {
args := []string{"run", iface}
for _, filter := range filters {
args = append(args, "-f", filter)
}
if cfg.XDPMode != "" {
args = append(args, "--xdp-mode", cfg.XDPMode)
}
return append(args, cfg.ExtraArgs...)
}

// Close stops Mimic and waits for it to detach.
func (i *Instance) Close() error {
if i == nil {
Expand Down Expand Up @@ -191,25 +202,41 @@ func runningOn(iface string) (int, bool) {

// filtersCover reports whether the running Mimic already matches our address.
// "mimic show" prints one "Filter: origin=ip:port" line per whitelist entry.
func filtersCover(bin, iface, filter string) (bool, error) {
func filtersCover(bin, iface string, filters []string) (bool, error) {
out, err := exec.Command(bin, "show", iface).Output()
if err != nil {
return false, err
}
want := filterAddr(filter)
covered := make(map[string]bool)
for _, line := range strings.Split(stripANSI(string(out)), "\n") {
_, v, ok := strings.Cut(line, "Filter:")
if ok && filterAddr(strings.TrimSpace(v)) == want {
return true, nil
if ok {
covered[filterAddr(strings.TrimSpace(v))] = true
}
}
return false, nil
for _, want := range filterAddrs(filters) {
if !covered[want] {
return false, nil
}
}
return true, nil
}

// filterAddr strips the settings a filter may carry, leaving origin=ip:port.
// filterAddr strips everything a filter line may carry beyond origin=ip:port:
// the settings after a comma, and the "(resolved from <host>)" note that
// "mimic show" appends when the filter came from a name rather than a literal.
func filterAddr(filter string) string {
addr, _, _ := strings.Cut(filter, ",")
return strings.TrimSpace(addr)
addr, _, _ = strings.Cut(strings.TrimSpace(addr), " ")
return addr
}

func filterAddrs(filters []string) []string {
addrs := make([]string, len(filters))
for i, filter := range filters {
addrs[i] = filterAddr(filter)
}
return addrs
}

// lockPID reads the PID from a Mimic lock file, a flat key=value list.
Expand Down Expand Up @@ -267,22 +294,49 @@ func waitReady(iface string, ourPID int, exited <-chan struct{}) error {
return fmt.Errorf("mimic did not become ready within %s", readyTimeout)
}

// filterFor builds Mimic's whitelist entry: the client matches on the peer, the
// server on itself.
func filterFor(role Role, addr *net.UDPAddr) string {
host := addr.IP.String()
if addr.IP == nil || addr.IP.IsUnspecified() {
host = "0.0.0.0"
}
if addr.IP != nil && addr.IP.To4() == nil {
host = "[" + host + "]"
}
if role == RoleServer {
// handshake is interval:retry; interval zero makes this side passive,
// so it answers connections but never opens one.
return fmt.Sprintf("local=%s:%d,handshake=0:3", host, addr.Port)
}
return fmt.Sprintf("remote=%s:%d", host, addr.Port)
// filtersFor builds Mimic's whitelist entries: the client matches on the peer,
// the server on itself. A server listener with no IP or an IPv6 wildcard
// accepts both address families, so Mimic needs one local filter for each. A
// client gets one filter per address the peer resolved to.
func filtersFor(role Role, addrs []*net.UDPAddr) []string {
if role == RoleClient {
filters := make([]string, 0, len(addrs))
seen := make(map[string]bool, len(addrs))
for _, addr := range addrs {
f := fmt.Sprintf("remote=%s:%d", filterHost(addr.IP), addr.Port)
if seen[f] {
continue
}
seen[f] = true
filters = append(filters, f)
}
return filters
}
addr := addrs[0]
if addr.IP == nil || (addr.IP.IsUnspecified() && addr.IP.To4() == nil) {
return []string{
fmt.Sprintf("local=0.0.0.0:%d,handshake=0:3", addr.Port),
fmt.Sprintf("local=[::]:%d,handshake=0:3", addr.Port),
}
}
// handshake is interval:retry; interval zero makes this side passive,
// so it answers connections but never opens one.
return []string{fmt.Sprintf("local=%s:%d,handshake=0:3", filterHost(addr.IP), addr.Port)}
}

// filterHost renders an IP the way Mimic's filter syntax expects, bracketing
// IPv6 so the port stays unambiguous.
func filterHost(ip net.IP) string {
if ip == nil || ip.IsUnspecified() {
if ip != nil && ip.To4() == nil {
return "[::]"
}
return "0.0.0.0"
}
if ip.To4() == nil {
return "[" + ip.String() + "]"
}
return ip.String()
}

// resolveInterface finds the interface carrying traffic for addr, falling back
Expand Down
Loading
Loading