Request.php 25 KB

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