frankenphp.c 30 KB

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