frankenphp.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package frankenphp
  2. // #cgo CFLAGS: -Wall -Wno-unused-variable
  3. // #cgo CFLAGS: -I/usr/local/include/php -I/usr/local/include/php/Zend -I/usr/local/include/php/TSRM -I/usr/local/include/php/main
  4. // #cgo LDFLAGS: -L/usr/local/lib -L/opt/homebrew/opt/libiconv/lib -L/usr/lib -lphp -lxml2 -liconv -lresolv -lsqlite3
  5. // #include <stdlib.h>
  6. // #include <stdint.h>
  7. // #include "php_variables.h"
  8. // #include "frankenphp.h"
  9. import "C"
  10. import (
  11. "context"
  12. "fmt"
  13. "io"
  14. "log"
  15. "net/http"
  16. "runtime"
  17. "runtime/cgo"
  18. "strconv"
  19. "strings"
  20. "sync/atomic"
  21. "unsafe"
  22. )
  23. var started int32
  24. type key int
  25. var contextKey key
  26. func init() {
  27. log.SetFlags(log.LstdFlags | log.Lshortfile)
  28. }
  29. // FrankenPHP executes PHP scripts.
  30. type FrankenPHPContext struct {
  31. // The root directory of the PHP application.
  32. DocumentRoot string
  33. // The path in the URL will be split into two, with the first piece ending
  34. // with the value of SplitPath. The first piece will be assumed as the
  35. // actual resource (CGI script) name, and the second piece will be set to
  36. // PATH_INFO for the CGI script to use.
  37. //
  38. // Future enhancements should be careful to avoid CVE-2019-11043,
  39. // which can be mitigated with use of a try_files-like behavior
  40. // that 404s if the fastcgi path info is not found.
  41. SplitPath []string
  42. // Path declared as root directory will be resolved to its absolute value
  43. // after the evaluation of any symbolic links.
  44. // Due to the nature of PHP opcache, root directory path is cached: when
  45. // using a symlinked directory as root this could generate errors when
  46. // symlink is changed without php-fpm being restarted; enabling this
  47. // directive will set $_SERVER['DOCUMENT_ROOT'] to the real directory path.
  48. ResolveRootSymlink bool
  49. // CGI-like environment variables that will be available in $_SERVER.
  50. // This map is populated automatically, exisiting key are never replaced.
  51. Env map[string]string
  52. populated bool
  53. authPassword string
  54. responseWriter http.ResponseWriter
  55. done chan interface{}
  56. }
  57. func NewRequestWithContext(r *http.Request, documentRoot string) *http.Request {
  58. ctx := context.WithValue(r.Context(), contextKey, &FrankenPHPContext{
  59. DocumentRoot: documentRoot,
  60. SplitPath: []string{".php"},
  61. Env: make(map[string]string),
  62. })
  63. return r.WithContext(ctx)
  64. }
  65. func FromContext(ctx context.Context) (fctx *FrankenPHPContext, ok bool) {
  66. fctx, ok = ctx.Value(contextKey).(*FrankenPHPContext)
  67. return
  68. }
  69. // Startup starts the PHP engine.
  70. // Startup and Shutdown must be called in the same goroutine (ideally in the main function).
  71. func Startup() error {
  72. if atomic.LoadInt32(&started) > 0 {
  73. return nil
  74. }
  75. atomic.StoreInt32(&started, 1)
  76. runtime.LockOSThread()
  77. if C.frankenphp_init() < 0 {
  78. return fmt.Errorf(`ZTS is not enabled, recompile PHP using the "--enable-zts" configuration option`)
  79. }
  80. return nil
  81. }
  82. // Shutdown stops the PHP engine.
  83. // Shutdown and Startup must be called in the same goroutine (ideally in the main function).
  84. func Shutdown() {
  85. if atomic.LoadInt32(&started) < 1 {
  86. return
  87. }
  88. atomic.StoreInt32(&started, 0)
  89. C.frankenphp_shutdown()
  90. }
  91. func updateServerContext(request *http.Request) error {
  92. if err := populateEnv(request); err != nil {
  93. return err
  94. }
  95. fc, ok := FromContext(request.Context())
  96. if !ok {
  97. panic("not a FrankenPHP request")
  98. }
  99. var cAuthUser, cAuthPassword *C.char
  100. if fc.authPassword != "" {
  101. cAuthPassword = C.CString(fc.authPassword)
  102. }
  103. if authUser := fc.Env["REMOTE_USER"]; authUser != "" {
  104. cAuthUser = C.CString(authUser)
  105. }
  106. rh := cgo.NewHandle(request)
  107. cMethod := C.CString(request.Method)
  108. cQueryString := C.CString(request.URL.RawQuery)
  109. contentLengthStr := request.Header.Get("Content-Length")
  110. contentLength := 0
  111. if contentLengthStr != "" {
  112. contentLength, _ = strconv.Atoi(contentLengthStr)
  113. }
  114. contentType := request.Header.Get("Content-Type")
  115. var cContentType *C.char
  116. if contentType != "" {
  117. cContentType = C.CString(contentType)
  118. }
  119. var cPathTranslated *C.char
  120. if pathTranslated := fc.Env["PATH_TRANSLATED"]; pathTranslated != "" {
  121. cPathTranslated = C.CString(pathTranslated)
  122. }
  123. cRequestUri := C.CString(request.URL.RequestURI())
  124. C.frankenphp_update_server_context(
  125. C.uintptr_t(rh),
  126. cMethod,
  127. cQueryString,
  128. C.zend_long(contentLength),
  129. cPathTranslated,
  130. cRequestUri,
  131. cContentType,
  132. cAuthUser,
  133. cAuthPassword,
  134. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  135. )
  136. return nil
  137. }
  138. func ExecuteScript(responseWriter http.ResponseWriter, request *http.Request) error {
  139. if atomic.LoadInt32(&started) < 1 {
  140. panic("FrankenPHP isn't started, call frankenphp.Startup()")
  141. }
  142. runtime.LockOSThread()
  143. // todo: check if it's ok or not to call runtime.UnlockOSThread() to reuse this thread
  144. if C.frankenphp_create_server_context(0, nil) < 0 {
  145. return fmt.Errorf("error during request context creation")
  146. }
  147. if err := updateServerContext(request); err != nil {
  148. return err
  149. }
  150. if C.frankenphp_request_startup() < 0 {
  151. return fmt.Errorf("error during PHP request startup")
  152. }
  153. fc := request.Context().Value(contextKey).(*FrankenPHPContext)
  154. fc.responseWriter = responseWriter
  155. cFileName := C.CString(fc.Env["SCRIPT_FILENAME"])
  156. defer C.free(unsafe.Pointer(cFileName))
  157. if C.frankenphp_execute_script(cFileName) < 0 {
  158. return fmt.Errorf("error during PHP script execution")
  159. }
  160. rh := C.frankenphp_clean_server_context()
  161. C.frankenphp_request_shutdown()
  162. cgo.Handle(rh).Delete()
  163. return nil
  164. }
  165. //export go_ub_write
  166. func go_ub_write(rh C.uintptr_t, cString *C.char, length C.int) C.size_t {
  167. r := cgo.Handle(rh).Value().(*http.Request)
  168. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  169. i, _ := fc.responseWriter.Write([]byte(C.GoStringN(cString, length)))
  170. return C.size_t(i)
  171. }
  172. //export go_register_variables
  173. func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) {
  174. var env map[string]string
  175. if rh == 0 {
  176. // Worker mode, waiting for a request, initialize some useful variables
  177. env = map[string]string{"FRANKENPHP_WORKER": "1"}
  178. } else {
  179. r := cgo.Handle(rh).Value().(*http.Request)
  180. env = r.Context().Value(contextKey).(*FrankenPHPContext).Env
  181. }
  182. env[fmt.Sprintf("REQUEST_%d", rh)] = "on"
  183. for k, v := range env {
  184. ck := C.CString(k)
  185. cv := C.CString(v)
  186. C.php_register_variable(ck, cv, trackVarsArray)
  187. C.free(unsafe.Pointer(ck))
  188. C.free(unsafe.Pointer(cv))
  189. }
  190. }
  191. //export go_add_header
  192. func go_add_header(rh C.uintptr_t, cString *C.char, length C.int) {
  193. r := cgo.Handle(rh).Value().(*http.Request)
  194. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  195. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  196. if len(parts) != 2 {
  197. log.Printf(`invalid header "%s"`+"\n", parts[0])
  198. return
  199. }
  200. fc.responseWriter.Header().Add(parts[0], parts[1])
  201. }
  202. //export go_write_header
  203. func go_write_header(rh C.uintptr_t, status C.int) {
  204. r := cgo.Handle(rh).Value().(*http.Request)
  205. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  206. fc.responseWriter.WriteHeader(int(status))
  207. }
  208. //export go_read_post
  209. func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) C.size_t {
  210. r := cgo.Handle(rh).Value().(*http.Request)
  211. p := make([]byte, int(countBytes))
  212. readBytes, err := r.Body.Read(p)
  213. if err != nil && err != io.EOF {
  214. panic(err)
  215. }
  216. if readBytes != 0 {
  217. // todo: memory leak?
  218. C.memcpy(unsafe.Pointer(cBuf), unsafe.Pointer(&p[0]), C.size_t(readBytes))
  219. }
  220. return C.size_t(readBytes)
  221. }
  222. //export go_read_cookies
  223. func go_read_cookies(rh C.uintptr_t) *C.char {
  224. r := cgo.Handle(rh).Value().(*http.Request)
  225. cookies := r.Cookies()
  226. if len(cookies) == 0 {
  227. return nil
  228. }
  229. cookieString := make([]string, len(cookies))
  230. for _, cookie := range r.Cookies() {
  231. cookieString = append(cookieString, cookie.String())
  232. }
  233. cCookie := C.CString(strings.Join(cookieString, "; "))
  234. // freed in frankenphp_request_shutdown()
  235. return cCookie
  236. }