frankenphp.go 19 KB

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