frankenphp.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. opt.workers[i].num = numCPU
  208. }
  209. numWorkers += opt.workers[i].num
  210. }
  211. if opt.numThreads <= 0 {
  212. if numWorkers >= numCPU {
  213. // Start at least as many threads as workers, and keep a free thread to handle requests in non-worker mode
  214. opt.numThreads = numWorkers + 1
  215. } else {
  216. opt.numThreads = numCPU
  217. }
  218. } else if opt.numThreads <= numWorkers {
  219. return NotEnoughThreads
  220. }
  221. config := Config()
  222. if config.Version.MajorVersion < 8 || config.Version.MinorVersion < 2 {
  223. return InvalidPHPVersionError
  224. }
  225. if config.ZTS {
  226. if !config.ZendMaxExecutionTimers && runtime.GOOS == "linux" {
  227. 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`)
  228. }
  229. } else {
  230. opt.numThreads = 1
  231. 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`)
  232. }
  233. shutdownWG.Add(1)
  234. requestChan = make(chan *http.Request)
  235. if C.frankenphp_init(C.int(opt.numThreads)) != 0 {
  236. return MainThreadCreationError
  237. }
  238. for _, w := range opt.workers {
  239. // TODO: start all the worker in parallell to reduce the boot time
  240. if err := startWorkers(w.fileName, w.num); err != nil {
  241. return err
  242. }
  243. }
  244. logger.Debug("FrankenPHP started")
  245. return nil
  246. }
  247. // Shutdown stops the workers and the PHP runtime.
  248. func Shutdown() {
  249. stopWorkers()
  250. close(requestChan)
  251. shutdownWG.Wait()
  252. requestChan = nil
  253. logger.Debug("FrankenPHP shut down")
  254. }
  255. //export go_shutdown
  256. func go_shutdown() {
  257. shutdownWG.Done()
  258. }
  259. func getLogger() *zap.Logger {
  260. loggerMu.RLock()
  261. defer loggerMu.RUnlock()
  262. return logger
  263. }
  264. func updateServerContext(request *http.Request, create bool, mrh C.uintptr_t) error {
  265. fc, ok := FromContext(request.Context())
  266. if !ok {
  267. return InvalidRequestError
  268. }
  269. var cAuthUser, cAuthPassword *C.char
  270. if fc.authPassword != "" {
  271. cAuthPassword = C.CString(fc.authPassword)
  272. }
  273. if authUser := fc.Env["REMOTE_USER"]; authUser != "" {
  274. cAuthUser = C.CString(authUser)
  275. }
  276. cMethod := C.CString(request.Method)
  277. cQueryString := C.CString(request.URL.RawQuery)
  278. contentLengthStr := request.Header.Get("Content-Length")
  279. contentLength := 0
  280. if contentLengthStr != "" {
  281. var err error
  282. contentLength, err = strconv.Atoi(contentLengthStr)
  283. if err != nil {
  284. return fmt.Errorf("invalid Content-Length header: %w", err)
  285. }
  286. }
  287. contentType := request.Header.Get("Content-Type")
  288. var cContentType *C.char
  289. if contentType != "" {
  290. cContentType = C.CString(contentType)
  291. }
  292. var cPathTranslated *C.char
  293. if pathTranslated := fc.Env["PATH_TRANSLATED"]; pathTranslated != "" {
  294. cPathTranslated = C.CString(pathTranslated)
  295. }
  296. cRequestUri := C.CString(request.URL.RequestURI())
  297. var rh cgo.Handle
  298. if fc.responseWriter == nil {
  299. mrh = C.uintptr_t(cgo.NewHandle(request))
  300. } else {
  301. rh = cgo.NewHandle(request)
  302. }
  303. ret := C.frankenphp_update_server_context(
  304. C.bool(create),
  305. C.uintptr_t(rh),
  306. mrh,
  307. cMethod,
  308. cQueryString,
  309. C.zend_long(contentLength),
  310. cPathTranslated,
  311. cRequestUri,
  312. cContentType,
  313. cAuthUser,
  314. cAuthPassword,
  315. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  316. )
  317. if ret > 0 {
  318. return RequestContextCreationError
  319. }
  320. return nil
  321. }
  322. // ServeHTTP executes a PHP script according to the given context.
  323. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error {
  324. shutdownWG.Add(1)
  325. defer shutdownWG.Done()
  326. fc, ok := FromContext(request.Context())
  327. if !ok {
  328. return InvalidRequestError
  329. }
  330. if err := populateEnv(request); err != nil {
  331. return err
  332. }
  333. fc.responseWriter = responseWriter
  334. fc.done = make(chan interface{})
  335. rc := requestChan
  336. // Detect if a worker is available to handle this request
  337. if nil == fc.responseWriter {
  338. fc.Env["FRANKENPHP_WORKER"] = "1"
  339. } else if v, ok := workersRequestChans.Load(fc.Env["SCRIPT_FILENAME"]); ok {
  340. fc.Env["FRANKENPHP_WORKER"] = "1"
  341. rc = v.(chan *http.Request)
  342. }
  343. if rc != nil {
  344. rc <- request
  345. <-fc.done
  346. }
  347. return nil
  348. }
  349. //export go_fetch_request
  350. func go_fetch_request() C.uintptr_t {
  351. r, ok := <-requestChan
  352. if !ok {
  353. return 0
  354. }
  355. return C.uintptr_t(cgo.NewHandle(r))
  356. }
  357. func maybeCloseContext(fc *FrankenPHPContext) {
  358. fc.closed.Do(func() {
  359. close(fc.done)
  360. })
  361. }
  362. //export go_execute_script
  363. func go_execute_script(rh unsafe.Pointer) {
  364. handle := cgo.Handle(rh)
  365. defer handle.Delete()
  366. request := handle.Value().(*http.Request)
  367. fc, ok := FromContext(request.Context())
  368. if !ok {
  369. panic(InvalidRequestError)
  370. }
  371. defer maybeCloseContext(fc)
  372. if err := updateServerContext(request, true, 0); err != nil {
  373. panic(err)
  374. }
  375. if C.frankenphp_request_startup() < 0 {
  376. panic(RequestStartupError)
  377. }
  378. cFileName := C.CString(fc.Env["SCRIPT_FILENAME"])
  379. defer C.free(unsafe.Pointer(cFileName))
  380. if C.frankenphp_execute_script(cFileName) < 0 {
  381. panic(ScriptExecutionError)
  382. }
  383. C.frankenphp_clean_server_context()
  384. C.frankenphp_request_shutdown()
  385. }
  386. //export go_ub_write
  387. func go_ub_write(rh C.uintptr_t, cString *C.char, length C.int) (C.size_t, C.bool) {
  388. r := cgo.Handle(rh).Value().(*http.Request)
  389. fc, _ := FromContext(r.Context())
  390. var writer io.Writer
  391. if fc.responseWriter == nil {
  392. var b bytes.Buffer
  393. // log the output of the worker
  394. writer = &b
  395. } else {
  396. writer = fc.responseWriter
  397. }
  398. i, _ := writer.Write([]byte(C.GoStringN(cString, length)))
  399. if fc.responseWriter == nil {
  400. fc.Logger.Info(writer.(*bytes.Buffer).String())
  401. }
  402. return C.size_t(i), C.bool(clientHasClosed(r))
  403. }
  404. //export go_register_variables
  405. func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) {
  406. var env map[string]string
  407. r := cgo.Handle(rh).Value().(*http.Request)
  408. env = r.Context().Value(contextKey).(*FrankenPHPContext).Env
  409. le := len(env) * 2
  410. cArr := (**C.char)(C.malloc(C.size_t(le) * C.size_t(unsafe.Sizeof((*C.char)(nil)))))
  411. defer C.free(unsafe.Pointer(cArr))
  412. variables := unsafe.Slice(cArr, le)
  413. var i int
  414. for k, v := range env {
  415. variables[i] = C.CString(k)
  416. i++
  417. variables[i] = C.CString(v)
  418. i++
  419. }
  420. C.frankenphp_register_bulk_variables(cArr, C.size_t(le), trackVarsArray)
  421. for _, v := range variables {
  422. C.free(unsafe.Pointer(v))
  423. }
  424. }
  425. //export go_add_header
  426. func go_add_header(rh C.uintptr_t, cString *C.char, length C.int) {
  427. r := cgo.Handle(rh).Value().(*http.Request)
  428. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  429. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  430. if len(parts) != 2 {
  431. fc.Logger.Debug("invalid header", zap.String("header", parts[0]))
  432. return
  433. }
  434. fc.responseWriter.Header().Add(parts[0], parts[1])
  435. }
  436. //export go_write_header
  437. func go_write_header(rh C.uintptr_t, status C.int) {
  438. r := cgo.Handle(rh).Value().(*http.Request)
  439. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  440. if fc.responseWriter == nil {
  441. return
  442. }
  443. // FIXME: http: superfluous response.WriteHeader call from github.com/dunglas/frankenphp.go_write_header
  444. fc.responseWriter.WriteHeader(int(status))
  445. if status >= 100 && status < 200 {
  446. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  447. h := fc.responseWriter.Header()
  448. for k := range h {
  449. delete(h, k)
  450. }
  451. }
  452. }
  453. //export go_sapi_flush
  454. func go_sapi_flush(rh C.uintptr_t) bool {
  455. r := cgo.Handle(rh).Value().(*http.Request)
  456. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  457. if fc.responseWriter == nil {
  458. return true
  459. }
  460. flusher, ok := fc.responseWriter.(http.Flusher)
  461. if !ok {
  462. return true
  463. }
  464. if clientHasClosed(r) {
  465. return true
  466. }
  467. if r.ProtoMajor == 1 {
  468. if _, err := r.Body.Read(nil); err != nil {
  469. // Don't flush until the whole body has been read to prevent https://github.com/golang/go/issues/15527
  470. return false
  471. }
  472. }
  473. flusher.Flush()
  474. return false
  475. }
  476. //export go_read_post
  477. func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) C.size_t {
  478. r := cgo.Handle(rh).Value().(*http.Request)
  479. p := make([]byte, int(countBytes))
  480. readBytes, err := r.Body.Read(p)
  481. if err != nil && err != io.EOF {
  482. // invalid Read on closed Body may happen because of https://github.com/golang/go/issues/15527
  483. fc, _ := FromContext(r.Context())
  484. fc.Logger.Error("error while reading the request body", zap.Error(err))
  485. }
  486. if readBytes != 0 {
  487. C.memcpy(unsafe.Pointer(cBuf), unsafe.Pointer(&p[0]), C.size_t(readBytes))
  488. }
  489. return C.size_t(readBytes)
  490. }
  491. //export go_read_cookies
  492. func go_read_cookies(rh C.uintptr_t) *C.char {
  493. r := cgo.Handle(rh).Value().(*http.Request)
  494. cookies := r.Cookies()
  495. if len(cookies) == 0 {
  496. return nil
  497. }
  498. cookieString := make([]string, len(cookies))
  499. for _, cookie := range r.Cookies() {
  500. cookieString = append(cookieString, cookie.String())
  501. }
  502. cCookie := C.CString(strings.Join(cookieString, "; "))
  503. // freed in frankenphp_request_shutdown()
  504. return cCookie
  505. }
  506. //export go_log
  507. func go_log(message *C.char, level C.int) {
  508. l := getLogger()
  509. m := C.GoString(message)
  510. var le syslogLevel
  511. if level < C.int(emerg) || level > C.int(debug) {
  512. le = info
  513. } else {
  514. le = syslogLevel(level)
  515. }
  516. switch le {
  517. case emerg, alert, crit, err:
  518. l.Error(m, zap.Stringer("syslog_level", syslogLevel(level)))
  519. case warning:
  520. l.Warn(m, zap.Stringer("syslog_level", syslogLevel(level)))
  521. case debug:
  522. l.Debug(m, zap.Stringer("syslog_level", syslogLevel(level)))
  523. default:
  524. l.Info(m, zap.Stringer("syslog_level", syslogLevel(level)))
  525. }
  526. }