frankenphp.c 28 KB

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