frankenphp.c 36 KB

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