Request.php 25 KB

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