frankenphp.c 35 KB

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