frankenphp.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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 --depth=1 git@github.com:Pithikos/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. }
  117. func clientHasClosed(r *http.Request) bool {
  118. select {
  119. case <-r.Context().Done():
  120. return true
  121. default:
  122. return false
  123. }
  124. }
  125. // NewRequestWithContext creates a new FrankenPHP request context.
  126. func NewRequestWithContext(r *http.Request, documentRoot string, l *zap.Logger) *http.Request {
  127. if l == nil {
  128. l = getLogger()
  129. }
  130. ctx := context.WithValue(r.Context(), contextKey, &FrankenPHPContext{
  131. DocumentRoot: documentRoot,
  132. SplitPath: []string{".php"},
  133. Env: make(map[string]string),
  134. Logger: l,
  135. })
  136. return r.WithContext(ctx)
  137. }
  138. // FromContext extracts the FrankenPHPContext from a context.
  139. func FromContext(ctx context.Context) (fctx *FrankenPHPContext, ok bool) {
  140. fctx, ok = ctx.Value(contextKey).(*FrankenPHPContext)
  141. return
  142. }
  143. type PHPVersion struct {
  144. MajorVersion int
  145. MinorVersion int
  146. ReleaseVersion int
  147. ExtraVersion string
  148. Version string
  149. VersionID int
  150. }
  151. // Version returns infos about the PHP version.
  152. func Version() PHPVersion {
  153. cVersion := C.frankenphp_version()
  154. return PHPVersion{
  155. int(cVersion.major_version),
  156. int(cVersion.minor_version),
  157. int(cVersion.release_version),
  158. C.GoString(cVersion.extra_version),
  159. C.GoString(cVersion.version),
  160. int(cVersion.version_id),
  161. }
  162. }
  163. // Init starts the PHP runtime and the configured workers.
  164. func Init(options ...Option) error {
  165. if requestChan != nil {
  166. return AlreaydStartedError
  167. }
  168. opt := &opt{}
  169. for _, o := range options {
  170. if err := o(opt); err != nil {
  171. return err
  172. }
  173. }
  174. if opt.logger == nil {
  175. l, err := zap.NewDevelopment()
  176. if err != nil {
  177. return err
  178. }
  179. loggerMu.Lock()
  180. logger = l
  181. loggerMu.Unlock()
  182. } else {
  183. loggerMu.Lock()
  184. logger = opt.logger
  185. loggerMu.Unlock()
  186. }
  187. numCPU := runtime.NumCPU()
  188. var numWorkers int
  189. for i, w := range opt.workers {
  190. if w.num <= 0 {
  191. opt.workers[i].num = numCPU
  192. }
  193. numWorkers += opt.workers[i].num
  194. }
  195. if opt.numThreads <= 0 {
  196. if numWorkers >= numCPU {
  197. // Start at least as many threads as workers, and keep a free thread to handle requests in non-worker mode
  198. opt.numThreads = numWorkers + 1
  199. } else {
  200. opt.numThreads = numCPU
  201. }
  202. } else if opt.numThreads <= numWorkers {
  203. return NotEnoughThreads
  204. }
  205. switch C.frankenphp_check_version() {
  206. case -1:
  207. if opt.numThreads != 1 {
  208. opt.numThreads = 1
  209. 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`)
  210. }
  211. case -2:
  212. return InvalidPHPVersionError
  213. case -3:
  214. return ZendSignalsError
  215. }
  216. shutdownWG.Add(1)
  217. requestChan = make(chan *http.Request)
  218. if C.frankenphp_init(C.int(opt.numThreads)) != 0 {
  219. return MainThreadCreationError
  220. }
  221. for _, w := range opt.workers {
  222. // TODO: start all the worker in parallell to reduce the boot time
  223. if err := startWorkers(w.fileName, w.num); err != nil {
  224. return err
  225. }
  226. }
  227. logger.Debug("FrankenPHP started")
  228. return nil
  229. }
  230. // Shutdown stops the workers and the PHP runtime.
  231. func Shutdown() {
  232. stopWorkers()
  233. close(requestChan)
  234. shutdownWG.Wait()
  235. requestChan = nil
  236. logger.Debug("FrankenPHP shut down")
  237. }
  238. //export go_shutdown
  239. func go_shutdown() {
  240. shutdownWG.Done()
  241. }
  242. func getLogger() *zap.Logger {
  243. loggerMu.RLock()
  244. defer loggerMu.RUnlock()
  245. return logger
  246. }
  247. func updateServerContext(request *http.Request, create bool) error {
  248. fc, ok := FromContext(request.Context())
  249. if !ok {
  250. return InvalidRequestError
  251. }
  252. var cAuthUser, cAuthPassword *C.char
  253. if fc.authPassword != "" {
  254. cAuthPassword = C.CString(fc.authPassword)
  255. }
  256. if authUser := fc.Env["REMOTE_USER"]; authUser != "" {
  257. cAuthUser = C.CString(authUser)
  258. }
  259. cMethod := C.CString(request.Method)
  260. cQueryString := C.CString(request.URL.RawQuery)
  261. contentLengthStr := request.Header.Get("Content-Length")
  262. contentLength := 0
  263. if contentLengthStr != "" {
  264. var err error
  265. contentLength, err = strconv.Atoi(contentLengthStr)
  266. if err != nil {
  267. return fmt.Errorf("invalid Content-Length header: %w", err)
  268. }
  269. }
  270. contentType := request.Header.Get("Content-Type")
  271. var cContentType *C.char
  272. if contentType != "" {
  273. cContentType = C.CString(contentType)
  274. }
  275. var cPathTranslated *C.char
  276. if pathTranslated := fc.Env["PATH_TRANSLATED"]; pathTranslated != "" {
  277. cPathTranslated = C.CString(pathTranslated)
  278. }
  279. cRequestUri := C.CString(request.URL.RequestURI())
  280. var rh, mwrh cgo.Handle
  281. if fc.responseWriter == nil {
  282. mwrh = cgo.NewHandle(request)
  283. } else {
  284. rh = cgo.NewHandle(request)
  285. }
  286. ret := C.frankenphp_update_server_context(
  287. C.bool(create),
  288. C.uintptr_t(rh),
  289. C.uintptr_t(mwrh),
  290. cMethod,
  291. cQueryString,
  292. C.zend_long(contentLength),
  293. cPathTranslated,
  294. cRequestUri,
  295. cContentType,
  296. cAuthUser,
  297. cAuthPassword,
  298. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  299. )
  300. if ret > 0 {
  301. return RequestContextCreationError
  302. }
  303. return nil
  304. }
  305. // ServeHTTP executes a PHP script according to the given context.
  306. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error {
  307. shutdownWG.Add(1)
  308. defer shutdownWG.Done()
  309. fc, ok := FromContext(request.Context())
  310. if !ok {
  311. return InvalidRequestError
  312. }
  313. if err := populateEnv(request); err != nil {
  314. return err
  315. }
  316. fc.responseWriter = responseWriter
  317. fc.done = make(chan interface{})
  318. rc := requestChan
  319. // Detect if a worker is available to handle this request
  320. if nil == fc.responseWriter {
  321. fc.Env["FRANKENPHP_WORKER"] = "1"
  322. } else if v, ok := workersRequestChans.Load(fc.Env["SCRIPT_FILENAME"]); ok {
  323. fc.Env["FRANKENPHP_WORKER"] = "1"
  324. rc = v.(chan *http.Request)
  325. }
  326. if rc != nil {
  327. rc <- request
  328. <-fc.done
  329. }
  330. return nil
  331. }
  332. //export go_fetch_request
  333. func go_fetch_request() C.uintptr_t {
  334. r, ok := <-requestChan
  335. if !ok {
  336. return 0
  337. }
  338. return C.uintptr_t(cgo.NewHandle(r))
  339. }
  340. func maybeCloseContext(fc *FrankenPHPContext) {
  341. fc.closed.Do(func() {
  342. close(fc.done)
  343. })
  344. }
  345. //export go_execute_script
  346. func go_execute_script(rh unsafe.Pointer) {
  347. handle := cgo.Handle(rh)
  348. defer handle.Delete()
  349. request := handle.Value().(*http.Request)
  350. fc, ok := FromContext(request.Context())
  351. if !ok {
  352. panic(InvalidRequestError)
  353. }
  354. defer maybeCloseContext(fc)
  355. if err := updateServerContext(request, true); err != nil {
  356. panic(err)
  357. }
  358. if C.frankenphp_request_startup() < 0 {
  359. panic(RequestStartupError)
  360. }
  361. cFileName := C.CString(fc.Env["SCRIPT_FILENAME"])
  362. defer C.free(unsafe.Pointer(cFileName))
  363. if C.frankenphp_execute_script(cFileName) < 0 {
  364. panic(ScriptExecutionError)
  365. }
  366. C.frankenphp_clean_server_context()
  367. C.frankenphp_request_shutdown()
  368. }
  369. //export go_ub_write
  370. func go_ub_write(rh C.uintptr_t, cString *C.char, length C.int) (C.size_t, C.bool) {
  371. r := cgo.Handle(rh).Value().(*http.Request)
  372. fc, _ := FromContext(r.Context())
  373. var writer io.Writer
  374. if fc.responseWriter == nil {
  375. var b bytes.Buffer
  376. // log the output of the worker
  377. writer = &b
  378. } else {
  379. writer = fc.responseWriter
  380. }
  381. i, _ := writer.Write([]byte(C.GoStringN(cString, length)))
  382. if fc.responseWriter == nil {
  383. fc.Logger.Info(writer.(*bytes.Buffer).String())
  384. }
  385. return C.size_t(i), C.bool(clientHasClosed(r))
  386. }
  387. //export go_register_variables
  388. func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) {
  389. var env map[string]string
  390. r := cgo.Handle(rh).Value().(*http.Request)
  391. env = r.Context().Value(contextKey).(*FrankenPHPContext).Env
  392. le := len(env) * 2
  393. cArr := (**C.char)(C.malloc(C.size_t(le) * C.size_t(unsafe.Sizeof((*C.char)(nil)))))
  394. defer C.free(unsafe.Pointer(cArr))
  395. variables := unsafe.Slice(cArr, le)
  396. var i int
  397. for k, v := range env {
  398. variables[i] = C.CString(k)
  399. i++
  400. variables[i] = C.CString(v)
  401. i++
  402. }
  403. C.frankenphp_register_bulk_variables(cArr, C.size_t(le), trackVarsArray)
  404. for _, v := range variables {
  405. C.free(unsafe.Pointer(v))
  406. }
  407. }
  408. //export go_add_header
  409. func go_add_header(rh C.uintptr_t, cString *C.char, length C.int) {
  410. r := cgo.Handle(rh).Value().(*http.Request)
  411. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  412. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  413. if len(parts) != 2 {
  414. fc.Logger.Debug("invalid header", zap.String("header", parts[0]))
  415. return
  416. }
  417. fc.responseWriter.Header().Add(parts[0], parts[1])
  418. }
  419. //export go_write_header
  420. func go_write_header(rh C.uintptr_t, status C.int) {
  421. r := cgo.Handle(rh).Value().(*http.Request)
  422. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  423. if fc.responseWriter == nil {
  424. return
  425. }
  426. fc.responseWriter.WriteHeader(int(status))
  427. if status >= 100 && status < 200 {
  428. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  429. h := fc.responseWriter.Header()
  430. for k := range h {
  431. delete(h, k)
  432. }
  433. }
  434. }
  435. //export go_sapi_flush
  436. func go_sapi_flush(rh C.uintptr_t) bool {
  437. r := cgo.Handle(rh).Value().(*http.Request)
  438. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  439. if fc.responseWriter == nil {
  440. return true
  441. }
  442. flusher, ok := fc.responseWriter.(http.Flusher)
  443. if !ok {
  444. return true
  445. }
  446. if clientHasClosed(r) {
  447. return true
  448. }
  449. if r.ProtoMajor == 1 {
  450. if _, err := r.Body.Read(nil); err != nil {
  451. // Don't flush until the whole body has been read to prevent https://github.com/golang/go/issues/15527
  452. return false
  453. }
  454. }
  455. flusher.Flush()
  456. return false
  457. }
  458. //export go_read_post
  459. func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) C.size_t {
  460. r := cgo.Handle(rh).Value().(*http.Request)
  461. p := make([]byte, int(countBytes))
  462. readBytes, err := r.Body.Read(p)
  463. if err != nil && err != io.EOF {
  464. // invalid Read on closed Body may happen because of https://github.com/golang/go/issues/15527
  465. fc, _ := FromContext(r.Context())
  466. fc.Logger.Error("error while reading the request body", zap.Error(err))
  467. }
  468. if readBytes != 0 {
  469. C.memcpy(unsafe.Pointer(cBuf), unsafe.Pointer(&p[0]), C.size_t(readBytes))
  470. }
  471. return C.size_t(readBytes)
  472. }
  473. //export go_read_cookies
  474. func go_read_cookies(rh C.uintptr_t) *C.char {
  475. r := cgo.Handle(rh).Value().(*http.Request)
  476. cookies := r.Cookies()
  477. if len(cookies) == 0 {
  478. return nil
  479. }
  480. cookieString := make([]string, len(cookies))
  481. for _, cookie := range r.Cookies() {
  482. cookieString = append(cookieString, cookie.String())
  483. }
  484. cCookie := C.CString(strings.Join(cookieString, "; "))
  485. // freed in frankenphp_request_shutdown()
  486. return cCookie
  487. }
  488. //export go_log
  489. func go_log(message *C.char, level C.int) {
  490. l := getLogger()
  491. m := C.GoString(message)
  492. var le syslogLevel
  493. if level < C.int(emerg) || level > C.int(debug) {
  494. le = info
  495. } else {
  496. le = syslogLevel(level)
  497. }
  498. switch le {
  499. case emerg, alert, crit, err:
  500. l.Error(m, zap.Stringer("syslog_level", syslogLevel(level)))
  501. case warning:
  502. l.Warn(m, zap.Stringer("syslog_level", syslogLevel(level)))
  503. case debug:
  504. l.Debug(m, zap.Stringer("syslog_level", syslogLevel(level)))
  505. default:
  506. l.Info(m, zap.Stringer("syslog_level", syslogLevel(level)))
  507. }
  508. }