frankenphp.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  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 (val == NULL || key == NULL) {
  581. return;
  582. }
  583. size_t new_val_len = val_len;
  584. if (!should_filter_var ||
  585. sapi_module.input_filter(PARSE_SERVER, key, &val, new_val_len,
  586. &new_val_len)) {
  587. php_register_variable_safe(key, val, new_val_len, track_vars_array);
  588. }
  589. }
  590. static void frankenphp_register_variables(zval *track_vars_array) {
  591. /* https://www.php.net/manual/en/reserved.variables.server.php */
  592. /* In CGI mode, we consider the environment to be a part of the server
  593. * variables.
  594. */
  595. frankenphp_server_context *ctx = SG(server_context);
  596. /* in non-worker mode we import the os environment regularly */
  597. if (!ctx->has_main_request) {
  598. get_full_env(track_vars_array);
  599. // php_import_environment_variables(track_vars_array);
  600. go_register_variables(thread_index, track_vars_array);
  601. return;
  602. }
  603. /* In worker mode we cache the os environment */
  604. if (os_environment == NULL) {
  605. os_environment = malloc(sizeof(zval));
  606. array_init(os_environment);
  607. get_full_env(os_environment);
  608. // php_import_environment_variables(os_environment);
  609. }
  610. zend_hash_copy(Z_ARR_P(track_vars_array), Z_ARR_P(os_environment),
  611. (copy_ctor_func_t)zval_add_ref);
  612. go_register_variables(thread_index, track_vars_array);
  613. }
  614. static void frankenphp_log_message(const char *message, int syslog_type_int) {
  615. go_log((char *)message, syslog_type_int);
  616. }
  617. sapi_module_struct frankenphp_sapi_module = {
  618. "frankenphp", /* name */
  619. "FrankenPHP", /* pretty name */
  620. frankenphp_startup, /* startup */
  621. php_module_shutdown_wrapper, /* shutdown */
  622. NULL, /* activate */
  623. frankenphp_deactivate, /* deactivate */
  624. frankenphp_ub_write, /* unbuffered write */
  625. frankenphp_sapi_flush, /* flush */
  626. NULL, /* get uid */
  627. NULL, /* getenv */
  628. php_error, /* error handler */
  629. NULL, /* header handler */
  630. frankenphp_send_headers, /* send headers handler */
  631. NULL, /* send header handler */
  632. frankenphp_read_post, /* read POST data */
  633. frankenphp_read_cookies, /* read Cookies */
  634. frankenphp_register_variables, /* register server variables */
  635. frankenphp_log_message, /* Log message */
  636. NULL, /* Get request time */
  637. NULL, /* Child terminate */
  638. STANDARD_SAPI_MODULE_PROPERTIES};
  639. /* Sets thread name for profiling and debugging.
  640. *
  641. * Adapted from https://github.com/Pithikos/C-Thread-Pool
  642. * Copyright: Johan Hanssen Seferidis
  643. * License: MIT
  644. */
  645. static void set_thread_name(char *thread_name) {
  646. #if defined(__linux__)
  647. /* Use prctl instead to prevent using _GNU_SOURCE flag and implicit
  648. * declaration */
  649. prctl(PR_SET_NAME, thread_name);
  650. #elif defined(__APPLE__) && defined(__MACH__)
  651. pthread_setname_np(thread_name);
  652. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  653. pthread_set_name_np(pthread_self(), thread_name);
  654. #endif
  655. }
  656. static void *php_thread(void *arg) {
  657. char thread_name[16] = {0};
  658. snprintf(thread_name, 16, "php-%" PRIxPTR, (uintptr_t)arg);
  659. thread_index = (uintptr_t)arg;
  660. set_thread_name(thread_name);
  661. #ifdef ZTS
  662. /* initial resource fetch */
  663. (void)ts_resource(0);
  664. #ifdef PHP_WIN32
  665. ZEND_TSRMLS_CACHE_UPDATE();
  666. #endif
  667. #endif
  668. local_ctx = malloc(sizeof(frankenphp_server_context));
  669. /* check if a default filter is set in php.ini and only filter if
  670. * it is, this is deprecated and will be removed in PHP 9 */
  671. char *default_filter;
  672. cfg_get_string("filter.default", &default_filter);
  673. should_filter_var = default_filter != NULL;
  674. while (go_handle_request(thread_index)) {
  675. }
  676. go_frankenphp_release_known_variable_keys(thread_index);
  677. #ifdef ZTS
  678. ts_free_thread();
  679. #endif
  680. return NULL;
  681. }
  682. static void *php_main(void *arg) {
  683. /*
  684. * SIGPIPE must be masked in non-Go threads:
  685. * https://pkg.go.dev/os/signal#hdr-Go_programs_that_use_cgo_or_SWIG
  686. */
  687. sigset_t set;
  688. sigemptyset(&set);
  689. sigaddset(&set, SIGPIPE);
  690. if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) {
  691. perror("failed to block SIGPIPE");
  692. exit(EXIT_FAILURE);
  693. }
  694. intptr_t num_threads = (intptr_t)arg;
  695. set_thread_name("php-main");
  696. #ifdef ZTS
  697. #if (PHP_VERSION_ID >= 80300)
  698. php_tsrm_startup_ex(num_threads);
  699. #else
  700. php_tsrm_startup();
  701. #endif
  702. /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/
  703. #ifdef PHP_WIN32
  704. ZEND_TSRMLS_CACHE_UPDATE();
  705. #endif
  706. #endif
  707. sapi_startup(&frankenphp_sapi_module);
  708. #ifndef ZEND_MAX_EXECUTION_TIMERS
  709. #if (PHP_VERSION_ID >= 80300)
  710. frankenphp_sapi_module.ini_entries = HARDCODED_INI;
  711. #else
  712. frankenphp_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
  713. if (frankenphp_sapi_module.ini_entries == NULL) {
  714. perror("malloc failed");
  715. exit(EXIT_FAILURE);
  716. }
  717. memcpy(frankenphp_sapi_module.ini_entries, HARDCODED_INI,
  718. sizeof(HARDCODED_INI));
  719. #endif
  720. #endif
  721. frankenphp_sapi_module.startup(&frankenphp_sapi_module);
  722. pthread_t *threads = malloc(num_threads * sizeof(pthread_t));
  723. if (threads == NULL) {
  724. perror("malloc failed");
  725. exit(EXIT_FAILURE);
  726. }
  727. for (uintptr_t i = 0; i < num_threads; i++) {
  728. if (pthread_create(&(*(threads + i)), NULL, &php_thread, (void *)i) != 0) {
  729. perror("failed to create PHP thread");
  730. free(threads);
  731. exit(EXIT_FAILURE);
  732. }
  733. }
  734. for (int i = 0; i < num_threads; i++) {
  735. if (pthread_join((*(threads + i)), NULL) != 0) {
  736. perror("failed to join PHP thread");
  737. free(threads);
  738. exit(EXIT_FAILURE);
  739. }
  740. }
  741. free(threads);
  742. /* channel closed, shutdown gracefully */
  743. frankenphp_sapi_module.shutdown(&frankenphp_sapi_module);
  744. sapi_shutdown();
  745. #ifdef ZTS
  746. tsrm_shutdown();
  747. #endif
  748. #if (PHP_VERSION_ID < 80300)
  749. if (frankenphp_sapi_module.ini_entries) {
  750. free(frankenphp_sapi_module.ini_entries);
  751. frankenphp_sapi_module.ini_entries = NULL;
  752. }
  753. #endif
  754. go_shutdown();
  755. return NULL;
  756. }
  757. int frankenphp_init(int num_threads) {
  758. pthread_t thread;
  759. if (pthread_create(&thread, NULL, &php_main, (void *)(intptr_t)num_threads) !=
  760. 0) {
  761. go_shutdown();
  762. return -1;
  763. }
  764. return pthread_detach(thread);
  765. }
  766. int frankenphp_request_startup() {
  767. if (php_request_startup() == SUCCESS) {
  768. return SUCCESS;
  769. }
  770. php_request_shutdown((void *)0);
  771. return FAILURE;
  772. }
  773. int frankenphp_execute_script(char *file_name) {
  774. if (frankenphp_request_startup() == FAILURE) {
  775. free(file_name);
  776. file_name = NULL;
  777. return FAILURE;
  778. }
  779. int status = SUCCESS;
  780. zend_file_handle file_handle;
  781. zend_stream_init_filename(&file_handle, file_name);
  782. free(file_name);
  783. file_name = NULL;
  784. file_handle.primary_script = 1;
  785. zend_first_try {
  786. EG(exit_status) = 0;
  787. php_execute_script(&file_handle);
  788. status = EG(exit_status);
  789. }
  790. zend_catch { status = EG(exit_status); }
  791. zend_end_try();
  792. // free the cached os environment before shutting down the script
  793. if (os_environment != NULL) {
  794. zval_ptr_dtor(os_environment);
  795. free(os_environment);
  796. os_environment = NULL;
  797. }
  798. zend_destroy_file_handle(&file_handle);
  799. frankenphp_free_request_context();
  800. frankenphp_request_shutdown();
  801. return status;
  802. }
  803. /* Use global variables to store CLI arguments to prevent useless allocations */
  804. static char *cli_script;
  805. static int cli_argc;
  806. static char **cli_argv;
  807. /*
  808. * CLI code is adapted from
  809. * https://github.com/php/php-src/blob/master/sapi/cli/php_cli.c Copyright (c)
  810. * The PHP Group Licensed under The PHP License Original uthors: Edin Kadribasic
  811. * <edink@php.net>, Marcus Boerger <helly@php.net> and Johannes Schlueter
  812. * <johannes@php.net> Parts based on CGI SAPI Module by Rasmus Lerdorf, Stig
  813. * Bakken and Zeev Suraski
  814. */
  815. static void cli_register_file_handles(bool no_close) /* {{{ */
  816. {
  817. php_stream *s_in, *s_out, *s_err;
  818. php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL;
  819. zend_constant ic, oc, ec;
  820. s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in);
  821. s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
  822. s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
  823. if (s_in == NULL || s_out == NULL || s_err == NULL) {
  824. if (s_in)
  825. php_stream_close(s_in);
  826. if (s_out)
  827. php_stream_close(s_out);
  828. if (s_err)
  829. php_stream_close(s_err);
  830. return;
  831. }
  832. if (no_close) {
  833. s_in->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  834. s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  835. s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  836. }
  837. /*s_in_process = s_in;*/
  838. php_stream_to_zval(s_in, &ic.value);
  839. php_stream_to_zval(s_out, &oc.value);
  840. php_stream_to_zval(s_err, &ec.value);
  841. ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0);
  842. ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0);
  843. zend_register_constant(&ic);
  844. ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0);
  845. oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0);
  846. zend_register_constant(&oc);
  847. ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0);
  848. ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0);
  849. zend_register_constant(&ec);
  850. }
  851. /* }}} */
  852. static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */
  853. {
  854. size_t len;
  855. char *docroot = "";
  856. /*
  857. * In CGI mode, we consider the environment to be a part of the server
  858. * variables
  859. */
  860. php_import_environment_variables(track_vars_array);
  861. /* Build the special-case PHP_SELF variable for the CLI version */
  862. len = strlen(cli_script);
  863. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &cli_script, len,
  864. &len)) {
  865. php_register_variable_safe("PHP_SELF", cli_script, len, track_vars_array);
  866. }
  867. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &cli_script, len,
  868. &len)) {
  869. php_register_variable_safe("SCRIPT_NAME", cli_script, len,
  870. track_vars_array);
  871. }
  872. /* filenames are empty for stdin */
  873. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &cli_script,
  874. len, &len)) {
  875. php_register_variable_safe("SCRIPT_FILENAME", cli_script, len,
  876. track_vars_array);
  877. }
  878. if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &cli_script,
  879. len, &len)) {
  880. php_register_variable_safe("PATH_TRANSLATED", cli_script, len,
  881. track_vars_array);
  882. }
  883. /* just make it available */
  884. len = 0U;
  885. if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len,
  886. &len)) {
  887. php_register_variable_safe("DOCUMENT_ROOT", docroot, len, track_vars_array);
  888. }
  889. }
  890. /* }}} */
  891. static void *execute_script_cli(void *arg) {
  892. void *exit_status;
  893. /*
  894. * The SAPI name "cli" is hardcoded into too many programs... let's usurp it.
  895. */
  896. php_embed_module.name = "cli";
  897. php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP";
  898. php_embed_module.register_server_variables = sapi_cli_register_variables;
  899. php_embed_init(cli_argc, cli_argv);
  900. cli_register_file_handles(false);
  901. zend_first_try {
  902. zend_file_handle file_handle;
  903. zend_stream_init_filename(&file_handle, cli_script);
  904. CG(skip_shebang) = 1;
  905. php_execute_script(&file_handle);
  906. }
  907. zend_end_try();
  908. exit_status = (void *)(intptr_t)EG(exit_status);
  909. php_embed_shutdown();
  910. return exit_status;
  911. }
  912. int frankenphp_execute_script_cli(char *script, int argc, char **argv) {
  913. pthread_t thread;
  914. int err;
  915. void *exit_status;
  916. cli_script = script;
  917. cli_argc = argc;
  918. cli_argv = argv;
  919. /*
  920. * Start the script in a dedicated thread to prevent conflicts between Go and
  921. * PHP signal handlers
  922. */
  923. err = pthread_create(&thread, NULL, execute_script_cli, NULL);
  924. if (err != 0) {
  925. return err;
  926. }
  927. err = pthread_join(thread, &exit_status);
  928. if (err != 0) {
  929. return err;
  930. }
  931. return (intptr_t)exit_status;
  932. }
  933. int frankenphp_execute_php_function(const char *php_function) {
  934. zval retval = {0};
  935. zend_fcall_info fci = {0};
  936. zend_fcall_info_cache fci_cache = {0};
  937. zend_string *func_name =
  938. zend_string_init(php_function, strlen(php_function), 0);
  939. ZVAL_STR(&fci.function_name, func_name);
  940. fci.size = sizeof fci;
  941. fci.retval = &retval;
  942. int success = 0;
  943. zend_try { success = zend_call_function(&fci, &fci_cache) == SUCCESS; }
  944. zend_end_try();
  945. zend_string_release(func_name);
  946. return success;
  947. }