frankenphp.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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/.github C-Thread-Pool/docs C-Thread-Pool/tests C-Thread-Pool/example.c
  10. // Use PHP includes corresponding to your PHP installation by running:
  11. //
  12. // export CGO_CFLAGS=$(php-config --includes)
  13. // export CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)"
  14. //
  15. // We also set these flags for hardening: https://github.com/docker-library/php/blob/master/8.2/bookworm/zts/Dockerfile#L57-L59
  16. // #cgo darwin pkg-config: libxml-2.0
  17. // #cgo CFLAGS: -Wall -Werror -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
  18. // #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
  19. // #cgo CFLAGS: -DTHREAD_NAME=frankenphp
  20. // #cgo linux CFLAGS: -D_GNU_SOURCE
  21. // #cgo CPPFLAGS: -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
  22. // #cgo darwin LDFLAGS: -L/opt/homebrew/opt/libiconv/lib -liconv
  23. // #cgo linux LDFLAGS: -Wl,-O1 -lresolv
  24. // #cgo LDFLAGS: -pie -L/usr/local/lib -L/usr/lib -lphp -ldl -lm -lutil
  25. // #include <stdlib.h>
  26. // #include <stdint.h>
  27. // #include <php_variables.h>
  28. // #include <zend_llist.h>
  29. // #include <SAPI.h>
  30. // #include "frankenphp.h"
  31. import "C"
  32. import (
  33. "bytes"
  34. "context"
  35. "errors"
  36. "fmt"
  37. "io"
  38. "net/http"
  39. "os"
  40. "runtime"
  41. "runtime/cgo"
  42. "strconv"
  43. "strings"
  44. "sync"
  45. "unsafe"
  46. "github.com/maypok86/otter"
  47. "go.uber.org/zap"
  48. // debug on Linux
  49. //_ "github.com/ianlancetaylor/cgosymbolizer"
  50. )
  51. type contextKeyStruct struct{}
  52. type handleKeyStruct struct{}
  53. var contextKey = contextKeyStruct{}
  54. var handleKey = handleKeyStruct{}
  55. var (
  56. InvalidRequestError = errors.New("not a FrankenPHP request")
  57. AlreaydStartedError = errors.New("FrankenPHP is already started")
  58. InvalidPHPVersionError = errors.New("FrankenPHP is only compatible with PHP 8.2+")
  59. ZendSignalsError = errors.New("Zend Signals are enabled, recompile PHP with --disable-zend-signals")
  60. NotEnoughThreads = errors.New("the number of threads must be superior to the number of workers")
  61. MainThreadCreationError = errors.New("error creating the main thread")
  62. RequestContextCreationError = errors.New("error during request context creation")
  63. RequestStartupError = errors.New("error during PHP request startup")
  64. ScriptExecutionError = errors.New("error during PHP script execution")
  65. requestChan chan *http.Request
  66. done chan struct{}
  67. shutdownWG sync.WaitGroup
  68. loggerMu sync.RWMutex
  69. logger *zap.Logger
  70. )
  71. type syslogLevel int
  72. const (
  73. emerg syslogLevel = iota // system is unusable
  74. alert // action must be taken immediately
  75. crit // critical conditions
  76. err // error conditions
  77. warning // warning conditions
  78. notice // normal but significant condition
  79. info // informational
  80. debug // debug-level messages
  81. )
  82. func (l syslogLevel) String() string {
  83. switch l {
  84. case emerg:
  85. return "emerg"
  86. case alert:
  87. return "alert"
  88. case crit:
  89. return "crit"
  90. case err:
  91. return "err"
  92. case warning:
  93. return "warning"
  94. case notice:
  95. return "notice"
  96. case debug:
  97. return "debug"
  98. default:
  99. return "info"
  100. }
  101. }
  102. // FrankenPHPContext provides contextual information about the Request to handle.
  103. type FrankenPHPContext struct {
  104. documentRoot string
  105. splitPath []string
  106. env PreparedEnv
  107. logger *zap.Logger
  108. docURI string
  109. pathInfo string
  110. scriptName string
  111. scriptFilename string
  112. // Whether the request is already closed by us
  113. closed sync.Once
  114. responseWriter http.ResponseWriter
  115. exitStatus C.int
  116. done chan interface{}
  117. currentWorkerRequest cgo.Handle
  118. }
  119. func clientHasClosed(r *http.Request) bool {
  120. select {
  121. case <-r.Context().Done():
  122. return true
  123. default:
  124. return false
  125. }
  126. }
  127. // NewRequestWithContext creates a new FrankenPHP request context.
  128. func NewRequestWithContext(r *http.Request, opts ...RequestOption) (*http.Request, error) {
  129. fc := &FrankenPHPContext{
  130. done: make(chan interface{}),
  131. }
  132. for _, o := range opts {
  133. if err := o(fc); err != nil {
  134. return nil, err
  135. }
  136. }
  137. if fc.documentRoot == "" {
  138. if EmbeddedAppPath != "" {
  139. fc.documentRoot = EmbeddedAppPath
  140. } else {
  141. var err error
  142. if fc.documentRoot, err = os.Getwd(); err != nil {
  143. return nil, err
  144. }
  145. }
  146. }
  147. if fc.splitPath == nil {
  148. fc.splitPath = []string{".php"}
  149. }
  150. if fc.env == nil {
  151. fc.env = make(map[string]string)
  152. }
  153. if fc.logger == nil {
  154. fc.logger = getLogger()
  155. }
  156. if splitPos := splitPos(fc, r.URL.Path); splitPos > -1 {
  157. fc.docURI = r.URL.Path[:splitPos]
  158. fc.pathInfo = r.URL.Path[splitPos:]
  159. // Strip PATH_INFO from SCRIPT_NAME
  160. fc.scriptName = strings.TrimSuffix(r.URL.Path, fc.pathInfo)
  161. // Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875
  162. // Info: https://tools.ietf.org/html/rfc3875#section-4.1.13
  163. if fc.scriptName != "" && !strings.HasPrefix(fc.scriptName, "/") {
  164. fc.scriptName = "/" + fc.scriptName
  165. }
  166. }
  167. // SCRIPT_FILENAME is the absolute path of SCRIPT_NAME
  168. fc.scriptFilename = sanitizedPathJoin(fc.documentRoot, fc.scriptName)
  169. c := context.WithValue(r.Context(), contextKey, fc)
  170. c = context.WithValue(c, handleKey, Handles())
  171. return r.WithContext(c), nil
  172. }
  173. // FromContext extracts the FrankenPHPContext from a context.
  174. func FromContext(ctx context.Context) (fctx *FrankenPHPContext, ok bool) {
  175. fctx, ok = ctx.Value(contextKey).(*FrankenPHPContext)
  176. return
  177. }
  178. type PHPVersion struct {
  179. MajorVersion int
  180. MinorVersion int
  181. ReleaseVersion int
  182. ExtraVersion string
  183. Version string
  184. VersionID int
  185. }
  186. type PHPConfig struct {
  187. Version PHPVersion
  188. ZTS bool
  189. ZendSignals bool
  190. ZendMaxExecutionTimers bool
  191. }
  192. // Version returns infos about the PHP version.
  193. func Version() PHPVersion {
  194. cVersion := C.frankenphp_get_version()
  195. return PHPVersion{
  196. int(cVersion.major_version),
  197. int(cVersion.minor_version),
  198. int(cVersion.release_version),
  199. C.GoString(cVersion.extra_version),
  200. C.GoString(cVersion.version),
  201. int(cVersion.version_id),
  202. }
  203. }
  204. func Config() PHPConfig {
  205. cConfig := C.frankenphp_get_config()
  206. return PHPConfig{
  207. Version: Version(),
  208. ZTS: bool(cConfig.zts),
  209. ZendSignals: bool(cConfig.zend_signals),
  210. ZendMaxExecutionTimers: bool(cConfig.zend_max_execution_timers),
  211. }
  212. }
  213. // Init starts the PHP runtime and the configured workers.
  214. func Init(options ...Option) error {
  215. if requestChan != nil {
  216. return AlreaydStartedError
  217. }
  218. opt := &opt{}
  219. for _, o := range options {
  220. if err := o(opt); err != nil {
  221. return err
  222. }
  223. }
  224. if opt.logger == nil {
  225. l, err := zap.NewDevelopment()
  226. if err != nil {
  227. return err
  228. }
  229. loggerMu.Lock()
  230. logger = l
  231. loggerMu.Unlock()
  232. } else {
  233. loggerMu.Lock()
  234. logger = opt.logger
  235. loggerMu.Unlock()
  236. }
  237. maxProcs := runtime.GOMAXPROCS(0)
  238. var numWorkers int
  239. for i, w := range opt.workers {
  240. if w.num <= 0 {
  241. // https://github.com/dunglas/frankenphp/issues/126
  242. opt.workers[i].num = maxProcs * 2
  243. }
  244. numWorkers += opt.workers[i].num
  245. }
  246. if opt.numThreads <= 0 {
  247. if numWorkers >= maxProcs {
  248. // Start at least as many threads as workers, and keep a free thread to handle requests in non-worker mode
  249. opt.numThreads = numWorkers + 1
  250. } else {
  251. opt.numThreads = maxProcs
  252. }
  253. } else if opt.numThreads <= numWorkers {
  254. return NotEnoughThreads
  255. }
  256. config := Config()
  257. if config.Version.MajorVersion < 8 || (config.Version.MajorVersion == 8 && config.Version.MinorVersion < 2) {
  258. return InvalidPHPVersionError
  259. }
  260. if config.ZTS {
  261. if !config.ZendMaxExecutionTimers && runtime.GOOS == "linux" {
  262. 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`)
  263. }
  264. } else {
  265. opt.numThreads = 1
  266. 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`)
  267. }
  268. shutdownWG.Add(1)
  269. done = make(chan struct{})
  270. requestChan = make(chan *http.Request)
  271. if C.frankenphp_init(C.int(opt.numThreads)) != 0 {
  272. return MainThreadCreationError
  273. }
  274. if err := initWorkers(opt.workers); err != nil {
  275. return err
  276. }
  277. logger.Info("FrankenPHP started 🐘", zap.String("php_version", Version().Version))
  278. if EmbeddedAppPath != "" {
  279. logger.Info("embedded PHP app 📦", zap.String("path", EmbeddedAppPath))
  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_fetch_request
  395. func go_fetch_request() C.uintptr_t {
  396. select {
  397. case <-done:
  398. return 0
  399. case r := <-requestChan:
  400. h := cgo.NewHandle(r)
  401. r.Context().Value(handleKey).(*handleList).AddHandle(h)
  402. return C.uintptr_t(h)
  403. }
  404. }
  405. func maybeCloseContext(fc *FrankenPHPContext) {
  406. fc.closed.Do(func() {
  407. close(fc.done)
  408. })
  409. }
  410. // go_execute_script Note: only called in cgi-mode
  411. //
  412. //export go_execute_script
  413. func go_execute_script(rh unsafe.Pointer) {
  414. handle := cgo.Handle(rh)
  415. request := handle.Value().(*http.Request)
  416. fc, ok := FromContext(request.Context())
  417. if !ok {
  418. panic(InvalidRequestError)
  419. }
  420. defer func() {
  421. maybeCloseContext(fc)
  422. request.Context().Value(handleKey).(*handleList).FreeAll()
  423. }()
  424. if err := updateServerContext(request, true, 0); err != nil {
  425. panic(err)
  426. }
  427. // scriptFilename is freed in frankenphp_execute_script()
  428. fc.exitStatus = C.frankenphp_execute_script(C.CString(fc.scriptFilename))
  429. if fc.exitStatus < 0 {
  430. panic(ScriptExecutionError)
  431. }
  432. }
  433. //export go_ub_write
  434. func go_ub_write(rh C.uintptr_t, cBuf *C.char, length C.int) (C.size_t, C.bool) {
  435. r := cgo.Handle(rh).Value().(*http.Request)
  436. fc, _ := FromContext(r.Context())
  437. var writer io.Writer
  438. if fc.responseWriter == nil {
  439. var b bytes.Buffer
  440. // log the output of the worker
  441. writer = &b
  442. } else {
  443. writer = fc.responseWriter
  444. }
  445. i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length))
  446. if e != nil {
  447. fc.logger.Error("write error", zap.Error(e))
  448. }
  449. if fc.responseWriter == nil {
  450. fc.logger.Info(writer.(*bytes.Buffer).String())
  451. }
  452. return C.size_t(i), C.bool(clientHasClosed(r))
  453. }
  454. // There are around 60 common request headers according to https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
  455. // Give some space for custom headers
  456. var headerKeyCache = func() otter.Cache[string, string] {
  457. c, err := otter.MustBuilder[string, string](256).Build()
  458. if err != nil {
  459. panic(err)
  460. }
  461. return c
  462. }()
  463. //export go_register_variables
  464. func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) {
  465. r := cgo.Handle(rh).Value().(*http.Request)
  466. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  467. p := &runtime.Pinner{}
  468. dynamicVariables := make([]C.php_variable, len(fc.env)+len(r.Header))
  469. var l int
  470. // Add all HTTP headers to env variables
  471. for field, val := range r.Header {
  472. k, ok := headerKeyCache.Get(field)
  473. if !ok {
  474. k = "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(field)) + "\x00"
  475. headerKeyCache.SetIfAbsent(field, k)
  476. }
  477. if _, ok := fc.env[k]; ok {
  478. continue
  479. }
  480. v := strings.Join(val, ", ")
  481. kData := unsafe.StringData(k)
  482. vData := unsafe.StringData(v)
  483. p.Pin(kData)
  484. p.Pin(vData)
  485. dynamicVariables[l]._var = (*C.char)(unsafe.Pointer(kData))
  486. dynamicVariables[l].data_len = C.size_t(len(v))
  487. dynamicVariables[l].data = (*C.char)(unsafe.Pointer(vData))
  488. l++
  489. }
  490. for k, v := range fc.env {
  491. if _, ok := knownServerKeys[k]; ok {
  492. continue
  493. }
  494. kData := unsafe.StringData(k)
  495. vData := unsafe.Pointer(unsafe.StringData(v))
  496. p.Pin(kData)
  497. p.Pin(vData)
  498. dynamicVariables[l]._var = (*C.char)(unsafe.Pointer(kData))
  499. dynamicVariables[l].data_len = C.size_t(len(v))
  500. dynamicVariables[l].data = (*C.char)(unsafe.Pointer(vData))
  501. l++
  502. }
  503. knownVariables := computeKnownVariables(r, p)
  504. dvsd := unsafe.SliceData(dynamicVariables)
  505. p.Pin(dvsd)
  506. C.frankenphp_register_bulk_variables(&knownVariables[0], dvsd, C.size_t(l), trackVarsArray)
  507. p.Unpin()
  508. fc.env = nil
  509. }
  510. //export go_apache_request_headers
  511. func go_apache_request_headers(rh, mrh C.uintptr_t) (*C.go_string, C.size_t, C.uintptr_t) {
  512. if rh == 0 {
  513. // worker mode, not handling a request
  514. mr := cgo.Handle(mrh).Value().(*http.Request)
  515. mfc := mr.Context().Value(contextKey).(*FrankenPHPContext)
  516. if c := mfc.logger.Check(zap.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil {
  517. c.Write(zap.String("worker", mfc.scriptFilename))
  518. }
  519. return nil, 0, 0
  520. }
  521. r := cgo.Handle(rh).Value().(*http.Request)
  522. pinner := &runtime.Pinner{}
  523. pinnerHandle := C.uintptr_t(cgo.NewHandle(pinner))
  524. headers := make([]C.go_string, 0, len(r.Header)*2)
  525. for field, val := range r.Header {
  526. fd := unsafe.StringData(field)
  527. pinner.Pin(fd)
  528. cv := strings.Join(val, ", ")
  529. vd := unsafe.StringData(cv)
  530. pinner.Pin(vd)
  531. headers = append(
  532. headers,
  533. C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))},
  534. C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))},
  535. )
  536. }
  537. sd := unsafe.SliceData(headers)
  538. pinner.Pin(sd)
  539. return sd, C.size_t(len(r.Header)), pinnerHandle
  540. }
  541. //export go_apache_request_cleanup
  542. func go_apache_request_cleanup(rh C.uintptr_t) {
  543. if rh == 0 {
  544. return
  545. }
  546. h := cgo.Handle(rh)
  547. p := h.Value().(*runtime.Pinner)
  548. p.Unpin()
  549. h.Delete()
  550. }
  551. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  552. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  553. if len(parts) != 2 {
  554. fc.logger.Debug("invalid header", zap.String("header", parts[0]))
  555. return
  556. }
  557. fc.responseWriter.Header().Add(parts[0], parts[1])
  558. }
  559. //export go_write_headers
  560. func go_write_headers(rh C.uintptr_t, status C.int, headers *C.zend_llist) {
  561. r := cgo.Handle(rh).Value().(*http.Request)
  562. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  563. if fc.responseWriter == nil {
  564. return
  565. }
  566. current := headers.head
  567. for current != nil {
  568. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  569. addHeader(fc, h.header, C.int(h.header_len))
  570. current = current.next
  571. }
  572. fc.responseWriter.WriteHeader(int(status))
  573. if status >= 100 && status < 200 {
  574. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  575. h := fc.responseWriter.Header()
  576. for k := range h {
  577. delete(h, k)
  578. }
  579. }
  580. }
  581. //export go_sapi_flush
  582. func go_sapi_flush(rh C.uintptr_t) bool {
  583. r := cgo.Handle(rh).Value().(*http.Request)
  584. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  585. if fc.responseWriter == nil || clientHasClosed(r) {
  586. return true
  587. }
  588. if r.ProtoMajor == 1 {
  589. if _, err := r.Body.Read(nil); err != nil {
  590. // Don't flush until the whole body has been read to prevent https://github.com/golang/go/issues/15527
  591. return false
  592. }
  593. }
  594. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  595. fc.logger.Error("the current responseWriter is not a flusher", zap.Error(err))
  596. }
  597. return false
  598. }
  599. //export go_read_post
  600. func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  601. r := cgo.Handle(rh).Value().(*http.Request)
  602. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  603. var err error
  604. for readBytes < countBytes && err == nil {
  605. var n int
  606. n, err = r.Body.Read(p[readBytes:])
  607. readBytes += C.size_t(n)
  608. }
  609. return
  610. }
  611. //export go_read_cookies
  612. func go_read_cookies(rh C.uintptr_t) *C.char {
  613. r := cgo.Handle(rh).Value().(*http.Request)
  614. cookies := r.Cookies()
  615. if len(cookies) == 0 {
  616. return nil
  617. }
  618. cookieStrings := make([]string, len(cookies))
  619. for i, cookie := range cookies {
  620. cookieStrings[i] = cookie.String()
  621. }
  622. // freed in frankenphp_request_shutdown()
  623. return C.CString(strings.Join(cookieStrings, "; "))
  624. }
  625. //export go_log
  626. func go_log(message *C.char, level C.int) {
  627. l := getLogger()
  628. m := C.GoString(message)
  629. var le syslogLevel
  630. if level < C.int(emerg) || level > C.int(debug) {
  631. le = info
  632. } else {
  633. le = syslogLevel(level)
  634. }
  635. switch le {
  636. case emerg, alert, crit, err:
  637. l.Error(m, zap.Stringer("syslog_level", syslogLevel(level)))
  638. case warning:
  639. l.Warn(m, zap.Stringer("syslog_level", syslogLevel(level)))
  640. case debug:
  641. l.Debug(m, zap.Stringer("syslog_level", syslogLevel(level)))
  642. default:
  643. l.Info(m, zap.Stringer("syslog_level", syslogLevel(level)))
  644. }
  645. }
  646. // ExecuteScriptCLI executes the PHP script passed as parameter.
  647. // It returns the exit status code of the script.
  648. func ExecuteScriptCLI(script string, args []string) int {
  649. cScript := C.CString(script)
  650. defer C.free(unsafe.Pointer(cScript))
  651. argc, argv := convertArgs(args)
  652. defer freeArgs(argv)
  653. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  654. }
  655. func convertArgs(args []string) (C.int, []*C.char) {
  656. argc := C.int(len(args))
  657. argv := make([]*C.char, argc)
  658. for i, arg := range args {
  659. argv[i] = C.CString(arg)
  660. }
  661. return argc, argv
  662. }
  663. func freeArgs(argv []*C.char) {
  664. for _, arg := range argv {
  665. C.free(unsafe.Pointer(arg))
  666. }
  667. }