frankenphp.go 19 KB

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