frankenphp.c 29 KB

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