frankenphp.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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. static void *manager_thread(void *arg) {
  592. // SIGPIPE must be masked in non-Go threads:
  593. // https://pkg.go.dev/os/signal#hdr-Go_programs_that_use_cgo_or_SWIG
  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. int num_threads = *((int *)arg);
  602. free(arg);
  603. arg = NULL;
  604. #ifdef ZTS
  605. #if (PHP_VERSION_ID >= 80300)
  606. php_tsrm_startup_ex(num_threads);
  607. #else
  608. php_tsrm_startup();
  609. #endif
  610. /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/
  611. #ifdef PHP_WIN32
  612. ZEND_TSRMLS_CACHE_UPDATE();
  613. #endif
  614. #endif
  615. sapi_startup(&frankenphp_sapi_module);
  616. #ifndef ZEND_MAX_EXECUTION_TIMERS
  617. #if (PHP_VERSION_ID >= 80300)
  618. frankenphp_sapi_module.ini_entries = HARDCODED_INI;
  619. #else
  620. frankenphp_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
  621. memcpy(frankenphp_sapi_module.ini_entries, HARDCODED_INI,
  622. sizeof(HARDCODED_INI));
  623. #endif
  624. #endif
  625. frankenphp_sapi_module.startup(&frankenphp_sapi_module);
  626. threadpool thpool = thpool_init(num_threads);
  627. uintptr_t rh;
  628. while ((rh = go_fetch_request())) {
  629. thpool_add_work(thpool, go_execute_script, (void *)rh);
  630. }
  631. /* channel closed, shutdown gracefully */
  632. thpool_wait(thpool);
  633. thpool_destroy(thpool);
  634. frankenphp_sapi_module.shutdown(&frankenphp_sapi_module);
  635. sapi_shutdown();
  636. #ifdef ZTS
  637. tsrm_shutdown();
  638. #endif
  639. #if (PHP_VERSION_ID < 80300)
  640. if (frankenphp_sapi_module.ini_entries) {
  641. free(frankenphp_sapi_module.ini_entries);
  642. frankenphp_sapi_module.ini_entries = NULL;
  643. }
  644. #endif
  645. go_shutdown();
  646. return NULL;
  647. }
  648. int frankenphp_init(int num_threads) {
  649. pthread_t thread;
  650. int *num_threads_ptr = calloc(1, sizeof(int));
  651. *num_threads_ptr = num_threads;
  652. if (pthread_create(&thread, NULL, *manager_thread, (void *)num_threads_ptr) !=
  653. 0) {
  654. go_shutdown();
  655. return -1;
  656. }
  657. return pthread_detach(thread);
  658. }
  659. int frankenphp_request_startup() {
  660. if (php_request_startup() == SUCCESS) {
  661. return SUCCESS;
  662. }
  663. frankenphp_server_context *ctx = SG(server_context);
  664. SG(server_context) = NULL;
  665. free(ctx);
  666. ctx = NULL;
  667. php_request_shutdown((void *)0);
  668. return FAILURE;
  669. }
  670. int frankenphp_execute_script(char *file_name) {
  671. if (frankenphp_request_startup() == FAILURE) {
  672. free(file_name);
  673. file_name = NULL;
  674. return FAILURE;
  675. }
  676. int status = SUCCESS;
  677. zend_file_handle file_handle;
  678. zend_stream_init_filename(&file_handle, file_name);
  679. free(file_name);
  680. file_name = NULL;
  681. file_handle.primary_script = 1;
  682. zend_first_try {
  683. EG(exit_status) = 0;
  684. php_execute_script(&file_handle);
  685. status = EG(exit_status);
  686. }
  687. zend_catch { status = EG(exit_status); }
  688. zend_end_try();
  689. zend_destroy_file_handle(&file_handle);
  690. frankenphp_clean_server_context();
  691. frankenphp_request_shutdown();
  692. return status;
  693. }
  694. // Use global variables to store CLI arguments to prevent useless allocations
  695. static char *cli_script;
  696. static int cli_argc;
  697. static char **cli_argv;
  698. // CLI code is adapted from
  699. // https://github.com/php/php-src/blob/master/sapi/cli/php_cli.c Copyright (c)
  700. // The PHP Group Licensed under The PHP License Original uthors: Edin Kadribasic
  701. // <edink@php.net>, Marcus Boerger <helly@php.net> and Johannes Schlueter
  702. // <johannes@php.net> Parts based on CGI SAPI Module by Rasmus Lerdorf, Stig
  703. // Bakken and Zeev Suraski
  704. static void cli_register_file_handles(bool no_close) /* {{{ */
  705. {
  706. php_stream *s_in, *s_out, *s_err;
  707. php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL;
  708. zend_constant ic, oc, ec;
  709. s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in);
  710. s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
  711. s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
  712. if (s_in == NULL || s_out == NULL || s_err == NULL) {
  713. if (s_in)
  714. php_stream_close(s_in);
  715. if (s_out)
  716. php_stream_close(s_out);
  717. if (s_err)
  718. php_stream_close(s_err);
  719. return;
  720. }
  721. if (no_close) {
  722. s_in->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  723. s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  724. s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  725. }
  726. // s_in_process = s_in;
  727. php_stream_to_zval(s_in, &ic.value);
  728. php_stream_to_zval(s_out, &oc.value);
  729. php_stream_to_zval(s_err, &ec.value);
  730. ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0);
  731. ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0);
  732. zend_register_constant(&ic);
  733. ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0);
  734. oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0);
  735. zend_register_constant(&oc);
  736. ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0);
  737. ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0);
  738. zend_register_constant(&ec);
  739. }
  740. /* }}} */
  741. static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */
  742. {
  743. size_t len;
  744. char *docroot = "";
  745. /* In CGI mode, we consider the environment to be a part of the server
  746. * variables
  747. */
  748. php_import_environment_variables(track_vars_array);
  749. /* Build the special-case PHP_SELF variable for the CLI version */
  750. len = strlen(cli_script);
  751. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &cli_script, len,
  752. &len)) {
  753. php_register_variable_safe("PHP_SELF", cli_script, len, track_vars_array);
  754. }
  755. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &cli_script, len,
  756. &len)) {
  757. php_register_variable_safe("SCRIPT_NAME", cli_script, len,
  758. track_vars_array);
  759. }
  760. /* filenames are empty for stdin */
  761. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &cli_script,
  762. len, &len)) {
  763. php_register_variable_safe("SCRIPT_FILENAME", cli_script, len,
  764. track_vars_array);
  765. }
  766. if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &cli_script,
  767. len, &len)) {
  768. php_register_variable_safe("PATH_TRANSLATED", cli_script, len,
  769. track_vars_array);
  770. }
  771. /* just make it available */
  772. len = 0U;
  773. if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len,
  774. &len)) {
  775. php_register_variable_safe("DOCUMENT_ROOT", docroot, len, track_vars_array);
  776. }
  777. }
  778. /* }}} */
  779. static void *execute_script_cli(void *arg) {
  780. void *exit_status;
  781. // The SAPI name "cli" is hardcoded into too many programs... let's usurp it.
  782. php_embed_module.name = "cli";
  783. php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP";
  784. php_embed_module.register_server_variables = sapi_cli_register_variables;
  785. php_embed_init(cli_argc, cli_argv);
  786. cli_register_file_handles(false);
  787. zend_first_try {
  788. zend_file_handle file_handle;
  789. zend_stream_init_filename(&file_handle, cli_script);
  790. CG(skip_shebang) = 1;
  791. php_execute_script(&file_handle);
  792. }
  793. zend_end_try();
  794. exit_status = (void *)(intptr_t)EG(exit_status);
  795. php_embed_shutdown();
  796. return exit_status;
  797. }
  798. int frankenphp_execute_script_cli(char *script, int argc, char **argv) {
  799. pthread_t thread;
  800. int err;
  801. void *exit_status;
  802. cli_script = script;
  803. cli_argc = argc;
  804. cli_argv = argv;
  805. // Start the script in a dedicated thread to prevent conflicts between Go and
  806. // PHP signal handlers
  807. err = pthread_create(&thread, NULL, execute_script_cli, NULL);
  808. if (err != 0) {
  809. return err;
  810. }
  811. err = pthread_join(thread, &exit_status);
  812. if (err != 0) {
  813. return err;
  814. }
  815. return (intptr_t)exit_status;
  816. }