frankenphp.go 19 KB

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