github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/opts/hosts.go (about)

     1  package opts // import "github.com/docker/docker/opts"
     2  
     3  import (
     4  	"net"
     5  	"net/url"
     6  	"path/filepath"
     7  	"strconv"
     8  	"strings"
     9  
    10  	"github.com/docker/docker/pkg/homedir"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  const (
    15  	// DefaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. dockerd -H tcp://
    16  	// These are the IANA registered port numbers for use with Docker
    17  	// see http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=docker
    18  	DefaultHTTPPort = 2375 // Default HTTP Port
    19  	// DefaultTLSHTTPPort Default HTTP Port used when TLS enabled
    20  	DefaultTLSHTTPPort = 2376 // Default TLS encrypted HTTP Port
    21  	// DefaultUnixSocket Path for the unix socket.
    22  	// Docker daemon by default always listens on the default unix socket
    23  	DefaultUnixSocket = "/var/run/docker.sock"
    24  	// DefaultTCPHost constant defines the default host string used by docker on Windows
    25  	DefaultTCPHost = "tcp://" + DefaultHTTPHost + ":2375"
    26  	// DefaultTLSHost constant defines the default host string used by docker for TLS sockets
    27  	DefaultTLSHost = "tcp://" + DefaultHTTPHost + ":2376"
    28  	// DefaultNamedPipe defines the default named pipe used by docker on Windows
    29  	DefaultNamedPipe = `//./pipe/docker_engine`
    30  	// HostGatewayName is the string value that can be passed
    31  	// to the IPAddr section in --add-host that is replaced by
    32  	// the value of HostGatewayIP daemon config value
    33  	HostGatewayName = "host-gateway"
    34  )
    35  
    36  // ValidateHost validates that the specified string is a valid host and returns it.
    37  func ValidateHost(val string) (string, error) {
    38  	host := strings.TrimSpace(val)
    39  	// The empty string means default and is not handled by parseDaemonHost
    40  	if host != "" {
    41  		_, err := parseDaemonHost(host)
    42  		if err != nil {
    43  			return val, err
    44  		}
    45  	}
    46  	// Note: unlike most flag validators, we don't return the mutated value here
    47  	//       we need to know what the user entered later (using ParseHost) to adjust for TLS
    48  	return val, nil
    49  }
    50  
    51  // ParseHost and set defaults for a Daemon host string.
    52  // defaultToTLS is preferred over defaultToUnixXDG.
    53  func ParseHost(defaultToTLS, defaultToUnixXDG bool, val string) (string, error) {
    54  	host := strings.TrimSpace(val)
    55  	if host == "" {
    56  		if defaultToTLS {
    57  			host = DefaultTLSHost
    58  		} else if defaultToUnixXDG {
    59  			runtimeDir, err := homedir.GetRuntimeDir()
    60  			if err != nil {
    61  				return "", err
    62  			}
    63  			socket := filepath.Join(runtimeDir, "docker.sock")
    64  			host = "unix://" + socket
    65  		} else {
    66  			host = DefaultHost
    67  		}
    68  	} else {
    69  		var err error
    70  		host, err = parseDaemonHost(host)
    71  		if err != nil {
    72  			return val, err
    73  		}
    74  	}
    75  	return host, nil
    76  }
    77  
    78  // parseDaemonHost parses the specified address and returns an address that will be used as the host.
    79  // Depending on the address specified, this may return one of the global Default* strings defined in hosts.go.
    80  func parseDaemonHost(addr string) (string, error) {
    81  	addrParts := strings.SplitN(addr, "://", 2)
    82  	if len(addrParts) == 1 && addrParts[0] != "" {
    83  		addrParts = []string{"tcp", addrParts[0]}
    84  	}
    85  
    86  	switch addrParts[0] {
    87  	case "tcp":
    88  		return ParseTCPAddr(addr, DefaultTCPHost)
    89  	case "unix":
    90  		return parseSimpleProtoAddr("unix", addrParts[1], DefaultUnixSocket)
    91  	case "npipe":
    92  		return parseSimpleProtoAddr("npipe", addrParts[1], DefaultNamedPipe)
    93  	case "fd":
    94  		return addr, nil
    95  	default:
    96  		return "", errors.Errorf("invalid bind address (%s): unsupported proto '%s'", addr, addrParts[0])
    97  	}
    98  }
    99  
   100  // parseSimpleProtoAddr parses and validates that the specified address is a valid
   101  // socket address for simple protocols like unix and npipe. It returns a formatted
   102  // socket address, either using the address parsed from addr, or the contents of
   103  // defaultAddr if addr is a blank string.
   104  func parseSimpleProtoAddr(proto, addr, defaultAddr string) (string, error) {
   105  	addr = strings.TrimPrefix(addr, proto+"://")
   106  	if strings.Contains(addr, "://") {
   107  		return "", errors.Errorf("invalid proto, expected %s: %s", proto, addr)
   108  	}
   109  	if addr == "" {
   110  		addr = defaultAddr
   111  	}
   112  	return proto + "://" + addr, nil
   113  }
   114  
   115  // ParseTCPAddr parses and validates that the specified address is a valid TCP
   116  // address. It returns a formatted TCP address, either using the address parsed
   117  // from tryAddr, or the contents of defaultAddr if tryAddr is a blank string.
   118  // tryAddr is expected to have already been Trim()'d
   119  // defaultAddr must be in the full `tcp://host:port` form
   120  func ParseTCPAddr(tryAddr string, defaultAddr string) (string, error) {
   121  	def, err := parseTCPAddr(defaultAddr, true)
   122  	if err != nil {
   123  		return "", errors.Wrapf(err, "invalid default address (%s)", defaultAddr)
   124  	}
   125  
   126  	addr, err := parseTCPAddr(tryAddr, false)
   127  	if err != nil {
   128  		return "", errors.Wrapf(err, "invalid bind address (%s)", tryAddr)
   129  	}
   130  
   131  	host := addr.Hostname()
   132  	if host == "" {
   133  		host = def.Hostname()
   134  	}
   135  	port := addr.Port()
   136  	if port == "" {
   137  		port = def.Port()
   138  	}
   139  
   140  	return "tcp://" + net.JoinHostPort(host, port), nil
   141  }
   142  
   143  // parseTCPAddr parses the given addr and validates if it is in the expected
   144  // format. If strict is enabled, the address must contain a scheme (tcp://),
   145  // a host (or IP-address) and a port number.
   146  func parseTCPAddr(address string, strict bool) (*url.URL, error) {
   147  	if !strict && !strings.Contains(address, "://") {
   148  		address = "tcp://" + address
   149  	}
   150  	parsedURL, err := url.Parse(address)
   151  	if err != nil {
   152  		return nil, err
   153  	}
   154  	if parsedURL.Scheme != "tcp" {
   155  		return nil, errors.Errorf("unsupported proto '%s'", parsedURL.Scheme)
   156  	}
   157  	if parsedURL.Path != "" {
   158  		return nil, errors.New("should not contain a path element")
   159  	}
   160  	if strict && parsedURL.Host == "" {
   161  		return nil, errors.New("no host or IP address")
   162  	}
   163  	if parsedURL.Port() != "" || strict {
   164  		if p, err := strconv.Atoi(parsedURL.Port()); err != nil || p == 0 {
   165  			return nil, errors.Errorf("invalid port: %s", parsedURL.Port())
   166  		}
   167  	}
   168  	return parsedURL, nil
   169  }
   170  
   171  // ValidateExtraHost validates that the specified string is a valid extrahost and returns it.
   172  // ExtraHost is in the form of name:ip where the ip has to be a valid ip (IPv4 or IPv6).
   173  func ValidateExtraHost(val string) (string, error) {
   174  	// allow for IPv6 addresses in extra hosts by only splitting on first ":"
   175  	arr := strings.SplitN(val, ":", 2)
   176  	if len(arr) != 2 || len(arr[0]) == 0 {
   177  		return "", errors.Errorf("bad format for add-host: %q", val)
   178  	}
   179  	// Skip IPaddr validation for special "host-gateway" string
   180  	if arr[1] != HostGatewayName {
   181  		if _, err := ValidateIPAddress(arr[1]); err != nil {
   182  			return "", errors.Errorf("invalid IP address in add-host: %q", arr[1])
   183  		}
   184  	}
   185  	return val, nil
   186  }