]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/cgi/host.go
085658ee7a6d373095f94dcb0d998a1d1aa01980
[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         "golang.org/x/net/http/httpguts"
34 )
35
36 var trailingPort = regexp.MustCompile(`:([0-9]+)$`)
37
38 var osDefaultInheritEnv = func() []string {
39         switch runtime.GOOS {
40         case "darwin", "ios":
41                 return []string{"DYLD_LIBRARY_PATH"}
42         case "android", "linux", "freebsd", "netbsd", "openbsd":
43                 return []string{"LD_LIBRARY_PATH"}
44         case "hpux":
45                 return []string{"LD_LIBRARY_PATH", "SHLIB_PATH"}
46         case "irix":
47                 return []string{"LD_LIBRARY_PATH", "LD_LIBRARYN32_PATH", "LD_LIBRARY64_PATH"}
48         case "illumos", "solaris":
49                 return []string{"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"}
50         case "windows":
51                 return []string{"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"}
52         }
53         return nil
54 }()
55
56 // Handler runs an executable in a subprocess with a CGI environment.
57 type Handler struct {
58         Path string // path to the CGI executable
59         Root string // root URI prefix of handler or empty for "/"
60
61         // Dir specifies the CGI executable's working directory.
62         // If Dir is empty, the base directory of Path is used.
63         // If Path has no base directory, the current working
64         // directory is used.
65         Dir string
66
67         Env        []string    // extra environment variables to set, if any, as "key=value"
68         InheritEnv []string    // environment variables to inherit from host, as "key"
69         Logger     *log.Logger // optional log for errors or nil to use log.Print
70         Args       []string    // optional arguments to pass to child process
71         Stderr     io.Writer   // optional stderr for the child process; nil means os.Stderr
72
73         // PathLocationHandler specifies the root http Handler that
74         // should handle internal redirects when the CGI process
75         // returns a Location header value starting with a "/", as
76         // specified in RFC 3875 ยง 6.3.2. This will likely be
77         // http.DefaultServeMux.
78         //
79         // If nil, a CGI response with a local URI path is instead sent
80         // back to the client and not redirected internally.
81         PathLocationHandler http.Handler
82 }
83
84 func (h *Handler) stderr() io.Writer {
85         if h.Stderr != nil {
86                 return h.Stderr
87         }
88         return os.Stderr
89 }
90
91 // removeLeadingDuplicates remove leading duplicate in environments.
92 // It's possible to override environment like following.
93 //
94 //      cgi.Handler{
95 //        ...
96 //        Env: []string{"SCRIPT_FILENAME=foo.php"},
97 //      }
98 func removeLeadingDuplicates(env []string) (ret []string) {
99         for i, e := range env {
100                 found := false
101                 if eq := strings.IndexByte(e, '='); eq != -1 {
102                         keq := e[:eq+1] // "key="
103                         for _, e2 := range env[i+1:] {
104                                 if strings.HasPrefix(e2, keq) {
105                                         found = true
106                                         break
107                                 }
108                         }
109                 }
110                 if !found {
111                         ret = append(ret, e)
112                 }
113         }
114         return
115 }
116
117 func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
118         root := h.Root
119         if root == "" {
120                 root = "/"
121         }
122
123         if len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked" {
124                 rw.WriteHeader(http.StatusBadRequest)
125                 rw.Write([]byte("Chunked request bodies are not supported by CGI."))
126                 return
127         }
128
129         pathInfo := req.URL.Path
130         if root != "/" && strings.HasPrefix(pathInfo, root) {
131                 pathInfo = pathInfo[len(root):]
132         }
133
134         port := "80"
135         if req.TLS != nil {
136                 port = "443"
137         }
138         if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 {
139                 port = matches[1]
140         }
141
142         env := []string{
143                 "SERVER_SOFTWARE=go",
144                 "SERVER_PROTOCOL=HTTP/1.1",
145                 "HTTP_HOST=" + req.Host,
146                 "GATEWAY_INTERFACE=CGI/1.1",
147                 "REQUEST_METHOD=" + req.Method,
148                 "QUERY_STRING=" + req.URL.RawQuery,
149                 "REQUEST_URI=" + req.URL.RequestURI(),
150                 "PATH_INFO=" + pathInfo,
151                 "SCRIPT_NAME=" + root,
152                 "SCRIPT_FILENAME=" + h.Path,
153                 "SERVER_PORT=" + port,
154         }
155
156         if remoteIP, remotePort, err := net.SplitHostPort(req.RemoteAddr); err == nil {
157                 env = append(env, "REMOTE_ADDR="+remoteIP, "REMOTE_HOST="+remoteIP, "REMOTE_PORT="+remotePort)
158         } else {
159                 // could not parse ip:port, let's use whole RemoteAddr and leave REMOTE_PORT undefined
160                 env = append(env, "REMOTE_ADDR="+req.RemoteAddr, "REMOTE_HOST="+req.RemoteAddr)
161         }
162
163         if hostDomain, _, err := net.SplitHostPort(req.Host); err == nil {
164                 env = append(env, "SERVER_NAME="+hostDomain)
165         } else {
166                 env = append(env, "SERVER_NAME="+req.Host)
167         }
168
169         if req.TLS != nil {
170                 env = append(env, "HTTPS=on")
171         }
172
173         for k, v := range req.Header {
174                 k = strings.Map(upperCaseAndUnderscore, k)
175                 if k == "PROXY" {
176                         // See Issue 16405
177                         continue
178                 }
179                 joinStr := ", "
180                 if k == "COOKIE" {
181                         joinStr = "; "
182                 }
183                 env = append(env, "HTTP_"+k+"="+strings.Join(v, joinStr))
184         }
185
186         if req.ContentLength > 0 {
187                 env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", req.ContentLength))
188         }
189         if ctype := req.Header.Get("Content-Type"); ctype != "" {
190                 env = append(env, "CONTENT_TYPE="+ctype)
191         }
192
193         envPath := os.Getenv("PATH")
194         if envPath == "" {
195                 envPath = "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
196         }
197         env = append(env, "PATH="+envPath)
198
199         for _, e := range h.InheritEnv {
200                 if v := os.Getenv(e); v != "" {
201                         env = append(env, e+"="+v)
202                 }
203         }
204
205         for _, e := range osDefaultInheritEnv {
206                 if v := os.Getenv(e); v != "" {
207                         env = append(env, e+"="+v)
208                 }
209         }
210
211         if h.Env != nil {
212                 env = append(env, h.Env...)
213         }
214
215         env = removeLeadingDuplicates(env)
216
217         var cwd, path string
218         if h.Dir != "" {
219                 path = h.Path
220                 cwd = h.Dir
221         } else {
222                 cwd, path = filepath.Split(h.Path)
223         }
224         if cwd == "" {
225                 cwd = "."
226         }
227
228         internalError := func(err error) {
229                 rw.WriteHeader(http.StatusInternalServerError)
230                 h.printf("CGI error: %v", err)
231         }
232
233         cmd := &exec.Cmd{
234                 Path:   path,
235                 Args:   append([]string{h.Path}, h.Args...),
236                 Dir:    cwd,
237                 Env:    env,
238                 Stderr: h.stderr(),
239         }
240         if req.ContentLength != 0 {
241                 cmd.Stdin = req.Body
242         }
243         stdoutRead, err := cmd.StdoutPipe()
244         if err != nil {
245                 internalError(err)
246                 return
247         }
248
249         err = cmd.Start()
250         if err != nil {
251                 internalError(err)
252                 return
253         }
254         if hook := testHookStartProcess; hook != nil {
255                 hook(cmd.Process)
256         }
257         defer cmd.Wait()
258         defer stdoutRead.Close()
259
260         linebody := bufio.NewReaderSize(stdoutRead, 1024)
261         headers := make(http.Header)
262         statusCode := 0
263         headerLines := 0
264         sawBlankLine := false
265         for {
266                 line, isPrefix, err := linebody.ReadLine()
267                 if isPrefix {
268                         rw.WriteHeader(http.StatusInternalServerError)
269                         h.printf("cgi: long header line from subprocess.")
270                         return
271                 }
272                 if err == io.EOF {
273                         break
274                 }
275                 if err != nil {
276                         rw.WriteHeader(http.StatusInternalServerError)
277                         h.printf("cgi: error reading headers: %v", err)
278                         return
279                 }
280                 if len(line) == 0 {
281                         sawBlankLine = true
282                         break
283                 }
284                 headerLines++
285                 header, val, ok := strings.Cut(string(line), ":")
286                 if !ok {
287                         h.printf("cgi: bogus header line: %s", string(line))
288                         continue
289                 }
290                 if !httpguts.ValidHeaderFieldName(header) {
291                         h.printf("cgi: invalid header name: %q", header)
292                         continue
293                 }
294                 val = textproto.TrimString(val)
295                 switch {
296                 case header == "Status":
297                         if len(val) < 3 {
298                                 h.printf("cgi: bogus status (short): %q", val)
299                                 return
300                         }
301                         code, err := strconv.Atoi(val[0:3])
302                         if err != nil {
303                                 h.printf("cgi: bogus status: %q", val)
304                                 h.printf("cgi: line was %q", line)
305                                 return
306                         }
307                         statusCode = code
308                 default:
309                         headers.Add(header, val)
310                 }
311         }
312         if headerLines == 0 || !sawBlankLine {
313                 rw.WriteHeader(http.StatusInternalServerError)
314                 h.printf("cgi: no headers")
315                 return
316         }
317
318         if loc := headers.Get("Location"); loc != "" {
319                 if strings.HasPrefix(loc, "/") && h.PathLocationHandler != nil {
320                         h.handleInternalRedirect(rw, req, loc)
321                         return
322                 }
323                 if statusCode == 0 {
324                         statusCode = http.StatusFound
325                 }
326         }
327
328         if statusCode == 0 && headers.Get("Content-Type") == "" {
329                 rw.WriteHeader(http.StatusInternalServerError)
330                 h.printf("cgi: missing required Content-Type in headers")
331                 return
332         }
333
334         if statusCode == 0 {
335                 statusCode = http.StatusOK
336         }
337
338         // Copy headers to rw's headers, after we've decided not to
339         // go into handleInternalRedirect, which won't want its rw
340         // headers to have been touched.
341         for k, vv := range headers {
342                 for _, v := range vv {
343                         rw.Header().Add(k, v)
344                 }
345         }
346
347         rw.WriteHeader(statusCode)
348
349         _, err = io.Copy(rw, linebody)
350         if err != nil {
351                 h.printf("cgi: copy error: %v", err)
352                 // And kill the child CGI process so we don't hang on
353                 // the deferred cmd.Wait above if the error was just
354                 // the client (rw) going away. If it was a read error
355                 // (because the child died itself), then the extra
356                 // kill of an already-dead process is harmless (the PID
357                 // won't be reused until the Wait above).
358                 cmd.Process.Kill()
359         }
360 }
361
362 func (h *Handler) printf(format string, v ...any) {
363         if h.Logger != nil {
364                 h.Logger.Printf(format, v...)
365         } else {
366                 log.Printf(format, v...)
367         }
368 }
369
370 func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) {
371         url, err := req.URL.Parse(path)
372         if err != nil {
373                 rw.WriteHeader(http.StatusInternalServerError)
374                 h.printf("cgi: error resolving local URI path %q: %v", path, err)
375                 return
376         }
377         // TODO: RFC 3875 isn't clear if only GET is supported, but it
378         // suggests so: "Note that any message-body attached to the
379         // request (such as for a POST request) may not be available
380         // to the resource that is the target of the redirect."  We
381         // should do some tests against Apache to see how it handles
382         // POST, HEAD, etc. Does the internal redirect get the same
383         // method or just GET? What about incoming headers?
384         // (e.g. Cookies) Which headers, if any, are copied into the
385         // second request?
386         newReq := &http.Request{
387                 Method:     "GET",
388                 URL:        url,
389                 Proto:      "HTTP/1.1",
390                 ProtoMajor: 1,
391                 ProtoMinor: 1,
392                 Header:     make(http.Header),
393                 Host:       url.Host,
394                 RemoteAddr: req.RemoteAddr,
395                 TLS:        req.TLS,
396         }
397         h.PathLocationHandler.ServeHTTP(rw, newReq)
398 }
399
400 func upperCaseAndUnderscore(r rune) rune {
401         switch {
402         case r >= 'a' && r <= 'z':
403                 return r - ('a' - 'A')
404         case r == '-':
405                 return '_'
406         case r == '=':
407                 // Maybe not part of the CGI 'spec' but would mess up
408                 // the environment in any case, as Go represents the
409                 // environment as a slice of "key=value" strings.
410                 return '_'
411         }
412         // TODO: other transformations in spec or practice?
413         return r
414 }
415
416 var testHookStartProcess func(*os.Process) // nil except for some tests