3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU APGL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
27 use Friendica\Core\Config\IConfig;
28 use Friendica\Core\System;
29 use Friendica\Util\Network;
30 use Friendica\Util\Profiler;
31 use GuzzleHttp\Client;
32 use GuzzleHttp\Exception\RequestException;
33 use GuzzleHttp\Exception\TransferException;
34 use Psr\Http\Message\RequestInterface;
35 use Psr\Http\Message\ResponseInterface;
36 use Psr\Http\Message\UriInterface;
37 use Psr\Log\LoggerInterface;
40 * Performs HTTP requests to a given URL
42 class HTTPRequest implements IHTTPRequest
44 /** @var LoggerInterface */
53 public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App\BaseURL $baseUrl)
55 $this->logger = $logger;
56 $this->profiler = $profiler;
57 $this->config = $config;
58 $this->baseUrl = $baseUrl->get();
63 * @throws HTTPException\InternalServerErrorException
65 public function head(string $url, array $opts = [])
67 $opts['nobody'] = true;
69 return $this->get($url, $opts);
75 public function get(string $url, bool $binary = false, array $opts = [])
77 $this->profiler->startRecording('network');
79 if (Network::isLocalLink($url)) {
80 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
83 if (strlen($url) > 1000) {
84 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
85 $this->profiler->stopRecording();
86 return CurlResult::createErrorCurl(substr($url, 0, 200));
90 $parts = parse_url($url);
91 $path_parts = explode('/', $parts['path'] ?? '');
92 foreach ($path_parts as $part) {
93 if (strlen($part) <> mb_strlen($part)) {
94 $parts2[] = rawurlencode($part);
99 $parts['path'] = implode('/', $parts2);
100 $url = Network::unparseURL($parts);
102 if (Network::isUrlBlocked($url)) {
103 $this->logger->info('Domain is blocked.', ['url' => $url]);
104 $this->profiler->stopRecording();
105 return CurlResult::createErrorCurl($url);
110 $curlOptions[CURLOPT_HEADER] = true;
112 if (!empty($opts['cookiejar'])) {
113 $curlOptions[CURLOPT_COOKIEJAR] = $opts["cookiejar"];
114 $curlOptions[CURLOPT_COOKIEFILE] = $opts["cookiejar"];
117 // These settings aren't needed. We're following the location already.
118 // $curlOptions[CURLOPT_FOLLOWLOCATION] =true;
119 // $curlOptions[CURLOPT_MAXREDIRS] = 5;
121 if (!empty($opts['accept_content'])) {
122 if (empty($curlOptions[CURLOPT_HTTPHEADER])) {
123 $curlOptions[CURLOPT_HTTPHEADER] = [];
125 array_push($curlOptions[CURLOPT_HTTPHEADER], 'Accept: ' . $opts['accept_content']);
128 if (!empty($opts['header'])) {
129 if (empty($curlOptions[CURLOPT_HTTPHEADER])) {
130 $curlOptions[CURLOPT_HTTPHEADER] = [];
132 $curlOptions[CURLOPT_HTTPHEADER] = array_merge($opts['header'], $curlOptions[CURLOPT_HTTPHEADER]);
135 $curlOptions[CURLOPT_RETURNTRANSFER] = true;
136 $curlOptions[CURLOPT_USERAGENT] = $this->getUserAgent();
138 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
141 $curlOptions[CURLOPT_RANGE] = '0-' . $range;
144 // Without this setting it seems as if some webservers send compressed content
145 // This seems to confuse curl so that it shows this uncompressed.
146 /// @todo We could possibly set this value to "gzip" or something similar
147 $curlOptions[CURLOPT_ENCODING] = '';
149 if (!empty($opts['headers'])) {
150 $this->logger->notice('Wrong option \'headers\' used.');
151 if (empty($curlOptions[CURLOPT_HTTPHEADER])) {
152 $curlOptions[CURLOPT_HTTPHEADER] = [];
154 $curlOptions[CURLOPT_HTTPHEADER] = array_merge($opts['headers'], $curlOptions[CURLOPT_HTTPHEADER]);
157 if (!empty($opts['nobody'])) {
158 $curlOptions[CURLOPT_NOBODY] = $opts['nobody'];
161 $curlOptions[CURLOPT_CONNECTTIMEOUT] = 10;
163 if (!empty($opts['timeout'])) {
164 $curlOptions[CURLOPT_TIMEOUT] = $opts['timeout'];
166 $curl_time = $this->config->get('system', 'curl_timeout', 60);
167 $curlOptions[CURLOPT_TIMEOUT] = intval($curl_time);
170 // by default we will allow self-signed certs
171 // but you can override this
173 $check_cert = $this->config->get('system', 'verifyssl');
174 $curlOptions[CURLOPT_SSL_VERIFYPEER] = ($check_cert) ? true : false;
177 $curlOptions[CURLOPT_SSL_VERIFYHOST] = 2;
180 $proxy = $this->config->get('system', 'proxy');
182 if (!empty($proxy)) {
183 $curlOptions[CURLOPT_HTTPPROXYTUNNEL] = 1;
184 $curlOptions[CURLOPT_PROXY] = $proxy;
185 $proxyuser = $this->config->get('system', 'proxyuser');
187 if (!empty($proxyuser)) {
188 $curlOptions[CURLOPT_PROXYUSERPWD] = $proxyuser;
192 if ($this->config->get('system', 'ipv4_resolve', false)) {
193 $curlOptions[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
197 $curlOptions[CURLOPT_BINARYTRANSFER] = 1;
200 $logger = $this->logger;
202 $onRedirect = function(
203 RequestInterface $request,
204 ResponseInterface $response,
207 $logger->notice('Curl redirect.', ['url' => $request->getUri(), 'to' => $uri]);
210 $onHeaders = function (ResponseInterface $response) use ($opts) {
211 if (!empty($opts['content_length']) &&
212 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
213 throw new TransferException('The file is too big!');
217 $client = new Client([
218 'allow_redirect' => [
220 'on_redirect' => $onRedirect,
221 'track_redirect' => true,
225 'on_headers' => $onHeaders,
226 'sink' => tempnam(get_temppath(), 'guzzle'),
227 'curl' => $curlOptions
231 $response = $client->get($url);
232 return new GuzzleResponse($response, $url);
233 } catch (TransferException $exception) {
234 if ($exception instanceof RequestException &&
235 $exception->hasResponse()) {
236 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), $exception->getMessage());
238 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), $exception->getMessage());
241 $this->profiler->stopRecording();
248 * @param int $redirects The recursion counter for internal use - default 0
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
254 $this->profiler->startRecording('network');
256 if (Network::isLocalLink($url)) {
257 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
260 if (Network::isUrlBlocked($url)) {
261 $this->logger->info('Domain is blocked.' . ['url' => $url]);
262 $this->profiler->stopRecording();
263 return CurlResult::createErrorCurl($url);
266 $ch = curl_init($url);
268 if (($redirects > 8) || (!$ch)) {
269 $this->profiler->stopRecording();
270 return CurlResult::createErrorCurl($url);
273 $this->logger->debug('Post_url: start.', ['url' => $url]);
275 curl_setopt($ch, CURLOPT_HEADER, true);
276 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
277 curl_setopt($ch, CURLOPT_POST, 1);
278 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
279 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
281 if ($this->config->get('system', 'ipv4_resolve', false)) {
282 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
285 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
287 if (intval($timeout)) {
288 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
290 $curl_time = $this->config->get('system', 'curl_timeout', 60);
291 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
294 if (!empty($headers)) {
295 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
298 $check_cert = $this->config->get('system', 'verifyssl');
299 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
302 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
305 $proxy = $this->config->get('system', 'proxy');
307 if (!empty($proxy)) {
308 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
309 curl_setopt($ch, CURLOPT_PROXY, $proxy);
310 $proxyuser = $this->config->get('system', 'proxyuser');
311 if (!empty($proxyuser)) {
312 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
316 // don't let curl abort the entire application
317 // if it throws any errors.
319 $s = @curl_exec($ch);
321 $curl_info = curl_getinfo($ch);
323 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
325 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
327 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
329 $this->profiler->stopRecording();
330 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
335 $this->profiler->stopRecording();
337 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
338 if ($curlResponse->getReturnCode() == 417) {
341 if (empty($headers)) {
342 $headers = ['Expect:'];
344 if (!in_array('Expect:', $headers)) {
345 array_push($headers, 'Expect:');
348 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
349 return $this->post($url, $params, $headers, $redirects, $timeout);
352 $this->logger->debug('Post_url: End.', ['url' => $url]);
354 return $curlResponse;
360 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
362 if (Network::isLocalLink($url)) {
363 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
366 if (Network::isUrlBlocked($url)) {
367 $this->logger->info('Domain is blocked.', ['url' => $url]);
371 if (Network::isRedirectBlocked($url)) {
372 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
376 $url = Network::stripTrackingQueryParams($url);
382 $url = trim($url, "'");
384 $this->profiler->startRecording('network');
387 curl_setopt($ch, CURLOPT_URL, $url);
388 curl_setopt($ch, CURLOPT_HEADER, 1);
389 curl_setopt($ch, CURLOPT_NOBODY, 1);
390 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
391 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
392 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
393 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
396 $curl_info = @curl_getinfo($ch);
397 $http_code = $curl_info['http_code'];
400 $this->profiler->stopRecording();
402 if ($http_code == 0) {
406 if (in_array($http_code, ['301', '302'])) {
407 if (!empty($curl_info['redirect_url'])) {
408 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
409 } elseif (!empty($curl_info['location'])) {
410 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
414 // Check for redirects in the meta elements of the body if there are no redirects in the header.
416 return $this->finalUrl($url, ++$depth, true);
419 // if the file is too large then exit
420 if ($curl_info["download_content_length"] > 1000000) {
424 // if it isn't a HTML file then exit
425 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
429 $this->profiler->startRecording('network');
432 curl_setopt($ch, CURLOPT_URL, $url);
433 curl_setopt($ch, CURLOPT_HEADER, 0);
434 curl_setopt($ch, CURLOPT_NOBODY, 0);
435 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
436 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
437 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
438 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
440 $body = curl_exec($ch);
443 $this->profiler->stopRecording();
445 if (trim($body) == "") {
449 // Check for redirect in meta elements
450 $doc = new DOMDocument();
451 @$doc->loadHTML($body);
453 $xpath = new DomXPath($doc);
455 $list = $xpath->query("//meta[@content]");
456 foreach ($list as $node) {
458 if ($node->attributes->length) {
459 foreach ($node->attributes as $attribute) {
460 $attr[$attribute->name] = $attribute->value;
464 if (@$attr["http-equiv"] == 'refresh') {
465 $path = $attr["content"];
466 $pathinfo = explode(";", $path);
467 foreach ($pathinfo as $value) {
468 if (substr(strtolower($value), 0, 4) == "url=") {
469 return $this->finalUrl(substr($value, 4), ++$depth);
481 * @param int $redirects The recursion counter for internal use - default 0
483 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
485 public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
487 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar, $redirects);
489 return $ret->getBody();
495 * @param int $redirects The recursion counter for internal use - default 0
497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
499 public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
504 'timeout' => $timeout,
505 'accept_content' => $accept_content,
506 'cookiejar' => $cookiejar
514 public function getUserAgent()
517 FRIENDICA_PLATFORM . " '" .
518 FRIENDICA_CODENAME . "' " .
519 FRIENDICA_VERSION . '-' .
520 DB_UPDATE_VERSION . '; ' .