frankenphp.go 18 KB

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