frankenphp.c 28 KB

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