frankenphp.c 36 KB

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