frankenphp.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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_ini.h>
  13. #include <php_main.h>
  14. #include <php_output.h>
  15. #include <php_variables.h>
  16. #include <pthread.h>
  17. #include <sapi/embed/php_embed.h>
  18. #include <signal.h>
  19. #include <stdint.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <unistd.h>
  23. #if defined(__linux__)
  24. #include <sys/prctl.h>
  25. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  26. #include <pthread_np.h>
  27. #endif
  28. #include "_cgo_export.h"
  29. #include "frankenphp_arginfo.h"
  30. #if defined(PHP_WIN32) && defined(ZTS)
  31. ZEND_TSRMLS_CACHE_DEFINE()
  32. #endif
  33. /* Timeouts are currently fundamentally broken with ZTS except on Linux and
  34. * FreeBSD: https://bugs.php.net/bug.php?id=79464 */
  35. #ifndef ZEND_MAX_EXECUTION_TIMERS
  36. static const char HARDCODED_INI[] = "max_execution_time=0\n"
  37. "max_input_time=-1\n\0";
  38. #endif
  39. static const char *MODULES_TO_RELOAD[] = {"filter", "session", NULL};
  40. frankenphp_version frankenphp_get_version() {
  41. return (frankenphp_version){
  42. PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION,
  43. PHP_EXTRA_VERSION, PHP_VERSION, PHP_VERSION_ID,
  44. };
  45. }
  46. frankenphp_config frankenphp_get_config() {
  47. return (frankenphp_config){
  48. frankenphp_get_version(),
  49. #ifdef ZTS
  50. true,
  51. #else
  52. false,
  53. #endif
  54. #ifdef ZEND_SIGNALS
  55. true,
  56. #else
  57. false,
  58. #endif
  59. #ifdef ZEND_MAX_EXECUTION_TIMERS
  60. true,
  61. #else
  62. false,
  63. #endif
  64. };
  65. }
  66. typedef struct frankenphp_server_context {
  67. bool has_main_request;
  68. bool has_active_request;
  69. bool worker_ready;
  70. char *cookie_data;
  71. bool finished;
  72. } frankenphp_server_context;
  73. __thread bool should_filter_var = 0;
  74. __thread frankenphp_server_context *local_ctx = NULL;
  75. __thread uintptr_t thread_index;
  76. __thread zval *os_environment = NULL;
  77. static void frankenphp_free_request_context() {
  78. frankenphp_server_context *ctx = SG(server_context);
  79. free(ctx->cookie_data);
  80. ctx->cookie_data = NULL;
  81. /* Is freed via thread.Unpin() at the end of each request */
  82. SG(request_info).auth_password = NULL;
  83. SG(request_info).auth_user = NULL;
  84. SG(request_info).request_method = NULL;
  85. SG(request_info).query_string = NULL;
  86. SG(request_info).content_type = NULL;
  87. SG(request_info).path_translated = NULL;
  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. PHPAPI void get_full_env(zval *track_vars_array) {
  126. struct go_getfullenv_return full_env = go_getfullenv(thread_index);
  127. for (int i = 0; i < full_env.r1; i++) {
  128. go_string key = full_env.r0[i * 2];
  129. go_string val = full_env.r0[i * 2 + 1];
  130. // create PHP strings for key and value
  131. zend_string *key_str = zend_string_init(key.data, key.len, 0);
  132. zend_string *val_str = zend_string_init(val.data, val.len, 0);
  133. // add to the associative array
  134. add_assoc_str(track_vars_array, ZSTR_VAL(key_str), val_str);
  135. // release the key string
  136. zend_string_release(key_str);
  137. }
  138. }
  139. /* Adapted from php_request_startup() */
  140. static int frankenphp_worker_request_startup() {
  141. int retval = SUCCESS;
  142. zend_try {
  143. frankenphp_destroy_super_globals();
  144. php_output_activate();
  145. /* initialize global variables */
  146. PG(header_is_being_sent) = 0;
  147. PG(connection_status) = PHP_CONNECTION_NORMAL;
  148. /* Keep the current execution context */
  149. sapi_activate();
  150. #ifdef ZEND_MAX_EXECUTION_TIMERS
  151. if (PG(max_input_time) == -1) {
  152. zend_set_timeout(EG(timeout_seconds), 1);
  153. } else {
  154. zend_set_timeout(PG(max_input_time), 1);
  155. }
  156. #endif
  157. if (PG(expose_php)) {
  158. sapi_add_header(SAPI_PHP_VERSION_HEADER,
  159. sizeof(SAPI_PHP_VERSION_HEADER) - 1, 1);
  160. }
  161. if (PG(output_handler) && PG(output_handler)[0]) {
  162. zval oh;
  163. ZVAL_STRING(&oh, PG(output_handler));
  164. php_output_start_user(&oh, 0, PHP_OUTPUT_HANDLER_STDFLAGS);
  165. zval_ptr_dtor(&oh);
  166. } else if (PG(output_buffering)) {
  167. php_output_start_user(NULL,
  168. PG(output_buffering) > 1 ? PG(output_buffering) : 0,
  169. PHP_OUTPUT_HANDLER_STDFLAGS);
  170. } else if (PG(implicit_flush)) {
  171. php_output_set_implicit_flush(1);
  172. }
  173. php_hash_environment();
  174. zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER));
  175. /* Unfinish the request */
  176. frankenphp_server_context *ctx = SG(server_context);
  177. ctx->finished = false;
  178. /* TODO: store the list of modules to reload in a global module variable */
  179. const char **module_name;
  180. zend_module_entry *module;
  181. for (module_name = MODULES_TO_RELOAD; *module_name; module_name++) {
  182. if ((module = zend_hash_str_find_ptr(&module_registry, *module_name,
  183. sizeof(*module_name) - 1)) &&
  184. module->request_startup_func) {
  185. module->request_startup_func(module->type, module->module_number);
  186. }
  187. }
  188. }
  189. zend_catch { retval = FAILURE; }
  190. zend_end_try();
  191. SG(sapi_started) = 1;
  192. return retval;
  193. }
  194. PHP_FUNCTION(frankenphp_finish_request) { /* {{{ */
  195. if (zend_parse_parameters_none() == FAILURE) {
  196. RETURN_THROWS();
  197. }
  198. frankenphp_server_context *ctx = SG(server_context);
  199. if (ctx->finished) {
  200. RETURN_FALSE;
  201. }
  202. php_output_end_all();
  203. php_header();
  204. if (ctx->has_active_request) {
  205. go_frankenphp_finish_php_request(thread_index);
  206. }
  207. ctx->finished = true;
  208. RETURN_TRUE;
  209. } /* }}} */
  210. /* {{{ Call go's putenv to prevent race conditions */
  211. PHP_FUNCTION(frankenphp_putenv) {
  212. char *setting;
  213. size_t setting_len;
  214. ZEND_PARSE_PARAMETERS_START(1, 1)
  215. Z_PARAM_STRING(setting, setting_len)
  216. ZEND_PARSE_PARAMETERS_END();
  217. // Cast str_len to int (ensure it fits in an int)
  218. if (setting_len > INT_MAX) {
  219. php_error(E_WARNING, "String length exceeds maximum integer value");
  220. RETURN_FALSE;
  221. }
  222. if (go_putenv(setting, (int)setting_len)) {
  223. RETURN_TRUE;
  224. } else {
  225. RETURN_FALSE;
  226. }
  227. } /* }}} */
  228. /* {{{ Call go's getenv to prevent race conditions */
  229. PHP_FUNCTION(frankenphp_getenv) {
  230. char *name = NULL;
  231. size_t name_len = 0;
  232. bool local_only = 0;
  233. ZEND_PARSE_PARAMETERS_START(0, 2)
  234. Z_PARAM_OPTIONAL
  235. Z_PARAM_STRING_OR_NULL(name, name_len)
  236. Z_PARAM_BOOL(local_only)
  237. ZEND_PARSE_PARAMETERS_END();
  238. if (!name) {
  239. array_init(return_value);
  240. get_full_env(return_value);
  241. return;
  242. }
  243. go_string gname = {name_len, name};
  244. struct go_getenv_return result = go_getenv(thread_index, &gname);
  245. if (result.r0) {
  246. // Return the single environment variable as a string
  247. RETVAL_STRINGL(result.r1->data, result.r1->len);
  248. } else {
  249. // Environment variable does not exist
  250. RETVAL_FALSE;
  251. }
  252. } /* }}} */
  253. /* {{{ Fetch all HTTP request headers */
  254. PHP_FUNCTION(frankenphp_request_headers) {
  255. if (zend_parse_parameters_none() == FAILURE) {
  256. RETURN_THROWS();
  257. }
  258. frankenphp_server_context *ctx = SG(server_context);
  259. struct go_apache_request_headers_return headers =
  260. go_apache_request_headers(thread_index, ctx->has_active_request);
  261. array_init_size(return_value, headers.r1);
  262. for (size_t i = 0; i < headers.r1; i++) {
  263. go_string key = headers.r0[i * 2];
  264. go_string val = headers.r0[i * 2 + 1];
  265. add_assoc_stringl_ex(return_value, key.data, key.len, val.data, val.len);
  266. }
  267. }
  268. /* }}} */
  269. /* add_response_header and apache_response_headers are copied from
  270. * https://github.com/php/php-src/blob/master/sapi/cli/php_cli_server.c
  271. * Copyright (c) The PHP Group
  272. * Licensed under The PHP License
  273. * Original authors: Moriyoshi Koizumi <moriyoshi@php.net> and Xinchen Hui
  274. * <laruence@php.net>
  275. */
  276. static void add_response_header(sapi_header_struct *h,
  277. zval *return_value) /* {{{ */
  278. {
  279. if (h->header_len > 0) {
  280. char *s;
  281. size_t len = 0;
  282. ALLOCA_FLAG(use_heap)
  283. char *p = strchr(h->header, ':');
  284. if (NULL != p) {
  285. len = p - h->header;
  286. }
  287. if (len > 0) {
  288. while (len != 0 &&
  289. (h->header[len - 1] == ' ' || h->header[len - 1] == '\t')) {
  290. len--;
  291. }
  292. if (len) {
  293. s = do_alloca(len + 1, use_heap);
  294. memcpy(s, h->header, len);
  295. s[len] = 0;
  296. do {
  297. p++;
  298. } while (*p == ' ' || *p == '\t');
  299. add_assoc_stringl_ex(return_value, s, len, p,
  300. h->header_len - (p - h->header));
  301. free_alloca(s, use_heap);
  302. }
  303. }
  304. }
  305. }
  306. /* }}} */
  307. PHP_FUNCTION(frankenphp_response_headers) /* {{{ */
  308. {
  309. if (zend_parse_parameters_none() == FAILURE) {
  310. RETURN_THROWS();
  311. }
  312. array_init(return_value);
  313. zend_llist_apply_with_argument(
  314. &SG(sapi_headers).headers,
  315. (llist_apply_with_arg_func_t)add_response_header, return_value);
  316. }
  317. /* }}} */
  318. PHP_FUNCTION(frankenphp_handle_request) {
  319. zend_fcall_info fci;
  320. zend_fcall_info_cache fcc;
  321. ZEND_PARSE_PARAMETERS_START(1, 1)
  322. Z_PARAM_FUNC(fci, fcc)
  323. ZEND_PARSE_PARAMETERS_END();
  324. frankenphp_server_context *ctx = SG(server_context);
  325. if (!ctx->has_main_request) {
  326. /* not a worker, throw an error */
  327. zend_throw_exception(
  328. spl_ce_RuntimeException,
  329. "frankenphp_handle_request() called while not in worker mode", 0);
  330. RETURN_THROWS();
  331. }
  332. if (!ctx->worker_ready) {
  333. /* Clean the first dummy request created to initialize the worker */
  334. frankenphp_worker_request_shutdown();
  335. ctx->worker_ready = true;
  336. }
  337. #ifdef ZEND_MAX_EXECUTION_TIMERS
  338. /* Disable timeouts while waiting for a request to handle */
  339. zend_unset_timeout();
  340. #endif
  341. bool request = go_frankenphp_worker_handle_request_start(thread_index);
  342. if (frankenphp_worker_request_startup() == FAILURE
  343. /* Shutting down */
  344. || !request) {
  345. RETURN_FALSE;
  346. }
  347. #ifdef ZEND_MAX_EXECUTION_TIMERS
  348. /*
  349. * Reset default timeout
  350. */
  351. if (PG(max_input_time) != -1) {
  352. zend_set_timeout(INI_INT("max_execution_time"), 0);
  353. }
  354. #endif
  355. /* Call the PHP func */
  356. zval retval = {0};
  357. fci.size = sizeof fci;
  358. fci.retval = &retval;
  359. if (zend_call_function(&fci, &fcc) == SUCCESS) {
  360. zval_ptr_dtor(&retval);
  361. }
  362. /*
  363. * If an exception occured, print the message to the client before closing the
  364. * connection
  365. */
  366. if (EG(exception)) {
  367. zend_exception_error(EG(exception), E_ERROR);
  368. }
  369. frankenphp_worker_request_shutdown();
  370. ctx->has_active_request = false;
  371. go_frankenphp_finish_worker_request(thread_index);
  372. RETURN_TRUE;
  373. }
  374. PHP_FUNCTION(headers_send) {
  375. zend_long response_code = 200;
  376. ZEND_PARSE_PARAMETERS_START(0, 1)
  377. Z_PARAM_OPTIONAL
  378. Z_PARAM_LONG(response_code)
  379. ZEND_PARSE_PARAMETERS_END();
  380. int previous_status_code = SG(sapi_headers).http_response_code;
  381. SG(sapi_headers).http_response_code = response_code;
  382. if (response_code >= 100 && response_code < 200) {
  383. int ret = sapi_module.send_headers(&SG(sapi_headers));
  384. SG(sapi_headers).http_response_code = previous_status_code;
  385. RETURN_LONG(ret);
  386. }
  387. RETURN_LONG(sapi_send_headers());
  388. }
  389. PHP_MINIT_FUNCTION(frankenphp) {
  390. zend_function *func;
  391. // Override putenv
  392. func = zend_hash_str_find_ptr(CG(function_table), "putenv",
  393. sizeof("putenv") - 1);
  394. if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION) {
  395. ((zend_internal_function *)func)->handler = ZEND_FN(frankenphp_putenv);
  396. } else {
  397. php_error(E_WARNING, "Failed to find built-in putenv function");
  398. }
  399. // Override getenv
  400. func = zend_hash_str_find_ptr(CG(function_table), "getenv",
  401. sizeof("getenv") - 1);
  402. if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION) {
  403. ((zend_internal_function *)func)->handler = ZEND_FN(frankenphp_getenv);
  404. } else {
  405. php_error(E_WARNING, "Failed to find built-in getenv function");
  406. }
  407. return SUCCESS;
  408. }
  409. static zend_module_entry frankenphp_module = {
  410. STANDARD_MODULE_HEADER,
  411. "frankenphp",
  412. ext_functions, /* function table */
  413. PHP_MINIT(frankenphp), /* initialization */
  414. NULL, /* shutdown */
  415. NULL, /* request initialization */
  416. NULL, /* request shutdown */
  417. NULL, /* information */
  418. TOSTRING(FRANKENPHP_VERSION),
  419. STANDARD_MODULE_PROPERTIES};
  420. static void frankenphp_request_shutdown() {
  421. frankenphp_server_context *ctx = SG(server_context);
  422. if (ctx->has_main_request && ctx->has_active_request) {
  423. frankenphp_destroy_super_globals();
  424. }
  425. php_request_shutdown((void *)0);
  426. frankenphp_free_request_context();
  427. memset(local_ctx, 0, sizeof(frankenphp_server_context));
  428. }
  429. int frankenphp_update_server_context(
  430. bool create, bool has_main_request, bool has_active_request,
  431. const char *request_method, char *query_string, zend_long content_length,
  432. char *path_translated, char *request_uri, const char *content_type,
  433. char *auth_user, char *auth_password, int proto_num) {
  434. frankenphp_server_context *ctx;
  435. if (create) {
  436. ctx = local_ctx;
  437. ctx->worker_ready = false;
  438. ctx->cookie_data = NULL;
  439. ctx->finished = false;
  440. SG(server_context) = ctx;
  441. } else {
  442. ctx = (frankenphp_server_context *)SG(server_context);
  443. }
  444. // It is not reset by zend engine, set it to 200.
  445. SG(sapi_headers).http_response_code = 200;
  446. ctx->has_main_request = has_main_request;
  447. ctx->has_active_request = has_active_request;
  448. SG(request_info).auth_password = auth_password;
  449. SG(request_info).auth_user = auth_user;
  450. SG(request_info).request_method = request_method;
  451. SG(request_info).query_string = query_string;
  452. SG(request_info).content_type = content_type;
  453. SG(request_info).content_length = content_length;
  454. SG(request_info).path_translated = path_translated;
  455. SG(request_info).request_uri = request_uri;
  456. SG(request_info).proto_num = proto_num;
  457. return SUCCESS;
  458. }
  459. static int frankenphp_startup(sapi_module_struct *sapi_module) {
  460. php_import_environment_variables = get_full_env;
  461. return php_module_startup(sapi_module, &frankenphp_module);
  462. }
  463. static int frankenphp_deactivate(void) {
  464. /* TODO: flush everything */
  465. return SUCCESS;
  466. }
  467. static size_t frankenphp_ub_write(const char *str, size_t str_length) {
  468. frankenphp_server_context *ctx = SG(server_context);
  469. if (ctx->finished) {
  470. /* TODO: maybe log a warning that we tried to write to a finished request?
  471. */
  472. return 0;
  473. }
  474. struct go_ub_write_return result =
  475. go_ub_write(thread_index, (char *)str, str_length);
  476. if (result.r1) {
  477. php_handle_aborted_connection();
  478. }
  479. return result.r0;
  480. }
  481. static int frankenphp_send_headers(sapi_headers_struct *sapi_headers) {
  482. if (SG(request_info).no_headers == 1) {
  483. return SAPI_HEADER_SENT_SUCCESSFULLY;
  484. }
  485. int status;
  486. frankenphp_server_context *ctx = SG(server_context);
  487. if (!ctx->has_active_request) {
  488. return SAPI_HEADER_SEND_FAILED;
  489. }
  490. if (SG(sapi_headers).http_status_line) {
  491. status = atoi((SG(sapi_headers).http_status_line) + 9);
  492. } else {
  493. status = SG(sapi_headers).http_response_code;
  494. if (!status) {
  495. status = 200;
  496. }
  497. }
  498. go_write_headers(thread_index, status, &sapi_headers->headers);
  499. return SAPI_HEADER_SENT_SUCCESSFULLY;
  500. }
  501. static void frankenphp_sapi_flush(void *server_context) {
  502. frankenphp_server_context *ctx = (frankenphp_server_context *)server_context;
  503. if (ctx && ctx->has_active_request && go_sapi_flush(thread_index)) {
  504. php_handle_aborted_connection();
  505. }
  506. }
  507. static size_t frankenphp_read_post(char *buffer, size_t count_bytes) {
  508. frankenphp_server_context *ctx = SG(server_context);
  509. return ctx->has_active_request
  510. ? go_read_post(thread_index, buffer, count_bytes)
  511. : 0;
  512. }
  513. static char *frankenphp_read_cookies(void) {
  514. frankenphp_server_context *ctx = SG(server_context);
  515. if (!ctx->has_active_request) {
  516. return "";
  517. }
  518. ctx->cookie_data = go_read_cookies(thread_index);
  519. return ctx->cookie_data;
  520. }
  521. /* all variables with well defined keys can safely be registered like this */
  522. void frankenphp_register_trusted_var(zend_string *z_key, char *value,
  523. int val_len, zval *track_vars_array) {
  524. if (value == NULL) {
  525. value = "";
  526. }
  527. size_t new_val_len = val_len;
  528. if (!should_filter_var ||
  529. sapi_module.input_filter(PARSE_SERVER, ZSTR_VAL(z_key), &value,
  530. new_val_len, &new_val_len)) {
  531. zval z_value;
  532. ZVAL_STRINGL_FAST(&z_value, value, new_val_len);
  533. zend_hash_update_ind(Z_ARRVAL_P(track_vars_array), z_key, &z_value);
  534. }
  535. }
  536. /** Persistent strings are ignored by the PHP GC, we have to release these
  537. * ourselves **/
  538. zend_string *frankenphp_init_persistent_string(const char *string, size_t len) {
  539. return zend_string_init(string, len, 1);
  540. }
  541. void frankenphp_release_zend_string(zend_string *z_string) {
  542. zend_string_release(z_string);
  543. }
  544. static void
  545. frankenphp_register_variable_from_request_info(zend_string *zKey, char *value,
  546. bool must_be_present,
  547. zval *track_vars_array) {
  548. if (value != NULL) {
  549. frankenphp_register_trusted_var(zKey, value, strlen(value),
  550. track_vars_array);
  551. } else if (must_be_present) {
  552. frankenphp_register_trusted_var(zKey, "", 0, track_vars_array);
  553. }
  554. }
  555. void frankenphp_register_variables_from_request_info(
  556. zval *track_vars_array, zend_string *content_type,
  557. zend_string *path_translated, zend_string *query_string,
  558. zend_string *auth_user, zend_string *request_method,
  559. zend_string *request_uri) {
  560. frankenphp_register_variable_from_request_info(
  561. content_type, (char *)SG(request_info).content_type, false,
  562. track_vars_array);
  563. frankenphp_register_variable_from_request_info(
  564. path_translated, (char *)SG(request_info).path_translated, false,
  565. track_vars_array);
  566. frankenphp_register_variable_from_request_info(
  567. query_string, SG(request_info).query_string, true, track_vars_array);
  568. frankenphp_register_variable_from_request_info(
  569. auth_user, (char *)SG(request_info).auth_user, false, track_vars_array);
  570. frankenphp_register_variable_from_request_info(
  571. request_method, (char *)SG(request_info).request_method, false,
  572. track_vars_array);
  573. frankenphp_register_variable_from_request_info(
  574. request_uri, SG(request_info).request_uri, true, track_vars_array);
  575. }
  576. /* variables with user-defined keys must be registered safely
  577. * see: php_variables.c -> php_register_variable_ex (#1106) */
  578. void frankenphp_register_variable_safe(char *key, char *val, size_t val_len,
  579. zval *track_vars_array) {
  580. if (val == NULL || key == NULL) {
  581. return;
  582. }
  583. size_t new_val_len = val_len;
  584. if (!should_filter_var ||
  585. sapi_module.input_filter(PARSE_SERVER, key, &val, new_val_len,
  586. &new_val_len)) {
  587. php_register_variable_safe(key, val, new_val_len, track_vars_array);
  588. }
  589. }
  590. static void frankenphp_register_variables(zval *track_vars_array) {
  591. /* https://www.php.net/manual/en/reserved.variables.server.php */
  592. /* In CGI mode, we consider the environment to be a part of the server
  593. * variables.
  594. */
  595. frankenphp_server_context *ctx = SG(server_context);
  596. /* in non-worker mode we import the os environment regularly */
  597. if (!ctx->has_main_request) {
  598. get_full_env(track_vars_array);
  599. // php_import_environment_variables(track_vars_array);
  600. go_register_variables(thread_index, track_vars_array);
  601. return;
  602. }
  603. /* In worker mode we cache the os environment */
  604. if (os_environment == NULL) {
  605. os_environment = malloc(sizeof(zval));
  606. array_init(os_environment);
  607. get_full_env(os_environment);
  608. // php_import_environment_variables(os_environment);
  609. }
  610. zend_hash_copy(Z_ARR_P(track_vars_array), Z_ARR_P(os_environment),
  611. (copy_ctor_func_t)zval_add_ref);
  612. go_register_variables(thread_index, track_vars_array);
  613. }
  614. static void frankenphp_log_message(const char *message, int syslog_type_int) {
  615. go_log((char *)message, syslog_type_int);
  616. }
  617. static char *frankenphp_getenv(const char *name, size_t name_len) {
  618. go_string gname = {name_len, (char *)name};
  619. return go_sapi_getenv(thread_index, &gname);
  620. }
  621. sapi_module_struct frankenphp_sapi_module = {
  622. "frankenphp", /* name */
  623. "FrankenPHP", /* pretty name */
  624. frankenphp_startup, /* startup */
  625. php_module_shutdown_wrapper, /* shutdown */
  626. NULL, /* activate */
  627. frankenphp_deactivate, /* deactivate */
  628. frankenphp_ub_write, /* unbuffered write */
  629. frankenphp_sapi_flush, /* flush */
  630. NULL, /* get uid */
  631. frankenphp_getenv, /* getenv */
  632. php_error, /* error handler */
  633. NULL, /* header handler */
  634. frankenphp_send_headers, /* send headers handler */
  635. NULL, /* send header handler */
  636. frankenphp_read_post, /* read POST data */
  637. frankenphp_read_cookies, /* read Cookies */
  638. frankenphp_register_variables, /* register server variables */
  639. frankenphp_log_message, /* Log message */
  640. NULL, /* Get request time */
  641. NULL, /* Child terminate */
  642. STANDARD_SAPI_MODULE_PROPERTIES};
  643. /* Sets thread name for profiling and debugging.
  644. *
  645. * Adapted from https://github.com/Pithikos/C-Thread-Pool
  646. * Copyright: Johan Hanssen Seferidis
  647. * License: MIT
  648. */
  649. static void set_thread_name(char *thread_name) {
  650. #if defined(__linux__)
  651. /* Use prctl instead to prevent using _GNU_SOURCE flag and implicit
  652. * declaration */
  653. prctl(PR_SET_NAME, thread_name);
  654. #elif defined(__APPLE__) && defined(__MACH__)
  655. pthread_setname_np(thread_name);
  656. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  657. pthread_set_name_np(pthread_self(), thread_name);
  658. #endif
  659. }
  660. static void *php_thread(void *arg) {
  661. thread_index = (uintptr_t)arg;
  662. char thread_name[16] = {0};
  663. snprintf(thread_name, 16, "php-%" PRIxPTR, thread_index);
  664. set_thread_name(thread_name);
  665. #ifdef ZTS
  666. /* initial resource fetch */
  667. (void)ts_resource(0);
  668. #ifdef PHP_WIN32
  669. ZEND_TSRMLS_CACHE_UPDATE();
  670. #endif
  671. #endif
  672. local_ctx = malloc(sizeof(frankenphp_server_context));
  673. /* check if a default filter is set in php.ini and only filter if
  674. * it is, this is deprecated and will be removed in PHP 9 */
  675. char *default_filter;
  676. cfg_get_string("filter.default", &default_filter);
  677. should_filter_var = default_filter != NULL;
  678. go_frankenphp_on_thread_startup(thread_index);
  679. // perform work until go signals to stop
  680. while (true) {
  681. char *scriptName = go_frankenphp_before_script_execution(thread_index);
  682. // if the script name is NULL, the thread should exit
  683. if (scriptName == NULL) {
  684. break;
  685. }
  686. // if the script name is not empty, execute the PHP script
  687. if (strlen(scriptName) != 0) {
  688. int exit_status = frankenphp_execute_script(scriptName);
  689. go_frankenphp_after_script_execution(thread_index, exit_status);
  690. }
  691. }
  692. go_frankenphp_release_known_variable_keys(thread_index);
  693. #ifdef ZTS
  694. ts_free_thread();
  695. #endif
  696. go_frankenphp_on_thread_shutdown(thread_index);
  697. return NULL;
  698. }
  699. static void *php_main(void *arg) {
  700. /*
  701. * SIGPIPE must be masked in non-Go threads:
  702. * https://pkg.go.dev/os/signal#hdr-Go_programs_that_use_cgo_or_SWIG
  703. */
  704. sigset_t set;
  705. sigemptyset(&set);
  706. sigaddset(&set, SIGPIPE);
  707. if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) {
  708. perror("failed to block SIGPIPE");
  709. exit(EXIT_FAILURE);
  710. }
  711. set_thread_name("php-main");
  712. #ifdef ZTS
  713. #if (PHP_VERSION_ID >= 80300)
  714. php_tsrm_startup_ex((intptr_t)arg);
  715. #else
  716. php_tsrm_startup();
  717. #endif
  718. /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/
  719. #ifdef PHP_WIN32
  720. ZEND_TSRMLS_CACHE_UPDATE();
  721. #endif
  722. #endif
  723. sapi_startup(&frankenphp_sapi_module);
  724. #ifndef ZEND_MAX_EXECUTION_TIMERS
  725. #if (PHP_VERSION_ID >= 80300)
  726. frankenphp_sapi_module.ini_entries = HARDCODED_INI;
  727. #else
  728. frankenphp_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
  729. if (frankenphp_sapi_module.ini_entries == NULL) {
  730. perror("malloc failed");
  731. exit(EXIT_FAILURE);
  732. }
  733. memcpy(frankenphp_sapi_module.ini_entries, HARDCODED_INI,
  734. sizeof(HARDCODED_INI));
  735. #endif
  736. #endif
  737. frankenphp_sapi_module.startup(&frankenphp_sapi_module);
  738. go_frankenphp_main_thread_is_ready();
  739. /* channel closed, shutdown gracefully */
  740. frankenphp_sapi_module.shutdown(&frankenphp_sapi_module);
  741. sapi_shutdown();
  742. #ifdef ZTS
  743. tsrm_shutdown();
  744. #endif
  745. #if (PHP_VERSION_ID < 80300)
  746. if (frankenphp_sapi_module.ini_entries) {
  747. free(frankenphp_sapi_module.ini_entries);
  748. frankenphp_sapi_module.ini_entries = NULL;
  749. }
  750. #endif
  751. go_frankenphp_shutdown_main_thread();
  752. return NULL;
  753. }
  754. int frankenphp_new_main_thread(int num_threads) {
  755. pthread_t thread;
  756. if (pthread_create(&thread, NULL, &php_main, (void *)(intptr_t)num_threads) !=
  757. 0) {
  758. return -1;
  759. }
  760. return pthread_detach(thread);
  761. }
  762. bool frankenphp_new_php_thread(uintptr_t thread_index) {
  763. pthread_t thread;
  764. if (pthread_create(&thread, NULL, &php_thread, (void *)thread_index) != 0) {
  765. return false;
  766. }
  767. pthread_detach(thread);
  768. return true;
  769. }
  770. int frankenphp_request_startup() {
  771. if (php_request_startup() == SUCCESS) {
  772. return SUCCESS;
  773. }
  774. php_request_shutdown((void *)0);
  775. return FAILURE;
  776. }
  777. int frankenphp_execute_script(char *file_name) {
  778. if (frankenphp_request_startup() == FAILURE) {
  779. return FAILURE;
  780. }
  781. int status = SUCCESS;
  782. zend_file_handle file_handle;
  783. zend_stream_init_filename(&file_handle, file_name);
  784. file_handle.primary_script = 1;
  785. zend_first_try {
  786. EG(exit_status) = 0;
  787. php_execute_script(&file_handle);
  788. status = EG(exit_status);
  789. }
  790. zend_catch { status = EG(exit_status); }
  791. zend_end_try();
  792. // free the cached os environment before shutting down the script
  793. if (os_environment != NULL) {
  794. zval_ptr_dtor(os_environment);
  795. free(os_environment);
  796. os_environment = NULL;
  797. }
  798. zend_destroy_file_handle(&file_handle);
  799. frankenphp_free_request_context();
  800. frankenphp_request_shutdown();
  801. return status;
  802. }
  803. /* Use global variables to store CLI arguments to prevent useless allocations */
  804. static char *cli_script;
  805. static int cli_argc;
  806. static char **cli_argv;
  807. /*
  808. * CLI code is adapted from
  809. * https://github.com/php/php-src/blob/master/sapi/cli/php_cli.c Copyright (c)
  810. * The PHP Group Licensed under The PHP License Original uthors: Edin Kadribasic
  811. * <edink@php.net>, Marcus Boerger <helly@php.net> and Johannes Schlueter
  812. * <johannes@php.net> Parts based on CGI SAPI Module by Rasmus Lerdorf, Stig
  813. * Bakken and Zeev Suraski
  814. */
  815. static void cli_register_file_handles(bool no_close) /* {{{ */
  816. {
  817. php_stream *s_in, *s_out, *s_err;
  818. php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL;
  819. zend_constant ic, oc, ec;
  820. s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in);
  821. s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
  822. s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
  823. if (s_in == NULL || s_out == NULL || s_err == NULL) {
  824. if (s_in)
  825. php_stream_close(s_in);
  826. if (s_out)
  827. php_stream_close(s_out);
  828. if (s_err)
  829. php_stream_close(s_err);
  830. return;
  831. }
  832. if (no_close) {
  833. s_in->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  834. s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  835. s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  836. }
  837. /*s_in_process = s_in;*/
  838. php_stream_to_zval(s_in, &ic.value);
  839. php_stream_to_zval(s_out, &oc.value);
  840. php_stream_to_zval(s_err, &ec.value);
  841. ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0);
  842. ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0);
  843. zend_register_constant(&ic);
  844. ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0);
  845. oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0);
  846. zend_register_constant(&oc);
  847. ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0);
  848. ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0);
  849. zend_register_constant(&ec);
  850. }
  851. /* }}} */
  852. static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */
  853. {
  854. size_t len;
  855. char *docroot = "";
  856. /*
  857. * In CGI mode, we consider the environment to be a part of the server
  858. * variables
  859. */
  860. php_import_environment_variables(track_vars_array);
  861. /* Build the special-case PHP_SELF variable for the CLI version */
  862. len = strlen(cli_script);
  863. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &cli_script, len,
  864. &len)) {
  865. php_register_variable_safe("PHP_SELF", cli_script, len, track_vars_array);
  866. }
  867. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &cli_script, len,
  868. &len)) {
  869. php_register_variable_safe("SCRIPT_NAME", cli_script, len,
  870. track_vars_array);
  871. }
  872. /* filenames are empty for stdin */
  873. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &cli_script,
  874. len, &len)) {
  875. php_register_variable_safe("SCRIPT_FILENAME", cli_script, len,
  876. track_vars_array);
  877. }
  878. if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &cli_script,
  879. len, &len)) {
  880. php_register_variable_safe("PATH_TRANSLATED", cli_script, len,
  881. track_vars_array);
  882. }
  883. /* just make it available */
  884. len = 0U;
  885. if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len,
  886. &len)) {
  887. php_register_variable_safe("DOCUMENT_ROOT", docroot, len, track_vars_array);
  888. }
  889. }
  890. /* }}} */
  891. static void *execute_script_cli(void *arg) {
  892. void *exit_status;
  893. /*
  894. * The SAPI name "cli" is hardcoded into too many programs... let's usurp it.
  895. */
  896. php_embed_module.name = "cli";
  897. php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP";
  898. php_embed_module.register_server_variables = sapi_cli_register_variables;
  899. php_embed_init(cli_argc, cli_argv);
  900. cli_register_file_handles(false);
  901. zend_first_try {
  902. zend_file_handle file_handle;
  903. zend_stream_init_filename(&file_handle, cli_script);
  904. CG(skip_shebang) = 1;
  905. php_execute_script(&file_handle);
  906. }
  907. zend_end_try();
  908. exit_status = (void *)(intptr_t)EG(exit_status);
  909. php_embed_shutdown();
  910. return exit_status;
  911. }
  912. int frankenphp_execute_script_cli(char *script, int argc, char **argv) {
  913. pthread_t thread;
  914. int err;
  915. void *exit_status;
  916. cli_script = script;
  917. cli_argc = argc;
  918. cli_argv = argv;
  919. /*
  920. * Start the script in a dedicated thread to prevent conflicts between Go and
  921. * PHP signal handlers
  922. */
  923. err = pthread_create(&thread, NULL, execute_script_cli, NULL);
  924. if (err != 0) {
  925. return err;
  926. }
  927. err = pthread_join(thread, &exit_status);
  928. if (err != 0) {
  929. return err;
  930. }
  931. return (intptr_t)exit_status;
  932. }
  933. int frankenphp_execute_php_function(const char *php_function) {
  934. zval retval = {0};
  935. zend_fcall_info fci = {0};
  936. zend_fcall_info_cache fci_cache = {0};
  937. zend_string *func_name =
  938. zend_string_init(php_function, strlen(php_function), 0);
  939. ZVAL_STR(&fci.function_name, func_name);
  940. fci.size = sizeof fci;
  941. fci.retval = &retval;
  942. int success = 0;
  943. zend_try { success = zend_call_function(&fci, &fci_cache) == SUCCESS; }
  944. zend_end_try();
  945. zend_string_release(func_name);
  946. return success;
  947. }
  948. int frankenphp_reset_opcache(void) {
  949. if (zend_hash_str_exists(CG(function_table), "opcache_reset",
  950. sizeof("opcache_reset") - 1)) {
  951. return frankenphp_execute_php_function("opcache_reset");
  952. }
  953. return 0;
  954. }