github.com/khulnasoft/cli@v0.0.0-20240402070845-01bcad7beefa/opts/hosts.go (about)

     1  package opts
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"net/url"
     7  	"strconv"
     8  	"strings"
     9  )
    10  
    11  const (
    12  	// defaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. dockerd -H tcp://
    13  	// These are the IANA registered port numbers for use with Docker
    14  	// see http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=docker
    15  	defaultHTTPPort = "2375" // Default HTTP Port
    16  	// defaultTLSHTTPPort Default HTTP Port used when TLS enabled
    17  	defaultTLSHTTPPort = "2376" // Default TLS encrypted HTTP Port
    18  	// defaultUnixSocket Path for the unix socket.
    19  	// Docker daemon by default always listens on the default unix socket
    20  	defaultUnixSocket = "/var/run/docker.sock"
    21  	// defaultTCPHost constant defines the default host string used by docker on Windows
    22  	defaultTCPHost = "tcp://" + defaultHTTPHost + ":" + defaultHTTPPort
    23  	// DefaultTLSHost constant defines the default host string used by docker for TLS sockets
    24  	defaultTLSHost = "tcp://" + defaultHTTPHost + ":" + defaultTLSHTTPPort
    25  	// DefaultNamedPipe defines the default named pipe used by docker on Windows
    26  	defaultNamedPipe = `//./pipe/docker_engine`
    27  	// hostGatewayName defines a special string which users can append to --add-host
    28  	// to add an extra entry in /etc/hosts that maps host.docker.internal to the host IP
    29  	// TODO Consider moving the hostGatewayName constant defined in docker at
    30  	// github.com/docker/docker/daemon/network/constants.go outside of the "daemon"
    31  	// package, so that the CLI can consume it.
    32  	hostGatewayName = "host-gateway"
    33  )
    34  
    35  // ValidateHost validates that the specified string is a valid host and returns it.
    36  //
    37  // TODO(thaJeztah): ValidateHost appears to be unused; deprecate it.
    38  func ValidateHost(val string) (string, error) {
    39  	host := strings.TrimSpace(val)
    40  	// The empty string means default and is not handled by parseDockerDaemonHost
    41  	if host != "" {
    42  		_, err := parseDockerDaemonHost(host)
    43  		if err != nil {
    44  			return val, err
    45  		}
    46  	}
    47  	// Note: unlike most flag validators, we don't return the mutated value here
    48  	//       we need to know what the user entered later (using ParseHost) to adjust for TLS
    49  	return val, nil
    50  }
    51  
    52  // ParseHost and set defaults for a Daemon host string
    53  func ParseHost(defaultToTLS bool, val string) (string, error) {
    54  	host := strings.TrimSpace(val)
    55  	if host == "" {
    56  		if defaultToTLS {
    57  			host = defaultTLSHost
    58  		} else {
    59  			host = defaultHost
    60  		}
    61  	} else {
    62  		var err error
    63  		host, err = parseDockerDaemonHost(host)
    64  		if err != nil {
    65  			return val, err
    66  		}
    67  	}
    68  	return host, nil
    69  }
    70  
    71  // parseDockerDaemonHost parses the specified address and returns an address that will be used as the host.
    72  // Depending of the address specified, this may return one of the global Default* strings defined in hosts.go.
    73  func parseDockerDaemonHost(addr string) (string, error) {
    74  	proto, host, hasProto := strings.Cut(addr, "://")
    75  	if !hasProto && proto != "" {
    76  		host = proto
    77  		proto = "tcp"
    78  	}
    79  
    80  	switch proto {
    81  	case "tcp":
    82  		return ParseTCPAddr(host, defaultTCPHost)
    83  	case "unix":
    84  		return parseSimpleProtoAddr(proto, host, defaultUnixSocket)
    85  	case "npipe":
    86  		return parseSimpleProtoAddr(proto, host, defaultNamedPipe)
    87  	case "fd":
    88  		return addr, nil
    89  	case "ssh":
    90  		return addr, nil
    91  	default:
    92  		return "", fmt.Errorf("invalid bind address format: %s", addr)
    93  	}
    94  }
    95  
    96  // parseSimpleProtoAddr parses and validates that the specified address is a valid
    97  // socket address for simple protocols like unix and npipe. It returns a formatted
    98  // socket address, either using the address parsed from addr, or the contents of
    99  // defaultAddr if addr is a blank string.
   100  func parseSimpleProtoAddr(proto, addr, defaultAddr string) (string, error) {
   101  	addr = strings.TrimPrefix(addr, proto+"://")
   102  	if strings.Contains(addr, "://") {
   103  		return "", fmt.Errorf("invalid proto, expected %s: %s", proto, addr)
   104  	}
   105  	if addr == "" {
   106  		addr = defaultAddr
   107  	}
   108  	return fmt.Sprintf("%s://%s", proto, addr), nil
   109  }
   110  
   111  // ParseTCPAddr parses and validates that the specified address is a valid TCP
   112  // address. It returns a formatted TCP address, either using the address parsed
   113  // from tryAddr, or the contents of defaultAddr if tryAddr is a blank string.
   114  // tryAddr is expected to have already been Trim()'d
   115  // defaultAddr must be in the full `tcp://host:port` form
   116  func ParseTCPAddr(tryAddr string, defaultAddr string) (string, error) {
   117  	if tryAddr == "" || tryAddr == "tcp://" {
   118  		return defaultAddr, nil
   119  	}
   120  	addr := strings.TrimPrefix(tryAddr, "tcp://")
   121  	if strings.Contains(addr, "://") || addr == "" {
   122  		return "", fmt.Errorf("invalid proto, expected tcp: %s", tryAddr)
   123  	}
   124  
   125  	defaultAddr = strings.TrimPrefix(defaultAddr, "tcp://")
   126  	defaultHost, defaultPort, err := net.SplitHostPort(defaultAddr)
   127  	if err != nil {
   128  		return "", err
   129  	}
   130  	// url.Parse fails for trailing colon on IPv6 brackets on Go 1.5, but
   131  	// not 1.4. See https://github.com/golang/go/issues/12200 and
   132  	// https://github.com/golang/go/issues/6530.
   133  	if strings.HasSuffix(addr, "]:") {
   134  		addr += defaultPort
   135  	}
   136  
   137  	u, err := url.Parse("tcp://" + addr)
   138  	if err != nil {
   139  		return "", err
   140  	}
   141  	host, port, err := net.SplitHostPort(u.Host)
   142  	if err != nil {
   143  		// try port addition once
   144  		host, port, err = net.SplitHostPort(net.JoinHostPort(u.Host, defaultPort))
   145  	}
   146  	if err != nil {
   147  		return "", fmt.Errorf("invalid bind address format: %s", tryAddr)
   148  	}
   149  
   150  	if host == "" {
   151  		host = defaultHost
   152  	}
   153  	if port == "" {
   154  		port = defaultPort
   155  	}
   156  	p, err := strconv.Atoi(port)
   157  	if err != nil && p == 0 {
   158  		return "", fmt.Errorf("invalid bind address format: %s", tryAddr)
   159  	}
   160  
   161  	return fmt.Sprintf("tcp://%s%s", net.JoinHostPort(host, port), u.Path), nil
   162  }
   163  
   164  // ValidateExtraHost validates that the specified string is a valid extrahost and
   165  // returns it. ExtraHost is in the form of name:ip or name=ip, where the ip has
   166  // to be a valid ip (IPv4 or IPv6). The address may be enclosed in square
   167  // brackets.
   168  //
   169  // For example:
   170  //
   171  //	my-hostname:127.0.0.1
   172  //	my-hostname:::1
   173  //	my-hostname=::1
   174  //	my-hostname:[::1]
   175  //
   176  // For compatibility with the API server, this function normalises the given
   177  // argument to use the ':' separator and strip square brackets enclosing the
   178  // address.
   179  func ValidateExtraHost(val string) (string, error) {
   180  	k, v, ok := strings.Cut(val, "=")
   181  	if !ok {
   182  		// allow for IPv6 addresses in extra hosts by only splitting on first ":"
   183  		k, v, ok = strings.Cut(val, ":")
   184  	}
   185  	// Check that a hostname was given, and that it doesn't contain a ":". (Colon
   186  	// isn't allowed in a hostname, along with many other characters. It's
   187  	// special-cased here because the API server doesn't know about '=' separators in
   188  	// '--add-host'. So, it'll split at the first colon and generate a strange error
   189  	// message.)
   190  	if !ok || k == "" || strings.Contains(k, ":") {
   191  		return "", fmt.Errorf("bad format for add-host: %q", val)
   192  	}
   193  	// Skip IPaddr validation for "host-gateway" string
   194  	if v != hostGatewayName {
   195  		// If the address is enclosed in square brackets, extract it (for IPv6, but
   196  		// permit it for IPv4 as well; we don't know the address family here, but it's
   197  		// unambiguous).
   198  		if len(v) > 2 && v[0] == '[' && v[len(v)-1] == ']' {
   199  			v = v[1 : len(v)-1]
   200  		}
   201  		// ValidateIPAddress returns the address in canonical form (for example,
   202  		// 0:0:0:0:0:0:0:1 -> ::1). But, stick with the original form, to avoid
   203  		// surprising a user who's expecting to see the address they supplied in the
   204  		// output of 'docker inspect' or '/etc/hosts'.
   205  		if _, err := ValidateIPAddress(v); err != nil {
   206  			return "", fmt.Errorf("invalid IP address in add-host: %q", v)
   207  		}
   208  	}
   209  	// This result is passed directly to the API, the daemon doesn't accept the '='
   210  	// separator or an address enclosed in brackets. So, construct something it can
   211  	// understand.
   212  	return k + ":" + v, nil
   213  }