cgi.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package frankenphp
  2. // #include <php_variables.h>
  3. // #include "frankenphp.h"
  4. import "C"
  5. import (
  6. "crypto/tls"
  7. "net"
  8. "net/http"
  9. "path/filepath"
  10. "strings"
  11. )
  12. var knownServerKeys = map[string]struct{}{
  13. "CONTENT_LENGTH\x00": {},
  14. "DOCUMENT_ROOT\x00": {},
  15. "DOCUMENT_URI\x00": {},
  16. "GATEWAY_INTERFACE\x00": {},
  17. "HTTP_HOST\x00": {},
  18. "HTTPS\x00": {},
  19. "PATH_INFO\x00": {},
  20. "PHP_SELF\x00": {},
  21. "REMOTE_ADDR\x00": {},
  22. "REMOTE_HOST\x00": {},
  23. "REMOTE_PORT\x00": {},
  24. "REQUEST_SCHEME\x00": {},
  25. "SCRIPT_FILENAME\x00": {},
  26. "SCRIPT_NAME\x00": {},
  27. "SERVER_NAME\x00": {},
  28. "SERVER_PORT\x00": {},
  29. "SERVER_PROTOCOL\x00": {},
  30. "SERVER_SOFTWARE\x00": {},
  31. "SSL_PROTOCOL\x00": {},
  32. "AUTH_TYPE\x00": {},
  33. "REMOTE_IDENT\x00": {},
  34. "CONTENT_TYPE\x00": {},
  35. "PATH_TRANSLATED\x00": {},
  36. "QUERY_STRING\x00": {},
  37. "REMOTE_USER\x00": {},
  38. "REQUEST_METHOD\x00": {},
  39. "REQUEST_URI\x00": {},
  40. }
  41. // computeKnownVariables returns a set of CGI environment variables for the request.
  42. //
  43. // TODO: handle this case https://github.com/caddyserver/caddy/issues/3718
  44. // Inspired by https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
  45. func addKnownVariablesToServer(thread *phpThread, request *http.Request, fc *FrankenPHPContext, trackVarsArray *C.zval) {
  46. keys := getKnownVariableKeys(thread)
  47. // Separate remote IP and port; more lenient than net.SplitHostPort
  48. var ip, port string
  49. if idx := strings.LastIndex(request.RemoteAddr, ":"); idx > -1 {
  50. ip = request.RemoteAddr[:idx]
  51. port = request.RemoteAddr[idx+1:]
  52. } else {
  53. ip = request.RemoteAddr
  54. }
  55. // Remove [] from IPv6 addresses
  56. ip = strings.Replace(ip, "[", "", 1)
  57. ip = strings.Replace(ip, "]", "", 1)
  58. ra, raOK := fc.env["REMOTE_ADDR\x00"]
  59. if raOK {
  60. registerTrustedVar(keys["REMOTE_ADDR\x00"], ra, trackVarsArray, thread)
  61. } else {
  62. registerTrustedVar(keys["REMOTE_ADDR\x00"], ip, trackVarsArray, thread)
  63. }
  64. if rh, ok := fc.env["REMOTE_HOST\x00"]; ok {
  65. registerTrustedVar(keys["REMOTE_HOST\x00"], rh, trackVarsArray, thread) // For speed, remote host lookups disabled
  66. } else {
  67. if raOK {
  68. registerTrustedVar(keys["REMOTE_HOST\x00"], ra, trackVarsArray, thread)
  69. } else {
  70. registerTrustedVar(keys["REMOTE_HOST\x00"], ip, trackVarsArray, thread)
  71. }
  72. }
  73. registerTrustedVar(keys["REMOTE_PORT\x00"], port, trackVarsArray, thread)
  74. registerTrustedVar(keys["DOCUMENT_ROOT\x00"], fc.documentRoot, trackVarsArray, thread)
  75. registerTrustedVar(keys["PATH_INFO\x00"], fc.pathInfo, trackVarsArray, thread)
  76. registerTrustedVar(keys["PHP_SELF\x00"], request.URL.Path, trackVarsArray, thread)
  77. registerTrustedVar(keys["DOCUMENT_URI\x00"], fc.docURI, trackVarsArray, thread)
  78. registerTrustedVar(keys["SCRIPT_FILENAME\x00"], fc.scriptFilename, trackVarsArray, thread)
  79. registerTrustedVar(keys["SCRIPT_NAME\x00"], fc.scriptName, trackVarsArray, thread)
  80. var rs string
  81. if request.TLS == nil {
  82. rs = "http"
  83. registerTrustedVar(keys["HTTPS\x00"], "", trackVarsArray, thread)
  84. registerTrustedVar(keys["SSL_PROTOCOL\x00"], "", trackVarsArray, thread)
  85. } else {
  86. rs = "https"
  87. if h, ok := fc.env["HTTPS\x00"]; ok {
  88. registerTrustedVar(keys["HTTPS\x00"], h, trackVarsArray, thread)
  89. } else {
  90. registerTrustedVar(keys["HTTPS\x00"], "on", trackVarsArray, thread)
  91. }
  92. // and pass the protocol details in a manner compatible with apache's mod_ssl
  93. // (which is why these have an SSL_ prefix and not TLS_).
  94. if pr, ok := fc.env["SSL_PROTOCOL\x00"]; ok {
  95. registerTrustedVar(keys["SSL_PROTOCOL\x00"], pr, trackVarsArray, thread)
  96. } else {
  97. if v, ok := tlsProtocolStrings[request.TLS.Version]; ok {
  98. registerTrustedVar(keys["SSL_PROTOCOL\x00"], v, trackVarsArray, thread)
  99. } else {
  100. registerTrustedVar(keys["SSL_PROTOCOL\x00"], "", trackVarsArray, thread)
  101. }
  102. }
  103. }
  104. registerTrustedVar(keys["REQUEST_SCHEME\x00"], rs, trackVarsArray, thread)
  105. reqHost, reqPort, _ := net.SplitHostPort(request.Host)
  106. if reqHost == "" {
  107. // whatever, just assume there was no port
  108. reqHost = request.Host
  109. }
  110. if reqPort == "" {
  111. // compliance with the CGI specification requires that
  112. // the SERVER_PORT variable MUST be set to the TCP/IP port number on which this request is received from the client
  113. // even if the port is the default port for the scheme and could otherwise be omitted from a URI.
  114. // https://tools.ietf.org/html/rfc3875#section-4.1.15
  115. switch rs {
  116. case "https":
  117. reqPort = "443"
  118. case "http":
  119. reqPort = "80"
  120. }
  121. }
  122. registerTrustedVar(keys["SERVER_NAME\x00"], reqHost, trackVarsArray, thread)
  123. if reqPort != "" {
  124. registerTrustedVar(keys["SERVER_PORT\x00"], reqPort, trackVarsArray, thread)
  125. } else {
  126. registerTrustedVar(keys["SERVER_PORT\x00"], "", trackVarsArray, thread)
  127. }
  128. // Variables defined in CGI 1.1 spec
  129. // Some variables are unused but cleared explicitly to prevent
  130. // the parent environment from interfering.
  131. // These values can not be overridden
  132. registerTrustedVar(keys["CONTENT_LENGTH\x00"], request.Header.Get("Content-Length"), trackVarsArray, thread)
  133. registerTrustedVar(keys["GATEWAY_INTERFACE\x00"], "CGI/1.1", trackVarsArray, thread)
  134. registerTrustedVar(keys["SERVER_PROTOCOL\x00"], request.Proto, trackVarsArray, thread)
  135. registerTrustedVar(keys["SERVER_SOFTWARE\x00"], "FrankenPHP", trackVarsArray, thread)
  136. registerTrustedVar(keys["HTTP_HOST\x00"], request.Host, trackVarsArray, thread) // added here, since not always part of headers
  137. // These values are always empty but must be defined:
  138. registerTrustedVar(keys["AUTH_TYPE\x00"], "", trackVarsArray, thread)
  139. registerTrustedVar(keys["REMOTE_IDENT\x00"], "", trackVarsArray, thread)
  140. // These values are already present in the SG(request_info), so we'll register them from there
  141. C.frankenphp_register_variables_from_request_info(
  142. trackVarsArray,
  143. keys["CONTENT_TYPE\x00"],
  144. keys["PATH_TRANSLATED\x00"],
  145. keys["QUERY_STRING\x00"],
  146. keys["REMOTE_USER\x00"],
  147. keys["REQUEST_METHOD\x00"],
  148. keys["REQUEST_URI\x00"],
  149. )
  150. }
  151. func registerTrustedVar(key *C.zend_string, value string, trackVarsArray *C.zval, thread *phpThread) {
  152. C.frankenphp_register_trusted_var(key, thread.pinString(value), C.int(len(value)), trackVarsArray)
  153. }
  154. func addHeadersToServer(thread *phpThread, request *http.Request, fc *FrankenPHPContext, trackVarsArray *C.zval) {
  155. for field, val := range request.Header {
  156. k, ok := headerKeyCache.Get(field)
  157. if !ok {
  158. k = "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(field)) + "\x00"
  159. headerKeyCache.SetIfAbsent(field, k)
  160. }
  161. if _, ok := fc.env[k]; ok {
  162. continue
  163. }
  164. v := strings.Join(val, ", ")
  165. C.frankenphp_register_variable_safe(thread.pinString(k), thread.pinString(v), C.size_t(len(v)), trackVarsArray)
  166. }
  167. }
  168. func addPreparedEnvToServer(thread *phpThread, fc *FrankenPHPContext, trackVarsArray *C.zval) {
  169. for k, v := range fc.env {
  170. C.frankenphp_register_variable_safe(thread.pinString(k), thread.pinString(v), C.size_t(len(v)), trackVarsArray)
  171. }
  172. fc.env = nil
  173. }
  174. func getKnownVariableKeys(thread *phpThread) map[string]*C.zend_string {
  175. if thread.knownVariableKeys != nil {
  176. return thread.knownVariableKeys
  177. }
  178. threadServerKeys := make(map[string]*C.zend_string)
  179. for k := range knownServerKeys {
  180. keyWithoutNull := strings.Replace(k, "\x00", "", -1)
  181. threadServerKeys[k] = C.frankenphp_init_persistent_string(thread.pinString(keyWithoutNull), C.size_t(len(keyWithoutNull)))
  182. }
  183. thread.knownVariableKeys = threadServerKeys
  184. return threadServerKeys
  185. }
  186. //export go_register_variables
  187. func go_register_variables(threadIndex C.uintptr_t, trackVarsArray *C.zval) {
  188. thread := phpThreads[threadIndex]
  189. r := thread.getActiveRequest()
  190. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  191. addKnownVariablesToServer(thread, r, fc, trackVarsArray)
  192. addHeadersToServer(thread, r, fc, trackVarsArray)
  193. addPreparedEnvToServer(thread, fc, trackVarsArray)
  194. }
  195. //export go_frankenphp_release_known_variable_keys
  196. func go_frankenphp_release_known_variable_keys(threadIndex C.uintptr_t) {
  197. thread := phpThreads[threadIndex]
  198. if thread.knownVariableKeys == nil {
  199. return
  200. }
  201. for _, v := range thread.knownVariableKeys {
  202. C.frankenphp_release_zend_string(v)
  203. }
  204. // release everything that might still be pinned to the thread
  205. thread.Unpin()
  206. thread.knownVariableKeys = nil
  207. }
  208. // splitPos returns the index where path should
  209. // be split based on SplitPath.
  210. //
  211. // Adapted from https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
  212. // Copyright 2015 Matthew Holt and The Caddy Authors
  213. func splitPos(fc *FrankenPHPContext, path string) int {
  214. if len(fc.splitPath) == 0 {
  215. return 0
  216. }
  217. lowerPath := strings.ToLower(path)
  218. for _, split := range fc.splitPath {
  219. if idx := strings.Index(lowerPath, strings.ToLower(split)); idx > -1 {
  220. return idx + len(split)
  221. }
  222. }
  223. return -1
  224. }
  225. // Map of supported protocols to Apache ssl_mod format
  226. // Note that these are slightly different from SupportedProtocols in caddytls/config.go
  227. var tlsProtocolStrings = map[uint16]string{
  228. tls.VersionTLS10: "TLSv1",
  229. tls.VersionTLS11: "TLSv1.1",
  230. tls.VersionTLS12: "TLSv1.2",
  231. tls.VersionTLS13: "TLSv1.3",
  232. }
  233. var headerNameReplacer = strings.NewReplacer(" ", "_", "-", "_")
  234. // SanitizedPathJoin performs filepath.Join(root, reqPath) that
  235. // is safe against directory traversal attacks. It uses logic
  236. // similar to that in the Go standard library, specifically
  237. // in the implementation of http.Dir. The root is assumed to
  238. // be a trusted path, but reqPath is not; and the output will
  239. // never be outside of root. The resulting path can be used
  240. // with the local file system.
  241. //
  242. // Adapted from https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
  243. // Copyright 2015 Matthew Holt and The Caddy Authors
  244. func sanitizedPathJoin(root, reqPath string) string {
  245. if root == "" {
  246. root = "."
  247. }
  248. path := filepath.Join(root, filepath.Clean("/"+reqPath))
  249. // filepath.Join also cleans the path, and cleaning strips
  250. // the trailing slash, so we need to re-add it afterward.
  251. // if the length is 1, then it's a path to the root,
  252. // and that should return ".", so we don't append the separator.
  253. if strings.HasSuffix(reqPath, "/") && len(reqPath) > 1 {
  254. path += separator
  255. }
  256. return path
  257. }
  258. const separator = string(filepath.Separator)