cgi.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package frankenphp
  2. import (
  3. "crypto/tls"
  4. "net"
  5. "net/http"
  6. "path/filepath"
  7. "strings"
  8. )
  9. // populateEnv returns a set of CGI environment variables for the request.
  10. //
  11. // TODO: handle this case https://github.com/caddyserver/caddy/issues/3718
  12. // Inspired by https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
  13. func populateEnv(request *http.Request) error {
  14. fc, ok := FromContext(request.Context())
  15. if !ok {
  16. panic("not a FrankenPHP request")
  17. }
  18. if fc.populated {
  19. return nil
  20. }
  21. _, addrOk := fc.Env["REMOTE_ADDR"]
  22. _, portOk := fc.Env["REMOTE_PORT"]
  23. if !addrOk || !portOk {
  24. // Separate remote IP and port; more lenient than net.SplitHostPort
  25. var ip, port string
  26. if idx := strings.LastIndex(request.RemoteAddr, ":"); idx > -1 {
  27. ip = request.RemoteAddr[:idx]
  28. port = request.RemoteAddr[idx+1:]
  29. } else {
  30. ip = request.RemoteAddr
  31. }
  32. // Remove [] from IPv6 addresses
  33. ip = strings.Replace(ip, "[", "", 1)
  34. ip = strings.Replace(ip, "]", "", 1)
  35. if _, ok := fc.Env["REMOTE_ADDR"]; !ok {
  36. fc.Env["REMOTE_ADDR"] = ip
  37. }
  38. if _, ok := fc.Env["REMOTE_HOST"]; !ok {
  39. fc.Env["REMOTE_HOST"] = ip // For speed, remote host lookups disabled
  40. }
  41. if _, ok := fc.Env["REMOTE_PORT"]; !ok {
  42. fc.Env["REMOTE_PORT"] = port
  43. }
  44. }
  45. if _, ok := fc.Env["DOCUMENT_ROOT"]; !ok {
  46. // make sure file root is absolute
  47. root, err := filepath.Abs(fc.DocumentRoot)
  48. if err != nil {
  49. return err
  50. }
  51. if fc.ResolveRootSymlink {
  52. if root, err = filepath.EvalSymlinks(root); err != nil {
  53. return err
  54. }
  55. }
  56. fc.Env["DOCUMENT_ROOT"] = root
  57. }
  58. fpath := request.URL.Path
  59. scriptName := fpath
  60. docURI := fpath
  61. // split "actual path" from "path info" if configured
  62. if splitPos := splitPos(fc, fpath); splitPos > -1 {
  63. docURI = fpath[:splitPos]
  64. fc.Env["PATH_INFO"] = fpath[splitPos:]
  65. // Strip PATH_INFO from SCRIPT_NAME
  66. scriptName = strings.TrimSuffix(scriptName, fc.Env["PATH_INFO"])
  67. }
  68. // SCRIPT_FILENAME is the absolute path of SCRIPT_NAME
  69. scriptFilename := sanitizedPathJoin(fc.Env["DOCUMENT_ROOT"], scriptName)
  70. // Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875
  71. // Info: https://tools.ietf.org/html/rfc3875#section-4.1.13
  72. if scriptName != "" && !strings.HasPrefix(scriptName, "/") {
  73. scriptName = "/" + scriptName
  74. }
  75. if _, ok := fc.Env["PHP_SELF"]; !ok {
  76. fc.Env["PHP_SELF"] = fpath
  77. }
  78. if _, ok := fc.Env["DOCUMENT_URI"]; !ok {
  79. fc.Env["DOCUMENT_URI"] = docURI
  80. }
  81. if _, ok := fc.Env["SCRIPT_FILENAME"]; !ok {
  82. fc.Env["SCRIPT_FILENAME"] = scriptFilename
  83. }
  84. if _, ok := fc.Env["SCRIPT_NAME"]; !ok {
  85. fc.Env["SCRIPT_NAME"] = scriptName
  86. }
  87. if _, ok := fc.Env["REQUEST_SCHEME"]; !ok {
  88. if request.TLS == nil {
  89. fc.Env["REQUEST_SCHEME"] = "http"
  90. } else {
  91. fc.Env["REQUEST_SCHEME"] = "https"
  92. }
  93. }
  94. if request.TLS != nil {
  95. if _, ok := fc.Env["HTTPS"]; !ok {
  96. fc.Env["HTTPS"] = "on"
  97. }
  98. // and pass the protocol details in a manner compatible with apache's mod_ssl
  99. // (which is why these have a SSL_ prefix and not TLS_).
  100. _, sslProtocolOk := fc.Env["SSL_PROTOCOL"]
  101. v, versionOk := tlsProtocolStrings[request.TLS.Version]
  102. if !sslProtocolOk && versionOk {
  103. fc.Env["SSL_PROTOCOL"] = v
  104. }
  105. }
  106. if fc.Env["SERVER_NAME"] == "" || fc.Env["SERVER_PORT"] == "" {
  107. reqHost, reqPort, _ := net.SplitHostPort(request.Host)
  108. if fc.Env["SERVER_NAME"] == "" {
  109. fc.Env["SERVER_NAME"] = reqHost
  110. }
  111. if fc.Env["SERVER_PORT"] == "" {
  112. fc.Env["SERVER_PORT"] = reqPort
  113. }
  114. if fc.Env["SERVER_NAME"] == "" {
  115. // whatever, just assume there was no port
  116. fc.Env["SERVER_NAME"] = request.Host
  117. }
  118. // compliance with the CGI specification requires that
  119. // the SERVER_PORT variable MUST be set to the TCP/IP port number on which this request is received from the client
  120. // even if the port is the default port for the scheme and could otherwise be omitted from a URI.
  121. // https://tools.ietf.org/html/rfc3875#section-4.1.15
  122. if fc.Env["SERVER_PORT"] == "" {
  123. if fc.Env["REQUEST_SCHEME"] == "https" {
  124. fc.Env["SERVER_PORT"] = "443"
  125. } else {
  126. fc.Env["SERVER_PORT"] = "80"
  127. }
  128. }
  129. }
  130. // Variables defined in CGI 1.1 spec
  131. // Some variables are unused but cleared explicitly to prevent
  132. // the parent environment from interfering.
  133. // We never override an entry previously set
  134. if _, ok := fc.Env["REMOTE_IDENT"]; !ok {
  135. fc.Env["REMOTE_IDENT"] = "" // Not used
  136. }
  137. if _, ok := fc.Env["AUTH_TYPE"]; !ok {
  138. fc.Env["AUTH_TYPE"] = "" // Not used
  139. }
  140. if _, ok := fc.Env["CONTENT_LENGTH"]; !ok {
  141. fc.Env["CONTENT_LENGTH"] = request.Header.Get("Content-Length")
  142. }
  143. if _, ok := fc.Env["CONTENT_TYPE"]; !ok {
  144. fc.Env["CONTENT_TYPE"] = request.Header.Get("Content-Type")
  145. }
  146. if _, ok := fc.Env["GATEWAY_INTERFACE"]; !ok {
  147. fc.Env["GATEWAY_INTERFACE"] = "CGI/1.1"
  148. }
  149. if _, ok := fc.Env["QUERY_STRING"]; !ok {
  150. fc.Env["QUERY_STRING"] = request.URL.RawQuery
  151. }
  152. if _, ok := fc.Env["QUERY_STRING"]; !ok {
  153. fc.Env["QUERY_STRING"] = request.URL.RawQuery
  154. }
  155. if _, ok := fc.Env["REQUEST_METHOD"]; !ok {
  156. fc.Env["REQUEST_METHOD"] = request.Method
  157. }
  158. if _, ok := fc.Env["SERVER_PROTOCOL"]; !ok {
  159. fc.Env["SERVER_PROTOCOL"] = request.Proto
  160. }
  161. if _, ok := fc.Env["SERVER_SOFTWARE"]; !ok {
  162. fc.Env["SERVER_SOFTWARE"] = "FrankenPHP"
  163. }
  164. if _, ok := fc.Env["HTTP_HOST"]; !ok {
  165. fc.Env["HTTP_HOST"] = request.Host // added here, since not always part of headers
  166. }
  167. if _, ok := fc.Env["REQUEST_URI"]; !ok {
  168. fc.Env["REQUEST_URI"] = request.URL.RequestURI()
  169. }
  170. // compliance with the CGI specification requires that
  171. // PATH_TRANSLATED should only exist if PATH_INFO is defined.
  172. // Info: https://www.ietf.org/rfc/rfc3875 Page 14
  173. if fc.Env["PATH_INFO"] != "" {
  174. fc.Env["PATH_TRANSLATED"] = sanitizedPathJoin(fc.Env["DOCUMENT_ROOT"], fc.Env["PATH_INFO"]) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
  175. }
  176. // Add all HTTP headers to env variables
  177. for field, val := range request.Header {
  178. k := "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(field))
  179. if _, ok := fc.Env[k]; !ok {
  180. fc.Env[k] = strings.Join(val, ", ")
  181. }
  182. }
  183. if _, ok := fc.Env["REMOTE_USER"]; !ok {
  184. var (
  185. authUser string
  186. ok bool
  187. )
  188. authUser, fc.authPassword, ok = request.BasicAuth()
  189. if ok {
  190. fc.Env["REMOTE_USER"] = authUser
  191. }
  192. }
  193. fc.populated = true
  194. return nil
  195. }
  196. // splitPos returns the index where path should
  197. // be split based on SplitPath.
  198. //
  199. // Adapted from https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
  200. // Copyright 2015 Matthew Holt and The Caddy Authors
  201. func splitPos(fc *FrankenPHPContext, path string) int {
  202. if len(fc.SplitPath) == 0 {
  203. return 0
  204. }
  205. lowerPath := strings.ToLower(path)
  206. for _, split := range fc.SplitPath {
  207. if idx := strings.Index(lowerPath, strings.ToLower(split)); idx > -1 {
  208. return idx + len(split)
  209. }
  210. }
  211. return -1
  212. }
  213. // Map of supported protocols to Apache ssl_mod format
  214. // Note that these are slightly different from SupportedProtocols in caddytls/config.go
  215. var tlsProtocolStrings = map[uint16]string{
  216. tls.VersionTLS10: "TLSv1",
  217. tls.VersionTLS11: "TLSv1.1",
  218. tls.VersionTLS12: "TLSv1.2",
  219. tls.VersionTLS13: "TLSv1.3",
  220. }
  221. var headerNameReplacer = strings.NewReplacer(" ", "_", "-", "_")
  222. // SanitizedPathJoin performs filepath.Join(root, reqPath) that
  223. // is safe against directory traversal attacks. It uses logic
  224. // similar to that in the Go standard library, specifically
  225. // in the implementation of http.Dir. The root is assumed to
  226. // be a trusted path, but reqPath is not; and the output will
  227. // never be outside of root. The resulting path can be used
  228. // with the local file system.
  229. //
  230. // Adapted from https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
  231. // Copyright 2015 Matthew Holt and The Caddy Authors
  232. func sanitizedPathJoin(root, reqPath string) string {
  233. if root == "" {
  234. root = "."
  235. }
  236. path := filepath.Join(root, filepath.Clean("/"+reqPath))
  237. // filepath.Join also cleans the path, and cleaning strips
  238. // the trailing slash, so we need to re-add it afterwards.
  239. // if the length is 1, then it's a path to the root,
  240. // and that should return ".", so we don't append the separator.
  241. if strings.HasSuffix(reqPath, "/") && len(reqPath) > 1 {
  242. path += separator
  243. }
  244. return path
  245. }
  246. const separator = string(filepath.Separator)