]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/net/http/cgi/host.go
net/http/cgi: the PATH_INFO should be empty or start with a slash
[gostls13.git] / src / net / http / cgi / host.go
index ec95a972c1a425b860c78d6456f320ec5d748d26..ef222ab73a75c0ce2c6d897bd635470f503ca071 100644 (file)
@@ -10,7 +10,7 @@
 //
 // Note that using CGI means starting a new process to handle each
 // request, which is typically less efficient than using a
-// long-running server.  This package is intended primarily for
+// long-running server. This package is intended primarily for
 // compatibility with existing systems.
 package cgi
 
@@ -19,7 +19,9 @@ import (
        "fmt"
        "io"
        "log"
+       "net"
        "net/http"
+       "net/textproto"
        "os"
        "os/exec"
        "path/filepath"
@@ -27,20 +29,29 @@ import (
        "runtime"
        "strconv"
        "strings"
+
+       "golang.org/x/net/http/httpguts"
 )
 
 var trailingPort = regexp.MustCompile(`:([0-9]+)$`)
 
-var osDefaultInheritEnv = map[string][]string{
-       "darwin":  {"DYLD_LIBRARY_PATH"},
-       "freebsd": {"LD_LIBRARY_PATH"},
-       "hpux":    {"LD_LIBRARY_PATH", "SHLIB_PATH"},
-       "irix":    {"LD_LIBRARY_PATH", "LD_LIBRARYN32_PATH", "LD_LIBRARY64_PATH"},
-       "linux":   {"LD_LIBRARY_PATH"},
-       "openbsd": {"LD_LIBRARY_PATH"},
-       "solaris": {"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"},
-       "windows": {"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"},
-}
+var osDefaultInheritEnv = func() []string {
+       switch runtime.GOOS {
+       case "darwin", "ios":
+               return []string{"DYLD_LIBRARY_PATH"}
+       case "android", "linux", "freebsd", "netbsd", "openbsd":
+               return []string{"LD_LIBRARY_PATH"}
+       case "hpux":
+               return []string{"LD_LIBRARY_PATH", "SHLIB_PATH"}
+       case "irix":
+               return []string{"LD_LIBRARY_PATH", "LD_LIBRARYN32_PATH", "LD_LIBRARY64_PATH"}
+       case "illumos", "solaris":
+               return []string{"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"}
+       case "windows":
+               return []string{"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"}
+       }
+       return nil
+}()
 
 // Handler runs an executable in a subprocess with a CGI environment.
 type Handler struct {
@@ -57,6 +68,7 @@ type Handler struct {
        InheritEnv []string    // environment variables to inherit from host, as "key"
        Logger     *log.Logger // optional log for errors or nil to use log.Print
        Args       []string    // optional arguments to pass to child process
+       Stderr     io.Writer   // optional stderr for the child process; nil means os.Stderr
 
        // PathLocationHandler specifies the root http Handler that
        // should handle internal redirects when the CGI process
@@ -69,22 +81,30 @@ type Handler struct {
        PathLocationHandler http.Handler
 }
 
+func (h *Handler) stderr() io.Writer {
+       if h.Stderr != nil {
+               return h.Stderr
+       }
+       return os.Stderr
+}
+
 // removeLeadingDuplicates remove leading duplicate in environments.
 // It's possible to override environment like following.
-//    cgi.Handler{
-//      ...
-//      Env: []string{"SCRIPT_FILENAME=foo.php"},
-//    }
+//
+//     cgi.Handler{
+//       ...
+//       Env: []string{"SCRIPT_FILENAME=foo.php"},
+//     }
 func removeLeadingDuplicates(env []string) (ret []string) {
-       n := len(env)
-       for i := 0; i < n; i++ {
-               e := env[i]
-               s := strings.SplitN(e, "=", 2)[0]
+       for i, e := range env {
                found := false
-               for j := i + 1; j < n; j++ {
-                       if s == strings.SplitN(env[j], "=", 2)[0] {
-                               found = true
-                               break
+               if eq := strings.IndexByte(e, '='); eq != -1 {
+                       keq := e[:eq+1] // "key="
+                       for _, e2 := range env[i+1:] {
+                               if strings.HasPrefix(e2, keq) {
+                                       found = true
+                                       break
+                               }
                        }
                }
                if !found {
@@ -95,30 +115,25 @@ func removeLeadingDuplicates(env []string) (ret []string) {
 }
 
 func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
-       root := h.Root
-       if root == "" {
-               root = "/"
-       }
-
        if len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked" {
                rw.WriteHeader(http.StatusBadRequest)
                rw.Write([]byte("Chunked request bodies are not supported by CGI."))
                return
        }
 
-       pathInfo := req.URL.Path
-       if root != "/" && strings.HasPrefix(pathInfo, root) {
-               pathInfo = pathInfo[len(root):]
-       }
+       root := strings.TrimRight(h.Root, "/")
+       pathInfo := strings.TrimPrefix(req.URL.Path, root)
 
        port := "80"
+       if req.TLS != nil {
+               port = "443"
+       }
        if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 {
                port = matches[1]
        }
 
        env := []string{
                "SERVER_SOFTWARE=go",
-               "SERVER_NAME=" + req.Host,
                "SERVER_PROTOCOL=HTTP/1.1",
                "HTTP_HOST=" + req.Host,
                "GATEWAY_INTERFACE=CGI/1.1",
@@ -128,17 +143,32 @@ func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
                "PATH_INFO=" + pathInfo,
                "SCRIPT_NAME=" + root,
                "SCRIPT_FILENAME=" + h.Path,
-               "REMOTE_ADDR=" + req.RemoteAddr,
-               "REMOTE_HOST=" + req.RemoteAddr,
                "SERVER_PORT=" + port,
        }
 
+       if remoteIP, remotePort, err := net.SplitHostPort(req.RemoteAddr); err == nil {
+               env = append(env, "REMOTE_ADDR="+remoteIP, "REMOTE_HOST="+remoteIP, "REMOTE_PORT="+remotePort)
+       } else {
+               // could not parse ip:port, let's use whole RemoteAddr and leave REMOTE_PORT undefined
+               env = append(env, "REMOTE_ADDR="+req.RemoteAddr, "REMOTE_HOST="+req.RemoteAddr)
+       }
+
+       if hostDomain, _, err := net.SplitHostPort(req.Host); err == nil {
+               env = append(env, "SERVER_NAME="+hostDomain)
+       } else {
+               env = append(env, "SERVER_NAME="+req.Host)
+       }
+
        if req.TLS != nil {
                env = append(env, "HTTPS=on")
        }
 
        for k, v := range req.Header {
                k = strings.Map(upperCaseAndUnderscore, k)
+               if k == "PROXY" {
+                       // See Issue 16405
+                       continue
+               }
                joinStr := ", "
                if k == "COOKIE" {
                        joinStr = "; "
@@ -153,10 +183,6 @@ func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
                env = append(env, "CONTENT_TYPE="+ctype)
        }
 
-       if h.Env != nil {
-               env = append(env, h.Env...)
-       }
-
        envPath := os.Getenv("PATH")
        if envPath == "" {
                envPath = "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
@@ -169,12 +195,16 @@ func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
                }
        }
 
-       for _, e := range osDefaultInheritEnv[runtime.GOOS] {
+       for _, e := range osDefaultInheritEnv {
                if v := os.Getenv(e); v != "" {
                        env = append(env, e+"="+v)
                }
        }
 
+       if h.Env != nil {
+               env = append(env, h.Env...)
+       }
+
        env = removeLeadingDuplicates(env)
 
        var cwd, path string
@@ -198,7 +228,7 @@ func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
                Args:   append([]string{h.Path}, h.Args...),
                Dir:    cwd,
                Env:    env,
-               Stderr: os.Stderr, // for now
+               Stderr: h.stderr(),
        }
        if req.ContentLength != 0 {
                cmd.Stdin = req.Body
@@ -245,14 +275,16 @@ func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
                        break
                }
                headerLines++
-               parts := strings.SplitN(string(line), ":", 2)
-               if len(parts) < 2 {
+               header, val, ok := strings.Cut(string(line), ":")
+               if !ok {
                        h.printf("cgi: bogus header line: %s", string(line))
                        continue
                }
-               header, val := parts[0], parts[1]
-               header = strings.TrimSpace(header)
-               val = strings.TrimSpace(val)
+               if !httpguts.ValidHeaderFieldName(header) {
+                       h.printf("cgi: invalid header name: %q", header)
+                       continue
+               }
+               val = textproto.TrimString(val)
                switch {
                case header == "Status":
                        if len(val) < 3 {
@@ -320,7 +352,7 @@ func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
        }
 }
 
-func (h *Handler) printf(format string, v ...interface{}) {
+func (h *Handler) printf(format string, v ...any) {
        if h.Logger != nil {
                h.Logger.Printf(format, v...)
        } else {