frankenphp.go 16 KB

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