frankenphp.go 19 KB

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