frankenphp.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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: -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. go startMainThreads(opt.numThreads)
  269. if err := initWorkers(opt.workers); err != nil {
  270. return err
  271. }
  272. logger.Info("FrankenPHP started 🐘", zap.String("php_version", Version().Version), zap.Int("num_threads", opt.numThreads))
  273. if EmbeddedAppPath != "" {
  274. logger.Info("embedded PHP app 📦", zap.String("path", EmbeddedAppPath))
  275. }
  276. return nil
  277. }
  278. func startMainThreads(numThreads int) bool {
  279. // prevent sharing this thread with other go funcs
  280. runtime.LockOSThread()
  281. // note: we do NOT unlock the thread so that Go will not try to reuse it when this func completes
  282. var threads sync.WaitGroup
  283. C.frankenphp_prepare_thread()
  284. C.frankenphp_prepare_sapi(C.int(numThreads))
  285. for i := 0; i < numThreads; i++ {
  286. threads.Add(1)
  287. go func() {
  288. runtime.LockOSThread()
  289. defer threads.Done()
  290. C.frankenphp_prepare_thread()
  291. go_fetch_and_execute()
  292. }()
  293. }
  294. threads.Wait()
  295. C.frankenphp_shutdown_sapi()
  296. go_shutdown()
  297. return true
  298. }
  299. // Shutdown stops the workers and the PHP runtime.
  300. func Shutdown() {
  301. stopWorkers()
  302. close(done)
  303. shutdownWG.Wait()
  304. requestChan = nil
  305. // Always reset the WaitGroup to ensure we're in a clean state
  306. workersReadyWG = sync.WaitGroup{}
  307. // Remove the installed app
  308. if EmbeddedAppPath != "" {
  309. os.RemoveAll(EmbeddedAppPath)
  310. }
  311. logger.Debug("FrankenPHP shut down")
  312. }
  313. //export go_shutdown
  314. func go_shutdown() {
  315. shutdownWG.Done()
  316. }
  317. func getLogger() *zap.Logger {
  318. loggerMu.RLock()
  319. defer loggerMu.RUnlock()
  320. return logger
  321. }
  322. func updateServerContext(request *http.Request, create bool, mrh C.uintptr_t) error {
  323. fc, ok := FromContext(request.Context())
  324. if !ok {
  325. return InvalidRequestError
  326. }
  327. authUser, authPassword, ok := request.BasicAuth()
  328. var cAuthUser, cAuthPassword *C.char
  329. if ok && authPassword != "" {
  330. cAuthPassword = C.CString(authPassword)
  331. }
  332. if ok && authUser != "" {
  333. cAuthUser = C.CString(authUser)
  334. }
  335. cMethod := C.CString(request.Method)
  336. cQueryString := C.CString(request.URL.RawQuery)
  337. contentLengthStr := request.Header.Get("Content-Length")
  338. contentLength := 0
  339. if contentLengthStr != "" {
  340. var err error
  341. contentLength, err = strconv.Atoi(contentLengthStr)
  342. if err != nil {
  343. return fmt.Errorf("invalid Content-Length header: %w", err)
  344. }
  345. }
  346. contentType := request.Header.Get("Content-Type")
  347. var cContentType *C.char
  348. if contentType != "" {
  349. cContentType = C.CString(contentType)
  350. }
  351. // compliance with the CGI specification requires that
  352. // PATH_TRANSLATED should only exist if PATH_INFO is defined.
  353. // Info: https://www.ietf.org/rfc/rfc3875 Page 14
  354. var cPathTranslated *C.char
  355. if fc.pathInfo != "" {
  356. cPathTranslated = C.CString(sanitizedPathJoin(fc.documentRoot, fc.pathInfo)) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
  357. }
  358. cRequestUri := C.CString(request.URL.RequestURI())
  359. var rh cgo.Handle
  360. if fc.responseWriter == nil {
  361. h := cgo.NewHandle(request)
  362. request.Context().Value(handleKey).(*handleList).AddHandle(h)
  363. mrh = C.uintptr_t(h)
  364. } else {
  365. rh = cgo.NewHandle(request)
  366. request.Context().Value(handleKey).(*handleList).AddHandle(rh)
  367. }
  368. ret := C.frankenphp_update_server_context(
  369. C.bool(create),
  370. C.uintptr_t(rh),
  371. mrh,
  372. cMethod,
  373. cQueryString,
  374. C.zend_long(contentLength),
  375. cPathTranslated,
  376. cRequestUri,
  377. cContentType,
  378. cAuthUser,
  379. cAuthPassword,
  380. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  381. )
  382. if ret > 0 {
  383. return RequestContextCreationError
  384. }
  385. return nil
  386. }
  387. // ServeHTTP executes a PHP script according to the given context.
  388. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error {
  389. shutdownWG.Add(1)
  390. defer shutdownWG.Done()
  391. fc, ok := FromContext(request.Context())
  392. if !ok {
  393. return InvalidRequestError
  394. }
  395. fc.responseWriter = responseWriter
  396. rc := requestChan
  397. // Detect if a worker is available to handle this request
  398. if nil != fc.responseWriter {
  399. if v, ok := workersRequestChans.Load(fc.scriptFilename); ok {
  400. rc = v.(chan *http.Request)
  401. }
  402. }
  403. select {
  404. case <-done:
  405. case rc <- request:
  406. <-fc.done
  407. }
  408. return nil
  409. }
  410. //export go_fetch_and_execute
  411. func go_fetch_and_execute() {
  412. for {
  413. select {
  414. case <-done:
  415. return
  416. case r := <-requestChan:
  417. h := cgo.NewHandle(r)
  418. r.Context().Value(handleKey).(*handleList).AddHandle(h)
  419. fc, ok := FromContext(r.Context())
  420. if !ok {
  421. panic(InvalidRequestError)
  422. }
  423. if err := updateServerContext(r, true, 0); err != nil {
  424. panic(err)
  425. }
  426. // scriptFilename is freed in frankenphp_execute_script()
  427. fc.exitStatus = C.frankenphp_execute_script(C.CString(fc.scriptFilename))
  428. if fc.exitStatus < 0 {
  429. panic(ScriptExecutionError)
  430. }
  431. maybeCloseContext(fc)
  432. r.Context().Value(handleKey).(*handleList).FreeAll()
  433. }
  434. }
  435. }
  436. func maybeCloseContext(fc *FrankenPHPContext) {
  437. fc.closed.Do(func() {
  438. close(fc.done)
  439. })
  440. }
  441. //export go_ub_write
  442. func go_ub_write(rh C.uintptr_t, cBuf *C.char, length C.int) (C.size_t, C.bool) {
  443. r := cgo.Handle(rh).Value().(*http.Request)
  444. fc, _ := FromContext(r.Context())
  445. var writer io.Writer
  446. if fc.responseWriter == nil {
  447. var b bytes.Buffer
  448. // log the output of the worker
  449. writer = &b
  450. } else {
  451. writer = fc.responseWriter
  452. }
  453. i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length))
  454. if e != nil {
  455. fc.logger.Error("write error", zap.Error(e))
  456. }
  457. if fc.responseWriter == nil {
  458. fc.logger.Info(writer.(*bytes.Buffer).String())
  459. }
  460. return C.size_t(i), C.bool(clientHasClosed(r))
  461. }
  462. // There are around 60 common request headers according to https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
  463. // Give some space for custom headers
  464. var headerKeyCache = func() otter.Cache[string, string] {
  465. c, err := otter.MustBuilder[string, string](256).Build()
  466. if err != nil {
  467. panic(err)
  468. }
  469. return c
  470. }()
  471. //export go_register_variables
  472. func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) {
  473. r := cgo.Handle(rh).Value().(*http.Request)
  474. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  475. p := &runtime.Pinner{}
  476. dynamicVariables := make([]C.php_variable, len(fc.env)+len(r.Header))
  477. var l int
  478. // Add all HTTP headers to env variables
  479. for field, val := range r.Header {
  480. k, ok := headerKeyCache.Get(field)
  481. if !ok {
  482. k = "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(field)) + "\x00"
  483. headerKeyCache.SetIfAbsent(field, k)
  484. }
  485. if _, ok := fc.env[k]; ok {
  486. continue
  487. }
  488. v := strings.Join(val, ", ")
  489. kData := unsafe.StringData(k)
  490. vData := 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. for k, v := range fc.env {
  499. if _, ok := knownServerKeys[k]; ok {
  500. continue
  501. }
  502. kData := unsafe.StringData(k)
  503. vData := unsafe.Pointer(unsafe.StringData(v))
  504. p.Pin(kData)
  505. p.Pin(vData)
  506. dynamicVariables[l]._var = (*C.char)(unsafe.Pointer(kData))
  507. dynamicVariables[l].data_len = C.size_t(len(v))
  508. dynamicVariables[l].data = (*C.char)(unsafe.Pointer(vData))
  509. l++
  510. }
  511. knownVariables := computeKnownVariables(r, p)
  512. dvsd := unsafe.SliceData(dynamicVariables)
  513. p.Pin(dvsd)
  514. C.frankenphp_register_bulk_variables(&knownVariables[0], dvsd, C.size_t(l), trackVarsArray)
  515. p.Unpin()
  516. fc.env = nil
  517. }
  518. //export go_apache_request_headers
  519. func go_apache_request_headers(rh, mrh C.uintptr_t) (*C.go_string, C.size_t, C.uintptr_t) {
  520. if rh == 0 {
  521. // worker mode, not handling a request
  522. mr := cgo.Handle(mrh).Value().(*http.Request)
  523. mfc := mr.Context().Value(contextKey).(*FrankenPHPContext)
  524. if c := mfc.logger.Check(zap.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil {
  525. c.Write(zap.String("worker", mfc.scriptFilename))
  526. }
  527. return nil, 0, 0
  528. }
  529. r := cgo.Handle(rh).Value().(*http.Request)
  530. pinner := &runtime.Pinner{}
  531. pinnerHandle := C.uintptr_t(cgo.NewHandle(pinner))
  532. headers := make([]C.go_string, 0, len(r.Header)*2)
  533. for field, val := range r.Header {
  534. fd := unsafe.StringData(field)
  535. pinner.Pin(fd)
  536. cv := strings.Join(val, ", ")
  537. vd := unsafe.StringData(cv)
  538. pinner.Pin(vd)
  539. headers = append(
  540. headers,
  541. C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))},
  542. C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))},
  543. )
  544. }
  545. sd := unsafe.SliceData(headers)
  546. pinner.Pin(sd)
  547. return sd, C.size_t(len(r.Header)), pinnerHandle
  548. }
  549. //export go_apache_request_cleanup
  550. func go_apache_request_cleanup(rh C.uintptr_t) {
  551. if rh == 0 {
  552. return
  553. }
  554. h := cgo.Handle(rh)
  555. p := h.Value().(*runtime.Pinner)
  556. p.Unpin()
  557. h.Delete()
  558. }
  559. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  560. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  561. if len(parts) != 2 {
  562. fc.logger.Debug("invalid header", zap.String("header", parts[0]))
  563. return
  564. }
  565. fc.responseWriter.Header().Add(parts[0], parts[1])
  566. }
  567. //export go_write_headers
  568. func go_write_headers(rh C.uintptr_t, status C.int, headers *C.zend_llist) {
  569. r := cgo.Handle(rh).Value().(*http.Request)
  570. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  571. if fc.responseWriter == nil {
  572. return
  573. }
  574. current := headers.head
  575. for current != nil {
  576. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  577. addHeader(fc, h.header, C.int(h.header_len))
  578. current = current.next
  579. }
  580. fc.responseWriter.WriteHeader(int(status))
  581. if status >= 100 && status < 200 {
  582. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  583. h := fc.responseWriter.Header()
  584. for k := range h {
  585. delete(h, k)
  586. }
  587. }
  588. }
  589. //export go_sapi_flush
  590. func go_sapi_flush(rh C.uintptr_t) bool {
  591. r := cgo.Handle(rh).Value().(*http.Request)
  592. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  593. if fc.responseWriter == nil || clientHasClosed(r) {
  594. return true
  595. }
  596. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  597. fc.logger.Error("the current responseWriter is not a flusher", zap.Error(err))
  598. }
  599. return false
  600. }
  601. //export go_read_post
  602. func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  603. r := cgo.Handle(rh).Value().(*http.Request)
  604. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  605. var err error
  606. for readBytes < countBytes && err == nil {
  607. var n int
  608. n, err = r.Body.Read(p[readBytes:])
  609. readBytes += C.size_t(n)
  610. }
  611. return
  612. }
  613. //export go_read_cookies
  614. func go_read_cookies(rh C.uintptr_t) *C.char {
  615. r := cgo.Handle(rh).Value().(*http.Request)
  616. cookies := r.Cookies()
  617. if len(cookies) == 0 {
  618. return nil
  619. }
  620. cookieStrings := make([]string, len(cookies))
  621. for i, cookie := range cookies {
  622. cookieStrings[i] = cookie.String()
  623. }
  624. // freed in frankenphp_request_shutdown()
  625. return C.CString(strings.Join(cookieStrings, "; "))
  626. }
  627. //export go_log
  628. func go_log(message *C.char, level C.int) {
  629. l := getLogger()
  630. m := C.GoString(message)
  631. var le syslogLevel
  632. if level < C.int(emerg) || level > C.int(debug) {
  633. le = info
  634. } else {
  635. le = syslogLevel(level)
  636. }
  637. switch le {
  638. case emerg, alert, crit, err:
  639. l.Error(m, zap.Stringer("syslog_level", syslogLevel(level)))
  640. case warning:
  641. l.Warn(m, zap.Stringer("syslog_level", syslogLevel(level)))
  642. case debug:
  643. l.Debug(m, zap.Stringer("syslog_level", syslogLevel(level)))
  644. default:
  645. l.Info(m, zap.Stringer("syslog_level", syslogLevel(level)))
  646. }
  647. }
  648. // ExecuteScriptCLI executes the PHP script passed as parameter.
  649. // It returns the exit status code of the script.
  650. func ExecuteScriptCLI(script string, args []string) int {
  651. cScript := C.CString(script)
  652. defer C.free(unsafe.Pointer(cScript))
  653. argc, argv := convertArgs(args)
  654. defer freeArgs(argv)
  655. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  656. }
  657. func convertArgs(args []string) (C.int, []*C.char) {
  658. argc := C.int(len(args))
  659. argv := make([]*C.char, argc)
  660. for i, arg := range args {
  661. argv[i] = C.CString(arg)
  662. }
  663. return argc, argv
  664. }
  665. func freeArgs(argv []*C.char) {
  666. for _, arg := range argv {
  667. C.free(unsafe.Pointer(arg))
  668. }
  669. }