cgi.go 8.4 KB

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