frankenphp.go 19 KB

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