Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 7 additions & 14 deletions caddy/php-cli.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package caddy

import (
"errors"
"os"
"path/filepath"
"strings"

caddycmd "github.com/caddyserver/caddy/v2/cmd"
"github.com/dunglas/frankenphp"
Expand All @@ -26,23 +26,16 @@ Executes a PHP script similarly to the CLI SAPI.`,
}

func cmdPHPCLI(fs caddycmd.Flags) (int, error) {
args := os.Args[2:]
if len(args) < 1 {
return 1, errors.New("the path to the PHP script is required")
}
// php's cli sapi expects the 0th arg to be the program itself, only filter out 'php-cli' arg
args := append([]string{os.Args[0]}, os.Args[2:]...)

if frankenphp.EmbeddedAppPath != "" {
if _, err := os.Stat(args[0]); err != nil {
args[0] = filepath.Join(frankenphp.EmbeddedAppPath, args[0])
if frankenphp.EmbeddedAppPath != "" && len(args) > 1 && !strings.HasPrefix(args[1], "-") && strings.HasSuffix(args[1], ".php") {
if _, err := os.Stat(args[1]); err != nil {
args[1] = filepath.Join(frankenphp.EmbeddedAppPath, args[1])
}
}

var status int
if len(args) >= 2 && args[0] == "-r" {
status = frankenphp.ExecutePHPCode(args[1])
} else {
status = frankenphp.ExecuteScriptCLI(args[0], args)
}
status := frankenphp.ExecuteScriptCLI(args)

os.Exit(status)

Expand Down
135 changes: 135 additions & 0 deletions emulate_php_cli.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
#include <SAPI.h>
#include <Zend/zend_alloc.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include <Zend/zend_types.h>
#include <errno.h>
#include <ext/spl/spl_exceptions.h>
#include <ext/standard/head.h>
#include <inttypes.h>
#include <php.h>
#include <php_config.h>
#include <php_ini.h>
#include <php_main.h>
#include <php_output.h>
#include <php_variables.h>
#include <php_version.h>
Comment on lines +1 to +16
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these are most definitely not all needed, but you can adjust that later @withinboredom


/*
* CLI code is adapted from
* https://github.com/php/php-src/blob/master/sapi/cli/php_cli.c Copyright (c)
* The PHP Group Licensed under The PHP License Original uthors: Edin Kadribasic
* <edink@php.net>, Marcus Boerger <helly@php.net> and Johannes Schlueter
* <johannes@php.net> Parts based on CGI SAPI Module by Rasmus Lerdorf, Stig
* Bakken and Zeev Suraski
*/
static void cli_register_file_handles(bool no_close) /* {{{ */
{
php_stream *s_in, *s_out, *s_err;
php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL;
zend_constant ic, oc, ec;

s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in);
s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);

if (s_in == NULL || s_out == NULL || s_err == NULL) {
if (s_in)
php_stream_close(s_in);
if (s_out)
php_stream_close(s_out);
if (s_err)
php_stream_close(s_err);
return;
}

if (no_close) {
s_in->flags |= PHP_STREAM_FLAG_NO_CLOSE;
s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
}

/*s_in_process = s_in;*/

php_stream_to_zval(s_in, &ic.value);
php_stream_to_zval(s_out, &oc.value);
php_stream_to_zval(s_err, &ec.value);

ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0);
ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0);
zend_register_constant(&ic);

ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0);
oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0);
zend_register_constant(&oc);

ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0);
ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0);
zend_register_constant(&ec);
}
/* }}} */

static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */
{
size_t len = strlen(cli_script);
char *docroot = "";

/*
* In CGI mode, we consider the environment to be a part of the server
* variables
*/
php_import_environment_variables(track_vars_array);

/* Build the special-case PHP_SELF variable for the CLI version */
register_server_variable_filtered("PHP_SELF", &cli_script, &len,
track_vars_array);
register_server_variable_filtered("SCRIPT_NAME", &cli_script, &len,
track_vars_array);

/* filenames are empty for stdin */
register_server_variable_filtered("SCRIPT_FILENAME", &cli_script, &len,
track_vars_array);
register_server_variable_filtered("PATH_TRANSLATED", &cli_script, &len,
track_vars_array);

/* just make it available */
len = 0U;
register_server_variable_filtered("DOCUMENT_ROOT", &docroot, &len,
track_vars_array);
}
/* }}} */

void *emulate_script_cli(void *arg) {
void *exit_status;
bool eval = (bool)arg;

/*
* The SAPI name "cli" is hardcoded into too many programs... let's usurp it.
*/
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;

php_embed_init(cli_argc, cli_argv);

cli_register_file_handles(false);
zend_first_try {
if (eval) {
/* evaluate the cli_script as literal PHP code (php-cli -r "...") */
zend_eval_string_ex(cli_script, NULL, "Command line code", 1);
} else {
zend_file_handle file_handle;
zend_stream_init_filename(&file_handle, cli_script);

CG(skip_shebang) = 1;
php_execute_script(&file_handle);
}
}
zend_end_try();

exit_status = (void *)(intptr_t)EG(exit_status);

php_embed_shutdown();

return exit_status;
}
1 change: 1 addition & 0 deletions emulate_php_cli.h
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
void *emulate_script_cli(void *arg);
10 changes: 10 additions & 0 deletions frankenphp.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include <php_main.h>
#include <php_output.h>
#include <php_variables.h>
#include <php_version.h>
#include <pthread.h>
#include <sapi/embed/php_embed.h>
#include <signal.h>
Expand All @@ -25,7 +26,12 @@
#elif defined(__FreeBSD__) || defined(__OpenBSD__)
#include <pthread_np.h>
#endif

#if PHP_VERSION_ID >= 85000
#include <sapi/cli/cli.h>
#else
#include "emulate_php_cli.h"
#endif

#include "_cgo_export.h"
#include "frankenphp_arginfo.h"
Expand Down Expand Up @@ -1022,7 +1028,11 @@ static int cli_argc;
static char **cli_argv;

static void *execute_script_cli(void *arg) {
#if PHP_VERSION_ID >= 85000
return (void *)(intptr_t)do_php_cli(cli_argc, cli_argv);
#else
return emulate_php_cli(arg);
#endif
}

int frankenphp_execute_script_cli(char *script, int argc, char **argv,
Expand Down
7 changes: 2 additions & 5 deletions frankenphp.go
Original file line number Diff line number Diff line change
Expand Up @@ -634,14 +634,11 @@ func go_is_context_done(threadIndex C.uintptr_t) C.bool {

// ExecuteScriptCLI executes the PHP script passed as parameter.
// It returns the exit status code of the script.
func ExecuteScriptCLI(script string, args []string) int {
cScript := C.CString(script)
defer C.free(unsafe.Pointer(cScript))

func ExecuteScriptCLI(args []string) int {
argc, argv := convertArgs(args)
defer freeArgs(argv)

return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0])), false))
return int(C.frankenphp_execute_script_cli(nil, argc, (**C.char)(unsafe.Pointer(&argv[0])), false))
}

func ExecutePHPCode(phpCode string) int {
Expand Down
2 changes: 1 addition & 1 deletion frankenphp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,7 @@ func ExampleExecuteScriptCLI() {
os.Exit(1)
}

os.Exit(frankenphp.ExecuteScriptCLI(os.Args[1], os.Args))
os.Exit(frankenphp.ExecuteScriptCLI(os.Args))
}

func BenchmarkHelloWorld(b *testing.B) {
Expand Down
6 changes: 1 addition & 5 deletions internal/testcli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,5 @@ func main() {
os.Exit(1)
}

if len(os.Args) == 3 && os.Args[1] == "-r" {
os.Exit(frankenphp.ExecutePHPCode(os.Args[2]))
}

os.Exit(frankenphp.ExecuteScriptCLI(os.Args[1], os.Args))
os.Exit(frankenphp.ExecuteScriptCLI(os.Args))
}