frankenphp.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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/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(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 = C.CString(authPassword)
  338. }
  339. if ok && authUser != "" {
  340. cAuthUser = C.CString(authUser)
  341. }
  342. cMethod := C.CString(request.Method)
  343. cQueryString := C.CString(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 {
  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 = C.CString(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 = C.CString(sanitizedPathJoin(fc.documentRoot, fc.pathInfo)) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
  364. }
  365. cRequestUri := C.CString(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. shutdownWG.Add(1)
  389. defer shutdownWG.Done()
  390. fc, ok := FromContext(request.Context())
  391. if !ok {
  392. return InvalidRequestError
  393. }
  394. fc.responseWriter = responseWriter
  395. fc.startedAt = time.Now()
  396. isWorker := fc.responseWriter == nil
  397. isWorkerRequest := false
  398. rc := requestChan
  399. // Detect if a worker is available to handle this request
  400. if !isWorker {
  401. if worker, ok := workers[fc.scriptFilename]; ok {
  402. isWorkerRequest = true
  403. metrics.StartWorkerRequest(fc.scriptFilename)
  404. rc = worker.requestChan
  405. } else {
  406. metrics.StartRequest()
  407. }
  408. }
  409. select {
  410. case <-done:
  411. case rc <- request:
  412. <-fc.done
  413. }
  414. if !isWorker {
  415. if isWorkerRequest {
  416. metrics.StopWorkerRequest(fc.scriptFilename, time.Since(fc.startedAt))
  417. } else {
  418. metrics.StopRequest()
  419. }
  420. }
  421. return nil
  422. }
  423. //export go_putenv
  424. func go_putenv(str *C.char, length C.int) C.bool {
  425. // Create a byte slice from C string with a specified length
  426. s := C.GoBytes(unsafe.Pointer(str), length)
  427. // Convert byte slice to string
  428. envString := string(s)
  429. // Check if '=' is present in the string
  430. if key, val, found := strings.Cut(envString, "="); found {
  431. if os.Setenv(key, val) != nil {
  432. return false // Failure
  433. }
  434. } else {
  435. // No '=', unset the environment variable
  436. if os.Unsetenv(envString) != nil {
  437. return false // Failure
  438. }
  439. }
  440. return true // Success
  441. }
  442. //export go_getfullenv
  443. func go_getfullenv(threadIndex C.uintptr_t) (*C.go_string, C.size_t) {
  444. thread := phpThreads[threadIndex]
  445. env := os.Environ()
  446. goStrings := make([]C.go_string, len(env)*2)
  447. for i, envVar := range env {
  448. key, val, _ := strings.Cut(envVar, "=")
  449. k := unsafe.StringData(key)
  450. v := unsafe.StringData(val)
  451. thread.Pin(k)
  452. thread.Pin(v)
  453. goStrings[i*2] = C.go_string{C.size_t(len(key)), (*C.char)(unsafe.Pointer(k))}
  454. goStrings[i*2+1] = C.go_string{C.size_t(len(val)), (*C.char)(unsafe.Pointer(v))}
  455. }
  456. value := unsafe.SliceData(goStrings)
  457. thread.Pin(value)
  458. return value, C.size_t(len(env))
  459. }
  460. //export go_getenv
  461. func go_getenv(threadIndex C.uintptr_t, name *C.go_string) (C.bool, *C.go_string) {
  462. thread := phpThreads[threadIndex]
  463. // Create a byte slice from C string with a specified length
  464. envName := C.GoStringN(name.data, C.int(name.len))
  465. // Get the environment variable value
  466. envValue, exists := os.LookupEnv(envName)
  467. if !exists {
  468. // Environment variable does not exist
  469. return false, nil // Return 0 to indicate failure
  470. }
  471. // Convert Go string to C string
  472. val := unsafe.StringData(envValue)
  473. thread.Pin(val)
  474. value := &C.go_string{C.size_t(len(envValue)), (*C.char)(unsafe.Pointer(val))}
  475. thread.Pin(value)
  476. return true, value // Return 1 to indicate success
  477. }
  478. //export go_handle_request
  479. func go_handle_request(threadIndex C.uintptr_t) bool {
  480. select {
  481. case <-done:
  482. return false
  483. case r := <-requestChan:
  484. thread := phpThreads[threadIndex]
  485. thread.mainRequest = r
  486. fc, ok := FromContext(r.Context())
  487. if !ok {
  488. panic(InvalidRequestError)
  489. }
  490. defer func() {
  491. maybeCloseContext(fc)
  492. thread.mainRequest = nil
  493. thread.Unpin()
  494. }()
  495. if err := updateServerContext(r, true, false); err != nil {
  496. panic(err)
  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_register_variables
  544. func go_register_variables(threadIndex C.uintptr_t, trackVarsArray *C.zval) {
  545. thread := phpThreads[threadIndex]
  546. r := thread.getActiveRequest()
  547. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  548. dynamicVariables := make([]C.php_variable, len(fc.env)+len(r.Header))
  549. var l int
  550. // Add all HTTP headers to env variables
  551. for field, val := range r.Header {
  552. k, ok := headerKeyCache.Get(field)
  553. if !ok {
  554. k = "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(field)) + "\x00"
  555. headerKeyCache.SetIfAbsent(field, k)
  556. }
  557. if _, ok := fc.env[k]; ok {
  558. continue
  559. }
  560. v := strings.Join(val, ", ")
  561. kData := unsafe.StringData(k)
  562. vData := unsafe.StringData(v)
  563. thread.Pin(kData)
  564. thread.Pin(vData)
  565. dynamicVariables[l]._var = (*C.char)(unsafe.Pointer(kData))
  566. dynamicVariables[l].data_len = C.size_t(len(v))
  567. dynamicVariables[l].data = (*C.char)(unsafe.Pointer(vData))
  568. l++
  569. }
  570. for k, v := range fc.env {
  571. if _, ok := knownServerKeys[k]; ok {
  572. continue
  573. }
  574. kData := unsafe.StringData(k)
  575. vData := unsafe.Pointer(unsafe.StringData(v))
  576. thread.Pin(kData)
  577. thread.Pin(vData)
  578. dynamicVariables[l]._var = (*C.char)(unsafe.Pointer(kData))
  579. dynamicVariables[l].data_len = C.size_t(len(v))
  580. dynamicVariables[l].data = (*C.char)(unsafe.Pointer(vData))
  581. l++
  582. }
  583. knownVariables := computeKnownVariables(r, &thread.Pinner)
  584. dvsd := unsafe.SliceData(dynamicVariables)
  585. thread.Pin(dvsd)
  586. C.frankenphp_register_bulk_variables(&knownVariables[0], dvsd, C.size_t(l), trackVarsArray)
  587. fc.env = nil
  588. }
  589. //export go_apache_request_headers
  590. func go_apache_request_headers(threadIndex C.uintptr_t, hasActiveRequest bool) (*C.go_string, C.size_t) {
  591. thread := phpThreads[threadIndex]
  592. if !hasActiveRequest {
  593. // worker mode, not handling a request
  594. mfc := thread.mainRequest.Context().Value(contextKey).(*FrankenPHPContext)
  595. if c := mfc.logger.Check(zapcore.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil {
  596. c.Write(zap.String("worker", mfc.scriptFilename))
  597. }
  598. return nil, 0
  599. }
  600. r := thread.getActiveRequest()
  601. headers := make([]C.go_string, 0, len(r.Header)*2)
  602. for field, val := range r.Header {
  603. fd := unsafe.StringData(field)
  604. thread.Pin(fd)
  605. cv := strings.Join(val, ", ")
  606. vd := unsafe.StringData(cv)
  607. thread.Pin(vd)
  608. headers = append(
  609. headers,
  610. C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))},
  611. C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))},
  612. )
  613. }
  614. sd := unsafe.SliceData(headers)
  615. thread.Pin(sd)
  616. return sd, C.size_t(len(r.Header))
  617. }
  618. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  619. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  620. if len(parts) != 2 {
  621. if c := fc.logger.Check(zapcore.DebugLevel, "invalid header"); c != nil {
  622. c.Write(zap.String("header", parts[0]))
  623. }
  624. return
  625. }
  626. fc.responseWriter.Header().Add(parts[0], parts[1])
  627. }
  628. //export go_write_headers
  629. func go_write_headers(threadIndex C.uintptr_t, status C.int, headers *C.zend_llist) {
  630. r := phpThreads[threadIndex].getActiveRequest()
  631. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  632. if fc.responseWriter == nil {
  633. return
  634. }
  635. current := headers.head
  636. for current != nil {
  637. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  638. addHeader(fc, h.header, C.int(h.header_len))
  639. current = current.next
  640. }
  641. fc.responseWriter.WriteHeader(int(status))
  642. if status >= 100 && status < 200 {
  643. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  644. h := fc.responseWriter.Header()
  645. for k := range h {
  646. delete(h, k)
  647. }
  648. }
  649. }
  650. //export go_sapi_flush
  651. func go_sapi_flush(threadIndex C.uintptr_t) bool {
  652. r := phpThreads[threadIndex].getActiveRequest()
  653. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  654. if fc.responseWriter == nil || clientHasClosed(r) {
  655. return true
  656. }
  657. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  658. if c := fc.logger.Check(zapcore.ErrorLevel, "the current responseWriter is not a flusher"); c != nil {
  659. c.Write(zap.Error(err))
  660. }
  661. }
  662. return false
  663. }
  664. //export go_read_post
  665. func go_read_post(threadIndex C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  666. r := phpThreads[threadIndex].getActiveRequest()
  667. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  668. var err error
  669. for readBytes < countBytes && err == nil {
  670. var n int
  671. n, err = r.Body.Read(p[readBytes:])
  672. readBytes += C.size_t(n)
  673. }
  674. return
  675. }
  676. //export go_read_cookies
  677. func go_read_cookies(threadIndex C.uintptr_t) *C.char {
  678. r := phpThreads[threadIndex].getActiveRequest()
  679. cookies := r.Cookies()
  680. if len(cookies) == 0 {
  681. return nil
  682. }
  683. cookieStrings := make([]string, len(cookies))
  684. for i, cookie := range cookies {
  685. cookieStrings[i] = cookie.String()
  686. }
  687. // freed in frankenphp_free_request_context()
  688. return C.CString(strings.Join(cookieStrings, "; "))
  689. }
  690. //export go_log
  691. func go_log(message *C.char, level C.int) {
  692. l := getLogger()
  693. m := C.GoString(message)
  694. var le syslogLevel
  695. if level < C.int(emerg) || level > C.int(debug) {
  696. le = info
  697. } else {
  698. le = syslogLevel(level)
  699. }
  700. switch le {
  701. case emerg, alert, crit, err:
  702. if c := l.Check(zapcore.ErrorLevel, m); c != nil {
  703. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  704. }
  705. case warning:
  706. if c := l.Check(zapcore.WarnLevel, m); c != nil {
  707. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  708. }
  709. case debug:
  710. if c := l.Check(zapcore.DebugLevel, m); c != nil {
  711. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  712. }
  713. default:
  714. if c := l.Check(zapcore.InfoLevel, m); c != nil {
  715. c.Write(zap.Stringer("syslog_level", syslogLevel(level)))
  716. }
  717. }
  718. }
  719. // ExecuteScriptCLI executes the PHP script passed as parameter.
  720. // It returns the exit status code of the script.
  721. func ExecuteScriptCLI(script string, args []string) int {
  722. cScript := C.CString(script)
  723. defer C.free(unsafe.Pointer(cScript))
  724. argc, argv := convertArgs(args)
  725. defer freeArgs(argv)
  726. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  727. }
  728. func convertArgs(args []string) (C.int, []*C.char) {
  729. argc := C.int(len(args))
  730. argv := make([]*C.char, argc)
  731. for i, arg := range args {
  732. argv[i] = C.CString(arg)
  733. }
  734. return argc, argv
  735. }
  736. func freeArgs(argv []*C.char) {
  737. for _, arg := range argv {
  738. C.free(unsafe.Pointer(arg))
  739. }
  740. }
  741. func executePHPFunction(functionName string) {
  742. cFunctionName := C.CString(functionName)
  743. defer C.free(unsafe.Pointer(cFunctionName))
  744. success := C.frankenphp_execute_php_function(cFunctionName)
  745. if success == 1 {
  746. if c := logger.Check(zapcore.DebugLevel, "php function call successful"); c != nil {
  747. c.Write(zap.String("function", functionName))
  748. }
  749. } else {
  750. if c := logger.Check(zapcore.ErrorLevel, "php function call failed"); c != nil {
  751. c.Write(zap.String("function", functionName))
  752. }
  753. }
  754. }