frankenphp.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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)
  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_putenv
  423. func go_putenv(str *C.char, length C.int) C.bool {
  424. // Create a byte slice from C string with a specified length
  425. s := C.GoBytes(unsafe.Pointer(str), length)
  426. // Convert byte slice to string
  427. envString := string(s)
  428. // Check if '=' is present in the string
  429. if key, val, found := strings.Cut(envString, "="); found {
  430. if os.Setenv(key, val) != nil {
  431. return false // Failure
  432. }
  433. } else {
  434. // No '=', unset the environment variable
  435. if os.Unsetenv(envString) != nil {
  436. return false // Failure
  437. }
  438. }
  439. return true // Success
  440. }
  441. //export go_getfullenv
  442. func go_getfullenv(threadIndex C.uintptr_t) (*C.go_string, C.size_t) {
  443. thread := phpThreads[threadIndex]
  444. env := os.Environ()
  445. goStrings := make([]C.go_string, len(env)*2)
  446. for i, envVar := range env {
  447. key, val, _ := strings.Cut(envVar, "=")
  448. k := unsafe.StringData(key)
  449. v := unsafe.StringData(val)
  450. thread.Pin(k)
  451. thread.Pin(v)
  452. goStrings[i*2] = C.go_string{C.size_t(len(key)), (*C.char)(unsafe.Pointer(k))}
  453. goStrings[i*2+1] = C.go_string{C.size_t(len(val)), (*C.char)(unsafe.Pointer(v))}
  454. }
  455. value := unsafe.SliceData(goStrings)
  456. thread.Pin(value)
  457. return value, C.size_t(len(env))
  458. }
  459. //export go_getenv
  460. func go_getenv(threadIndex C.uintptr_t, name *C.go_string) (C.bool, *C.go_string) {
  461. thread := phpThreads[threadIndex]
  462. // Create a byte slice from C string with a specified length
  463. envName := C.GoStringN(name.data, C.int(name.len))
  464. // Get the environment variable value
  465. envValue, exists := os.LookupEnv(envName)
  466. if !exists {
  467. // Environment variable does not exist
  468. return false, nil // Return 0 to indicate failure
  469. }
  470. // Convert Go string to C string
  471. val := unsafe.StringData(envValue)
  472. thread.Pin(val)
  473. value := &C.go_string{C.size_t(len(envValue)), (*C.char)(unsafe.Pointer(val))}
  474. thread.Pin(value)
  475. return true, value // Return 1 to indicate success
  476. }
  477. //export go_sapi_getenv
  478. func go_sapi_getenv(threadIndex C.uintptr_t, name *C.go_string) *C.char {
  479. envName := C.GoStringN(name.data, C.int(name.len))
  480. envValue, exists := os.LookupEnv(envName)
  481. if !exists {
  482. return nil
  483. }
  484. return phpThreads[threadIndex].pinCString(envValue)
  485. }
  486. //export go_handle_request
  487. func go_handle_request(threadIndex C.uintptr_t) bool {
  488. select {
  489. case <-done:
  490. return false
  491. case r := <-requestChan:
  492. thread := phpThreads[threadIndex]
  493. thread.mainRequest = r
  494. fc, ok := FromContext(r.Context())
  495. if !ok {
  496. panic(InvalidRequestError)
  497. }
  498. defer func() {
  499. maybeCloseContext(fc)
  500. thread.mainRequest = nil
  501. thread.Unpin()
  502. }()
  503. if err := updateServerContext(thread, r, true, false); err != nil {
  504. rejectRequest(fc.responseWriter, err.Error())
  505. return true
  506. }
  507. // scriptFilename is freed in frankenphp_execute_script()
  508. fc.exitStatus = C.frankenphp_execute_script(C.CString(fc.scriptFilename))
  509. if fc.exitStatus < 0 {
  510. panic(ScriptExecutionError)
  511. }
  512. return true
  513. }
  514. }
  515. func maybeCloseContext(fc *FrankenPHPContext) {
  516. fc.closed.Do(func() {
  517. close(fc.done)
  518. })
  519. }
  520. //export go_ub_write
  521. func go_ub_write(threadIndex C.uintptr_t, cBuf *C.char, length C.int) (C.size_t, C.bool) {
  522. r := phpThreads[threadIndex].getActiveRequest()
  523. fc, _ := FromContext(r.Context())
  524. var writer io.Writer
  525. if fc.responseWriter == nil {
  526. var b bytes.Buffer
  527. // log the output of the worker
  528. writer = &b
  529. } else {
  530. writer = fc.responseWriter
  531. }
  532. i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length))
  533. if e != nil {
  534. if c := fc.logger.Check(zapcore.ErrorLevel, "write error"); c != nil {
  535. c.Write(zap.Error(e))
  536. }
  537. }
  538. if fc.responseWriter == nil {
  539. fc.logger.Info(writer.(*bytes.Buffer).String())
  540. }
  541. return C.size_t(i), C.bool(clientHasClosed(r))
  542. }
  543. // There are around 60 common request headers according to https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
  544. // Give some space for custom headers
  545. var headerKeyCache = func() otter.Cache[string, string] {
  546. c, err := otter.MustBuilder[string, string](256).Build()
  547. if err != nil {
  548. panic(err)
  549. }
  550. return c
  551. }()
  552. //export go_apache_request_headers
  553. func go_apache_request_headers(threadIndex C.uintptr_t, hasActiveRequest bool) (*C.go_string, C.size_t) {
  554. thread := phpThreads[threadIndex]
  555. if !hasActiveRequest {
  556. // worker mode, not handling a request
  557. mfc := thread.mainRequest.Context().Value(contextKey).(*FrankenPHPContext)
  558. if c := mfc.logger.Check(zapcore.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil {
  559. c.Write(zap.String("worker", mfc.scriptFilename))
  560. }
  561. return nil, 0
  562. }
  563. r := thread.getActiveRequest()
  564. headers := make([]C.go_string, 0, len(r.Header)*2)
  565. for field, val := range r.Header {
  566. fd := unsafe.StringData(field)
  567. thread.Pin(fd)
  568. cv := strings.Join(val, ", ")
  569. vd := unsafe.StringData(cv)
  570. thread.Pin(vd)
  571. headers = append(
  572. headers,
  573. C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))},
  574. C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))},
  575. )
  576. }
  577. sd := unsafe.SliceData(headers)
  578. thread.Pin(sd)
  579. return sd, C.size_t(len(r.Header))
  580. }
  581. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  582. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  583. if len(parts) != 2 {
  584. if c := fc.logger.Check(zapcore.DebugLevel, "invalid header"); c != nil {
  585. c.Write(zap.String("header", parts[0]))
  586. }
  587. return
  588. }
  589. fc.responseWriter.Header().Add(parts[0], parts[1])
  590. }
  591. //export go_write_headers
  592. func go_write_headers(threadIndex C.uintptr_t, status C.int, headers *C.zend_llist) {
  593. r := phpThreads[threadIndex].getActiveRequest()
  594. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  595. if fc.responseWriter == nil {
  596. return
  597. }
  598. current := headers.head
  599. for current != nil {
  600. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  601. addHeader(fc, h.header, C.int(h.header_len))
  602. current = current.next
  603. }
  604. fc.responseWriter.WriteHeader(int(status))
  605. if status >= 100 && status < 200 {
  606. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  607. h := fc.responseWriter.Header()
  608. for k := range h {
  609. delete(h, k)
  610. }
  611. }
  612. }
  613. //export go_sapi_flush
  614. func go_sapi_flush(threadIndex C.uintptr_t) bool {
  615. r := phpThreads[threadIndex].getActiveRequest()
  616. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  617. if fc.responseWriter == nil || clientHasClosed(r) {
  618. return true
  619. }
  620. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  621. if c := fc.logger.Check(zapcore.ErrorLevel, "the current responseWriter is not a flusher"); c != nil {
  622. c.Write(zap.Error(err))
  623. }
  624. }
  625. return false
  626. }
  627. //export go_read_post
  628. func go_read_post(threadIndex C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  629. r := phpThreads[threadIndex].getActiveRequest()
  630. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  631. var err error
  632. for readBytes < countBytes && err == nil {
  633. var n int
  634. n, err = r.Body.Read(p[readBytes:])
  635. readBytes += C.size_t(n)
  636. }
  637. return
  638. }
  639. //export go_read_cookies
  640. func go_read_cookies(threadIndex C.uintptr_t) *C.char {
  641. r := phpThreads[threadIndex].getActiveRequest()
  642. cookies := r.Cookies()
  643. if len(cookies) == 0 {
  644. return nil
  645. }
  646. cookieStrings := make([]string, len(cookies))
  647. for i, cookie := range cookies {
  648. cookieStrings[i] = cookie.String()
  649. }
  650. // freed in frankenphp_free_request_context()
  651. return C.CString(strings.Join(cookieStrings, "; "))
  652. }
  653. //export go_log
  654. func go_log(message *C.char, level C.int) {
  655. l := getLogger()
  656. m := C.GoString(message)
  657. var le syslogLevel
  658. if level < C.int(emerg) || level > C.int(debug) {
  659. le = info
  660. } else {
  661. le = syslogLevel(level)
  662. }
  663. switch le {
  664. case emerg, alert, crit, err:
  665. if c := l.Check(zapcore.ErrorLevel, m); c != nil {
  666. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  667. }
  668. case warning:
  669. if c := l.Check(zapcore.WarnLevel, m); c != nil {
  670. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  671. }
  672. case debug:
  673. if c := l.Check(zapcore.DebugLevel, m); c != nil {
  674. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  675. }
  676. default:
  677. if c := l.Check(zapcore.InfoLevel, m); c != nil {
  678. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  679. }
  680. }
  681. }
  682. // ExecuteScriptCLI executes the PHP script passed as parameter.
  683. // It returns the exit status code of the script.
  684. func ExecuteScriptCLI(script string, args []string) int {
  685. cScript := C.CString(script)
  686. defer C.free(unsafe.Pointer(cScript))
  687. argc, argv := convertArgs(args)
  688. defer freeArgs(argv)
  689. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  690. }
  691. func convertArgs(args []string) (C.int, []*C.char) {
  692. argc := C.int(len(args))
  693. argv := make([]*C.char, argc)
  694. for i, arg := range args {
  695. argv[i] = C.CString(arg)
  696. }
  697. return argc, argv
  698. }
  699. func freeArgs(argv []*C.char) {
  700. for _, arg := range argv {
  701. C.free(unsafe.Pointer(arg))
  702. }
  703. }
  704. func executePHPFunction(functionName string) {
  705. cFunctionName := C.CString(functionName)
  706. defer C.free(unsafe.Pointer(cFunctionName))
  707. success := C.frankenphp_execute_php_function(cFunctionName)
  708. if success == 1 {
  709. if c := logger.Check(zapcore.DebugLevel, "php function call successful"); c != nil {
  710. c.Write(zap.String("function", functionName))
  711. }
  712. } else {
  713. if c := logger.Check(zapcore.ErrorLevel, "php function call failed"); c != nil {
  714. c.Write(zap.String("function", functionName))
  715. }
  716. }
  717. }
  718. // Ensure that the request path does not contain null bytes
  719. func requestIsValid(r *http.Request, rw http.ResponseWriter) bool {
  720. if !strings.Contains(r.URL.Path, "\x00") {
  721. return true
  722. }
  723. rejectRequest(rw, "Invalid request path")
  724. return false
  725. }
  726. func rejectRequest(rw http.ResponseWriter, message string) {
  727. rw.WriteHeader(http.StatusBadRequest)
  728. _, _ = rw.Write([]byte(message))
  729. rw.(http.Flusher).Flush()
  730. }