frankenphp.go 20 KB

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