|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "log" |
| 5 | + "net/http" |
| 6 | + "net/http/httputil" |
| 7 | + "net/url" |
| 8 | + "os" |
| 9 | +) |
| 10 | + |
| 11 | +// newHandler creates a new http.Handler with CSRF protection |
| 12 | +func newHandler(dir string, d string, e string, tlsFlags TLSFlags) http.Handler { |
| 13 | + var ( |
| 14 | + mux = http.NewServeMux() |
| 15 | + fileHandler = http.FileServer(http.Dir(dir)) |
| 16 | + ) |
| 17 | + |
| 18 | + u, perr := url.Parse(e) |
| 19 | + if perr != nil { |
| 20 | + log.Fatal(perr) |
| 21 | + } |
| 22 | + |
| 23 | + handler := newAPIHandler(u, tlsFlags) |
| 24 | + CSRFHandler := newCSRFHandler(d) |
| 25 | + |
| 26 | + mux.Handle("/dockerapi/", http.StripPrefix("/dockerapi", handler)) |
| 27 | + mux.Handle("/", fileHandler) |
| 28 | + return CSRFHandler(newCSRFWrapper(mux)) |
| 29 | +} |
| 30 | + |
| 31 | +// newAPIHandler initializes a new http.Handler based on the URL scheme |
| 32 | +func newAPIHandler(u *url.URL, tlsFlags TLSFlags) http.Handler { |
| 33 | + var handler http.Handler |
| 34 | + if u.Scheme == "tcp" { |
| 35 | + if tlsFlags.tls { |
| 36 | + handler = newTCPHandlerWithTLS(u, tlsFlags) |
| 37 | + } else { |
| 38 | + handler = newTCPHandler(u) |
| 39 | + } |
| 40 | + } else if u.Scheme == "unix" { |
| 41 | + socketPath := u.Path |
| 42 | + if _, err := os.Stat(socketPath); err != nil { |
| 43 | + if os.IsNotExist(err) { |
| 44 | + log.Fatalf("Unix socket %s does not exist", socketPath) |
| 45 | + } |
| 46 | + log.Fatal(err) |
| 47 | + } |
| 48 | + handler = newUnixHandler(socketPath) |
| 49 | + } else { |
| 50 | + log.Fatalf("Bad Docker enpoint: %s. Only unix:// and tcp:// are supported.", u) |
| 51 | + } |
| 52 | + return handler |
| 53 | +} |
| 54 | + |
| 55 | +// newUnixHandler initializes a new UnixHandler |
| 56 | +func newUnixHandler(e string) http.Handler { |
| 57 | + return &unixHandler{e} |
| 58 | +} |
| 59 | + |
| 60 | +// newTCPHandler initializes a HTTP reverse proxy |
| 61 | +func newTCPHandler(u *url.URL) http.Handler { |
| 62 | + u.Scheme = "http" |
| 63 | + return httputil.NewSingleHostReverseProxy(u) |
| 64 | +} |
| 65 | + |
| 66 | +// newTCPHandlerWithL initializes a HTTPS reverse proxy with a TLS configuration |
| 67 | +func newTCPHandlerWithTLS(u *url.URL, tlsFlags TLSFlags) http.Handler { |
| 68 | + u.Scheme = "https" |
| 69 | + var tlsConfig = newTLSConfig(tlsFlags) |
| 70 | + proxy := httputil.NewSingleHostReverseProxy(u) |
| 71 | + proxy.Transport = &http.Transport{ |
| 72 | + TLSClientConfig: tlsConfig, |
| 73 | + } |
| 74 | + return proxy |
| 75 | +} |
0 commit comments