Files
RustProxy/docker-agent/network.go
T
2026-11-14 21:52:48 +01:00

354 lines
8.5 KiB
Go

package main
import (
"bufio"
"context"
"encoding/binary"
"encoding/hex"
"io"
"net"
"net/http"
"os"
"sort"
"strings"
"sync"
"time"
)
func validIP(raw string) string {
ip := net.ParseIP(strings.TrimSpace(raw))
if ip == nil || ip.IsUnspecified() || ip.IsLoopback() || ip.IsMulticast() || ip.IsLinkLocalUnicast() {
return ""
}
return ip.String()
}
func publicIPFromURL(ctx context.Context, rawURL string) string {
if rawURL == "" {
return ""
}
client := &http.Client{Timeout: 2 * time.Second}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return ""
}
resp, err := client.Do(req)
if err != nil {
return ""
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ""
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 128))
if err != nil {
return ""
}
return validIP(string(body))
}
func routeIP() string {
conn, err := net.DialTimeout("udp", "1.1.1.1:53", time.Second)
if err != nil {
return ""
}
defer conn.Close()
if addr, ok := conn.LocalAddr().(*net.UDPAddr); ok {
return validIP(addr.IP.String())
}
return ""
}
func ipScope(ip net.IP) string {
switch {
case ip.IsPrivate():
return "private"
case ip.IsLinkLocalUnicast():
return "link_local"
default:
return "public"
}
}
func skipInterface(name string) bool {
name = strings.ToLower(strings.TrimSpace(name))
return name == "docker0" || strings.HasPrefix(name, "docker") || strings.HasPrefix(name, "veth") || strings.HasPrefix(name, "br-") || strings.HasPrefix(name, "virbr")
}
func bridgeInterface(name string) bool {
name = strings.ToLower(strings.TrimSpace(name))
if strings.HasPrefix(name, "veth") {
return false
}
return skipInterface(name) || strings.HasPrefix(name, "podman") || strings.HasPrefix(name, "cni-")
}
func localHostAddresses() []hostAddress {
return interfaceAddresses(false)
}
func bridgeHostAddresses() []hostAddress {
return interfaceAddresses(true)
}
type procAddress struct {
iface string
ip string
}
func procIPv6Addresses(path string) []procAddress {
file, err := os.Open(path)
if err != nil {
return nil
}
defer file.Close()
out := make([]procAddress, 0)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 6 || len(fields[0]) != 32 {
continue
}
raw, err := hex.DecodeString(fields[0])
if err != nil {
continue
}
out = append(out, procAddress{iface: fields[5], ip: net.IP(raw).String()})
}
return out
}
type procRoute struct {
iface string
network *net.IPNet
}
func procIPv4Routes(path string) []procRoute {
file, err := os.Open(path)
if err != nil {
return nil
}
defer file.Close()
out := make([]procRoute, 0)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 8 || fields[0] == "Iface" {
continue
}
destination, errDestination := hex.DecodeString(fields[1])
mask, errMask := hex.DecodeString(fields[7])
if errDestination != nil || errMask != nil || len(destination) != 4 || len(mask) != 4 {
continue
}
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, binary.LittleEndian.Uint32(destination))
ipMask := make(net.IPMask, 4)
binary.BigEndian.PutUint32(ipMask, binary.LittleEndian.Uint32(mask))
if ones, _ := ipMask.Size(); ones == 0 {
continue
}
out = append(out, procRoute{iface: fields[0], network: &net.IPNet{IP: ip, Mask: ipMask}})
}
return out
}
func procIPv4Local(path string) []string {
file, err := os.Open(path)
if err != nil {
return nil
}
defer file.Close()
out := make([]string, 0)
seen := make(map[string]bool)
last := ""
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "|--") {
last = strings.TrimSpace(strings.TrimPrefix(line, "|--"))
continue
}
if strings.Contains(line, "host LOCAL") && last != "" && !seen[last] {
seen[last] = true
out = append(out, last)
}
}
return out
}
func procAddresses(root string) []procAddress {
out := procIPv6Addresses(root + "/if_inet6")
routes := procIPv4Routes(root + "/route")
for _, raw := range procIPv4Local(root + "/fib_trie") {
ip := net.ParseIP(raw).To4()
if ip == nil || ip.IsLoopback() {
continue
}
best, bestOnes := "", -1
for _, route := range routes {
if ones, _ := route.network.Mask.Size(); route.network.Contains(ip) && ones > bestOnes {
best, bestOnes = route.iface, ones
}
}
if best != "" {
out = append(out, procAddress{iface: best, ip: ip.String()})
}
}
return out
}
func interfaceAddresses(bridges bool) []hostAddress {
source := "interface"
if bridges {
source = "bridge"
}
interfaces, err := net.Interfaces()
if err != nil {
return procInterfaceAddresses(procAddresses("/proc/net"), bridges, source)
}
out := make([]hostAddress, 0)
for _, iface := range interfaces {
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
continue
}
if bridges != bridgeInterface(iface.Name) || (!bridges && skipInterface(iface.Name)) {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
raw := addr.String()
if host, _, err := net.ParseCIDR(raw); err == nil {
raw = host.String()
} else if host, _, err := net.SplitHostPort(raw); err == nil {
raw = host
}
clean := validIP(raw)
if clean == "" {
continue
}
ip := net.ParseIP(clean)
out = append(out, hostAddress{IP: clean, Source: source, Interface: iface.Name, Scope: ipScope(ip)})
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].Interface != out[j].Interface {
return out[i].Interface < out[j].Interface
}
return out[i].IP < out[j].IP
})
return out
}
func procInterfaceAddresses(items []procAddress, bridges bool, source string) []hostAddress {
out := make([]hostAddress, 0)
for _, item := range items {
if item.iface == "lo" || bridges != bridgeInterface(item.iface) || (!bridges && skipInterface(item.iface)) {
continue
}
clean := validIP(item.ip)
if clean == "" {
continue
}
out = append(out, hostAddress{IP: clean, Source: source, Interface: item.iface, Scope: ipScope(net.ParseIP(clean))})
}
sort.Slice(out, func(i, j int) bool {
if out[i].Interface != out[j].Interface {
return out[i].Interface < out[j].Interface
}
return out[i].IP < out[j].IP
})
return out
}
type ipDetector struct {
mu sync.Mutex
publicIP string
expires time.Time
}
func (d *ipDetector) public(ctx context.Context, rawURL string) string {
if rawURL == "" {
return ""
}
d.mu.Lock()
defer d.mu.Unlock()
if time.Now().Before(d.expires) {
return d.publicIP
}
d.publicIP = publicIPFromURL(ctx, rawURL)
d.expires = time.Now().Add(5 * time.Minute)
if d.publicIP == "" {
d.expires = time.Now().Add(30 * time.Second)
}
return d.publicIP
}
func mergeHostAddress(out *[]hostAddress, index map[string]int, candidate hostAddress) {
candidate.IP = validIP(candidate.IP)
if candidate.IP == "" {
return
}
if candidate.Scope == "" {
candidate.Scope = ipScope(net.ParseIP(candidate.IP))
}
if pos, ok := index[candidate.IP]; ok {
existing := &(*out)[pos]
if candidate.Interface != "" && existing.Interface == "" {
existing.Interface = candidate.Interface
}
if candidate.Source != "" && !strings.Contains(existing.Source, candidate.Source) {
if existing.Source == "" {
existing.Source = candidate.Source
} else {
existing.Source += "," + candidate.Source
}
}
return
}
index[candidate.IP] = len(*out)
*out = append(*out, candidate)
}
func detectedAddresses(ctx context.Context, cfg config, detector *ipDetector) ([]hostAddress, string, string) {
out := make([]hostAddress, 0, 8)
index := make(map[string]int)
for _, item := range localHostAddresses() {
mergeHostAddress(&out, index, item)
}
routed := routeIP()
if routed != "" {
mergeHostAddress(&out, index, hostAddress{IP: routed, Source: "route"})
}
public := detector.public(ctx, cfg.PublicIPURL)
if public != "" {
mergeHostAddress(&out, index, hostAddress{IP: public, Source: "public_api"})
}
advertised := validIP(cfg.AdvertiseIP)
if advertised != "" {
mergeHostAddress(&out, index, hostAddress{IP: advertised, Source: "override"})
}
for _, item := range bridgeHostAddresses() {
if len(out) >= 48 {
break
}
mergeHostAddress(&out, index, item)
}
switch {
case advertised != "":
return out, advertised, "override"
case routed != "":
return out, routed, "route"
case public != "":
return out, public, "public_api"
case len(out) > 0:
return out, out[0].IP, out[0].Source
default:
return out, "", "unavailable"
}
}