1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // This file implements the host side of CGI (being the webserver
8 // Package cgi implements CGI (Common Gateway Interface) as specified
11 // Note that using CGI means starting a new process to handle each
12 // request, which is typically less efficient than using a
13 // long-running server. This package is intended primarily for
14 // compatibility with existing systems.
33 var trailingPort = regexp.MustCompile(`:([0-9]+)$`)
35 var osDefaultInheritEnv = map[string][]string{
36 "darwin": {"DYLD_LIBRARY_PATH"},
37 "freebsd": {"LD_LIBRARY_PATH"},
38 "hpux": {"LD_LIBRARY_PATH", "SHLIB_PATH"},
39 "irix": {"LD_LIBRARY_PATH", "LD_LIBRARYN32_PATH", "LD_LIBRARY64_PATH"},
40 "linux": {"LD_LIBRARY_PATH"},
41 "openbsd": {"LD_LIBRARY_PATH"},
42 "solaris": {"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"},
43 "windows": {"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"},
46 // Handler runs an executable in a subprocess with a CGI environment.
48 Path string // path to the CGI executable
49 Root string // root URI prefix of handler or empty for "/"
51 // Dir specifies the CGI executable's working directory.
52 // If Dir is empty, the base directory of Path is used.
53 // If Path has no base directory, the current working
57 Env []string // extra environment variables to set, if any, as "key=value"
58 InheritEnv []string // environment variables to inherit from host, as "key"
59 Logger *log.Logger // optional log for errors or nil to use log.Print
60 Args []string // optional arguments to pass to child process
62 // PathLocationHandler specifies the root http Handler that
63 // should handle internal redirects when the CGI process
64 // returns a Location header value starting with a "/", as
65 // specified in RFC 3875 ยง 6.3.2. This will likely be
66 // http.DefaultServeMux.
68 // If nil, a CGI response with a local URI path is instead sent
69 // back to the client and not redirected internally.
70 PathLocationHandler http.Handler
73 // removeLeadingDuplicates remove leading duplicate in environments.
74 // It's possible to override environment like following.
77 // Env: []string{"SCRIPT_FILENAME=foo.php"},
79 func removeLeadingDuplicates(env []string) (ret []string) {
80 for i, e := range env {
82 if eq := strings.IndexByte(e, '='); eq != -1 {
83 keq := e[:eq+1] // "key="
84 for _, e2 := range env[i+1:] {
85 if strings.HasPrefix(e2, keq) {
98 func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
104 if len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked" {
105 rw.WriteHeader(http.StatusBadRequest)
106 rw.Write([]byte("Chunked request bodies are not supported by CGI."))
110 pathInfo := req.URL.Path
111 if root != "/" && strings.HasPrefix(pathInfo, root) {
112 pathInfo = pathInfo[len(root):]
116 if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 {
121 "SERVER_SOFTWARE=go",
122 "SERVER_NAME=" + req.Host,
123 "SERVER_PROTOCOL=HTTP/1.1",
124 "HTTP_HOST=" + req.Host,
125 "GATEWAY_INTERFACE=CGI/1.1",
126 "REQUEST_METHOD=" + req.Method,
127 "QUERY_STRING=" + req.URL.RawQuery,
128 "REQUEST_URI=" + req.URL.RequestURI(),
129 "PATH_INFO=" + pathInfo,
130 "SCRIPT_NAME=" + root,
131 "SCRIPT_FILENAME=" + h.Path,
132 "SERVER_PORT=" + port,
135 if remoteIP, remotePort, err := net.SplitHostPort(req.RemoteAddr); err == nil {
136 env = append(env, "REMOTE_ADDR="+remoteIP, "REMOTE_HOST="+remoteIP, "REMOTE_PORT="+remotePort)
138 // could not parse ip:port, let's use whole RemoteAddr and leave REMOTE_PORT undefined
139 env = append(env, "REMOTE_ADDR="+req.RemoteAddr, "REMOTE_HOST="+req.RemoteAddr)
143 env = append(env, "HTTPS=on")
146 for k, v := range req.Header {
147 k = strings.Map(upperCaseAndUnderscore, k)
152 env = append(env, "HTTP_"+k+"="+strings.Join(v, joinStr))
155 if req.ContentLength > 0 {
156 env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", req.ContentLength))
158 if ctype := req.Header.Get("Content-Type"); ctype != "" {
159 env = append(env, "CONTENT_TYPE="+ctype)
162 envPath := os.Getenv("PATH")
164 envPath = "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
166 env = append(env, "PATH="+envPath)
168 for _, e := range h.InheritEnv {
169 if v := os.Getenv(e); v != "" {
170 env = append(env, e+"="+v)
174 for _, e := range osDefaultInheritEnv[runtime.GOOS] {
175 if v := os.Getenv(e); v != "" {
176 env = append(env, e+"="+v)
181 env = append(env, h.Env...)
184 env = removeLeadingDuplicates(env)
191 cwd, path = filepath.Split(h.Path)
197 internalError := func(err error) {
198 rw.WriteHeader(http.StatusInternalServerError)
199 h.printf("CGI error: %v", err)
204 Args: append([]string{h.Path}, h.Args...),
207 Stderr: os.Stderr, // for now
209 if req.ContentLength != 0 {
212 stdoutRead, err := cmd.StdoutPipe()
223 if hook := testHookStartProcess; hook != nil {
227 defer stdoutRead.Close()
229 linebody := bufio.NewReaderSize(stdoutRead, 1024)
230 headers := make(http.Header)
233 sawBlankLine := false
235 line, isPrefix, err := linebody.ReadLine()
237 rw.WriteHeader(http.StatusInternalServerError)
238 h.printf("cgi: long header line from subprocess.")
245 rw.WriteHeader(http.StatusInternalServerError)
246 h.printf("cgi: error reading headers: %v", err)
254 parts := strings.SplitN(string(line), ":", 2)
256 h.printf("cgi: bogus header line: %s", string(line))
259 header, val := parts[0], parts[1]
260 header = strings.TrimSpace(header)
261 val = strings.TrimSpace(val)
263 case header == "Status":
265 h.printf("cgi: bogus status (short): %q", val)
268 code, err := strconv.Atoi(val[0:3])
270 h.printf("cgi: bogus status: %q", val)
271 h.printf("cgi: line was %q", line)
276 headers.Add(header, val)
279 if headerLines == 0 || !sawBlankLine {
280 rw.WriteHeader(http.StatusInternalServerError)
281 h.printf("cgi: no headers")
285 if loc := headers.Get("Location"); loc != "" {
286 if strings.HasPrefix(loc, "/") && h.PathLocationHandler != nil {
287 h.handleInternalRedirect(rw, req, loc)
291 statusCode = http.StatusFound
295 if statusCode == 0 && headers.Get("Content-Type") == "" {
296 rw.WriteHeader(http.StatusInternalServerError)
297 h.printf("cgi: missing required Content-Type in headers")
302 statusCode = http.StatusOK
305 // Copy headers to rw's headers, after we've decided not to
306 // go into handleInternalRedirect, which won't want its rw
307 // headers to have been touched.
308 for k, vv := range headers {
309 for _, v := range vv {
310 rw.Header().Add(k, v)
314 rw.WriteHeader(statusCode)
316 _, err = io.Copy(rw, linebody)
318 h.printf("cgi: copy error: %v", err)
319 // And kill the child CGI process so we don't hang on
320 // the deferred cmd.Wait above if the error was just
321 // the client (rw) going away. If it was a read error
322 // (because the child died itself), then the extra
323 // kill of an already-dead process is harmless (the PID
324 // won't be reused until the Wait above).
329 func (h *Handler) printf(format string, v ...interface{}) {
331 h.Logger.Printf(format, v...)
333 log.Printf(format, v...)
337 func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) {
338 url, err := req.URL.Parse(path)
340 rw.WriteHeader(http.StatusInternalServerError)
341 h.printf("cgi: error resolving local URI path %q: %v", path, err)
344 // TODO: RFC 3875 isn't clear if only GET is supported, but it
345 // suggests so: "Note that any message-body attached to the
346 // request (such as for a POST request) may not be available
347 // to the resource that is the target of the redirect." We
348 // should do some tests against Apache to see how it handles
349 // POST, HEAD, etc. Does the internal redirect get the same
350 // method or just GET? What about incoming headers?
351 // (e.g. Cookies) Which headers, if any, are copied into the
353 newReq := &http.Request{
359 Header: make(http.Header),
361 RemoteAddr: req.RemoteAddr,
364 h.PathLocationHandler.ServeHTTP(rw, newReq)
367 func upperCaseAndUnderscore(r rune) rune {
369 case r >= 'a' && r <= 'z':
370 return r - ('a' - 'A')
374 // Maybe not part of the CGI 'spec' but would mess up
375 // the environment in any case, as Go represents the
376 // environment as a slice of "key=value" strings.
379 // TODO: other transformations in spec or practice?
383 var testHookStartProcess func(*os.Process) // nil except for some tests