github.com/rawahars/moby@v24.0.4+incompatible/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  			host = "unix://" + filepath.Join(runtimeDir, "docker.sock")
    64  		} else {
    65  			host = DefaultHost
    66  		}
    67  	} else {
    68  		var err error
    69  		host, err = parseDaemonHost(host)
    70  		if err != nil {
    71  			return val, err
    72  		}
    73  	}
    74  	return host, nil
    75  }
    76  
    77  // parseDaemonHost parses the specified address and returns an address that will be used as the host.
    78  // Depending on the address specified, this may return one of the global Default* strings defined in hosts.go.
    79  func parseDaemonHost(address string) (string, error) {
    80  	proto, addr, ok := strings.Cut(address, "://")
    81  	if !ok && proto != "" {
    82  		addr = proto
    83  		proto = "tcp"
    84  	}
    85  
    86  	switch proto {
    87  	case "tcp":
    88  		return ParseTCPAddr(address, DefaultTCPHost)
    89  	case "unix":
    90  		a, err := parseSimpleProtoAddr(proto, addr, DefaultUnixSocket)
    91  		if err != nil {
    92  			return "", errors.Wrapf(err, "invalid bind address (%s)", address)
    93  		}
    94  		return a, nil
    95  	case "npipe":
    96  		a, err := parseSimpleProtoAddr(proto, addr, DefaultNamedPipe)
    97  		if err != nil {
    98  			return "", errors.Wrapf(err, "invalid bind address (%s)", address)
    99  		}
   100  		return a, nil
   101  	case "fd":
   102  		return address, nil
   103  	default:
   104  		return "", errors.Errorf("invalid bind address (%s): unsupported proto '%s'", address, proto)
   105  	}
   106  }
   107  
   108  // parseSimpleProtoAddr parses and validates that the specified address is a valid
   109  // socket address for simple protocols like unix and npipe. It returns a formatted
   110  // socket address, either using the address parsed from addr, or the contents of
   111  // defaultAddr if addr is a blank string.
   112  func parseSimpleProtoAddr(proto, addr, defaultAddr string) (string, error) {
   113  	if strings.Contains(addr, "://") {
   114  		return "", errors.Errorf("invalid %s address: %s", proto, addr)
   115  	}
   116  	if addr == "" {
   117  		addr = defaultAddr
   118  	}
   119  	return proto + "://" + addr, nil
   120  }
   121  
   122  // ParseTCPAddr parses and validates that the specified address is a valid TCP
   123  // address. It returns a formatted TCP address, either using the address parsed
   124  // from tryAddr, or the contents of defaultAddr if tryAddr is a blank string.
   125  // tryAddr is expected to have already been Trim()'d
   126  // defaultAddr must be in the full `tcp://host:port` form
   127  func ParseTCPAddr(tryAddr string, defaultAddr string) (string, error) {
   128  	def, err := parseTCPAddr(defaultAddr, true)
   129  	if err != nil {
   130  		return "", errors.Wrapf(err, "invalid default address (%s)", defaultAddr)
   131  	}
   132  
   133  	addr, err := parseTCPAddr(tryAddr, false)
   134  	if err != nil {
   135  		return "", errors.Wrapf(err, "invalid bind address (%s)", tryAddr)
   136  	}
   137  
   138  	host := addr.Hostname()
   139  	if host == "" {
   140  		host = def.Hostname()
   141  	}
   142  	port := addr.Port()
   143  	if port == "" {
   144  		port = def.Port()
   145  	}
   146  
   147  	return "tcp://" + net.JoinHostPort(host, port), nil
   148  }
   149  
   150  // parseTCPAddr parses the given addr and validates if it is in the expected
   151  // format. If strict is enabled, the address must contain a scheme (tcp://),
   152  // a host (or IP-address) and a port number.
   153  func parseTCPAddr(address string, strict bool) (*url.URL, error) {
   154  	if !strict && !strings.Contains(address, "://") {
   155  		address = "tcp://" + address
   156  	}
   157  	parsedURL, err := url.Parse(address)
   158  	if err != nil {
   159  		return nil, err
   160  	}
   161  	if parsedURL.Scheme != "tcp" {
   162  		return nil, errors.Errorf("unsupported proto '%s'", parsedURL.Scheme)
   163  	}
   164  	if parsedURL.Path != "" {
   165  		return nil, errors.New("should not contain a path element")
   166  	}
   167  	if strict && parsedURL.Host == "" {
   168  		return nil, errors.New("no host or IP address")
   169  	}
   170  	if parsedURL.Port() != "" || strict {
   171  		if p, err := strconv.Atoi(parsedURL.Port()); err != nil || p == 0 {
   172  			return nil, errors.Errorf("invalid port: %s", parsedURL.Port())
   173  		}
   174  	}
   175  	return parsedURL, nil
   176  }
   177  
   178  // ValidateExtraHost validates that the specified string is a valid extrahost and returns it.
   179  // ExtraHost is in the form of name:ip where the ip has to be a valid ip (IPv4 or IPv6).
   180  func ValidateExtraHost(val string) (string, error) {
   181  	// allow for IPv6 addresses in extra hosts by only splitting on first ":"
   182  	name, ip, ok := strings.Cut(val, ":")
   183  	if !ok || name == "" {
   184  		return "", errors.Errorf("bad format for add-host: %q", val)
   185  	}
   186  	// Skip IPaddr validation for special "host-gateway" string
   187  	if ip != HostGatewayName {
   188  		if _, err := ValidateIPAddress(ip); err != nil {
   189  			return "", errors.Errorf("invalid IP address in add-host: %q", ip)
   190  		}
   191  	}
   192  	return val, nil
   193  }