frankenphp.c 29 KB

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