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
61 Stderr io.Writer // optional stderr for the child process; nil means os.Stderr
63 // PathLocationHandler specifies the root http Handler that
64 // should handle internal redirects when the CGI process
65 // returns a Location header value starting with a "/", as
66 // specified in RFC 3875 ยง 6.3.2. This will likely be
67 // http.DefaultServeMux.
69 // If nil, a CGI response with a local URI path is instead sent
70 // back to the client and not redirected internally.
71 PathLocationHandler http.Handler
74 func (h *Handler) stderr() io.Writer {
81 // removeLeadingDuplicates remove leading duplicate in environments.
82 // It's possible to override environment like following.
85 // Env: []string{"SCRIPT_FILENAME=foo.php"},
87 func removeLeadingDuplicates(env []string) (ret []string) {
88 for i, e := range env {
90 if eq := strings.IndexByte(e, '='); eq != -1 {
91 keq := e[:eq+1] // "key="
92 for _, e2 := range env[i+1:] {
93 if strings.HasPrefix(e2, keq) {
106 func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
112 if len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked" {
113 rw.WriteHeader(http.StatusBadRequest)
114 rw.Write([]byte("Chunked request bodies are not supported by CGI."))
118 pathInfo := req.URL.Path
119 if root != "/" && strings.HasPrefix(pathInfo, root) {
120 pathInfo = pathInfo[len(root):]
124 if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 {
129 "SERVER_SOFTWARE=go",
130 "SERVER_NAME=" + req.Host,
131 "SERVER_PROTOCOL=HTTP/1.1",
132 "HTTP_HOST=" + req.Host,
133 "GATEWAY_INTERFACE=CGI/1.1",
134 "REQUEST_METHOD=" + req.Method,
135 "QUERY_STRING=" + req.URL.RawQuery,
136 "REQUEST_URI=" + req.URL.RequestURI(),
137 "PATH_INFO=" + pathInfo,
138 "SCRIPT_NAME=" + root,
139 "SCRIPT_FILENAME=" + h.Path,
140 "SERVER_PORT=" + port,
143 if remoteIP, remotePort, err := net.SplitHostPort(req.RemoteAddr); err == nil {
144 env = append(env, "REMOTE_ADDR="+remoteIP, "REMOTE_HOST="+remoteIP, "REMOTE_PORT="+remotePort)
146 // could not parse ip:port, let's use whole RemoteAddr and leave REMOTE_PORT undefined
147 env = append(env, "REMOTE_ADDR="+req.RemoteAddr, "REMOTE_HOST="+req.RemoteAddr)
151 env = append(env, "HTTPS=on")
154 for k, v := range req.Header {
155 k = strings.Map(upperCaseAndUnderscore, k)
164 env = append(env, "HTTP_"+k+"="+strings.Join(v, joinStr))
167 if req.ContentLength > 0 {
168 env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", req.ContentLength))
170 if ctype := req.Header.Get("Content-Type"); ctype != "" {
171 env = append(env, "CONTENT_TYPE="+ctype)
174 envPath := os.Getenv("PATH")
176 envPath = "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
178 env = append(env, "PATH="+envPath)
180 for _, e := range h.InheritEnv {
181 if v := os.Getenv(e); v != "" {
182 env = append(env, e+"="+v)
186 for _, e := range osDefaultInheritEnv[runtime.GOOS] {
187 if v := os.Getenv(e); v != "" {
188 env = append(env, e+"="+v)
193 env = append(env, h.Env...)
196 env = removeLeadingDuplicates(env)
203 cwd, path = filepath.Split(h.Path)
209 internalError := func(err error) {
210 rw.WriteHeader(http.StatusInternalServerError)
211 h.printf("CGI error: %v", err)
216 Args: append([]string{h.Path}, h.Args...),
221 if req.ContentLength != 0 {
224 stdoutRead, err := cmd.StdoutPipe()
235 if hook := testHookStartProcess; hook != nil {
239 defer stdoutRead.Close()
241 linebody := bufio.NewReaderSize(stdoutRead, 1024)
242 headers := make(http.Header)
245 sawBlankLine := false
247 line, isPrefix, err := linebody.ReadLine()
249 rw.WriteHeader(http.StatusInternalServerError)
250 h.printf("cgi: long header line from subprocess.")
257 rw.WriteHeader(http.StatusInternalServerError)
258 h.printf("cgi: error reading headers: %v", err)
266 parts := strings.SplitN(string(line), ":", 2)
268 h.printf("cgi: bogus header line: %s", string(line))
271 header, val := parts[0], parts[1]
272 header = strings.TrimSpace(header)
273 val = strings.TrimSpace(val)
275 case header == "Status":
277 h.printf("cgi: bogus status (short): %q", val)
280 code, err := strconv.Atoi(val[0:3])
282 h.printf("cgi: bogus status: %q", val)
283 h.printf("cgi: line was %q", line)
288 headers.Add(header, val)
291 if headerLines == 0 || !sawBlankLine {
292 rw.WriteHeader(http.StatusInternalServerError)
293 h.printf("cgi: no headers")
297 if loc := headers.Get("Location"); loc != "" {
298 if strings.HasPrefix(loc, "/") && h.PathLocationHandler != nil {
299 h.handleInternalRedirect(rw, req, loc)
303 statusCode = http.StatusFound
307 if statusCode == 0 && headers.Get("Content-Type") == "" {
308 rw.WriteHeader(http.StatusInternalServerError)
309 h.printf("cgi: missing required Content-Type in headers")
314 statusCode = http.StatusOK
317 // Copy headers to rw's headers, after we've decided not to
318 // go into handleInternalRedirect, which won't want its rw
319 // headers to have been touched.
320 for k, vv := range headers {
321 for _, v := range vv {
322 rw.Header().Add(k, v)
326 rw.WriteHeader(statusCode)
328 _, err = io.Copy(rw, linebody)
330 h.printf("cgi: copy error: %v", err)
331 // And kill the child CGI process so we don't hang on
332 // the deferred cmd.Wait above if the error was just
333 // the client (rw) going away. If it was a read error
334 // (because the child died itself), then the extra
335 // kill of an already-dead process is harmless (the PID
336 // won't be reused until the Wait above).
341 func (h *Handler) printf(format string, v ...interface{}) {
343 h.Logger.Printf(format, v...)
345 log.Printf(format, v...)
349 func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) {
350 url, err := req.URL.Parse(path)
352 rw.WriteHeader(http.StatusInternalServerError)
353 h.printf("cgi: error resolving local URI path %q: %v", path, err)
356 // TODO: RFC 3875 isn't clear if only GET is supported, but it
357 // suggests so: "Note that any message-body attached to the
358 // request (such as for a POST request) may not be available
359 // to the resource that is the target of the redirect." We
360 // should do some tests against Apache to see how it handles
361 // POST, HEAD, etc. Does the internal redirect get the same
362 // method or just GET? What about incoming headers?
363 // (e.g. Cookies) Which headers, if any, are copied into the
365 newReq := &http.Request{
371 Header: make(http.Header),
373 RemoteAddr: req.RemoteAddr,
376 h.PathLocationHandler.ServeHTTP(rw, newReq)
379 func upperCaseAndUnderscore(r rune) rune {
381 case r >= 'a' && r <= 'z':
382 return r - ('a' - 'A')
386 // Maybe not part of the CGI 'spec' but would mess up
387 // the environment in any case, as Go represents the
388 // environment as a slice of "key=value" strings.
391 // TODO: other transformations in spec or practice?
395 var testHookStartProcess func(*os.Process) // nil except for some tests