Completed
Push — master ( 9222dc...c12161 )
by Morris
56:15 queued 36:32
created

Request::getInsecureServerHost()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 14

Duplication

Lines 6
Ratio 33.33 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 5
nop 0
dl 6
loc 18
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Bart Visscher <[email protected]>
6
 * @author Bernhard Posselt <[email protected]>
7
 * @author Christoph Wurst <[email protected]>
8
 * @author coderkun <[email protected]>
9
 * @author Joas Schilling <[email protected]>
10
 * @author Juan Pablo Villafáñez <[email protected]>
11
 * @author Jörn Friedrich Dreyer <[email protected]>
12
 * @author Lukas Reschke <[email protected]>
13
 * @author Mitar <[email protected]>
14
 * @author Morris Jobke <[email protected]>
15
 * @author Robin Appelman <[email protected]>
16
 * @author Robin McCorkell <[email protected]>
17
 * @author Roeland Jago Douma <[email protected]>
18
 * @author Thomas Müller <[email protected]>
19
 * @author Thomas Tanghus <[email protected]>
20
 * @author Vincent Petry <[email protected]>
21
 *
22
 * @license AGPL-3.0
23
 *
24
 * This code is free software: you can redistribute it and/or modify
25
 * it under the terms of the GNU Affero General Public License, version 3,
26
 * as published by the Free Software Foundation.
27
 *
28
 * This program is distributed in the hope that it will be useful,
29
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31
 * GNU Affero General Public License for more details.
32
 *
33
 * You should have received a copy of the GNU Affero General Public License, version 3,
34
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
35
 *
36
 */
37
38
namespace OC\AppFramework\Http;
39
40
use OC\Security\CSRF\CsrfToken;
41
use OC\Security\CSRF\CsrfTokenManager;
42
use OC\Security\TrustedDomainHelper;
43
use OCP\IConfig;
44
use OCP\IRequest;
45
use OCP\Security\ICrypto;
46
use OCP\Security\ISecureRandom;
47
48
/**
49
 * Class for accessing variables in the request.
50
 * This class provides an immutable object with request variables.
51
 *
52
 * @property mixed[] cookies
53
 * @property mixed[] env
54
 * @property mixed[] files
55
 * @property string method
56
 * @property mixed[] parameters
57
 * @property mixed[] server
58
 */
59
class Request implements \ArrayAccess, \Countable, IRequest {
60
61
	const USER_AGENT_IE = '/(MSIE)|(Trident)/';
62
	// Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
63
	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.]+$/';
64
	// Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
65
	const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
66
	// Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
67
	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.]+$/';
68
	// Safari User Agent from http://www.useragentstring.com/pages/Safari/
69
	const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
70
	// Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
71
	const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
72
	const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
73
	const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
74
75
	/**
76
	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
77
	 */
78
	const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
79
	/**
80
	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
81
	 */
82
	const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
83
	/**
84
	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
85
	 */
86
	const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
87
88
	protected $inputStream;
89
	protected $content;
90
	protected $items = array();
91
	protected $allowedKeys = array(
92
		'get',
93
		'post',
94
		'files',
95
		'server',
96
		'env',
97
		'cookies',
98
		'urlParams',
99
		'parameters',
100
		'method',
101
		'requesttoken',
102
	);
103
	/** @var ISecureRandom */
104
	protected $secureRandom;
105
	/** @var IConfig */
106
	protected $config;
107
	/** @var string */
108
	protected $requestId = '';
109
	/** @var ICrypto */
110
	protected $crypto;
111
	/** @var CsrfTokenManager|null */
112
	protected $csrfTokenManager;
113
114
	/** @var bool */
115
	protected $contentDecoded = false;
116
117
	/**
118
	 * @param array $vars An associative array with the following optional values:
119
	 *        - array 'urlParams' the parameters which were matched from the URL
120
	 *        - array 'get' the $_GET array
121
	 *        - array|string 'post' the $_POST array or JSON string
122
	 *        - array 'files' the $_FILES array
123
	 *        - array 'server' the $_SERVER array
124
	 *        - array 'env' the $_ENV array
125
	 *        - array 'cookies' the $_COOKIE array
126
	 *        - string 'method' the request method (GET, POST etc)
127
	 *        - string|false 'requesttoken' the requesttoken or false when not available
128
	 * @param ISecureRandom $secureRandom
129
	 * @param IConfig $config
130
	 * @param CsrfTokenManager|null $csrfTokenManager
131
	 * @param string $stream
132
	 * @see http://www.php.net/manual/en/reserved.variables.php
133
	 */
134
	public function __construct(array $vars=array(),
135
								ISecureRandom $secureRandom = null,
136
								IConfig $config,
137
								CsrfTokenManager $csrfTokenManager = null,
138
								$stream = 'php://input') {
139
		$this->inputStream = $stream;
140
		$this->items['params'] = array();
141
		$this->secureRandom = $secureRandom;
142
		$this->config = $config;
143
		$this->csrfTokenManager = $csrfTokenManager;
144
145
		if(!array_key_exists('method', $vars)) {
146
			$vars['method'] = 'GET';
147
		}
148
149
		foreach($this->allowedKeys as $name) {
150
			$this->items[$name] = isset($vars[$name])
151
				? $vars[$name]
152
				: array();
153
		}
154
155
		$this->items['parameters'] = array_merge(
156
			$this->items['get'],
157
			$this->items['post'],
158
			$this->items['urlParams'],
159
			$this->items['params']
160
		);
161
162
	}
163
	/**
164
	 * @param array $parameters
165
	 */
166
	public function setUrlParameters(array $parameters) {
167
		$this->items['urlParams'] = $parameters;
168
		$this->items['parameters'] = array_merge(
169
			$this->items['parameters'],
170
			$this->items['urlParams']
171
		);
172
	}
173
174
	/**
175
	 * Countable method
176
	 * @return int
177
	 */
178
	public function count() {
179
		return count(array_keys($this->items['parameters']));
180
	}
181
182
	/**
183
	* ArrayAccess methods
184
	*
185
	* Gives access to the combined GET, POST and urlParams arrays
186
	*
187
	* Examples:
188
	*
189
	* $var = $request['myvar'];
190
	*
191
	* or
192
	*
193
	* if(!isset($request['myvar']) {
194
	* 	// Do something
195
	* }
196
	*
197
	* $request['myvar'] = 'something'; // This throws an exception.
198
	*
199
	* @param string $offset The key to lookup
200
	* @return boolean
201
	*/
202
	public function offsetExists($offset) {
203
		return isset($this->items['parameters'][$offset]);
204
	}
205
206
	/**
207
	* @see offsetExists
208
	*/
209
	public function offsetGet($offset) {
210
		return isset($this->items['parameters'][$offset])
211
			? $this->items['parameters'][$offset]
212
			: null;
213
	}
214
215
	/**
216
	* @see offsetExists
217
	*/
218
	public function offsetSet($offset, $value) {
219
		throw new \RuntimeException('You cannot change the contents of the request object');
220
	}
221
222
	/**
223
	* @see offsetExists
224
	*/
225
	public function offsetUnset($offset) {
226
		throw new \RuntimeException('You cannot change the contents of the request object');
227
	}
228
229
	/**
230
	 * Magic property accessors
231
	 * @param string $name
232
	 * @param mixed $value
233
	 */
234
	public function __set($name, $value) {
235
		throw new \RuntimeException('You cannot change the contents of the request object');
236
	}
237
238
	/**
239
	* Access request variables by method and name.
240
	* Examples:
241
	*
242
	* $request->post['myvar']; // Only look for POST variables
243
	* $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
244
	* Looks in the combined GET, POST and urlParams array.
245
	*
246
	* If you access e.g. ->post but the current HTTP request method
247
	* is GET a \LogicException will be thrown.
248
	*
249
	* @param string $name The key to look for.
250
	* @throws \LogicException
251
	* @return mixed|null
252
	*/
253
	public function __get($name) {
254
		switch($name) {
255
			case 'put':
256
			case 'patch':
257
			case 'get':
258
			case 'post':
259
				if($this->method !== strtoupper($name)) {
260
					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
261
				}
262
				return $this->getContent();
263
			case 'files':
264
			case 'server':
265
			case 'env':
266
			case 'cookies':
267
			case 'urlParams':
268
			case 'method':
269
				return isset($this->items[$name])
270
					? $this->items[$name]
271
					: null;
272
			case 'parameters':
273
			case 'params':
274
				return $this->getContent();
275
			default;
0 ignored issues
show
Coding Style introduced by
DEFAULT statements must be defined using a colon

As per the PSR-2 coding standard, default statements should not be wrapped in curly braces.

switch ($expr) {
    default: { //wrong
        doSomething();
        break;
    }
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
276
				return isset($this[$name])
277
					? $this[$name]
278
					: null;
279
		}
280
	}
281
282
	/**
283
	 * @param string $name
284
	 * @return bool
285
	 */
286
	public function __isset($name) {
287
		if (in_array($name, $this->allowedKeys, true)) {
288
			return true;
289
		}
290
		return isset($this->items['parameters'][$name]);
291
	}
292
293
	/**
294
	 * @param string $id
295
	 */
296
	public function __unset($id) {
297
		throw new \RuntimeException('You cannot change the contents of the request object');
298
	}
299
300
	/**
301
	 * Returns the value for a specific http header.
302
	 *
303
	 * This method returns null if the header did not exist.
304
	 *
305
	 * @param string $name
306
	 * @return string
307
	 */
308
	public function getHeader($name) {
309
310
		$name = strtoupper(str_replace(array('-'),array('_'),$name));
311
		if (isset($this->server['HTTP_' . $name])) {
312
			return $this->server['HTTP_' . $name];
313
		}
314
315
		// There's a few headers that seem to end up in the top-level
316
		// server array.
317
		switch($name) {
318
			case 'CONTENT_TYPE' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
319
			case 'CONTENT_LENGTH' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
320
				if (isset($this->server[$name])) {
321
					return $this->server[$name];
322
				}
323
				break;
324
325
		}
326
327
		return '';
328
	}
329
330
	/**
331
	 * Lets you access post and get parameters by the index
332
	 * In case of json requests the encoded json body is accessed
333
	 *
334
	 * @param string $key the key which you want to access in the URL Parameter
335
	 *                     placeholder, $_POST or $_GET array.
336
	 *                     The priority how they're returned is the following:
337
	 *                     1. URL parameters
338
	 *                     2. POST parameters
339
	 *                     3. GET parameters
340
	 * @param mixed $default If the key is not found, this value will be returned
341
	 * @return mixed the content of the array
342
	 */
343
	public function getParam($key, $default = null) {
344
		return isset($this->parameters[$key])
345
			? $this->parameters[$key]
346
			: $default;
347
	}
348
349
	/**
350
	 * Returns all params that were received, be it from the request
351
	 * (as GET or POST) or throuh the URL by the route
352
	 * @return array the array with all parameters
353
	 */
354
	public function getParams() {
355
		return $this->parameters;
356
	}
357
358
	/**
359
	 * Returns the method of the request
360
	 * @return string the method of the request (POST, GET, etc)
361
	 */
362
	public function getMethod() {
363
		return $this->method;
364
	}
365
366
	/**
367
	 * Shortcut for accessing an uploaded file through the $_FILES array
368
	 * @param string $key the key that will be taken from the $_FILES array
369
	 * @return array the file in the $_FILES element
370
	 */
371
	public function getUploadedFile($key) {
372
		return isset($this->files[$key]) ? $this->files[$key] : null;
373
	}
374
375
	/**
376
	 * Shortcut for getting env variables
377
	 * @param string $key the key that will be taken from the $_ENV array
378
	 * @return array the value in the $_ENV element
379
	 */
380
	public function getEnv($key) {
381
		return isset($this->env[$key]) ? $this->env[$key] : null;
382
	}
383
384
	/**
385
	 * Shortcut for getting cookie variables
386
	 * @param string $key the key that will be taken from the $_COOKIE array
387
	 * @return string the value in the $_COOKIE element
388
	 */
389
	public function getCookie($key) {
390
		return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
391
	}
392
393
	/**
394
	 * Returns the request body content.
395
	 *
396
	 * If the HTTP request method is PUT and the body
397
	 * not application/x-www-form-urlencoded or application/json a stream
398
	 * resource is returned, otherwise an array.
399
	 *
400
	 * @return array|string|resource The request body content or a resource to read the body stream.
401
	 *
402
	 * @throws \LogicException
403
	 */
404
	protected function getContent() {
405
		// If the content can't be parsed into an array then return a stream resource.
406
		if ($this->method === 'PUT'
407
			&& $this->getHeader('Content-Length') !== '0'
408
			&& $this->getHeader('Content-Length') !== ''
409
			&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
410
			&& strpos($this->getHeader('Content-Type'), 'application/json') === false
411
		) {
412
			if ($this->content === false) {
413
				throw new \LogicException(
414
					'"put" can only be accessed once if not '
415
					. 'application/x-www-form-urlencoded or application/json.'
416
				);
417
			}
418
			$this->content = false;
419
			return fopen($this->inputStream, 'rb');
420
		} else {
421
			$this->decodeContent();
422
			return $this->items['parameters'];
423
		}
424
	}
425
426
	/**
427
	 * Attempt to decode the content and populate parameters
428
	 */
429
	protected function decodeContent() {
430
		if ($this->contentDecoded) {
431
			return;
432
		}
433
		$params = [];
434
435
		// 'application/json' must be decoded manually.
436
		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
437
			$params = json_decode(file_get_contents($this->inputStream), true);
438
			if($params !== null && count($params) > 0) {
439
				$this->items['params'] = $params;
440
				if($this->method === 'POST') {
441
					$this->items['post'] = $params;
442
				}
443
			}
444
445
		// Handle application/x-www-form-urlencoded for methods other than GET
446
		// or post correctly
447
		} elseif($this->method !== 'GET'
448
				&& $this->method !== 'POST'
449
				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
450
451
			parse_str(file_get_contents($this->inputStream), $params);
452
			if(is_array($params)) {
453
				$this->items['params'] = $params;
454
			}
455
		}
456
457
		if (is_array($params)) {
458
			$this->items['parameters'] = array_merge($this->items['parameters'], $params);
459
		}
460
		$this->contentDecoded = true;
461
	}
462
463
464
	/**
465
	 * Checks if the CSRF check was correct
466
	 * @return bool true if CSRF check passed
467
	 */
468
	public function passesCSRFCheck() {
469
		if($this->csrfTokenManager === null) {
470
			return false;
471
		}
472
473
		if(!$this->passesStrictCookieCheck()) {
474
			return false;
475
		}
476
477
		if (isset($this->items['get']['requesttoken'])) {
478
			$token = $this->items['get']['requesttoken'];
479
		} elseif (isset($this->items['post']['requesttoken'])) {
480
			$token = $this->items['post']['requesttoken'];
481
		} elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
482
			$token = $this->items['server']['HTTP_REQUESTTOKEN'];
483
		} else {
484
			//no token found.
485
			return false;
486
		}
487
		$token = new CsrfToken($token);
488
489
		return $this->csrfTokenManager->isTokenValid($token);
490
	}
491
492
	/**
493
	 * Whether the cookie checks are required
494
	 *
495
	 * @return bool
496
	 */
497
	private function cookieCheckRequired() {
498
		if ($this->getHeader('OCS-APIREQUEST')) {
499
			return false;
500
		}
501
		if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
502
			return false;
503
		}
504
505
		return true;
506
	}
507
508
	/**
509
	 * Wrapper around session_get_cookie_params
510
	 *
511
	 * @return array
512
	 */
513
	public function getCookieParams() {
514
		return session_get_cookie_params();
515
	}
516
517
	/**
518
	 * Appends the __Host- prefix to the cookie if applicable
519
	 *
520
	 * @param string $name
521
	 * @return string
522
	 */
523
	protected function getProtectedCookieName($name) {
524
		$cookieParams = $this->getCookieParams();
525
		$prefix = '';
526
		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
527
			$prefix = '__Host-';
528
		}
529
530
		return $prefix.$name;
531
	}
532
533
	/**
534
	 * Checks if the strict cookie has been sent with the request if the request
535
	 * is including any cookies.
536
	 *
537
	 * @return bool
538
	 * @since 9.1.0
539
	 */
540 View Code Duplication
	public function passesStrictCookieCheck() {
541
		if(!$this->cookieCheckRequired()) {
542
			return true;
543
		}
544
545
		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
546
		if($this->getCookie($cookieName) === 'true'
547
			&& $this->passesLaxCookieCheck()) {
548
			return true;
549
		}
550
		return false;
551
	}
552
553
	/**
554
	 * Checks if the lax cookie has been sent with the request if the request
555
	 * is including any cookies.
556
	 *
557
	 * @return bool
558
	 * @since 9.1.0
559
	 */
560 View Code Duplication
	public function passesLaxCookieCheck() {
561
		if(!$this->cookieCheckRequired()) {
562
			return true;
563
		}
564
565
		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
566
		if($this->getCookie($cookieName) === 'true') {
567
			return true;
568
		}
569
		return false;
570
	}
571
572
573
	/**
574
	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
575
	 * If `mod_unique_id` is installed this value will be taken.
576
	 * @return string
577
	 */
578
	public function getId() {
579
		if(isset($this->server['UNIQUE_ID'])) {
580
			return $this->server['UNIQUE_ID'];
581
		}
582
583
		if(empty($this->requestId)) {
584
			$validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
585
			$this->requestId = $this->secureRandom->generate(20, $validChars);
586
		}
587
588
		return $this->requestId;
589
	}
590
591
	/**
592
	 * Returns the remote address, if the connection came from a trusted proxy
593
	 * and `forwarded_for_headers` has been configured then the IP address
594
	 * specified in this header will be returned instead.
595
	 * Do always use this instead of $_SERVER['REMOTE_ADDR']
596
	 * @return string IP address
597
	 */
598
	public function getRemoteAddress() {
599
		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
600
		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
601
602
		if(is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
603
			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
604
				'HTTP_X_FORWARDED_FOR'
605
				// only have one default, so we cannot ship an insecure product out of the box
606
			]);
607
608
			foreach($forwardedForHeaders as $header) {
609
				if(isset($this->server[$header])) {
610
					foreach(explode(',', $this->server[$header]) as $IP) {
611
						$IP = trim($IP);
612
						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
613
							return $IP;
614
						}
615
					}
616
				}
617
			}
618
		}
619
620
		return $remoteAddress;
621
	}
622
623
	/**
624
	 * Check overwrite condition
625
	 * @param string $type
626
	 * @return bool
627
	 */
628
	private function isOverwriteCondition($type = '') {
629
		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
630
		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
631
		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
632
		|| $type !== 'protocol';
633
	}
634
635
	/**
636
	 * Returns the server protocol. It respects one or more reverse proxies servers
637
	 * and load balancers
638
	 * @return string Server protocol (http or https)
639
	 */
640
	public function getServerProtocol() {
641
		if($this->config->getSystemValue('overwriteprotocol') !== ''
642
			&& $this->isOverwriteCondition('protocol')) {
643
			return $this->config->getSystemValue('overwriteprotocol');
644
		}
645
646
		if (isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
647 View Code Duplication
			if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
648
				$parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
649
				$proto = strtolower(trim($parts[0]));
650
			} else {
651
				$proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
652
			}
653
654
			// Verify that the protocol is always HTTP or HTTPS
655
			// default to http if an invalid value is provided
656
			return $proto === 'https' ? 'https' : 'http';
657
		}
658
659
		if (isset($this->server['HTTPS'])
660
			&& $this->server['HTTPS'] !== null
661
			&& $this->server['HTTPS'] !== 'off'
662
			&& $this->server['HTTPS'] !== '') {
663
			return 'https';
664
		}
665
666
		return 'http';
667
	}
668
669
	/**
670
	 * Returns the used HTTP protocol.
671
	 *
672
	 * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
673
	 */
674 View Code Duplication
	public function getHttpProtocol() {
675
		$claimedProtocol = strtoupper($this->server['SERVER_PROTOCOL']);
676
677
		$validProtocols = [
678
			'HTTP/1.0',
679
			'HTTP/1.1',
680
			'HTTP/2',
681
		];
682
683
		if(in_array($claimedProtocol, $validProtocols, true)) {
684
			return $claimedProtocol;
685
		}
686
687
		return 'HTTP/1.1';
688
	}
689
690
	/**
691
	 * Returns the request uri, even if the website uses one or more
692
	 * reverse proxies
693
	 * @return string
694
	 */
695
	public function getRequestUri() {
696
		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
697
		if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
698
			$uri = $this->getScriptName() . substr($uri, strlen($this->server['SCRIPT_NAME']));
699
		}
700
		return $uri;
701
	}
702
703
	/**
704
	 * Get raw PathInfo from request (not urldecoded)
705
	 * @throws \Exception
706
	 * @return string Path info
707
	 */
708
	public function getRawPathInfo() {
709
		$requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
710
		// remove too many leading slashes - can be caused by reverse proxy configuration
711
		if (strpos($requestUri, '/') === 0) {
712
			$requestUri = '/' . ltrim($requestUri, '/');
713
		}
714
715
		$requestUri = preg_replace('%/{2,}%', '/', $requestUri);
0 ignored issues
show
Bug Compatibility introduced by
The expression preg_replace('%/{2,}%', '/', $requestUri); of type string|string[] adds the type string[] to the return on line 744 which is incompatible with the return type declared by the interface OCP\IRequest::getRawPathInfo of type string.
Loading history...
716
717
		// Remove the query string from REQUEST_URI
718
		if ($pos = strpos($requestUri, '?')) {
719
			$requestUri = substr($requestUri, 0, $pos);
720
		}
721
722
		$scriptName = $this->server['SCRIPT_NAME'];
723
		$pathInfo = $requestUri;
724
725
		// strip off the script name's dir and file name
726
		// FIXME: Sabre does not really belong here
727
		list($path, $name) = \Sabre\Uri\split($scriptName);
728
		if (!empty($path)) {
729
			if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
730
				$pathInfo = substr($pathInfo, strlen($path));
731
			} else {
732
				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
733
			}
734
		}
735
		if (strpos($pathInfo, '/'.$name) === 0) {
736
			$pathInfo = substr($pathInfo, strlen($name) + 1);
737
		}
738
		if (strpos($pathInfo, $name) === 0) {
739
			$pathInfo = substr($pathInfo, strlen($name));
740
		}
741
		if($pathInfo === false || $pathInfo === '/'){
742
			return '';
743
		} else {
744
			return $pathInfo;
745
		}
746
	}
747
748
	/**
749
	 * Get PathInfo from request
750
	 * @throws \Exception
751
	 * @return string|false Path info or false when not found
752
	 */
753
	public function getPathInfo() {
754
		$pathInfo = $this->getRawPathInfo();
755
		// following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
756
		$pathInfo = rawurldecode($pathInfo);
757
		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
758
759
		switch($encoding) {
760
			case 'ISO-8859-1' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
761
				$pathInfo = utf8_encode($pathInfo);
762
		}
763
		// end copy
764
765
		return $pathInfo;
766
	}
767
768
	/**
769
	 * Returns the script name, even if the website uses one or more
770
	 * reverse proxies
771
	 * @return string the script name
772
	 */
773
	public function getScriptName() {
774
		$name = $this->server['SCRIPT_NAME'];
775
		$overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
776
		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
777
			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
778
			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -strlen('lib/private/appframework/http/')));
779
			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), strlen($serverRoot)));
780
			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
781
		}
782
		return $name;
783
	}
784
785
	/**
786
	 * Checks whether the user agent matches a given regex
787
	 * @param array $agent array of agent names
788
	 * @return bool true if at least one of the given agent matches, false otherwise
789
	 */
790
	public function isUserAgent(array $agent) {
791
		if (!isset($this->server['HTTP_USER_AGENT'])) {
792
			return false;
793
		}
794
		foreach ($agent as $regex) {
795
			if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
796
				return true;
797
			}
798
		}
799
		return false;
800
	}
801
802
	/**
803
	 * Returns the unverified server host from the headers without checking
804
	 * whether it is a trusted domain
805
	 * @return string Server host
806
	 */
807
	public function getInsecureServerHost() {
808
		$host = 'localhost';
809
		if (isset($this->server['HTTP_X_FORWARDED_HOST'])) {
810 View Code Duplication
			if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
811
				$parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
812
				$host = trim(current($parts));
813
			} else {
814
				$host = $this->server['HTTP_X_FORWARDED_HOST'];
815
			}
816
		} else {
817
			if (isset($this->server['HTTP_HOST'])) {
818
				$host = $this->server['HTTP_HOST'];
819
			} else if (isset($this->server['SERVER_NAME'])) {
820
				$host = $this->server['SERVER_NAME'];
821
			}
822
		}
823
		return $host;
824
	}
825
826
827
	/**
828
	 * Returns the server host from the headers, or the first configured
829
	 * trusted domain if the host isn't in the trusted list
830
	 * @return string Server host
831
	 */
832
	public function getServerHost() {
833
		// overwritehost is always trusted
834
		$host = $this->getOverwriteHost();
835
		if ($host !== null) {
836
			return $host;
837
		}
838
839
		// get the host from the headers
840
		$host = $this->getInsecureServerHost();
841
842
		// Verify that the host is a trusted domain if the trusted domains
843
		// are defined
844
		// If no trusted domain is provided the first trusted domain is returned
845
		$trustedDomainHelper = new TrustedDomainHelper($this->config);
846
		if ($trustedDomainHelper->isTrustedDomain($host)) {
847
			return $host;
848
		} else {
849
			$trustedList = $this->config->getSystemValue('trusted_domains', []);
850
			if(!empty($trustedList)) {
851
				return $trustedList[0];
852
			} else {
853
				return '';
854
			}
855
		}
856
	}
857
858
	/**
859
	 * Returns the overwritehost setting from the config if set and
860
	 * if the overwrite condition is met
861
	 * @return string|null overwritehost value or null if not defined or the defined condition
862
	 * isn't met
863
	 */
864
	private function getOverwriteHost() {
865
		if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
866
			return $this->config->getSystemValue('overwritehost');
867
		}
868
		return null;
869
	}
870
871
}
872