frankenphp.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  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_ini.h>
  13. #include <php_main.h>
  14. #include <php_output.h>
  15. #include <php_variables.h>
  16. #include <pthread.h>
  17. #include <sapi/embed/php_embed.h>
  18. #include <signal.h>
  19. #include <stdint.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <unistd.h>
  23. #if defined(__linux__)
  24. #include <sys/prctl.h>
  25. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  26. #include <pthread_np.h>
  27. #endif
  28. #include "_cgo_export.h"
  29. #include "frankenphp_arginfo.h"
  30. #if defined(PHP_WIN32) && defined(ZTS)
  31. ZEND_TSRMLS_CACHE_DEFINE()
  32. #endif
  33. /* Timeouts are currently fundamentally broken with ZTS except on Linux and
  34. * FreeBSD: https://bugs.php.net/bug.php?id=79464 */
  35. #ifndef ZEND_MAX_EXECUTION_TIMERS
  36. static const char HARDCODED_INI[] = "max_execution_time=0\n"
  37. "max_input_time=-1\n\0";
  38. #endif
  39. static const char *MODULES_TO_RELOAD[] = {"filter", "session", NULL};
  40. frankenphp_version frankenphp_get_version() {
  41. return (frankenphp_version){
  42. PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION,
  43. PHP_EXTRA_VERSION, PHP_VERSION, PHP_VERSION_ID,
  44. };
  45. }
  46. frankenphp_config frankenphp_get_config() {
  47. return (frankenphp_config){
  48. frankenphp_get_version(),
  49. #ifdef ZTS
  50. true,
  51. #else
  52. false,
  53. #endif
  54. #ifdef ZEND_SIGNALS
  55. true,
  56. #else
  57. false,
  58. #endif
  59. #ifdef ZEND_MAX_EXECUTION_TIMERS
  60. true,
  61. #else
  62. false,
  63. #endif
  64. };
  65. }
  66. typedef struct frankenphp_server_context {
  67. bool has_main_request;
  68. bool has_active_request;
  69. bool worker_ready;
  70. char *cookie_data;
  71. bool finished;
  72. } frankenphp_server_context;
  73. __thread bool should_filter_var = 0;
  74. __thread frankenphp_server_context *local_ctx = NULL;
  75. __thread uintptr_t thread_index;
  76. __thread zval *os_environment = NULL;
  77. static void frankenphp_free_request_context() {
  78. frankenphp_server_context *ctx = SG(server_context);
  79. free(ctx->cookie_data);
  80. ctx->cookie_data = NULL;
  81. /* Is freed via thread.Unpin() at the end of each request */
  82. SG(request_info).auth_password = NULL;
  83. SG(request_info).auth_user = NULL;
  84. SG(request_info).request_method = NULL;
  85. SG(request_info).query_string = NULL;
  86. SG(request_info).content_type = NULL;
  87. SG(request_info).path_translated = NULL;
  88. SG(request_info).request_uri = NULL;
  89. }
  90. static void frankenphp_destroy_super_globals() {
  91. zend_try {
  92. for (int i = 0; i < NUM_TRACK_VARS; i++) {
  93. zval_ptr_dtor_nogc(&PG(http_globals)[i]);
  94. }
  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. /* SAPI related shutdown (free stuff) */
  117. frankenphp_free_request_context();
  118. zend_try { sapi_deactivate(); }
  119. zend_end_try();
  120. zend_set_memory_limit(PG(memory_limit));
  121. /* TODO: remove next line when https://github.com/php/php-src/pull/14499 will
  122. * be available */
  123. SG(rfc1867_uploaded_files) = NULL;
  124. }
  125. PHPAPI void get_full_env(zval *track_vars_array) {
  126. struct go_getfullenv_return full_env = go_getfullenv(thread_index);
  127. for (int i = 0; i < full_env.r1; i++) {
  128. go_string key = full_env.r0[i * 2];
  129. go_string val = full_env.r0[i * 2 + 1];
  130. // create PHP strings for key and value
  131. zend_string *key_str = zend_string_init(key.data, key.len, 0);
  132. zend_string *val_str = zend_string_init(val.data, val.len, 0);
  133. // add to the associative array
  134. add_assoc_str(track_vars_array, ZSTR_VAL(key_str), val_str);
  135. // release the key string
  136. zend_string_release(key_str);
  137. }
  138. }
  139. /* Adapted from php_request_startup() */
  140. static int frankenphp_worker_request_startup() {
  141. int retval = SUCCESS;
  142. zend_try {
  143. frankenphp_destroy_super_globals();
  144. php_output_activate();
  145. /* initialize global variables */
  146. PG(header_is_being_sent) = 0;
  147. PG(connection_status) = PHP_CONNECTION_NORMAL;
  148. /* Keep the current execution context */
  149. sapi_activate();
  150. #ifdef ZEND_MAX_EXECUTION_TIMERS
  151. if (PG(max_input_time) == -1) {
  152. zend_set_timeout(EG(timeout_seconds), 1);
  153. } else {
  154. zend_set_timeout(PG(max_input_time), 1);
  155. }
  156. #endif
  157. if (PG(expose_php)) {
  158. sapi_add_header(SAPI_PHP_VERSION_HEADER,
  159. sizeof(SAPI_PHP_VERSION_HEADER) - 1, 1);
  160. }
  161. if (PG(output_handler) && PG(output_handler)[0]) {
  162. zval oh;
  163. ZVAL_STRING(&oh, PG(output_handler));
  164. php_output_start_user(&oh, 0, PHP_OUTPUT_HANDLER_STDFLAGS);
  165. zval_ptr_dtor(&oh);
  166. } else if (PG(output_buffering)) {
  167. php_output_start_user(NULL,
  168. PG(output_buffering) > 1 ? PG(output_buffering) : 0,
  169. PHP_OUTPUT_HANDLER_STDFLAGS);
  170. } else if (PG(implicit_flush)) {
  171. php_output_set_implicit_flush(1);
  172. }
  173. php_hash_environment();
  174. zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER));
  175. /* Unfinish the request */
  176. frankenphp_server_context *ctx = SG(server_context);
  177. ctx->finished = false;
  178. /* TODO: store the list of modules to reload in a global module variable */
  179. const char **module_name;
  180. zend_module_entry *module;
  181. for (module_name = MODULES_TO_RELOAD; *module_name; module_name++) {
  182. if ((module = zend_hash_str_find_ptr(&module_registry, *module_name,
  183. sizeof(*module_name) - 1)) &&
  184. module->request_startup_func) {
  185. module->request_startup_func(module->type, module->module_number);
  186. }
  187. }
  188. }
  189. zend_catch { retval = FAILURE; }
  190. zend_end_try();
  191. SG(sapi_started) = 1;
  192. return retval;
  193. }
  194. PHP_FUNCTION(frankenphp_finish_request) { /* {{{ */
  195. if (zend_parse_parameters_none() == FAILURE) {
  196. RETURN_THROWS();
  197. }
  198. frankenphp_server_context *ctx = SG(server_context);
  199. if (ctx->finished) {
  200. RETURN_FALSE;
  201. }
  202. php_output_end_all();
  203. php_header();
  204. if (ctx->has_active_request) {
  205. go_frankenphp_finish_request(thread_index, false);
  206. }
  207. ctx->finished = true;
  208. RETURN_TRUE;
  209. } /* }}} */
  210. /* {{{ Call go's putenv to prevent race conditions */
  211. PHP_FUNCTION(frankenphp_putenv) {
  212. char *setting;
  213. size_t setting_len;
  214. ZEND_PARSE_PARAMETERS_START(1, 1)
  215. Z_PARAM_STRING(setting, setting_len)
  216. ZEND_PARSE_PARAMETERS_END();
  217. // Cast str_len to int (ensure it fits in an int)
  218. if (setting_len > INT_MAX) {
  219. php_error(E_WARNING, "String length exceeds maximum integer value");
  220. RETURN_FALSE;
  221. }
  222. if (go_putenv(setting, (int)setting_len)) {
  223. RETURN_TRUE;
  224. } else {
  225. RETURN_FALSE;
  226. }
  227. } /* }}} */
  228. /* {{{ Call go's getenv to prevent race conditions */
  229. PHP_FUNCTION(frankenphp_getenv) {
  230. char *name = NULL;
  231. size_t name_len = 0;
  232. bool local_only = 0;
  233. ZEND_PARSE_PARAMETERS_START(0, 2)
  234. Z_PARAM_OPTIONAL
  235. Z_PARAM_STRING_OR_NULL(name, name_len)
  236. Z_PARAM_BOOL(local_only)
  237. ZEND_PARSE_PARAMETERS_END();
  238. if (!name) {
  239. array_init(return_value);
  240. get_full_env(return_value);
  241. return;
  242. }
  243. go_string gname = {name_len, name};
  244. struct go_getenv_return result = go_getenv(thread_index, &gname);
  245. if (result.r0) {
  246. // Return the single environment variable as a string
  247. RETVAL_STRINGL(result.r1->data, result.r1->len);
  248. } else {
  249. // Environment variable does not exist
  250. RETVAL_FALSE;
  251. }
  252. } /* }}} */
  253. /* {{{ Fetch all HTTP request headers */
  254. PHP_FUNCTION(frankenphp_request_headers) {
  255. if (zend_parse_parameters_none() == FAILURE) {
  256. RETURN_THROWS();
  257. }
  258. frankenphp_server_context *ctx = SG(server_context);
  259. struct go_apache_request_headers_return headers =
  260. go_apache_request_headers(thread_index, ctx->has_active_request);
  261. array_init_size(return_value, headers.r1);
  262. for (size_t i = 0; i < headers.r1; i++) {
  263. go_string key = headers.r0[i * 2];
  264. go_string val = headers.r0[i * 2 + 1];
  265. add_assoc_stringl_ex(return_value, key.data, key.len, val.data, val.len);
  266. }
  267. }
  268. /* }}} */
  269. /* add_response_header and apache_response_headers are copied from
  270. * https://github.com/php/php-src/blob/master/sapi/cli/php_cli_server.c
  271. * Copyright (c) The PHP Group
  272. * Licensed under The PHP License
  273. * Original authors: Moriyoshi Koizumi <moriyoshi@php.net> and Xinchen Hui
  274. * <laruence@php.net>
  275. */
  276. static void add_response_header(sapi_header_struct *h,
  277. zval *return_value) /* {{{ */
  278. {
  279. if (h->header_len > 0) {
  280. char *s;
  281. size_t len = 0;
  282. ALLOCA_FLAG(use_heap)
  283. char *p = strchr(h->header, ':');
  284. if (NULL != p) {
  285. len = p - h->header;
  286. }
  287. if (len > 0) {
  288. while (len != 0 &&
  289. (h->header[len - 1] == ' ' || h->header[len - 1] == '\t')) {
  290. len--;
  291. }
  292. if (len) {
  293. s = do_alloca(len + 1, use_heap);
  294. memcpy(s, h->header, len);
  295. s[len] = 0;
  296. do {
  297. p++;
  298. } while (*p == ' ' || *p == '\t');
  299. add_assoc_stringl_ex(return_value, s, len, p,
  300. h->header_len - (p - h->header));
  301. free_alloca(s, use_heap);
  302. }
  303. }
  304. }
  305. }
  306. /* }}} */
  307. PHP_FUNCTION(frankenphp_response_headers) /* {{{ */
  308. {
  309. if (zend_parse_parameters_none() == FAILURE) {
  310. RETURN_THROWS();
  311. }
  312. array_init(return_value);
  313. zend_llist_apply_with_argument(
  314. &SG(sapi_headers).headers,
  315. (llist_apply_with_arg_func_t)add_response_header, return_value);
  316. }
  317. /* }}} */
  318. PHP_FUNCTION(frankenphp_handle_request) {
  319. zend_fcall_info fci;
  320. zend_fcall_info_cache fcc;
  321. ZEND_PARSE_PARAMETERS_START(1, 1)
  322. Z_PARAM_FUNC(fci, fcc)
  323. ZEND_PARSE_PARAMETERS_END();
  324. frankenphp_server_context *ctx = SG(server_context);
  325. if (!ctx->has_main_request) {
  326. /* not a worker, throw an error */
  327. zend_throw_exception(
  328. spl_ce_RuntimeException,
  329. "frankenphp_handle_request() called while not in worker mode", 0);
  330. RETURN_THROWS();
  331. }
  332. if (!ctx->worker_ready) {
  333. /* Clean the first dummy request created to initialize the worker */
  334. frankenphp_worker_request_shutdown();
  335. ctx->worker_ready = true;
  336. }
  337. #ifdef ZEND_MAX_EXECUTION_TIMERS
  338. /* Disable timeouts while waiting for a request to handle */
  339. zend_unset_timeout();
  340. #endif
  341. bool request = go_frankenphp_worker_handle_request_start(thread_index);
  342. if (frankenphp_worker_request_startup() == FAILURE
  343. /* Shutting down */
  344. || !request) {
  345. RETURN_FALSE;
  346. }
  347. #ifdef ZEND_MAX_EXECUTION_TIMERS
  348. /*
  349. * Reset default timeout
  350. */
  351. if (PG(max_input_time) != -1) {
  352. zend_set_timeout(INI_INT("max_execution_time"), 0);
  353. }
  354. #endif
  355. /* Call the PHP func */
  356. zval retval = {0};
  357. fci.size = sizeof fci;
  358. fci.retval = &retval;
  359. if (zend_call_function(&fci, &fcc) == SUCCESS) {
  360. zval_ptr_dtor(&retval);
  361. }
  362. /*
  363. * If an exception occured, print the message to the client before closing the
  364. * connection
  365. */
  366. if (EG(exception)) {
  367. zend_exception_error(EG(exception), E_ERROR);
  368. }
  369. frankenphp_worker_request_shutdown();
  370. ctx->has_active_request = false;
  371. go_frankenphp_finish_request(thread_index, true);
  372. RETURN_TRUE;
  373. }
  374. PHP_FUNCTION(headers_send) {
  375. zend_long response_code = 200;
  376. ZEND_PARSE_PARAMETERS_START(0, 1)
  377. Z_PARAM_OPTIONAL
  378. Z_PARAM_LONG(response_code)
  379. ZEND_PARSE_PARAMETERS_END();
  380. int previous_status_code = SG(sapi_headers).http_response_code;
  381. SG(sapi_headers).http_response_code = response_code;
  382. if (response_code >= 100 && response_code < 200) {
  383. int ret = sapi_module.send_headers(&SG(sapi_headers));
  384. SG(sapi_headers).http_response_code = previous_status_code;
  385. RETURN_LONG(ret);
  386. }
  387. RETURN_LONG(sapi_send_headers());
  388. }
  389. PHP_MINIT_FUNCTION(frankenphp) {
  390. zend_function *func;
  391. // Override putenv
  392. func = zend_hash_str_find_ptr(CG(function_table), "putenv",
  393. sizeof("putenv") - 1);
  394. if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION) {
  395. ((zend_internal_function *)func)->handler = ZEND_FN(frankenphp_putenv);
  396. } else {
  397. php_error(E_WARNING, "Failed to find built-in putenv function");
  398. }
  399. // Override getenv
  400. func = zend_hash_str_find_ptr(CG(function_table), "getenv",
  401. sizeof("getenv") - 1);
  402. if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION) {
  403. ((zend_internal_function *)func)->handler = ZEND_FN(frankenphp_getenv);
  404. } else {
  405. php_error(E_WARNING, "Failed to find built-in getenv function");
  406. }
  407. return SUCCESS;
  408. }
  409. static zend_module_entry frankenphp_module = {
  410. STANDARD_MODULE_HEADER,
  411. "frankenphp",
  412. ext_functions, /* function table */
  413. PHP_MINIT(frankenphp), /* initialization */
  414. NULL, /* shutdown */
  415. NULL, /* request initialization */
  416. NULL, /* request shutdown */
  417. NULL, /* information */
  418. TOSTRING(FRANKENPHP_VERSION),
  419. STANDARD_MODULE_PROPERTIES};
  420. static void frankenphp_request_shutdown() {
  421. frankenphp_server_context *ctx = SG(server_context);
  422. if (ctx->has_main_request && ctx->has_active_request) {
  423. frankenphp_destroy_super_globals();
  424. }
  425. php_request_shutdown((void *)0);
  426. frankenphp_free_request_context();
  427. memset(local_ctx, 0, sizeof(frankenphp_server_context));
  428. }
  429. int frankenphp_update_server_context(
  430. bool create, bool has_main_request, bool has_active_request,
  431. const char *request_method, char *query_string, zend_long content_length,
  432. char *path_translated, char *request_uri, const char *content_type,
  433. char *auth_user, char *auth_password, int proto_num) {
  434. frankenphp_server_context *ctx;
  435. if (create) {
  436. ctx = local_ctx;
  437. ctx->worker_ready = false;
  438. ctx->cookie_data = NULL;
  439. ctx->finished = false;
  440. SG(server_context) = ctx;
  441. } else {
  442. ctx = (frankenphp_server_context *)SG(server_context);
  443. }
  444. // It is not reset by zend engine, set it to 200.
  445. SG(sapi_headers).http_response_code = 200;
  446. ctx->has_main_request = has_main_request;
  447. ctx->has_active_request = has_active_request;
  448. SG(request_info).auth_password = auth_password;
  449. SG(request_info).auth_user = auth_user;
  450. SG(request_info).request_method = request_method;
  451. SG(request_info).query_string = query_string;
  452. SG(request_info).content_type = content_type;
  453. SG(request_info).content_length = content_length;
  454. SG(request_info).path_translated = path_translated;
  455. SG(request_info).request_uri = request_uri;
  456. SG(request_info).proto_num = proto_num;
  457. return SUCCESS;
  458. }
  459. static int frankenphp_startup(sapi_module_struct *sapi_module) {
  460. php_import_environment_variables = get_full_env;
  461. return php_module_startup(sapi_module, &frankenphp_module);
  462. }
  463. static int frankenphp_deactivate(void) {
  464. /* TODO: flush everything */
  465. return SUCCESS;
  466. }
  467. static size_t frankenphp_ub_write(const char *str, size_t str_length) {
  468. frankenphp_server_context *ctx = SG(server_context);
  469. if (ctx->finished) {
  470. /* TODO: maybe log a warning that we tried to write to a finished request?
  471. */
  472. return 0;
  473. }
  474. struct go_ub_write_return result =
  475. go_ub_write(thread_index, (char *)str, str_length);
  476. if (result.r1) {
  477. php_handle_aborted_connection();
  478. }
  479. return result.r0;
  480. }
  481. static int frankenphp_send_headers(sapi_headers_struct *sapi_headers) {
  482. if (SG(request_info).no_headers == 1) {
  483. return SAPI_HEADER_SENT_SUCCESSFULLY;
  484. }
  485. int status;
  486. frankenphp_server_context *ctx = SG(server_context);
  487. if (!ctx->has_active_request) {
  488. return SAPI_HEADER_SEND_FAILED;
  489. }
  490. if (SG(sapi_headers).http_status_line) {
  491. status = atoi((SG(sapi_headers).http_status_line) + 9);
  492. } else {
  493. status = SG(sapi_headers).http_response_code;
  494. if (!status) {
  495. status = 200;
  496. }
  497. }
  498. go_write_headers(thread_index, status, &sapi_headers->headers);
  499. return SAPI_HEADER_SENT_SUCCESSFULLY;
  500. }
  501. static void frankenphp_sapi_flush(void *server_context) {
  502. frankenphp_server_context *ctx = (frankenphp_server_context *)server_context;
  503. if (ctx && ctx->has_active_request && go_sapi_flush(thread_index)) {
  504. php_handle_aborted_connection();
  505. }
  506. }
  507. static size_t frankenphp_read_post(char *buffer, size_t count_bytes) {
  508. frankenphp_server_context *ctx = SG(server_context);
  509. return ctx->has_active_request
  510. ? go_read_post(thread_index, buffer, count_bytes)
  511. : 0;
  512. }
  513. static char *frankenphp_read_cookies(void) {
  514. frankenphp_server_context *ctx = SG(server_context);
  515. if (!ctx->has_active_request) {
  516. return "";
  517. }
  518. ctx->cookie_data = go_read_cookies(thread_index);
  519. return ctx->cookie_data;
  520. }
  521. /* all variables with well defined keys can safely be registered like this */
  522. void frankenphp_register_trusted_var(zend_string *z_key, char *value,
  523. int val_len, zval *track_vars_array) {
  524. if (value == NULL) {
  525. value = "";
  526. }
  527. size_t new_val_len = val_len;
  528. if (!should_filter_var ||
  529. sapi_module.input_filter(PARSE_SERVER, ZSTR_VAL(z_key), &value,
  530. new_val_len, &new_val_len)) {
  531. zval z_value;
  532. ZVAL_STRINGL_FAST(&z_value, value, new_val_len);
  533. zend_hash_update_ind(Z_ARRVAL_P(track_vars_array), z_key, &z_value);
  534. }
  535. }
  536. /** Persistent strings are ignored by the PHP GC, we have to release these
  537. * ourselves **/
  538. zend_string *frankenphp_init_persistent_string(const char *string, size_t len) {
  539. return zend_string_init(string, len, 1);
  540. }
  541. void frankenphp_release_zend_string(zend_string *z_string) {
  542. zend_string_release(z_string);
  543. }
  544. static void
  545. frankenphp_register_variable_from_request_info(zend_string *zKey, char *value,
  546. bool must_be_present,
  547. zval *track_vars_array) {
  548. if (value != NULL) {
  549. frankenphp_register_trusted_var(zKey, value, strlen(value),
  550. track_vars_array);
  551. } else if (must_be_present) {
  552. frankenphp_register_trusted_var(zKey, "", 0, track_vars_array);
  553. }
  554. }
  555. void frankenphp_register_variables_from_request_info(
  556. zval *track_vars_array, zend_string *content_type,
  557. zend_string *path_translated, zend_string *query_string,
  558. zend_string *auth_user, zend_string *request_method,
  559. zend_string *request_uri) {
  560. frankenphp_register_variable_from_request_info(
  561. content_type, (char *)SG(request_info).content_type, false,
  562. track_vars_array);
  563. frankenphp_register_variable_from_request_info(
  564. path_translated, (char *)SG(request_info).path_translated, false,
  565. track_vars_array);
  566. frankenphp_register_variable_from_request_info(
  567. query_string, SG(request_info).query_string, true, track_vars_array);
  568. frankenphp_register_variable_from_request_info(
  569. auth_user, (char *)SG(request_info).auth_user, false, track_vars_array);
  570. frankenphp_register_variable_from_request_info(
  571. request_method, (char *)SG(request_info).request_method, false,
  572. track_vars_array);
  573. frankenphp_register_variable_from_request_info(
  574. request_uri, SG(request_info).request_uri, true, track_vars_array);
  575. }
  576. /* variables with user-defined keys must be registered safely
  577. * see: php_variables.c -> php_register_variable_ex (#1106) */
  578. void frankenphp_register_variable_safe(char *key, char *val, size_t val_len,
  579. zval *track_vars_array) {
  580. if (key == NULL) {
  581. return;
  582. }
  583. if (val == NULL) {
  584. val = "";
  585. }
  586. size_t new_val_len = val_len;
  587. if (!should_filter_var ||
  588. sapi_module.input_filter(PARSE_SERVER, key, &val, new_val_len,
  589. &new_val_len)) {
  590. php_register_variable_safe(key, val, new_val_len, track_vars_array);
  591. }
  592. }
  593. static void frankenphp_register_variables(zval *track_vars_array) {
  594. /* https://www.php.net/manual/en/reserved.variables.server.php */
  595. /* In CGI mode, we consider the environment to be a part of the server
  596. * variables.
  597. */
  598. frankenphp_server_context *ctx = SG(server_context);
  599. /* in non-worker mode we import the os environment regularly */
  600. if (!ctx->has_main_request) {
  601. get_full_env(track_vars_array);
  602. // php_import_environment_variables(track_vars_array);
  603. go_register_variables(thread_index, track_vars_array);
  604. return;
  605. }
  606. /* In worker mode we cache the os environment */
  607. if (os_environment == NULL) {
  608. os_environment = malloc(sizeof(zval));
  609. array_init(os_environment);
  610. get_full_env(os_environment);
  611. // php_import_environment_variables(os_environment);
  612. }
  613. zend_hash_copy(Z_ARR_P(track_vars_array), Z_ARR_P(os_environment),
  614. (copy_ctor_func_t)zval_add_ref);
  615. go_register_variables(thread_index, track_vars_array);
  616. }
  617. static void frankenphp_log_message(const char *message, int syslog_type_int) {
  618. go_log((char *)message, syslog_type_int);
  619. }
  620. static char *frankenphp_getenv(const char *name, size_t name_len) {
  621. go_string gname = {name_len, (char *)name};
  622. return go_sapi_getenv(thread_index, &gname);
  623. }
  624. sapi_module_struct frankenphp_sapi_module = {
  625. "frankenphp", /* name */
  626. "FrankenPHP", /* pretty name */
  627. frankenphp_startup, /* startup */
  628. php_module_shutdown_wrapper, /* shutdown */
  629. NULL, /* activate */
  630. frankenphp_deactivate, /* deactivate */
  631. frankenphp_ub_write, /* unbuffered write */
  632. frankenphp_sapi_flush, /* flush */
  633. NULL, /* get uid */
  634. frankenphp_getenv, /* getenv */
  635. php_error, /* error handler */
  636. NULL, /* header handler */
  637. frankenphp_send_headers, /* send headers handler */
  638. NULL, /* send header handler */
  639. frankenphp_read_post, /* read POST data */
  640. frankenphp_read_cookies, /* read Cookies */
  641. frankenphp_register_variables, /* register server variables */
  642. frankenphp_log_message, /* Log message */
  643. NULL, /* Get request time */
  644. NULL, /* Child terminate */
  645. STANDARD_SAPI_MODULE_PROPERTIES};
  646. /* Sets thread name for profiling and debugging.
  647. *
  648. * Adapted from https://github.com/Pithikos/C-Thread-Pool
  649. * Copyright: Johan Hanssen Seferidis
  650. * License: MIT
  651. */
  652. static void set_thread_name(char *thread_name) {
  653. #if defined(__linux__)
  654. /* Use prctl instead to prevent using _GNU_SOURCE flag and implicit
  655. * declaration */
  656. prctl(PR_SET_NAME, thread_name);
  657. #elif defined(__APPLE__) && defined(__MACH__)
  658. pthread_setname_np(thread_name);
  659. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  660. pthread_set_name_np(pthread_self(), thread_name);
  661. #endif
  662. }
  663. static void *php_thread(void *arg) {
  664. char thread_name[16] = {0};
  665. snprintf(thread_name, 16, "php-%" PRIxPTR, (uintptr_t)arg);
  666. thread_index = (uintptr_t)arg;
  667. set_thread_name(thread_name);
  668. #ifdef ZTS
  669. /* initial resource fetch */
  670. (void)ts_resource(0);
  671. #ifdef PHP_WIN32
  672. ZEND_TSRMLS_CACHE_UPDATE();
  673. #endif
  674. #endif
  675. local_ctx = malloc(sizeof(frankenphp_server_context));
  676. /* check if a default filter is set in php.ini and only filter if
  677. * it is, this is deprecated and will be removed in PHP 9 */
  678. char *default_filter;
  679. cfg_get_string("filter.default", &default_filter);
  680. should_filter_var = default_filter != NULL;
  681. while (go_handle_request(thread_index)) {
  682. }
  683. go_frankenphp_release_known_variable_keys(thread_index);
  684. #ifdef ZTS
  685. ts_free_thread();
  686. #endif
  687. return NULL;
  688. }
  689. static void *php_main(void *arg) {
  690. /*
  691. * SIGPIPE must be masked in non-Go threads:
  692. * https://pkg.go.dev/os/signal#hdr-Go_programs_that_use_cgo_or_SWIG
  693. */
  694. sigset_t set;
  695. sigemptyset(&set);
  696. sigaddset(&set, SIGPIPE);
  697. if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) {
  698. perror("failed to block SIGPIPE");
  699. exit(EXIT_FAILURE);
  700. }
  701. intptr_t num_threads = (intptr_t)arg;
  702. set_thread_name("php-main");
  703. #ifdef ZTS
  704. #if (PHP_VERSION_ID >= 80300)
  705. php_tsrm_startup_ex(num_threads);
  706. #else
  707. php_tsrm_startup();
  708. #endif
  709. /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/
  710. #ifdef PHP_WIN32
  711. ZEND_TSRMLS_CACHE_UPDATE();
  712. #endif
  713. #endif
  714. sapi_startup(&frankenphp_sapi_module);
  715. #ifndef ZEND_MAX_EXECUTION_TIMERS
  716. #if (PHP_VERSION_ID >= 80300)
  717. frankenphp_sapi_module.ini_entries = HARDCODED_INI;
  718. #else
  719. frankenphp_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
  720. if (frankenphp_sapi_module.ini_entries == NULL) {
  721. perror("malloc failed");
  722. exit(EXIT_FAILURE);
  723. }
  724. memcpy(frankenphp_sapi_module.ini_entries, HARDCODED_INI,
  725. sizeof(HARDCODED_INI));
  726. #endif
  727. #endif
  728. frankenphp_sapi_module.startup(&frankenphp_sapi_module);
  729. pthread_t *threads = malloc(num_threads * sizeof(pthread_t));
  730. if (threads == NULL) {
  731. perror("malloc failed");
  732. exit(EXIT_FAILURE);
  733. }
  734. for (uintptr_t i = 0; i < num_threads; i++) {
  735. if (pthread_create(&(*(threads + i)), NULL, &php_thread, (void *)i) != 0) {
  736. perror("failed to create PHP thread");
  737. free(threads);
  738. exit(EXIT_FAILURE);
  739. }
  740. }
  741. for (int i = 0; i < num_threads; i++) {
  742. if (pthread_join((*(threads + i)), NULL) != 0) {
  743. perror("failed to join PHP thread");
  744. free(threads);
  745. exit(EXIT_FAILURE);
  746. }
  747. }
  748. free(threads);
  749. /* channel closed, shutdown gracefully */
  750. frankenphp_sapi_module.shutdown(&frankenphp_sapi_module);
  751. sapi_shutdown();
  752. #ifdef ZTS
  753. tsrm_shutdown();
  754. #endif
  755. #if (PHP_VERSION_ID < 80300)
  756. if (frankenphp_sapi_module.ini_entries) {
  757. free(frankenphp_sapi_module.ini_entries);
  758. frankenphp_sapi_module.ini_entries = NULL;
  759. }
  760. #endif
  761. go_shutdown();
  762. return NULL;
  763. }
  764. int frankenphp_init(int num_threads) {
  765. pthread_t thread;
  766. if (pthread_create(&thread, NULL, &php_main, (void *)(intptr_t)num_threads) !=
  767. 0) {
  768. go_shutdown();
  769. return -1;
  770. }
  771. return pthread_detach(thread);
  772. }
  773. int frankenphp_request_startup() {
  774. if (php_request_startup() == SUCCESS) {
  775. return SUCCESS;
  776. }
  777. php_request_shutdown((void *)0);
  778. return FAILURE;
  779. }
  780. int frankenphp_execute_script(char *file_name) {
  781. if (frankenphp_request_startup() == FAILURE) {
  782. free(file_name);
  783. file_name = NULL;
  784. return FAILURE;
  785. }
  786. int status = SUCCESS;
  787. zend_file_handle file_handle;
  788. zend_stream_init_filename(&file_handle, file_name);
  789. free(file_name);
  790. file_name = NULL;
  791. file_handle.primary_script = 1;
  792. zend_first_try {
  793. EG(exit_status) = 0;
  794. php_execute_script(&file_handle);
  795. status = EG(exit_status);
  796. }
  797. zend_catch { status = EG(exit_status); }
  798. zend_end_try();
  799. // free the cached os environment before shutting down the script
  800. if (os_environment != NULL) {
  801. zval_ptr_dtor(os_environment);
  802. free(os_environment);
  803. os_environment = NULL;
  804. }
  805. zend_destroy_file_handle(&file_handle);
  806. frankenphp_free_request_context();
  807. frankenphp_request_shutdown();
  808. return status;
  809. }
  810. /* Use global variables to store CLI arguments to prevent useless allocations */
  811. static char *cli_script;
  812. static int cli_argc;
  813. static char **cli_argv;
  814. /*
  815. * CLI code is adapted from
  816. * https://github.com/php/php-src/blob/master/sapi/cli/php_cli.c Copyright (c)
  817. * The PHP Group Licensed under The PHP License Original uthors: Edin Kadribasic
  818. * <edink@php.net>, Marcus Boerger <helly@php.net> and Johannes Schlueter
  819. * <johannes@php.net> Parts based on CGI SAPI Module by Rasmus Lerdorf, Stig
  820. * Bakken and Zeev Suraski
  821. */
  822. static void cli_register_file_handles(bool no_close) /* {{{ */
  823. {
  824. php_stream *s_in, *s_out, *s_err;
  825. php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL;
  826. zend_constant ic, oc, ec;
  827. s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in);
  828. s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
  829. s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
  830. if (s_in == NULL || s_out == NULL || s_err == NULL) {
  831. if (s_in)
  832. php_stream_close(s_in);
  833. if (s_out)
  834. php_stream_close(s_out);
  835. if (s_err)
  836. php_stream_close(s_err);
  837. return;
  838. }
  839. if (no_close) {
  840. s_in->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  841. s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  842. s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  843. }
  844. /*s_in_process = s_in;*/
  845. php_stream_to_zval(s_in, &ic.value);
  846. php_stream_to_zval(s_out, &oc.value);
  847. php_stream_to_zval(s_err, &ec.value);
  848. ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0);
  849. ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0);
  850. zend_register_constant(&ic);
  851. ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0);
  852. oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0);
  853. zend_register_constant(&oc);
  854. ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0);
  855. ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0);
  856. zend_register_constant(&ec);
  857. }
  858. /* }}} */
  859. static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */
  860. {
  861. size_t len;
  862. char *docroot = "";
  863. /*
  864. * In CGI mode, we consider the environment to be a part of the server
  865. * variables
  866. */
  867. php_import_environment_variables(track_vars_array);
  868. /* Build the special-case PHP_SELF variable for the CLI version */
  869. len = strlen(cli_script);
  870. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &cli_script, len,
  871. &len)) {
  872. php_register_variable_safe("PHP_SELF", cli_script, len, track_vars_array);
  873. }
  874. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &cli_script, len,
  875. &len)) {
  876. php_register_variable_safe("SCRIPT_NAME", cli_script, len,
  877. track_vars_array);
  878. }
  879. /* filenames are empty for stdin */
  880. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &cli_script,
  881. len, &len)) {
  882. php_register_variable_safe("SCRIPT_FILENAME", cli_script, len,
  883. track_vars_array);
  884. }
  885. if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &cli_script,
  886. len, &len)) {
  887. php_register_variable_safe("PATH_TRANSLATED", cli_script, len,
  888. track_vars_array);
  889. }
  890. /* just make it available */
  891. len = 0U;
  892. if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len,
  893. &len)) {
  894. php_register_variable_safe("DOCUMENT_ROOT", docroot, len, track_vars_array);
  895. }
  896. }
  897. /* }}} */
  898. static void *execute_script_cli(void *arg) {
  899. void *exit_status;
  900. /*
  901. * The SAPI name "cli" is hardcoded into too many programs... let's usurp it.
  902. */
  903. php_embed_module.name = "cli";
  904. php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP";
  905. php_embed_module.register_server_variables = sapi_cli_register_variables;
  906. php_embed_init(cli_argc, cli_argv);
  907. cli_register_file_handles(false);
  908. zend_first_try {
  909. zend_file_handle file_handle;
  910. zend_stream_init_filename(&file_handle, cli_script);
  911. CG(skip_shebang) = 1;
  912. php_execute_script(&file_handle);
  913. }
  914. zend_end_try();
  915. exit_status = (void *)(intptr_t)EG(exit_status);
  916. php_embed_shutdown();
  917. return exit_status;
  918. }
  919. int frankenphp_execute_script_cli(char *script, int argc, char **argv) {
  920. pthread_t thread;
  921. int err;
  922. void *exit_status;
  923. cli_script = script;
  924. cli_argc = argc;
  925. cli_argv = argv;
  926. /*
  927. * Start the script in a dedicated thread to prevent conflicts between Go and
  928. * PHP signal handlers
  929. */
  930. err = pthread_create(&thread, NULL, execute_script_cli, NULL);
  931. if (err != 0) {
  932. return err;
  933. }
  934. err = pthread_join(thread, &exit_status);
  935. if (err != 0) {
  936. return err;
  937. }
  938. return (intptr_t)exit_status;
  939. }
  940. int frankenphp_execute_php_function(const char *php_function) {
  941. zval retval = {0};
  942. zend_fcall_info fci = {0};
  943. zend_fcall_info_cache fci_cache = {0};
  944. zend_string *func_name =
  945. zend_string_init(php_function, strlen(php_function), 0);
  946. ZVAL_STR(&fci.function_name, func_name);
  947. fci.size = sizeof fci;
  948. fci.retval = &retval;
  949. int success = 0;
  950. zend_try { success = zend_call_function(&fci, &fci_cache) == SUCCESS; }
  951. zend_end_try();
  952. zend_string_release(func_name);
  953. return success;
  954. }
  955. int frankenphp_reset_opcache(void) {
  956. if (zend_hash_str_exists(CG(function_table), "opcache_reset",
  957. sizeof("opcache_reset") - 1)) {
  958. return frankenphp_execute_php_function("opcache_reset");
  959. }
  960. return 0;
  961. }