frankenphp.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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. /* {{{ Fetch all HTTP request headers */
  198. PHP_FUNCTION(frankenphp_request_headers) {
  199. if (zend_parse_parameters_none() == FAILURE) {
  200. RETURN_THROWS();
  201. }
  202. frankenphp_server_context *ctx = SG(server_context);
  203. struct go_apache_request_headers_return headers =
  204. go_apache_request_headers(ctx->current_request);
  205. array_init_size(return_value, headers.r1);
  206. for (size_t i = 0; i < headers.r1; i++) {
  207. go_string key = headers.r0[i * 2];
  208. go_string val = headers.r0[i * 2 + 1];
  209. add_assoc_stringl_ex(return_value, key.data, key.len, val.data, val.len);
  210. }
  211. free(headers.r0);
  212. }
  213. /* }}} */
  214. // add_response_header and apache_response_headers are copied from https://github.com/php/php-src/blob/master/sapi/cli/php_cli_server.c
  215. // Copyright (c) The PHP Group
  216. // Licensed under The PHP License
  217. // Original authors: Moriyoshi Koizumi <moriyoshi@php.net> and Xinchen Hui <laruence@php.net>
  218. static void add_response_header(sapi_header_struct *h, zval *return_value) /* {{{ */
  219. {
  220. if (h->header_len > 0) {
  221. char *s;
  222. size_t len = 0;
  223. ALLOCA_FLAG(use_heap)
  224. char *p = strchr(h->header, ':');
  225. if (NULL != p) {
  226. len = p - h->header;
  227. }
  228. if (len > 0) {
  229. while (len != 0 && (h->header[len-1] == ' ' || h->header[len-1] == '\t')) {
  230. len--;
  231. }
  232. if (len) {
  233. s = do_alloca(len + 1, use_heap);
  234. memcpy(s, h->header, len);
  235. s[len] = 0;
  236. do {
  237. p++;
  238. } while (*p == ' ' || *p == '\t');
  239. add_assoc_stringl_ex(return_value, s, len, p, h->header_len - (p - h->header));
  240. free_alloca(s, use_heap);
  241. }
  242. }
  243. }
  244. }
  245. /* }}} */
  246. PHP_FUNCTION(frankenphp_response_headers) /* {{{ */
  247. {
  248. if (zend_parse_parameters_none() == FAILURE) {
  249. RETURN_THROWS();
  250. }
  251. array_init(return_value);
  252. zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t)add_response_header, return_value);
  253. }
  254. /* }}} */
  255. PHP_FUNCTION(frankenphp_handle_request) {
  256. zend_fcall_info fci;
  257. zend_fcall_info_cache fcc;
  258. ZEND_PARSE_PARAMETERS_START(1, 1)
  259. Z_PARAM_FUNC(fci, fcc)
  260. ZEND_PARSE_PARAMETERS_END();
  261. frankenphp_server_context *ctx = SG(server_context);
  262. if (ctx->main_request == 0) {
  263. // not a worker, throw an error
  264. zend_throw_exception(
  265. spl_ce_RuntimeException,
  266. "frankenphp_handle_request() called while not in worker mode", 0);
  267. RETURN_THROWS();
  268. }
  269. if (!ctx->worker_ready) {
  270. /* Clean the first dummy request created to initialize the worker */
  271. frankenphp_worker_request_shutdown();
  272. ctx->worker_ready = true;
  273. /* Mark the worker as ready to handle requests */
  274. go_frankenphp_worker_ready();
  275. }
  276. #ifdef ZEND_MAX_EXECUTION_TIMERS
  277. // Disable timeouts while waiting for a request to handle
  278. zend_unset_timeout();
  279. #endif
  280. uintptr_t request =
  281. go_frankenphp_worker_handle_request_start(ctx->main_request);
  282. if (frankenphp_worker_request_startup() == FAILURE
  283. /* Shutting down */
  284. || !request) {
  285. RETURN_FALSE;
  286. }
  287. #ifdef ZEND_MAX_EXECUTION_TIMERS
  288. // Reset default timeout
  289. // TODO: add support for max_input_time
  290. zend_set_timeout(INI_INT("max_execution_time"), 0);
  291. #endif
  292. /* Call the PHP func */
  293. zval retval = {0};
  294. fci.size = sizeof fci;
  295. fci.retval = &retval;
  296. if (zend_call_function(&fci, &fcc) == SUCCESS) {
  297. zval_ptr_dtor(&retval);
  298. }
  299. /* If an exception occured, print the message to the client before closing the
  300. * connection */
  301. if (EG(exception)) {
  302. zend_exception_error(EG(exception), E_ERROR);
  303. }
  304. frankenphp_worker_request_shutdown();
  305. ctx->current_request = 0;
  306. go_frankenphp_finish_request(ctx->main_request, request, true);
  307. RETURN_TRUE;
  308. }
  309. PHP_FUNCTION(headers_send) {
  310. zend_long response_code = 200;
  311. ZEND_PARSE_PARAMETERS_START(0, 1)
  312. Z_PARAM_OPTIONAL
  313. Z_PARAM_LONG(response_code)
  314. ZEND_PARSE_PARAMETERS_END();
  315. int previous_status_code = SG(sapi_headers).http_response_code;
  316. SG(sapi_headers).http_response_code = response_code;
  317. if (response_code >= 100 && response_code < 200) {
  318. int ret = sapi_module.send_headers(&SG(sapi_headers));
  319. SG(sapi_headers).http_response_code = previous_status_code;
  320. RETURN_LONG(ret);
  321. }
  322. RETURN_LONG(sapi_send_headers());
  323. }
  324. static zend_module_entry frankenphp_module = {
  325. STANDARD_MODULE_HEADER,
  326. "frankenphp",
  327. ext_functions, /* function table */
  328. NULL, /* initialization */
  329. NULL, /* shutdown */
  330. NULL, /* request initialization */
  331. NULL, /* request shutdown */
  332. NULL, /* information */
  333. TOSTRING(FRANKENPHP_VERSION),
  334. STANDARD_MODULE_PROPERTIES};
  335. static uintptr_t frankenphp_request_shutdown() {
  336. frankenphp_server_context *ctx = SG(server_context);
  337. if (ctx->main_request && ctx->current_request) {
  338. frankenphp_request_reset();
  339. }
  340. php_request_shutdown((void *)0);
  341. free(ctx->cookie_data);
  342. ((frankenphp_server_context *)SG(server_context))->cookie_data = NULL;
  343. uintptr_t rh = frankenphp_clean_server_context();
  344. free(ctx);
  345. SG(server_context) = NULL;
  346. #if defined(ZTS)
  347. ts_free_thread();
  348. #endif
  349. return rh;
  350. }
  351. int frankenphp_update_server_context(
  352. bool create, uintptr_t current_request, uintptr_t main_request,
  353. const char *request_method, char *query_string, zend_long content_length,
  354. char *path_translated, char *request_uri, const char *content_type,
  355. char *auth_user, char *auth_password, int proto_num) {
  356. frankenphp_server_context *ctx;
  357. if (create) {
  358. #ifdef ZTS
  359. /* initial resource fetch */
  360. (void)ts_resource(0);
  361. #ifdef PHP_WIN32
  362. ZEND_TSRMLS_CACHE_UPDATE();
  363. #endif
  364. #endif
  365. /* todo: use a pool */
  366. ctx = (frankenphp_server_context *)calloc(
  367. 1, sizeof(frankenphp_server_context));
  368. if (ctx == NULL) {
  369. return FAILURE;
  370. }
  371. ctx->cookie_data = NULL;
  372. ctx->finished = false;
  373. SG(server_context) = ctx;
  374. } else {
  375. ctx = (frankenphp_server_context *)SG(server_context);
  376. }
  377. ctx->main_request = main_request;
  378. ctx->current_request = current_request;
  379. SG(request_info).auth_password = auth_password;
  380. SG(request_info).auth_user = auth_user;
  381. SG(request_info).request_method = request_method;
  382. SG(request_info).query_string = query_string;
  383. SG(request_info).content_type = content_type;
  384. SG(request_info).content_length = content_length;
  385. SG(request_info).path_translated = path_translated;
  386. SG(request_info).request_uri = request_uri;
  387. SG(request_info).proto_num = proto_num;
  388. return SUCCESS;
  389. }
  390. static int frankenphp_startup(sapi_module_struct *sapi_module) {
  391. return php_module_startup(sapi_module, &frankenphp_module);
  392. }
  393. static int frankenphp_deactivate(void) {
  394. /* TODO: flush everything */
  395. return SUCCESS;
  396. }
  397. static size_t frankenphp_ub_write(const char *str, size_t str_length) {
  398. frankenphp_server_context *ctx = SG(server_context);
  399. if (ctx->finished) {
  400. // TODO: maybe log a warning that we tried to write to a finished request?
  401. return 0;
  402. }
  403. struct go_ub_write_return result = go_ub_write(
  404. ctx->current_request ? ctx->current_request : ctx->main_request,
  405. (char *)str, str_length);
  406. if (result.r1) {
  407. php_handle_aborted_connection();
  408. }
  409. return result.r0;
  410. }
  411. static int frankenphp_send_headers(sapi_headers_struct *sapi_headers) {
  412. if (SG(request_info).no_headers == 1) {
  413. return SAPI_HEADER_SENT_SUCCESSFULLY;
  414. }
  415. int status;
  416. frankenphp_server_context *ctx = SG(server_context);
  417. if (ctx->current_request == 0) {
  418. return SAPI_HEADER_SEND_FAILED;
  419. }
  420. if (SG(sapi_headers).http_status_line) {
  421. status = atoi((SG(sapi_headers).http_status_line) + 9);
  422. } else {
  423. status = SG(sapi_headers).http_response_code;
  424. if (!status) {
  425. status = 200;
  426. }
  427. }
  428. go_write_headers(ctx->current_request, status, &sapi_headers->headers);
  429. return SAPI_HEADER_SENT_SUCCESSFULLY;
  430. }
  431. static void frankenphp_sapi_flush(void *server_context) {
  432. frankenphp_server_context *ctx = (frankenphp_server_context *)server_context;
  433. if (ctx && ctx->current_request != 0 && go_sapi_flush(ctx->current_request)) {
  434. php_handle_aborted_connection();
  435. }
  436. }
  437. static size_t frankenphp_read_post(char *buffer, size_t count_bytes) {
  438. frankenphp_server_context *ctx = SG(server_context);
  439. return ctx->current_request
  440. ? go_read_post(ctx->current_request, buffer, count_bytes)
  441. : 0;
  442. }
  443. static char *frankenphp_read_cookies(void) {
  444. frankenphp_server_context *ctx = SG(server_context);
  445. if (ctx->current_request == 0) {
  446. return "";
  447. }
  448. ctx->cookie_data = go_read_cookies(ctx->current_request);
  449. return ctx->cookie_data;
  450. }
  451. static void frankenphp_register_known_variable(const char *key, char *value,
  452. zval *track_vars_array, bool f) {
  453. if (value == NULL) {
  454. return;
  455. }
  456. size_t new_val_len;
  457. if (sapi_module.input_filter(PARSE_SERVER, key, &value, strlen(value),
  458. &new_val_len)) {
  459. php_register_variable_safe(key, value, new_val_len, track_vars_array);
  460. }
  461. if (f) {
  462. free(value);
  463. value = NULL;
  464. }
  465. }
  466. void frankenphp_register_bulk_variables(char *known_variables[27],
  467. char **dynamic_variables, size_t size,
  468. zval *track_vars_array) {
  469. /* Not used, but must be present */
  470. frankenphp_register_known_variable("AUTH_TYPE", "", track_vars_array, false);
  471. frankenphp_register_known_variable("REMOTE_IDENT", "", track_vars_array,
  472. false);
  473. /* Allocated in frankenphp_update_server_context() */
  474. frankenphp_register_known_variable("CONTENT_TYPE",
  475. (char *)SG(request_info).content_type,
  476. track_vars_array, false);
  477. frankenphp_register_known_variable("PATH_TRANSLATED",
  478. (char *)SG(request_info).path_translated,
  479. track_vars_array, false);
  480. frankenphp_register_known_variable(
  481. "QUERY_STRING", SG(request_info).query_string, track_vars_array, false);
  482. frankenphp_register_known_variable("REMOTE_USER",
  483. (char *)SG(request_info).auth_user,
  484. track_vars_array, false);
  485. frankenphp_register_known_variable("REQUEST_METHOD",
  486. (char *)SG(request_info).request_method,
  487. track_vars_array, false);
  488. frankenphp_register_known_variable(
  489. "REQUEST_URI", SG(request_info).request_uri, track_vars_array, false);
  490. /* Known variables */
  491. frankenphp_register_known_variable("CONTENT_LENGTH", known_variables[0],
  492. track_vars_array, true);
  493. frankenphp_register_known_variable("DOCUMENT_ROOT", known_variables[1],
  494. track_vars_array, true);
  495. frankenphp_register_known_variable("DOCUMENT_URI", known_variables[2],
  496. track_vars_array, true);
  497. frankenphp_register_known_variable("GATEWAY_INTERFACE", known_variables[3],
  498. track_vars_array, true);
  499. frankenphp_register_known_variable("HTTP_HOST", known_variables[4],
  500. track_vars_array, true);
  501. frankenphp_register_known_variable("HTTPS", known_variables[5],
  502. track_vars_array, true);
  503. frankenphp_register_known_variable("PATH_INFO", known_variables[6],
  504. track_vars_array, true);
  505. frankenphp_register_known_variable("PHP_SELF", known_variables[7],
  506. track_vars_array, true);
  507. frankenphp_register_known_variable("REMOTE_ADDR", known_variables[8],
  508. track_vars_array,
  509. known_variables[8] != known_variables[9]);
  510. frankenphp_register_known_variable("REMOTE_HOST", known_variables[9],
  511. track_vars_array, true);
  512. frankenphp_register_known_variable("REMOTE_PORT", known_variables[10],
  513. track_vars_array, true);
  514. frankenphp_register_known_variable("REQUEST_SCHEME", known_variables[11],
  515. track_vars_array, true);
  516. frankenphp_register_known_variable("SCRIPT_FILENAME", known_variables[12],
  517. track_vars_array, true);
  518. frankenphp_register_known_variable("SCRIPT_NAME", known_variables[13],
  519. track_vars_array, true);
  520. frankenphp_register_known_variable("SERVER_NAME", known_variables[14],
  521. track_vars_array, true);
  522. frankenphp_register_known_variable("SERVER_PORT", known_variables[15],
  523. track_vars_array, true);
  524. frankenphp_register_known_variable("SERVER_PROTOCOL", known_variables[16],
  525. track_vars_array, true);
  526. frankenphp_register_known_variable("SERVER_SOFTWARE", known_variables[17],
  527. track_vars_array, true);
  528. frankenphp_register_known_variable("SSL_PROTOCOL", known_variables[18],
  529. track_vars_array, true);
  530. size_t new_val_len;
  531. for (size_t i = 0; i < size; i = i + 2) {
  532. if (sapi_module.input_filter(
  533. PARSE_SERVER, dynamic_variables[i], &dynamic_variables[i + 1],
  534. strlen(dynamic_variables[i + 1]), &new_val_len)) {
  535. php_register_variable_safe(dynamic_variables[i], dynamic_variables[i + 1],
  536. new_val_len, track_vars_array);
  537. }
  538. free(dynamic_variables[i]);
  539. free(dynamic_variables[i + 1]);
  540. }
  541. }
  542. static void frankenphp_register_variables(zval *track_vars_array) {
  543. /* https://www.php.net/manual/en/reserved.variables.server.php */
  544. frankenphp_server_context *ctx = SG(server_context);
  545. go_register_variables(ctx->current_request ? ctx->current_request
  546. : ctx->main_request,
  547. track_vars_array);
  548. }
  549. static void frankenphp_log_message(const char *message, int syslog_type_int) {
  550. go_log((char *)message, syslog_type_int);
  551. }
  552. sapi_module_struct frankenphp_sapi_module = {
  553. "frankenphp", /* name */
  554. "FrankenPHP", /* pretty name */
  555. frankenphp_startup, /* startup */
  556. php_module_shutdown_wrapper, /* shutdown */
  557. NULL, /* activate */
  558. frankenphp_deactivate, /* deactivate */
  559. frankenphp_ub_write, /* unbuffered write */
  560. frankenphp_sapi_flush, /* flush */
  561. NULL, /* get uid */
  562. NULL, /* getenv */
  563. php_error, /* error handler */
  564. NULL, /* header handler */
  565. frankenphp_send_headers, /* send headers handler */
  566. NULL, /* send header handler */
  567. frankenphp_read_post, /* read POST data */
  568. frankenphp_read_cookies, /* read Cookies */
  569. frankenphp_register_variables, /* register server variables */
  570. frankenphp_log_message, /* Log message */
  571. NULL, /* Get request time */
  572. NULL, /* Child terminate */
  573. STANDARD_SAPI_MODULE_PROPERTIES};
  574. static void *manager_thread(void *arg) {
  575. #ifdef ZTS
  576. // TODO: use tsrm_startup() directly as we know the number of expected threads
  577. php_tsrm_startup();
  578. /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/
  579. #ifdef PHP_WIN32
  580. ZEND_TSRMLS_CACHE_UPDATE();
  581. #endif
  582. #endif
  583. sapi_startup(&frankenphp_sapi_module);
  584. #ifndef ZEND_MAX_EXECUTION_TIMERS
  585. #if (PHP_VERSION_ID >= 80300)
  586. frankenphp_sapi_module.ini_entries = HARDCODED_INI;
  587. #else
  588. frankenphp_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
  589. memcpy(frankenphp_sapi_module.ini_entries, HARDCODED_INI,
  590. sizeof(HARDCODED_INI));
  591. #endif
  592. #endif
  593. frankenphp_sapi_module.startup(&frankenphp_sapi_module);
  594. threadpool thpool = thpool_init(*((int *)arg));
  595. free(arg);
  596. uintptr_t rh;
  597. while ((rh = go_fetch_request())) {
  598. thpool_add_work(thpool, go_execute_script, (void *)rh);
  599. }
  600. /* channel closed, shutdown gracefully */
  601. thpool_wait(thpool);
  602. thpool_destroy(thpool);
  603. frankenphp_sapi_module.shutdown(&frankenphp_sapi_module);
  604. sapi_shutdown();
  605. #ifdef ZTS
  606. tsrm_shutdown();
  607. #endif
  608. #if (PHP_VERSION_ID < 80300)
  609. if (frankenphp_sapi_module.ini_entries) {
  610. free(frankenphp_sapi_module.ini_entries);
  611. frankenphp_sapi_module.ini_entries = NULL;
  612. }
  613. #endif
  614. go_shutdown();
  615. return NULL;
  616. }
  617. int frankenphp_init(int num_threads) {
  618. pthread_t thread;
  619. int *num_threads_ptr = calloc(1, sizeof(int));
  620. *num_threads_ptr = num_threads;
  621. if (pthread_create(&thread, NULL, *manager_thread, (void *)num_threads_ptr) !=
  622. 0) {
  623. go_shutdown();
  624. return -1;
  625. }
  626. return pthread_detach(thread);
  627. }
  628. int frankenphp_request_startup() {
  629. if (php_request_startup() == SUCCESS) {
  630. return SUCCESS;
  631. }
  632. frankenphp_server_context *ctx = SG(server_context);
  633. SG(server_context) = NULL;
  634. free(ctx);
  635. php_request_shutdown((void *)0);
  636. return FAILURE;
  637. }
  638. int frankenphp_execute_script(char *file_name) {
  639. if (frankenphp_request_startup() == FAILURE) {
  640. free(file_name);
  641. return FAILURE;
  642. }
  643. int status = SUCCESS;
  644. zend_file_handle file_handle;
  645. zend_stream_init_filename(&file_handle, file_name);
  646. free(file_name);
  647. file_handle.primary_script = 1;
  648. zend_first_try {
  649. EG(exit_status) = 0;
  650. php_execute_script(&file_handle);
  651. status = EG(exit_status);
  652. }
  653. zend_catch { status = EG(exit_status); }
  654. zend_end_try();
  655. zend_destroy_file_handle(&file_handle);
  656. frankenphp_clean_server_context();
  657. frankenphp_request_shutdown();
  658. return status;
  659. }
  660. // Use global variables to store CLI arguments to prevent useless allocations
  661. static char *cli_script;
  662. static int cli_argc;
  663. static char **cli_argv;
  664. // CLI code is adapted from https://github.com/php/php-src/blob/master/sapi/cli/php_cli.c
  665. // Copyright (c) The PHP Group
  666. // Licensed under The PHP License
  667. // Original uthors: Edin Kadribasic <edink@php.net>, Marcus Boerger <helly@php.net> and Johannes Schlueter <johannes@php.net>
  668. // Parts based on CGI SAPI Module by Rasmus Lerdorf, Stig Bakken and Zeev Suraski
  669. static void cli_register_file_handles(bool no_close) /* {{{ */
  670. {
  671. php_stream *s_in, *s_out, *s_err;
  672. php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL;
  673. zend_constant ic, oc, ec;
  674. s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in);
  675. s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
  676. s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
  677. if (s_in == NULL || s_out == NULL || s_err == NULL) {
  678. if (s_in)
  679. php_stream_close(s_in);
  680. if (s_out)
  681. php_stream_close(s_out);
  682. if (s_err)
  683. php_stream_close(s_err);
  684. return;
  685. }
  686. if (no_close) {
  687. s_in->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  688. s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  689. s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  690. }
  691. // s_in_process = s_in;
  692. php_stream_to_zval(s_in, &ic.value);
  693. php_stream_to_zval(s_out, &oc.value);
  694. php_stream_to_zval(s_err, &ec.value);
  695. ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0);
  696. ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0);
  697. zend_register_constant(&ic);
  698. ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0);
  699. oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0);
  700. zend_register_constant(&oc);
  701. ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0);
  702. ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0);
  703. zend_register_constant(&ec);
  704. }
  705. /* }}} */
  706. static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */
  707. {
  708. size_t len;
  709. char *docroot = "";
  710. /* In CGI mode, we consider the environment to be a part of the server
  711. * variables
  712. */
  713. php_import_environment_variables(track_vars_array);
  714. /* Build the special-case PHP_SELF variable for the CLI version */
  715. len = strlen(cli_script);
  716. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &cli_script, len,
  717. &len)) {
  718. php_register_variable_safe("PHP_SELF", cli_script, len, track_vars_array);
  719. }
  720. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &cli_script, len,
  721. &len)) {
  722. php_register_variable_safe("SCRIPT_NAME", cli_script, len,
  723. track_vars_array);
  724. }
  725. /* filenames are empty for stdin */
  726. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &cli_script,
  727. len, &len)) {
  728. php_register_variable_safe("SCRIPT_FILENAME", cli_script, len,
  729. track_vars_array);
  730. }
  731. if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &cli_script,
  732. len, &len)) {
  733. php_register_variable_safe("PATH_TRANSLATED", cli_script, len,
  734. track_vars_array);
  735. }
  736. /* just make it available */
  737. len = 0U;
  738. if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len,
  739. &len)) {
  740. php_register_variable_safe("DOCUMENT_ROOT", docroot, len, track_vars_array);
  741. }
  742. }
  743. /* }}} */
  744. static void *execute_script_cli(void *arg) {
  745. void *exit_status;
  746. // The SAPI name "cli" is hardcoded into too many programs... let's usurp it.
  747. php_embed_module.name = "cli";
  748. php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP";
  749. php_embed_module.register_server_variables = sapi_cli_register_variables;
  750. php_embed_init(cli_argc, cli_argv);
  751. cli_register_file_handles(false);
  752. zend_first_try {
  753. zend_file_handle file_handle;
  754. zend_stream_init_filename(&file_handle, cli_script);
  755. CG(skip_shebang) = 1;
  756. php_execute_script(&file_handle);
  757. }
  758. zend_end_try();
  759. exit_status = (void *)(intptr_t)EG(exit_status);
  760. php_embed_shutdown();
  761. return exit_status;
  762. }
  763. int frankenphp_execute_script_cli(char *script, int argc, char **argv) {
  764. pthread_t thread;
  765. int err;
  766. void *exit_status;
  767. cli_script = script;
  768. cli_argc = argc;
  769. cli_argv = argv;
  770. // Start the script in a dedicated thread to prevent conflicts between Go and
  771. // PHP signal handlers
  772. err = pthread_create(&thread, NULL, execute_script_cli, NULL);
  773. if (err != 0) {
  774. return err;
  775. }
  776. err = pthread_join(thread, &exit_status);
  777. if (err != 0) {
  778. return err;
  779. }
  780. return (intptr_t)exit_status;
  781. }