frankenphp.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. // Package frankenphp embeds PHP in Go projects and provides a SAPI for net/http.
  2. //
  3. // This is the core of the [FrankenPHP app server], and can be used in any Go program.
  4. //
  5. // [FrankenPHP app server]: https://frankenphp.dev
  6. package frankenphp
  7. // Use PHP includes corresponding to your PHP installation by running:
  8. //
  9. // export CGO_CFLAGS=$(php-config --includes)
  10. // export CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)"
  11. //
  12. // We also set these flags for hardening: https://github.com/docker-library/php/blob/master/8.2/bookworm/zts/Dockerfile#L57-L59
  13. // #cgo darwin pkg-config: libxml-2.0
  14. // #cgo CFLAGS: -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. "strconv"
  36. "strings"
  37. "sync"
  38. "unsafe"
  39. "github.com/maypok86/otter"
  40. "go.uber.org/zap"
  41. // debug on Linux
  42. //_ "github.com/ianlancetaylor/cgosymbolizer"
  43. )
  44. type contextKeyStruct struct{}
  45. type handleKeyStruct struct{}
  46. var contextKey = contextKeyStruct{}
  47. var handleKey = handleKeyStruct{}
  48. var (
  49. InvalidRequestError = errors.New("not a FrankenPHP request")
  50. AlreaydStartedError = errors.New("FrankenPHP is already started")
  51. InvalidPHPVersionError = errors.New("FrankenPHP is only compatible with PHP 8.2+")
  52. ZendSignalsError = errors.New("Zend Signals are enabled, recompile PHP with --disable-zend-signals")
  53. NotEnoughThreads = errors.New("the number of threads must be superior to the number of workers")
  54. MainThreadCreationError = errors.New("error creating the main thread")
  55. RequestContextCreationError = errors.New("error during request context creation")
  56. RequestStartupError = errors.New("error during PHP request startup")
  57. ScriptExecutionError = errors.New("error during PHP script execution")
  58. requestChan chan *http.Request
  59. done chan struct{}
  60. shutdownWG sync.WaitGroup
  61. loggerMu sync.RWMutex
  62. logger *zap.Logger
  63. )
  64. type syslogLevel int
  65. const (
  66. emerg syslogLevel = iota // system is unusable
  67. alert // action must be taken immediately
  68. crit // critical conditions
  69. err // error conditions
  70. warning // warning conditions
  71. notice // normal but significant condition
  72. info // informational
  73. debug // debug-level messages
  74. )
  75. func (l syslogLevel) String() string {
  76. switch l {
  77. case emerg:
  78. return "emerg"
  79. case alert:
  80. return "alert"
  81. case crit:
  82. return "crit"
  83. case err:
  84. return "err"
  85. case warning:
  86. return "warning"
  87. case notice:
  88. return "notice"
  89. case debug:
  90. return "debug"
  91. default:
  92. return "info"
  93. }
  94. }
  95. // FrankenPHPContext provides contextual information about the Request to handle.
  96. type FrankenPHPContext struct {
  97. documentRoot string
  98. splitPath []string
  99. env PreparedEnv
  100. logger *zap.Logger
  101. docURI string
  102. pathInfo string
  103. scriptName string
  104. scriptFilename string
  105. // Whether the request is already closed by us
  106. closed sync.Once
  107. responseWriter http.ResponseWriter
  108. exitStatus C.int
  109. done chan interface{}
  110. currentWorkerRequest handle
  111. }
  112. func clientHasClosed(r *http.Request) bool {
  113. select {
  114. case <-r.Context().Done():
  115. return true
  116. default:
  117. return false
  118. }
  119. }
  120. // NewRequestWithContext creates a new FrankenPHP request context.
  121. func NewRequestWithContext(r *http.Request, opts ...RequestOption) (*http.Request, error) {
  122. fc := &FrankenPHPContext{
  123. done: make(chan interface{}),
  124. }
  125. for _, o := range opts {
  126. if err := o(fc); err != nil {
  127. return nil, err
  128. }
  129. }
  130. if fc.documentRoot == "" {
  131. if EmbeddedAppPath != "" {
  132. fc.documentRoot = EmbeddedAppPath
  133. } else {
  134. var err error
  135. if fc.documentRoot, err = os.Getwd(); err != nil {
  136. return nil, err
  137. }
  138. }
  139. }
  140. if fc.splitPath == nil {
  141. fc.splitPath = []string{".php"}
  142. }
  143. if fc.env == nil {
  144. fc.env = make(map[string]string)
  145. }
  146. if fc.logger == nil {
  147. fc.logger = getLogger()
  148. }
  149. if splitPos := splitPos(fc, r.URL.Path); splitPos > -1 {
  150. fc.docURI = r.URL.Path[:splitPos]
  151. fc.pathInfo = r.URL.Path[splitPos:]
  152. // Strip PATH_INFO from SCRIPT_NAME
  153. fc.scriptName = strings.TrimSuffix(r.URL.Path, fc.pathInfo)
  154. // Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875
  155. // Info: https://tools.ietf.org/html/rfc3875#section-4.1.13
  156. if fc.scriptName != "" && !strings.HasPrefix(fc.scriptName, "/") {
  157. fc.scriptName = "/" + fc.scriptName
  158. }
  159. }
  160. // SCRIPT_FILENAME is the absolute path of SCRIPT_NAME
  161. fc.scriptFilename = sanitizedPathJoin(fc.documentRoot, fc.scriptName)
  162. c := context.WithValue(r.Context(), contextKey, fc)
  163. return r.WithContext(c), nil
  164. }
  165. // FromContext extracts the FrankenPHPContext from a context.
  166. func FromContext(ctx context.Context) (fctx *FrankenPHPContext, ok bool) {
  167. fctx, ok = ctx.Value(contextKey).(*FrankenPHPContext)
  168. return
  169. }
  170. type PHPVersion struct {
  171. MajorVersion int
  172. MinorVersion int
  173. ReleaseVersion int
  174. ExtraVersion string
  175. Version string
  176. VersionID int
  177. }
  178. type PHPConfig struct {
  179. Version PHPVersion
  180. ZTS bool
  181. ZendSignals bool
  182. ZendMaxExecutionTimers bool
  183. }
  184. // Version returns infos about the PHP version.
  185. func Version() PHPVersion {
  186. cVersion := C.frankenphp_get_version()
  187. return PHPVersion{
  188. int(cVersion.major_version),
  189. int(cVersion.minor_version),
  190. int(cVersion.release_version),
  191. C.GoString(cVersion.extra_version),
  192. C.GoString(cVersion.version),
  193. int(cVersion.version_id),
  194. }
  195. }
  196. func Config() PHPConfig {
  197. cConfig := C.frankenphp_get_config()
  198. return PHPConfig{
  199. Version: Version(),
  200. ZTS: bool(cConfig.zts),
  201. ZendSignals: bool(cConfig.zend_signals),
  202. ZendMaxExecutionTimers: bool(cConfig.zend_max_execution_timers),
  203. }
  204. }
  205. // Init starts the PHP runtime and the configured workers.
  206. func Init(options ...Option) error {
  207. if requestChan != nil {
  208. return AlreaydStartedError
  209. }
  210. opt := &opt{}
  211. for _, o := range options {
  212. if err := o(opt); err != nil {
  213. return err
  214. }
  215. }
  216. if opt.logger == nil {
  217. l, err := zap.NewDevelopment()
  218. if err != nil {
  219. return err
  220. }
  221. loggerMu.Lock()
  222. logger = l
  223. loggerMu.Unlock()
  224. } else {
  225. loggerMu.Lock()
  226. logger = opt.logger
  227. loggerMu.Unlock()
  228. }
  229. maxProcs := runtime.GOMAXPROCS(0)
  230. var numWorkers int
  231. for i, w := range opt.workers {
  232. if w.num <= 0 {
  233. // https://github.com/dunglas/frankenphp/issues/126
  234. opt.workers[i].num = maxProcs * 2
  235. }
  236. numWorkers += opt.workers[i].num
  237. }
  238. if opt.numThreads <= 0 {
  239. if numWorkers >= maxProcs {
  240. // Start at least as many threads as workers, and keep a free thread to handle requests in non-worker mode
  241. opt.numThreads = numWorkers + 1
  242. } else {
  243. opt.numThreads = maxProcs
  244. }
  245. } else if opt.numThreads <= numWorkers {
  246. return NotEnoughThreads
  247. }
  248. config := Config()
  249. if config.Version.MajorVersion < 8 || (config.Version.MajorVersion == 8 && config.Version.MinorVersion < 2) {
  250. return InvalidPHPVersionError
  251. }
  252. if config.ZTS {
  253. if !config.ZendMaxExecutionTimers && runtime.GOOS == "linux" {
  254. 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`)
  255. }
  256. } else {
  257. opt.numThreads = 1
  258. 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`)
  259. }
  260. shutdownWG.Add(1)
  261. done = make(chan struct{})
  262. requestChan = make(chan *http.Request, opt.numThreads*2)
  263. if C.frankenphp_init(C.int(opt.numThreads)) != 0 {
  264. return MainThreadCreationError
  265. }
  266. if err := initWorkers(opt.workers); err != nil {
  267. return err
  268. }
  269. logger.Info("FrankenPHP started 🐘", zap.String("php_version", Version().Version), zap.Int("num_threads", opt.numThreads))
  270. if EmbeddedAppPath != "" {
  271. logger.Info("embedded PHP app 📦", zap.String("path", EmbeddedAppPath))
  272. }
  273. return nil
  274. }
  275. // Shutdown stops the workers and the PHP runtime.
  276. func Shutdown() {
  277. stopWorkers()
  278. close(done)
  279. shutdownWG.Wait()
  280. requestChan = nil
  281. // Always reset the WaitGroup to ensure we're in a clean state
  282. workersReadyWG = sync.WaitGroup{}
  283. // Remove the installed app
  284. if EmbeddedAppPath != "" {
  285. os.RemoveAll(EmbeddedAppPath)
  286. }
  287. logger.Debug("FrankenPHP shut down")
  288. }
  289. //export go_shutdown
  290. func go_shutdown() {
  291. shutdownWG.Done()
  292. }
  293. func getLogger() *zap.Logger {
  294. loggerMu.RLock()
  295. defer loggerMu.RUnlock()
  296. return logger
  297. }
  298. func updateServerContext(request *http.Request, create bool, mrh C.uintptr_t) (*handle, error) {
  299. fc, ok := FromContext(request.Context())
  300. if !ok {
  301. return nil, InvalidRequestError
  302. }
  303. authUser, authPassword, ok := request.BasicAuth()
  304. var cAuthUser, cAuthPassword *C.char
  305. if ok && authPassword != "" {
  306. cAuthPassword = C.CString(authPassword)
  307. }
  308. if ok && authUser != "" {
  309. cAuthUser = C.CString(authUser)
  310. }
  311. cMethod := C.CString(request.Method)
  312. cQueryString := C.CString(request.URL.RawQuery)
  313. contentLengthStr := request.Header.Get("Content-Length")
  314. contentLength := 0
  315. if contentLengthStr != "" {
  316. var err error
  317. contentLength, err = strconv.Atoi(contentLengthStr)
  318. if err != nil {
  319. return nil, fmt.Errorf("invalid Content-Length header: %w", err)
  320. }
  321. }
  322. contentType := request.Header.Get("Content-Type")
  323. var cContentType *C.char
  324. if contentType != "" {
  325. cContentType = C.CString(contentType)
  326. }
  327. // compliance with the CGI specification requires that
  328. // PATH_TRANSLATED should only exist if PATH_INFO is defined.
  329. // Info: https://www.ietf.org/rfc/rfc3875 Page 14
  330. var cPathTranslated *C.char
  331. if fc.pathInfo != "" {
  332. cPathTranslated = C.CString(sanitizedPathJoin(fc.documentRoot, fc.pathInfo)) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
  333. }
  334. cRequestUri := C.CString(request.URL.RequestURI())
  335. var rh handle
  336. if fc.responseWriter == nil {
  337. mrh = C.uintptr_t(newHandle(request))
  338. } else {
  339. rh = newHandle(request)
  340. }
  341. ret := C.frankenphp_update_server_context(
  342. C.bool(create),
  343. C.uintptr_t(rh),
  344. mrh,
  345. cMethod,
  346. cQueryString,
  347. C.zend_long(contentLength),
  348. cPathTranslated,
  349. cRequestUri,
  350. cContentType,
  351. cAuthUser,
  352. cAuthPassword,
  353. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  354. )
  355. if ret > 0 {
  356. rh.Delete()
  357. handle(mrh).Delete()
  358. return nil, RequestContextCreationError
  359. }
  360. if rh != 0 {
  361. return &rh, nil
  362. }
  363. rh = handle(mrh)
  364. return &rh, 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. fc, ok := FromContext(r.Context())
  396. if !ok {
  397. panic(InvalidRequestError)
  398. }
  399. defer func() {
  400. maybeCloseContext(fc)
  401. }()
  402. rh, err := updateServerContext(r, true, 0)
  403. if err != nil {
  404. rh.Delete()
  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. rh.Delete()
  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 := 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 := 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 := 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 := handle(rh).Value().(*http.Request)
  510. pinner := &runtime.Pinner{}
  511. pinnerHandle := C.uintptr_t(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 := 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 := 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 := 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 := 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 := 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. }