frankenphp.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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. return true
  449. }
  450. }
  451. func maybeCloseContext(fc *FrankenPHPContext) {
  452. fc.closed.Do(func() {
  453. close(fc.done)
  454. })
  455. }
  456. //export go_ub_write
  457. func go_ub_write(threadIndex C.uintptr_t, cBuf *C.char, length C.int) (C.size_t, C.bool) {
  458. r := phpThreads[threadIndex].getActiveRequest()
  459. fc, _ := FromContext(r.Context())
  460. var writer io.Writer
  461. if fc.responseWriter == nil {
  462. var b bytes.Buffer
  463. // log the output of the worker
  464. writer = &b
  465. } else {
  466. writer = fc.responseWriter
  467. }
  468. i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length))
  469. if e != nil {
  470. if c := fc.logger.Check(zapcore.ErrorLevel, "write error"); c != nil {
  471. c.Write(zap.Error(e))
  472. }
  473. }
  474. if fc.responseWriter == nil {
  475. fc.logger.Info(writer.(*bytes.Buffer).String())
  476. }
  477. return C.size_t(i), C.bool(clientHasClosed(r))
  478. }
  479. // There are around 60 common request headers according to https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
  480. // Give some space for custom headers
  481. var headerKeyCache = func() otter.Cache[string, string] {
  482. c, err := otter.MustBuilder[string, string](256).Build()
  483. if err != nil {
  484. panic(err)
  485. }
  486. return c
  487. }()
  488. //export go_apache_request_headers
  489. func go_apache_request_headers(threadIndex C.uintptr_t, hasActiveRequest bool) (*C.go_string, C.size_t) {
  490. thread := phpThreads[threadIndex]
  491. if !hasActiveRequest {
  492. // worker mode, not handling a request
  493. mfc := thread.mainRequest.Context().Value(contextKey).(*FrankenPHPContext)
  494. if c := mfc.logger.Check(zapcore.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil {
  495. c.Write(zap.String("worker", mfc.scriptFilename))
  496. }
  497. return nil, 0
  498. }
  499. r := thread.getActiveRequest()
  500. headers := make([]C.go_string, 0, len(r.Header)*2)
  501. for field, val := range r.Header {
  502. fd := unsafe.StringData(field)
  503. thread.Pin(fd)
  504. cv := strings.Join(val, ", ")
  505. vd := unsafe.StringData(cv)
  506. thread.Pin(vd)
  507. headers = append(
  508. headers,
  509. C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))},
  510. C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))},
  511. )
  512. }
  513. sd := unsafe.SliceData(headers)
  514. thread.Pin(sd)
  515. return sd, C.size_t(len(r.Header))
  516. }
  517. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  518. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  519. if len(parts) != 2 {
  520. if c := fc.logger.Check(zapcore.DebugLevel, "invalid header"); c != nil {
  521. c.Write(zap.String("header", parts[0]))
  522. }
  523. return
  524. }
  525. fc.responseWriter.Header().Add(parts[0], parts[1])
  526. }
  527. //export go_write_headers
  528. func go_write_headers(threadIndex C.uintptr_t, status C.int, headers *C.zend_llist) {
  529. r := phpThreads[threadIndex].getActiveRequest()
  530. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  531. if fc.responseWriter == nil {
  532. return
  533. }
  534. current := headers.head
  535. for current != nil {
  536. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  537. addHeader(fc, h.header, C.int(h.header_len))
  538. current = current.next
  539. }
  540. fc.responseWriter.WriteHeader(int(status))
  541. if status >= 100 && status < 200 {
  542. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  543. h := fc.responseWriter.Header()
  544. for k := range h {
  545. delete(h, k)
  546. }
  547. }
  548. }
  549. //export go_sapi_flush
  550. func go_sapi_flush(threadIndex C.uintptr_t) bool {
  551. r := phpThreads[threadIndex].getActiveRequest()
  552. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  553. if fc.responseWriter == nil || clientHasClosed(r) {
  554. return true
  555. }
  556. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  557. if c := fc.logger.Check(zapcore.ErrorLevel, "the current responseWriter is not a flusher"); c != nil {
  558. c.Write(zap.Error(err))
  559. }
  560. }
  561. return false
  562. }
  563. //export go_read_post
  564. func go_read_post(threadIndex C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  565. r := phpThreads[threadIndex].getActiveRequest()
  566. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  567. var err error
  568. for readBytes < countBytes && err == nil {
  569. var n int
  570. n, err = r.Body.Read(p[readBytes:])
  571. readBytes += C.size_t(n)
  572. }
  573. return
  574. }
  575. //export go_read_cookies
  576. func go_read_cookies(threadIndex C.uintptr_t) *C.char {
  577. r := phpThreads[threadIndex].getActiveRequest()
  578. cookies := r.Cookies()
  579. if len(cookies) == 0 {
  580. return nil
  581. }
  582. cookieStrings := make([]string, len(cookies))
  583. for i, cookie := range cookies {
  584. cookieStrings[i] = cookie.String()
  585. }
  586. // freed in frankenphp_free_request_context()
  587. return C.CString(strings.Join(cookieStrings, "; "))
  588. }
  589. //export go_log
  590. func go_log(message *C.char, level C.int) {
  591. l := getLogger()
  592. m := C.GoString(message)
  593. var le syslogLevel
  594. if level < C.int(emerg) || level > C.int(debug) {
  595. le = info
  596. } else {
  597. le = syslogLevel(level)
  598. }
  599. switch le {
  600. case emerg, alert, crit, err:
  601. if c := l.Check(zapcore.ErrorLevel, m); c != nil {
  602. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  603. }
  604. case warning:
  605. if c := l.Check(zapcore.WarnLevel, m); c != nil {
  606. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  607. }
  608. case debug:
  609. if c := l.Check(zapcore.DebugLevel, m); c != nil {
  610. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  611. }
  612. default:
  613. if c := l.Check(zapcore.InfoLevel, m); c != nil {
  614. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  615. }
  616. }
  617. }
  618. // ExecuteScriptCLI executes the PHP script passed as parameter.
  619. // It returns the exit status code of the script.
  620. func ExecuteScriptCLI(script string, args []string) int {
  621. cScript := C.CString(script)
  622. defer C.free(unsafe.Pointer(cScript))
  623. argc, argv := convertArgs(args)
  624. defer freeArgs(argv)
  625. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  626. }
  627. func convertArgs(args []string) (C.int, []*C.char) {
  628. argc := C.int(len(args))
  629. argv := make([]*C.char, argc)
  630. for i, arg := range args {
  631. argv[i] = C.CString(arg)
  632. }
  633. return argc, argv
  634. }
  635. func freeArgs(argv []*C.char) {
  636. for _, arg := range argv {
  637. C.free(unsafe.Pointer(arg))
  638. }
  639. }
  640. func executePHPFunction(functionName string) {
  641. cFunctionName := C.CString(functionName)
  642. defer C.free(unsafe.Pointer(cFunctionName))
  643. success := C.frankenphp_execute_php_function(cFunctionName)
  644. if success == 1 {
  645. if c := logger.Check(zapcore.DebugLevel, "php function call successful"); c != nil {
  646. c.Write(zap.String("function", functionName))
  647. }
  648. } else {
  649. if c := logger.Check(zapcore.ErrorLevel, "php function call failed"); c != nil {
  650. c.Write(zap.String("function", functionName))
  651. }
  652. }
  653. }
  654. // Ensure that the request path does not contain null bytes
  655. func requestIsValid(r *http.Request, rw http.ResponseWriter) bool {
  656. if !strings.Contains(r.URL.Path, "\x00") {
  657. return true
  658. }
  659. rejectRequest(rw, "Invalid request path")
  660. return false
  661. }
  662. func rejectRequest(rw http.ResponseWriter, message string) {
  663. rw.WriteHeader(http.StatusBadRequest)
  664. _, _ = rw.Write([]byte(message))
  665. rw.(http.Flusher).Flush()
  666. }