frankenphp.go 22 KB

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