frankenphp.c 30 KB

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