frankenphp.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. #include <SAPI.h>
  2. #include <Zend/zend_alloc.h>
  3. #include <Zend/zend_exceptions.h>
  4. #include <Zend/zend_interfaces.h>
  5. #include <Zend/zend_types.h>
  6. #include <errno.h>
  7. #include <ext/spl/spl_exceptions.h>
  8. #include <ext/standard/head.h>
  9. #include <php.h>
  10. #include <php_config.h>
  11. #include <php_main.h>
  12. #include <php_output.h>
  13. #include <php_variables.h>
  14. #include <sapi/embed/php_embed.h>
  15. #include <stdint.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <unistd.h>
  19. #include "C-Thread-Pool/thpool.c"
  20. #include "C-Thread-Pool/thpool.h"
  21. #include "_cgo_export.h"
  22. #include "frankenphp_arginfo.h"
  23. #if defined(PHP_WIN32) && defined(ZTS)
  24. ZEND_TSRMLS_CACHE_DEFINE()
  25. #endif
  26. /* Timeouts are currently fundamentally broken with ZTS except on Linux:
  27. * https://bugs.php.net/bug.php?id=79464 */
  28. #ifndef ZEND_MAX_EXECUTION_TIMERS
  29. static const char HARDCODED_INI[] = "max_execution_time=0\n"
  30. "max_input_time=-1\n\0";
  31. #endif
  32. static const char *MODULES_TO_RELOAD[] = {"filter", "session", NULL};
  33. frankenphp_version frankenphp_get_version() {
  34. return (frankenphp_version){
  35. PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION,
  36. PHP_EXTRA_VERSION, PHP_VERSION, PHP_VERSION_ID,
  37. };
  38. }
  39. frankenphp_config frankenphp_get_config() {
  40. return (frankenphp_config){
  41. frankenphp_get_version(),
  42. #ifdef ZTS
  43. true,
  44. #else
  45. false,
  46. #endif
  47. #ifdef ZEND_SIGNALS
  48. true,
  49. #else
  50. false,
  51. #endif
  52. #ifdef ZEND_MAX_EXECUTION_TIMERS
  53. true,
  54. #else
  55. false,
  56. #endif
  57. };
  58. }
  59. typedef struct frankenphp_server_context {
  60. uintptr_t current_request;
  61. uintptr_t main_request;
  62. bool worker_ready;
  63. char *cookie_data;
  64. bool finished;
  65. } frankenphp_server_context;
  66. static uintptr_t frankenphp_clean_server_context() {
  67. frankenphp_server_context *ctx = SG(server_context);
  68. if (ctx == NULL) {
  69. return 0;
  70. }
  71. SG(request_info).auth_password = NULL;
  72. SG(request_info).auth_user = NULL;
  73. SG(request_info).request_method = NULL;
  74. SG(request_info).query_string = NULL;
  75. SG(request_info).content_type = NULL;
  76. SG(request_info).path_translated = NULL;
  77. SG(request_info).request_uri = NULL;
  78. return ctx->current_request;
  79. }
  80. static void frankenphp_request_reset() {
  81. zend_try {
  82. int i;
  83. for (i = 0; i < NUM_TRACK_VARS; i++) {
  84. zval_ptr_dtor(&PG(http_globals)[i]);
  85. }
  86. memset(&PG(http_globals), 0, sizeof(zval) * NUM_TRACK_VARS);
  87. }
  88. zend_end_try();
  89. }
  90. /* Adapted from php_request_shutdown */
  91. static void frankenphp_worker_request_shutdown() {
  92. /* Flush all output buffers */
  93. zend_try { php_output_end_all(); }
  94. zend_end_try();
  95. // TODO: store the list of modules to reload in a global module variable
  96. const char **module_name;
  97. zend_module_entry *module;
  98. for (module_name = MODULES_TO_RELOAD; *module_name; module_name++) {
  99. if ((module = zend_hash_str_find_ptr(&module_registry, *module_name,
  100. strlen(*module_name)))) {
  101. module->request_shutdown_func(module->type, module->module_number);
  102. }
  103. }
  104. /* Shutdown output layer (send the set HTTP headers, cleanup output handlers,
  105. * etc.) */
  106. zend_try { php_output_deactivate(); }
  107. zend_end_try();
  108. /* Clean super globals */
  109. frankenphp_request_reset();
  110. /* SAPI related shutdown (free stuff) */
  111. frankenphp_clean_server_context();
  112. zend_try { sapi_deactivate(); }
  113. zend_end_try();
  114. zend_set_memory_limit(PG(memory_limit));
  115. }
  116. /* Adapted from php_request_startup() */
  117. static int frankenphp_worker_request_startup() {
  118. int retval = SUCCESS;
  119. zend_try {
  120. php_output_activate();
  121. /* initialize global variables */
  122. PG(header_is_being_sent) = 0;
  123. PG(connection_status) = PHP_CONNECTION_NORMAL;
  124. /* Keep the current execution context */
  125. sapi_activate();
  126. /*
  127. * Timeouts are currently fundamentally broken with ZTS:
  128. *https://bugs.php.net/bug.php?id=79464
  129. *
  130. *if (PG(max_input_time) == -1) {
  131. * zend_set_timeout(EG(timeout_seconds), 1);
  132. *} else {
  133. * zend_set_timeout(PG(max_input_time), 1);
  134. *}
  135. */
  136. if (PG(expose_php)) {
  137. sapi_add_header(SAPI_PHP_VERSION_HEADER,
  138. sizeof(SAPI_PHP_VERSION_HEADER) - 1, 1);
  139. }
  140. if (PG(output_handler) && PG(output_handler)[0]) {
  141. zval oh;
  142. ZVAL_STRING(&oh, PG(output_handler));
  143. php_output_start_user(&oh, 0, PHP_OUTPUT_HANDLER_STDFLAGS);
  144. zval_ptr_dtor(&oh);
  145. } else if (PG(output_buffering)) {
  146. php_output_start_user(NULL,
  147. PG(output_buffering) > 1 ? PG(output_buffering) : 0,
  148. PHP_OUTPUT_HANDLER_STDFLAGS);
  149. } else if (PG(implicit_flush)) {
  150. php_output_set_implicit_flush(1);
  151. }
  152. php_hash_environment();
  153. zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER));
  154. // unfinish the request
  155. frankenphp_server_context *ctx = SG(server_context);
  156. ctx->finished = false;
  157. // TODO: store the list of modules to reload in a global module variable
  158. const char **module_name;
  159. zend_module_entry *module;
  160. for (module_name = MODULES_TO_RELOAD; *module_name; module_name++) {
  161. if ((module = zend_hash_str_find_ptr(&module_registry, *module_name,
  162. sizeof(*module_name) - 1)) &&
  163. module->request_startup_func) {
  164. module->request_startup_func(module->type, module->module_number);
  165. }
  166. }
  167. }
  168. zend_catch { retval = FAILURE; }
  169. zend_end_try();
  170. SG(sapi_started) = 1;
  171. return retval;
  172. }
  173. PHP_FUNCTION(frankenphp_finish_request) { /* {{{ */
  174. if (zend_parse_parameters_none() == FAILURE) {
  175. RETURN_THROWS();
  176. }
  177. frankenphp_server_context *ctx = SG(server_context);
  178. if (ctx->finished) {
  179. RETURN_FALSE;
  180. }
  181. php_output_end_all();
  182. php_header();
  183. if (ctx->current_request != 0) {
  184. go_frankenphp_finish_request(ctx->main_request, ctx->current_request,
  185. false);
  186. }
  187. ctx->finished = true;
  188. RETURN_TRUE;
  189. } /* }}} */
  190. PHP_FUNCTION(frankenphp_handle_request) {
  191. zend_fcall_info fci;
  192. zend_fcall_info_cache fcc;
  193. ZEND_PARSE_PARAMETERS_START(1, 1)
  194. Z_PARAM_FUNC(fci, fcc)
  195. ZEND_PARSE_PARAMETERS_END();
  196. frankenphp_server_context *ctx = SG(server_context);
  197. if (ctx->main_request == 0) {
  198. // not a worker, throw an error
  199. zend_throw_exception(
  200. spl_ce_RuntimeException,
  201. "frankenphp_handle_request() called while not in worker mode", 0);
  202. RETURN_THROWS();
  203. }
  204. if (!ctx->worker_ready) {
  205. /* Clean the first dummy request created to initialize the worker */
  206. frankenphp_worker_request_shutdown();
  207. ctx->worker_ready = true;
  208. /* Mark the worker as ready to handle requests */
  209. go_frankenphp_worker_ready();
  210. }
  211. #ifdef ZEND_MAX_EXECUTION_TIMERS
  212. // Disable timeouts while waiting for a request to handle
  213. zend_unset_timeout();
  214. #endif
  215. uintptr_t request =
  216. go_frankenphp_worker_handle_request_start(ctx->main_request);
  217. if (frankenphp_worker_request_startup() == FAILURE
  218. /* Shutting down */
  219. || !request) {
  220. RETURN_FALSE;
  221. }
  222. #ifdef ZEND_MAX_EXECUTION_TIMERS
  223. // Reset default timeout
  224. // TODO: add support for max_input_time
  225. zend_set_timeout(INI_INT("max_execution_time"), 0);
  226. #endif
  227. /* Call the PHP func */
  228. zval retval = {0};
  229. fci.size = sizeof fci;
  230. fci.retval = &retval;
  231. if (zend_call_function(&fci, &fcc) == SUCCESS) {
  232. zval_ptr_dtor(&retval);
  233. }
  234. /* If an exception occured, print the message to the client before closing the
  235. * connection */
  236. if (EG(exception)) {
  237. zend_exception_error(EG(exception), E_ERROR);
  238. }
  239. frankenphp_worker_request_shutdown();
  240. ctx->current_request = 0;
  241. go_frankenphp_finish_request(ctx->main_request, request, true);
  242. RETURN_TRUE;
  243. }
  244. PHP_FUNCTION(headers_send) {
  245. zend_long response_code = 200;
  246. ZEND_PARSE_PARAMETERS_START(0, 1)
  247. Z_PARAM_OPTIONAL
  248. Z_PARAM_LONG(response_code)
  249. ZEND_PARSE_PARAMETERS_END();
  250. int previous_status_code = SG(sapi_headers).http_response_code;
  251. SG(sapi_headers).http_response_code = response_code;
  252. if (response_code >= 100 && response_code < 200) {
  253. int ret = sapi_module.send_headers(&SG(sapi_headers));
  254. SG(sapi_headers).http_response_code = previous_status_code;
  255. RETURN_LONG(ret);
  256. }
  257. RETURN_LONG(sapi_send_headers());
  258. }
  259. static zend_module_entry frankenphp_module = {
  260. STANDARD_MODULE_HEADER,
  261. "frankenphp",
  262. ext_functions, /* function table */
  263. NULL, /* initialization */
  264. NULL, /* shutdown */
  265. NULL, /* request initialization */
  266. NULL, /* request shutdown */
  267. NULL, /* information */
  268. TOSTRING(FRANKENPHP_VERSION),
  269. STANDARD_MODULE_PROPERTIES};
  270. static uintptr_t frankenphp_request_shutdown() {
  271. frankenphp_server_context *ctx = SG(server_context);
  272. if (ctx->main_request && ctx->current_request) {
  273. frankenphp_request_reset();
  274. }
  275. php_request_shutdown((void *)0);
  276. ((frankenphp_server_context *)SG(server_context))->cookie_data = NULL;
  277. uintptr_t rh = frankenphp_clean_server_context();
  278. free(ctx);
  279. SG(server_context) = NULL;
  280. #if defined(ZTS)
  281. ts_free_thread();
  282. #endif
  283. return rh;
  284. }
  285. int frankenphp_update_server_context(
  286. bool create, uintptr_t current_request, uintptr_t main_request,
  287. const char *request_method, char *query_string, zend_long content_length,
  288. char *path_translated, char *request_uri, const char *content_type,
  289. char *auth_user, char *auth_password, int proto_num) {
  290. frankenphp_server_context *ctx;
  291. if (create) {
  292. #ifdef ZTS
  293. /* initial resource fetch */
  294. (void)ts_resource(0);
  295. #ifdef PHP_WIN32
  296. ZEND_TSRMLS_CACHE_UPDATE();
  297. #endif
  298. #endif
  299. /* todo: use a pool */
  300. ctx = (frankenphp_server_context *)calloc(
  301. 1, sizeof(frankenphp_server_context));
  302. if (ctx == NULL) {
  303. return FAILURE;
  304. }
  305. ctx->cookie_data = NULL;
  306. ctx->finished = false;
  307. SG(server_context) = ctx;
  308. } else {
  309. ctx = (frankenphp_server_context *)SG(server_context);
  310. }
  311. ctx->main_request = main_request;
  312. ctx->current_request = current_request;
  313. SG(request_info).auth_password = auth_password;
  314. SG(request_info).auth_user = auth_user;
  315. SG(request_info).request_method = request_method;
  316. SG(request_info).query_string = query_string;
  317. SG(request_info).content_type = content_type;
  318. SG(request_info).content_length = content_length;
  319. SG(request_info).path_translated = path_translated;
  320. SG(request_info).request_uri = request_uri;
  321. SG(request_info).proto_num = proto_num;
  322. return SUCCESS;
  323. }
  324. static int frankenphp_startup(sapi_module_struct *sapi_module) {
  325. return php_module_startup(sapi_module, &frankenphp_module);
  326. }
  327. static int frankenphp_deactivate(void) {
  328. /* TODO: flush everything */
  329. return SUCCESS;
  330. }
  331. static size_t frankenphp_ub_write(const char *str, size_t str_length) {
  332. frankenphp_server_context *ctx = SG(server_context);
  333. if (ctx->finished) {
  334. // TODO: maybe log a warning that we tried to write to a finished request?
  335. return 0;
  336. }
  337. struct go_ub_write_return result = go_ub_write(
  338. ctx->current_request ? ctx->current_request : ctx->main_request,
  339. (char *)str, str_length);
  340. if (result.r1) {
  341. php_handle_aborted_connection();
  342. }
  343. return result.r0;
  344. }
  345. static int frankenphp_send_headers(sapi_headers_struct *sapi_headers) {
  346. if (SG(request_info).no_headers == 1) {
  347. return SAPI_HEADER_SENT_SUCCESSFULLY;
  348. }
  349. int status;
  350. frankenphp_server_context *ctx = SG(server_context);
  351. if (ctx->current_request == 0) {
  352. return SAPI_HEADER_SEND_FAILED;
  353. }
  354. if (SG(sapi_headers).http_status_line) {
  355. status = atoi((SG(sapi_headers).http_status_line) + 9);
  356. } else {
  357. status = SG(sapi_headers).http_response_code;
  358. if (!status) {
  359. status = 200;
  360. }
  361. }
  362. go_write_headers(ctx->current_request, status, &sapi_headers->headers);
  363. return SAPI_HEADER_SENT_SUCCESSFULLY;
  364. }
  365. static void frankenphp_sapi_flush(void *server_context) {
  366. frankenphp_server_context *ctx = (frankenphp_server_context *)server_context;
  367. if (ctx && ctx->current_request != 0 && go_sapi_flush(ctx->current_request)) {
  368. php_handle_aborted_connection();
  369. }
  370. }
  371. static size_t frankenphp_read_post(char *buffer, size_t count_bytes) {
  372. frankenphp_server_context *ctx = SG(server_context);
  373. return ctx->current_request
  374. ? go_read_post(ctx->current_request, buffer, count_bytes)
  375. : 0;
  376. }
  377. static char *frankenphp_read_cookies(void) {
  378. frankenphp_server_context *ctx = SG(server_context);
  379. if (ctx->current_request == 0) {
  380. return "";
  381. }
  382. ctx->cookie_data = go_read_cookies(ctx->current_request);
  383. return ctx->cookie_data;
  384. }
  385. static void frankenphp_register_known_variable(const char *key, char *value,
  386. zval *track_vars_array, bool f) {
  387. if (value == NULL) {
  388. return;
  389. }
  390. size_t new_val_len;
  391. if (sapi_module.input_filter(PARSE_SERVER, key, &value, strlen(value),
  392. &new_val_len)) {
  393. php_register_variable_safe(key, value, new_val_len, track_vars_array);
  394. }
  395. }
  396. void frankenphp_register_bulk_variables(char *known_variables[27],
  397. char **dynamic_variables, size_t size,
  398. zval *track_vars_array) {
  399. /* Not used, but must be present */
  400. frankenphp_register_known_variable("AUTH_TYPE", "", track_vars_array, false);
  401. frankenphp_register_known_variable("REMOTE_IDENT", "", track_vars_array,
  402. false);
  403. /* Allocated in frankenphp_update_server_context() */
  404. frankenphp_register_known_variable("CONTENT_TYPE",
  405. (char *)SG(request_info).content_type,
  406. track_vars_array, false);
  407. frankenphp_register_known_variable("PATH_TRANSLATED",
  408. (char *)SG(request_info).path_translated,
  409. track_vars_array, false);
  410. frankenphp_register_known_variable(
  411. "QUERY_STRING", SG(request_info).query_string, track_vars_array, false);
  412. frankenphp_register_known_variable("REMOTE_USER",
  413. (char *)SG(request_info).auth_user,
  414. track_vars_array, false);
  415. frankenphp_register_known_variable("REQUEST_METHOD",
  416. (char *)SG(request_info).request_method,
  417. track_vars_array, false);
  418. frankenphp_register_known_variable(
  419. "REQUEST_URI", SG(request_info).request_uri, track_vars_array, false);
  420. /* Known variables */
  421. frankenphp_register_known_variable("CONTENT_LENGTH", known_variables[0],
  422. track_vars_array, true);
  423. frankenphp_register_known_variable("DOCUMENT_ROOT", known_variables[1],
  424. track_vars_array, true);
  425. frankenphp_register_known_variable("DOCUMENT_URI", known_variables[2],
  426. track_vars_array, true);
  427. frankenphp_register_known_variable("GATEWAY_INTERFACE", known_variables[3],
  428. track_vars_array, true);
  429. frankenphp_register_known_variable("HTTP_HOST", known_variables[4],
  430. track_vars_array, true);
  431. frankenphp_register_known_variable("HTTPS", known_variables[5],
  432. track_vars_array, true);
  433. frankenphp_register_known_variable("PATH_INFO", known_variables[6],
  434. track_vars_array, true);
  435. frankenphp_register_known_variable("PHP_SELF", known_variables[7],
  436. track_vars_array, true);
  437. frankenphp_register_known_variable("REMOTE_ADDR", known_variables[8],
  438. track_vars_array,
  439. known_variables[8] != known_variables[9]);
  440. frankenphp_register_known_variable("REMOTE_HOST", known_variables[9],
  441. track_vars_array, true);
  442. frankenphp_register_known_variable("REMOTE_PORT", known_variables[10],
  443. track_vars_array, true);
  444. frankenphp_register_known_variable("REQUEST_SCHEME", known_variables[11],
  445. track_vars_array, true);
  446. frankenphp_register_known_variable("SCRIPT_FILENAME", known_variables[12],
  447. track_vars_array, true);
  448. frankenphp_register_known_variable("SCRIPT_NAME", known_variables[13],
  449. track_vars_array, true);
  450. frankenphp_register_known_variable("SERVER_NAME", known_variables[14],
  451. track_vars_array, true);
  452. frankenphp_register_known_variable("SERVER_PORT", known_variables[15],
  453. track_vars_array, true);
  454. frankenphp_register_known_variable("SERVER_PROTOCOL", known_variables[16],
  455. track_vars_array, true);
  456. frankenphp_register_known_variable("SERVER_SOFTWARE", known_variables[17],
  457. track_vars_array, true);
  458. frankenphp_register_known_variable("SSL_PROTOCOL", known_variables[18],
  459. track_vars_array, true);
  460. size_t new_val_len;
  461. for (size_t i = 0; i < size; i = i + 2) {
  462. if (sapi_module.input_filter(
  463. PARSE_SERVER, dynamic_variables[i], &dynamic_variables[i + 1],
  464. strlen(dynamic_variables[i + 1]), &new_val_len)) {
  465. php_register_variable_safe(dynamic_variables[i], dynamic_variables[i + 1],
  466. new_val_len, track_vars_array);
  467. }
  468. }
  469. }
  470. static void frankenphp_register_variables(zval *track_vars_array) {
  471. /* https://www.php.net/manual/en/reserved.variables.server.php */
  472. frankenphp_server_context *ctx = SG(server_context);
  473. go_register_variables(ctx->current_request ? ctx->current_request
  474. : ctx->main_request,
  475. track_vars_array);
  476. }
  477. static void frankenphp_log_message(const char *message, int syslog_type_int) {
  478. go_log((char *)message, syslog_type_int);
  479. }
  480. sapi_module_struct frankenphp_sapi_module = {
  481. "frankenphp", /* name */
  482. "FrankenPHP", /* pretty name */
  483. frankenphp_startup, /* startup */
  484. php_module_shutdown_wrapper, /* shutdown */
  485. NULL, /* activate */
  486. frankenphp_deactivate, /* deactivate */
  487. frankenphp_ub_write, /* unbuffered write */
  488. frankenphp_sapi_flush, /* flush */
  489. NULL, /* get uid */
  490. NULL, /* getenv */
  491. php_error, /* error handler */
  492. NULL, /* header handler */
  493. frankenphp_send_headers, /* send headers handler */
  494. NULL, /* send header handler */
  495. frankenphp_read_post, /* read POST data */
  496. frankenphp_read_cookies, /* read Cookies */
  497. frankenphp_register_variables, /* register server variables */
  498. frankenphp_log_message, /* Log message */
  499. NULL, /* Get request time */
  500. NULL, /* Child terminate */
  501. STANDARD_SAPI_MODULE_PROPERTIES};
  502. static void *manager_thread(void *arg) {
  503. #ifdef ZTS
  504. // TODO: use tsrm_startup() directly as we know the number of expected threads
  505. php_tsrm_startup();
  506. /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/
  507. #ifdef PHP_WIN32
  508. ZEND_TSRMLS_CACHE_UPDATE();
  509. #endif
  510. #endif
  511. sapi_startup(&frankenphp_sapi_module);
  512. #ifndef ZEND_MAX_EXECUTION_TIMERS
  513. #if (PHP_VERSION_ID >= 80300)
  514. frankenphp_sapi_module.ini_entries = HARDCODED_INI;
  515. #else
  516. frankenphp_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
  517. memcpy(frankenphp_sapi_module.ini_entries, HARDCODED_INI,
  518. sizeof(HARDCODED_INI));
  519. #endif
  520. #endif
  521. frankenphp_sapi_module.startup(&frankenphp_sapi_module);
  522. threadpool thpool = thpool_init(*((int *)arg));
  523. free(arg);
  524. uintptr_t rh;
  525. while ((rh = go_fetch_request())) {
  526. thpool_add_work(thpool, go_execute_script, (void *)rh);
  527. }
  528. /* channel closed, shutdown gracefully */
  529. thpool_wait(thpool);
  530. thpool_destroy(thpool);
  531. frankenphp_sapi_module.shutdown(&frankenphp_sapi_module);
  532. sapi_shutdown();
  533. #ifdef ZTS
  534. tsrm_shutdown();
  535. #endif
  536. #if (PHP_VERSION_ID < 80300)
  537. if (frankenphp_sapi_module.ini_entries) {
  538. free(frankenphp_sapi_module.ini_entries);
  539. frankenphp_sapi_module.ini_entries = NULL;
  540. }
  541. #endif
  542. go_shutdown();
  543. return NULL;
  544. }
  545. int frankenphp_init(int num_threads) {
  546. pthread_t thread;
  547. int *num_threads_ptr = calloc(1, sizeof(int));
  548. *num_threads_ptr = num_threads;
  549. if (pthread_create(&thread, NULL, *manager_thread, (void *)num_threads_ptr) !=
  550. 0) {
  551. go_shutdown();
  552. return -1;
  553. }
  554. return pthread_detach(thread);
  555. }
  556. int frankenphp_request_startup() {
  557. if (php_request_startup() == SUCCESS) {
  558. return SUCCESS;
  559. }
  560. frankenphp_server_context *ctx = SG(server_context);
  561. SG(server_context) = NULL;
  562. free(ctx);
  563. php_request_shutdown((void *)0);
  564. return FAILURE;
  565. }
  566. int frankenphp_execute_script(char *file_name) {
  567. if (frankenphp_request_startup() == FAILURE) {
  568. return FAILURE;
  569. }
  570. int status = SUCCESS;
  571. zend_file_handle file_handle;
  572. zend_stream_init_filename(&file_handle, file_name);
  573. file_handle.primary_script = 1;
  574. zend_first_try {
  575. EG(exit_status) = 0;
  576. php_execute_script(&file_handle);
  577. status = EG(exit_status);
  578. }
  579. zend_catch { status = EG(exit_status); }
  580. zend_end_try();
  581. zend_destroy_file_handle(&file_handle);
  582. frankenphp_clean_server_context();
  583. frankenphp_request_shutdown();
  584. return status;
  585. }
  586. // Use global variables to store CLI arguments to prevent useless allocations
  587. static char *cli_script;
  588. static int cli_argc;
  589. static char **cli_argv;
  590. // Adapted from https://github.com/php/php-src/sapi/cli/php_cli.c (The PHP
  591. // Group, The PHP License)
  592. static void cli_register_file_handles(bool no_close) /* {{{ */
  593. {
  594. php_stream *s_in, *s_out, *s_err;
  595. php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL;
  596. zend_constant ic, oc, ec;
  597. s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in);
  598. s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
  599. s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
  600. if (s_in == NULL || s_out == NULL || s_err == NULL) {
  601. if (s_in)
  602. php_stream_close(s_in);
  603. if (s_out)
  604. php_stream_close(s_out);
  605. if (s_err)
  606. php_stream_close(s_err);
  607. return;
  608. }
  609. if (no_close) {
  610. s_in->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  611. s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  612. s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  613. }
  614. // s_in_process = s_in;
  615. php_stream_to_zval(s_in, &ic.value);
  616. php_stream_to_zval(s_out, &oc.value);
  617. php_stream_to_zval(s_err, &ec.value);
  618. ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0);
  619. ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0);
  620. zend_register_constant(&ic);
  621. ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0);
  622. oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0);
  623. zend_register_constant(&oc);
  624. ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0);
  625. ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0);
  626. zend_register_constant(&ec);
  627. }
  628. /* }}} */
  629. static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */
  630. {
  631. size_t len;
  632. char *docroot = "";
  633. /* In CGI mode, we consider the environment to be a part of the server
  634. * variables
  635. */
  636. php_import_environment_variables(track_vars_array);
  637. /* Build the special-case PHP_SELF variable for the CLI version */
  638. len = strlen(cli_script);
  639. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &cli_script, len,
  640. &len)) {
  641. php_register_variable_safe("PHP_SELF", cli_script, len, track_vars_array);
  642. }
  643. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &cli_script, len,
  644. &len)) {
  645. php_register_variable_safe("SCRIPT_NAME", cli_script, len,
  646. track_vars_array);
  647. }
  648. /* filenames are empty for stdin */
  649. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &cli_script,
  650. len, &len)) {
  651. php_register_variable_safe("SCRIPT_FILENAME", cli_script, len,
  652. track_vars_array);
  653. }
  654. if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &cli_script,
  655. len, &len)) {
  656. php_register_variable_safe("PATH_TRANSLATED", cli_script, len,
  657. track_vars_array);
  658. }
  659. /* just make it available */
  660. len = 0U;
  661. if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len,
  662. &len)) {
  663. php_register_variable_safe("DOCUMENT_ROOT", docroot, len, track_vars_array);
  664. }
  665. }
  666. /* }}} */
  667. static void *execute_script_cli(void *arg) {
  668. void *exit_status;
  669. // The SAPI name "cli" is hardcoded into too many programs... let's usurp it.
  670. php_embed_module.name = "cli";
  671. php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP";
  672. php_embed_module.register_server_variables = sapi_cli_register_variables;
  673. php_embed_init(cli_argc, cli_argv);
  674. cli_register_file_handles(false);
  675. zend_first_try {
  676. zend_file_handle file_handle;
  677. zend_stream_init_filename(&file_handle, cli_script);
  678. CG(skip_shebang) = 1;
  679. php_execute_script(&file_handle);
  680. }
  681. zend_end_try();
  682. exit_status = (void *)(intptr_t)EG(exit_status);
  683. php_embed_shutdown();
  684. return exit_status;
  685. }
  686. int frankenphp_execute_script_cli(char *script, int argc, char **argv) {
  687. pthread_t thread;
  688. int err;
  689. void *exit_status;
  690. cli_script = script;
  691. cli_argc = argc;
  692. cli_argv = argv;
  693. // Start the script in a dedicated thread to prevent conflicts between Go and
  694. // PHP signal handlers
  695. err = pthread_create(&thread, NULL, execute_script_cli, NULL);
  696. if (err != 0) {
  697. return err;
  698. }
  699. err = pthread_join(thread, &exit_status);
  700. if (err != 0) {
  701. return err;
  702. }
  703. return (intptr_t)exit_status;
  704. }