3 * @copyright Copyright (C) 2020, Friendica
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();
64 public function get(string $url, bool $binary = false, array $opts = [])
66 $stamp1 = microtime(true);
68 if (strlen($url) > 1000) {
69 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
70 return CurlResult::createErrorCurl(substr($url, 0, 200));
74 $parts = parse_url($url);
75 $path_parts = explode('/', $parts['path'] ?? '');
76 foreach ($path_parts as $part) {
77 if (strlen($part) <> mb_strlen($part)) {
78 $parts2[] = rawurlencode($part);
83 $parts['path'] = implode('/', $parts2);
84 $url = Network::unparseURL($parts);
86 if (Network::isUrlBlocked($url)) {
87 $this->logger->info('Domain is blocked.', ['url' => $url]);
88 return CurlResult::createErrorCurl($url);
93 $curlOptions[CURLOPT_HEADER] = true;
95 if (!empty($opts['cookiejar'])) {
96 $curlOptions[CURLOPT_COOKIEJAR] = $opts["cookiejar"];
97 $curlOptions[CURLOPT_COOKIEFILE] = $opts["cookiejar"];
100 // These settings aren't needed. We're following the location already.
101 // $curlOptions[CURLOPT_FOLLOWLOCATION] =true;
102 // $curlOptions[CURLOPT_MAXREDIRS] = 5;
104 if (!empty($opts['accept_content'])) {
105 if (empty($curlOptions[CURLOPT_HTTPHEADER])) {
106 $curlOptions[CURLOPT_HTTPHEADER] = [];
108 array_push($curlOptions[CURLOPT_HTTPHEADER], 'Accept: ' . $opts['accept_content']);
111 if (!empty($opts['header'])) {
112 if (empty($curlOptions[CURLOPT_HTTPHEADER])) {
113 $curlOptions[CURLOPT_HTTPHEADER] = [];
115 $curlOptions[CURLOPT_HTTPHEADER] = array_merge($opts['header'], $curlOptions[CURLOPT_HTTPHEADER]);
118 $curlOptions[CURLOPT_RETURNTRANSFER] = true;
119 $curlOptions[CURLOPT_USERAGENT] = $this->getUserAgent();
121 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
124 $curlOptions[CURLOPT_RANGE] = '0-' . $range;
127 // Without this setting it seems as if some webservers send compressed content
128 // This seems to confuse curl so that it shows this uncompressed.
129 /// @todo We could possibly set this value to "gzip" or something similar
130 $curlOptions[CURLOPT_ENCODING] = '';
132 if (!empty($opts['headers'])) {
133 if (empty($curlOptions[CURLOPT_HTTPHEADER])) {
134 $curlOptions[CURLOPT_HTTPHEADER] = [];
136 $curlOptions[CURLOPT_HTTPHEADER] = array_merge($opts['headers'], $curlOptions[CURLOPT_HTTPHEADER]);
139 if (!empty($opts['nobody'])) {
140 $curlOptions[CURLOPT_NOBODY] = $opts['nobody'];
143 $curlOptions[CURLOPT_CONNECTTIMEOUT] = 10;
145 if (!empty($opts['timeout'])) {
146 $curlOptions[CURLOPT_TIMEOUT] = $opts['timeout'];
148 $curl_time = $this->config->get('system', 'curl_timeout', 60);
149 $curlOptions[CURLOPT_TIMEOUT] = intval($curl_time);
152 // by default we will allow self-signed certs
153 // but you can override this
155 $check_cert = $this->config->get('system', 'verifyssl');
156 $curlOptions[CURLOPT_SSL_VERIFYPEER] = ($check_cert) ? true : false;
159 $curlOptions[CURLOPT_SSL_VERIFYHOST] = 2;
162 $proxy = $this->config->get('system', 'proxy');
164 if (!empty($proxy)) {
165 $curlOptions[CURLOPT_HTTPPROXYTUNNEL] = 1;
166 $curlOptions[CURLOPT_PROXY] = $proxy;
167 $proxyuser = $this->config->get('system', 'proxyuser');
169 if (!empty($proxyuser)) {
170 $curlOptions[CURLOPT_PROXYUSERPWD] = $proxyuser;
174 if ($this->config->get('system', 'ipv4_resolve', false)) {
175 $curlOptions[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
179 $curlOptions[CURLOPT_BINARYTRANSFER] = 1;
182 $onRedirect = function(
183 RequestInterface $request,
184 ResponseInterface $response,
187 $this->logger->notice('Curl redirect.', ['url' => $request->getUri(), 'to' => $uri]);
190 $onHeaders = function (ResponseInterface $response) use ($opts) {
191 if (!empty($opts['content_length']) &&
192 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
193 throw new TransferException('The file is too big!');
197 $client = new Client([
198 'allow_redirect' => [
200 'on_redirect' => $onRedirect,
201 'track_redirect' => true,
205 'on_headers' => $onHeaders,
206 'sink' => tempnam(get_temppath(), 'guzzle'),
207 'curl' => $curlOptions
211 $response = $client->get($url);
212 return new GuzzleResponse($response, $url);
213 } catch (TransferException $exception) {
214 if ($exception instanceof RequestException &&
215 $exception->hasResponse()) {
216 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), $exception->getMessage());
218 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), $exception->getMessage());
221 $this->profiler->saveTimestamp($stamp1, 'network');
228 * @param int $redirects The recursion counter for internal use - default 0
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
232 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
234 $stamp1 = microtime(true);
236 if (Network::isUrlBlocked($url)) {
237 $this->logger->info('Domain is blocked.' . ['url' => $url]);
238 return CurlResult::createErrorCurl($url);
241 $ch = curl_init($url);
243 if (($redirects > 8) || (!$ch)) {
244 return CurlResult::createErrorCurl($url);
247 $this->logger->debug('Post_url: start.', ['url' => $url]);
249 curl_setopt($ch, CURLOPT_HEADER, true);
250 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
251 curl_setopt($ch, CURLOPT_POST, 1);
252 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
253 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
255 if ($this->config->get('system', 'ipv4_resolve', false)) {
256 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
259 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
261 if (intval($timeout)) {
262 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
264 $curl_time = $this->config->get('system', 'curl_timeout', 60);
265 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
268 if (!empty($headers)) {
269 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
272 $check_cert = $this->config->get('system', 'verifyssl');
273 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
276 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
279 $proxy = $this->config->get('system', 'proxy');
281 if (!empty($proxy)) {
282 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
283 curl_setopt($ch, CURLOPT_PROXY, $proxy);
284 $proxyuser = $this->config->get('system', 'proxyuser');
285 if (!empty($proxyuser)) {
286 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
290 // don't let curl abort the entire application
291 // if it throws any errors.
293 $s = @curl_exec($ch);
295 $curl_info = curl_getinfo($ch);
297 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
299 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
301 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
303 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
308 $this->profiler->saveTimestamp($stamp1, 'network');
310 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
311 if ($curlResponse->getReturnCode() == 417) {
314 if (empty($headers)) {
315 $headers = ['Expect:'];
317 if (!in_array('Expect:', $headers)) {
318 array_push($headers, 'Expect:');
321 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
322 return $this->post($url, $params, $headers, $redirects, $timeout);
325 $this->logger->debug('Post_url: End.', ['url' => $url]);
327 return $curlResponse;
333 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
335 if (Network::isUrlBlocked($url)) {
336 $this->logger->info('Domain is blocked.', ['url' => $url]);
340 if (Network::isRedirectBlocked($url)) {
341 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
345 $url = Network::stripTrackingQueryParams($url);
351 $url = trim($url, "'");
353 $stamp1 = microtime(true);
356 curl_setopt($ch, CURLOPT_URL, $url);
357 curl_setopt($ch, CURLOPT_HEADER, 1);
358 curl_setopt($ch, CURLOPT_NOBODY, 1);
359 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
360 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
361 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
362 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
365 $curl_info = @curl_getinfo($ch);
366 $http_code = $curl_info['http_code'];
369 $this->profiler->saveTimestamp($stamp1, "network");
371 if ($http_code == 0) {
375 if (in_array($http_code, ['301', '302'])) {
376 if (!empty($curl_info['redirect_url'])) {
377 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
378 } elseif (!empty($curl_info['location'])) {
379 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
383 // Check for redirects in the meta elements of the body if there are no redirects in the header.
385 return $this->finalUrl($url, ++$depth, true);
388 // if the file is too large then exit
389 if ($curl_info["download_content_length"] > 1000000) {
393 // if it isn't a HTML file then exit
394 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
398 $stamp1 = microtime(true);
401 curl_setopt($ch, CURLOPT_URL, $url);
402 curl_setopt($ch, CURLOPT_HEADER, 0);
403 curl_setopt($ch, CURLOPT_NOBODY, 0);
404 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
405 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
406 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
407 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
409 $body = curl_exec($ch);
412 $this->profiler->saveTimestamp($stamp1, "network");
414 if (trim($body) == "") {
418 // Check for redirect in meta elements
419 $doc = new DOMDocument();
420 @$doc->loadHTML($body);
422 $xpath = new DomXPath($doc);
424 $list = $xpath->query("//meta[@content]");
425 foreach ($list as $node) {
427 if ($node->attributes->length) {
428 foreach ($node->attributes as $attribute) {
429 $attr[$attribute->name] = $attribute->value;
433 if (@$attr["http-equiv"] == 'refresh') {
434 $path = $attr["content"];
435 $pathinfo = explode(";", $path);
436 foreach ($pathinfo as $value) {
437 if (substr(strtolower($value), 0, 4) == "url=") {
438 return $this->finalUrl(substr($value, 4), ++$depth);
450 * @param int $redirects The recursion counter for internal use - default 0
452 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
454 public function fetch(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
456 $ret = $this->fetchFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
458 return $ret->getBody();
464 * @param int $redirects The recursion counter for internal use - default 0
466 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
468 public function fetchFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
474 'timeout' => $timeout,
475 'accept_content' => $accept_content,
476 'cookiejar' => $cookiejar
484 public function getUserAgent()
487 FRIENDICA_PLATFORM . " '" .
488 FRIENDICA_CODENAME . "' " .
489 FRIENDICA_VERSION . '-' .
490 DB_UPDATE_VERSION . '; ' .