From b71dae9b03b292841e1be64d9d1a78d7ff332316 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Tue, 27 Feb 2024 17:03:04 +0100 Subject: [PATCH] fix: prevent crash when calling apache_request_headers() in non-HTTP context --- frankenphp.c | 2 +- frankenphp.go | 17 ++++++++++++++++- testdata/request-headers.php | 2 ++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/frankenphp.c b/frankenphp.c index 5a2aba00..bed5ed50 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -250,7 +250,7 @@ PHP_FUNCTION(frankenphp_request_headers) { frankenphp_server_context *ctx = SG(server_context); struct go_apache_request_headers_return headers = - go_apache_request_headers(ctx->current_request); + go_apache_request_headers(ctx->current_request, ctx->main_request); array_init_size(return_value, headers.r1); diff --git a/frankenphp.go b/frankenphp.go index 73dce8a0..9fe685f7 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -582,7 +582,18 @@ func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) { } //export go_apache_request_headers -func go_apache_request_headers(rh C.uintptr_t) (*C.go_string, C.size_t, C.uintptr_t) { +func go_apache_request_headers(rh, mrh C.uintptr_t) (*C.go_string, C.size_t, C.uintptr_t) { + if rh == 0 { + // worker mode, not handling a request + mr := cgo.Handle(mrh).Value().(*http.Request) + mfc := mr.Context().Value(contextKey).(*FrankenPHPContext) + + if c := mfc.logger.Check(zap.DebugLevel, "apache_request_headers() called in non-HTTP context"); c != nil { + c.Write(zap.String("worker", mfc.scriptFilename)) + } + + return nil, 0, 0 + } r := cgo.Handle(rh).Value().(*http.Request) pinner := &runtime.Pinner{} @@ -613,6 +624,10 @@ func go_apache_request_headers(rh C.uintptr_t) (*C.go_string, C.size_t, C.uintpt //export go_apache_request_cleanup func go_apache_request_cleanup(rh C.uintptr_t) { + if rh == 0 { + return + } + h := cgo.Handle(rh) p := h.Value().(*runtime.Pinner) p.Unpin() diff --git a/testdata/request-headers.php b/testdata/request-headers.php index a33cc0e7..8ac33263 100644 --- a/testdata/request-headers.php +++ b/testdata/request-headers.php @@ -1,5 +1,7 @@