Request.php 24 KB

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