frankenphp.c 29 KB

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