2011-03-24 23:46:17 +00:00
|
|
|
// Copyright 2011 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
// This file implements the host side of CGI (being the webserver
|
|
|
|
// parent process).
|
|
|
|
|
|
|
|
// Package cgi implements CGI (Common Gateway Interface) as specified
|
|
|
|
// in RFC 3875.
|
|
|
|
//
|
|
|
|
// Note that using CGI means starting a new process to handle each
|
|
|
|
// request, which is typically less efficient than using a
|
2016-07-22 18:15:38 +00:00
|
|
|
// long-running server. This package is intended primarily for
|
2011-03-24 23:46:17 +00:00
|
|
|
// compatibility with existing systems.
|
|
|
|
package cgi
|
|
|
|
|
|
|
|
import (
|
2011-05-20 00:18:15 +00:00
|
|
|
"bufio"
|
2011-03-24 23:46:17 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
2015-10-31 00:59:47 +00:00
|
|
|
"net"
|
2011-12-07 01:11:29 +00:00
|
|
|
"net/http"
|
2020-07-27 22:27:54 -07:00
|
|
|
"net/textproto"
|
2011-03-24 23:46:17 +00:00
|
|
|
"os"
|
2011-12-07 01:11:29 +00:00
|
|
|
"os/exec"
|
2011-03-24 23:46:17 +00:00
|
|
|
"path/filepath"
|
|
|
|
"regexp"
|
2011-04-22 18:23:47 +00:00
|
|
|
"runtime"
|
2011-03-24 23:46:17 +00:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2020-07-27 22:27:54 -07:00
|
|
|
|
|
|
|
"golang.org/x/net/http/httpguts"
|
2011-03-24 23:46:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var trailingPort = regexp.MustCompile(`:([0-9]+)$`)
|
|
|
|
|
2020-07-27 22:27:54 -07:00
|
|
|
var osDefaultInheritEnv = func() []string {
|
|
|
|
switch runtime.GOOS {
|
2020-10-21 03:00:04 -04:00
|
|
|
case "darwin", "ios":
|
2020-07-27 22:27:54 -07:00
|
|
|
return []string{"DYLD_LIBRARY_PATH"}
|
2020-10-21 03:00:04 -04:00
|
|
|
case "linux", "freebsd", "netbsd", "openbsd":
|
2020-07-27 22:27:54 -07:00
|
|
|
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"}
|
2020-10-21 03:00:04 -04:00
|
|
|
case "illumos", "solaris":
|
2020-07-27 22:27:54 -07:00
|
|
|
return []string{"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"}
|
|
|
|
case "windows":
|
|
|
|
return []string{"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}()
|
2011-04-22 18:23:47 +00:00
|
|
|
|
2011-03-24 23:46:17 +00:00
|
|
|
// Handler runs an executable in a subprocess with a CGI environment.
|
|
|
|
type Handler struct {
|
|
|
|
Path string // path to the CGI executable
|
|
|
|
Root string // root URI prefix of handler or empty for "/"
|
|
|
|
|
2011-09-16 15:47:21 +00:00
|
|
|
// Dir specifies the CGI executable's working directory.
|
|
|
|
// If Dir is empty, the base directory of Path is used.
|
|
|
|
// If Path has no base directory, the current working
|
|
|
|
// directory is used.
|
|
|
|
Dir string
|
|
|
|
|
2011-04-22 18:23:47 +00:00
|
|
|
Env []string // extra environment variables to set, if any, as "key=value"
|
|
|
|
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
|
2016-07-22 18:15:38 +00:00
|
|
|
Stderr io.Writer // optional stderr for the child process; nil means os.Stderr
|
2011-05-20 00:18:15 +00:00
|
|
|
|
|
|
|
// PathLocationHandler specifies the root http Handler that
|
|
|
|
// should handle internal redirects when the CGI process
|
|
|
|
// returns a Location header value starting with a "/", as
|
|
|
|
// specified in RFC 3875 § 6.3.2. This will likely be
|
|
|
|
// http.DefaultServeMux.
|
|
|
|
//
|
|
|
|
// If nil, a CGI response with a local URI path is instead sent
|
|
|
|
// back to the client and not redirected internally.
|
|
|
|
PathLocationHandler http.Handler
|
2011-03-24 23:46:17 +00:00
|
|
|
}
|
|
|
|
|
2016-07-22 18:15:38 +00:00
|
|
|
func (h *Handler) stderr() io.Writer {
|
|
|
|
if h.Stderr != nil {
|
|
|
|
return h.Stderr
|
|
|
|
}
|
|
|
|
return os.Stderr
|
|
|
|
}
|
|
|
|
|
2011-10-26 23:57:58 +00:00
|
|
|
// removeLeadingDuplicates remove leading duplicate in environments.
|
|
|
|
// It's possible to override environment like following.
|
|
|
|
// cgi.Handler{
|
|
|
|
// ...
|
|
|
|
// Env: []string{"SCRIPT_FILENAME=foo.php"},
|
|
|
|
// }
|
|
|
|
func removeLeadingDuplicates(env []string) (ret []string) {
|
2016-02-03 21:58:02 +00:00
|
|
|
for i, e := range env {
|
2011-10-26 23:57:58 +00:00
|
|
|
found := false
|
2016-02-03 21:58:02 +00:00
|
|
|
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
|
|
|
|
}
|
2011-10-26 23:57:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if !found {
|
|
|
|
ret = append(ret, e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2011-03-24 23:46:17 +00:00
|
|
|
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):]
|
|
|
|
}
|
|
|
|
|
|
|
|
port := "80"
|
|
|
|
if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 {
|
|
|
|
port = matches[1]
|
|
|
|
}
|
|
|
|
|
|
|
|
env := []string{
|
|
|
|
"SERVER_SOFTWARE=go",
|
|
|
|
"SERVER_NAME=" + req.Host,
|
2011-05-20 00:18:15 +00:00
|
|
|
"SERVER_PROTOCOL=HTTP/1.1",
|
2011-03-24 23:46:17 +00:00
|
|
|
"HTTP_HOST=" + req.Host,
|
|
|
|
"GATEWAY_INTERFACE=CGI/1.1",
|
|
|
|
"REQUEST_METHOD=" + req.Method,
|
|
|
|
"QUERY_STRING=" + req.URL.RawQuery,
|
2012-01-25 21:54:22 +00:00
|
|
|
"REQUEST_URI=" + req.URL.RequestURI(),
|
2011-03-24 23:46:17 +00:00
|
|
|
"PATH_INFO=" + pathInfo,
|
|
|
|
"SCRIPT_NAME=" + root,
|
|
|
|
"SCRIPT_FILENAME=" + h.Path,
|
|
|
|
"SERVER_PORT=" + port,
|
|
|
|
}
|
|
|
|
|
2015-10-31 00:59:47 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2011-03-24 23:46:17 +00:00
|
|
|
if req.TLS != nil {
|
|
|
|
env = append(env, "HTTPS=on")
|
|
|
|
}
|
|
|
|
|
|
|
|
for k, v := range req.Header {
|
|
|
|
k = strings.Map(upperCaseAndUnderscore, k)
|
2016-07-22 18:15:38 +00:00
|
|
|
if k == "PROXY" {
|
|
|
|
// See Issue 16405
|
|
|
|
continue
|
|
|
|
}
|
2011-09-16 15:47:21 +00:00
|
|
|
joinStr := ", "
|
|
|
|
if k == "COOKIE" {
|
|
|
|
joinStr = "; "
|
|
|
|
}
|
|
|
|
env = append(env, "HTTP_"+k+"="+strings.Join(v, joinStr))
|
2011-03-24 23:46:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if req.ContentLength > 0 {
|
|
|
|
env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", req.ContentLength))
|
|
|
|
}
|
|
|
|
if ctype := req.Header.Get("Content-Type"); ctype != "" {
|
|
|
|
env = append(env, "CONTENT_TYPE="+ctype)
|
|
|
|
}
|
|
|
|
|
2011-09-16 15:47:21 +00:00
|
|
|
envPath := os.Getenv("PATH")
|
|
|
|
if envPath == "" {
|
|
|
|
envPath = "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
|
2011-04-22 18:23:47 +00:00
|
|
|
}
|
2011-09-16 15:47:21 +00:00
|
|
|
env = append(env, "PATH="+envPath)
|
2011-04-22 18:23:47 +00:00
|
|
|
|
|
|
|
for _, e := range h.InheritEnv {
|
|
|
|
if v := os.Getenv(e); v != "" {
|
|
|
|
env = append(env, e+"="+v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-27 22:27:54 -07:00
|
|
|
for _, e := range osDefaultInheritEnv {
|
2011-04-22 18:23:47 +00:00
|
|
|
if v := os.Getenv(e); v != "" {
|
|
|
|
env = append(env, e+"="+v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-03 21:58:02 +00:00
|
|
|
if h.Env != nil {
|
|
|
|
env = append(env, h.Env...)
|
|
|
|
}
|
|
|
|
|
2011-10-26 23:57:58 +00:00
|
|
|
env = removeLeadingDuplicates(env)
|
|
|
|
|
2011-09-16 15:47:21 +00:00
|
|
|
var cwd, path string
|
|
|
|
if h.Dir != "" {
|
|
|
|
path = h.Path
|
|
|
|
cwd = h.Dir
|
|
|
|
} else {
|
|
|
|
cwd, path = filepath.Split(h.Path)
|
|
|
|
}
|
2011-03-24 23:46:17 +00:00
|
|
|
if cwd == "" {
|
|
|
|
cwd = "."
|
|
|
|
}
|
|
|
|
|
2011-12-03 02:17:34 +00:00
|
|
|
internalError := func(err error) {
|
2011-03-24 23:46:17 +00:00
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
|
|
|
h.printf("CGI error: %v", err)
|
|
|
|
}
|
|
|
|
|
2011-09-16 15:47:21 +00:00
|
|
|
cmd := &exec.Cmd{
|
|
|
|
Path: path,
|
|
|
|
Args: append([]string{h.Path}, h.Args...),
|
|
|
|
Dir: cwd,
|
|
|
|
Env: env,
|
2016-07-22 18:15:38 +00:00
|
|
|
Stderr: h.stderr(),
|
2011-09-16 15:47:21 +00:00
|
|
|
}
|
2011-03-24 23:46:17 +00:00
|
|
|
if req.ContentLength != 0 {
|
2011-09-16 15:47:21 +00:00
|
|
|
cmd.Stdin = req.Body
|
|
|
|
}
|
|
|
|
stdoutRead, err := cmd.StdoutPipe()
|
|
|
|
if err != nil {
|
|
|
|
internalError(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
err = cmd.Start()
|
|
|
|
if err != nil {
|
|
|
|
internalError(err)
|
|
|
|
return
|
2011-03-24 23:46:17 +00:00
|
|
|
}
|
2014-07-19 08:53:52 +00:00
|
|
|
if hook := testHookStartProcess; hook != nil {
|
|
|
|
hook(cmd.Process)
|
|
|
|
}
|
2011-09-16 15:47:21 +00:00
|
|
|
defer cmd.Wait()
|
|
|
|
defer stdoutRead.Close()
|
2011-03-24 23:46:17 +00:00
|
|
|
|
2012-02-09 08:19:58 +00:00
|
|
|
linebody := bufio.NewReaderSize(stdoutRead, 1024)
|
2011-05-20 00:18:15 +00:00
|
|
|
headers := make(http.Header)
|
|
|
|
statusCode := 0
|
2014-07-19 08:53:52 +00:00
|
|
|
headerLines := 0
|
|
|
|
sawBlankLine := false
|
2011-03-24 23:46:17 +00:00
|
|
|
for {
|
|
|
|
line, isPrefix, err := linebody.ReadLine()
|
|
|
|
if isPrefix {
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
2011-05-20 00:18:15 +00:00
|
|
|
h.printf("cgi: long header line from subprocess.")
|
2011-03-24 23:46:17 +00:00
|
|
|
return
|
|
|
|
}
|
2011-12-03 02:17:34 +00:00
|
|
|
if err == io.EOF {
|
2011-03-24 23:46:17 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
2011-05-20 00:18:15 +00:00
|
|
|
h.printf("cgi: error reading headers: %v", err)
|
2011-03-24 23:46:17 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if len(line) == 0 {
|
2014-07-19 08:53:52 +00:00
|
|
|
sawBlankLine = true
|
2011-03-24 23:46:17 +00:00
|
|
|
break
|
|
|
|
}
|
2014-07-19 08:53:52 +00:00
|
|
|
headerLines++
|
2022-02-11 14:53:56 -08:00
|
|
|
header, val, ok := strings.Cut(string(line), ":")
|
|
|
|
if !ok {
|
2011-05-20 00:18:15 +00:00
|
|
|
h.printf("cgi: bogus header line: %s", string(line))
|
2011-03-24 23:46:17 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-07-27 22:27:54 -07:00
|
|
|
if !httpguts.ValidHeaderFieldName(header) {
|
|
|
|
h.printf("cgi: invalid header name: %q", header)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
val = textproto.TrimString(val)
|
2011-03-24 23:46:17 +00:00
|
|
|
switch {
|
|
|
|
case header == "Status":
|
|
|
|
if len(val) < 3 {
|
2011-05-20 00:18:15 +00:00
|
|
|
h.printf("cgi: bogus status (short): %q", val)
|
2011-03-24 23:46:17 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
code, err := strconv.Atoi(val[0:3])
|
|
|
|
if err != nil {
|
2011-05-20 00:18:15 +00:00
|
|
|
h.printf("cgi: bogus status: %q", val)
|
|
|
|
h.printf("cgi: line was %q", line)
|
2011-03-24 23:46:17 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
statusCode = code
|
|
|
|
default:
|
|
|
|
headers.Add(header, val)
|
|
|
|
}
|
|
|
|
}
|
2014-07-19 08:53:52 +00:00
|
|
|
if headerLines == 0 || !sawBlankLine {
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
|
|
|
h.printf("cgi: no headers")
|
|
|
|
return
|
|
|
|
}
|
2011-05-20 00:18:15 +00:00
|
|
|
|
|
|
|
if loc := headers.Get("Location"); loc != "" {
|
|
|
|
if strings.HasPrefix(loc, "/") && h.PathLocationHandler != nil {
|
|
|
|
h.handleInternalRedirect(rw, req, loc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if statusCode == 0 {
|
|
|
|
statusCode = http.StatusFound
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-19 08:53:52 +00:00
|
|
|
if statusCode == 0 && headers.Get("Content-Type") == "" {
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
|
|
|
h.printf("cgi: missing required Content-Type in headers")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2011-05-20 00:18:15 +00:00
|
|
|
if statusCode == 0 {
|
|
|
|
statusCode = http.StatusOK
|
|
|
|
}
|
|
|
|
|
|
|
|
// Copy headers to rw's headers, after we've decided not to
|
|
|
|
// go into handleInternalRedirect, which won't want its rw
|
|
|
|
// headers to have been touched.
|
|
|
|
for k, vv := range headers {
|
|
|
|
for _, v := range vv {
|
|
|
|
rw.Header().Add(k, v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-03-24 23:46:17 +00:00
|
|
|
rw.WriteHeader(statusCode)
|
|
|
|
|
|
|
|
_, err = io.Copy(rw, linebody)
|
|
|
|
if err != nil {
|
2011-05-20 00:18:15 +00:00
|
|
|
h.printf("cgi: copy error: %v", err)
|
2014-07-19 08:53:52 +00:00
|
|
|
// And kill the child CGI process so we don't hang on
|
|
|
|
// the deferred cmd.Wait above if the error was just
|
|
|
|
// the client (rw) going away. If it was a read error
|
|
|
|
// (because the child died itself), then the extra
|
|
|
|
// kill of an already-dead process is harmless (the PID
|
|
|
|
// won't be reused until the Wait above).
|
|
|
|
cmd.Process.Kill()
|
2011-03-24 23:46:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-11 14:53:56 -08:00
|
|
|
func (h *Handler) printf(format string, v ...any) {
|
2011-03-24 23:46:17 +00:00
|
|
|
if h.Logger != nil {
|
|
|
|
h.Logger.Printf(format, v...)
|
|
|
|
} else {
|
|
|
|
log.Printf(format, v...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-05-20 00:18:15 +00:00
|
|
|
func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) {
|
2011-09-16 15:47:21 +00:00
|
|
|
url, err := req.URL.Parse(path)
|
2011-05-20 00:18:15 +00:00
|
|
|
if err != nil {
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
|
|
|
h.printf("cgi: error resolving local URI path %q: %v", path, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// TODO: RFC 3875 isn't clear if only GET is supported, but it
|
|
|
|
// suggests so: "Note that any message-body attached to the
|
|
|
|
// request (such as for a POST request) may not be available
|
|
|
|
// to the resource that is the target of the redirect." We
|
|
|
|
// should do some tests against Apache to see how it handles
|
|
|
|
// POST, HEAD, etc. Does the internal redirect get the same
|
|
|
|
// method or just GET? What about incoming headers?
|
|
|
|
// (e.g. Cookies) Which headers, if any, are copied into the
|
|
|
|
// second request?
|
|
|
|
newReq := &http.Request{
|
|
|
|
Method: "GET",
|
|
|
|
URL: url,
|
|
|
|
Proto: "HTTP/1.1",
|
|
|
|
ProtoMajor: 1,
|
|
|
|
ProtoMinor: 1,
|
|
|
|
Header: make(http.Header),
|
|
|
|
Host: url.Host,
|
|
|
|
RemoteAddr: req.RemoteAddr,
|
|
|
|
TLS: req.TLS,
|
|
|
|
}
|
|
|
|
h.PathLocationHandler.ServeHTTP(rw, newReq)
|
|
|
|
}
|
|
|
|
|
2011-12-02 19:34:41 +00:00
|
|
|
func upperCaseAndUnderscore(r rune) rune {
|
2011-03-24 23:46:17 +00:00
|
|
|
switch {
|
2011-12-02 19:34:41 +00:00
|
|
|
case r >= 'a' && r <= 'z':
|
|
|
|
return r - ('a' - 'A')
|
|
|
|
case r == '-':
|
2011-03-24 23:46:17 +00:00
|
|
|
return '_'
|
2011-12-02 19:34:41 +00:00
|
|
|
case r == '=':
|
2011-03-24 23:46:17 +00:00
|
|
|
// Maybe not part of the CGI 'spec' but would mess up
|
|
|
|
// the environment in any case, as Go represents the
|
|
|
|
// environment as a slice of "key=value" strings.
|
|
|
|
return '_'
|
|
|
|
}
|
|
|
|
// TODO: other transformations in spec or practice?
|
2011-12-02 19:34:41 +00:00
|
|
|
return r
|
2011-03-24 23:46:17 +00:00
|
|
|
}
|
2014-07-19 08:53:52 +00:00
|
|
|
|
|
|
|
var testHookStartProcess func(*os.Process) // nil except for some tests
|