frankenphp.go 22 KB

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