ProxyController::proxy()   F
last analyzed

Complexity

Conditions 23
Paths 550

Size

Total Lines 144

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 49
CRAP Score 23.6869

Importance

Changes 0
Metric Value
dl 0
loc 144
ccs 49
cts 55
cp 0.8909
rs 0.5
c 0
b 0
f 0
cc 23
nc 550
nop 1
crap 23.6869

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * ownCloud - Calendar App
4
 *
5
 * @author Georg Ehrke
6
 * @copyright 2016 Georg Ehrke <[email protected]>
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
10
 * License as published by the Free Software Foundation; either
11
 * version 3 of the License, or any later version.
12
 *
13
 * This library is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public
19
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 */
22
namespace OCA\Calendar\Controller;
23
24
use GuzzleHttp\Exception\RequestException;
25
use GuzzleHttp\Exception\ClientException;
26
use GuzzleHttp\Exception\ConnectException;
27
28
use OCP\AppFramework\Http;
29
use OCP\AppFramework\Http\JSONResponse;
30
use OCP\AppFramework\Http\DataDisplayResponse;
31
use OCP\AppFramework\Controller;
32
use OCP\Http\Client\IClientService;
33
use OCP\IConfig;
34
use OCP\IL10N;
35
use OCP\ILogger;
36
use OCP\IRequest;
37
use Sabre\VObject\Reader;
38
39
class ProxyController extends Controller {
40
41
	/**
42
	 * @var IClientService
43
	 */
44
	protected $client;
45
46
	/**
47
	 * @var IL10N
48
	 */
49
	protected $l10n;
50
51
	/**
52
	 * @var ILogger
53
	 */
54
	protected $logger;
55
56
	/**
57
	 * @var IConfig
58
	 */
59
	protected $config;
60
61
	/**
62 10
	 * @param string $appName
63
	 * @param IRequest $request an instance of the request
64
	 * @param IClientService $client
65 10
	 * @param IL10N $l10n
66 10
	 * @param ILogger $logger
67 10
	 * @param IConfig $config
68 10
	 */
69 10
	public function __construct($appName, IRequest $request,
70
								IClientService $client,
71
								IL10N $l10n, ILogger $logger,
72
								IConfig $config) {
73
		parent::__construct($appName, $request);
74
		$this->client = $client;
75
		$this->l10n = $l10n;
76
		$this->logger = $logger;
77 10
		$this->config = $config;
78 10
	}
79
80 10
	/**
81 10
	 * @NoAdminRequired
82 10
	 *
83 10
	 * @param $url
84 10
	 * @return DataDisplayResponse|JSONResponse
85
	 */
86
	public function proxy($url) {
87
		$client = $this->client->newClient();
88 10
		try {
89 10
			$queryUrl = $url;
90
			$allow_redirects = false; // try to handle redirects manually at first
91
			$redirect_count = 0;
92 6
			$max_redirects = 5;
93 6
			$done = false;
94 4
95 4
			$allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
96 5
			if ($allowLocalAccess !== 'yes') {
97 2
				$host = strtolower(parse_url($url, PHP_URL_HOST));
98
				// remove brackets from IPv6 addresses
99
				if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
100 1
					$host = substr($host, 1, -1);
101
				}
102
103
				// Disallow localhost and local network
104
				if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost') {
105
					$this->logger->warning("ProxyController: Subscription $url was not refreshed because it violates local access rules");
106 1
107
					$response = new JSONResponse([
108
						'message' => $this->l10n->t('URL violates local access rules'),
109
						'proxy_code' => 403
110 4
					], Http::STATUS_UNPROCESSABLE_ENTITY);
111
112 6
					return $response;
113
				}
114 6
115 3
				// Disallow hostname only
116 3
				if (substr_count($host, '.') === 0) {
117 3
					$this->logger->warning("ProxyController: Subscription $url was not refreshed because it violates local access rules");
118 3
119 3
					$response = new JSONResponse([
120 2
						'message' => $this->l10n->t('URL violates local access rules'),
121
						'proxy_code' => 403
122
					], Http::STATUS_UNPROCESSABLE_ENTITY);
123 2
124
					return $response;
125
				}
126
127
				if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
128
					$this->logger->warning("ProxyController: Subscription $url was not refreshed because it violates local access rules");
129
130
					$response = new JSONResponse([
131
						'message' => $this->l10n->t('URL violates local access rules'),
132
						'proxy_code' => 403
133 2
					], Http::STATUS_UNPROCESSABLE_ENTITY);
134 2
135 2
					return $response;
136
				}
137
			}
138 1
139 1
			// try to find a chain of 301s
140
			do {
141 6
				$clientResponse = $client->get($queryUrl, [
142
					'allow_redirects' => $allow_redirects,
143 4
				]);
144 1
145 1
				$statusCode = $clientResponse->getStatusCode();
146
				if ($statusCode === 301) { // 400+ goes straight to catch
147 1
					$redirect_count++;
148 1
					$queryUrl = $clientResponse->getHeader('Location');
149 1
				} elseif ($statusCode >= 300) {
150 1
					if ($redirect_count > 0) {
151
						// $redirect_count > 0 => There have been 301s before,
152 1
						// break and return Location from last 301
153 1
						break;
154 3
					} else {
155 1
						// this is the very first request
156 1
						// it's being redirected, but the redirection is not
157 1
						// permanently, just let Guzzle take care
158
						$allow_redirects = [
159 1
							'max' => $max_redirects
160 2
						];
161 2
					}
162
				} else {
163 2
					$done = true;
164 1
				}
165
			} while(!$done && $redirect_count <= $max_redirects);
166 1
167
			if ($redirect_count > 0 && $redirect_count <= $max_redirects) {
168
				$response = new JSONResponse([
169 2
					'proxy_code' => -4,
170 2
					'new_url' => $queryUrl,
171
				], Http::STATUS_BAD_REQUEST);
172 2
			} elseif ($done) {
173
				$icsData = $clientResponse->getBody();
174
175 10
				try {
176
					Reader::read($icsData, Reader::OPTION_FORGIVING);
177
				} catch(\Exception $ex) {
178
					$response = new JSONResponse([
179
						'message' => $this->l10n->t('The remote server did not give us access to the calendar (HTTP 404 error)'),
180
						'proxy_code' => 404
181
					], Http::STATUS_UNPROCESSABLE_ENTITY);
182
183
					return $response;
184
				}
185
186
				$response = new DataDisplayResponse($icsData, 200);
187
				$response->setHeaders([
188
					'Content-Type' => 'text/calendar',
189
				]);
190
			} else {
191
				$response = new JSONResponse([
192
					'message' => $this->l10n->t('Too many redirects. Aborting ...'),
193
					'proxy_code' => -3
194
				], Http::STATUS_UNPROCESSABLE_ENTITY);
195
			}
196
		} catch (ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
197
			$error_code = $e->getResponse()->getStatusCode();
198
			$message = $e->getMessage();
199
200
			$this->logger->debug($message);
201
			$response = new JSONResponse([
202
				'message' => $this->l10n->t('The remote server did not give us access to the calendar (HTTP {%s} error)', [
203
					(string) $error_code
204
				]),
205
				'proxy_code' => $error_code
206
			], Http::STATUS_UNPROCESSABLE_ENTITY);
207
		} catch (ConnectException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ConnectException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
208
			$this->logger->debug($e->getMessage());
209
			$response = new JSONResponse([
210
				'message' => $this->l10n->t('Error connecting to remote server'),
211
				'proxy_code' => -1
212
			], Http::STATUS_UNPROCESSABLE_ENTITY);
213
		} catch (RequestException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\RequestException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
214
			$this->logger->debug($e->getMessage());
215
216
			if (substr($url, 0, 8) === 'https://') {
217
				$message = $this->l10n->t('Error requesting resource on remote server. This could possible be related to a certificate mismatch');
218
			} else {
219
				$message = $this->l10n->t('Error requesting resource on remote server');
220
			}
221
222
			$response = new JSONResponse([
223
				'message' => $message,
224
				'proxy_code' => -2,
225
			], Http::STATUS_UNPROCESSABLE_ENTITY);
226
		}
227
228
		return $response;
229
	}
230
}
231