frankenphp.c 26 KB

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