frankenphp.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  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. done chan struct{}
  61. shutdownWG sync.WaitGroup
  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. 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 C.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) 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 NotEnoughThreads
  229. }
  230. metrics.TotalThreads(opt.numThreads)
  231. MaxThreads = opt.numThreads
  232. return nil
  233. }
  234. // Init starts the PHP runtime and the configured workers.
  235. func Init(options ...Option) error {
  236. if requestChan != nil {
  237. return AlreadyStartedError
  238. }
  239. // Ignore all SIGPIPE signals to prevent weird issues with systemd: https://github.com/dunglas/frankenphp/issues/1020
  240. // Docker/Moby has a similar hack: https://github.com/moby/moby/blob/d828b032a87606ae34267e349bf7f7ccb1f6495a/cmd/dockerd/docker.go#L87-L90
  241. signal.Ignore(syscall.SIGPIPE)
  242. opt := &opt{}
  243. for _, o := range options {
  244. if err := o(opt); err != nil {
  245. return err
  246. }
  247. }
  248. if opt.logger == nil {
  249. l, err := zap.NewDevelopment()
  250. if err != nil {
  251. return err
  252. }
  253. loggerMu.Lock()
  254. logger = l
  255. loggerMu.Unlock()
  256. } else {
  257. loggerMu.Lock()
  258. logger = opt.logger
  259. loggerMu.Unlock()
  260. }
  261. if opt.metrics != nil {
  262. metrics = opt.metrics
  263. }
  264. err := calculateMaxThreads(opt)
  265. if err != nil {
  266. return err
  267. }
  268. config := Config()
  269. if config.Version.MajorVersion < 8 || (config.Version.MajorVersion == 8 && config.Version.MinorVersion < 2) {
  270. return InvalidPHPVersionError
  271. }
  272. if config.ZTS {
  273. if !config.ZendMaxExecutionTimers && runtime.GOOS == "linux" {
  274. 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`)
  275. }
  276. } else {
  277. opt.numThreads = 1
  278. 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`)
  279. }
  280. shutdownWG.Add(1)
  281. done = make(chan struct{})
  282. requestChan = make(chan *http.Request, opt.numThreads)
  283. initPHPThreads(opt.numThreads)
  284. if C.frankenphp_init(C.int(opt.numThreads)) != 0 {
  285. return MainThreadCreationError
  286. }
  287. if err := initWorkers(opt.workers); err != nil {
  288. return err
  289. }
  290. if err := restartWorkersOnFileChanges(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", opt.numThreads))
  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. drainWorkers()
  306. drainThreads()
  307. metrics.Shutdown()
  308. requestChan = nil
  309. // Remove the installed app
  310. if EmbeddedAppPath != "" {
  311. _ = os.RemoveAll(EmbeddedAppPath)
  312. }
  313. logger.Debug("FrankenPHP shut down")
  314. }
  315. //export go_shutdown
  316. func go_shutdown() {
  317. shutdownWG.Done()
  318. }
  319. func drainThreads() {
  320. close(done)
  321. shutdownWG.Wait()
  322. phpThreads = nil
  323. }
  324. func getLogger() *zap.Logger {
  325. loggerMu.RLock()
  326. defer loggerMu.RUnlock()
  327. return logger
  328. }
  329. func updateServerContext(thread *phpThread, request *http.Request, create bool, isWorkerRequest bool) error {
  330. fc, ok := FromContext(request.Context())
  331. if !ok {
  332. return InvalidRequestError
  333. }
  334. authUser, authPassword, ok := request.BasicAuth()
  335. var cAuthUser, cAuthPassword *C.char
  336. if ok && authPassword != "" {
  337. cAuthPassword = thread.pinCString(authPassword)
  338. }
  339. if ok && authUser != "" {
  340. cAuthUser = thread.pinCString(authUser)
  341. }
  342. cMethod := thread.pinCString(request.Method)
  343. cQueryString := thread.pinCString(request.URL.RawQuery)
  344. contentLengthStr := request.Header.Get("Content-Length")
  345. contentLength := 0
  346. if contentLengthStr != "" {
  347. var err error
  348. contentLength, err = strconv.Atoi(contentLengthStr)
  349. if err != nil || contentLength < 0 {
  350. return fmt.Errorf("invalid Content-Length header: %w", err)
  351. }
  352. }
  353. contentType := request.Header.Get("Content-Type")
  354. var cContentType *C.char
  355. if contentType != "" {
  356. cContentType = thread.pinCString(contentType)
  357. }
  358. // compliance with the CGI specification requires that
  359. // PATH_TRANSLATED should only exist if PATH_INFO is defined.
  360. // Info: https://www.ietf.org/rfc/rfc3875 Page 14
  361. var cPathTranslated *C.char
  362. if fc.pathInfo != "" {
  363. cPathTranslated = thread.pinCString(sanitizedPathJoin(fc.documentRoot, fc.pathInfo)) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
  364. }
  365. cRequestUri := thread.pinCString(request.URL.RequestURI())
  366. isBootingAWorkerScript := fc.responseWriter == nil
  367. ret := C.frankenphp_update_server_context(
  368. C.bool(create),
  369. C.bool(isWorkerRequest || isBootingAWorkerScript),
  370. C.bool(!isBootingAWorkerScript),
  371. cMethod,
  372. cQueryString,
  373. C.zend_long(contentLength),
  374. cPathTranslated,
  375. cRequestUri,
  376. cContentType,
  377. cAuthUser,
  378. cAuthPassword,
  379. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  380. )
  381. if ret > 0 {
  382. return RequestContextCreationError
  383. }
  384. return nil
  385. }
  386. // ServeHTTP executes a PHP script according to the given context.
  387. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error {
  388. if !requestIsValid(request, responseWriter) {
  389. return nil
  390. }
  391. shutdownWG.Add(1)
  392. defer shutdownWG.Done()
  393. fc, ok := FromContext(request.Context())
  394. if !ok {
  395. return InvalidRequestError
  396. }
  397. fc.responseWriter = responseWriter
  398. fc.startedAt = time.Now()
  399. isWorker := fc.responseWriter == nil
  400. // Detect if a worker is available to handle this request
  401. if !isWorker {
  402. if worker, ok := workers[fc.scriptFilename]; ok {
  403. metrics.StartWorkerRequest(fc.scriptFilename)
  404. worker.handleRequest(request)
  405. <-fc.done
  406. metrics.StopWorkerRequest(fc.scriptFilename, time.Since(fc.startedAt))
  407. return nil
  408. } else {
  409. metrics.StartRequest()
  410. }
  411. }
  412. select {
  413. case <-done:
  414. case requestChan <- request:
  415. <-fc.done
  416. }
  417. if !isWorker {
  418. metrics.StopRequest()
  419. }
  420. return nil
  421. }
  422. //export go_handle_request
  423. func go_handle_request(threadIndex C.uintptr_t) bool {
  424. select {
  425. case <-done:
  426. return false
  427. case r := <-requestChan:
  428. thread := phpThreads[threadIndex]
  429. thread.mainRequest = r
  430. fc, ok := FromContext(r.Context())
  431. if !ok {
  432. panic(InvalidRequestError)
  433. }
  434. defer func() {
  435. maybeCloseContext(fc)
  436. thread.mainRequest = nil
  437. thread.Unpin()
  438. }()
  439. if err := updateServerContext(thread, r, true, false); err != nil {
  440. rejectRequest(fc.responseWriter, err.Error())
  441. return true
  442. }
  443. // scriptFilename is freed in frankenphp_execute_script()
  444. fc.exitStatus = C.frankenphp_execute_script(C.CString(fc.scriptFilename))
  445. if fc.exitStatus < 0 {
  446. panic(ScriptExecutionError)
  447. }
  448. // if the script has errored or timed out, make sure any pending worker requests are closed
  449. if fc.exitStatus > 0 && thread.workerRequest != nil {
  450. fc := thread.workerRequest.Context().Value(contextKey).(*FrankenPHPContext)
  451. maybeCloseContext(fc)
  452. thread.workerRequest = nil
  453. }
  454. return true
  455. }
  456. }
  457. func maybeCloseContext(fc *FrankenPHPContext) {
  458. fc.closed.Do(func() {
  459. close(fc.done)
  460. })
  461. }
  462. //export go_ub_write
  463. func go_ub_write(threadIndex C.uintptr_t, cBuf *C.char, length C.int) (C.size_t, C.bool) {
  464. r := phpThreads[threadIndex].getActiveRequest()
  465. fc, _ := FromContext(r.Context())
  466. var writer io.Writer
  467. if fc.responseWriter == nil {
  468. var b bytes.Buffer
  469. // log the output of the worker
  470. writer = &b
  471. } else {
  472. writer = fc.responseWriter
  473. }
  474. i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length))
  475. if e != nil {
  476. if c := fc.logger.Check(zapcore.ErrorLevel, "write error"); c != nil {
  477. c.Write(zap.Error(e))
  478. }
  479. }
  480. if fc.responseWriter == nil {
  481. fc.logger.Info(writer.(*bytes.Buffer).String())
  482. }
  483. return C.size_t(i), C.bool(clientHasClosed(r))
  484. }
  485. // There are around 60 common request headers according to https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
  486. // Give some space for custom headers
  487. var headerKeyCache = func() otter.Cache[string, string] {
  488. c, err := otter.MustBuilder[string, string](256).Build()
  489. if err != nil {
  490. panic(err)
  491. }
  492. return c
  493. }()
  494. //export go_apache_request_headers
  495. func go_apache_request_headers(threadIndex C.uintptr_t, hasActiveRequest bool) (*C.go_string, C.size_t) {
  496. thread := phpThreads[threadIndex]
  497. if !hasActiveRequest {
  498. // worker mode, not handling a request
  499. mfc := thread.mainRequest.Context().Value(contextKey).(*FrankenPHPContext)
  500. if c := mfc.logger.Check(zapcore.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil {
  501. c.Write(zap.String("worker", mfc.scriptFilename))
  502. }
  503. return nil, 0
  504. }
  505. r := thread.getActiveRequest()
  506. headers := make([]C.go_string, 0, len(r.Header)*2)
  507. for field, val := range r.Header {
  508. fd := unsafe.StringData(field)
  509. thread.Pin(fd)
  510. cv := strings.Join(val, ", ")
  511. vd := unsafe.StringData(cv)
  512. thread.Pin(vd)
  513. headers = append(
  514. headers,
  515. C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))},
  516. C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))},
  517. )
  518. }
  519. sd := unsafe.SliceData(headers)
  520. thread.Pin(sd)
  521. return sd, C.size_t(len(r.Header))
  522. }
  523. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  524. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  525. if len(parts) != 2 {
  526. if c := fc.logger.Check(zapcore.DebugLevel, "invalid header"); c != nil {
  527. c.Write(zap.String("header", parts[0]))
  528. }
  529. return
  530. }
  531. fc.responseWriter.Header().Add(parts[0], parts[1])
  532. }
  533. //export go_write_headers
  534. func go_write_headers(threadIndex C.uintptr_t, status C.int, headers *C.zend_llist) {
  535. r := phpThreads[threadIndex].getActiveRequest()
  536. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  537. if fc.responseWriter == nil {
  538. return
  539. }
  540. current := headers.head
  541. for current != nil {
  542. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  543. addHeader(fc, h.header, C.int(h.header_len))
  544. current = current.next
  545. }
  546. fc.responseWriter.WriteHeader(int(status))
  547. if status >= 100 && status < 200 {
  548. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  549. h := fc.responseWriter.Header()
  550. for k := range h {
  551. delete(h, k)
  552. }
  553. }
  554. }
  555. //export go_sapi_flush
  556. func go_sapi_flush(threadIndex C.uintptr_t) bool {
  557. r := phpThreads[threadIndex].getActiveRequest()
  558. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  559. if fc.responseWriter == nil || clientHasClosed(r) {
  560. return true
  561. }
  562. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  563. if c := fc.logger.Check(zapcore.ErrorLevel, "the current responseWriter is not a flusher"); c != nil {
  564. c.Write(zap.Error(err))
  565. }
  566. }
  567. return false
  568. }
  569. //export go_read_post
  570. func go_read_post(threadIndex C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  571. r := phpThreads[threadIndex].getActiveRequest()
  572. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  573. var err error
  574. for readBytes < countBytes && err == nil {
  575. var n int
  576. n, err = r.Body.Read(p[readBytes:])
  577. readBytes += C.size_t(n)
  578. }
  579. return
  580. }
  581. //export go_read_cookies
  582. func go_read_cookies(threadIndex C.uintptr_t) *C.char {
  583. r := phpThreads[threadIndex].getActiveRequest()
  584. cookies := r.Cookies()
  585. if len(cookies) == 0 {
  586. return nil
  587. }
  588. cookieStrings := make([]string, len(cookies))
  589. for i, cookie := range cookies {
  590. cookieStrings[i] = cookie.String()
  591. }
  592. // freed in frankenphp_free_request_context()
  593. return C.CString(strings.Join(cookieStrings, "; "))
  594. }
  595. //export go_log
  596. func go_log(message *C.char, level C.int) {
  597. l := getLogger()
  598. m := C.GoString(message)
  599. var le syslogLevel
  600. if level < C.int(emerg) || level > C.int(debug) {
  601. le = info
  602. } else {
  603. le = syslogLevel(level)
  604. }
  605. switch le {
  606. case emerg, alert, crit, err:
  607. if c := l.Check(zapcore.ErrorLevel, m); c != nil {
  608. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  609. }
  610. case warning:
  611. if c := l.Check(zapcore.WarnLevel, m); c != nil {
  612. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  613. }
  614. case debug:
  615. if c := l.Check(zapcore.DebugLevel, m); c != nil {
  616. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  617. }
  618. default:
  619. if c := l.Check(zapcore.InfoLevel, m); c != nil {
  620. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  621. }
  622. }
  623. }
  624. // ExecuteScriptCLI executes the PHP script passed as parameter.
  625. // It returns the exit status code of the script.
  626. func ExecuteScriptCLI(script string, args []string) int {
  627. cScript := C.CString(script)
  628. defer C.free(unsafe.Pointer(cScript))
  629. argc, argv := convertArgs(args)
  630. defer freeArgs(argv)
  631. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  632. }
  633. func convertArgs(args []string) (C.int, []*C.char) {
  634. argc := C.int(len(args))
  635. argv := make([]*C.char, argc)
  636. for i, arg := range args {
  637. argv[i] = C.CString(arg)
  638. }
  639. return argc, argv
  640. }
  641. func freeArgs(argv []*C.char) {
  642. for _, arg := range argv {
  643. C.free(unsafe.Pointer(arg))
  644. }
  645. }
  646. func executePHPFunction(functionName string) {
  647. cFunctionName := C.CString(functionName)
  648. defer C.free(unsafe.Pointer(cFunctionName))
  649. success := C.frankenphp_execute_php_function(cFunctionName)
  650. if success == 1 {
  651. if c := logger.Check(zapcore.DebugLevel, "php function call successful"); c != nil {
  652. c.Write(zap.String("function", functionName))
  653. }
  654. } else {
  655. if c := logger.Check(zapcore.ErrorLevel, "php function call failed"); c != nil {
  656. c.Write(zap.String("function", functionName))
  657. }
  658. }
  659. }
  660. // Ensure that the request path does not contain null bytes
  661. func requestIsValid(r *http.Request, rw http.ResponseWriter) bool {
  662. if !strings.Contains(r.URL.Path, "\x00") {
  663. return true
  664. }
  665. rejectRequest(rw, "Invalid request path")
  666. return false
  667. }
  668. func rejectRequest(rw http.ResponseWriter, message string) {
  669. rw.WriteHeader(http.StatusBadRequest)
  670. _, _ = rw.Write([]byte(message))
  671. rw.(http.Flusher).Flush()
  672. }