frankenphp.go 20 KB

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