frankenphp.go 23 KB

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