frankenphp.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. // Package frankenphp embeds PHP in Go projects and provides a SAPI for net/http.
  2. //
  3. // This is the core of the [FrankenPHP app server], and can be used in any Go program.
  4. //
  5. // [FrankenPHP app server]: https://frankenphp.dev
  6. package frankenphp
  7. //go:generate rm -Rf C-Thread-Pool/
  8. //go:generate git clone --branch=fix/SA_ONSTACK --depth=1 git@github.com:dunglas/C-Thread-Pool.git
  9. //go:generate rm -Rf C-Thread-Pool/.git C-Thread-Pool/.circleci C-Thread-Pool/docs C-Thread-Pool/tests
  10. // #cgo CFLAGS: -Wall -Werror
  11. // #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
  12. // #cgo linux CFLAGS: -D_GNU_SOURCE
  13. // #cgo LDFLAGS: -L/usr/local/lib -L/opt/homebrew/opt/libiconv/lib -L/usr/lib -lphp -lxml2 -lresolv -lsqlite3 -ldl -lm -lutil
  14. // #cgo darwin LDFLAGS: -liconv
  15. // #include <stdlib.h>
  16. // #include <stdint.h>
  17. // #include <php_variables.h>
  18. // #include "frankenphp.h"
  19. import "C"
  20. import (
  21. "bytes"
  22. "context"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "net/http"
  27. "runtime"
  28. "runtime/cgo"
  29. "strconv"
  30. "strings"
  31. "sync"
  32. "unsafe"
  33. "go.uber.org/zap"
  34. // debug on Linux
  35. //_ "github.com/ianlancetaylor/cgosymbolizer"
  36. )
  37. type key int
  38. var contextKey key
  39. var (
  40. InvalidRequestError = errors.New("not a FrankenPHP request")
  41. AlreaydStartedError = errors.New("FrankenPHP is already started")
  42. InvalidPHPVersionError = errors.New("FrankenPHP is only compatible with PHP 8.2+")
  43. ZendSignalsError = errors.New("Zend Signals are enabled, recompile PHP with --disable-zend-signals")
  44. NotEnoughThreads = errors.New("the number of threads must be superior to the number of workers")
  45. MainThreadCreationError = errors.New("error creating the main thread")
  46. RequestContextCreationError = errors.New("error during request context creation")
  47. RequestStartupError = errors.New("error during PHP request startup")
  48. ScriptExecutionError = errors.New("error during PHP script execution")
  49. requestChan chan *http.Request
  50. done chan struct{}
  51. shutdownWG sync.WaitGroup
  52. loggerMu sync.RWMutex
  53. logger *zap.Logger
  54. )
  55. type syslogLevel int
  56. const (
  57. emerg syslogLevel = iota // system is unusable
  58. alert // action must be taken immediately
  59. crit // critical conditions
  60. err // error conditions
  61. warning // warning conditions
  62. notice // normal but significant condition
  63. info // informational
  64. debug // debug-level messages
  65. )
  66. func (l syslogLevel) String() string {
  67. switch l {
  68. case emerg:
  69. return "emerg"
  70. case alert:
  71. return "alert"
  72. case crit:
  73. return "crit"
  74. case err:
  75. return "err"
  76. case warning:
  77. return "warning"
  78. case notice:
  79. return "notice"
  80. case debug:
  81. return "debug"
  82. default:
  83. return "info"
  84. }
  85. }
  86. // FrankenPHPContext provides contextual information about the Request to handle.
  87. type FrankenPHPContext struct {
  88. // The root directory of the PHP application.
  89. DocumentRoot string
  90. // The path in the URL will be split into two, with the first piece ending
  91. // with the value of SplitPath. The first piece will be assumed as the
  92. // actual resource (CGI script) name, and the second piece will be set to
  93. // PATH_INFO for the CGI script to use.
  94. //
  95. // Future enhancements should be careful to avoid CVE-2019-11043,
  96. // which can be mitigated with use of a try_files-like behavior
  97. // that 404s if the fastcgi path info is not found.
  98. SplitPath []string
  99. // Path declared as root directory will be resolved to its absolute value
  100. // after the evaluation of any symbolic links.
  101. // Due to the nature of PHP opcache, root directory path is cached: when
  102. // using a symlinked directory as root this could generate errors when
  103. // symlink is changed without php-fpm being restarted; enabling this
  104. // directive will set $_SERVER['DOCUMENT_ROOT'] to the real directory path.
  105. ResolveRootSymlink bool
  106. // CGI-like environment variables that will be available in $_SERVER.
  107. // This map is populated automatically, exisiting key are never replaced.
  108. Env map[string]string
  109. // The logger associated with the current request
  110. Logger *zap.Logger
  111. populated bool
  112. authPassword string
  113. // Whether the request is already closed by us
  114. closed sync.Once
  115. responseWriter http.ResponseWriter
  116. done chan interface{}
  117. currentWorkerRequest cgo.Handle
  118. }
  119. func clientHasClosed(r *http.Request) bool {
  120. select {
  121. case <-r.Context().Done():
  122. return true
  123. default:
  124. return false
  125. }
  126. }
  127. // NewRequestWithContext creates a new FrankenPHP request context.
  128. func NewRequestWithContext(r *http.Request, documentRoot string, l *zap.Logger) *http.Request {
  129. if l == nil {
  130. l = getLogger()
  131. }
  132. ctx := context.WithValue(r.Context(), contextKey, &FrankenPHPContext{
  133. DocumentRoot: documentRoot,
  134. SplitPath: []string{".php"},
  135. Env: make(map[string]string),
  136. Logger: l,
  137. })
  138. return r.WithContext(ctx)
  139. }
  140. // FromContext extracts the FrankenPHPContext from a context.
  141. func FromContext(ctx context.Context) (fctx *FrankenPHPContext, ok bool) {
  142. fctx, ok = ctx.Value(contextKey).(*FrankenPHPContext)
  143. return
  144. }
  145. type PHPVersion struct {
  146. MajorVersion int
  147. MinorVersion int
  148. ReleaseVersion int
  149. ExtraVersion string
  150. Version string
  151. VersionID int
  152. }
  153. type PHPConfig struct {
  154. Version PHPVersion
  155. ZTS bool
  156. ZendSignals bool
  157. ZendMaxExecutionTimers bool
  158. }
  159. // Version returns infos about the PHP version.
  160. func Version() PHPVersion {
  161. cVersion := C.frankenphp_get_version()
  162. return PHPVersion{
  163. int(cVersion.major_version),
  164. int(cVersion.minor_version),
  165. int(cVersion.release_version),
  166. C.GoString(cVersion.extra_version),
  167. C.GoString(cVersion.version),
  168. int(cVersion.version_id),
  169. }
  170. }
  171. func Config() PHPConfig {
  172. cConfig := C.frankenphp_get_config()
  173. return PHPConfig{
  174. Version: Version(),
  175. ZTS: bool(cConfig.zts),
  176. ZendSignals: bool(cConfig.zend_signals),
  177. ZendMaxExecutionTimers: bool(cConfig.zend_max_execution_timers),
  178. }
  179. }
  180. // Init starts the PHP runtime and the configured workers.
  181. func Init(options ...Option) error {
  182. if requestChan != nil {
  183. return AlreaydStartedError
  184. }
  185. opt := &opt{}
  186. for _, o := range options {
  187. if err := o(opt); err != nil {
  188. return err
  189. }
  190. }
  191. if opt.logger == nil {
  192. l, err := zap.NewDevelopment()
  193. if err != nil {
  194. return err
  195. }
  196. loggerMu.Lock()
  197. logger = l
  198. loggerMu.Unlock()
  199. } else {
  200. loggerMu.Lock()
  201. logger = opt.logger
  202. loggerMu.Unlock()
  203. }
  204. maxProcs := runtime.GOMAXPROCS(0)
  205. var numWorkers int
  206. for i, w := range opt.workers {
  207. if w.num <= 0 {
  208. // https://github.com/dunglas/frankenphp/issues/126
  209. opt.workers[i].num = maxProcs * 2
  210. }
  211. numWorkers += opt.workers[i].num
  212. }
  213. if opt.numThreads <= 0 {
  214. if numWorkers >= maxProcs {
  215. // Start at least as many threads as workers, and keep a free thread to handle requests in non-worker mode
  216. opt.numThreads = numWorkers + 1
  217. } else {
  218. opt.numThreads = maxProcs
  219. }
  220. } else if opt.numThreads <= numWorkers {
  221. return NotEnoughThreads
  222. }
  223. config := Config()
  224. if config.Version.MajorVersion < 8 || config.Version.MinorVersion < 2 {
  225. return InvalidPHPVersionError
  226. }
  227. if config.ZTS {
  228. if !config.ZendMaxExecutionTimers && runtime.GOOS == "linux" {
  229. logger.Warn(`Zend Timer is not enabled, "--enable-zend-max-execution-timers" configuration option or timeouts (e.g. "max_execution_time") will not work as expected`)
  230. }
  231. } else {
  232. opt.numThreads = 1
  233. logger.Warn(`ZTS is not enabled, only 1 thread will be available, recompile PHP using the "--enable-zts" configuration option or performance will be degraded`)
  234. }
  235. shutdownWG.Add(1)
  236. done = make(chan struct{})
  237. requestChan = make(chan *http.Request)
  238. if C.frankenphp_init(C.int(opt.numThreads)) != 0 {
  239. return MainThreadCreationError
  240. }
  241. for _, w := range opt.workers {
  242. // TODO: start all the worker in parallell to reduce the boot time
  243. if err := startWorkers(w.fileName, w.num); err != nil {
  244. return err
  245. }
  246. }
  247. logger.Debug("FrankenPHP started")
  248. return nil
  249. }
  250. // Shutdown stops the workers and the PHP runtime.
  251. func Shutdown() {
  252. stopWorkers()
  253. close(done)
  254. shutdownWG.Wait()
  255. requestChan = nil
  256. logger.Debug("FrankenPHP shut down")
  257. }
  258. //export go_shutdown
  259. func go_shutdown() {
  260. shutdownWG.Done()
  261. }
  262. func getLogger() *zap.Logger {
  263. loggerMu.RLock()
  264. defer loggerMu.RUnlock()
  265. return logger
  266. }
  267. func updateServerContext(request *http.Request, create bool, mrh C.uintptr_t) error {
  268. fc, ok := FromContext(request.Context())
  269. if !ok {
  270. return InvalidRequestError
  271. }
  272. var cAuthUser, cAuthPassword *C.char
  273. if fc.authPassword != "" {
  274. cAuthPassword = C.CString(fc.authPassword)
  275. }
  276. if authUser := fc.Env["REMOTE_USER"]; authUser != "" {
  277. cAuthUser = C.CString(authUser)
  278. }
  279. cMethod := C.CString(request.Method)
  280. cQueryString := C.CString(request.URL.RawQuery)
  281. contentLengthStr := request.Header.Get("Content-Length")
  282. contentLength := 0
  283. if contentLengthStr != "" {
  284. var err error
  285. contentLength, err = strconv.Atoi(contentLengthStr)
  286. if err != nil {
  287. return fmt.Errorf("invalid Content-Length header: %w", err)
  288. }
  289. }
  290. contentType := request.Header.Get("Content-Type")
  291. var cContentType *C.char
  292. if contentType != "" {
  293. cContentType = C.CString(contentType)
  294. }
  295. var cPathTranslated *C.char
  296. if pathTranslated := fc.Env["PATH_TRANSLATED"]; pathTranslated != "" {
  297. cPathTranslated = C.CString(pathTranslated)
  298. }
  299. cRequestUri := C.CString(request.URL.RequestURI())
  300. var rh cgo.Handle
  301. if fc.responseWriter == nil {
  302. mrh = C.uintptr_t(cgo.NewHandle(request))
  303. } else {
  304. rh = cgo.NewHandle(request)
  305. }
  306. ret := C.frankenphp_update_server_context(
  307. C.bool(create),
  308. C.uintptr_t(rh),
  309. mrh,
  310. cMethod,
  311. cQueryString,
  312. C.zend_long(contentLength),
  313. cPathTranslated,
  314. cRequestUri,
  315. cContentType,
  316. cAuthUser,
  317. cAuthPassword,
  318. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  319. )
  320. if ret > 0 {
  321. return RequestContextCreationError
  322. }
  323. return nil
  324. }
  325. // ServeHTTP executes a PHP script according to the given context.
  326. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error {
  327. shutdownWG.Add(1)
  328. defer shutdownWG.Done()
  329. fc, ok := FromContext(request.Context())
  330. if !ok {
  331. return InvalidRequestError
  332. }
  333. if err := populateEnv(request); err != nil {
  334. return err
  335. }
  336. fc.responseWriter = responseWriter
  337. fc.done = make(chan interface{})
  338. rc := requestChan
  339. // Detect if a worker is available to handle this request
  340. if nil == fc.responseWriter {
  341. fc.Env["FRANKENPHP_WORKER"] = "1"
  342. } else if v, ok := workersRequestChans.Load(fc.Env["SCRIPT_FILENAME"]); ok {
  343. fc.Env["FRANKENPHP_WORKER"] = "1"
  344. rc = v.(chan *http.Request)
  345. }
  346. select {
  347. case <-done:
  348. case rc <- request:
  349. <-fc.done
  350. }
  351. return nil
  352. }
  353. //export go_fetch_request
  354. func go_fetch_request() C.uintptr_t {
  355. select {
  356. case <-done:
  357. return 0
  358. case r := <-requestChan:
  359. return C.uintptr_t(cgo.NewHandle(r))
  360. }
  361. }
  362. func maybeCloseContext(fc *FrankenPHPContext) {
  363. fc.closed.Do(func() {
  364. close(fc.done)
  365. })
  366. }
  367. //export go_execute_script
  368. func go_execute_script(rh unsafe.Pointer) {
  369. handle := cgo.Handle(rh)
  370. defer handle.Delete()
  371. request := handle.Value().(*http.Request)
  372. fc, ok := FromContext(request.Context())
  373. if !ok {
  374. panic(InvalidRequestError)
  375. }
  376. defer maybeCloseContext(fc)
  377. if err := updateServerContext(request, true, 0); err != nil {
  378. panic(err)
  379. }
  380. if C.frankenphp_request_startup() < 0 {
  381. panic(RequestStartupError)
  382. }
  383. cFileName := C.CString(fc.Env["SCRIPT_FILENAME"])
  384. defer C.free(unsafe.Pointer(cFileName))
  385. if C.frankenphp_execute_script(cFileName) < 0 {
  386. panic(ScriptExecutionError)
  387. }
  388. C.frankenphp_clean_server_context()
  389. C.frankenphp_request_shutdown()
  390. }
  391. //export go_ub_write
  392. func go_ub_write(rh C.uintptr_t, cString *C.char, length C.int) (C.size_t, C.bool) {
  393. r := cgo.Handle(rh).Value().(*http.Request)
  394. fc, _ := FromContext(r.Context())
  395. var writer io.Writer
  396. if fc.responseWriter == nil {
  397. var b bytes.Buffer
  398. // log the output of the worker
  399. writer = &b
  400. } else {
  401. writer = fc.responseWriter
  402. }
  403. i, _ := writer.Write([]byte(C.GoStringN(cString, length)))
  404. if fc.responseWriter == nil {
  405. fc.Logger.Info(writer.(*bytes.Buffer).String())
  406. }
  407. return C.size_t(i), C.bool(clientHasClosed(r))
  408. }
  409. //export go_register_variables
  410. func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) {
  411. var env map[string]string
  412. r := cgo.Handle(rh).Value().(*http.Request)
  413. env = r.Context().Value(contextKey).(*FrankenPHPContext).Env
  414. le := len(env) * 2
  415. cArr := (**C.char)(C.malloc(C.size_t(le) * C.size_t(unsafe.Sizeof((*C.char)(nil)))))
  416. defer C.free(unsafe.Pointer(cArr))
  417. variables := unsafe.Slice(cArr, le)
  418. var i int
  419. for k, v := range env {
  420. variables[i] = C.CString(k)
  421. i++
  422. variables[i] = C.CString(v)
  423. i++
  424. }
  425. C.frankenphp_register_bulk_variables(cArr, C.size_t(le), trackVarsArray)
  426. for _, v := range variables {
  427. C.free(unsafe.Pointer(v))
  428. }
  429. }
  430. //export go_add_header
  431. func go_add_header(rh C.uintptr_t, cString *C.char, length C.int) {
  432. r := cgo.Handle(rh).Value().(*http.Request)
  433. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  434. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  435. if len(parts) != 2 {
  436. fc.Logger.Debug("invalid header", zap.String("header", parts[0]))
  437. return
  438. }
  439. fc.responseWriter.Header().Add(parts[0], parts[1])
  440. }
  441. //export go_write_header
  442. func go_write_header(rh C.uintptr_t, status C.int) {
  443. r := cgo.Handle(rh).Value().(*http.Request)
  444. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  445. if fc.responseWriter == nil {
  446. return
  447. }
  448. // FIXME: http: superfluous response.WriteHeader call from github.com/dunglas/frankenphp.go_write_header
  449. fc.responseWriter.WriteHeader(int(status))
  450. if status >= 100 && status < 200 {
  451. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  452. h := fc.responseWriter.Header()
  453. for k := range h {
  454. delete(h, k)
  455. }
  456. }
  457. }
  458. //export go_sapi_flush
  459. func go_sapi_flush(rh C.uintptr_t) bool {
  460. r := cgo.Handle(rh).Value().(*http.Request)
  461. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  462. if fc.responseWriter == nil {
  463. return true
  464. }
  465. flusher, ok := fc.responseWriter.(http.Flusher)
  466. if !ok {
  467. return true
  468. }
  469. if clientHasClosed(r) {
  470. return true
  471. }
  472. if r.ProtoMajor == 1 {
  473. if _, err := r.Body.Read(nil); err != nil {
  474. // Don't flush until the whole body has been read to prevent https://github.com/golang/go/issues/15527
  475. return false
  476. }
  477. }
  478. flusher.Flush()
  479. return false
  480. }
  481. //export go_read_post
  482. func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) C.size_t {
  483. r := cgo.Handle(rh).Value().(*http.Request)
  484. p := make([]byte, int(countBytes))
  485. readBytes, err := r.Body.Read(p)
  486. if err != nil && err != io.EOF {
  487. // invalid Read on closed Body may happen because of https://github.com/golang/go/issues/15527
  488. fc, _ := FromContext(r.Context())
  489. fc.Logger.Error("error while reading the request body", zap.Error(err))
  490. }
  491. if readBytes != 0 {
  492. C.memcpy(unsafe.Pointer(cBuf), unsafe.Pointer(&p[0]), C.size_t(readBytes))
  493. }
  494. return C.size_t(readBytes)
  495. }
  496. //export go_read_cookies
  497. func go_read_cookies(rh C.uintptr_t) *C.char {
  498. r := cgo.Handle(rh).Value().(*http.Request)
  499. cookies := r.Cookies()
  500. if len(cookies) == 0 {
  501. return nil
  502. }
  503. cookieString := make([]string, len(cookies))
  504. for _, cookie := range r.Cookies() {
  505. cookieString = append(cookieString, cookie.String())
  506. }
  507. cCookie := C.CString(strings.Join(cookieString, "; "))
  508. // freed in frankenphp_request_shutdown()
  509. return cCookie
  510. }
  511. //export go_log
  512. func go_log(message *C.char, level C.int) {
  513. l := getLogger()
  514. m := C.GoString(message)
  515. var le syslogLevel
  516. if level < C.int(emerg) || level > C.int(debug) {
  517. le = info
  518. } else {
  519. le = syslogLevel(level)
  520. }
  521. switch le {
  522. case emerg, alert, crit, err:
  523. l.Error(m, zap.Stringer("syslog_level", syslogLevel(level)))
  524. case warning:
  525. l.Warn(m, zap.Stringer("syslog_level", syslogLevel(level)))
  526. case debug:
  527. l.Debug(m, zap.Stringer("syslog_level", syslogLevel(level)))
  528. default:
  529. l.Info(m, zap.Stringer("syslog_level", syslogLevel(level)))
  530. }
  531. }