frankenphp.go 19 KB

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