frankenphp.c 26 KB

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