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 Psr\Http\Message\RequestInterface;
34 use Psr\Http\Message\ResponseInterface;
35 use Psr\Http\Message\UriInterface;
36 use Psr\Log\LoggerInterface;
39 * Performs HTTP requests to a given URL
41 class HTTPRequest implements IHTTPRequest
43 /** @var LoggerInterface */
52 public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App\BaseURL $baseUrl)
54 $this->logger = $logger;
55 $this->profiler = $profiler;
56 $this->config = $config;
57 $this->baseUrl = $baseUrl->get();
63 public function get(string $url, bool $binary = false, array $opts = [])
65 $stamp1 = microtime(true);
67 if (strlen($url) > 1000) {
68 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
69 return CurlResult::createErrorCurl(substr($url, 0, 200));
73 $parts = parse_url($url);
74 $path_parts = explode('/', $parts['path'] ?? '');
75 foreach ($path_parts as $part) {
76 if (strlen($part) <> mb_strlen($part)) {
77 $parts2[] = rawurlencode($part);
82 $parts['path'] = implode('/', $parts2);
83 $url = Network::unparseURL($parts);
85 if (Network::isUrlBlocked($url)) {
86 $this->logger->info('Domain is blocked.', ['url' => $url]);
87 return CurlResult::createErrorCurl($url);
92 $curlOptions[CURLOPT_HEADER] = true;
94 if (!empty($opts['cookiejar'])) {
95 $curlOptions[CURLOPT_COOKIEJAR] = $opts["cookiejar"];
96 $curlOptions[CURLOPT_COOKIEFILE] = $opts["cookiejar"];
99 // These settings aren't needed. We're following the location already.
100 // $curlOptions[CURLOPT_FOLLOWLOCATION] =true;
101 // $curlOptions[CURLOPT_MAXREDIRS] = 5;
103 if (!empty($opts['accept_content'])) {
104 $curlOptions[CURLOPT_HTTPHEADER][] = ['Accept: ' . $opts['accept_content']];
107 if (!empty($opts['header'])) {
108 $curlOptions[CURLOPT_HTTPHEADER][] = $opts['header'];
111 $curlOptions[CURLOPT_RETURNTRANSFER] = true;
112 $curlOptions[CURLOPT_USERAGENT] = $this->getUserAgent();
114 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
117 $curlOptions[CURLOPT_RANGE] = '0-' . $range;
120 // Without this setting it seems as if some webservers send compressed content
121 // This seems to confuse curl so that it shows this uncompressed.
122 /// @todo We could possibly set this value to "gzip" or something similar
123 $curlOptions[CURLOPT_ENCODING] = '';
125 if (!empty($opts['headers'])) {
126 $curlOptions[CURLOPT_HTTPHEADER][] = $opts['headers'];
129 if (!empty($opts['nobody'])) {
130 $curlOptions[CURLOPT_NOBODY] = $opts['nobody'];
133 $curlOptions[CURLOPT_CONNECTTIMEOUT] = 10;
135 if (!empty($opts['timeout'])) {
136 $curlOptions[CURLOPT_TIMEOUT] = $opts['timeout'];
138 $curl_time = $this->config->get('system', 'curl_timeout', 60);
139 $curlOptions[CURLOPT_TIMEOUT] = intval($curl_time);
142 // by default we will allow self-signed certs
143 // but you can override this
145 $check_cert = $this->config->get('system', 'verifyssl');
146 $curlOptions[CURLOPT_SSL_VERIFYPEER] = ($check_cert) ? true : false;
149 $curlOptions[CURLOPT_SSL_VERIFYHOST] = 2;
152 $proxy = $this->config->get('system', 'proxy');
154 if (!empty($proxy)) {
155 $curlOptions[CURLOPT_HTTPPROXYTUNNEL] = 1;
156 $curlOptions[CURLOPT_PROXY] = $proxy;
157 $proxyuser = $this->config->get('system', 'proxyuser');
159 if (!empty($proxyuser)) {
160 $curlOptions[CURLOPT_PROXYUSERPWD] = $proxyuser;
164 if ($this->config->get('system', 'ipv4_resolve', false)) {
165 $curlOptions[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
169 $curlOptions[CURLOPT_BINARYTRANSFER] = 1;
172 $onRedirect = function(
173 RequestInterface $request,
174 ResponseInterface $response,
177 $this->logger->notice('Curl redirect.', ['url' => $request->getUri(), 'to' => $uri]);
180 $client = new Client([
181 'allow_redirect' => [
183 'on_redirect' => $onRedirect,
184 'track_redirect' => true,
188 'curl' => $curlOptions
192 $response = $client->get($url);
193 return new GuzzleResponse($response, $url);
194 } catch (RequestException $exception) {
195 if ($exception->hasResponse()) {
196 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), $exception->getMessage());
198 return new GuzzleResponse(null, $url, $exception->getCode(), $exception->getMessage());
201 $this->profiler->saveTimestamp($stamp1, 'network');
208 * @param int $redirects The recursion counter for internal use - default 0
210 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
212 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
214 $stamp1 = microtime(true);
216 if (Network::isUrlBlocked($url)) {
217 $this->logger->info('Domain is blocked.' . ['url' => $url]);
218 return CurlResult::createErrorCurl($url);
221 $ch = curl_init($url);
223 if (($redirects > 8) || (!$ch)) {
224 return CurlResult::createErrorCurl($url);
227 $this->logger->debug('Post_url: start.', ['url' => $url]);
229 curl_setopt($ch, CURLOPT_HEADER, true);
230 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
231 curl_setopt($ch, CURLOPT_POST, 1);
232 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
233 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
235 if ($this->config->get('system', 'ipv4_resolve', false)) {
236 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
239 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
241 if (intval($timeout)) {
242 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
244 $curl_time = $this->config->get('system', 'curl_timeout', 60);
245 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
248 if (!empty($headers)) {
249 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
252 $check_cert = $this->config->get('system', 'verifyssl');
253 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
256 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
259 $proxy = $this->config->get('system', 'proxy');
261 if (!empty($proxy)) {
262 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
263 curl_setopt($ch, CURLOPT_PROXY, $proxy);
264 $proxyuser = $this->config->get('system', 'proxyuser');
265 if (!empty($proxyuser)) {
266 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
270 // don't let curl abort the entire application
271 // if it throws any errors.
273 $s = @curl_exec($ch);
275 $curl_info = curl_getinfo($ch);
277 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
279 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
281 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
283 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
288 $this->profiler->saveTimestamp($stamp1, 'network');
290 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
291 if ($curlResponse->getReturnCode() == 417) {
294 if (empty($headers)) {
295 $headers = ['Expect:'];
297 if (!in_array('Expect:', $headers)) {
298 array_push($headers, 'Expect:');
301 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
302 return $this->post($url, $params, $headers, $redirects, $timeout);
305 $this->logger->debug('Post_url: End.', ['url' => $url]);
307 return $curlResponse;
313 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
315 if (Network::isUrlBlocked($url)) {
316 $this->logger->info('Domain is blocked.', ['url' => $url]);
320 if (Network::isRedirectBlocked($url)) {
321 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
325 $url = Network::stripTrackingQueryParams($url);
331 $url = trim($url, "'");
333 $stamp1 = microtime(true);
336 curl_setopt($ch, CURLOPT_URL, $url);
337 curl_setopt($ch, CURLOPT_HEADER, 1);
338 curl_setopt($ch, CURLOPT_NOBODY, 1);
339 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
340 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
341 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
342 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
345 $curl_info = @curl_getinfo($ch);
346 $http_code = $curl_info['http_code'];
349 $this->profiler->saveTimestamp($stamp1, "network");
351 if ($http_code == 0) {
355 if (in_array($http_code, ['301', '302'])) {
356 if (!empty($curl_info['redirect_url'])) {
357 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
358 } elseif (!empty($curl_info['location'])) {
359 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
363 // Check for redirects in the meta elements of the body if there are no redirects in the header.
365 return $this->finalUrl($url, ++$depth, true);
368 // if the file is too large then exit
369 if ($curl_info["download_content_length"] > 1000000) {
373 // if it isn't a HTML file then exit
374 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
378 $stamp1 = microtime(true);
381 curl_setopt($ch, CURLOPT_URL, $url);
382 curl_setopt($ch, CURLOPT_HEADER, 0);
383 curl_setopt($ch, CURLOPT_NOBODY, 0);
384 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
385 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
386 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
387 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
389 $body = curl_exec($ch);
392 $this->profiler->saveTimestamp($stamp1, "network");
394 if (trim($body) == "") {
398 // Check for redirect in meta elements
399 $doc = new DOMDocument();
400 @$doc->loadHTML($body);
402 $xpath = new DomXPath($doc);
404 $list = $xpath->query("//meta[@content]");
405 foreach ($list as $node) {
407 if ($node->attributes->length) {
408 foreach ($node->attributes as $attribute) {
409 $attr[$attribute->name] = $attribute->value;
413 if (@$attr["http-equiv"] == 'refresh') {
414 $path = $attr["content"];
415 $pathinfo = explode(";", $path);
416 foreach ($pathinfo as $value) {
417 if (substr(strtolower($value), 0, 4) == "url=") {
418 return $this->finalUrl(substr($value, 4), ++$depth);
430 * @param int $redirects The recursion counter for internal use - default 0
432 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
434 public function fetch(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
436 $ret = $this->fetchFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
438 return $ret->getBody();
444 * @param int $redirects The recursion counter for internal use - default 0
446 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
448 public function fetchFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
454 'timeout' => $timeout,
455 'accept_content' => $accept_content,
456 'cookiejar' => $cookiejar
465 public function getUserAgent()
468 FRIENDICA_PLATFORM . " '" .
469 FRIENDICA_CODENAME . "' " .
470 FRIENDICA_VERSION . '-' .
471 DB_UPDATE_VERSION . '; ' .