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)
160 env = append(env, "HTTP_"+k+"="+strings.Join(v, joinStr))
163 if req.ContentLength > 0 {
164 env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", req.ContentLength))
166 if ctype := req.Header.Get("Content-Type"); ctype != "" {
167 env = append(env, "CONTENT_TYPE="+ctype)
170 envPath := os.Getenv("PATH")
172 envPath = "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
174 env = append(env, "PATH="+envPath)
176 for _, e := range h.InheritEnv {
177 if v := os.Getenv(e); v != "" {
178 env = append(env, e+"="+v)
182 for _, e := range osDefaultInheritEnv[runtime.GOOS] {
183 if v := os.Getenv(e); v != "" {
184 env = append(env, e+"="+v)
189 env = append(env, h.Env...)
192 env = removeLeadingDuplicates(env)
199 cwd, path = filepath.Split(h.Path)
205 internalError := func(err error) {
206 rw.WriteHeader(http.StatusInternalServerError)
207 h.printf("CGI error: %v", err)
212 Args: append([]string{h.Path}, h.Args...),
217 if req.ContentLength != 0 {
220 stdoutRead, err := cmd.StdoutPipe()
231 if hook := testHookStartProcess; hook != nil {
235 defer stdoutRead.Close()
237 linebody := bufio.NewReaderSize(stdoutRead, 1024)
238 headers := make(http.Header)
241 sawBlankLine := false
243 line, isPrefix, err := linebody.ReadLine()
245 rw.WriteHeader(http.StatusInternalServerError)
246 h.printf("cgi: long header line from subprocess.")
253 rw.WriteHeader(http.StatusInternalServerError)
254 h.printf("cgi: error reading headers: %v", err)
262 parts := strings.SplitN(string(line), ":", 2)
264 h.printf("cgi: bogus header line: %s", string(line))
267 header, val := parts[0], parts[1]
268 header = strings.TrimSpace(header)
269 val = strings.TrimSpace(val)
271 case header == "Status":
273 h.printf("cgi: bogus status (short): %q", val)
276 code, err := strconv.Atoi(val[0:3])
278 h.printf("cgi: bogus status: %q", val)
279 h.printf("cgi: line was %q", line)
284 headers.Add(header, val)
287 if headerLines == 0 || !sawBlankLine {
288 rw.WriteHeader(http.StatusInternalServerError)
289 h.printf("cgi: no headers")
293 if loc := headers.Get("Location"); loc != "" {
294 if strings.HasPrefix(loc, "/") && h.PathLocationHandler != nil {
295 h.handleInternalRedirect(rw, req, loc)
299 statusCode = http.StatusFound
303 if statusCode == 0 && headers.Get("Content-Type") == "" {
304 rw.WriteHeader(http.StatusInternalServerError)
305 h.printf("cgi: missing required Content-Type in headers")
310 statusCode = http.StatusOK
313 // Copy headers to rw's headers, after we've decided not to
314 // go into handleInternalRedirect, which won't want its rw
315 // headers to have been touched.
316 for k, vv := range headers {
317 for _, v := range vv {
318 rw.Header().Add(k, v)
322 rw.WriteHeader(statusCode)
324 _, err = io.Copy(rw, linebody)
326 h.printf("cgi: copy error: %v", err)
327 // And kill the child CGI process so we don't hang on
328 // the deferred cmd.Wait above if the error was just
329 // the client (rw) going away. If it was a read error
330 // (because the child died itself), then the extra
331 // kill of an already-dead process is harmless (the PID
332 // won't be reused until the Wait above).
337 func (h *Handler) printf(format string, v ...interface{}) {
339 h.Logger.Printf(format, v...)
341 log.Printf(format, v...)
345 func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) {
346 url, err := req.URL.Parse(path)
348 rw.WriteHeader(http.StatusInternalServerError)
349 h.printf("cgi: error resolving local URI path %q: %v", path, err)
352 // TODO: RFC 3875 isn't clear if only GET is supported, but it
353 // suggests so: "Note that any message-body attached to the
354 // request (such as for a POST request) may not be available
355 // to the resource that is the target of the redirect." We
356 // should do some tests against Apache to see how it handles
357 // POST, HEAD, etc. Does the internal redirect get the same
358 // method or just GET? What about incoming headers?
359 // (e.g. Cookies) Which headers, if any, are copied into the
361 newReq := &http.Request{
367 Header: make(http.Header),
369 RemoteAddr: req.RemoteAddr,
372 h.PathLocationHandler.ServeHTTP(rw, newReq)
375 func upperCaseAndUnderscore(r rune) rune {
377 case r >= 'a' && r <= 'z':
378 return r - ('a' - 'A')
382 // Maybe not part of the CGI 'spec' but would mess up
383 // the environment in any case, as Go represents the
384 // environment as a slice of "key=value" strings.
387 // TODO: other transformations in spec or practice?
391 var testHookStartProcess func(*os.Process) // nil except for some tests