Request.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author b108@volgograd "b108@volgograd"
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author Georg Ehrke <oc.list@georgehrke.com>
  12. * @author J0WI <J0WI@users.noreply.github.com>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  15. * @author Julius Härtl <jus@bitgrid.net>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Mitar <mitar.git@tnode.com>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Oliver Wegner <void1976@gmail.com>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Robin McCorkell <robin@mccorkell.me.uk>
  22. * @author Roeland Jago Douma <roeland@famdouma.nl>
  23. * @author Thomas Müller <thomas.mueller@tmit.eu>
  24. * @author Thomas Tanghus <thomas@tanghus.net>
  25. * @author Vincent Petry <vincent@nextcloud.com>
  26. * @author Simon Leiner <simon@leiner.me>
  27. * @author Stanimir Bozhilov <stanimir@audriga.com>
  28. *
  29. * @license AGPL-3.0
  30. *
  31. * This code is free software: you can redistribute it and/or modify
  32. * it under the terms of the GNU Affero General Public License, version 3,
  33. * as published by the Free Software Foundation.
  34. *
  35. * This program is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. * GNU Affero General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU Affero General Public License, version 3,
  41. * along with this program. If not, see <http://www.gnu.org/licenses/>
  42. *
  43. */
  44. namespace OC\AppFramework\Http;
  45. use OC\Security\CSRF\CsrfToken;
  46. use OC\Security\CSRF\CsrfTokenManager;
  47. use OC\Security\TrustedDomainHelper;
  48. use OCP\IConfig;
  49. use OCP\IRequest;
  50. use OCP\IRequestId;
  51. use Symfony\Component\HttpFoundation\IpUtils;
  52. /**
  53. * Class for accessing variables in the request.
  54. * This class provides an immutable object with request variables.
  55. *
  56. * @property mixed[] cookies
  57. * @property mixed[] env
  58. * @property mixed[] files
  59. * @property string method
  60. * @property mixed[] parameters
  61. * @property mixed[] server
  62. */
  63. class Request implements \ArrayAccess, \Countable, IRequest {
  64. public const USER_AGENT_IE = '/(MSIE)|(Trident)/';
  65. // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
  66. public const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/';
  67. // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
  68. public const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
  69. // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
  70. public const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+( (Vivaldi|Brave|OPR)\/[0-9.]+|)$/';
  71. // Safari User Agent from http://www.useragentstring.com/pages/Safari/
  72. public const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
  73. // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
  74. public const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
  75. public const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
  76. public const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|\[::1\])$/';
  77. protected string $inputStream;
  78. protected $content;
  79. protected array $items = [];
  80. protected array $allowedKeys = [
  81. 'get',
  82. 'post',
  83. 'files',
  84. 'server',
  85. 'env',
  86. 'cookies',
  87. 'urlParams',
  88. 'parameters',
  89. 'method',
  90. 'requesttoken',
  91. ];
  92. protected IRequestId $requestId;
  93. protected IConfig $config;
  94. protected ?CsrfTokenManager $csrfTokenManager;
  95. protected bool $contentDecoded = false;
  96. /**
  97. * @param array $vars An associative array with the following optional values:
  98. * - array 'urlParams' the parameters which were matched from the URL
  99. * - array 'get' the $_GET array
  100. * - array|string 'post' the $_POST array or JSON string
  101. * - array 'files' the $_FILES array
  102. * - array 'server' the $_SERVER array
  103. * - array 'env' the $_ENV array
  104. * - array 'cookies' the $_COOKIE array
  105. * - string 'method' the request method (GET, POST etc)
  106. * - string|false 'requesttoken' the requesttoken or false when not available
  107. * @param IRequestId $requestId
  108. * @param IConfig $config
  109. * @param CsrfTokenManager|null $csrfTokenManager
  110. * @param string $stream
  111. * @see https://www.php.net/manual/en/reserved.variables.php
  112. */
  113. public function __construct(array $vars,
  114. IRequestId $requestId,
  115. IConfig $config,
  116. CsrfTokenManager $csrfTokenManager = null,
  117. string $stream = 'php://input') {
  118. $this->inputStream = $stream;
  119. $this->items['params'] = [];
  120. $this->requestId = $requestId;
  121. $this->config = $config;
  122. $this->csrfTokenManager = $csrfTokenManager;
  123. if (!array_key_exists('method', $vars)) {
  124. $vars['method'] = 'GET';
  125. }
  126. foreach ($this->allowedKeys as $name) {
  127. $this->items[$name] = $vars[$name] ?? [];
  128. }
  129. $this->items['parameters'] = array_merge(
  130. $this->items['get'],
  131. $this->items['post'],
  132. $this->items['urlParams'],
  133. $this->items['params']
  134. );
  135. }
  136. /**
  137. * @param array $parameters
  138. */
  139. public function setUrlParameters(array $parameters) {
  140. $this->items['urlParams'] = $parameters;
  141. $this->items['parameters'] = array_merge(
  142. $this->items['parameters'],
  143. $this->items['urlParams']
  144. );
  145. }
  146. /**
  147. * Countable method
  148. * @return int
  149. */
  150. public function count(): int {
  151. return \count($this->items['parameters']);
  152. }
  153. /**
  154. * ArrayAccess methods
  155. *
  156. * Gives access to the combined GET, POST and urlParams arrays
  157. *
  158. * Examples:
  159. *
  160. * $var = $request['myvar'];
  161. *
  162. * or
  163. *
  164. * if(!isset($request['myvar']) {
  165. * // Do something
  166. * }
  167. *
  168. * $request['myvar'] = 'something'; // This throws an exception.
  169. *
  170. * @param string $offset The key to lookup
  171. * @return boolean
  172. */
  173. public function offsetExists($offset): bool {
  174. return isset($this->items['parameters'][$offset]);
  175. }
  176. /**
  177. * @see offsetExists
  178. * @param string $offset
  179. * @return mixed
  180. */
  181. #[\ReturnTypeWillChange]
  182. public function offsetGet($offset) {
  183. return isset($this->items['parameters'][$offset])
  184. ? $this->items['parameters'][$offset]
  185. : null;
  186. }
  187. /**
  188. * @see offsetExists
  189. * @param string $offset
  190. * @param mixed $value
  191. */
  192. public function offsetSet($offset, $value): void {
  193. throw new \RuntimeException('You cannot change the contents of the request object');
  194. }
  195. /**
  196. * @see offsetExists
  197. * @param string $offset
  198. */
  199. public function offsetUnset($offset): void {
  200. throw new \RuntimeException('You cannot change the contents of the request object');
  201. }
  202. /**
  203. * Magic property accessors
  204. * @param string $name
  205. * @param mixed $value
  206. */
  207. public function __set($name, $value) {
  208. throw new \RuntimeException('You cannot change the contents of the request object');
  209. }
  210. /**
  211. * Access request variables by method and name.
  212. * Examples:
  213. *
  214. * $request->post['myvar']; // Only look for POST variables
  215. * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
  216. * Looks in the combined GET, POST and urlParams array.
  217. *
  218. * If you access e.g. ->post but the current HTTP request method
  219. * is GET a \LogicException will be thrown.
  220. *
  221. * @param string $name The key to look for.
  222. * @throws \LogicException
  223. * @return mixed|null
  224. */
  225. public function __get($name) {
  226. switch ($name) {
  227. case 'put':
  228. case 'patch':
  229. case 'get':
  230. case 'post':
  231. if ($this->method !== strtoupper($name)) {
  232. throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
  233. }
  234. return $this->getContent();
  235. case 'files':
  236. case 'server':
  237. case 'env':
  238. case 'cookies':
  239. case 'urlParams':
  240. case 'method':
  241. return isset($this->items[$name])
  242. ? $this->items[$name]
  243. : null;
  244. case 'parameters':
  245. case 'params':
  246. if ($this->isPutStreamContent()) {
  247. return $this->items['parameters'];
  248. }
  249. return $this->getContent();
  250. default:
  251. return isset($this[$name])
  252. ? $this[$name]
  253. : null;
  254. }
  255. }
  256. /**
  257. * @param string $name
  258. * @return bool
  259. */
  260. public function __isset($name) {
  261. if (\in_array($name, $this->allowedKeys, true)) {
  262. return true;
  263. }
  264. return isset($this->items['parameters'][$name]);
  265. }
  266. /**
  267. * @param string $id
  268. */
  269. public function __unset($id) {
  270. throw new \RuntimeException('You cannot change the contents of the request object');
  271. }
  272. /**
  273. * Returns the value for a specific http header.
  274. *
  275. * This method returns an empty string if the header did not exist.
  276. *
  277. * @param string $name
  278. * @return string
  279. */
  280. public function getHeader(string $name): string {
  281. $name = strtoupper(str_replace('-', '_', $name));
  282. if (isset($this->server['HTTP_' . $name])) {
  283. return $this->server['HTTP_' . $name];
  284. }
  285. // There's a few headers that seem to end up in the top-level
  286. // server array.
  287. switch ($name) {
  288. case 'CONTENT_TYPE':
  289. case 'CONTENT_LENGTH':
  290. case 'REMOTE_ADDR':
  291. if (isset($this->server[$name])) {
  292. return $this->server[$name];
  293. }
  294. break;
  295. }
  296. return '';
  297. }
  298. /**
  299. * Lets you access post and get parameters by the index
  300. * In case of json requests the encoded json body is accessed
  301. *
  302. * @param string $key the key which you want to access in the URL Parameter
  303. * placeholder, $_POST or $_GET array.
  304. * The priority how they're returned is the following:
  305. * 1. URL parameters
  306. * 2. POST parameters
  307. * 3. GET parameters
  308. * @param mixed $default If the key is not found, this value will be returned
  309. * @return mixed the content of the array
  310. */
  311. public function getParam(string $key, $default = null) {
  312. return isset($this->parameters[$key])
  313. ? $this->parameters[$key]
  314. : $default;
  315. }
  316. /**
  317. * Returns all params that were received, be it from the request
  318. * (as GET or POST) or through the URL by the route
  319. * @return array the array with all parameters
  320. */
  321. public function getParams(): array {
  322. return is_array($this->parameters) ? $this->parameters : [];
  323. }
  324. /**
  325. * Returns the method of the request
  326. * @return string the method of the request (POST, GET, etc)
  327. */
  328. public function getMethod(): string {
  329. return $this->method;
  330. }
  331. /**
  332. * Shortcut for accessing an uploaded file through the $_FILES array
  333. * @param string $key the key that will be taken from the $_FILES array
  334. * @return array the file in the $_FILES element
  335. */
  336. public function getUploadedFile(string $key) {
  337. return isset($this->files[$key]) ? $this->files[$key] : null;
  338. }
  339. /**
  340. * Shortcut for getting env variables
  341. * @param string $key the key that will be taken from the $_ENV array
  342. * @return array the value in the $_ENV element
  343. */
  344. public function getEnv(string $key) {
  345. return isset($this->env[$key]) ? $this->env[$key] : null;
  346. }
  347. /**
  348. * Shortcut for getting cookie variables
  349. * @param string $key the key that will be taken from the $_COOKIE array
  350. * @return string the value in the $_COOKIE element
  351. */
  352. public function getCookie(string $key) {
  353. return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
  354. }
  355. /**
  356. * Returns the request body content.
  357. *
  358. * If the HTTP request method is PUT and the body
  359. * not application/x-www-form-urlencoded or application/json a stream
  360. * resource is returned, otherwise an array.
  361. *
  362. * @return array|string|resource The request body content or a resource to read the body stream.
  363. *
  364. * @throws \LogicException
  365. */
  366. protected function getContent() {
  367. // If the content can't be parsed into an array then return a stream resource.
  368. if ($this->isPutStreamContent()) {
  369. if ($this->content === false) {
  370. throw new \LogicException(
  371. '"put" can only be accessed once if not '
  372. . 'application/x-www-form-urlencoded or application/json.'
  373. );
  374. }
  375. $this->content = false;
  376. return fopen($this->inputStream, 'rb');
  377. } else {
  378. $this->decodeContent();
  379. return $this->items['parameters'];
  380. }
  381. }
  382. private function isPutStreamContent(): bool {
  383. return $this->method === 'PUT'
  384. && $this->getHeader('Content-Length') !== '0'
  385. && $this->getHeader('Content-Length') !== ''
  386. && !str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')
  387. && !str_contains($this->getHeader('Content-Type'), 'application/json');
  388. }
  389. /**
  390. * Attempt to decode the content and populate parameters
  391. */
  392. protected function decodeContent() {
  393. if ($this->contentDecoded) {
  394. return;
  395. }
  396. $params = [];
  397. // 'application/json' and other JSON-related content types must be decoded manually.
  398. if (preg_match(self::JSON_CONTENT_TYPE_REGEX, $this->getHeader('Content-Type')) === 1) {
  399. $params = json_decode(file_get_contents($this->inputStream), true);
  400. if (\is_array($params) && \count($params) > 0) {
  401. $this->items['params'] = $params;
  402. if ($this->method === 'POST') {
  403. $this->items['post'] = $params;
  404. }
  405. }
  406. // Handle application/x-www-form-urlencoded for methods other than GET
  407. // or post correctly
  408. } elseif ($this->method !== 'GET'
  409. && $this->method !== 'POST'
  410. && str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')) {
  411. parse_str(file_get_contents($this->inputStream), $params);
  412. if (\is_array($params)) {
  413. $this->items['params'] = $params;
  414. }
  415. }
  416. if (\is_array($params)) {
  417. $this->items['parameters'] = array_merge($this->items['parameters'], $params);
  418. }
  419. $this->contentDecoded = true;
  420. }
  421. /**
  422. * Checks if the CSRF check was correct
  423. * @return bool true if CSRF check passed
  424. */
  425. public function passesCSRFCheck(): bool {
  426. if ($this->csrfTokenManager === null) {
  427. return false;
  428. }
  429. if (!$this->passesStrictCookieCheck()) {
  430. return false;
  431. }
  432. if (isset($this->items['get']['requesttoken'])) {
  433. $token = $this->items['get']['requesttoken'];
  434. } elseif (isset($this->items['post']['requesttoken'])) {
  435. $token = $this->items['post']['requesttoken'];
  436. } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
  437. $token = $this->items['server']['HTTP_REQUESTTOKEN'];
  438. } else {
  439. //no token found.
  440. return false;
  441. }
  442. $token = new CsrfToken($token);
  443. return $this->csrfTokenManager->isTokenValid($token);
  444. }
  445. /**
  446. * Whether the cookie checks are required
  447. *
  448. * @return bool
  449. */
  450. private function cookieCheckRequired(): bool {
  451. if ($this->getHeader('OCS-APIREQUEST')) {
  452. return false;
  453. }
  454. if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
  455. return false;
  456. }
  457. return true;
  458. }
  459. /**
  460. * Wrapper around session_get_cookie_params
  461. *
  462. * @return array
  463. */
  464. public function getCookieParams(): array {
  465. return session_get_cookie_params();
  466. }
  467. /**
  468. * Appends the __Host- prefix to the cookie if applicable
  469. *
  470. * @param string $name
  471. * @return string
  472. */
  473. protected function getProtectedCookieName(string $name): string {
  474. $cookieParams = $this->getCookieParams();
  475. $prefix = '';
  476. if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
  477. $prefix = '__Host-';
  478. }
  479. return $prefix.$name;
  480. }
  481. /**
  482. * Checks if the strict cookie has been sent with the request if the request
  483. * is including any cookies.
  484. *
  485. * @return bool
  486. * @since 9.1.0
  487. */
  488. public function passesStrictCookieCheck(): bool {
  489. if (!$this->cookieCheckRequired()) {
  490. return true;
  491. }
  492. $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
  493. if ($this->getCookie($cookieName) === 'true'
  494. && $this->passesLaxCookieCheck()) {
  495. return true;
  496. }
  497. return false;
  498. }
  499. /**
  500. * Checks if the lax cookie has been sent with the request if the request
  501. * is including any cookies.
  502. *
  503. * @return bool
  504. * @since 9.1.0
  505. */
  506. public function passesLaxCookieCheck(): bool {
  507. if (!$this->cookieCheckRequired()) {
  508. return true;
  509. }
  510. $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
  511. if ($this->getCookie($cookieName) === 'true') {
  512. return true;
  513. }
  514. return false;
  515. }
  516. /**
  517. * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
  518. * If `mod_unique_id` is installed this value will be taken.
  519. * @return string
  520. */
  521. public function getId(): string {
  522. return $this->requestId->getId();
  523. }
  524. /**
  525. * Checks if given $remoteAddress matches any entry in the given array $trustedProxies.
  526. * For details regarding what "match" means, refer to `matchesTrustedProxy`.
  527. * @return boolean true if $remoteAddress matches any entry in $trustedProxies, false otherwise
  528. */
  529. protected function isTrustedProxy($trustedProxies, $remoteAddress) {
  530. return IpUtils::checkIp($remoteAddress, $trustedProxies);
  531. }
  532. /**
  533. * Returns the remote address, if the connection came from a trusted proxy
  534. * and `forwarded_for_headers` has been configured then the IP address
  535. * specified in this header will be returned instead.
  536. * Do always use this instead of $_SERVER['REMOTE_ADDR']
  537. * @return string IP address
  538. */
  539. public function getRemoteAddress(): string {
  540. $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  541. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  542. if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
  543. $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
  544. 'HTTP_X_FORWARDED_FOR'
  545. // only have one default, so we cannot ship an insecure product out of the box
  546. ]);
  547. foreach ($forwardedForHeaders as $header) {
  548. if (isset($this->server[$header])) {
  549. foreach (explode(',', $this->server[$header]) as $IP) {
  550. $IP = trim($IP);
  551. // remove brackets from IPv6 addresses
  552. if (str_starts_with($IP, '[') && str_ends_with($IP, ']')) {
  553. $IP = substr($IP, 1, -1);
  554. }
  555. if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
  556. return $IP;
  557. }
  558. }
  559. }
  560. }
  561. }
  562. return $remoteAddress;
  563. }
  564. /**
  565. * Check overwrite condition
  566. * @param string $type
  567. * @return bool
  568. */
  569. private function isOverwriteCondition(string $type = ''): bool {
  570. $regex = '/' . $this->config->getSystemValueString('overwritecondaddr', '') . '/';
  571. $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  572. return $regex === '//' || preg_match($regex, $remoteAddr) === 1
  573. || $type !== 'protocol';
  574. }
  575. /**
  576. * Returns the server protocol. It respects one or more reverse proxies servers
  577. * and load balancers
  578. * @return string Server protocol (http or https)
  579. */
  580. public function getServerProtocol(): string {
  581. if ($this->config->getSystemValueString('overwriteprotocol') !== ''
  582. && $this->isOverwriteCondition('protocol')) {
  583. return $this->config->getSystemValueString('overwriteprotocol');
  584. }
  585. if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
  586. if (str_contains($this->server['HTTP_X_FORWARDED_PROTO'], ',')) {
  587. $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
  588. $proto = strtolower(trim($parts[0]));
  589. } else {
  590. $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
  591. }
  592. // Verify that the protocol is always HTTP or HTTPS
  593. // default to http if an invalid value is provided
  594. return $proto === 'https' ? 'https' : 'http';
  595. }
  596. if (isset($this->server['HTTPS'])
  597. && $this->server['HTTPS'] !== null
  598. && $this->server['HTTPS'] !== 'off'
  599. && $this->server['HTTPS'] !== '') {
  600. return 'https';
  601. }
  602. return 'http';
  603. }
  604. /**
  605. * Returns the used HTTP protocol.
  606. *
  607. * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
  608. */
  609. public function getHttpProtocol(): string {
  610. $claimedProtocol = $this->server['SERVER_PROTOCOL'];
  611. if (\is_string($claimedProtocol)) {
  612. $claimedProtocol = strtoupper($claimedProtocol);
  613. }
  614. $validProtocols = [
  615. 'HTTP/1.0',
  616. 'HTTP/1.1',
  617. 'HTTP/2',
  618. ];
  619. if (\in_array($claimedProtocol, $validProtocols, true)) {
  620. return $claimedProtocol;
  621. }
  622. return 'HTTP/1.1';
  623. }
  624. /**
  625. * Returns the request uri, even if the website uses one or more
  626. * reverse proxies
  627. * @return string
  628. */
  629. public function getRequestUri(): string {
  630. $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  631. if ($this->config->getSystemValueString('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
  632. $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
  633. }
  634. return $uri;
  635. }
  636. /**
  637. * Get raw PathInfo from request (not urldecoded)
  638. * @throws \Exception
  639. * @return string Path info
  640. */
  641. public function getRawPathInfo(): string {
  642. $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  643. // remove too many slashes - can be caused by reverse proxy configuration
  644. $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
  645. // Remove the query string from REQUEST_URI
  646. if ($pos = strpos($requestUri, '?')) {
  647. $requestUri = substr($requestUri, 0, $pos);
  648. }
  649. $scriptName = $this->server['SCRIPT_NAME'];
  650. $pathInfo = $requestUri;
  651. // strip off the script name's dir and file name
  652. // FIXME: Sabre does not really belong here
  653. [$path, $name] = \Sabre\Uri\split($scriptName);
  654. if (!empty($path)) {
  655. if ($path === $pathInfo || str_starts_with($pathInfo, $path . '/')) {
  656. $pathInfo = substr($pathInfo, \strlen($path));
  657. } else {
  658. throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
  659. }
  660. }
  661. if ($name === null) {
  662. $name = '';
  663. }
  664. if (str_starts_with($pathInfo, '/' . $name)) {
  665. $pathInfo = substr($pathInfo, \strlen($name) + 1);
  666. }
  667. if ($name !== '' && str_starts_with($pathInfo, $name)) {
  668. $pathInfo = substr($pathInfo, \strlen($name));
  669. }
  670. if ($pathInfo === false || $pathInfo === '/') {
  671. return '';
  672. } else {
  673. return $pathInfo;
  674. }
  675. }
  676. /**
  677. * Get PathInfo from request
  678. * @throws \Exception
  679. * @return string|false Path info or false when not found
  680. */
  681. public function getPathInfo() {
  682. $pathInfo = $this->getRawPathInfo();
  683. return \Sabre\HTTP\decodePath($pathInfo);
  684. }
  685. /**
  686. * Returns the script name, even if the website uses one or more
  687. * reverse proxies
  688. * @return string the script name
  689. */
  690. public function getScriptName(): string {
  691. $name = $this->server['SCRIPT_NAME'];
  692. $overwriteWebRoot = $this->config->getSystemValueString('overwritewebroot');
  693. if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
  694. // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
  695. $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
  696. $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
  697. $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
  698. }
  699. return $name;
  700. }
  701. /**
  702. * Checks whether the user agent matches a given regex
  703. * @param array $agent array of agent names
  704. * @return bool true if at least one of the given agent matches, false otherwise
  705. */
  706. public function isUserAgent(array $agent): bool {
  707. if (!isset($this->server['HTTP_USER_AGENT'])) {
  708. return false;
  709. }
  710. foreach ($agent as $regex) {
  711. if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
  712. return true;
  713. }
  714. }
  715. return false;
  716. }
  717. /**
  718. * Returns the unverified server host from the headers without checking
  719. * whether it is a trusted domain
  720. * @return string Server host
  721. */
  722. public function getInsecureServerHost(): string {
  723. if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
  724. return $this->getOverwriteHost();
  725. }
  726. $host = 'localhost';
  727. if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
  728. if (str_contains($this->server['HTTP_X_FORWARDED_HOST'], ',')) {
  729. $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
  730. $host = trim(current($parts));
  731. } else {
  732. $host = $this->server['HTTP_X_FORWARDED_HOST'];
  733. }
  734. } else {
  735. if (isset($this->server['HTTP_HOST'])) {
  736. $host = $this->server['HTTP_HOST'];
  737. } elseif (isset($this->server['SERVER_NAME'])) {
  738. $host = $this->server['SERVER_NAME'];
  739. }
  740. }
  741. return $host;
  742. }
  743. /**
  744. * Returns the server host from the headers, or the first configured
  745. * trusted domain if the host isn't in the trusted list
  746. * @return string Server host
  747. */
  748. public function getServerHost(): string {
  749. // overwritehost is always trusted
  750. $host = $this->getOverwriteHost();
  751. if ($host !== null) {
  752. return $host;
  753. }
  754. // get the host from the headers
  755. $host = $this->getInsecureServerHost();
  756. // Verify that the host is a trusted domain if the trusted domains
  757. // are defined
  758. // If no trusted domain is provided the first trusted domain is returned
  759. $trustedDomainHelper = new TrustedDomainHelper($this->config);
  760. if ($trustedDomainHelper->isTrustedDomain($host)) {
  761. return $host;
  762. }
  763. $trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
  764. if (count($trustedList) > 0) {
  765. return reset($trustedList);
  766. }
  767. return '';
  768. }
  769. /**
  770. * Returns the overwritehost setting from the config if set and
  771. * if the overwrite condition is met
  772. * @return string|null overwritehost value or null if not defined or the defined condition
  773. * isn't met
  774. */
  775. private function getOverwriteHost() {
  776. if ($this->config->getSystemValueString('overwritehost') !== '' && $this->isOverwriteCondition()) {
  777. return $this->config->getSystemValueString('overwritehost');
  778. }
  779. return null;
  780. }
  781. private function fromTrustedProxy(): bool {
  782. $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  783. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  784. return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
  785. }
  786. }