PageRenderTime 57ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/libgo/go/net/http/cgi/host.go

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