]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/cgi/host.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / net / http / cgi / host.go
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.
4
5 // This file implements the host side of CGI (being the webserver
6 // parent process).
7
8 // Package cgi implements CGI (Common Gateway Interface) as specified
9 // in RFC 3875.
10 //
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.
15 package cgi
16
17 import (
18         "bufio"
19         "fmt"
20         "io"
21         "log"
22         "net"
23         "net/http"
24         "net/textproto"
25         "os"
26         "os/exec"
27         "path/filepath"
28         "regexp"
29         "runtime"
30         "strconv"
31         "strings"
32 )
33
34 var trailingPort = regexp.MustCompile(`:([0-9]+)$`)
35
36 var osDefaultInheritEnv = func() []string {
37         switch runtime.GOOS {
38         case "darwin":
39                 return []string{"DYLD_LIBRARY_PATH"}
40         case "linux", "freebsd", "openbsd":
41                 return []string{"LD_LIBRARY_PATH"}
42         case "hpux":
43                 return []string{"LD_LIBRARY_PATH", "SHLIB_PATH"}
44         case "irix":
45                 return []string{"LD_LIBRARY_PATH", "LD_LIBRARYN32_PATH", "LD_LIBRARY64_PATH"}
46         case "solaris":
47                 return []string{"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"}
48         case "windows":
49                 return []string{"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"}
50         }
51         return nil
52 }()
53
54 // Handler runs an executable in a subprocess with a CGI environment.
55 type Handler struct {
56         Path string // path to the CGI executable
57         Root string // root URI prefix of handler or empty for "/"
58
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
62         // directory is used.
63         Dir string
64
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
70
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.
76         //
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
80 }
81
82 func (h *Handler) stderr() io.Writer {
83         if h.Stderr != nil {
84                 return h.Stderr
85         }
86         return os.Stderr
87 }
88
89 // removeLeadingDuplicates remove leading duplicate in environments.
90 // It's possible to override environment like following.
91 //    cgi.Handler{
92 //      ...
93 //      Env: []string{"SCRIPT_FILENAME=foo.php"},
94 //    }
95 func removeLeadingDuplicates(env []string) (ret []string) {
96         for i, e := range env {
97                 found := false
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) {
102                                         found = true
103                                         break
104                                 }
105                         }
106                 }
107                 if !found {
108                         ret = append(ret, e)
109                 }
110         }
111         return
112 }
113
114 func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
115         root := h.Root
116         if root == "" {
117                 root = "/"
118         }
119
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."))
123                 return
124         }
125
126         pathInfo := req.URL.Path
127         if root != "/" && strings.HasPrefix(pathInfo, root) {
128                 pathInfo = pathInfo[len(root):]
129         }
130
131         port := "80"
132         if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 {
133                 port = matches[1]
134         }
135
136         env := []string{
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,
149         }
150
151         if remoteIP, remotePort, err := net.SplitHostPort(req.RemoteAddr); err == nil {
152                 env = append(env, "REMOTE_ADDR="+remoteIP, "REMOTE_HOST="+remoteIP, "REMOTE_PORT="+remotePort)
153         } else {
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)
156         }
157
158         if req.TLS != nil {
159                 env = append(env, "HTTPS=on")
160         }
161
162         for k, v := range req.Header {
163                 k = strings.Map(upperCaseAndUnderscore, k)
164                 if k == "PROXY" {
165                         // See Issue 16405
166                         continue
167                 }
168                 joinStr := ", "
169                 if k == "COOKIE" {
170                         joinStr = "; "
171                 }
172                 env = append(env, "HTTP_"+k+"="+strings.Join(v, joinStr))
173         }
174
175         if req.ContentLength > 0 {
176                 env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", req.ContentLength))
177         }
178         if ctype := req.Header.Get("Content-Type"); ctype != "" {
179                 env = append(env, "CONTENT_TYPE="+ctype)
180         }
181
182         envPath := os.Getenv("PATH")
183         if envPath == "" {
184                 envPath = "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
185         }
186         env = append(env, "PATH="+envPath)
187
188         for _, e := range h.InheritEnv {
189                 if v := os.Getenv(e); v != "" {
190                         env = append(env, e+"="+v)
191                 }
192         }
193
194         for _, e := range osDefaultInheritEnv {
195                 if v := os.Getenv(e); v != "" {
196                         env = append(env, e+"="+v)
197                 }
198         }
199
200         if h.Env != nil {
201                 env = append(env, h.Env...)
202         }
203
204         env = removeLeadingDuplicates(env)
205
206         var cwd, path string
207         if h.Dir != "" {
208                 path = h.Path
209                 cwd = h.Dir
210         } else {
211                 cwd, path = filepath.Split(h.Path)
212         }
213         if cwd == "" {
214                 cwd = "."
215         }
216
217         internalError := func(err error) {
218                 rw.WriteHeader(http.StatusInternalServerError)
219                 h.printf("CGI error: %v", err)
220         }
221
222         cmd := &exec.Cmd{
223                 Path:   path,
224                 Args:   append([]string{h.Path}, h.Args...),
225                 Dir:    cwd,
226                 Env:    env,
227                 Stderr: h.stderr(),
228         }
229         if req.ContentLength != 0 {
230                 cmd.Stdin = req.Body
231         }
232         stdoutRead, err := cmd.StdoutPipe()
233         if err != nil {
234                 internalError(err)
235                 return
236         }
237
238         err = cmd.Start()
239         if err != nil {
240                 internalError(err)
241                 return
242         }
243         if hook := testHookStartProcess; hook != nil {
244                 hook(cmd.Process)
245         }
246         defer cmd.Wait()
247         defer stdoutRead.Close()
248
249         linebody := bufio.NewReaderSize(stdoutRead, 1024)
250         headers := make(http.Header)
251         statusCode := 0
252         headerLines := 0
253         sawBlankLine := false
254         for {
255                 line, isPrefix, err := linebody.ReadLine()
256                 if isPrefix {
257                         rw.WriteHeader(http.StatusInternalServerError)
258                         h.printf("cgi: long header line from subprocess.")
259                         return
260                 }
261                 if err == io.EOF {
262                         break
263                 }
264                 if err != nil {
265                         rw.WriteHeader(http.StatusInternalServerError)
266                         h.printf("cgi: error reading headers: %v", err)
267                         return
268                 }
269                 if len(line) == 0 {
270                         sawBlankLine = true
271                         break
272                 }
273                 headerLines++
274                 parts := strings.SplitN(string(line), ":", 2)
275                 if len(parts) < 2 {
276                         h.printf("cgi: bogus header line: %s", string(line))
277                         continue
278                 }
279                 header, val := parts[0], parts[1]
280                 header = textproto.TrimString(header)
281                 val = textproto.TrimString(val)
282                 switch {
283                 case header == "Status":
284                         if len(val) < 3 {
285                                 h.printf("cgi: bogus status (short): %q", val)
286                                 return
287                         }
288                         code, err := strconv.Atoi(val[0:3])
289                         if err != nil {
290                                 h.printf("cgi: bogus status: %q", val)
291                                 h.printf("cgi: line was %q", line)
292                                 return
293                         }
294                         statusCode = code
295                 default:
296                         headers.Add(header, val)
297                 }
298         }
299         if headerLines == 0 || !sawBlankLine {
300                 rw.WriteHeader(http.StatusInternalServerError)
301                 h.printf("cgi: no headers")
302                 return
303         }
304
305         if loc := headers.Get("Location"); loc != "" {
306                 if strings.HasPrefix(loc, "/") && h.PathLocationHandler != nil {
307                         h.handleInternalRedirect(rw, req, loc)
308                         return
309                 }
310                 if statusCode == 0 {
311                         statusCode = http.StatusFound
312                 }
313         }
314
315         if statusCode == 0 && headers.Get("Content-Type") == "" {
316                 rw.WriteHeader(http.StatusInternalServerError)
317                 h.printf("cgi: missing required Content-Type in headers")
318                 return
319         }
320
321         if statusCode == 0 {
322                 statusCode = http.StatusOK
323         }
324
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)
331                 }
332         }
333
334         rw.WriteHeader(statusCode)
335
336         _, err = io.Copy(rw, linebody)
337         if err != nil {
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).
345                 cmd.Process.Kill()
346         }
347 }
348
349 func (h *Handler) printf(format string, v ...interface{}) {
350         if h.Logger != nil {
351                 h.Logger.Printf(format, v...)
352         } else {
353                 log.Printf(format, v...)
354         }
355 }
356
357 func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) {
358         url, err := req.URL.Parse(path)
359         if err != nil {
360                 rw.WriteHeader(http.StatusInternalServerError)
361                 h.printf("cgi: error resolving local URI path %q: %v", path, err)
362                 return
363         }
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
372         // second request?
373         newReq := &http.Request{
374                 Method:     "GET",
375                 URL:        url,
376                 Proto:      "HTTP/1.1",
377                 ProtoMajor: 1,
378                 ProtoMinor: 1,
379                 Header:     make(http.Header),
380                 Host:       url.Host,
381                 RemoteAddr: req.RemoteAddr,
382                 TLS:        req.TLS,
383         }
384         h.PathLocationHandler.ServeHTTP(rw, newReq)
385 }
386
387 func upperCaseAndUnderscore(r rune) rune {
388         switch {
389         case r >= 'a' && r <= 'z':
390                 return r - ('a' - 'A')
391         case r == '-':
392                 return '_'
393         case r == '=':
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.
397                 return '_'
398         }
399         // TODO: other transformations in spec or practice?
400         return r
401 }
402
403 var testHookStartProcess func(*os.Process) // nil except for some tests