| 1 | |
| 2 | |
| 3 | |
| 4 | package usernet |
| 5 | |
| 6 | import ( |
| 7 | "bufio" |
| 8 | "context" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "net/netip" |
| 14 | "os" |
| 15 | "runtime" |
| 16 | "strconv" |
| 17 | "strings" |
| 18 | "sync" |
| 19 | "time" |
| 20 | |
| 21 | "github.com/balajiv113/fd" |
| 22 | "github.com/containers/gvisor-tap-vsock/pkg/types" |
| 23 | "github.com/containers/gvisor-tap-vsock/pkg/virtualnetwork" |
| 24 | "github.com/miekg/dns" |
| 25 | "github.com/sirupsen/logrus" |
| 26 | "golang.org/x/sync/errgroup" |
| 27 | ) |
| 28 | |
| 29 | type GVisorNetstackOpts struct { |
| 30 | MTU int |
| 31 | |
| 32 | QemuSocket string |
| 33 | FdSocket string |
| 34 | Endpoint string |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | DgramConn net.Conn |
| 40 | |
| 41 | Subnet string |
| 42 | |
| 43 | Async bool |
| 44 | |
| 45 | DefaultLeases map[string]string |
| 46 | } |
| 47 | |
| 48 | var opts *GVisorNetstackOpts |
| 49 | |
| 50 | const gatewayMacAddr = "5a:94:ef:e4:0c:dd" |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | var Outbound types.Outbound |
| 56 | |
| 57 | |
| 58 | var DroppedIPv6 func([]byte) |
| 59 | |
| 60 | |
| 61 | var GuestDial types.DialContext |
| 62 | var DNSExchange func(context.Context, *dns.Msg) (*dns.Msg, error) |
| 63 | |
| 64 | func dialGuest(ctx context.Context, network, addr string) (net.Conn, error) { |
| 65 | if GuestDial == nil { |
| 66 | return (&net.Dialer{}).DialContext(ctx, network, addr) |
| 67 | } |
| 68 | dst, err := netip.ParseAddrPort(addr) |
| 69 | if err == nil && dst.Addr().Unmap() == netip.MustParseAddr("127.0.0.1") { |
| 70 | if _, ok := hostServices.Load(hostService{network, dst.Port()}); ok { |
| 71 | return (&net.Dialer{}).DialContext(ctx, network, addr) |
| 72 | } |
| 73 | } |
| 74 | return GuestDial(ctx, network, addr) |
| 75 | } |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | var ( |
| 81 | Names func(name string) bool |
| 82 | Answered func(name string, ips []net.IP) |
| 83 | ) |
| 84 | |
| 85 | type hostService struct { |
| 86 | network string |
| 87 | port uint16 |
| 88 | } |
| 89 | |
| 90 | |
| 91 | var hostServices sync.Map |
| 92 | |
| 93 | |
| 94 | |
| 95 | func AllowHostService(network string, port int) { |
| 96 | hostServices.Store(hostService{network, uint16(port)}, true) |
| 97 | } |
| 98 | |
| 99 | func outbound(network string, dst netip.AddrPort) bool { |
| 100 | if dst.Addr().Unmap() == netip.AddrFrom4([4]byte{127, 0, 0, 1}) { |
| 101 | if _, ok := hostServices.Load(hostService{network, dst.Port()}); ok { |
| 102 | return true |
| 103 | } |
| 104 | } |
| 105 | return Outbound.Allows(network, dst) |
| 106 | } |
| 107 | |
| 108 | func StartGVisorNetstack(ctx context.Context, gVisorOpts *GVisorNetstackOpts) error { |
| 109 | opts = gVisorOpts |
| 110 | |
| 111 | ip, ipNet, err := net.ParseCIDR(opts.Subnet) |
| 112 | if err != nil { |
| 113 | return err |
| 114 | } |
| 115 | gatewayIP := GatewayIP(ip) |
| 116 | |
| 117 | leases := map[string]string{} |
| 118 | if opts.DefaultLeases != nil { |
| 119 | for k, v := range opts.DefaultLeases { |
| 120 | if ipNet.Contains(net.ParseIP(k)) { |
| 121 | leases[k] = v |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | leases[gatewayIP] = gatewayMacAddr |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | config := types.Configuration{ |
| 134 | Debug: false, |
| 135 | MTU: opts.MTU, |
| 136 | Subnet: opts.Subnet, |
| 137 | GatewayIP: gatewayIP, |
| 138 | GatewayMacAddress: gatewayMacAddr, |
| 139 | DHCPStaticLeases: leases, |
| 140 | Forwards: map[string]string{}, |
| 141 | DNS: []types.Zone{}, |
| 142 | DNSSearchDomains: searchDomains(), |
| 143 | NAT: map[string]string{ |
| 144 | gatewayIP: "127.0.0.1", |
| 145 | }, |
| 146 | GatewayVirtualIPs: []string{gatewayIP}, |
| 147 | Outbound: outbound, |
| 148 | DroppedIPv6: DroppedIPv6, |
| 149 | DialContext: dialGuest, |
| 150 | DNSExchange: DNSExchange, |
| 151 | DNSNames: Names, |
| 152 | DNSAnswered: Answered, |
| 153 | } |
| 154 | |
| 155 | groupErrs, ctx := errgroup.WithContext(ctx) |
| 156 | err = run(ctx, groupErrs, &config) |
| 157 | if err != nil { |
| 158 | return err |
| 159 | } |
| 160 | if opts.Async { |
| 161 | return err |
| 162 | } |
| 163 | return groupErrs.Wait() |
| 164 | } |
| 165 | |
| 166 | func run(ctx context.Context, g *errgroup.Group, configuration *types.Configuration) error { |
| 167 | vn, err := virtualnetwork.New(configuration) |
| 168 | if err != nil { |
| 169 | return err |
| 170 | } |
| 171 | |
| 172 | ln, err := net.Listen("unix", opts.Endpoint) |
| 173 | if err != nil { |
| 174 | return err |
| 175 | } |
| 176 | |
| 177 | httpServe(ctx, g, ln, muxWithExtension(vn)) |
| 178 | |
| 179 | if opts.QemuSocket != "" { |
| 180 | err = listenQEMU(ctx, vn) |
| 181 | if err != nil { |
| 182 | return err |
| 183 | } |
| 184 | } |
| 185 | if opts.FdSocket != "" { |
| 186 | err = listenFD(ctx, vn) |
| 187 | if err != nil { |
| 188 | return err |
| 189 | } |
| 190 | } |
| 191 | if opts.DgramConn != nil { |
| 192 | serveDgram(ctx, vn, opts.DgramConn) |
| 193 | } |
| 194 | return nil |
| 195 | } |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | func serveDgram(ctx context.Context, vn *virtualnetwork.VirtualNetwork, conn net.Conn) { |
| 201 | ctx, cancel := context.WithCancel(ctx) |
| 202 | go func() { |
| 203 | <-ctx.Done() |
| 204 | conn.Close() |
| 205 | }() |
| 206 | go func() { |
| 207 | defer cancel() |
| 208 | if err := vn.AcceptBess(ctx, &UDPFileConn{Conn: conn}); err != nil && ctx.Err() == nil { |
| 209 | logrus.Error("QEMU datagram connection closed with error: ", err) |
| 210 | } |
| 211 | }() |
| 212 | } |
| 213 | |
| 214 | func listenQEMU(ctx context.Context, vn *virtualnetwork.VirtualNetwork) error { |
| 215 | var lc net.ListenConfig |
| 216 | listener, err := lc.Listen(ctx, "unix", opts.QemuSocket) |
| 217 | if err != nil { |
| 218 | return err |
| 219 | } |
| 220 | |
| 221 | go func() { |
| 222 | defer listener.Close() |
| 223 | <-ctx.Done() |
| 224 | }() |
| 225 | |
| 226 | go func() { |
| 227 | for { |
| 228 | conn, err := listener.Accept() |
| 229 | if err != nil { |
| 230 | if errors.Is(err, net.ErrClosed) { |
| 231 | return |
| 232 | } |
| 233 | logrus.Error("QEMU accept failed", err) |
| 234 | } |
| 235 | |
| 236 | go func() { |
| 237 | err = vn.AcceptQemu(ctx, conn) |
| 238 | if err != nil { |
| 239 | logrus.Error("QEMU connection closed with error", err) |
| 240 | } |
| 241 | conn.Close() |
| 242 | }() |
| 243 | select { |
| 244 | case <-ctx.Done(): |
| 245 | return |
| 246 | default: |
| 247 | continue |
| 248 | } |
| 249 | } |
| 250 | }() |
| 251 | |
| 252 | return nil |
| 253 | } |
| 254 | |
| 255 | func listenFD(ctx context.Context, vn *virtualnetwork.VirtualNetwork) error { |
| 256 | var lc net.ListenConfig |
| 257 | listener, err := lc.Listen(ctx, "unix", opts.FdSocket) |
| 258 | if err != nil { |
| 259 | return err |
| 260 | } |
| 261 | |
| 262 | go func() { |
| 263 | defer listener.Close() |
| 264 | <-ctx.Done() |
| 265 | }() |
| 266 | |
| 267 | go func() { |
| 268 | for { |
| 269 | conn, err := listener.Accept() |
| 270 | if err != nil { |
| 271 | if errors.Is(err, net.ErrClosed) { |
| 272 | return |
| 273 | } |
| 274 | logrus.Error("FD accept failed", err) |
| 275 | continue |
| 276 | } |
| 277 | |
| 278 | files, err := fd.Get(conn.(*net.UnixConn), 1, []string{"client"}) |
| 279 | if err != nil { |
| 280 | logrus.Error("Failed to get FD via socket", err) |
| 281 | } |
| 282 | |
| 283 | if len(files) != 1 { |
| 284 | logrus.Error("Invalid number of fd in response", err) |
| 285 | } |
| 286 | fileConn, err := net.FileConn(files[0]) |
| 287 | if err != nil { |
| 288 | logrus.Error("Error in FD Socket", err) |
| 289 | } |
| 290 | files[0].Close() |
| 291 | |
| 292 | go func() { |
| 293 | err = vn.AcceptBess(ctx, &UDPFileConn{Conn: fileConn}) |
| 294 | if err != nil { |
| 295 | logrus.Error("FD connection closed with error", err) |
| 296 | } |
| 297 | fileConn.Close() |
| 298 | }() |
| 299 | select { |
| 300 | case <-ctx.Done(): |
| 301 | return |
| 302 | default: |
| 303 | continue |
| 304 | } |
| 305 | } |
| 306 | }() |
| 307 | |
| 308 | return nil |
| 309 | } |
| 310 | |
| 311 | func httpServe(ctx context.Context, g *errgroup.Group, ln net.Listener, mux http.Handler) { |
| 312 | s := &http.Server{ |
| 313 | Handler: mux, |
| 314 | ReadTimeout: 10 * time.Second, |
| 315 | WriteTimeout: 10 * time.Second, |
| 316 | } |
| 317 | g.Go(func() error { |
| 318 | <-ctx.Done() |
| 319 | return s.Close() |
| 320 | }) |
| 321 | g.Go(func() error { |
| 322 | err := s.Serve(ln) |
| 323 | if err != nil { |
| 324 | if err == http.ErrServerClosed { |
| 325 | return nil |
| 326 | } |
| 327 | return err |
| 328 | } |
| 329 | return nil |
| 330 | }) |
| 331 | } |
| 332 | |
| 333 | func muxWithExtension(n *virtualnetwork.VirtualNetwork) *http.ServeMux { |
| 334 | m := n.Mux() |
| 335 | m.HandleFunc("/extension/wait_port", func(w http.ResponseWriter, r *http.Request) { |
| 336 | ip := r.URL.Query().Get("ip") |
| 337 | if net.ParseIP(ip) == nil { |
| 338 | msg := fmt.Sprintf("invalid ip address: %s", ip) |
| 339 | http.Error(w, msg, http.StatusBadRequest) |
| 340 | return |
| 341 | } |
| 342 | port16, err := strconv.ParseUint(r.URL.Query().Get("port"), 10, 16) |
| 343 | if err != nil { |
| 344 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 345 | return |
| 346 | } |
| 347 | port := uint16(port16) |
| 348 | addr := fmt.Sprintf("%s:%d", ip, port) |
| 349 | |
| 350 | timeoutSeconds := 10 |
| 351 | if timeoutString := r.URL.Query().Get("timeout"); timeoutString != "" { |
| 352 | timeout16, err := strconv.ParseUint(timeoutString, 10, 16) |
| 353 | if err != nil { |
| 354 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 355 | return |
| 356 | } |
| 357 | timeoutSeconds = int(timeout16) |
| 358 | } |
| 359 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds)*time.Second) |
| 360 | defer cancel() |
| 361 | |
| 362 | for { |
| 363 | conn, err := n.DialContextTCP(ctx, addr) |
| 364 | if err == nil { |
| 365 | conn.Close() |
| 366 | logrus.Debugf("Port is available on %s", addr) |
| 367 | w.WriteHeader(http.StatusOK) |
| 368 | break |
| 369 | } |
| 370 | select { |
| 371 | case <-ctx.Done(): |
| 372 | msg := fmt.Sprintf("timed out waiting for port to become available on %s", addr) |
| 373 | logrus.Warn(msg) |
| 374 | http.Error(w, msg, http.StatusRequestTimeout) |
| 375 | return |
| 376 | default: |
| 377 | } |
| 378 | logrus.Debugf("Waiting for port to become available on %s", addr) |
| 379 | time.Sleep(1 * time.Second) |
| 380 | } |
| 381 | }) |
| 382 | return m |
| 383 | } |
| 384 | |
| 385 | func searchDomains() []string { |
| 386 | if runtime.GOOS != "windows" { |
| 387 | return resolveSearchDomain("/etc/resolv.conf") |
| 388 | } |
| 389 | return nil |
| 390 | } |
| 391 | |
| 392 | func resolveSearchDomain(file string) []string { |
| 393 | f, err := os.Open(file) |
| 394 | if err != nil { |
| 395 | logrus.Errorf("open file error: %v", err) |
| 396 | return nil |
| 397 | } |
| 398 | defer f.Close() |
| 399 | sc := bufio.NewScanner(f) |
| 400 | searchPrefix := "search " |
| 401 | for sc.Scan() { |
| 402 | if after, ok := strings.CutPrefix(sc.Text(), searchPrefix); ok { |
| 403 | searchDomains := strings.Split(after, " ") |
| 404 | logrus.Debugf("Using search domains: %v", searchDomains) |
| 405 | return searchDomains |
| 406 | } |
| 407 | } |
| 408 | if err := sc.Err(); err != nil { |
| 409 | logrus.Errorf("scan file error: %v", err) |
| 410 | return nil |
| 411 | } |
| 412 | return nil |
| 413 | } |