frankenphp.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. #include <errno.h>
  2. #include <stdint.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <php_config.h>
  6. #include <php.h>
  7. #include <php_main.h>
  8. #include <php_variables.h>
  9. #include <php_output.h>
  10. #include <SAPI.h>
  11. #include <Zend/zend_alloc.h>
  12. #include <Zend/zend_types.h>
  13. #include <Zend/zend_exceptions.h>
  14. #include <Zend/zend_interfaces.h>
  15. #include <ext/standard/head.h>
  16. #include <ext/spl/spl_exceptions.h>
  17. #include "C-Thread-Pool/thpool.h"
  18. #include "C-Thread-Pool/thpool.c"
  19. #include "frankenphp_arginfo.h"
  20. #include "_cgo_export.h"
  21. #if defined(PHP_WIN32) && defined(ZTS)
  22. ZEND_TSRMLS_CACHE_DEFINE()
  23. #endif
  24. /* Timeouts are currently fundamentally broken with ZTS except on Linux: https://bugs.php.net/bug.php?id=79464 */
  25. #ifndef ZEND_MAX_EXECUTION_TIMERS
  26. static const char HARDCODED_INI[] =
  27. "max_execution_time=0\n"
  28. "max_input_time=-1\n\0";
  29. #endif
  30. static const char *MODULES_TO_RELOAD[] = {
  31. "filter",
  32. "session",
  33. NULL
  34. };
  35. frankenphp_version frankenphp_get_version() {
  36. return (frankenphp_version){
  37. PHP_MAJOR_VERSION,
  38. PHP_MINOR_VERSION,
  39. PHP_RELEASE_VERSION,
  40. PHP_EXTRA_VERSION,
  41. PHP_VERSION,
  42. PHP_VERSION_ID,
  43. };
  44. }
  45. frankenphp_config frankenphp_get_config() {
  46. return (frankenphp_config){
  47. frankenphp_get_version(),
  48. #ifdef ZTS
  49. true,
  50. #else
  51. false,
  52. #endif
  53. #ifdef ZEND_SIGNALS
  54. true,
  55. #else
  56. false,
  57. #endif
  58. #ifdef ZEND_MAX_EXECUTION_TIMERS
  59. true,
  60. #else
  61. false,
  62. #endif
  63. };
  64. }
  65. typedef struct frankenphp_server_context {
  66. uintptr_t current_request;
  67. uintptr_t main_request;
  68. bool worker_ready;
  69. char *cookie_data;
  70. bool finished;
  71. } frankenphp_server_context;
  72. static void frankenphp_request_reset() {
  73. zend_try {
  74. int i;
  75. for (i=0; i<NUM_TRACK_VARS; i++) {
  76. zval_ptr_dtor(&PG(http_globals)[i]);
  77. }
  78. memset(&PG(http_globals), 0, sizeof(zval) * NUM_TRACK_VARS);
  79. } zend_end_try();
  80. }
  81. /* Adapted from php_request_shutdown */
  82. static void frankenphp_worker_request_shutdown() {
  83. /* Flush all output buffers */
  84. zend_try {
  85. php_output_end_all();
  86. } zend_end_try();
  87. // TODO: store the list of modules to reload in a global module variable
  88. const char **module_name;
  89. zend_module_entry *module;
  90. for (module_name = MODULES_TO_RELOAD; *module_name; module_name++) {
  91. if ((module = zend_hash_str_find_ptr(&module_registry, *module_name, strlen(*module_name)))) {
  92. module->request_shutdown_func(module->type, module->module_number);
  93. }
  94. }
  95. /* Shutdown output layer (send the set HTTP headers, cleanup output handlers, etc.) */
  96. zend_try {
  97. php_output_deactivate();
  98. } zend_end_try();
  99. /* Clean super globals */
  100. frankenphp_request_reset();
  101. /* SAPI related shutdown (free stuff) */
  102. frankenphp_clean_server_context();
  103. zend_try {
  104. sapi_deactivate();
  105. } zend_end_try();
  106. zend_set_memory_limit(PG(memory_limit));
  107. }
  108. /* Adapted from php_request_startup() */
  109. static int frankenphp_worker_request_startup() {
  110. int retval = SUCCESS;
  111. zend_try {
  112. php_output_activate();
  113. /* initialize global variables */
  114. PG(header_is_being_sent) = 0;
  115. PG(connection_status) = PHP_CONNECTION_NORMAL;
  116. /* Keep the current execution context */
  117. sapi_activate();
  118. /*
  119. * Timeouts are currently fundamentally broken with ZTS: https://bugs.php.net/bug.php?id=79464
  120. *
  121. *if (PG(max_input_time) == -1) {
  122. * zend_set_timeout(EG(timeout_seconds), 1);
  123. *} else {
  124. * zend_set_timeout(PG(max_input_time), 1);
  125. *}
  126. */
  127. if (PG(expose_php)) {
  128. sapi_add_header(SAPI_PHP_VERSION_HEADER, sizeof(SAPI_PHP_VERSION_HEADER)-1, 1);
  129. }
  130. if (PG(output_handler) && PG(output_handler)[0]) {
  131. zval oh;
  132. ZVAL_STRING(&oh, PG(output_handler));
  133. php_output_start_user(&oh, 0, PHP_OUTPUT_HANDLER_STDFLAGS);
  134. zval_ptr_dtor(&oh);
  135. } else if (PG(output_buffering)) {
  136. php_output_start_user(NULL, PG(output_buffering) > 1 ? PG(output_buffering) : 0, PHP_OUTPUT_HANDLER_STDFLAGS);
  137. } else if (PG(implicit_flush)) {
  138. php_output_set_implicit_flush(1);
  139. }
  140. php_hash_environment();
  141. zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER));
  142. // unfinish the request
  143. frankenphp_server_context *ctx = SG(server_context);
  144. ctx->finished = false;
  145. // TODO: store the list of modules to reload in a global module variable
  146. const char **module_name;
  147. zend_module_entry *module;
  148. for (module_name = MODULES_TO_RELOAD; *module_name; module_name++) {
  149. if (
  150. (module = zend_hash_str_find_ptr(&module_registry, *module_name, sizeof(*module_name)-1))
  151. && module->request_startup_func
  152. ) {
  153. module->request_startup_func(module->type, module->module_number);
  154. }
  155. }
  156. } zend_catch {
  157. retval = FAILURE;
  158. } zend_end_try();
  159. SG(sapi_started) = 1;
  160. return retval;
  161. }
  162. PHP_FUNCTION(frankenphp_finish_request) { /* {{{ */
  163. if (zend_parse_parameters_none() == FAILURE) {
  164. RETURN_THROWS();
  165. }
  166. frankenphp_server_context *ctx = SG(server_context);
  167. if (ctx->finished) {
  168. RETURN_FALSE;
  169. }
  170. php_output_end_all();
  171. php_header();
  172. if (ctx->current_request != 0) {
  173. go_frankenphp_finish_request(ctx->main_request, ctx->current_request, false);
  174. }
  175. ctx->finished = true;
  176. RETURN_TRUE;
  177. } /* }}} */
  178. PHP_FUNCTION(frankenphp_handle_request) {
  179. zend_fcall_info fci;
  180. zend_fcall_info_cache fcc;
  181. ZEND_PARSE_PARAMETERS_START(1, 1)
  182. Z_PARAM_FUNC(fci, fcc)
  183. ZEND_PARSE_PARAMETERS_END();
  184. frankenphp_server_context *ctx = SG(server_context);
  185. if (ctx->main_request == 0) {
  186. // not a worker, throw an error
  187. zend_throw_exception(spl_ce_RuntimeException, "frankenphp_handle_request() called while not in worker mode", 0);
  188. RETURN_THROWS();
  189. }
  190. if (!ctx->worker_ready) {
  191. /* Clean the first dummy request created to initialize the worker */
  192. frankenphp_worker_request_shutdown();
  193. ctx->worker_ready = true;
  194. /* Mark the worker as ready to handle requests */
  195. go_frankenphp_worker_ready();
  196. }
  197. #ifdef ZEND_MAX_EXECUTION_TIMERS
  198. // Disable timeouts while waiting for a request to handle
  199. zend_unset_timeout();
  200. #endif
  201. uintptr_t request = go_frankenphp_worker_handle_request_start(ctx->main_request);
  202. if (
  203. frankenphp_worker_request_startup() == FAILURE
  204. /* Shutting down */
  205. || !request
  206. ) {
  207. RETURN_FALSE;
  208. }
  209. #ifdef ZEND_MAX_EXECUTION_TIMERS
  210. // Reset default timeout
  211. // TODO: add support for max_input_time
  212. zend_set_timeout(INI_INT("max_execution_time"), 0);
  213. #endif
  214. /* Call the PHP func */
  215. zval retval = {0};
  216. fci.size = sizeof fci;
  217. fci.retval = &retval;
  218. if (zend_call_function(&fci, &fcc) == SUCCESS) {
  219. zval_ptr_dtor(&retval);
  220. }
  221. /* If an exception occured, print the message to the client before closing the connection */
  222. if (EG(exception)) {
  223. zend_exception_error(EG(exception), E_ERROR);
  224. }
  225. frankenphp_worker_request_shutdown();
  226. ctx->current_request = 0;
  227. go_frankenphp_finish_request(ctx->main_request, request, true);
  228. RETURN_TRUE;
  229. }
  230. PHP_FUNCTION(headers_send) {
  231. zend_long response_code = 200;
  232. ZEND_PARSE_PARAMETERS_START(0, 1)
  233. Z_PARAM_OPTIONAL
  234. Z_PARAM_LONG(response_code)
  235. ZEND_PARSE_PARAMETERS_END();
  236. int previous_status_code = SG(sapi_headers).http_response_code;
  237. SG(sapi_headers).http_response_code = response_code;
  238. if (response_code >= 100 && response_code < 200) {
  239. int ret = sapi_module.send_headers(&SG(sapi_headers));
  240. SG(sapi_headers).http_response_code = previous_status_code;
  241. RETURN_LONG(ret);
  242. }
  243. RETURN_LONG(sapi_send_headers());
  244. }
  245. static zend_module_entry frankenphp_module = {
  246. STANDARD_MODULE_HEADER,
  247. "frankenphp",
  248. ext_functions, /* function table */
  249. NULL, /* initialization */
  250. NULL, /* shutdown */
  251. NULL, /* request initialization */
  252. NULL, /* request shutdown */
  253. NULL, /* information */
  254. TOSTRING(FRANKENPHP_VERSION),
  255. STANDARD_MODULE_PROPERTIES
  256. };
  257. uintptr_t frankenphp_clean_server_context() {
  258. frankenphp_server_context *ctx = SG(server_context);
  259. if (ctx == NULL) return 0;
  260. free(SG(request_info.auth_password));
  261. SG(request_info.auth_password) = NULL;
  262. free(SG(request_info.auth_user));
  263. SG(request_info.auth_user) = NULL;
  264. free((char *) SG(request_info.request_method));
  265. SG(request_info.request_method) = NULL;
  266. free(SG(request_info.query_string));
  267. SG(request_info.query_string) = NULL;
  268. free((char *) SG(request_info.content_type));
  269. SG(request_info.content_type) = NULL;
  270. free(SG(request_info.path_translated));
  271. SG(request_info.path_translated) = NULL;
  272. free(SG(request_info.request_uri));
  273. SG(request_info.request_uri) = NULL;
  274. return ctx->current_request;
  275. }
  276. uintptr_t frankenphp_request_shutdown()
  277. {
  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,
  295. uintptr_t current_request,
  296. uintptr_t main_request,
  297. const char *request_method,
  298. char *query_string,
  299. zend_long content_length,
  300. char *path_translated,
  301. char *request_uri,
  302. const char *content_type,
  303. char *auth_user,
  304. char *auth_password,
  305. int proto_num
  306. ) {
  307. frankenphp_server_context *ctx;
  308. if (create) {
  309. #ifdef ZTS
  310. /* initial resource fetch */
  311. (void)ts_resource(0);
  312. # ifdef PHP_WIN32
  313. ZEND_TSRMLS_CACHE_UPDATE();
  314. # endif
  315. #endif
  316. /* todo: use a pool */
  317. ctx = (frankenphp_server_context *) calloc(1, sizeof(frankenphp_server_context));
  318. if (ctx == NULL) {
  319. return FAILURE;
  320. }
  321. ctx->cookie_data = NULL;
  322. ctx->finished = false;
  323. SG(server_context) = ctx;
  324. } else {
  325. ctx = (frankenphp_server_context *) SG(server_context);
  326. }
  327. ctx->main_request = main_request;
  328. ctx->current_request = current_request;
  329. SG(request_info).auth_password = auth_password;
  330. SG(request_info).auth_user = auth_user;
  331. SG(request_info).request_method = request_method;
  332. SG(request_info).query_string = query_string;
  333. SG(request_info).content_type = content_type;
  334. SG(request_info).content_length = content_length;
  335. SG(request_info).path_translated = path_translated;
  336. SG(request_info).request_uri = request_uri;
  337. SG(request_info).proto_num = proto_num;
  338. return SUCCESS;
  339. }
  340. static int frankenphp_startup(sapi_module_struct *sapi_module)
  341. {
  342. return php_module_startup(sapi_module, &frankenphp_module);
  343. }
  344. static int frankenphp_deactivate(void)
  345. {
  346. /* TODO: flush everything */
  347. return SUCCESS;
  348. }
  349. static size_t frankenphp_ub_write(const char *str, size_t str_length)
  350. {
  351. frankenphp_server_context* ctx = SG(server_context);
  352. if(ctx->finished) {
  353. // TODO: maybe log a warning that we tried to write to a finished request?
  354. return 0;
  355. }
  356. struct go_ub_write_return result = go_ub_write(ctx->current_request ? ctx->current_request : ctx->main_request, (char *) str, str_length);
  357. if (result.r1) {
  358. php_handle_aborted_connection();
  359. }
  360. return result.r0;
  361. }
  362. static int frankenphp_send_headers(sapi_headers_struct *sapi_headers)
  363. {
  364. if (SG(request_info).no_headers == 1) {
  365. return SAPI_HEADER_SENT_SUCCESSFULLY;
  366. }
  367. int status;
  368. frankenphp_server_context* ctx = SG(server_context);
  369. if (ctx->current_request == 0) {
  370. return SAPI_HEADER_SEND_FAILED;
  371. }
  372. if (SG(sapi_headers).http_status_line) {
  373. status = atoi((SG(sapi_headers).http_status_line) + 9);
  374. } else {
  375. status = SG(sapi_headers).http_response_code;
  376. if (!status) {
  377. status = 200;
  378. }
  379. }
  380. go_write_headers(ctx->current_request, status, &sapi_headers->headers);
  381. return SAPI_HEADER_SENT_SUCCESSFULLY;
  382. }
  383. static void frankenphp_sapi_flush(void *server_context)
  384. {
  385. frankenphp_server_context *ctx = (frankenphp_server_context *) server_context;
  386. if (ctx && ctx->current_request != 0 && go_sapi_flush(ctx->current_request)) {
  387. php_handle_aborted_connection();
  388. }
  389. }
  390. static size_t frankenphp_read_post(char *buffer, size_t count_bytes)
  391. {
  392. frankenphp_server_context* ctx = SG(server_context);
  393. return ctx->current_request ? go_read_post(ctx->current_request, buffer, count_bytes) : 0;
  394. }
  395. static char* frankenphp_read_cookies(void)
  396. {
  397. frankenphp_server_context* ctx = SG(server_context);
  398. if (ctx->current_request == 0) {
  399. return "";
  400. }
  401. ctx->cookie_data = go_read_cookies(ctx->current_request);
  402. return ctx->cookie_data;
  403. }
  404. void frankenphp_register_bulk_variables(char **variables, size_t size, zval *track_vars_array)
  405. {
  406. for (size_t i = 1; i < size; i = i+2)
  407. {
  408. php_register_variable(variables[i-1], variables[i], track_vars_array);
  409. }
  410. }
  411. static void frankenphp_register_variables(zval *track_vars_array)
  412. {
  413. /* https://www.php.net/manual/en/reserved.variables.server.php */
  414. frankenphp_server_context* ctx = SG(server_context);
  415. go_register_variables(ctx->current_request ? ctx->current_request : ctx->main_request, track_vars_array);
  416. }
  417. static void frankenphp_log_message(const char *message, int syslog_type_int)
  418. {
  419. go_log((char *) message, syslog_type_int);
  420. }
  421. sapi_module_struct frankenphp_sapi_module = {
  422. "frankenphp", /* name */
  423. "FrankenPHP", /* pretty name */
  424. frankenphp_startup, /* startup */
  425. php_module_shutdown_wrapper, /* shutdown */
  426. NULL, /* activate */
  427. frankenphp_deactivate, /* deactivate */
  428. frankenphp_ub_write, /* unbuffered write */
  429. frankenphp_sapi_flush, /* flush */
  430. NULL, /* get uid */
  431. NULL, /* getenv */
  432. php_error, /* error handler */
  433. NULL, /* header handler */
  434. frankenphp_send_headers, /* send headers handler */
  435. NULL, /* send header handler */
  436. frankenphp_read_post, /* read POST data */
  437. frankenphp_read_cookies, /* read Cookies */
  438. frankenphp_register_variables, /* register server variables */
  439. frankenphp_log_message, /* Log message */
  440. NULL, /* Get request time */
  441. NULL, /* Child terminate */
  442. STANDARD_SAPI_MODULE_PROPERTIES
  443. };
  444. static void *manager_thread(void *arg) {
  445. #ifdef ZTS
  446. // TODO: use tsrm_startup() directly as we know the number of expected threads
  447. php_tsrm_startup();
  448. /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/
  449. # ifdef PHP_WIN32
  450. ZEND_TSRMLS_CACHE_UPDATE();
  451. # endif
  452. #endif
  453. sapi_startup(&frankenphp_sapi_module);
  454. #ifndef ZEND_MAX_EXECUTION_TIMERS
  455. # if (PHP_VERSION_ID >= 80300)
  456. frankenphp_sapi_module.ini_entries = HARDCODED_INI;
  457. # else
  458. frankenphp_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
  459. memcpy(frankenphp_sapi_module.ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI));
  460. # endif
  461. #endif
  462. frankenphp_sapi_module.startup(&frankenphp_sapi_module);
  463. threadpool thpool = thpool_init(*((int *) arg));
  464. free(arg);
  465. uintptr_t rh;
  466. while ((rh = go_fetch_request())) {
  467. thpool_add_work(thpool, go_execute_script, (void *) rh);
  468. }
  469. /* channel closed, shutdown gracefully */
  470. thpool_wait(thpool);
  471. thpool_destroy(thpool);
  472. frankenphp_sapi_module.shutdown(&frankenphp_sapi_module);
  473. sapi_shutdown();
  474. #ifdef ZTS
  475. tsrm_shutdown();
  476. #endif
  477. #if (PHP_VERSION_ID < 80300)
  478. if (frankenphp_sapi_module.ini_entries) {
  479. free(frankenphp_sapi_module.ini_entries);
  480. frankenphp_sapi_module.ini_entries = NULL;
  481. }
  482. #endif
  483. go_shutdown();
  484. return NULL;
  485. }
  486. int frankenphp_init(int num_threads) {
  487. pthread_t thread;
  488. int *num_threads_ptr = calloc(1, sizeof(int));
  489. *num_threads_ptr = num_threads;
  490. if (pthread_create(&thread, NULL, *manager_thread, (void *) num_threads_ptr) != 0) {
  491. go_shutdown();
  492. return -1;
  493. }
  494. return pthread_detach(thread);
  495. }
  496. int frankenphp_request_startup()
  497. {
  498. if (php_request_startup() == SUCCESS) {
  499. return SUCCESS;
  500. }
  501. frankenphp_server_context *ctx = SG(server_context);
  502. SG(server_context) = NULL;
  503. free(ctx);
  504. php_request_shutdown((void *) 0);
  505. return FAILURE;
  506. }
  507. int frankenphp_execute_script(const char* file_name)
  508. {
  509. int status = FAILURE;
  510. zend_file_handle file_handle;
  511. zend_stream_init_filename(&file_handle, file_name);
  512. file_handle.primary_script = 1;
  513. zend_first_try {
  514. status = php_execute_script(&file_handle);
  515. } zend_catch {
  516. /* int exit_status = EG(exit_status); */
  517. } zend_end_try();
  518. zend_destroy_file_handle(&file_handle);
  519. return status;
  520. }