frankenphp.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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. //go:generate rm -Rf C-Thread-Pool/
  8. //go:generate git clone --depth=1 git@github.com:Pithikos/C-Thread-Pool.git
  9. //go:generate rm -Rf C-Thread-Pool/.git C-Thread-Pool/.github C-Thread-Pool/docs C-Thread-Pool/tests C-Thread-Pool/example.c
  10. // Use PHP includes corresponding to your PHP installation by running:
  11. //
  12. // export CGO_CFLAGS=$(php-config --includes)
  13. // export CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)"
  14. //
  15. // We also set these flags for hardening: https://github.com/docker-library/php/blob/master/8.2/bookworm/zts/Dockerfile#L57-L59
  16. // #cgo darwin pkg-config: libxml-2.0
  17. // #cgo CFLAGS: -Wall -Werror -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
  18. // #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
  19. // #cgo CFLAGS: -DTHREAD_NAME=frankenphp
  20. // #cgo linux CFLAGS: -D_GNU_SOURCE
  21. // #cgo CPPFLAGS: -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
  22. // #cgo darwin LDFLAGS: -L/opt/homebrew/opt/libiconv/lib -liconv
  23. // #cgo linux LDFLAGS: -Wl,-O1 -lresolv
  24. // #cgo LDFLAGS: -pie -L/usr/local/lib -L/usr/lib -lphp -ldl -lm -lutil
  25. // #include <stdlib.h>
  26. // #include <stdint.h>
  27. // #include <php_variables.h>
  28. // #include <zend_llist.h>
  29. // #include <SAPI.h>
  30. // #include "frankenphp.h"
  31. import "C"
  32. import (
  33. "bytes"
  34. "context"
  35. "errors"
  36. "fmt"
  37. "io"
  38. "net/http"
  39. "os"
  40. "runtime"
  41. "runtime/cgo"
  42. "strconv"
  43. "strings"
  44. "sync"
  45. "sync/atomic"
  46. "time"
  47. "unsafe"
  48. "github.com/maypok86/otter"
  49. "go.uber.org/zap"
  50. // debug on Linux
  51. //_ "github.com/ianlancetaylor/cgosymbolizer"
  52. )
  53. type contextKeyStruct struct{}
  54. type handleKeyStruct struct{}
  55. var contextKey = contextKeyStruct{}
  56. var handleKey = handleKeyStruct{}
  57. var (
  58. InvalidRequestError = errors.New("not a FrankenPHP request")
  59. AlreaydStartedError = errors.New("FrankenPHP is already started")
  60. InvalidPHPVersionError = errors.New("FrankenPHP is only compatible with PHP 8.2+")
  61. ZendSignalsError = errors.New("Zend Signals are enabled, recompile PHP with --disable-zend-signals")
  62. NotEnoughThreads = errors.New("the number of threads must be superior to the number of workers")
  63. MainThreadCreationError = errors.New("error creating the main thread")
  64. RequestContextCreationError = errors.New("error during request context creation")
  65. RequestStartupError = errors.New("error during PHP request startup")
  66. ScriptExecutionError = errors.New("error during PHP script execution")
  67. requestChan chan *http.Request
  68. done chan struct{}
  69. shutdownWG sync.WaitGroup
  70. loggerMu sync.RWMutex
  71. logger *zap.Logger
  72. )
  73. type syslogLevel int
  74. const (
  75. emerg syslogLevel = iota // system is unusable
  76. alert // action must be taken immediately
  77. crit // critical conditions
  78. err // error conditions
  79. warning // warning conditions
  80. notice // normal but significant condition
  81. info // informational
  82. debug // debug-level messages
  83. )
  84. func (l syslogLevel) String() string {
  85. switch l {
  86. case emerg:
  87. return "emerg"
  88. case alert:
  89. return "alert"
  90. case crit:
  91. return "crit"
  92. case err:
  93. return "err"
  94. case warning:
  95. return "warning"
  96. case notice:
  97. return "notice"
  98. case debug:
  99. return "debug"
  100. default:
  101. return "info"
  102. }
  103. }
  104. // FrankenPHPContext provides contextual information about the Request to handle.
  105. type FrankenPHPContext struct {
  106. documentRoot string
  107. splitPath []string
  108. env PreparedEnv
  109. logger *zap.Logger
  110. docURI string
  111. pathInfo string
  112. scriptName string
  113. scriptFilename string
  114. // Whether the request is already closed by us
  115. closed sync.Once
  116. responseWriter http.ResponseWriter
  117. exitStatus C.int
  118. done chan interface{}
  119. currentWorkerRequest cgo.Handle
  120. }
  121. func clientHasClosed(r *http.Request) bool {
  122. select {
  123. case <-r.Context().Done():
  124. return true
  125. default:
  126. return false
  127. }
  128. }
  129. // NewRequestWithContext creates a new FrankenPHP request context.
  130. func NewRequestWithContext(r *http.Request, opts ...RequestOption) (*http.Request, error) {
  131. fc := &FrankenPHPContext{
  132. done: make(chan interface{}),
  133. }
  134. for _, o := range opts {
  135. if err := o(fc); err != nil {
  136. return nil, err
  137. }
  138. }
  139. if fc.documentRoot == "" {
  140. if EmbeddedAppPath != "" {
  141. fc.documentRoot = EmbeddedAppPath
  142. } else {
  143. var err error
  144. if fc.documentRoot, err = os.Getwd(); err != nil {
  145. return nil, err
  146. }
  147. }
  148. }
  149. if fc.splitPath == nil {
  150. fc.splitPath = []string{".php"}
  151. }
  152. if fc.env == nil {
  153. fc.env = make(map[string]string)
  154. }
  155. if fc.logger == nil {
  156. fc.logger = getLogger()
  157. }
  158. if splitPos := splitPos(fc, r.URL.Path); splitPos > -1 {
  159. fc.docURI = r.URL.Path[:splitPos]
  160. fc.pathInfo = r.URL.Path[splitPos:]
  161. // Strip PATH_INFO from SCRIPT_NAME
  162. fc.scriptName = strings.TrimSuffix(r.URL.Path, fc.pathInfo)
  163. // Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875
  164. // Info: https://tools.ietf.org/html/rfc3875#section-4.1.13
  165. if fc.scriptName != "" && !strings.HasPrefix(fc.scriptName, "/") {
  166. fc.scriptName = "/" + fc.scriptName
  167. }
  168. }
  169. // SCRIPT_FILENAME is the absolute path of SCRIPT_NAME
  170. fc.scriptFilename = sanitizedPathJoin(fc.documentRoot, fc.scriptName)
  171. c := context.WithValue(r.Context(), contextKey, fc)
  172. c = context.WithValue(c, handleKey, Handles())
  173. return r.WithContext(c), nil
  174. }
  175. // FromContext extracts the FrankenPHPContext from a context.
  176. func FromContext(ctx context.Context) (fctx *FrankenPHPContext, ok bool) {
  177. fctx, ok = ctx.Value(contextKey).(*FrankenPHPContext)
  178. return
  179. }
  180. type PHPVersion struct {
  181. MajorVersion int
  182. MinorVersion int
  183. ReleaseVersion int
  184. ExtraVersion string
  185. Version string
  186. VersionID int
  187. }
  188. type PHPConfig struct {
  189. Version PHPVersion
  190. ZTS bool
  191. ZendSignals bool
  192. ZendMaxExecutionTimers bool
  193. }
  194. // Version returns infos about the PHP version.
  195. func Version() PHPVersion {
  196. cVersion := C.frankenphp_get_version()
  197. return PHPVersion{
  198. int(cVersion.major_version),
  199. int(cVersion.minor_version),
  200. int(cVersion.release_version),
  201. C.GoString(cVersion.extra_version),
  202. C.GoString(cVersion.version),
  203. int(cVersion.version_id),
  204. }
  205. }
  206. func Config() PHPConfig {
  207. cConfig := C.frankenphp_get_config()
  208. return PHPConfig{
  209. Version: Version(),
  210. ZTS: bool(cConfig.zts),
  211. ZendSignals: bool(cConfig.zend_signals),
  212. ZendMaxExecutionTimers: bool(cConfig.zend_max_execution_timers),
  213. }
  214. }
  215. // Init starts the PHP runtime and the configured workers.
  216. func Init(options ...Option) error {
  217. if requestChan != nil {
  218. return AlreaydStartedError
  219. }
  220. opt := &opt{}
  221. for _, o := range options {
  222. if err := o(opt); err != nil {
  223. return err
  224. }
  225. }
  226. if opt.logger == nil {
  227. l, err := zap.NewDevelopment()
  228. if err != nil {
  229. return err
  230. }
  231. loggerMu.Lock()
  232. logger = l
  233. loggerMu.Unlock()
  234. } else {
  235. loggerMu.Lock()
  236. logger = opt.logger
  237. loggerMu.Unlock()
  238. }
  239. maxProcs := runtime.GOMAXPROCS(0)
  240. var numWorkers int
  241. for i, w := range opt.workers {
  242. if w.num <= 0 {
  243. // https://github.com/dunglas/frankenphp/issues/126
  244. opt.workers[i].num = maxProcs * 2
  245. }
  246. numWorkers += opt.workers[i].num
  247. }
  248. if opt.numThreads <= 0 {
  249. if numWorkers >= maxProcs {
  250. // Start at least as many threads as workers, and keep a free thread to handle requests in non-worker mode
  251. opt.numThreads = numWorkers + 1
  252. } else {
  253. opt.numThreads = maxProcs
  254. }
  255. } else if opt.numThreads <= numWorkers {
  256. return NotEnoughThreads
  257. }
  258. config := Config()
  259. if config.Version.MajorVersion < 8 || (config.Version.MajorVersion == 8 && config.Version.MinorVersion < 2) {
  260. return InvalidPHPVersionError
  261. }
  262. if config.ZTS {
  263. if !config.ZendMaxExecutionTimers && runtime.GOOS == "linux" {
  264. 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`)
  265. }
  266. } else {
  267. opt.numThreads = 1
  268. 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`)
  269. }
  270. shutdownWG.Add(1)
  271. done = make(chan struct{})
  272. requestChan = make(chan *http.Request)
  273. if C.frankenphp_init(C.int(opt.numThreads), C.int(opt.numThreads-numWorkers)) != 0 {
  274. return MainThreadCreationError
  275. }
  276. if err := initWorkers(opt.workers); err != nil {
  277. return err
  278. }
  279. logger.Info("FrankenPHP started 🐘", zap.String("php_version", Version().Version), zap.Int("num_threads", opt.numThreads))
  280. if EmbeddedAppPath != "" {
  281. logger.Info("embedded PHP app 📦", zap.String("path", EmbeddedAppPath))
  282. }
  283. return nil
  284. }
  285. // Shutdown stops the workers and the PHP runtime.
  286. func Shutdown() {
  287. stopWorkers()
  288. close(done)
  289. shutdownWG.Wait()
  290. requestChan = nil
  291. // Always reset the WaitGroup to ensure we're in a clean state
  292. workersReadyWG = sync.WaitGroup{}
  293. // Remove the installed app
  294. if EmbeddedAppPath != "" {
  295. os.RemoveAll(EmbeddedAppPath)
  296. }
  297. logger.Debug("FrankenPHP shut down")
  298. }
  299. //export go_shutdown
  300. func go_shutdown() {
  301. shutdownWG.Done()
  302. }
  303. func getLogger() *zap.Logger {
  304. loggerMu.RLock()
  305. defer loggerMu.RUnlock()
  306. return logger
  307. }
  308. func updateServerContext(request *http.Request, create bool, mrh C.uintptr_t) error {
  309. fc, ok := FromContext(request.Context())
  310. if !ok {
  311. return InvalidRequestError
  312. }
  313. authUser, authPassword, ok := request.BasicAuth()
  314. var cAuthUser, cAuthPassword *C.char
  315. if ok && authPassword != "" {
  316. cAuthPassword = C.CString(authPassword)
  317. }
  318. if ok && authUser != "" {
  319. cAuthUser = C.CString(authUser)
  320. }
  321. cMethod := C.CString(request.Method)
  322. cQueryString := C.CString(request.URL.RawQuery)
  323. contentLengthStr := request.Header.Get("Content-Length")
  324. contentLength := 0
  325. if contentLengthStr != "" {
  326. var err error
  327. contentLength, err = strconv.Atoi(contentLengthStr)
  328. if err != nil {
  329. return fmt.Errorf("invalid Content-Length header: %w", err)
  330. }
  331. }
  332. contentType := request.Header.Get("Content-Type")
  333. var cContentType *C.char
  334. if contentType != "" {
  335. cContentType = C.CString(contentType)
  336. }
  337. // compliance with the CGI specification requires that
  338. // PATH_TRANSLATED should only exist if PATH_INFO is defined.
  339. // Info: https://www.ietf.org/rfc/rfc3875 Page 14
  340. var cPathTranslated *C.char
  341. if fc.pathInfo != "" {
  342. cPathTranslated = C.CString(sanitizedPathJoin(fc.documentRoot, fc.pathInfo)) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
  343. }
  344. cRequestUri := C.CString(request.URL.RequestURI())
  345. var rh cgo.Handle
  346. if fc.responseWriter == nil {
  347. h := cgo.NewHandle(request)
  348. request.Context().Value(handleKey).(*handleList).AddHandle(h)
  349. mrh = C.uintptr_t(h)
  350. } else {
  351. rh = cgo.NewHandle(request)
  352. request.Context().Value(handleKey).(*handleList).AddHandle(rh)
  353. }
  354. ret := C.frankenphp_update_server_context(
  355. C.bool(create),
  356. C.uintptr_t(rh),
  357. mrh,
  358. cMethod,
  359. cQueryString,
  360. C.zend_long(contentLength),
  361. cPathTranslated,
  362. cRequestUri,
  363. cContentType,
  364. cAuthUser,
  365. cAuthPassword,
  366. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  367. )
  368. if ret > 0 {
  369. return RequestContextCreationError
  370. }
  371. return nil
  372. }
  373. var counter int
  374. // ServeHTTP executes a PHP script according to the given context.
  375. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error {
  376. shutdownWG.Add(1)
  377. defer shutdownWG.Done()
  378. fc, ok := FromContext(request.Context())
  379. if !ok {
  380. return InvalidRequestError
  381. }
  382. fc.responseWriter = responseWriter
  383. rc := requestChan
  384. // Detect if a worker is available to handle this request
  385. if nil != fc.responseWriter {
  386. if v, ok := workersRequestChans.Load(fc.scriptFilename); ok {
  387. rc = v.(chan *http.Request)
  388. }
  389. }
  390. select {
  391. case <-done:
  392. case rc <- request:
  393. <-fc.done
  394. }
  395. return nil
  396. }
  397. //export go_fetch_request
  398. func go_fetch_request() C.uintptr_t {
  399. select {
  400. case <-done:
  401. return 0
  402. case r := <-requestChan:
  403. count := counter
  404. counter += 1
  405. logger.Warn("Fetched request", zap.Int("counter", count))
  406. r = r.WithContext(context.WithValue(r.Context(), "counter__", count))
  407. h := cgo.NewHandle(r)
  408. r.Context().Value(handleKey).(*handleList).AddHandle(h)
  409. return C.uintptr_t(h)
  410. }
  411. }
  412. func maybeCloseContext(fc *FrankenPHPContext) {
  413. fc.closed.Do(func() {
  414. close(fc.done)
  415. })
  416. }
  417. //export go_log_s
  418. func go_log_s(cstr *C.char) {
  419. // Convert C string to Go string
  420. str := C.GoString(cstr)
  421. // Log (print) the string
  422. logger.Warn(str)
  423. }
  424. var conReqs atomic.Int32
  425. //export go_fetch_and_execute
  426. func go_fetch_and_execute(rh unsafe.Pointer) {
  427. //logger.Warn("Starting fetch and execute")
  428. start := time.Now()
  429. for {
  430. select {
  431. case <-done:
  432. return
  433. case r := <-requestChan:
  434. conReqs.Add(1)
  435. logger.Warn("Executing request", zap.Int("total", int(conReqs.Load())), zap.Duration("elapsed", time.Since(start)))
  436. start = time.Now()
  437. fc, ok := FromContext(r.Context())
  438. handle := cgo.NewHandle(r)
  439. r.Context().Value(handleKey).(*handleList).AddHandle(handle)
  440. if !ok {
  441. panic(InvalidRequestError)
  442. }
  443. if err := updateServerContext(r, true, 0); err != nil {
  444. panic(err)
  445. }
  446. fc.exitStatus = C.frankenphp_execute_script(C.CString(fc.scriptFilename))
  447. if fc.exitStatus < 0 {
  448. panic(ScriptExecutionError)
  449. }
  450. maybeCloseContext(fc)
  451. r.Context().Value(handleKey).(*handleList).FreeAll()
  452. conReqs.Add(-1)
  453. logger.Warn("finished execution", zap.Int("total", int(conReqs.Load())), zap.Duration("elapsed", time.Since(start)))
  454. start = time.Now()
  455. }
  456. }
  457. }
  458. // go_execute_script Note: only called in cgi-mode and the main worker request
  459. //
  460. //export go_execute_script
  461. func go_execute_script(rh unsafe.Pointer) {
  462. handle := cgo.Handle(rh)
  463. request := handle.Value().(*http.Request)
  464. fc, ok := FromContext(request.Context())
  465. if !ok {
  466. panic(InvalidRequestError)
  467. }
  468. defer func() {
  469. maybeCloseContext(fc)
  470. request.Context().Value(handleKey).(*handleList).FreeAll()
  471. }()
  472. if err := updateServerContext(request, true, 0); err != nil {
  473. panic(err)
  474. }
  475. // scriptFilename is freed in frankenphp_execute_script()
  476. fc.exitStatus = C.frankenphp_execute_script(C.CString(fc.scriptFilename))
  477. if fc.exitStatus < 0 {
  478. panic(ScriptExecutionError)
  479. }
  480. logger.Warn("Handled request", zap.Any("counter", request.Context().Value("counter__")))
  481. }
  482. //export go_ub_write
  483. func go_ub_write(rh C.uintptr_t, cBuf *C.char, length C.int) (C.size_t, C.bool) {
  484. r := cgo.Handle(rh).Value().(*http.Request)
  485. fc, _ := FromContext(r.Context())
  486. var writer io.Writer
  487. if fc.responseWriter == nil {
  488. var b bytes.Buffer
  489. // log the output of the worker
  490. writer = &b
  491. } else {
  492. writer = fc.responseWriter
  493. }
  494. i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length))
  495. if e != nil {
  496. fc.logger.Error("write error", zap.Error(e))
  497. }
  498. if fc.responseWriter == nil {
  499. fc.logger.Info(writer.(*bytes.Buffer).String())
  500. }
  501. return C.size_t(i), C.bool(clientHasClosed(r))
  502. }
  503. // There are around 60 common request headers according to https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
  504. // Give some space for custom headers
  505. var headerKeyCache = func() otter.Cache[string, string] {
  506. c, err := otter.MustBuilder[string, string](256).Build()
  507. if err != nil {
  508. panic(err)
  509. }
  510. return c
  511. }()
  512. //export go_register_variables
  513. func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) {
  514. r := cgo.Handle(rh).Value().(*http.Request)
  515. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  516. p := &runtime.Pinner{}
  517. dynamicVariables := make([]C.php_variable, len(fc.env)+len(r.Header))
  518. var l int
  519. // Add all HTTP headers to env variables
  520. for field, val := range r.Header {
  521. k, ok := headerKeyCache.Get(field)
  522. if !ok {
  523. k = "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(field)) + "\x00"
  524. headerKeyCache.SetIfAbsent(field, k)
  525. }
  526. if _, ok := fc.env[k]; ok {
  527. continue
  528. }
  529. v := strings.Join(val, ", ")
  530. kData := unsafe.StringData(k)
  531. vData := unsafe.StringData(v)
  532. p.Pin(kData)
  533. p.Pin(vData)
  534. dynamicVariables[l]._var = (*C.char)(unsafe.Pointer(kData))
  535. dynamicVariables[l].data_len = C.size_t(len(v))
  536. dynamicVariables[l].data = (*C.char)(unsafe.Pointer(vData))
  537. l++
  538. }
  539. for k, v := range fc.env {
  540. if _, ok := knownServerKeys[k]; ok {
  541. continue
  542. }
  543. kData := unsafe.StringData(k)
  544. vData := unsafe.Pointer(unsafe.StringData(v))
  545. p.Pin(kData)
  546. p.Pin(vData)
  547. dynamicVariables[l]._var = (*C.char)(unsafe.Pointer(kData))
  548. dynamicVariables[l].data_len = C.size_t(len(v))
  549. dynamicVariables[l].data = (*C.char)(unsafe.Pointer(vData))
  550. l++
  551. }
  552. knownVariables := computeKnownVariables(r, p)
  553. dvsd := unsafe.SliceData(dynamicVariables)
  554. p.Pin(dvsd)
  555. C.frankenphp_register_bulk_variables(&knownVariables[0], dvsd, C.size_t(l), trackVarsArray)
  556. p.Unpin()
  557. fc.env = nil
  558. }
  559. //export go_apache_request_headers
  560. func go_apache_request_headers(rh, mrh C.uintptr_t) (*C.go_string, C.size_t, C.uintptr_t) {
  561. if rh == 0 {
  562. // worker mode, not handling a request
  563. mr := cgo.Handle(mrh).Value().(*http.Request)
  564. mfc := mr.Context().Value(contextKey).(*FrankenPHPContext)
  565. if c := mfc.logger.Check(zap.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil {
  566. c.Write(zap.String("worker", mfc.scriptFilename))
  567. }
  568. return nil, 0, 0
  569. }
  570. r := cgo.Handle(rh).Value().(*http.Request)
  571. pinner := &runtime.Pinner{}
  572. pinnerHandle := C.uintptr_t(cgo.NewHandle(pinner))
  573. headers := make([]C.go_string, 0, len(r.Header)*2)
  574. for field, val := range r.Header {
  575. fd := unsafe.StringData(field)
  576. pinner.Pin(fd)
  577. cv := strings.Join(val, ", ")
  578. vd := unsafe.StringData(cv)
  579. pinner.Pin(vd)
  580. headers = append(
  581. headers,
  582. C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))},
  583. C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))},
  584. )
  585. }
  586. sd := unsafe.SliceData(headers)
  587. pinner.Pin(sd)
  588. return sd, C.size_t(len(r.Header)), pinnerHandle
  589. }
  590. //export go_apache_request_cleanup
  591. func go_apache_request_cleanup(rh C.uintptr_t) {
  592. if rh == 0 {
  593. return
  594. }
  595. h := cgo.Handle(rh)
  596. p := h.Value().(*runtime.Pinner)
  597. p.Unpin()
  598. h.Delete()
  599. }
  600. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  601. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  602. if len(parts) != 2 {
  603. fc.logger.Debug("invalid header", zap.String("header", parts[0]))
  604. return
  605. }
  606. fc.responseWriter.Header().Add(parts[0], parts[1])
  607. }
  608. //export go_write_headers
  609. func go_write_headers(rh C.uintptr_t, status C.int, headers *C.zend_llist) {
  610. r := cgo.Handle(rh).Value().(*http.Request)
  611. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  612. if fc.responseWriter == nil {
  613. return
  614. }
  615. current := headers.head
  616. for current != nil {
  617. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  618. addHeader(fc, h.header, C.int(h.header_len))
  619. current = current.next
  620. }
  621. fc.responseWriter.WriteHeader(int(status))
  622. if status >= 100 && status < 200 {
  623. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  624. h := fc.responseWriter.Header()
  625. for k := range h {
  626. delete(h, k)
  627. }
  628. }
  629. }
  630. //export go_sapi_flush
  631. func go_sapi_flush(rh C.uintptr_t) bool {
  632. r := cgo.Handle(rh).Value().(*http.Request)
  633. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  634. if fc.responseWriter == nil || clientHasClosed(r) {
  635. return true
  636. }
  637. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  638. fc.logger.Error("the current responseWriter is not a flusher", zap.Error(err))
  639. }
  640. return false
  641. }
  642. //export go_read_post
  643. func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  644. r := cgo.Handle(rh).Value().(*http.Request)
  645. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  646. var err error
  647. for readBytes < countBytes && err == nil {
  648. var n int
  649. n, err = r.Body.Read(p[readBytes:])
  650. readBytes += C.size_t(n)
  651. }
  652. return
  653. }
  654. //export go_read_cookies
  655. func go_read_cookies(rh C.uintptr_t) *C.char {
  656. r := cgo.Handle(rh).Value().(*http.Request)
  657. cookies := r.Cookies()
  658. if len(cookies) == 0 {
  659. return nil
  660. }
  661. cookieStrings := make([]string, len(cookies))
  662. for i, cookie := range cookies {
  663. cookieStrings[i] = cookie.String()
  664. }
  665. // freed in frankenphp_request_shutdown()
  666. return C.CString(strings.Join(cookieStrings, "; "))
  667. }
  668. //export go_log
  669. func go_log(message *C.char, level C.int) {
  670. l := getLogger()
  671. m := C.GoString(message)
  672. var le syslogLevel
  673. if level < C.int(emerg) || level > C.int(debug) {
  674. le = info
  675. } else {
  676. le = syslogLevel(level)
  677. }
  678. switch le {
  679. case emerg, alert, crit, err:
  680. l.Error(m, zap.Stringer("syslog_level", syslogLevel(level)))
  681. case warning:
  682. l.Warn(m, zap.Stringer("syslog_level", syslogLevel(level)))
  683. case debug:
  684. l.Debug(m, zap.Stringer("syslog_level", syslogLevel(level)))
  685. default:
  686. l.Info(m, zap.Stringer("syslog_level", syslogLevel(level)))
  687. }
  688. }
  689. // ExecuteScriptCLI executes the PHP script passed as parameter.
  690. // It returns the exit status code of the script.
  691. func ExecuteScriptCLI(script string, args []string) int {
  692. cScript := C.CString(script)
  693. defer C.free(unsafe.Pointer(cScript))
  694. argc, argv := convertArgs(args)
  695. defer freeArgs(argv)
  696. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  697. }
  698. func convertArgs(args []string) (C.int, []*C.char) {
  699. argc := C.int(len(args))
  700. argv := make([]*C.char, argc)
  701. for i, arg := range args {
  702. argv[i] = C.CString(arg)
  703. }
  704. return argc, argv
  705. }
  706. func freeArgs(argv []*C.char) {
  707. for _, arg := range argv {
  708. C.free(unsafe.Pointer(arg))
  709. }
  710. }