tcp_socket.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Package sockets provides helper functions to create and configure Unix or TCP
  2. // sockets.
  3. package sockets
  4. import (
  5. "crypto/tls"
  6. "net"
  7. "net/http"
  8. "time"
  9. "github.com/docker/docker/pkg/listenbuffer"
  10. )
  11. // NewTCPSocket creates a TCP socket listener with the specified address and
  12. // and the specified tls configuration. If TLSConfig is set, will encapsulate the
  13. // TCP listener inside a TLS one.
  14. // The channel passed is used to activate the listenbuffer when the caller is ready
  15. // to accept connections.
  16. func NewTCPSocket(addr string, tlsConfig *tls.Config, activate <-chan struct{}) (net.Listener, error) {
  17. l, err := listenbuffer.NewListenBuffer("tcp", addr, activate)
  18. if err != nil {
  19. return nil, err
  20. }
  21. if tlsConfig != nil {
  22. tlsConfig.NextProtos = []string{"http/1.1"}
  23. l = tls.NewListener(l, tlsConfig)
  24. }
  25. return l, nil
  26. }
  27. // ConfigureTCPTransport configures the specified Transport according to the
  28. // specified proto and addr.
  29. // If the proto is unix (using a unix socket to communicate) the compression
  30. // is disabled.
  31. func ConfigureTCPTransport(tr *http.Transport, proto, addr string) {
  32. // Why 32? See https://github.com/docker/docker/pull/8035.
  33. timeout := 32 * time.Second
  34. if proto == "unix" {
  35. // No need for compression in local communications.
  36. tr.DisableCompression = true
  37. tr.Dial = func(_, _ string) (net.Conn, error) {
  38. return net.DialTimeout(proto, addr, timeout)
  39. }
  40. } else {
  41. tr.Proxy = http.ProxyFromEnvironment
  42. tr.Dial = (&net.Dialer{Timeout: timeout}).Dial
  43. }
  44. }