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.
34 var trailingPort = regexp.MustCompile(`:([0-9]+)$`)
36 var osDefaultInheritEnv = func() []string {
39 return []string{"DYLD_LIBRARY_PATH"}
40 case "linux", "freebsd", "openbsd":
41 return []string{"LD_LIBRARY_PATH"}
43 return []string{"LD_LIBRARY_PATH", "SHLIB_PATH"}
45 return []string{"LD_LIBRARY_PATH", "LD_LIBRARYN32_PATH", "LD_LIBRARY64_PATH"}
47 return []string{"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"}
49 return []string{"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"}
54 // Handler runs an executable in a subprocess with a CGI environment.
56 Path string // path to the CGI executable
57 Root string // root URI prefix of handler or empty for "/"
59 // Dir specifies the CGI executable's working directory.
60 // If Dir is empty, the base directory of Path is used.
61 // If Path has no base directory, the current working
65 Env []string // extra environment variables to set, if any, as "key=value"
66 InheritEnv []string // environment variables to inherit from host, as "key"
67 Logger *log.Logger // optional log for errors or nil to use log.Print
68 Args []string // optional arguments to pass to child process
69 Stderr io.Writer // optional stderr for the child process; nil means os.Stderr
71 // PathLocationHandler specifies the root http Handler that
72 // should handle internal redirects when the CGI process
73 // returns a Location header value starting with a "/", as
74 // specified in RFC 3875 ยง 6.3.2. This will likely be
75 // http.DefaultServeMux.
77 // If nil, a CGI response with a local URI path is instead sent
78 // back to the client and not redirected internally.
79 PathLocationHandler http.Handler
82 func (h *Handler) stderr() io.Writer {
89 // removeLeadingDuplicates remove leading duplicate in environments.
90 // It's possible to override environment like following.
93 // Env: []string{"SCRIPT_FILENAME=foo.php"},
95 func removeLeadingDuplicates(env []string) (ret []string) {
96 for i, e := range env {
98 if eq := strings.IndexByte(e, '='); eq != -1 {
99 keq := e[:eq+1] // "key="
100 for _, e2 := range env[i+1:] {
101 if strings.HasPrefix(e2, keq) {
114 func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
120 if len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked" {
121 rw.WriteHeader(http.StatusBadRequest)
122 rw.Write([]byte("Chunked request bodies are not supported by CGI."))
126 pathInfo := req.URL.Path
127 if root != "/" && strings.HasPrefix(pathInfo, root) {
128 pathInfo = pathInfo[len(root):]
132 if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 {
137 "SERVER_SOFTWARE=go",
138 "SERVER_NAME=" + req.Host,
139 "SERVER_PROTOCOL=HTTP/1.1",
140 "HTTP_HOST=" + req.Host,
141 "GATEWAY_INTERFACE=CGI/1.1",
142 "REQUEST_METHOD=" + req.Method,
143 "QUERY_STRING=" + req.URL.RawQuery,
144 "REQUEST_URI=" + req.URL.RequestURI(),
145 "PATH_INFO=" + pathInfo,
146 "SCRIPT_NAME=" + root,
147 "SCRIPT_FILENAME=" + h.Path,
148 "SERVER_PORT=" + port,
151 if remoteIP, remotePort, err := net.SplitHostPort(req.RemoteAddr); err == nil {
152 env = append(env, "REMOTE_ADDR="+remoteIP, "REMOTE_HOST="+remoteIP, "REMOTE_PORT="+remotePort)
154 // could not parse ip:port, let's use whole RemoteAddr and leave REMOTE_PORT undefined
155 env = append(env, "REMOTE_ADDR="+req.RemoteAddr, "REMOTE_HOST="+req.RemoteAddr)
159 env = append(env, "HTTPS=on")
162 for k, v := range req.Header {
163 k = strings.Map(upperCaseAndUnderscore, k)
172 env = append(env, "HTTP_"+k+"="+strings.Join(v, joinStr))
175 if req.ContentLength > 0 {
176 env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", req.ContentLength))
178 if ctype := req.Header.Get("Content-Type"); ctype != "" {
179 env = append(env, "CONTENT_TYPE="+ctype)
182 envPath := os.Getenv("PATH")
184 envPath = "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
186 env = append(env, "PATH="+envPath)
188 for _, e := range h.InheritEnv {
189 if v := os.Getenv(e); v != "" {
190 env = append(env, e+"="+v)
194 for _, e := range osDefaultInheritEnv {
195 if v := os.Getenv(e); v != "" {
196 env = append(env, e+"="+v)
201 env = append(env, h.Env...)
204 env = removeLeadingDuplicates(env)
211 cwd, path = filepath.Split(h.Path)
217 internalError := func(err error) {
218 rw.WriteHeader(http.StatusInternalServerError)
219 h.printf("CGI error: %v", err)
224 Args: append([]string{h.Path}, h.Args...),
229 if req.ContentLength != 0 {
232 stdoutRead, err := cmd.StdoutPipe()
243 if hook := testHookStartProcess; hook != nil {
247 defer stdoutRead.Close()
249 linebody := bufio.NewReaderSize(stdoutRead, 1024)
250 headers := make(http.Header)
253 sawBlankLine := false
255 line, isPrefix, err := linebody.ReadLine()
257 rw.WriteHeader(http.StatusInternalServerError)
258 h.printf("cgi: long header line from subprocess.")
265 rw.WriteHeader(http.StatusInternalServerError)
266 h.printf("cgi: error reading headers: %v", err)
274 parts := strings.SplitN(string(line), ":", 2)
276 h.printf("cgi: bogus header line: %s", string(line))
279 header, val := parts[0], parts[1]
280 header = textproto.TrimString(header)
281 val = textproto.TrimString(val)
283 case header == "Status":
285 h.printf("cgi: bogus status (short): %q", val)
288 code, err := strconv.Atoi(val[0:3])
290 h.printf("cgi: bogus status: %q", val)
291 h.printf("cgi: line was %q", line)
296 headers.Add(header, val)
299 if headerLines == 0 || !sawBlankLine {
300 rw.WriteHeader(http.StatusInternalServerError)
301 h.printf("cgi: no headers")
305 if loc := headers.Get("Location"); loc != "" {
306 if strings.HasPrefix(loc, "/") && h.PathLocationHandler != nil {
307 h.handleInternalRedirect(rw, req, loc)
311 statusCode = http.StatusFound
315 if statusCode == 0 && headers.Get("Content-Type") == "" {
316 rw.WriteHeader(http.StatusInternalServerError)
317 h.printf("cgi: missing required Content-Type in headers")
322 statusCode = http.StatusOK
325 // Copy headers to rw's headers, after we've decided not to
326 // go into handleInternalRedirect, which won't want its rw
327 // headers to have been touched.
328 for k, vv := range headers {
329 for _, v := range vv {
330 rw.Header().Add(k, v)
334 rw.WriteHeader(statusCode)
336 _, err = io.Copy(rw, linebody)
338 h.printf("cgi: copy error: %v", err)
339 // And kill the child CGI process so we don't hang on
340 // the deferred cmd.Wait above if the error was just
341 // the client (rw) going away. If it was a read error
342 // (because the child died itself), then the extra
343 // kill of an already-dead process is harmless (the PID
344 // won't be reused until the Wait above).
349 func (h *Handler) printf(format string, v ...interface{}) {
351 h.Logger.Printf(format, v...)
353 log.Printf(format, v...)
357 func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) {
358 url, err := req.URL.Parse(path)
360 rw.WriteHeader(http.StatusInternalServerError)
361 h.printf("cgi: error resolving local URI path %q: %v", path, err)
364 // TODO: RFC 3875 isn't clear if only GET is supported, but it
365 // suggests so: "Note that any message-body attached to the
366 // request (such as for a POST request) may not be available
367 // to the resource that is the target of the redirect." We
368 // should do some tests against Apache to see how it handles
369 // POST, HEAD, etc. Does the internal redirect get the same
370 // method or just GET? What about incoming headers?
371 // (e.g. Cookies) Which headers, if any, are copied into the
373 newReq := &http.Request{
379 Header: make(http.Header),
381 RemoteAddr: req.RemoteAddr,
384 h.PathLocationHandler.ServeHTTP(rw, newReq)
387 func upperCaseAndUnderscore(r rune) rune {
389 case r >= 'a' && r <= 'z':
390 return r - ('a' - 'A')
394 // Maybe not part of the CGI 'spec' but would mess up
395 // the environment in any case, as Go represents the
396 // environment as a slice of "key=value" strings.
399 // TODO: other transformations in spec or practice?
403 var testHookStartProcess func(*os.Process) // nil except for some tests