github.com/devdivbcp/moby@v17.12.0-ce-rc1.0.20200726071732-2d4bfdc789ad+incompatible/opts/hosts.go (about)

     1  package opts // import "github.com/docker/docker/opts"
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"net/url"
     7  	"path/filepath"
     8  	"strconv"
     9  	"strings"
    10  
    11  	"github.com/docker/docker/pkg/homedir"
    12  )
    13  
    14  var (
    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 = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultHTTPPort)
    26  	// DefaultTLSHost constant defines the default host string used by docker for TLS sockets
    27  	DefaultTLSHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultTLSHTTPPort)
    28  	// DefaultNamedPipe defines the default named pipe used by docker on Windows
    29  	DefaultNamedPipe = `//./pipe/docker_engine`
    30  )
    31  
    32  // ValidateHost validates that the specified string is a valid host and returns it.
    33  func ValidateHost(val string) (string, error) {
    34  	host := strings.TrimSpace(val)
    35  	// The empty string means default and is not handled by parseDaemonHost
    36  	if host != "" {
    37  		_, err := parseDaemonHost(host)
    38  		if err != nil {
    39  			return val, err
    40  		}
    41  	}
    42  	// Note: unlike most flag validators, we don't return the mutated value here
    43  	//       we need to know what the user entered later (using ParseHost) to adjust for TLS
    44  	return val, nil
    45  }
    46  
    47  // ParseHost and set defaults for a Daemon host string.
    48  // defaultToTLS is preferred over defaultToUnixXDG.
    49  func ParseHost(defaultToTLS, defaultToUnixXDG bool, val string) (string, error) {
    50  	host := strings.TrimSpace(val)
    51  	if host == "" {
    52  		if defaultToTLS {
    53  			host = DefaultTLSHost
    54  		} else if defaultToUnixXDG {
    55  			runtimeDir, err := homedir.GetRuntimeDir()
    56  			if err != nil {
    57  				return "", err
    58  			}
    59  			socket := filepath.Join(runtimeDir, "docker.sock")
    60  			host = "unix://" + socket
    61  		} else {
    62  			host = DefaultHost
    63  		}
    64  	} else {
    65  		var err error
    66  		host, err = parseDaemonHost(host)
    67  		if err != nil {
    68  			return val, err
    69  		}
    70  	}
    71  	return host, nil
    72  }
    73  
    74  // parseDaemonHost parses the specified address and returns an address that will be used as the host.
    75  // Depending of the address specified, this may return one of the global Default* strings defined in hosts.go.
    76  func parseDaemonHost(addr string) (string, error) {
    77  	addrParts := strings.SplitN(addr, "://", 2)
    78  	if len(addrParts) == 1 && addrParts[0] != "" {
    79  		addrParts = []string{"tcp", addrParts[0]}
    80  	}
    81  
    82  	switch addrParts[0] {
    83  	case "tcp":
    84  		return ParseTCPAddr(addrParts[1], DefaultTCPHost)
    85  	case "unix":
    86  		return parseSimpleProtoAddr("unix", addrParts[1], DefaultUnixSocket)
    87  	case "npipe":
    88  		return parseSimpleProtoAddr("npipe", addrParts[1], DefaultNamedPipe)
    89  	case "fd":
    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 returns it.
   165  // ExtraHost is in the form of name:ip where the ip has to be a valid ip (IPv4 or IPv6).
   166  func ValidateExtraHost(val string) (string, error) {
   167  	// allow for IPv6 addresses in extra hosts by only splitting on first ":"
   168  	arr := strings.SplitN(val, ":", 2)
   169  	if len(arr) != 2 || len(arr[0]) == 0 {
   170  		return "", fmt.Errorf("bad format for add-host: %q", val)
   171  	}
   172  	if _, err := ValidateIPAddress(arr[1]); err != nil {
   173  		return "", fmt.Errorf("invalid IP address in add-host: %q", arr[1])
   174  	}
   175  	return val, nil
   176  }