frankenphp.go 19 KB

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