github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/opts/hosts.go (about)

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