Request.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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 ($this->getHeader('OCS-APIRequest') !== '') {
  394. return true;
  395. }
  396. if (isset($this->items['get']['requesttoken'])) {
  397. $token = $this->items['get']['requesttoken'];
  398. } elseif (isset($this->items['post']['requesttoken'])) {
  399. $token = $this->items['post']['requesttoken'];
  400. } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
  401. $token = $this->items['server']['HTTP_REQUESTTOKEN'];
  402. } else {
  403. //no token found.
  404. return false;
  405. }
  406. $token = new CsrfToken($token);
  407. return $this->csrfTokenManager->isTokenValid($token);
  408. }
  409. /**
  410. * Whether the cookie checks are required
  411. *
  412. * @return bool
  413. */
  414. private function cookieCheckRequired(): bool {
  415. if ($this->getHeader('OCS-APIREQUEST')) {
  416. return false;
  417. }
  418. if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
  419. return false;
  420. }
  421. return true;
  422. }
  423. /**
  424. * Wrapper around session_get_cookie_params
  425. *
  426. * @return array
  427. */
  428. public function getCookieParams(): array {
  429. return session_get_cookie_params();
  430. }
  431. /**
  432. * Appends the __Host- prefix to the cookie if applicable
  433. *
  434. * @param string $name
  435. * @return string
  436. */
  437. protected function getProtectedCookieName(string $name): string {
  438. $cookieParams = $this->getCookieParams();
  439. $prefix = '';
  440. if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
  441. $prefix = '__Host-';
  442. }
  443. return $prefix.$name;
  444. }
  445. /**
  446. * Checks if the strict cookie has been sent with the request if the request
  447. * is including any cookies.
  448. *
  449. * @return bool
  450. * @since 9.1.0
  451. */
  452. public function passesStrictCookieCheck(): bool {
  453. if (!$this->cookieCheckRequired()) {
  454. return true;
  455. }
  456. $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
  457. if ($this->getCookie($cookieName) === 'true'
  458. && $this->passesLaxCookieCheck()) {
  459. return true;
  460. }
  461. return false;
  462. }
  463. /**
  464. * Checks if the lax cookie has been sent with the request if the request
  465. * is including any cookies.
  466. *
  467. * @return bool
  468. * @since 9.1.0
  469. */
  470. public function passesLaxCookieCheck(): bool {
  471. if (!$this->cookieCheckRequired()) {
  472. return true;
  473. }
  474. $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
  475. if ($this->getCookie($cookieName) === 'true') {
  476. return true;
  477. }
  478. return false;
  479. }
  480. /**
  481. * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
  482. * If `mod_unique_id` is installed this value will be taken.
  483. * @return string
  484. */
  485. public function getId(): string {
  486. return $this->requestId->getId();
  487. }
  488. /**
  489. * Checks if given $remoteAddress matches any entry in the given array $trustedProxies.
  490. * For details regarding what "match" means, refer to `matchesTrustedProxy`.
  491. * @return boolean true if $remoteAddress matches any entry in $trustedProxies, false otherwise
  492. */
  493. protected function isTrustedProxy($trustedProxies, $remoteAddress) {
  494. try {
  495. return IpUtils::checkIp($remoteAddress, $trustedProxies);
  496. } catch (\Throwable) {
  497. // 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
  498. // Reaching this line means `trustedProxies` is in invalid format.
  499. error_log('Nextcloud trustedProxies has malformed entries');
  500. return false;
  501. }
  502. }
  503. /**
  504. * Returns the remote address, if the connection came from a trusted proxy
  505. * and `forwarded_for_headers` has been configured then the IP address
  506. * specified in this header will be returned instead.
  507. * Do always use this instead of $_SERVER['REMOTE_ADDR']
  508. * @return string IP address
  509. */
  510. public function getRemoteAddress(): string {
  511. $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  512. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  513. if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
  514. $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
  515. 'HTTP_X_FORWARDED_FOR'
  516. // only have one default, so we cannot ship an insecure product out of the box
  517. ]);
  518. // Read the x-forwarded-for headers and values in reverse order as per
  519. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For#selecting_an_ip_address
  520. foreach (array_reverse($forwardedForHeaders) as $header) {
  521. if (isset($this->server[$header])) {
  522. foreach (array_reverse(explode(',', $this->server[$header])) as $IP) {
  523. $IP = trim($IP);
  524. $colons = substr_count($IP, ':');
  525. if ($colons > 1) {
  526. // Extract IP from string with brackets and optional port
  527. if (preg_match('/^\[(.+?)\](?::\d+)?$/', $IP, $matches) && isset($matches[1])) {
  528. $IP = $matches[1];
  529. }
  530. } elseif ($colons === 1) {
  531. // IPv4 with port
  532. $IP = substr($IP, 0, strpos($IP, ':'));
  533. }
  534. if ($this->isTrustedProxy($trustedProxies, $IP)) {
  535. continue;
  536. }
  537. if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
  538. return $IP;
  539. }
  540. }
  541. }
  542. }
  543. }
  544. return $remoteAddress;
  545. }
  546. /**
  547. * Check overwrite condition
  548. * @return bool
  549. */
  550. private function isOverwriteCondition(): bool {
  551. $regex = '/' . $this->config->getSystemValueString('overwritecondaddr', '') . '/';
  552. $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  553. return $regex === '//' || preg_match($regex, $remoteAddr) === 1;
  554. }
  555. /**
  556. * Returns the server protocol. It respects one or more reverse proxies servers
  557. * and load balancers
  558. * @return string Server protocol (http or https)
  559. */
  560. public function getServerProtocol(): string {
  561. if ($this->config->getSystemValueString('overwriteprotocol') !== ''
  562. && $this->isOverwriteCondition()) {
  563. return $this->config->getSystemValueString('overwriteprotocol');
  564. }
  565. if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
  566. if (str_contains($this->server['HTTP_X_FORWARDED_PROTO'], ',')) {
  567. $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
  568. $proto = strtolower(trim($parts[0]));
  569. } else {
  570. $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
  571. }
  572. // Verify that the protocol is always HTTP or HTTPS
  573. // default to http if an invalid value is provided
  574. return $proto === 'https' ? 'https' : 'http';
  575. }
  576. if (isset($this->server['HTTPS'])
  577. && $this->server['HTTPS'] !== null
  578. && $this->server['HTTPS'] !== 'off'
  579. && $this->server['HTTPS'] !== '') {
  580. return 'https';
  581. }
  582. return 'http';
  583. }
  584. /**
  585. * Returns the used HTTP protocol.
  586. *
  587. * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
  588. */
  589. public function getHttpProtocol(): string {
  590. $claimedProtocol = $this->server['SERVER_PROTOCOL'];
  591. if (\is_string($claimedProtocol)) {
  592. $claimedProtocol = strtoupper($claimedProtocol);
  593. }
  594. $validProtocols = [
  595. 'HTTP/1.0',
  596. 'HTTP/1.1',
  597. 'HTTP/2',
  598. ];
  599. if (\in_array($claimedProtocol, $validProtocols, true)) {
  600. return $claimedProtocol;
  601. }
  602. return 'HTTP/1.1';
  603. }
  604. /**
  605. * Returns the request uri, even if the website uses one or more
  606. * reverse proxies
  607. * @return string
  608. */
  609. public function getRequestUri(): string {
  610. $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  611. if ($this->config->getSystemValueString('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
  612. $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
  613. }
  614. return $uri;
  615. }
  616. /**
  617. * Get raw PathInfo from request (not urldecoded)
  618. * @throws \Exception
  619. * @return string Path info
  620. */
  621. public function getRawPathInfo(): string {
  622. $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  623. // remove too many slashes - can be caused by reverse proxy configuration
  624. $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
  625. // Remove the query string from REQUEST_URI
  626. if ($pos = strpos($requestUri, '?')) {
  627. $requestUri = substr($requestUri, 0, $pos);
  628. }
  629. $scriptName = $this->server['SCRIPT_NAME'];
  630. $pathInfo = $requestUri;
  631. // strip off the script name's dir and file name
  632. // FIXME: Sabre does not really belong here
  633. [$path, $name] = \Sabre\Uri\split($scriptName);
  634. if (!empty($path)) {
  635. if ($path === $pathInfo || str_starts_with($pathInfo, $path . '/')) {
  636. $pathInfo = substr($pathInfo, \strlen($path));
  637. } else {
  638. throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
  639. }
  640. }
  641. if ($name === null) {
  642. $name = '';
  643. }
  644. if (str_starts_with($pathInfo, '/' . $name)) {
  645. $pathInfo = substr($pathInfo, \strlen($name) + 1);
  646. }
  647. if ($name !== '' && str_starts_with($pathInfo, $name)) {
  648. $pathInfo = substr($pathInfo, \strlen($name));
  649. }
  650. if ($pathInfo === false || $pathInfo === '/') {
  651. return '';
  652. } else {
  653. return $pathInfo;
  654. }
  655. }
  656. /**
  657. * Get PathInfo from request
  658. * @throws \Exception
  659. * @return string|false Path info or false when not found
  660. */
  661. public function getPathInfo() {
  662. $pathInfo = $this->getRawPathInfo();
  663. return \Sabre\HTTP\decodePath($pathInfo);
  664. }
  665. /**
  666. * Returns the script name, even if the website uses one or more
  667. * reverse proxies
  668. * @return string the script name
  669. */
  670. public function getScriptName(): string {
  671. $name = $this->server['SCRIPT_NAME'];
  672. $overwriteWebRoot = $this->config->getSystemValueString('overwritewebroot');
  673. if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
  674. // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
  675. $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
  676. $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
  677. $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
  678. }
  679. return $name;
  680. }
  681. /**
  682. * Checks whether the user agent matches a given regex
  683. * @param array $agent array of agent names
  684. * @return bool true if at least one of the given agent matches, false otherwise
  685. */
  686. public function isUserAgent(array $agent): bool {
  687. if (!isset($this->server['HTTP_USER_AGENT'])) {
  688. return false;
  689. }
  690. foreach ($agent as $regex) {
  691. if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
  692. return true;
  693. }
  694. }
  695. return false;
  696. }
  697. /**
  698. * Returns the unverified server host from the headers without checking
  699. * whether it is a trusted domain
  700. * @return string Server host
  701. */
  702. public function getInsecureServerHost(): string {
  703. if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
  704. return $this->getOverwriteHost();
  705. }
  706. $host = 'localhost';
  707. if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
  708. if (str_contains($this->server['HTTP_X_FORWARDED_HOST'], ',')) {
  709. $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
  710. $host = trim(current($parts));
  711. } else {
  712. $host = $this->server['HTTP_X_FORWARDED_HOST'];
  713. }
  714. } else {
  715. if (isset($this->server['HTTP_HOST'])) {
  716. $host = $this->server['HTTP_HOST'];
  717. } elseif (isset($this->server['SERVER_NAME'])) {
  718. $host = $this->server['SERVER_NAME'];
  719. }
  720. }
  721. return $host;
  722. }
  723. /**
  724. * Returns the server host from the headers, or the first configured
  725. * trusted domain if the host isn't in the trusted list
  726. * @return string Server host
  727. */
  728. public function getServerHost(): string {
  729. // overwritehost is always trusted
  730. $host = $this->getOverwriteHost();
  731. if ($host !== null) {
  732. return $host;
  733. }
  734. // get the host from the headers
  735. $host = $this->getInsecureServerHost();
  736. // Verify that the host is a trusted domain if the trusted domains
  737. // are defined
  738. // If no trusted domain is provided the first trusted domain is returned
  739. $trustedDomainHelper = new TrustedDomainHelper($this->config);
  740. if ($trustedDomainHelper->isTrustedDomain($host)) {
  741. return $host;
  742. }
  743. $trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
  744. if (count($trustedList) > 0) {
  745. return reset($trustedList);
  746. }
  747. return '';
  748. }
  749. /**
  750. * Returns the overwritehost setting from the config if set and
  751. * if the overwrite condition is met
  752. * @return string|null overwritehost value or null if not defined or the defined condition
  753. * isn't met
  754. */
  755. private function getOverwriteHost() {
  756. if ($this->config->getSystemValueString('overwritehost') !== '' && $this->isOverwriteCondition()) {
  757. return $this->config->getSystemValueString('overwritehost');
  758. }
  759. return null;
  760. }
  761. private function fromTrustedProxy(): bool {
  762. $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  763. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  764. return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
  765. }
  766. }