frankenphp.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  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() */
  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. size_t val_len, HashTable *ht) {
  524. if (value == NULL) {
  525. zval empty;
  526. ZVAL_EMPTY_STRING(&empty);
  527. zend_hash_update_ind(ht, z_key, &empty);
  528. return;
  529. }
  530. size_t new_val_len = val_len;
  531. if (!should_filter_var ||
  532. sapi_module.input_filter(PARSE_SERVER, ZSTR_VAL(z_key), &value,
  533. new_val_len, &new_val_len)) {
  534. zval z_value;
  535. ZVAL_STRINGL_FAST(&z_value, value, new_val_len);
  536. zend_hash_update_ind(ht, z_key, &z_value);
  537. }
  538. }
  539. /* Register known $_SERVER variables in bulk to avoid cgo overhead */
  540. void frankenphp_register_bulk(
  541. zval *track_vars_array, ht_key_value_pair remote_addr,
  542. ht_key_value_pair remote_host, ht_key_value_pair remote_port,
  543. ht_key_value_pair document_root, ht_key_value_pair path_info,
  544. ht_key_value_pair php_self, ht_key_value_pair document_uri,
  545. ht_key_value_pair script_filename, ht_key_value_pair script_name,
  546. ht_key_value_pair https, ht_key_value_pair ssl_protocol,
  547. ht_key_value_pair request_scheme, ht_key_value_pair server_name,
  548. ht_key_value_pair server_port, ht_key_value_pair content_length,
  549. ht_key_value_pair gateway_interface, ht_key_value_pair server_protocol,
  550. ht_key_value_pair server_software, ht_key_value_pair http_host,
  551. ht_key_value_pair auth_type, ht_key_value_pair remote_ident,
  552. ht_key_value_pair request_uri) {
  553. HashTable *ht = Z_ARRVAL_P(track_vars_array);
  554. frankenphp_register_trusted_var(remote_addr.key, remote_addr.val,
  555. remote_addr.val_len, ht);
  556. frankenphp_register_trusted_var(remote_host.key, remote_host.val,
  557. remote_host.val_len, ht);
  558. frankenphp_register_trusted_var(remote_port.key, remote_port.val,
  559. remote_port.val_len, ht);
  560. frankenphp_register_trusted_var(document_root.key, document_root.val,
  561. document_root.val_len, ht);
  562. frankenphp_register_trusted_var(path_info.key, path_info.val,
  563. path_info.val_len, ht);
  564. frankenphp_register_trusted_var(php_self.key, php_self.val, php_self.val_len,
  565. ht);
  566. frankenphp_register_trusted_var(document_uri.key, document_uri.val,
  567. document_uri.val_len, ht);
  568. frankenphp_register_trusted_var(script_filename.key, script_filename.val,
  569. script_filename.val_len, ht);
  570. frankenphp_register_trusted_var(script_name.key, script_name.val,
  571. script_name.val_len, ht);
  572. frankenphp_register_trusted_var(https.key, https.val, https.val_len, ht);
  573. frankenphp_register_trusted_var(ssl_protocol.key, ssl_protocol.val,
  574. ssl_protocol.val_len, ht);
  575. frankenphp_register_trusted_var(request_scheme.key, request_scheme.val,
  576. request_scheme.val_len, ht);
  577. frankenphp_register_trusted_var(server_name.key, server_name.val,
  578. server_name.val_len, ht);
  579. frankenphp_register_trusted_var(server_port.key, server_port.val,
  580. server_port.val_len, ht);
  581. frankenphp_register_trusted_var(content_length.key, content_length.val,
  582. content_length.val_len, ht);
  583. frankenphp_register_trusted_var(gateway_interface.key, gateway_interface.val,
  584. gateway_interface.val_len, ht);
  585. frankenphp_register_trusted_var(server_protocol.key, server_protocol.val,
  586. server_protocol.val_len, ht);
  587. frankenphp_register_trusted_var(server_software.key, server_software.val,
  588. server_software.val_len, ht);
  589. frankenphp_register_trusted_var(http_host.key, http_host.val,
  590. http_host.val_len, ht);
  591. frankenphp_register_trusted_var(auth_type.key, auth_type.val,
  592. auth_type.val_len, ht);
  593. frankenphp_register_trusted_var(remote_ident.key, remote_ident.val,
  594. remote_ident.val_len, ht);
  595. frankenphp_register_trusted_var(request_uri.key, request_uri.val,
  596. request_uri.val_len, ht);
  597. }
  598. /** Persistent strings are ignored by the PHP GC, we have to release these
  599. * ourselves **/
  600. zend_string *frankenphp_init_persistent_string(const char *string, size_t len) {
  601. return zend_string_init(string, len, 1);
  602. }
  603. void frankenphp_release_zend_string(zend_string *z_string) {
  604. zend_string_release(z_string);
  605. }
  606. static void
  607. frankenphp_register_variable_from_request_info(zend_string *zKey, char *value,
  608. bool must_be_present,
  609. zval *track_vars_array) {
  610. if (value != NULL) {
  611. frankenphp_register_trusted_var(zKey, value, strlen(value),
  612. Z_ARRVAL_P(track_vars_array));
  613. } else if (must_be_present) {
  614. frankenphp_register_trusted_var(zKey, "", 0, Z_ARRVAL_P(track_vars_array));
  615. }
  616. }
  617. void frankenphp_register_variables_from_request_info(
  618. zval *track_vars_array, zend_string *content_type,
  619. zend_string *path_translated, zend_string *query_string,
  620. zend_string *auth_user, zend_string *request_method) {
  621. frankenphp_register_variable_from_request_info(
  622. content_type, (char *)SG(request_info).content_type, false,
  623. track_vars_array);
  624. frankenphp_register_variable_from_request_info(
  625. path_translated, (char *)SG(request_info).path_translated, false,
  626. track_vars_array);
  627. frankenphp_register_variable_from_request_info(
  628. query_string, SG(request_info).query_string, true, track_vars_array);
  629. frankenphp_register_variable_from_request_info(
  630. auth_user, (char *)SG(request_info).auth_user, false, track_vars_array);
  631. frankenphp_register_variable_from_request_info(
  632. request_method, (char *)SG(request_info).request_method, false,
  633. track_vars_array);
  634. }
  635. /* variables with user-defined keys must be registered safely
  636. * see: php_variables.c -> php_register_variable_ex (#1106) */
  637. void frankenphp_register_variable_safe(char *key, char *val, size_t val_len,
  638. zval *track_vars_array) {
  639. if (key == NULL) {
  640. return;
  641. }
  642. if (val == NULL) {
  643. val = "";
  644. }
  645. size_t new_val_len = val_len;
  646. if (!should_filter_var ||
  647. sapi_module.input_filter(PARSE_SERVER, key, &val, new_val_len,
  648. &new_val_len)) {
  649. php_register_variable_safe(key, val, new_val_len, track_vars_array);
  650. }
  651. }
  652. static void frankenphp_register_variables(zval *track_vars_array) {
  653. /* https://www.php.net/manual/en/reserved.variables.server.php */
  654. /* In CGI mode, we consider the environment to be a part of the server
  655. * variables.
  656. */
  657. frankenphp_server_context *ctx = SG(server_context);
  658. /* in non-worker mode we import the os environment regularly */
  659. if (!ctx->has_main_request) {
  660. get_full_env(track_vars_array);
  661. // php_import_environment_variables(track_vars_array);
  662. go_register_variables(thread_index, track_vars_array);
  663. return;
  664. }
  665. /* In worker mode we cache the os environment */
  666. if (os_environment == NULL) {
  667. os_environment = malloc(sizeof(zval));
  668. array_init(os_environment);
  669. get_full_env(os_environment);
  670. // php_import_environment_variables(os_environment);
  671. }
  672. zend_hash_copy(Z_ARR_P(track_vars_array), Z_ARR_P(os_environment),
  673. (copy_ctor_func_t)zval_add_ref);
  674. go_register_variables(thread_index, track_vars_array);
  675. }
  676. static void frankenphp_log_message(const char *message, int syslog_type_int) {
  677. go_log((char *)message, syslog_type_int);
  678. }
  679. static char *frankenphp_getenv(const char *name, size_t name_len) {
  680. go_string gname = {name_len, (char *)name};
  681. return go_sapi_getenv(thread_index, &gname);
  682. }
  683. sapi_module_struct frankenphp_sapi_module = {
  684. "frankenphp", /* name */
  685. "FrankenPHP", /* pretty name */
  686. frankenphp_startup, /* startup */
  687. php_module_shutdown_wrapper, /* shutdown */
  688. NULL, /* activate */
  689. frankenphp_deactivate, /* deactivate */
  690. frankenphp_ub_write, /* unbuffered write */
  691. frankenphp_sapi_flush, /* flush */
  692. NULL, /* get uid */
  693. frankenphp_getenv, /* getenv */
  694. php_error, /* error handler */
  695. NULL, /* header handler */
  696. frankenphp_send_headers, /* send headers handler */
  697. NULL, /* send header handler */
  698. frankenphp_read_post, /* read POST data */
  699. frankenphp_read_cookies, /* read Cookies */
  700. frankenphp_register_variables, /* register server variables */
  701. frankenphp_log_message, /* Log message */
  702. NULL, /* Get request time */
  703. NULL, /* Child terminate */
  704. STANDARD_SAPI_MODULE_PROPERTIES};
  705. /* Sets thread name for profiling and debugging.
  706. *
  707. * Adapted from https://github.com/Pithikos/C-Thread-Pool
  708. * Copyright: Johan Hanssen Seferidis
  709. * License: MIT
  710. */
  711. static void set_thread_name(char *thread_name) {
  712. #if defined(__linux__)
  713. /* Use prctl instead to prevent using _GNU_SOURCE flag and implicit
  714. * declaration */
  715. prctl(PR_SET_NAME, thread_name);
  716. #elif defined(__APPLE__) && defined(__MACH__)
  717. pthread_setname_np(thread_name);
  718. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  719. pthread_set_name_np(pthread_self(), thread_name);
  720. #endif
  721. }
  722. static void *php_thread(void *arg) {
  723. thread_index = (uintptr_t)arg;
  724. char thread_name[16] = {0};
  725. snprintf(thread_name, 16, "php-%" PRIxPTR, thread_index);
  726. set_thread_name(thread_name);
  727. #ifdef ZTS
  728. /* initial resource fetch */
  729. (void)ts_resource(0);
  730. #ifdef PHP_WIN32
  731. ZEND_TSRMLS_CACHE_UPDATE();
  732. #endif
  733. #endif
  734. local_ctx = malloc(sizeof(frankenphp_server_context));
  735. /* check if a default filter is set in php.ini and only filter if
  736. * it is, this is deprecated and will be removed in PHP 9 */
  737. char *default_filter;
  738. cfg_get_string("filter.default", &default_filter);
  739. should_filter_var = default_filter != NULL;
  740. // loop until Go signals to stop
  741. char *scriptName = NULL;
  742. while ((scriptName = go_frankenphp_before_script_execution(thread_index))) {
  743. go_frankenphp_after_script_execution(thread_index,
  744. frankenphp_execute_script(scriptName));
  745. }
  746. go_frankenphp_release_known_variable_keys(thread_index);
  747. #ifdef ZTS
  748. ts_free_thread();
  749. #endif
  750. go_frankenphp_on_thread_shutdown(thread_index);
  751. return NULL;
  752. }
  753. static void *php_main(void *arg) {
  754. /*
  755. * SIGPIPE must be masked in non-Go threads:
  756. * https://pkg.go.dev/os/signal#hdr-Go_programs_that_use_cgo_or_SWIG
  757. */
  758. sigset_t set;
  759. sigemptyset(&set);
  760. sigaddset(&set, SIGPIPE);
  761. if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) {
  762. perror("failed to block SIGPIPE");
  763. exit(EXIT_FAILURE);
  764. }
  765. set_thread_name("php-main");
  766. #ifdef ZTS
  767. #if (PHP_VERSION_ID >= 80300)
  768. php_tsrm_startup_ex((intptr_t)arg);
  769. #else
  770. php_tsrm_startup();
  771. #endif
  772. /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/
  773. #ifdef PHP_WIN32
  774. ZEND_TSRMLS_CACHE_UPDATE();
  775. #endif
  776. #endif
  777. sapi_startup(&frankenphp_sapi_module);
  778. #ifndef ZEND_MAX_EXECUTION_TIMERS
  779. #if (PHP_VERSION_ID >= 80300)
  780. frankenphp_sapi_module.ini_entries = HARDCODED_INI;
  781. #else
  782. frankenphp_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
  783. if (frankenphp_sapi_module.ini_entries == NULL) {
  784. perror("malloc failed");
  785. exit(EXIT_FAILURE);
  786. }
  787. memcpy(frankenphp_sapi_module.ini_entries, HARDCODED_INI,
  788. sizeof(HARDCODED_INI));
  789. #endif
  790. #endif
  791. frankenphp_sapi_module.startup(&frankenphp_sapi_module);
  792. go_frankenphp_main_thread_is_ready();
  793. /* channel closed, shutdown gracefully */
  794. frankenphp_sapi_module.shutdown(&frankenphp_sapi_module);
  795. sapi_shutdown();
  796. #ifdef ZTS
  797. tsrm_shutdown();
  798. #endif
  799. #if (PHP_VERSION_ID < 80300)
  800. if (frankenphp_sapi_module.ini_entries) {
  801. free(frankenphp_sapi_module.ini_entries);
  802. frankenphp_sapi_module.ini_entries = NULL;
  803. }
  804. #endif
  805. go_frankenphp_shutdown_main_thread();
  806. return NULL;
  807. }
  808. int frankenphp_new_main_thread(int num_threads) {
  809. pthread_t thread;
  810. if (pthread_create(&thread, NULL, &php_main, (void *)(intptr_t)num_threads) !=
  811. 0) {
  812. return -1;
  813. }
  814. return pthread_detach(thread);
  815. }
  816. bool frankenphp_new_php_thread(uintptr_t thread_index) {
  817. pthread_t thread;
  818. if (pthread_create(&thread, NULL, &php_thread, (void *)thread_index) != 0) {
  819. return false;
  820. }
  821. pthread_detach(thread);
  822. return true;
  823. }
  824. int frankenphp_request_startup() {
  825. if (php_request_startup() == SUCCESS) {
  826. return SUCCESS;
  827. }
  828. php_request_shutdown((void *)0);
  829. return FAILURE;
  830. }
  831. int frankenphp_execute_script(char *file_name) {
  832. if (frankenphp_request_startup() == FAILURE) {
  833. return FAILURE;
  834. }
  835. int status = SUCCESS;
  836. zend_file_handle file_handle;
  837. zend_stream_init_filename(&file_handle, file_name);
  838. file_handle.primary_script = 1;
  839. zend_first_try {
  840. EG(exit_status) = 0;
  841. php_execute_script(&file_handle);
  842. status = EG(exit_status);
  843. }
  844. zend_catch { status = EG(exit_status); }
  845. zend_end_try();
  846. // free the cached os environment before shutting down the script
  847. if (os_environment != NULL) {
  848. zval_ptr_dtor(os_environment);
  849. free(os_environment);
  850. os_environment = NULL;
  851. }
  852. zend_destroy_file_handle(&file_handle);
  853. frankenphp_free_request_context();
  854. frankenphp_request_shutdown();
  855. return status;
  856. }
  857. /* Use global variables to store CLI arguments to prevent useless allocations */
  858. static char *cli_script;
  859. static int cli_argc;
  860. static char **cli_argv;
  861. /*
  862. * CLI code is adapted from
  863. * https://github.com/php/php-src/blob/master/sapi/cli/php_cli.c Copyright (c)
  864. * The PHP Group Licensed under The PHP License Original uthors: Edin Kadribasic
  865. * <edink@php.net>, Marcus Boerger <helly@php.net> and Johannes Schlueter
  866. * <johannes@php.net> Parts based on CGI SAPI Module by Rasmus Lerdorf, Stig
  867. * Bakken and Zeev Suraski
  868. */
  869. static void cli_register_file_handles(bool no_close) /* {{{ */
  870. {
  871. php_stream *s_in, *s_out, *s_err;
  872. php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL;
  873. zend_constant ic, oc, ec;
  874. s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in);
  875. s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
  876. s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
  877. if (s_in == NULL || s_out == NULL || s_err == NULL) {
  878. if (s_in)
  879. php_stream_close(s_in);
  880. if (s_out)
  881. php_stream_close(s_out);
  882. if (s_err)
  883. php_stream_close(s_err);
  884. return;
  885. }
  886. if (no_close) {
  887. s_in->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  888. s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  889. s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
  890. }
  891. /*s_in_process = s_in;*/
  892. php_stream_to_zval(s_in, &ic.value);
  893. php_stream_to_zval(s_out, &oc.value);
  894. php_stream_to_zval(s_err, &ec.value);
  895. ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0);
  896. ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0);
  897. zend_register_constant(&ic);
  898. ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0);
  899. oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0);
  900. zend_register_constant(&oc);
  901. ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0);
  902. ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0);
  903. zend_register_constant(&ec);
  904. }
  905. /* }}} */
  906. static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */
  907. {
  908. size_t len;
  909. char *docroot = "";
  910. /*
  911. * In CGI mode, we consider the environment to be a part of the server
  912. * variables
  913. */
  914. php_import_environment_variables(track_vars_array);
  915. /* Build the special-case PHP_SELF variable for the CLI version */
  916. len = strlen(cli_script);
  917. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &cli_script, len,
  918. &len)) {
  919. php_register_variable_safe("PHP_SELF", cli_script, len, track_vars_array);
  920. }
  921. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &cli_script, len,
  922. &len)) {
  923. php_register_variable_safe("SCRIPT_NAME", cli_script, len,
  924. track_vars_array);
  925. }
  926. /* filenames are empty for stdin */
  927. if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &cli_script,
  928. len, &len)) {
  929. php_register_variable_safe("SCRIPT_FILENAME", cli_script, len,
  930. track_vars_array);
  931. }
  932. if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &cli_script,
  933. len, &len)) {
  934. php_register_variable_safe("PATH_TRANSLATED", cli_script, len,
  935. track_vars_array);
  936. }
  937. /* just make it available */
  938. len = 0U;
  939. if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len,
  940. &len)) {
  941. php_register_variable_safe("DOCUMENT_ROOT", docroot, len, track_vars_array);
  942. }
  943. }
  944. /* }}} */
  945. static void *execute_script_cli(void *arg) {
  946. void *exit_status;
  947. /*
  948. * The SAPI name "cli" is hardcoded into too many programs... let's usurp it.
  949. */
  950. php_embed_module.name = "cli";
  951. php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP";
  952. php_embed_module.register_server_variables = sapi_cli_register_variables;
  953. php_embed_init(cli_argc, cli_argv);
  954. cli_register_file_handles(false);
  955. zend_first_try {
  956. zend_file_handle file_handle;
  957. zend_stream_init_filename(&file_handle, cli_script);
  958. CG(skip_shebang) = 1;
  959. php_execute_script(&file_handle);
  960. }
  961. zend_end_try();
  962. exit_status = (void *)(intptr_t)EG(exit_status);
  963. php_embed_shutdown();
  964. return exit_status;
  965. }
  966. int frankenphp_execute_script_cli(char *script, int argc, char **argv) {
  967. pthread_t thread;
  968. int err;
  969. void *exit_status;
  970. cli_script = script;
  971. cli_argc = argc;
  972. cli_argv = argv;
  973. /*
  974. * Start the script in a dedicated thread to prevent conflicts between Go and
  975. * PHP signal handlers
  976. */
  977. err = pthread_create(&thread, NULL, execute_script_cli, NULL);
  978. if (err != 0) {
  979. return err;
  980. }
  981. err = pthread_join(thread, &exit_status);
  982. if (err != 0) {
  983. return err;
  984. }
  985. return (intptr_t)exit_status;
  986. }
  987. int frankenphp_execute_php_function(const char *php_function) {
  988. zval retval = {0};
  989. zend_fcall_info fci = {0};
  990. zend_fcall_info_cache fci_cache = {0};
  991. zend_string *func_name =
  992. zend_string_init(php_function, strlen(php_function), 0);
  993. ZVAL_STR(&fci.function_name, func_name);
  994. fci.size = sizeof fci;
  995. fci.retval = &retval;
  996. int success = 0;
  997. zend_try { success = zend_call_function(&fci, &fci_cache) == SUCCESS; }
  998. zend_end_try();
  999. zend_string_release(func_name);
  1000. return success;
  1001. }
  1002. int frankenphp_reset_opcache(void) {
  1003. if (zend_hash_str_exists(CG(function_table), "opcache_reset",
  1004. sizeof("opcache_reset") - 1)) {
  1005. return frankenphp_execute_php_function("opcache_reset");
  1006. }
  1007. return 0;
  1008. }