diff --git a/caddy/br.go b/caddy/br.go index 6522cb67a4..c6991ca1af 100644 --- a/caddy/br.go +++ b/caddy/br.go @@ -2,4 +2,21 @@ package caddy +import ( + "runtime/debug" + + "github.com/dunglas/frankenphp" +) + var brotli = true + +func init() { + if buildInfo, ok := debug.ReadBuildInfo(); ok { + for _, dep := range buildInfo.Deps { + if dep.Path == "github.com/dunglas/caddy-cbrotli" { + frankenphp.AddPHPInfoModule("dunglas/caddy-cbrotli", dep) + break + } + } + } +} diff --git a/caddy/caddy.go b/caddy/caddy.go index 24c5011900..ed1ad5fde0 100644 --- a/caddy/caddy.go +++ b/caddy/caddy.go @@ -9,6 +9,7 @@ import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" + "github.com/dunglas/frankenphp" ) const ( @@ -26,6 +27,14 @@ func init() { caddy.RegisterModule(&FrankenPHPModule{}) caddy.RegisterModule(&FrankenPHPAdmin{}) + // Report Caddy version in phpinfo() + simpleVersion, fullVersion := caddy.Version() + if fullVersion != "" { + frankenphp.AddPHPInfoEntry("caddy", fullVersion) + } else if simpleVersion != "" { + frankenphp.AddPHPInfoEntry("caddy", simpleVersion) + } + httpcaddyfile.RegisterGlobalOption("frankenphp", parseGlobalOption) httpcaddyfile.RegisterHandlerDirective("php", parseCaddyfile) diff --git a/cli.go b/cli.go index a96153a14a..9e02c8497e 100644 --- a/cli.go +++ b/cli.go @@ -9,6 +9,7 @@ import "unsafe" func ExecuteScriptCLI(script string, args []string) int { // Ensure extensions are registered before CLI execution registerExtensions() + initPHPInfoEntries() cScript := C.CString(script) defer C.free(unsafe.Pointer(cScript)) diff --git a/cli_linux_test.go b/cli_linux_test.go new file mode 100644 index 0000000000..3354545f7c --- /dev/null +++ b/cli_linux_test.go @@ -0,0 +1,118 @@ +//go:build linux + +package frankenphp_test + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +func TestExecuteScriptCLIDetachedChild(t *testing.T) { + const helperEnv = "FRANKENPHP_TEST_DETACHED_CHILD" + dir := os.Getenv(helperEnv) + if dir == "" { + if _, err := os.Stat("internal/testcli/testcli"); err != nil { + t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`") + } + self, err := os.Executable() + require.NoError(t, err) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, self, "-test.run=^TestExecuteScriptCLIDetachedChild$", "-test.v") + cmd.Env = append(os.Environ(), helperEnv+"="+t.TempDir()) + cmd.WaitDelay = time.Second + output, err := cmd.CombinedOutput() + var exitError *exec.ExitError + if errors.As(err, &exitError) && exitError.ExitCode() == 77 { + t.Skipf("pcntl/posix unavailable: %s", output) + } + require.NoError(t, err, "%s", output) + return + } + + // PDEATHSIG and subreapers are Linux-specific. Isolate adoption from other tests. + require.NoError(t, unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0)) + input, release, err := os.Pipe() + require.NoError(t, err) + defer func() { _ = input.Close() }() + pid := 0 + t.Cleanup(func() { + // EOF also releases a child whose PID was not reported before a parent failure. + _ = release.Close() + if pid > 0 { + _ = unix.Kill(pid, unix.SIGKILL) + } + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + var status unix.WaitStatus + _, err := unix.Wait4(-1, &status, unix.WNOHANG, nil) + if errors.Is(err, unix.ECHILD) { + return + } + if err != nil && !errors.Is(err, unix.EINTR) { + t.Errorf("reaping detached child: %v", err) + return + } + time.Sleep(10 * time.Millisecond) + } + t.Error("detached child cleanup timed out") + }) + + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + ready := filepath.Join(dir, "ready") + _, err = os.Lstat(ready) + require.ErrorIs(t, err, os.ErrNotExist, "readiness path must not already exist") + cmd := exec.CommandContext(ctx, "internal/testcli/testcli", "testdata/command-detached.php") + // PHP's emulated and native CLIs expose different script argv layouts. + cmd.Env = append(os.Environ(), "FRANKENPHP_TEST_DETACHED_READY="+ready) + cmd.Stdin = input + cmd.WaitDelay = time.Second + output, err := cmd.CombinedOutput() + var exitError *exec.ExitError + if errors.As(err, &exitError) && exitError.ExitCode() == 2 { + // The fixture checks extensions before forking, so nothing needs reaping. + t.Logf("%s", output) + os.Exit(77) + } + for _, line := range strings.Split(string(output), "\n") { + if strings.HasPrefix(line, "CHILD=") { + pid, _ = strconv.Atoi(strings.TrimPrefix(line, "CHILD=")) + } + } + require.NoError(t, err, "CLI parent: %s", output) + require.Greater(t, pid, 0, "no child PID: %s", output) + + // CombinedOutput has waited for the actual CLI parent exit, not just readiness. + // The CLI joins its PHP thread before exiting, so this also covers Linux's + // PDEATHSIG on the forking thread's exit rather than the whole process's exit. + _, writeErr := release.WriteString("survived\n") + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + var status unix.WaitStatus + got, err := unix.Wait4(pid, &status, unix.WNOHANG, nil) + if errors.Is(err, unix.EINTR) { + continue + } + require.NoError(t, err) + if got == pid { + pid = 0 // Reaped: cleanup must not signal a potentially reused PID. + require.True(t, status.Exited(), "detached child terminated by signal %d (%s)", status.Signal(), status.Signal()) + require.Equal(t, 0, status.ExitStatus(), "detached child failed") + require.NoError(t, writeErr) + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatal("detached child did not finish after CLI parent exited") +} diff --git a/cli_test.go b/cli_test.go index 56d88a92d9..742449b2e4 100644 --- a/cli_test.go +++ b/cli_test.go @@ -1,15 +1,20 @@ package frankenphp_test import ( + "context" "errors" + "fmt" "log" "os" "os/exec" + "path/filepath" "runtime" "testing" + "time" "github.com/dunglas/frankenphp" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestExecuteScriptCLI(t *testing.T) { @@ -45,8 +50,30 @@ func TestExecuteCLICode(t *testing.T) { assert.Equal(t, stdoutStderrStr, `Hello World`) } +// The CLI must print phpinfo() as plain text, like the CLI SAPI does. +func TestExecuteCLICodePHPInfoAsText(t *testing.T) { + if _, err := os.Stat("internal/testcli/testcli"); err != nil { + t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`") + } + + cmd := exec.Command("internal/testcli/testcli", "-r", "phpinfo();") + stdoutStderr, err := cmd.CombinedOutput() + assert.NoError(t, err) + + stdoutStderrStr := string(stdoutStderr) + + assert.Contains(t, stdoutStderrStr, "PHP Version => ") + assert.Contains(t, stdoutStderrStr, "frankenphp => ") + assert.Contains(t, stdoutStderrStr, "go => go") + assert.Contains(t, stdoutStderrStr, "Go modules") + assert.Contains(t, stdoutStderrStr, "Module => Version") + assert.NotContains(t, stdoutStderrStr, "") + assert.NotContains(t, stdoutStderrStr, "
") +} + // `-i` (and any other invocation without a script) is only supported since PHP -// 8.6, where the real CLI SAPI is reused. older versions must fail cleanly. +// 8.6, where the real CLI SAPI is reused. Older versions must fail cleanly. func TestExecuteCLIPHPInfo(t *testing.T) { if _, err := os.Stat("internal/testcli/testcli"); err != nil { t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`") @@ -93,6 +120,284 @@ func TestExecuteScriptCLISignals(t *testing.T) { assert.Contains(t, string(stdoutStderr), "ok") } +func TestExecuteCLIEnvironment(t *testing.T) { + if _, err := os.Stat("internal/testcli/testcli"); err != nil { + t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`") + } + + t.Setenv("FRANKENPHP_CLI_ENVIRONMENT_TEST", "inherited") + for _, tt := range []struct { + name string + code string + want string + }{ + { + name: "getenv named", + code: `echo json_encode([getenv($name), getenv($name, true)]);`, + want: `["inherited","inherited"]`, + }, + { + name: "getenv all", + code: ` +$env = getenv(); +$localEnv = getenv(null, true); +echo json_encode([is_array($env), $env[$name], is_array($localEnv), $localEnv[$name]]);`, + want: `[true,"inherited",true,"inherited"]`, + }, + { + name: "putenv", + code: ` +$results = [putenv($name . "=changed=value"), getenv($name), getenv($name, true), getenv()[$name]]; +$results[] = putenv($name . "="); +$results[] = getenv($name); +$results[] = array_key_exists($name, getenv()); +$results[] = putenv($name); +$results[] = getenv($name); +$results[] = getenv($name, true); +$results[] = array_key_exists($name, getenv()); +echo json_encode($results);`, + want: `[true,"changed=value","changed=value","changed=value",true,"",true,true,false,false,false]`, + }, + } { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + cmd := exec.CommandContext(ctx, "internal/testcli/testcli", "-n", "-r", `$name = "FRANKENPHP_CLI_ENVIRONMENT_TEST"; `+tt.code) + cmd.WaitDelay = time.Second + output, err := cmd.CombinedOutput() + require.NoError(t, ctx.Err(), "CLI timed out; output: %s", output) + require.NoError(t, err, "output: %s", output) + require.Equal(t, tt.want, string(output)) + }) + } +} + +func TestExecuteCLIHTTPFunctionsUnavailable(t *testing.T) { + if _, err := os.Stat("internal/testcli/testcli"); err != nil { + t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`") + } + + for _, tt := range []struct { + name string + args string + }{ + {"getallheaders", ""}, + {"apache_request_headers", ""}, + {"fastcgi_finish_request", ""}, + {"frankenphp_request_headers", ""}, + {"frankenphp_response_headers", ""}, + {"apache_response_headers", ""}, + {"frankenphp_finish_request", ""}, + {"frankenphp_handle_request", "static function () {}"}, + {"headers_send", "103"}, + {"mercure_publish", "'https://example.com/topic', 'test'"}, + {"frankenphp_log", "'CLI feature detection'"}, + } { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + + // Frameworks call these after feature detection. Exposing HTTP + // callbacks in CLI can access missing Go threads or a foreign SAPI context. + code := fmt.Sprintf(` +$function = %q; +if (function_exists($function)) { + $function(%s); +} +var_export(function_exists($function)); +`, tt.name, tt.args) + cmd := exec.CommandContext(ctx, "internal/testcli/testcli", "-r", code) + cmd.WaitDelay = time.Second + output, err := cmd.CombinedOutput() + require.NoError(t, ctx.Err(), "output: %s", output) + require.NoError(t, err, "output: %s", output) + require.Equal(t, "false", string(output)) + }) + } +} + +func TestExecuteCLINativeHTTPFunctions(t *testing.T) { + if _, err := os.Stat("internal/testcli/testcli"); err != nil { + t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`") + } + + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "internal/testcli/testcli", "-r", ` +if (PHP_SAPI !== 'cli') { + throw new RuntimeException('Expected ordinary CLI'); +} +foreach (['header', 'header_remove', 'headers_list', 'headers_sent', + 'http_response_code', 'flush', 'connection_status', + 'connection_aborted', 'ignore_user_abort'] as $function) { + if (!function_exists($function)) { + throw new RuntimeException('Missing native function: ' . $function); + } +} +header('X-CLI-Test: test'); +header_remove('X-CLI-Test'); +headers_list(); +headers_sent(); +http_response_code(204); +flush(); +connection_status(); +connection_aborted(); +ignore_user_abort(false); +// Older PHP versions use the embed SAPI rather than the native CLI SAPI. +if (PHP_VERSION_ID >= 80600) { + foreach (['dl', 'cli_set_process_title', 'cli_get_process_title'] as $function) { + if (!function_exists($function)) { + throw new RuntimeException('Missing native CLI function: ' . $function); + } + } +} +echo 'ok'; +`) + cmd.WaitDelay = time.Second + output, err := cmd.CombinedOutput() + require.NoError(t, ctx.Err(), "output: %s", output) + require.NoError(t, err, "output: %s", output) + require.Equal(t, "ok", string(output)) +} + +func TestExecuteScriptCLILifecycle(t *testing.T) { + const childEnv = "FRANKENPHP_CLI_LIFECYCLE_CHILD" + if scenario := os.Getenv(childEnv); scenario != "" { + calls := 1 + switch scenario { + case "repeated": + calls = 2 + case "rejected-then-script": + // Missing -r code is rejected before PHP startup by the pre-8.6 + // emulation, but still installs the module registration hook. + args := []string{"cli-lifecycle", "-n", "-r"} + if status := frankenphp.ExecuteScriptCLI(args[0], args); status == 0 { + t.Fatal("CLI accepted -r without code") + } + default: + t.Fatalf("unknown CLI lifecycle scenario %q", scenario) + } + + for i := 1; i <= calls; i++ { + code := fmt.Sprintf("file_put_contents('cli-lifecycle-script-%d', 'executed'); exit(%d);", i, 20+i) + args := []string{"cli-lifecycle", "-n", "-r", code} + if status := frankenphp.ExecuteScriptCLI(args[0], args); status != 20+i { + t.Fatalf("CLI call %d returned %d, want %d", i, status, 20+i) + } + } + // Older CLI emulation closes standard streams at shutdown. Use the + // process exit status rather than the test runner's final output. + os.Exit(0) + } + + for _, scenario := range []string{"repeated", "rejected-then-script"} { + t.Run(scenario, func(t *testing.T) { + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + // Keep PHP's process-global CLI lifecycle out of server tests, and + // bound both a recursive-hook crash and a hung child. + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, self, "-test.run=^TestExecuteScriptCLILifecycle$") + cmd.Env = append(os.Environ(), childEnv+"="+scenario) + // File markers survive pre-8.6 CLI shutdown closing standard streams. + cmd.Dir = t.TempDir() + cmd.WaitDelay = time.Second + output, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("CLI lifecycle child failed: %v (context: %v)\n%s", err, ctx.Err(), output) + } + calls := 1 + if scenario == "repeated" { + calls = 2 + } + for i := 1; i <= calls; i++ { + marker := filepath.Join(cmd.Dir, fmt.Sprintf("cli-lifecycle-script-%d", i)) + if content, err := os.ReadFile(marker); err != nil || string(content) != "executed" { + t.Fatalf("CLI lifecycle child did not execute script %d: marker %q, error %v\n%s", i, content, err, output) + } + } + }) + } +} + +func TestExecuteCLIOpcacheReset(t *testing.T) { + if _, err := os.Stat("internal/testcli/testcli"); err != nil { + t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`") + } + + for _, tt := range []struct { + name string + enableCLI string + code string + want string + }{ + { + name: "disabled", + enableCLI: "0", + code: `echo json_encode([ini_get('opcache.enable_cli'), opcache_reset()]);`, + want: `["0",false]`, + }, + { + name: "enabled", + enableCLI: "1", + // Native reset schedules a restart at request shutdown, not an + // immediate cache flush. Inspecting the pending flag needs no fixture. + code: ` +$before = opcache_get_status(false); +$reset = opcache_reset(); +$after = opcache_get_status(false); +echo json_encode([ini_get('opcache.enable_cli'), $before['opcache_enabled'], + $before['restart_pending'], $reset, $after['restart_pending']]);`, + want: `["1",true,false,true,true]`, + }, + } { + t.Run(tt.name, func(t *testing.T) { + // The emulated CLI (PHP < 8.6) does not parse -d or -n. Use an + // isolated INI instead, including an empty scan directory. + iniPath := filepath.Join(t.TempDir(), "php.ini") + t.Setenv("PHPRC", iniPath) + t.Setenv("PHP_INI_SCAN_DIR", t.TempDir()) + ini := "opcache.enable=1\nopcache.enable_cli=" + tt.enableCLI + "\n" + + "opcache.file_cache_only=0\nopcache.restrict_api=\nopcache.jit=disable\n" + code := ` +if (!extension_loaded('Zend OPcache')) { + fwrite(STDERR, "OPcache is not loaded\n"); + exit(77); +} +` + tt.code + + // PHP 8.5+ includes OPcache; older builds may link it statically + // or provide a shared extension. Do not load a static extension twice. + for _, shared := range []bool{false, true} { + config := ini + if shared { + config += "zend_extension=opcache\n" + } + require.NoError(t, os.WriteFile(iniPath, []byte(config), 0o600)) + + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + cmd := exec.CommandContext(ctx, "internal/testcli/testcli", "-r", code) + cmd.WaitDelay = time.Second + output, err := cmd.CombinedOutput() + cancel() + if exitError, ok := errors.AsType[*exec.ExitError](err); ok && exitError.ExitCode() == 77 { + if shared { + t.Skipf("OPcache is unavailable, including as a shared extension: %s", output) + } + continue + } + require.NoError(t, err, "output: %s", output) + require.Equal(t, tt.want, string(output)) + return + } + }) + } +} + func ExampleExecuteScriptCLI() { if len(os.Args) <= 1 { log.Println("Usage: my-program script.php") diff --git a/emulate_php_cli.c b/emulate_php_cli.c index f33f360359..38d77260e3 100644 --- a/emulate_php_cli.c +++ b/emulate_php_cli.c @@ -165,6 +165,8 @@ void *emulate_script_cli(void *arg) { php_embed_module.name = "cli"; php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP"; php_embed_module.register_server_variables = sapi_cli_register_variables; + /* the CLI SAPI prints phpinfo() as plain text, not as HTML */ + php_embed_module.phpinfo_as_text = 1; php_embed_init(cli_args->argc, cli_args->argv); diff --git a/frankenphp.c b/frankenphp.c index 2378ac8ff6..608bf74a24 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -6,6 +6,7 @@ #include #include #include +#include #ifdef HAVE_PHP_SESSION #include #endif @@ -113,6 +114,9 @@ frankenphp_config frankenphp_get_config() { }; } +const char **frankenphp_phpinfo_entries = NULL; +const char **frankenphp_go_modules = NULL; + bool should_filter_var = 0; bool original_user_abort_setting = 0; frankenphp_interned_strings_t frankenphp_strings = {0}; @@ -1116,6 +1120,45 @@ PHP_MINIT_FUNCTION(frankenphp) { return SUCCESS; } +static void frankenphp_print_info_rows(const char **entries) { + for (int i = 0; entries[i] != NULL; i += 2) { + php_info_print_table_row(2, entries[i], entries[i + 1]); + } +} + +PHP_MINFO_FUNCTION(frankenphp) { + php_info_print_table_start(); + php_info_print_table_row(2, "frankenphp", TOSTRING(FRANKENPHP_VERSION)); + if (frankenphp_phpinfo_entries) { + frankenphp_print_info_rows(frankenphp_phpinfo_entries); + } + php_info_print_table_end(); + + if (frankenphp_go_modules == NULL) { + return; + } + + /* The list of Go modules is long, collapse it by default when rendering + * HTML */ + if (sapi_module.phpinfo_as_text) { + php_info_print_table_start(); + php_info_print_table_header(1, "Go modules"); + php_info_print_table_end(); + } else { + php_printf("
Go " + "modules\n"); + } + + php_info_print_table_start(); + php_info_print_table_header(2, "Module", "Version"); + frankenphp_print_info_rows(frankenphp_go_modules); + php_info_print_table_end(); + + if (!sapi_module.phpinfo_as_text) { + php_printf("
\n"); + } +} + static zend_module_entry frankenphp_module = { STANDARD_MODULE_HEADER, "frankenphp", @@ -1124,7 +1167,21 @@ static zend_module_entry frankenphp_module = { NULL, /* shutdown */ NULL, /* request initialization */ NULL, /* request shutdown */ - NULL, /* information */ + PHP_MINFO(frankenphp), /* information */ + TOSTRING(FRANKENPHP_VERSION), + STANDARD_MODULE_PROPERTIES}; + +/* CLI exposes the same metadata, but must keep PHP's native functions and + * avoid initializing hooks that depend on the server runtime. */ +static zend_module_entry frankenphp_cli_module = { + STANDARD_MODULE_HEADER, + "frankenphp", + NULL, /* function table */ + NULL, /* initialization */ + NULL, /* shutdown */ + NULL, /* request initialization */ + NULL, /* request shutdown */ + PHP_MINFO(frankenphp), /* information */ TOSTRING(FRANKENPHP_VERSION), STANDARD_MODULE_PROPERTIES}; @@ -1773,6 +1830,20 @@ static void *execute_script_cli(void *arg) { #endif } +static int (*previous_php_register_internal_extensions_func)(void) = NULL; + +/* frankenphp_module is passed to php_module_startup() by our own SAPI, but the + * CLI SAPIs take no additional modules: hook their module startup instead */ +static int register_frankenphp_module(void) { + if (previous_php_register_internal_extensions_func() != SUCCESS) { + return FAILURE; + } + + return zend_register_internal_module(&frankenphp_cli_module) == NULL + ? FAILURE + : SUCCESS; +} + int frankenphp_execute_script_cli(char *script, int argc, char **argv, bool eval) { pthread_t thread; @@ -1782,20 +1853,29 @@ int frankenphp_execute_script_cli(char *script, int argc, char **argv, cli_exec_args_t args = { .script = script, .argc = argc, .argv = argv, .eval = eval}; + previous_php_register_internal_extensions_func = + php_register_internal_extensions_func; + php_register_internal_extensions_func = register_frankenphp_module; + /* * Start the script in a dedicated thread to prevent conflicts between Go and * PHP signal handlers */ err = pthread_create(&thread, NULL, execute_script_cli, &args); if (err != 0) { + php_register_internal_extensions_func = + previous_php_register_internal_extensions_func; return err; } err = pthread_join(thread, &exit_status); if (err != 0) { + /* The CLI thread may still be using the hook; do not restore it yet. */ return err; } + php_register_internal_extensions_func = + previous_php_register_internal_extensions_func; return (intptr_t)exit_status; } diff --git a/frankenphp.go b/frankenphp.go index 8b19dd2285..2bad167983 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -30,6 +30,8 @@ import ( "os" "os/signal" "runtime" + "runtime/debug" + "sort" "strings" "sync" "sync/atomic" @@ -37,7 +39,7 @@ import ( "time" "unsafe" // debug on Linux - //_ "github.com/ianlancetaylor/cgosymbolizer" + // _ "github.com/ianlancetaylor/cgosymbolizer" ) type contextKeyStruct struct{} @@ -156,6 +158,122 @@ func Config() PHPConfig { } } +type phpinfoEntry struct { + key, value string +} + +var ( + phpinfoEntries []phpinfoEntry + goModuleEntries []phpinfoEntry + cPhpinfoArr []*C.char + cGoModulesArr []*C.char +) + +// Report the Go toolchain and Go module versions. +// The list is verbose, so it's displayed in a collapsed section. +func init() { + buildInfo, ok := debug.ReadBuildInfo() + if !ok { + return + } + + AddPHPInfoEntry("go", buildInfo.GoVersion) + + goModuleEntries = buildGoModuleEntries(buildInfo) +} + +func buildGoModuleEntries(buildInfo *debug.BuildInfo) []phpinfoEntry { + entries := make([]phpinfoEntry, 0, len(buildInfo.Deps)+1) + if buildInfo.Main.Path != "" { + entries = append(entries, phpinfoEntry{buildInfo.Main.Path, goModuleVersion(&buildInfo.Main)}) + } + for _, dep := range buildInfo.Deps { + entries = append(entries, phpinfoEntry{dep.Path, goModuleVersion(dep)}) + } + return entries +} + +// goModuleVersion returns the version of the given module, taking "replace" +// directives into account. +func goModuleVersion(module *debug.Module) string { + if module.Replace == nil { + return module.Version + } + + if module.Replace.Version == "" { + // Replaced by a local directory + return module.Replace.Path + } + + return module.Replace.Path + " " + module.Replace.Version +} + +// AddPHPInfoEntry adds an entry to the frankenphp section of phpinfo(). +// Call it during package initialization before Init. +func AddPHPInfoEntry(key, value string) { + phpinfoEntries = append(phpinfoEntries, phpinfoEntry{key, value}) +} + +// AddPHPInfoModule adds a component's Go module version to the frankenphp section +// of phpinfo(). Call it during package initialization before Init. +func AddPHPInfoModule(key string, module *debug.Module) { + AddPHPInfoEntry(key, goModuleVersion(module)) +} + +func initPHPInfoEntries() { + freeCEntries(cPhpinfoArr) + freeCEntries(cGoModulesArr) + + cPhpinfoArr = newCEntries(phpinfoEntries) + cGoModulesArr = newCEntries(goModuleEntries) + + C.frankenphp_phpinfo_entries = firstCEntry(cPhpinfoArr) + C.frankenphp_go_modules = firstCEntry(cGoModulesArr) +} + +// newCEntries converts entries to a null-terminated C array of key, value, key, +// value, ... sorted by key. The returned slice is backed by memory allocated by +// C, free it with freeCEntries(). +func newCEntries(entries []phpinfoEntry) []*C.char { + if len(entries) == 0 { + return nil + } + + sort.Slice(entries, func(i, j int) bool { + return entries[i].key < entries[j].key + }) + + n := 2*len(entries) + 1 + arr := (*[1 << 28]*C.char)(C.malloc(C.size_t(n) * C.size_t(unsafe.Sizeof(uintptr(0)))))[:n:n] + for i, e := range entries { + arr[2*i] = C.CString(e.key) + arr[2*i+1] = C.CString(e.value) + } + arr[n-1] = nil + + return arr +} + +func freeCEntries(arr []*C.char) { + for _, cstr := range arr { + if cstr != nil { + C.free(unsafe.Pointer(cstr)) + } + } + + if arr != nil { + C.free(unsafe.Pointer(&arr[0])) + } +} + +func firstCEntry(arr []*C.char) **C.char { + if arr == nil { + return nil + } + + return &arr[0] +} + func calculateMaxThreads(opt *opt) (numWorkers int, _ error) { maxProcs := runtime.GOMAXPROCS(0) * 2 maxThreadsFromWorkers := 0 @@ -252,6 +370,7 @@ func Init(options ...Option) error { signal.Ignore(syscall.SIGPIPE) registerExtensions() + initPHPInfoEntries() opt := &opt{} for _, o := range options { diff --git a/frankenphp.h b/frankenphp.h index 99ac0ab7ec..7ec4e17d56 100644 --- a/frankenphp.h +++ b/frankenphp.h @@ -47,6 +47,14 @@ typedef struct { #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) +/* phpinfo entries from Go - null-terminated array of key, value, key, value, + * ... */ +extern const char **frankenphp_phpinfo_entries; + +/* Go modules linked into the binary, same layout, displayed in a section + * collapsed by default */ +extern const char **frankenphp_go_modules; + typedef struct go_string { size_t len; char *data; diff --git a/frankenphp_test.go b/frankenphp_test.go index 322fccf281..8b133615b7 100644 --- a/frankenphp_test.go +++ b/frankenphp_test.go @@ -27,6 +27,7 @@ import ( "os/user" "path/filepath" "runtime" + "runtime/debug" "strconv" "strings" "sync" @@ -458,6 +459,17 @@ func testSession(t *testing.T, opts *testOptions) { }, opts) } +const phpInfoTestComponent = "test/component<&>" + +func init() { + // Register before any Init call, as required by AddPHPInfoModule's contract. + frankenphp.AddPHPInfoModule(phpInfoTestComponent, &debug.Module{ + Path: "example.com/component", + Version: "v1.0.0", + Replace: &debug.Module{Path: "example.com/fork<&>", Version: "v2.0.0"}, + }) +} + func TestPhpInfo_module(t *testing.T) { testPhpInfo(t, nil) } func TestPhpInfo_worker(t *testing.T) { testPhpInfo(t, &testOptions{workerScript: "phpinfo.php"}) } func testPhpInfo(t *testing.T, opts *testOptions) { @@ -471,6 +483,8 @@ func testPhpInfo(t *testing.T, opts *testOptions) { assert.Contains(t, body, "frankenphp") assert.Contains(t, body, fmt.Sprintf("i=%d", i)) + assert.Contains(t, body, runtime.Version()) + assert.Contains(t, body, `test/component<&> example.com/fork<&> v2.0.0 `) }, opts) } @@ -579,6 +593,11 @@ func TestException_worker(t *testing.T) { testException(t, &testOptions{workerScript: "exception.php"}) } func testException(t *testing.T, opts *testOptions) { + if opts.phpIni == nil { + opts.phpIni = map[string]string{} + } + opts.phpIni["display_errors"] = "1" + runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/exception.php?i=%d", i), handler, t) diff --git a/go.mod b/go.mod index 552a12442b..381d981e6b 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/prometheus/client_golang v1.24.1 github.com/stretchr/testify v1.12.1 golang.org/x/net v0.58.0 + golang.org/x/sys v0.47.0 ) require ( @@ -58,7 +59,6 @@ require ( go.opentelemetry.io/otel/trace v1.45.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/crypto v0.55.0 // indirect - golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.41.0 // indirect google.golang.org/protobuf v1.36.11 // indirect ) diff --git a/mercure.go b/mercure.go index 821b057915..41ae854680 100644 --- a/mercure.go +++ b/mercure.go @@ -8,11 +8,23 @@ package frankenphp import "C" import ( "log/slog" + "runtime/debug" "unsafe" "github.com/dunglas/mercure" ) +func init() { + if buildInfo, ok := debug.ReadBuildInfo(); ok { + for _, dep := range buildInfo.Deps { + if dep.Path == "github.com/dunglas/mercure" { + AddPHPInfoModule("dunglas/mercure", dep) + break + } + } + } +} + type mercureContext struct { mercureHub *mercure.Hub } diff --git a/server_test.go b/server_test.go index f297db7c29..3ad2032bbe 100644 --- a/server_test.go +++ b/server_test.go @@ -102,6 +102,7 @@ func TestServer(t *testing.T) { server2, _ := frankenphp.NewServer(testDataDir) initServers( t, + frankenphp.WithPhpIni(map[string]string{"display_errors": "1"}), frankenphp.WithServer(server1), frankenphp.WithServer(server2), frankenphp.WithWorkers("counter", testDataDir+"worker-with-counter.php", 1, frankenphp.WithWorkerServerScope(server1)), diff --git a/testdata/command-detached.php b/testdata/command-detached.php new file mode 100644 index 0000000000..bd612c0ef2 --- /dev/null +++ b/testdata/command-detached.php @@ -0,0 +1,43 @@ + "$1" && IFS= read -r result && [ "$result" = survived ]', 'detached', $ready]); + exit(1); +} + +printf("CHILD=%d\n", $pid); +$deadline = microtime(true) + 5; +do { + if (is_file($ready)) { + exit(0); + } + usleep(1000); +} while (microtime(true) < $deadline); + +fwrite(STDERR, "detached child did not exec within 5s\n"); +exit(1); diff --git a/types_test.go b/types_test.go index a08f90725e..e89bc4a516 100644 --- a/types_test.go +++ b/types_test.go @@ -2,6 +2,8 @@ package frankenphp import ( "log/slog" + "runtime/debug" + "slices" "testing" "github.com/stretchr/testify/assert" @@ -145,3 +147,118 @@ func TestNestedMixedArray(t *testing.T) { assert.Equal(t, originalArray, convertedArray, "nested mixed array should be equal after conversion") }) } + +func TestBuildGoModuleEntries(t *testing.T) { + deps := []*debug.Module{ + {Path: "example.com/dependency", Version: "v1.2.3"}, + { + Path: "example.com/replaced", + Version: "v1.0.0", + Replace: &debug.Module{Path: "example.com/fork", Version: "v1.4.0"}, + }, + { + Path: "example.com/local", + Version: "v1.0.0", + Replace: &debug.Module{Path: "../local"}, + }, + } + wantDeps := []phpinfoEntry{ + {"example.com/dependency", "v1.2.3"}, + {"example.com/replaced", "example.com/fork v1.4.0"}, + {"example.com/local", "../local"}, + } + + for _, tt := range []struct { + name string + info debug.BuildInfo + want []phpinfoEntry + }{ + { + name: "direct caddy main", + info: debug.BuildInfo{ + Main: debug.Module{Path: "github.com/dunglas/frankenphp/caddy", Version: "v1.12.7"}, + }, + want: []phpinfoEntry{{"github.com/dunglas/frankenphp/caddy", "v1.12.7"}}, + }, + { + name: "development main", + info: debug.BuildInfo{Main: debug.Module{Path: "caddy", Version: "(devel)"}}, + want: []phpinfoEntry{{"caddy", "(devel)"}}, + }, + { + name: "main without version", + info: debug.BuildInfo{Main: debug.Module{Path: "example.com/app"}}, + want: []phpinfoEntry{{"example.com/app", ""}}, + }, + { + name: "main absent", + }, + { + name: "generated command", + info: debug.BuildInfo{Path: "command-line-arguments"}, + }, + { + name: "main without path", + info: debug.BuildInfo{Main: debug.Module{Version: "(devel)"}}, + }, + { + name: "replaced main", + info: debug.BuildInfo{Main: debug.Module{ + Path: "example.com/app", + Version: "v1.0.0", + Replace: &debug.Module{Path: "example.com/app-fork", Version: "v1.1.0"}, + }}, + want: []phpinfoEntry{{"example.com/app", "example.com/app-fork v1.1.0"}}, + }, + { + name: "locally replaced main", + info: debug.BuildInfo{Main: debug.Module{ + Path: "example.com/app", + Version: "v1.0.0", + Replace: &debug.Module{Path: "../app"}, + }}, + want: []phpinfoEntry{{"example.com/app", "../app"}}, + }, + } { + t.Run(tt.name, func(t *testing.T) { + if got := buildGoModuleEntries(&tt.info); !slices.Equal(got, tt.want) { + t.Fatalf("without dependencies: got %v, want %v", got, tt.want) + } + + tt.info.Deps = deps + want := append(slices.Clone(tt.want), wantDeps...) + if got := buildGoModuleEntries(&tt.info); !slices.Equal(got, want) { + t.Fatalf("with dependencies: got %v, want %v", got, want) + } + }) + } +} + +func TestAddPHPInfoModule(t *testing.T) { + // Keep this test serial and isolate registrations from the runtime tests. + previous := phpinfoEntries + t.Cleanup(func() { phpinfoEntries = previous }) + + const key, path = "test/component", "example.com/component" + for _, tt := range []struct { + name string + replace *debug.Module + want string + }{ + {name: "unreplaced", want: "v1.2.3"}, + {name: "same module version replacement", replace: &debug.Module{Path: path, Version: "v1.2.4"}, want: path + " v1.2.4"}, + {name: "fork version replacement", replace: &debug.Module{Path: "example.com/fork", Version: "v2.0.0"}, want: "example.com/fork v2.0.0"}, + {name: "local path replacement", replace: &debug.Module{Path: "../local-component"}, want: "../local-component"}, + } { + t.Run(tt.name, func(t *testing.T) { + phpinfoEntries = nil + AddPHPInfoModule(key, &debug.Module{Path: path, Version: "v1.2.3", Replace: tt.replace}) + if len(phpinfoEntries) != 1 { + t.Fatalf("registered %d entries, want 1", len(phpinfoEntries)) + } + if got := phpinfoEntries[0]; got != (phpinfoEntry{key, tt.want}) { + t.Errorf("component entry = %#v, want key %q and version %q", got, key, tt.want) + } + }) + } +} diff --git a/watcher.go b/watcher.go index cfe133e5ab..474418aa00 100644 --- a/watcher.go +++ b/watcher.go @@ -3,12 +3,25 @@ package frankenphp import ( + "runtime/debug" "sync/atomic" "github.com/dunglas/frankenphp/internal/watcher" watcherGo "github.com/e-dant/watcher/watcher-go" ) +func init() { + // watcher doesn't expose the version, so get it from the build info. + if buildInfo, ok := debug.ReadBuildInfo(); ok { + for _, dep := range buildInfo.Deps { + if dep.Path == "github.com/e-dant/watcher" { + AddPHPInfoModule("e-dant/watcher", dep) + break + } + } + } +} + type hotReloadOpt struct { hotReload []*watcher.PatternGroup } diff --git a/worker_test.go b/worker_test.go index 10c2b669ae..8ef48bc569 100644 --- a/worker_test.go +++ b/worker_test.go @@ -76,7 +76,7 @@ func TestCannotCallHandleRequestInNonWorkerMode(t *testing.T) { body, _ := io.ReadAll(resp.Body) assert.Contains(t, string(body), "Fatal error: Uncaught RuntimeException: frankenphp_handle_request() called while not in worker mode") - }, nil) + }, &testOptions{phpIni: map[string]string{"display_errors": "1", "html_errors": "1"}}) } func TestWorkerEnv(t *testing.T) {