frankenphp.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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. // Use PHP includes corresponding to your PHP installation by running:
  8. //
  9. // export CGO_CFLAGS=$(php-config --includes)
  10. // export CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)"
  11. //
  12. // We also set these flags for hardening: https://github.com/docker-library/php/blob/master/8.2/bookworm/zts/Dockerfile#L57-L59
  13. // #cgo darwin pkg-config: libxml-2.0
  14. // #cgo CFLAGS: -Wall -Werror
  15. // #cgo CFLAGS: -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib
  16. // #cgo linux CFLAGS: -D_GNU_SOURCE
  17. // #cgo darwin LDFLAGS: -L/opt/homebrew/opt/libiconv/lib -liconv
  18. // #cgo linux LDFLAGS: -lresolv
  19. // #cgo LDFLAGS: -L/usr/local/lib -L/usr/lib -lphp -ldl -lm -lutil
  20. // #include <stdlib.h>
  21. // #include <stdint.h>
  22. // #include <php_variables.h>
  23. // #include <zend_llist.h>
  24. // #include <SAPI.h>
  25. // #include "frankenphp.h"
  26. import "C"
  27. import (
  28. "bytes"
  29. "context"
  30. "errors"
  31. "fmt"
  32. "io"
  33. "net/http"
  34. "os"
  35. "runtime"
  36. "runtime/cgo"
  37. "strconv"
  38. "strings"
  39. "sync"
  40. "time"
  41. "unsafe"
  42. "github.com/maypok86/otter"
  43. "go.uber.org/zap"
  44. "go.uber.org/zap/zapcore"
  45. // debug on Linux
  46. //_ "github.com/ianlancetaylor/cgosymbolizer"
  47. )
  48. type contextKeyStruct struct{}
  49. type handleKeyStruct struct{}
  50. var contextKey = contextKeyStruct{}
  51. var handleKey = handleKeyStruct{}
  52. var (
  53. InvalidRequestError = errors.New("not a FrankenPHP request")
  54. AlreaydStartedError = errors.New("FrankenPHP is already started")
  55. InvalidPHPVersionError = errors.New("FrankenPHP is only compatible with PHP 8.2+")
  56. ZendSignalsError = errors.New("Zend Signals are enabled, recompile PHP with --disable-zend-signals")
  57. NotEnoughThreads = errors.New("the number of threads must be superior to the number of workers")
  58. MainThreadCreationError = errors.New("error creating the main thread")
  59. RequestContextCreationError = errors.New("error during request context creation")
  60. RequestStartupError = errors.New("error during PHP request startup")
  61. ScriptExecutionError = errors.New("error during PHP script execution")
  62. requestChan chan *http.Request
  63. done chan struct{}
  64. shutdownWG sync.WaitGroup
  65. loggerMu sync.RWMutex
  66. logger *zap.Logger
  67. metrics Metrics = nullMetrics{}
  68. )
  69. type syslogLevel int
  70. const (
  71. emerg syslogLevel = iota // system is unusable
  72. alert // action must be taken immediately
  73. crit // critical conditions
  74. err // error conditions
  75. warning // warning conditions
  76. notice // normal but significant condition
  77. info // informational
  78. debug // debug-level messages
  79. )
  80. func (l syslogLevel) String() string {
  81. switch l {
  82. case emerg:
  83. return "emerg"
  84. case alert:
  85. return "alert"
  86. case crit:
  87. return "crit"
  88. case err:
  89. return "err"
  90. case warning:
  91. return "warning"
  92. case notice:
  93. return "notice"
  94. case debug:
  95. return "debug"
  96. default:
  97. return "info"
  98. }
  99. }
  100. // FrankenPHPContext provides contextual information about the Request to handle.
  101. type FrankenPHPContext struct {
  102. documentRoot string
  103. splitPath []string
  104. env PreparedEnv
  105. logger *zap.Logger
  106. docURI string
  107. pathInfo string
  108. scriptName string
  109. scriptFilename string
  110. // Whether the request is already closed by us
  111. closed sync.Once
  112. responseWriter http.ResponseWriter
  113. exitStatus C.int
  114. done chan interface{}
  115. currentWorkerRequest cgo.Handle
  116. startedAt time.Time
  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, opts ...RequestOption) (*http.Request, error) {
  128. fc := &FrankenPHPContext{
  129. done: make(chan interface{}),
  130. }
  131. for _, o := range opts {
  132. if err := o(fc); err != nil {
  133. return nil, err
  134. }
  135. }
  136. if fc.documentRoot == "" {
  137. if EmbeddedAppPath != "" {
  138. fc.documentRoot = EmbeddedAppPath
  139. } else {
  140. var err error
  141. if fc.documentRoot, err = os.Getwd(); err != nil {
  142. return nil, err
  143. }
  144. }
  145. }
  146. if fc.splitPath == nil {
  147. fc.splitPath = []string{".php"}
  148. }
  149. if fc.env == nil {
  150. fc.env = make(map[string]string)
  151. }
  152. if fc.logger == nil {
  153. fc.logger = getLogger()
  154. }
  155. if splitPos := splitPos(fc, r.URL.Path); splitPos > -1 {
  156. fc.docURI = r.URL.Path[:splitPos]
  157. fc.pathInfo = r.URL.Path[splitPos:]
  158. // Strip PATH_INFO from SCRIPT_NAME
  159. fc.scriptName = strings.TrimSuffix(r.URL.Path, fc.pathInfo)
  160. // Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875
  161. // Info: https://tools.ietf.org/html/rfc3875#section-4.1.13
  162. if fc.scriptName != "" && !strings.HasPrefix(fc.scriptName, "/") {
  163. fc.scriptName = "/" + fc.scriptName
  164. }
  165. }
  166. // SCRIPT_FILENAME is the absolute path of SCRIPT_NAME
  167. fc.scriptFilename = sanitizedPathJoin(fc.documentRoot, fc.scriptName)
  168. c := context.WithValue(r.Context(), contextKey, fc)
  169. c = context.WithValue(c, handleKey, Handles())
  170. return r.WithContext(c), nil
  171. }
  172. // FromContext extracts the FrankenPHPContext from a context.
  173. func FromContext(ctx context.Context) (fctx *FrankenPHPContext, ok bool) {
  174. fctx, ok = ctx.Value(contextKey).(*FrankenPHPContext)
  175. return
  176. }
  177. type PHPVersion struct {
  178. MajorVersion int
  179. MinorVersion int
  180. ReleaseVersion int
  181. ExtraVersion string
  182. Version string
  183. VersionID int
  184. }
  185. type PHPConfig struct {
  186. Version PHPVersion
  187. ZTS bool
  188. ZendSignals bool
  189. ZendMaxExecutionTimers bool
  190. }
  191. // Version returns infos about the PHP version.
  192. func Version() PHPVersion {
  193. cVersion := C.frankenphp_get_version()
  194. return PHPVersion{
  195. int(cVersion.major_version),
  196. int(cVersion.minor_version),
  197. int(cVersion.release_version),
  198. C.GoString(cVersion.extra_version),
  199. C.GoString(cVersion.version),
  200. int(cVersion.version_id),
  201. }
  202. }
  203. func Config() PHPConfig {
  204. cConfig := C.frankenphp_get_config()
  205. return PHPConfig{
  206. Version: Version(),
  207. ZTS: bool(cConfig.zts),
  208. ZendSignals: bool(cConfig.zend_signals),
  209. ZendMaxExecutionTimers: bool(cConfig.zend_max_execution_timers),
  210. }
  211. }
  212. // MaxThreads is the maximum number of threads that can be started, it is set by frankenphp.Init and should be considered read-only.
  213. var MaxThreads int
  214. func calculateMaxThreads(opt *opt) error {
  215. maxProcs := runtime.GOMAXPROCS(0) * 2
  216. var numWorkers int
  217. for i, w := range opt.workers {
  218. if w.num <= 0 {
  219. // https://github.com/dunglas/frankenphp/issues/126
  220. opt.workers[i].num = maxProcs
  221. }
  222. metrics.TotalWorkers(w.fileName, w.num)
  223. numWorkers += opt.workers[i].num
  224. }
  225. if opt.numThreads <= 0 {
  226. if numWorkers >= maxProcs {
  227. // Start at least as many threads as workers, and keep a free thread to handle requests in non-worker mode
  228. opt.numThreads = numWorkers + 1
  229. } else {
  230. opt.numThreads = maxProcs
  231. }
  232. } else if opt.numThreads <= numWorkers {
  233. return NotEnoughThreads
  234. }
  235. metrics.TotalThreads(opt.numThreads)
  236. MaxThreads = opt.numThreads
  237. return nil
  238. }
  239. // Init starts the PHP runtime and the configured workers.
  240. func Init(options ...Option) error {
  241. if requestChan != nil {
  242. return AlreaydStartedError
  243. }
  244. opt := &opt{}
  245. for _, o := range options {
  246. if err := o(opt); err != nil {
  247. return err
  248. }
  249. }
  250. if opt.logger == nil {
  251. l, err := zap.NewDevelopment()
  252. if err != nil {
  253. return err
  254. }
  255. loggerMu.Lock()
  256. logger = l
  257. loggerMu.Unlock()
  258. } else {
  259. loggerMu.Lock()
  260. logger = opt.logger
  261. loggerMu.Unlock()
  262. }
  263. if opt.metrics != nil {
  264. metrics = opt.metrics
  265. }
  266. err := calculateMaxThreads(opt)
  267. if err != nil {
  268. return err
  269. }
  270. config := Config()
  271. if config.Version.MajorVersion < 8 || (config.Version.MajorVersion == 8 && config.Version.MinorVersion < 2) {
  272. return InvalidPHPVersionError
  273. }
  274. if config.ZTS {
  275. if !config.ZendMaxExecutionTimers && runtime.GOOS == "linux" {
  276. logger.Warn(`Zend Max Execution Timers are not enabled, timeouts (e.g. "max_execution_time") are disabled, recompile PHP with the "--enable-zend-max-execution-timers" configuration option to fix this issue`)
  277. }
  278. } else {
  279. opt.numThreads = 1
  280. 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`)
  281. }
  282. shutdownWG.Add(1)
  283. done = make(chan struct{})
  284. requestChan = make(chan *http.Request)
  285. if C.frankenphp_init(C.int(opt.numThreads)) != 0 {
  286. return MainThreadCreationError
  287. }
  288. if err := initWorkers(opt.workers); err != nil {
  289. return err
  290. }
  291. if c := logger.Check(zapcore.InfoLevel, "FrankenPHP started 🐘"); c != nil {
  292. c.Write(zap.String("php_version", Version().Version), zap.Int("num_threads", opt.numThreads))
  293. }
  294. if EmbeddedAppPath != "" {
  295. if c := logger.Check(zapcore.InfoLevel, "embedded PHP app 📦"); c != nil {
  296. c.Write(zap.String("path", EmbeddedAppPath))
  297. }
  298. }
  299. return nil
  300. }
  301. // Shutdown stops the workers and the PHP runtime.
  302. func Shutdown() {
  303. stopWorkers()
  304. close(done)
  305. shutdownWG.Wait()
  306. metrics.Shutdown()
  307. requestChan = nil
  308. // Always reset the WaitGroup to ensure we're in a clean state
  309. workersReadyWG = sync.WaitGroup{}
  310. // Remove the installed app
  311. if EmbeddedAppPath != "" {
  312. os.RemoveAll(EmbeddedAppPath)
  313. }
  314. logger.Debug("FrankenPHP shut down")
  315. }
  316. //export go_shutdown
  317. func go_shutdown() {
  318. shutdownWG.Done()
  319. }
  320. func getLogger() *zap.Logger {
  321. loggerMu.RLock()
  322. defer loggerMu.RUnlock()
  323. return logger
  324. }
  325. func updateServerContext(request *http.Request, create bool, mrh C.uintptr_t) error {
  326. fc, ok := FromContext(request.Context())
  327. if !ok {
  328. return InvalidRequestError
  329. }
  330. authUser, authPassword, ok := request.BasicAuth()
  331. var cAuthUser, cAuthPassword *C.char
  332. if ok && authPassword != "" {
  333. cAuthPassword = C.CString(authPassword)
  334. }
  335. if ok && authUser != "" {
  336. cAuthUser = C.CString(authUser)
  337. }
  338. cMethod := C.CString(request.Method)
  339. cQueryString := C.CString(request.URL.RawQuery)
  340. contentLengthStr := request.Header.Get("Content-Length")
  341. contentLength := 0
  342. if contentLengthStr != "" {
  343. var err error
  344. contentLength, err = strconv.Atoi(contentLengthStr)
  345. if err != nil {
  346. return fmt.Errorf("invalid Content-Length header: %w", err)
  347. }
  348. }
  349. contentType := request.Header.Get("Content-Type")
  350. var cContentType *C.char
  351. if contentType != "" {
  352. cContentType = C.CString(contentType)
  353. }
  354. // compliance with the CGI specification requires that
  355. // PATH_TRANSLATED should only exist if PATH_INFO is defined.
  356. // Info: https://www.ietf.org/rfc/rfc3875 Page 14
  357. var cPathTranslated *C.char
  358. if fc.pathInfo != "" {
  359. cPathTranslated = C.CString(sanitizedPathJoin(fc.documentRoot, fc.pathInfo)) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
  360. }
  361. cRequestUri := C.CString(request.URL.RequestURI())
  362. var rh cgo.Handle
  363. if fc.responseWriter == nil {
  364. h := cgo.NewHandle(request)
  365. request.Context().Value(handleKey).(*handleList).AddHandle(h)
  366. mrh = C.uintptr_t(h)
  367. } else {
  368. rh = cgo.NewHandle(request)
  369. request.Context().Value(handleKey).(*handleList).AddHandle(rh)
  370. }
  371. ret := C.frankenphp_update_server_context(
  372. C.bool(create),
  373. C.uintptr_t(rh),
  374. mrh,
  375. cMethod,
  376. cQueryString,
  377. C.zend_long(contentLength),
  378. cPathTranslated,
  379. cRequestUri,
  380. cContentType,
  381. cAuthUser,
  382. cAuthPassword,
  383. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  384. )
  385. if ret > 0 {
  386. return RequestContextCreationError
  387. }
  388. return nil
  389. }
  390. // ServeHTTP executes a PHP script according to the given context.
  391. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error {
  392. shutdownWG.Add(1)
  393. defer shutdownWG.Done()
  394. fc, ok := FromContext(request.Context())
  395. if !ok {
  396. return InvalidRequestError
  397. }
  398. fc.responseWriter = responseWriter
  399. fc.startedAt = time.Now()
  400. isWorker := nil == fc.responseWriter
  401. isWorkerRequest := false
  402. rc := requestChan
  403. // Detect if a worker is available to handle this request
  404. if !isWorker {
  405. if v, ok := workersRequestChans.Load(fc.scriptFilename); ok {
  406. isWorkerRequest = true
  407. metrics.StartWorkerRequest(fc.scriptFilename)
  408. rc = v.(chan *http.Request)
  409. } else {
  410. metrics.StartRequest()
  411. }
  412. }
  413. select {
  414. case <-done:
  415. case rc <- request:
  416. <-fc.done
  417. }
  418. if !isWorker {
  419. if isWorkerRequest {
  420. metrics.StopWorkerRequest(fc.scriptFilename, time.Since(fc.startedAt))
  421. } else {
  422. metrics.StopRequest()
  423. }
  424. }
  425. return nil
  426. }
  427. //export go_handle_request
  428. func go_handle_request() bool {
  429. select {
  430. case <-done:
  431. return false
  432. case r := <-requestChan:
  433. h := cgo.NewHandle(r)
  434. r.Context().Value(handleKey).(*handleList).AddHandle(h)
  435. fc, ok := FromContext(r.Context())
  436. if !ok {
  437. panic(InvalidRequestError)
  438. }
  439. defer func() {
  440. maybeCloseContext(fc)
  441. r.Context().Value(handleKey).(*handleList).FreeAll()
  442. }()
  443. if err := updateServerContext(r, true, 0); err != nil {
  444. panic(err)
  445. }
  446. // scriptFilename is freed in frankenphp_execute_script()
  447. fc.exitStatus = C.frankenphp_execute_script(C.CString(fc.scriptFilename))
  448. if fc.exitStatus < 0 {
  449. panic(ScriptExecutionError)
  450. }
  451. return true
  452. }
  453. }
  454. func maybeCloseContext(fc *FrankenPHPContext) {
  455. fc.closed.Do(func() {
  456. close(fc.done)
  457. })
  458. }
  459. //export go_ub_write
  460. func go_ub_write(rh C.uintptr_t, cBuf *C.char, length C.int) (C.size_t, C.bool) {
  461. r := cgo.Handle(rh).Value().(*http.Request)
  462. fc, _ := FromContext(r.Context())
  463. var writer io.Writer
  464. if fc.responseWriter == nil {
  465. var b bytes.Buffer
  466. // log the output of the worker
  467. writer = &b
  468. } else {
  469. writer = fc.responseWriter
  470. }
  471. i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length))
  472. if e != nil {
  473. if c := fc.logger.Check(zapcore.ErrorLevel, "write error"); c != nil {
  474. c.Write(zap.Error(e))
  475. }
  476. }
  477. if fc.responseWriter == nil {
  478. fc.logger.Info(writer.(*bytes.Buffer).String())
  479. }
  480. return C.size_t(i), C.bool(clientHasClosed(r))
  481. }
  482. // There are around 60 common request headers according to https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
  483. // Give some space for custom headers
  484. var headerKeyCache = func() otter.Cache[string, string] {
  485. c, err := otter.MustBuilder[string, string](256).Build()
  486. if err != nil {
  487. panic(err)
  488. }
  489. return c
  490. }()
  491. //export go_register_variables
  492. func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) {
  493. r := cgo.Handle(rh).Value().(*http.Request)
  494. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  495. p := &runtime.Pinner{}
  496. dynamicVariables := make([]C.php_variable, len(fc.env)+len(r.Header))
  497. var l int
  498. // Add all HTTP headers to env variables
  499. for field, val := range r.Header {
  500. k, ok := headerKeyCache.Get(field)
  501. if !ok {
  502. k = "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(field)) + "\x00"
  503. headerKeyCache.SetIfAbsent(field, k)
  504. }
  505. if _, ok := fc.env[k]; ok {
  506. continue
  507. }
  508. v := strings.Join(val, ", ")
  509. kData := unsafe.StringData(k)
  510. vData := unsafe.StringData(v)
  511. p.Pin(kData)
  512. p.Pin(vData)
  513. dynamicVariables[l]._var = (*C.char)(unsafe.Pointer(kData))
  514. dynamicVariables[l].data_len = C.size_t(len(v))
  515. dynamicVariables[l].data = (*C.char)(unsafe.Pointer(vData))
  516. l++
  517. }
  518. for k, v := range fc.env {
  519. if _, ok := knownServerKeys[k]; ok {
  520. continue
  521. }
  522. kData := unsafe.StringData(k)
  523. vData := unsafe.Pointer(unsafe.StringData(v))
  524. p.Pin(kData)
  525. p.Pin(vData)
  526. dynamicVariables[l]._var = (*C.char)(unsafe.Pointer(kData))
  527. dynamicVariables[l].data_len = C.size_t(len(v))
  528. dynamicVariables[l].data = (*C.char)(unsafe.Pointer(vData))
  529. l++
  530. }
  531. knownVariables := computeKnownVariables(r, p)
  532. dvsd := unsafe.SliceData(dynamicVariables)
  533. p.Pin(dvsd)
  534. C.frankenphp_register_bulk_variables(&knownVariables[0], dvsd, C.size_t(l), trackVarsArray)
  535. p.Unpin()
  536. fc.env = nil
  537. }
  538. //export go_apache_request_headers
  539. func go_apache_request_headers(rh, mrh C.uintptr_t) (*C.go_string, C.size_t, C.uintptr_t) {
  540. if rh == 0 {
  541. // worker mode, not handling a request
  542. mr := cgo.Handle(mrh).Value().(*http.Request)
  543. mfc := mr.Context().Value(contextKey).(*FrankenPHPContext)
  544. if c := mfc.logger.Check(zapcore.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil {
  545. c.Write(zap.String("worker", mfc.scriptFilename))
  546. }
  547. return nil, 0, 0
  548. }
  549. r := cgo.Handle(rh).Value().(*http.Request)
  550. pinner := &runtime.Pinner{}
  551. pinnerHandle := C.uintptr_t(cgo.NewHandle(pinner))
  552. headers := make([]C.go_string, 0, len(r.Header)*2)
  553. for field, val := range r.Header {
  554. fd := unsafe.StringData(field)
  555. pinner.Pin(fd)
  556. cv := strings.Join(val, ", ")
  557. vd := unsafe.StringData(cv)
  558. pinner.Pin(vd)
  559. headers = append(
  560. headers,
  561. C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))},
  562. C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))},
  563. )
  564. }
  565. sd := unsafe.SliceData(headers)
  566. pinner.Pin(sd)
  567. return sd, C.size_t(len(r.Header)), pinnerHandle
  568. }
  569. //export go_apache_request_cleanup
  570. func go_apache_request_cleanup(rh C.uintptr_t) {
  571. if rh == 0 {
  572. return
  573. }
  574. h := cgo.Handle(rh)
  575. p := h.Value().(*runtime.Pinner)
  576. p.Unpin()
  577. h.Delete()
  578. }
  579. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  580. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  581. if len(parts) != 2 {
  582. if c := fc.logger.Check(zapcore.DebugLevel, "invalid header"); c != nil {
  583. c.Write(zap.String("header", parts[0]))
  584. }
  585. return
  586. }
  587. fc.responseWriter.Header().Add(parts[0], parts[1])
  588. }
  589. //export go_write_headers
  590. func go_write_headers(rh C.uintptr_t, status C.int, headers *C.zend_llist) {
  591. r := cgo.Handle(rh).Value().(*http.Request)
  592. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  593. if fc.responseWriter == nil {
  594. return
  595. }
  596. current := headers.head
  597. for current != nil {
  598. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  599. addHeader(fc, h.header, C.int(h.header_len))
  600. current = current.next
  601. }
  602. fc.responseWriter.WriteHeader(int(status))
  603. if status >= 100 && status < 200 {
  604. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  605. h := fc.responseWriter.Header()
  606. for k := range h {
  607. delete(h, k)
  608. }
  609. }
  610. }
  611. //export go_sapi_flush
  612. func go_sapi_flush(rh C.uintptr_t) bool {
  613. r := cgo.Handle(rh).Value().(*http.Request)
  614. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  615. if fc.responseWriter == nil || clientHasClosed(r) {
  616. return true
  617. }
  618. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  619. if c := fc.logger.Check(zapcore.ErrorLevel, "the current responseWriter is not a flusher"); c != nil {
  620. c.Write(zap.Error(err))
  621. }
  622. }
  623. return false
  624. }
  625. //export go_read_post
  626. func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  627. r := cgo.Handle(rh).Value().(*http.Request)
  628. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  629. var err error
  630. for readBytes < countBytes && err == nil {
  631. var n int
  632. n, err = r.Body.Read(p[readBytes:])
  633. readBytes += C.size_t(n)
  634. }
  635. return
  636. }
  637. //export go_read_cookies
  638. func go_read_cookies(rh C.uintptr_t) *C.char {
  639. r := cgo.Handle(rh).Value().(*http.Request)
  640. cookies := r.Cookies()
  641. if len(cookies) == 0 {
  642. return nil
  643. }
  644. cookieStrings := make([]string, len(cookies))
  645. for i, cookie := range cookies {
  646. cookieStrings[i] = cookie.String()
  647. }
  648. // freed in frankenphp_free_request_context()
  649. return C.CString(strings.Join(cookieStrings, "; "))
  650. }
  651. //export go_log
  652. func go_log(message *C.char, level C.int) {
  653. l := getLogger()
  654. m := C.GoString(message)
  655. var le syslogLevel
  656. if level < C.int(emerg) || level > C.int(debug) {
  657. le = info
  658. } else {
  659. le = syslogLevel(level)
  660. }
  661. switch le {
  662. case emerg, alert, crit, err:
  663. if c := l.Check(zapcore.ErrorLevel, m); c != nil {
  664. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  665. }
  666. case warning:
  667. if c := l.Check(zapcore.WarnLevel, m); c != nil {
  668. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  669. }
  670. case debug:
  671. if c := l.Check(zapcore.DebugLevel, m); c != nil {
  672. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  673. }
  674. default:
  675. if c := l.Check(zapcore.InfoLevel, m); c != nil {
  676. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  677. }
  678. }
  679. }
  680. // ExecuteScriptCLI executes the PHP script passed as parameter.
  681. // It returns the exit status code of the script.
  682. func ExecuteScriptCLI(script string, args []string) int {
  683. cScript := C.CString(script)
  684. defer C.free(unsafe.Pointer(cScript))
  685. argc, argv := convertArgs(args)
  686. defer freeArgs(argv)
  687. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  688. }
  689. func convertArgs(args []string) (C.int, []*C.char) {
  690. argc := C.int(len(args))
  691. argv := make([]*C.char, argc)
  692. for i, arg := range args {
  693. argv[i] = C.CString(arg)
  694. }
  695. return argc, argv
  696. }
  697. func freeArgs(argv []*C.char) {
  698. for _, arg := range argv {
  699. C.free(unsafe.Pointer(arg))
  700. }
  701. }