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 $curlOptions[CURLOPT_HTTPHEADER][] = ['Accept: ' . $opts['accept_content']];
108 if (!empty($opts['header'])) {
109 $curlOptions[CURLOPT_HTTPHEADER][] = $opts['header'];
112 $curlOptions[CURLOPT_RETURNTRANSFER] = true;
113 $curlOptions[CURLOPT_USERAGENT] = $this->getUserAgent();
115 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
118 $curlOptions[CURLOPT_RANGE] = '0-' . $range;
121 // Without this setting it seems as if some webservers send compressed content
122 // This seems to confuse curl so that it shows this uncompressed.
123 /// @todo We could possibly set this value to "gzip" or something similar
124 $curlOptions[CURLOPT_ENCODING] = '';
126 if (!empty($opts['headers'])) {
127 $curlOptions[CURLOPT_HTTPHEADER][] = $opts['headers'];
130 if (!empty($opts['nobody'])) {
131 $curlOptions[CURLOPT_NOBODY] = $opts['nobody'];
134 $curlOptions[CURLOPT_CONNECTTIMEOUT] = 10;
136 if (!empty($opts['timeout'])) {
137 $curlOptions[CURLOPT_TIMEOUT] = $opts['timeout'];
139 $curl_time = $this->config->get('system', 'curl_timeout', 60);
140 $curlOptions[CURLOPT_TIMEOUT] = intval($curl_time);
143 // by default we will allow self-signed certs
144 // but you can override this
146 $check_cert = $this->config->get('system', 'verifyssl');
147 $curlOptions[CURLOPT_SSL_VERIFYPEER] = ($check_cert) ? true : false;
150 $curlOptions[CURLOPT_SSL_VERIFYHOST] = 2;
153 $proxy = $this->config->get('system', 'proxy');
155 if (!empty($proxy)) {
156 $curlOptions[CURLOPT_HTTPPROXYTUNNEL] = 1;
157 $curlOptions[CURLOPT_PROXY] = $proxy;
158 $proxyuser = $this->config->get('system', 'proxyuser');
160 if (!empty($proxyuser)) {
161 $curlOptions[CURLOPT_PROXYUSERPWD] = $proxyuser;
165 if ($this->config->get('system', 'ipv4_resolve', false)) {
166 $curlOptions[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
170 $curlOptions[CURLOPT_BINARYTRANSFER] = 1;
173 $logger = $this->logger;
175 $onRedirect = function(
176 RequestInterface $request,
177 ResponseInterface $response,
180 $logger->notice('Curl redirect.', ['url' => $request->getUri(), 'to' => $uri]);
183 $onHeaders = function (ResponseInterface $response) use ($opts) {
184 if (!empty($opts['content_length']) &&
185 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
186 throw new TransferException('The file is too big!');
190 $client = new Client([
191 'allow_redirect' => [
193 'on_redirect' => $onRedirect,
194 'on_headers' => $onHeaders,
195 'track_redirect' => true,
199 'curl' => $curlOptions
203 $response = $client->get($url);
204 return new GuzzleResponse($response, $url);
205 } catch (TransferException $exception) {
206 if ($exception instanceof RequestException &&
207 $exception->hasResponse()) {
208 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
210 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), '');
213 $this->profiler->saveTimestamp($stamp1, 'network');
220 * @param int $redirects The recursion counter for internal use - default 0
222 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
226 $stamp1 = microtime(true);
228 if (Network::isUrlBlocked($url)) {
229 $this->logger->info('Domain is blocked.' . ['url' => $url]);
230 return CurlResult::createErrorCurl($url);
233 $ch = curl_init($url);
235 if (($redirects > 8) || (!$ch)) {
236 return CurlResult::createErrorCurl($url);
239 $this->logger->debug('Post_url: start.', ['url' => $url]);
241 curl_setopt($ch, CURLOPT_HEADER, true);
242 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
243 curl_setopt($ch, CURLOPT_POST, 1);
244 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
245 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
247 if ($this->config->get('system', 'ipv4_resolve', false)) {
248 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
251 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
253 if (intval($timeout)) {
254 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
256 $curl_time = $this->config->get('system', 'curl_timeout', 60);
257 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
260 if (!empty($headers)) {
261 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
264 $check_cert = $this->config->get('system', 'verifyssl');
265 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
268 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
271 $proxy = $this->config->get('system', 'proxy');
273 if (!empty($proxy)) {
274 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
275 curl_setopt($ch, CURLOPT_PROXY, $proxy);
276 $proxyuser = $this->config->get('system', 'proxyuser');
277 if (!empty($proxyuser)) {
278 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
282 // don't let curl abort the entire application
283 // if it throws any errors.
285 $s = @curl_exec($ch);
287 $curl_info = curl_getinfo($ch);
289 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
291 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
293 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
295 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
300 $this->profiler->saveTimestamp($stamp1, 'network');
302 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
303 if ($curlResponse->getReturnCode() == 417) {
306 if (empty($headers)) {
307 $headers = ['Expect:'];
309 if (!in_array('Expect:', $headers)) {
310 array_push($headers, 'Expect:');
313 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
314 return $this->post($url, $params, $headers, $redirects, $timeout);
317 $this->logger->debug('Post_url: End.', ['url' => $url]);
319 return $curlResponse;
325 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
327 if (Network::isUrlBlocked($url)) {
328 $this->logger->info('Domain is blocked.', ['url' => $url]);
332 if (Network::isRedirectBlocked($url)) {
333 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
337 $url = Network::stripTrackingQueryParams($url);
343 $url = trim($url, "'");
345 $stamp1 = microtime(true);
348 curl_setopt($ch, CURLOPT_URL, $url);
349 curl_setopt($ch, CURLOPT_HEADER, 1);
350 curl_setopt($ch, CURLOPT_NOBODY, 1);
351 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
352 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
353 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
354 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
357 $curl_info = @curl_getinfo($ch);
358 $http_code = $curl_info['http_code'];
361 $this->profiler->saveTimestamp($stamp1, "network");
363 if ($http_code == 0) {
367 if (in_array($http_code, ['301', '302'])) {
368 if (!empty($curl_info['redirect_url'])) {
369 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
370 } elseif (!empty($curl_info['location'])) {
371 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
375 // Check for redirects in the meta elements of the body if there are no redirects in the header.
377 return $this->finalUrl($url, ++$depth, true);
380 // if the file is too large then exit
381 if ($curl_info["download_content_length"] > 1000000) {
385 // if it isn't a HTML file then exit
386 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
390 $stamp1 = microtime(true);
393 curl_setopt($ch, CURLOPT_URL, $url);
394 curl_setopt($ch, CURLOPT_HEADER, 0);
395 curl_setopt($ch, CURLOPT_NOBODY, 0);
396 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
397 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
398 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
399 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
401 $body = curl_exec($ch);
404 $this->profiler->saveTimestamp($stamp1, "network");
406 if (trim($body) == "") {
410 // Check for redirect in meta elements
411 $doc = new DOMDocument();
412 @$doc->loadHTML($body);
414 $xpath = new DomXPath($doc);
416 $list = $xpath->query("//meta[@content]");
417 foreach ($list as $node) {
419 if ($node->attributes->length) {
420 foreach ($node->attributes as $attribute) {
421 $attr[$attribute->name] = $attribute->value;
425 if (@$attr["http-equiv"] == 'refresh') {
426 $path = $attr["content"];
427 $pathinfo = explode(";", $path);
428 foreach ($pathinfo as $value) {
429 if (substr(strtolower($value), 0, 4) == "url=") {
430 return $this->finalUrl(substr($value, 4), ++$depth);
442 * @param int $redirects The recursion counter for internal use - default 0
444 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
446 public function fetch(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
448 $ret = $this->fetchFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
450 return $ret->getBody();
456 * @param int $redirects The recursion counter for internal use - default 0
458 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
460 public function fetchFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
466 'timeout' => $timeout,
467 'accept_content' => $accept_content,
468 'cookiejar' => $cookiejar
476 public function getUserAgent()
479 FRIENDICA_PLATFORM . " '" .
480 FRIENDICA_CODENAME . "' " .
481 FRIENDICA_VERSION . '-' .
482 DB_UPDATE_VERSION . '; ' .