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