frankenphp.c 37 KB

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