frankenphp.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. thread := getInactivePHPThread()
  284. convertToRegularThread(thread)
  285. }
  286. if err := initWorkers(opt.workers); err != nil {
  287. return err
  288. }
  289. if c := logger.Check(zapcore.InfoLevel, "FrankenPHP started 🐘"); c != nil {
  290. c.Write(zap.String("php_version", Version().Version), zap.Int("num_threads", totalThreadCount))
  291. }
  292. if EmbeddedAppPath != "" {
  293. if c := logger.Check(zapcore.InfoLevel, "embedded PHP app 📦"); c != nil {
  294. c.Write(zap.String("path", EmbeddedAppPath))
  295. }
  296. }
  297. return nil
  298. }
  299. // Shutdown stops the workers and the PHP runtime.
  300. func Shutdown() {
  301. drainWorkers()
  302. drainPHPThreads()
  303. metrics.Shutdown()
  304. requestChan = nil
  305. // Remove the installed app
  306. if EmbeddedAppPath != "" {
  307. _ = os.RemoveAll(EmbeddedAppPath)
  308. }
  309. logger.Debug("FrankenPHP shut down")
  310. }
  311. func getLogger() *zap.Logger {
  312. loggerMu.RLock()
  313. defer loggerMu.RUnlock()
  314. return logger
  315. }
  316. func updateServerContext(thread *phpThread, request *http.Request, create bool, isWorkerRequest bool) error {
  317. fc, ok := FromContext(request.Context())
  318. if !ok {
  319. return InvalidRequestError
  320. }
  321. authUser, authPassword, ok := request.BasicAuth()
  322. var cAuthUser, cAuthPassword *C.char
  323. if ok && authPassword != "" {
  324. cAuthPassword = thread.pinCString(authPassword)
  325. }
  326. if ok && authUser != "" {
  327. cAuthUser = thread.pinCString(authUser)
  328. }
  329. cMethod := thread.pinCString(request.Method)
  330. cQueryString := thread.pinCString(request.URL.RawQuery)
  331. contentLengthStr := request.Header.Get("Content-Length")
  332. contentLength := 0
  333. if contentLengthStr != "" {
  334. var err error
  335. contentLength, err = strconv.Atoi(contentLengthStr)
  336. if err != nil || contentLength < 0 {
  337. return fmt.Errorf("invalid Content-Length header: %w", err)
  338. }
  339. }
  340. contentType := request.Header.Get("Content-Type")
  341. var cContentType *C.char
  342. if contentType != "" {
  343. cContentType = thread.pinCString(contentType)
  344. }
  345. // compliance with the CGI specification requires that
  346. // PATH_TRANSLATED should only exist if PATH_INFO is defined.
  347. // Info: https://www.ietf.org/rfc/rfc3875 Page 14
  348. var cPathTranslated *C.char
  349. if fc.pathInfo != "" {
  350. cPathTranslated = thread.pinCString(sanitizedPathJoin(fc.documentRoot, fc.pathInfo)) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
  351. }
  352. cRequestUri := thread.pinCString(request.URL.RequestURI())
  353. isBootingAWorkerScript := fc.responseWriter == nil
  354. ret := C.frankenphp_update_server_context(
  355. C.bool(create),
  356. C.bool(isWorkerRequest || isBootingAWorkerScript),
  357. C.bool(!isBootingAWorkerScript),
  358. cMethod,
  359. cQueryString,
  360. C.zend_long(contentLength),
  361. cPathTranslated,
  362. cRequestUri,
  363. cContentType,
  364. cAuthUser,
  365. cAuthPassword,
  366. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  367. )
  368. if ret > 0 {
  369. return RequestContextCreationError
  370. }
  371. return nil
  372. }
  373. // ServeHTTP executes a PHP script according to the given context.
  374. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error {
  375. if !requestIsValid(request, responseWriter) {
  376. return nil
  377. }
  378. fc, ok := FromContext(request.Context())
  379. if !ok {
  380. return InvalidRequestError
  381. }
  382. fc.responseWriter = responseWriter
  383. fc.startedAt = time.Now()
  384. // Detect if a worker is available to handle this request
  385. if worker, ok := workers[fc.scriptFilename]; ok {
  386. worker.handleRequest(request, fc)
  387. return nil
  388. }
  389. metrics.StartRequest()
  390. select {
  391. case <-mainThread.done:
  392. case requestChan <- request:
  393. <-fc.done
  394. }
  395. metrics.StopRequest()
  396. return nil
  397. }
  398. func maybeCloseContext(fc *FrankenPHPContext) {
  399. fc.closed.Do(func() {
  400. close(fc.done)
  401. })
  402. }
  403. //export go_ub_write
  404. func go_ub_write(threadIndex C.uintptr_t, cBuf *C.char, length C.int) (C.size_t, C.bool) {
  405. r := phpThreads[threadIndex].getActiveRequest()
  406. fc, _ := FromContext(r.Context())
  407. var writer io.Writer
  408. if fc.responseWriter == nil {
  409. var b bytes.Buffer
  410. // log the output of the worker
  411. writer = &b
  412. } else {
  413. writer = fc.responseWriter
  414. }
  415. i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length))
  416. if e != nil {
  417. if c := fc.logger.Check(zapcore.ErrorLevel, "write error"); c != nil {
  418. c.Write(zap.Error(e))
  419. }
  420. }
  421. if fc.responseWriter == nil {
  422. fc.logger.Info(writer.(*bytes.Buffer).String())
  423. }
  424. return C.size_t(i), C.bool(clientHasClosed(r))
  425. }
  426. // There are around 60 common request headers according to https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
  427. // Give some space for custom headers
  428. var headerKeyCache = func() otter.Cache[string, string] {
  429. c, err := otter.MustBuilder[string, string](256).Build()
  430. if err != nil {
  431. panic(err)
  432. }
  433. return c
  434. }()
  435. //export go_apache_request_headers
  436. func go_apache_request_headers(threadIndex C.uintptr_t, hasActiveRequest bool) (*C.go_string, C.size_t) {
  437. thread := phpThreads[threadIndex]
  438. if !hasActiveRequest {
  439. // worker mode, not handling a request
  440. mfc := thread.getActiveRequest().Context().Value(contextKey).(*FrankenPHPContext)
  441. if c := mfc.logger.Check(zapcore.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil {
  442. c.Write(zap.String("worker", mfc.scriptFilename))
  443. }
  444. return nil, 0
  445. }
  446. r := thread.getActiveRequest()
  447. headers := make([]C.go_string, 0, len(r.Header)*2)
  448. for field, val := range r.Header {
  449. fd := unsafe.StringData(field)
  450. thread.Pin(fd)
  451. cv := strings.Join(val, ", ")
  452. vd := unsafe.StringData(cv)
  453. thread.Pin(vd)
  454. headers = append(
  455. headers,
  456. C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))},
  457. C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))},
  458. )
  459. }
  460. sd := unsafe.SliceData(headers)
  461. thread.Pin(sd)
  462. return sd, C.size_t(len(r.Header))
  463. }
  464. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  465. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  466. if len(parts) != 2 {
  467. if c := fc.logger.Check(zapcore.DebugLevel, "invalid header"); c != nil {
  468. c.Write(zap.String("header", parts[0]))
  469. }
  470. return
  471. }
  472. fc.responseWriter.Header().Add(parts[0], parts[1])
  473. }
  474. //export go_write_headers
  475. func go_write_headers(threadIndex C.uintptr_t, status C.int, headers *C.zend_llist) {
  476. r := phpThreads[threadIndex].getActiveRequest()
  477. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  478. if fc.responseWriter == nil {
  479. return
  480. }
  481. current := headers.head
  482. for current != nil {
  483. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  484. addHeader(fc, h.header, C.int(h.header_len))
  485. current = current.next
  486. }
  487. fc.responseWriter.WriteHeader(int(status))
  488. if status >= 100 && status < 200 {
  489. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  490. h := fc.responseWriter.Header()
  491. for k := range h {
  492. delete(h, k)
  493. }
  494. }
  495. }
  496. //export go_sapi_flush
  497. func go_sapi_flush(threadIndex C.uintptr_t) bool {
  498. r := phpThreads[threadIndex].getActiveRequest()
  499. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  500. if fc.responseWriter == nil || clientHasClosed(r) {
  501. return true
  502. }
  503. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  504. if c := fc.logger.Check(zapcore.ErrorLevel, "the current responseWriter is not a flusher"); c != nil {
  505. c.Write(zap.Error(err))
  506. }
  507. }
  508. return false
  509. }
  510. //export go_read_post
  511. func go_read_post(threadIndex C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  512. r := phpThreads[threadIndex].getActiveRequest()
  513. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  514. var err error
  515. for readBytes < countBytes && err == nil {
  516. var n int
  517. n, err = r.Body.Read(p[readBytes:])
  518. readBytes += C.size_t(n)
  519. }
  520. return
  521. }
  522. //export go_read_cookies
  523. func go_read_cookies(threadIndex C.uintptr_t) *C.char {
  524. r := phpThreads[threadIndex].getActiveRequest()
  525. cookies := r.Cookies()
  526. if len(cookies) == 0 {
  527. return nil
  528. }
  529. cookieStrings := make([]string, len(cookies))
  530. for i, cookie := range cookies {
  531. cookieStrings[i] = cookie.String()
  532. }
  533. // freed in frankenphp_free_request_context()
  534. return C.CString(strings.Join(cookieStrings, "; "))
  535. }
  536. //export go_log
  537. func go_log(message *C.char, level C.int) {
  538. l := getLogger()
  539. m := C.GoString(message)
  540. var le syslogLevel
  541. if level < C.int(emerg) || level > C.int(debug) {
  542. le = info
  543. } else {
  544. le = syslogLevel(level)
  545. }
  546. switch le {
  547. case emerg, alert, crit, err:
  548. if c := l.Check(zapcore.ErrorLevel, m); c != nil {
  549. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  550. }
  551. case warning:
  552. if c := l.Check(zapcore.WarnLevel, m); c != nil {
  553. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  554. }
  555. case debug:
  556. if c := l.Check(zapcore.DebugLevel, m); c != nil {
  557. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  558. }
  559. default:
  560. if c := l.Check(zapcore.InfoLevel, m); c != nil {
  561. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  562. }
  563. }
  564. }
  565. // ExecuteScriptCLI executes the PHP script passed as parameter.
  566. // It returns the exit status code of the script.
  567. func ExecuteScriptCLI(script string, args []string) int {
  568. cScript := C.CString(script)
  569. defer C.free(unsafe.Pointer(cScript))
  570. argc, argv := convertArgs(args)
  571. defer freeArgs(argv)
  572. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  573. }
  574. func convertArgs(args []string) (C.int, []*C.char) {
  575. argc := C.int(len(args))
  576. argv := make([]*C.char, argc)
  577. for i, arg := range args {
  578. argv[i] = C.CString(arg)
  579. }
  580. return argc, argv
  581. }
  582. func freeArgs(argv []*C.char) {
  583. for _, arg := range argv {
  584. C.free(unsafe.Pointer(arg))
  585. }
  586. }
  587. func executePHPFunction(functionName string) bool {
  588. cFunctionName := C.CString(functionName)
  589. defer C.free(unsafe.Pointer(cFunctionName))
  590. return C.frankenphp_execute_php_function(cFunctionName) == 1
  591. }
  592. // Ensure that the request path does not contain null bytes
  593. func requestIsValid(r *http.Request, rw http.ResponseWriter) bool {
  594. if !strings.Contains(r.URL.Path, "\x00") {
  595. return true
  596. }
  597. rejectRequest(rw, "Invalid request path")
  598. return false
  599. }
  600. func rejectRequest(rw http.ResponseWriter, message string) {
  601. rw.WriteHeader(http.StatusBadRequest)
  602. _, _ = rw.Write([]byte(message))
  603. rw.(http.Flusher).Flush()
  604. }