frankenphp.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. ctx->main_request = main_request;
  374. ctx->current_request = current_request;
  375. SG(request_info).auth_password = auth_password;
  376. SG(request_info).auth_user = auth_user;
  377. SG(request_info).request_method = request_method;
  378. SG(request_info).query_string = query_string;
  379. SG(request_info).content_type = content_type;
  380. SG(request_info).content_length = content_length;
  381. SG(request_info).path_translated = path_translated;
  382. SG(request_info).request_uri = request_uri;
  383. SG(request_info).proto_num = proto_num;
  384. return SUCCESS;
  385. }
  386. static int frankenphp_startup(sapi_module_struct *sapi_module) {
  387. return php_module_startup(sapi_module, &frankenphp_module);
  388. }
  389. static int frankenphp_deactivate(void) {
  390. /* TODO: flush everything */
  391. return SUCCESS;
  392. }
  393. static size_t frankenphp_ub_write(const char *str, size_t str_length) {
  394. frankenphp_server_context *ctx = SG(server_context);
  395. if (ctx->finished) {
  396. /* TODO: maybe log a warning that we tried to write to a finished request?
  397. */
  398. return 0;
  399. }
  400. struct go_ub_write_return result = go_ub_write(
  401. ctx->current_request ? ctx->current_request : ctx->main_request,
  402. (char *)str, str_length);
  403. if (result.r1) {
  404. php_handle_aborted_connection();
  405. }
  406. return result.r0;
  407. }
  408. static int frankenphp_send_headers(sapi_headers_struct *sapi_headers) {
  409. if (SG(request_info).no_headers == 1) {
  410. return SAPI_HEADER_SENT_SUCCESSFULLY;
  411. }
  412. int status;
  413. frankenphp_server_context *ctx = SG(server_context);
  414. if (ctx->current_request == 0) {
  415. return SAPI_HEADER_SEND_FAILED;
  416. }
  417. if (SG(sapi_headers).http_status_line) {
  418. status = atoi((SG(sapi_headers).http_status_line) + 9);
  419. } else {
  420. status = SG(sapi_headers).http_response_code;
  421. if (!status) {
  422. status = 200;
  423. }
  424. }
  425. go_write_headers(ctx->current_request, status, &sapi_headers->headers);
  426. return SAPI_HEADER_SENT_SUCCESSFULLY;
  427. }
  428. static void frankenphp_sapi_flush(void *server_context) {
  429. frankenphp_server_context *ctx = (frankenphp_server_context *)server_context;
  430. if (ctx && ctx->current_request != 0 && go_sapi_flush(ctx->current_request)) {
  431. php_handle_aborted_connection();
  432. }
  433. }
  434. static size_t frankenphp_read_post(char *buffer, size_t count_bytes) {
  435. frankenphp_server_context *ctx = SG(server_context);
  436. return ctx->current_request
  437. ? go_read_post(ctx->current_request, buffer, count_bytes)
  438. : 0;
  439. }
  440. static char *frankenphp_read_cookies(void) {
  441. frankenphp_server_context *ctx = SG(server_context);
  442. if (ctx->current_request == 0) {
  443. return "";
  444. }
  445. ctx->cookie_data = go_read_cookies(ctx->current_request);
  446. return ctx->cookie_data;
  447. }
  448. static void frankenphp_register_known_variable(const char *key, go_string value,
  449. zval *track_vars_array) {
  450. if (value.data == NULL) {
  451. php_register_variable_safe(key, "", 0, track_vars_array);
  452. return;
  453. }
  454. size_t new_val_len;
  455. if (sapi_module.input_filter(PARSE_SERVER, key, &value.data, value.len,
  456. &new_val_len)) {
  457. php_register_variable_safe(key, value.data, new_val_len, track_vars_array);
  458. }
  459. }
  460. static void
  461. frankenphp_register_variable_from_request_info(const char *key, char *value,
  462. zval *track_vars_array) {
  463. if (value == NULL) {
  464. return;
  465. }
  466. size_t new_val_len;
  467. if (sapi_module.input_filter(PARSE_SERVER, key, &value, strlen(value),
  468. &new_val_len)) {
  469. php_register_variable_safe(key, value, new_val_len, track_vars_array);
  470. }
  471. }
  472. void frankenphp_register_bulk_variables(go_string known_variables[27],
  473. php_variable *dynamic_variables,
  474. size_t size, zval *track_vars_array) {
  475. /* Not used, but must be present */
  476. php_register_variable_safe("AUTH_TYPE", "", 0, track_vars_array);
  477. php_register_variable_safe("REMOTE_IDENT", "", 0, track_vars_array);
  478. /* Allocated in frankenphp_update_server_context() */
  479. frankenphp_register_variable_from_request_info(
  480. "CONTENT_TYPE", (char *)SG(request_info).content_type, track_vars_array);
  481. frankenphp_register_variable_from_request_info(
  482. "PATH_TRANSLATED", (char *)SG(request_info).path_translated,
  483. track_vars_array);
  484. frankenphp_register_variable_from_request_info(
  485. "QUERY_STRING", SG(request_info).query_string, track_vars_array);
  486. frankenphp_register_variable_from_request_info(
  487. "REMOTE_USER", (char *)SG(request_info).auth_user, track_vars_array);
  488. frankenphp_register_variable_from_request_info(
  489. "REQUEST_METHOD", (char *)SG(request_info).request_method,
  490. track_vars_array);
  491. frankenphp_register_variable_from_request_info(
  492. "REQUEST_URI", SG(request_info).request_uri, track_vars_array);
  493. /* Known variables */
  494. frankenphp_register_known_variable("CONTENT_LENGTH", known_variables[0],
  495. track_vars_array);
  496. frankenphp_register_known_variable("DOCUMENT_ROOT", known_variables[1],
  497. track_vars_array);
  498. frankenphp_register_known_variable("DOCUMENT_URI", known_variables[2],
  499. track_vars_array);
  500. frankenphp_register_known_variable("GATEWAY_INTERFACE", known_variables[3],
  501. track_vars_array);
  502. frankenphp_register_known_variable("HTTP_HOST", known_variables[4],
  503. track_vars_array);
  504. frankenphp_register_known_variable("HTTPS", known_variables[5],
  505. track_vars_array);
  506. frankenphp_register_known_variable("PATH_INFO", known_variables[6],
  507. track_vars_array);
  508. frankenphp_register_known_variable("PHP_SELF", known_variables[7],
  509. track_vars_array);
  510. frankenphp_register_known_variable("REMOTE_ADDR", known_variables[8],
  511. track_vars_array);
  512. frankenphp_register_known_variable("REMOTE_HOST", known_variables[9],
  513. track_vars_array);
  514. frankenphp_register_known_variable("REMOTE_PORT", known_variables[10],
  515. track_vars_array);
  516. frankenphp_register_known_variable("REQUEST_SCHEME", known_variables[11],
  517. track_vars_array);
  518. frankenphp_register_known_variable("SCRIPT_FILENAME", known_variables[12],
  519. track_vars_array);
  520. frankenphp_register_known_variable("SCRIPT_NAME", known_variables[13],
  521. track_vars_array);
  522. frankenphp_register_known_variable("SERVER_NAME", known_variables[14],
  523. track_vars_array);
  524. frankenphp_register_known_variable("SERVER_PORT", known_variables[15],
  525. track_vars_array);
  526. frankenphp_register_known_variable("SERVER_PROTOCOL", known_variables[16],
  527. track_vars_array);
  528. frankenphp_register_known_variable("SERVER_SOFTWARE", known_variables[17],
  529. track_vars_array);
  530. frankenphp_register_known_variable("SSL_PROTOCOL", known_variables[18],
  531. track_vars_array);
  532. size_t new_val_len;
  533. for (size_t i = 0; i < size; i++) {
  534. if (sapi_module.input_filter(PARSE_SERVER, dynamic_variables[i].var,
  535. &dynamic_variables[i].data,
  536. dynamic_variables[i].data_len, &new_val_len)) {
  537. php_register_variable_safe(dynamic_variables[i].var,
  538. dynamic_variables[i].data, new_val_len,
  539. track_vars_array);
  540. }
  541. }
  542. }
  543. static void frankenphp_register_variables(zval *track_vars_array) {
  544. /* https://www.php.net/manual/en/reserved.variables.server.php */
  545. frankenphp_server_context *ctx = SG(server_context);
  546. /* In CGI mode, we consider the environment to be a part of the server
  547. * variables
  548. */
  549. php_import_environment_variables(track_vars_array);
  550. go_register_variables(ctx->current_request ? ctx->current_request
  551. : ctx->main_request,
  552. track_vars_array);
  553. }
  554. static void frankenphp_log_message(const char *message, int syslog_type_int) {
  555. go_log((char *)message, syslog_type_int);
  556. }
  557. sapi_module_struct frankenphp_sapi_module = {
  558. "frankenphp", /* name */
  559. "FrankenPHP", /* pretty name */
  560. frankenphp_startup, /* startup */
  561. php_module_shutdown_wrapper, /* shutdown */
  562. NULL, /* activate */
  563. frankenphp_deactivate, /* deactivate */
  564. frankenphp_ub_write, /* unbuffered write */
  565. frankenphp_sapi_flush, /* flush */
  566. NULL, /* get uid */
  567. NULL, /* getenv */
  568. php_error, /* error handler */
  569. NULL, /* header handler */
  570. frankenphp_send_headers, /* send headers handler */
  571. NULL, /* send header handler */
  572. frankenphp_read_post, /* read POST data */
  573. frankenphp_read_cookies, /* read Cookies */
  574. frankenphp_register_variables, /* register server variables */
  575. frankenphp_log_message, /* Log message */
  576. NULL, /* Get request time */
  577. NULL, /* Child terminate */
  578. STANDARD_SAPI_MODULE_PROPERTIES};
  579. /* Sets thread name for profiling and debugging.
  580. *
  581. * Adapted from https://github.com/Pithikos/C-Thread-Pool
  582. * Copyright: Johan Hanssen Seferidis
  583. * License: MIT
  584. */
  585. static void set_thread_name(char *thread_name) {
  586. #if defined(__linux__)
  587. /* Use prctl instead to prevent using _GNU_SOURCE flag and implicit
  588. * declaration */
  589. prctl(PR_SET_NAME, thread_name);
  590. #elif defined(__APPLE__) && defined(__MACH__)
  591. pthread_setname_np(thread_name);
  592. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  593. pthread_set_name_np(pthread_self(), thread_name);
  594. #endif
  595. }
  596. static void *php_thread(void *arg) {
  597. char thread_name[16] = {0};
  598. snprintf(thread_name, 16, "php-%" PRIxPTR, (uintptr_t)arg);
  599. set_thread_name(thread_name);
  600. #ifdef ZTS
  601. /* initial resource fetch */
  602. (void)ts_resource(0);
  603. #ifdef PHP_WIN32
  604. ZEND_TSRMLS_CACHE_UPDATE();
  605. #endif
  606. #endif
  607. local_ctx = malloc(sizeof(frankenphp_server_context));
  608. while (go_handle_request()) {
  609. }
  610. #ifdef ZTS
  611. ts_free_thread();
  612. #endif
  613. return NULL;
  614. }
  615. static void *php_main(void *arg) {
  616. /*
  617. * SIGPIPE must be masked in non-Go threads:
  618. * https://pkg.go.dev/os/signal#hdr-Go_programs_that_use_cgo_or_SWIG
  619. */
  620. sigset_t set;
  621. sigemptyset(&set);
  622. sigaddset(&set, SIGPIPE);
  623. if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) {
  624. perror("failed to block SIGPIPE");
  625. exit(EXIT_FAILURE);
  626. }
  627. intptr_t num_threads = (intptr_t)arg;
  628. set_thread_name("php-main");
  629. #ifdef ZTS
  630. #if (PHP_VERSION_ID >= 80300)
  631. php_tsrm_startup_ex(num_threads);
  632. #else
  633. php_tsrm_startup();
  634. #endif
  635. /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/
  636. #ifdef PHP_WIN32
  637. ZEND_TSRMLS_CACHE_UPDATE();
  638. #endif
  639. #endif
  640. sapi_startup(&frankenphp_sapi_module);
  641. #ifndef ZEND_MAX_EXECUTION_TIMERS
  642. #if (PHP_VERSION_ID >= 80300)
  643. frankenphp_sapi_module.ini_entries = HARDCODED_INI;
  644. #else
  645. frankenphp_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
  646. if (frankenphp_sapi_module.ini_entries == NULL) {
  647. perror("malloc failed");
  648. exit(EXIT_FAILURE);
  649. }
  650. memcpy(frankenphp_sapi_module.ini_entries, HARDCODED_INI,
  651. sizeof(HARDCODED_INI));
  652. #endif
  653. #endif
  654. frankenphp_sapi_module.startup(&frankenphp_sapi_module);
  655. pthread_t *threads = malloc(num_threads * sizeof(pthread_t));
  656. if (threads == NULL) {
  657. perror("malloc failed");
  658. exit(EXIT_FAILURE);
  659. }
  660. for (uintptr_t i = 0; i < num_threads; i++) {
  661. if (pthread_create(&(*(threads + i)), NULL, &php_thread, (void *)i) != 0) {
  662. perror("failed to create PHP thread");
  663. free(threads);
  664. exit(EXIT_FAILURE);
  665. }
  666. }
  667. for (int i = 0; i < num_threads; i++) {
  668. if (pthread_join((*(threads + i)), NULL) != 0) {
  669. perror("failed to join PHP thread");
  670. free(threads);
  671. exit(EXIT_FAILURE);
  672. }
  673. }
  674. free(threads);
  675. /* channel closed, shutdown gracefully */
  676. frankenphp_sapi_module.shutdown(&frankenphp_sapi_module);
  677. sapi_shutdown();
  678. #ifdef ZTS
  679. tsrm_shutdown();
  680. #endif
  681. #if (PHP_VERSION_ID < 80300)
  682. if (frankenphp_sapi_module.ini_entries) {
  683. free(frankenphp_sapi_module.ini_entries);
  684. frankenphp_sapi_module.ini_entries = NULL;
  685. }
  686. #endif
  687. go_shutdown();
  688. return NULL;
  689. }
  690. int frankenphp_init(int num_threads) {
  691. pthread_t thread;
  692. if (pthread_create(&thread, NULL, &php_main, (void *)(intptr_t)num_threads) !=
  693. 0) {
  694. go_shutdown();
  695. return -1;
  696. }
  697. return pthread_detach(thread);
  698. }
  699. int frankenphp_request_startup() {
  700. if (php_request_startup() == SUCCESS) {
  701. return SUCCESS;
  702. }
  703. php_request_shutdown((void *)0);
  704. return FAILURE;
  705. }
  706. int frankenphp_execute_script(char *file_name) {
  707. if (frankenphp_request_startup() == FAILURE) {
  708. free(file_name);
  709. file_name = NULL;
  710. return FAILURE;
  711. }
  712. int status = SUCCESS;
  713. zend_file_handle file_handle;
  714. zend_stream_init_filename(&file_handle, file_name);
  715. free(file_name);
  716. file_name = NULL;
  717. file_handle.primary_script = 1;
  718. zend_first_try {
  719. EG(exit_status) = 0;
  720. php_execute_script(&file_handle);
  721. status = EG(exit_status);
  722. }
  723. zend_catch { status = EG(exit_status); }
  724. zend_end_try();
  725. zend_destroy_file_handle(&file_handle);
  726. frankenphp_free_request_context();
  727. frankenphp_request_shutdown();
  728. return status;
  729. }
  730. /* Use global variables to store CLI arguments to prevent useless allocations */
  731. static char *cli_script;
  732. static int cli_argc;
  733. static char **cli_argv;
  734. /*
  735. * CLI code is adapted from
  736. * https://github.com/php/php-src/blob/master/sapi/cli/php_cli.c Copyright (c)
  737. * The PHP Group Licensed under The PHP License Original uthors: Edin Kadribasic
  738. * <edink@php.net>, Marcus Boerger <helly@php.net> and Johannes Schlueter
  739. * <johannes@php.net> Parts based on CGI SAPI Module by Rasmus Lerdorf, Stig
  740. * Bakken and Zeev Suraski
  741. */
  742. static void cli_register_file_handles(bool no_close) /* {{{ */
  743. {
  744. php_stream *s_in, *s_out, *s_err;
  745. php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL;
  746. zend_constant ic, oc, ec;
  747. s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in);
  748. s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
  749. s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
  750. if (s_in == NULL || s_out == NULL || s_err == NULL) {
  751. if (s_in)
  752. php_stream_close(s_in);
  753. if (s_out)
  754. php_stream_close(s_out);
  755. if (s_err)
  756. php_stream_close(s_err);
  757. return;
  758. }
  759. if (no_close) {
  760. s_in->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  761. s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  762. s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  763. }
  764. /*s_in_process = s_in;*/
  765. php_stream_to_zval(s_in, &ic.value);
  766. php_stream_to_zval(s_out, &oc.value);
  767. php_stream_to_zval(s_err, &ec.value);
  768. ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0);
  769. ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0);
  770. zend_register_constant(&ic);
  771. ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0);
  772. oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0);
  773. zend_register_constant(&oc);
  774. ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0);
  775. ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0);
  776. zend_register_constant(&ec);
  777. }
  778. /* }}} */
  779. static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */
  780. {
  781. size_t len;
  782. char *docroot = "";
  783. /*
  784. * In CGI mode, we consider the environment to be a part of the server
  785. * variables
  786. */
  787. php_import_environment_variables(track_vars_array);
  788. /* Build the special-case PHP_SELF variable for the CLI version */
  789. len = strlen(cli_script);
  790. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &cli_script, len,
  791. &len)) {
  792. php_register_variable_safe("PHP_SELF", cli_script, len, track_vars_array);
  793. }
  794. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &cli_script, len,
  795. &len)) {
  796. php_register_variable_safe("SCRIPT_NAME", cli_script, len,
  797. track_vars_array);
  798. }
  799. /* filenames are empty for stdin */
  800. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &cli_script,
  801. len, &len)) {
  802. php_register_variable_safe("SCRIPT_FILENAME", cli_script, len,
  803. track_vars_array);
  804. }
  805. if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &cli_script,
  806. len, &len)) {
  807. php_register_variable_safe("PATH_TRANSLATED", cli_script, len,
  808. track_vars_array);
  809. }
  810. /* just make it available */
  811. len = 0U;
  812. if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len,
  813. &len)) {
  814. php_register_variable_safe("DOCUMENT_ROOT", docroot, len, track_vars_array);
  815. }
  816. }
  817. /* }}} */
  818. static void *execute_script_cli(void *arg) {
  819. void *exit_status;
  820. /*
  821. * The SAPI name "cli" is hardcoded into too many programs... let's usurp it.
  822. */
  823. php_embed_module.name = "cli";
  824. php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP";
  825. php_embed_module.register_server_variables = sapi_cli_register_variables;
  826. php_embed_init(cli_argc, cli_argv);
  827. cli_register_file_handles(false);
  828. zend_first_try {
  829. zend_file_handle file_handle;
  830. zend_stream_init_filename(&file_handle, cli_script);
  831. CG(skip_shebang) = 1;
  832. php_execute_script(&file_handle);
  833. }
  834. zend_end_try();
  835. exit_status = (void *)(intptr_t)EG(exit_status);
  836. php_embed_shutdown();
  837. return exit_status;
  838. }
  839. int frankenphp_execute_script_cli(char *script, int argc, char **argv) {
  840. pthread_t thread;
  841. int err;
  842. void *exit_status;
  843. cli_script = script;
  844. cli_argc = argc;
  845. cli_argv = argv;
  846. /*
  847. * Start the script in a dedicated thread to prevent conflicts between Go and
  848. * PHP signal handlers
  849. */
  850. err = pthread_create(&thread, NULL, execute_script_cli, NULL);
  851. if (err != 0) {
  852. return err;
  853. }
  854. err = pthread_join(thread, &exit_status);
  855. if (err != 0) {
  856. return err;
  857. }
  858. return (intptr_t)exit_status;
  859. }