frankenphp.c 30 KB

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