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 $logger = $this->logger;
184 $onRedirect = function(
185 RequestInterface $request,
186 ResponseInterface $response,
189 $logger->notice('Curl redirect.', ['url' => $request->getUri(), 'to' => $uri]);
192 $onHeaders = function (ResponseInterface $response) use ($opts) {
193 if (!empty($opts['content_length']) &&
194 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
195 throw new TransferException('The file is too big!');
199 $client = new Client([
200 'allow_redirect' => [
202 'on_redirect' => $onRedirect,
203 'track_redirect' => true,
207 'on_headers' => $onHeaders,
208 'sink' => tempnam(get_temppath(), 'guzzle'),
209 'curl' => $curlOptions
213 $response = $client->get($url);
214 return new GuzzleResponse($response, $url);
215 } catch (TransferException $exception) {
216 if ($exception instanceof RequestException &&
217 $exception->hasResponse()) {
218 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), $exception->getMessage());
220 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), $exception->getMessage());
223 $this->profiler->saveTimestamp($stamp1, 'network');
230 * @param int $redirects The recursion counter for internal use - default 0
232 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
234 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
236 $stamp1 = microtime(true);
238 if (Network::isUrlBlocked($url)) {
239 $this->logger->info('Domain is blocked.' . ['url' => $url]);
240 return CurlResult::createErrorCurl($url);
243 $ch = curl_init($url);
245 if (($redirects > 8) || (!$ch)) {
246 return CurlResult::createErrorCurl($url);
249 $this->logger->debug('Post_url: start.', ['url' => $url]);
251 curl_setopt($ch, CURLOPT_HEADER, true);
252 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
253 curl_setopt($ch, CURLOPT_POST, 1);
254 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
255 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
257 if ($this->config->get('system', 'ipv4_resolve', false)) {
258 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
261 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
263 if (intval($timeout)) {
264 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
266 $curl_time = $this->config->get('system', 'curl_timeout', 60);
267 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
270 if (!empty($headers)) {
271 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
274 $check_cert = $this->config->get('system', 'verifyssl');
275 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
278 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
281 $proxy = $this->config->get('system', 'proxy');
283 if (!empty($proxy)) {
284 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
285 curl_setopt($ch, CURLOPT_PROXY, $proxy);
286 $proxyuser = $this->config->get('system', 'proxyuser');
287 if (!empty($proxyuser)) {
288 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
292 // don't let curl abort the entire application
293 // if it throws any errors.
295 $s = @curl_exec($ch);
297 $curl_info = curl_getinfo($ch);
299 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
301 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
303 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
305 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
310 $this->profiler->saveTimestamp($stamp1, 'network');
312 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
313 if ($curlResponse->getReturnCode() == 417) {
316 if (empty($headers)) {
317 $headers = ['Expect:'];
319 if (!in_array('Expect:', $headers)) {
320 array_push($headers, 'Expect:');
323 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
324 return $this->post($url, $params, $headers, $redirects, $timeout);
327 $this->logger->debug('Post_url: End.', ['url' => $url]);
329 return $curlResponse;
335 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
337 if (Network::isUrlBlocked($url)) {
338 $this->logger->info('Domain is blocked.', ['url' => $url]);
342 if (Network::isRedirectBlocked($url)) {
343 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
347 $url = Network::stripTrackingQueryParams($url);
353 $url = trim($url, "'");
355 $stamp1 = microtime(true);
358 curl_setopt($ch, CURLOPT_URL, $url);
359 curl_setopt($ch, CURLOPT_HEADER, 1);
360 curl_setopt($ch, CURLOPT_NOBODY, 1);
361 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
362 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
363 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
364 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
367 $curl_info = @curl_getinfo($ch);
368 $http_code = $curl_info['http_code'];
371 $this->profiler->saveTimestamp($stamp1, "network");
373 if ($http_code == 0) {
377 if (in_array($http_code, ['301', '302'])) {
378 if (!empty($curl_info['redirect_url'])) {
379 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
380 } elseif (!empty($curl_info['location'])) {
381 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
385 // Check for redirects in the meta elements of the body if there are no redirects in the header.
387 return $this->finalUrl($url, ++$depth, true);
390 // if the file is too large then exit
391 if ($curl_info["download_content_length"] > 1000000) {
395 // if it isn't a HTML file then exit
396 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
400 $stamp1 = microtime(true);
403 curl_setopt($ch, CURLOPT_URL, $url);
404 curl_setopt($ch, CURLOPT_HEADER, 0);
405 curl_setopt($ch, CURLOPT_NOBODY, 0);
406 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
407 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
408 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
409 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
411 $body = curl_exec($ch);
414 $this->profiler->saveTimestamp($stamp1, "network");
416 if (trim($body) == "") {
420 // Check for redirect in meta elements
421 $doc = new DOMDocument();
422 @$doc->loadHTML($body);
424 $xpath = new DomXPath($doc);
426 $list = $xpath->query("//meta[@content]");
427 foreach ($list as $node) {
429 if ($node->attributes->length) {
430 foreach ($node->attributes as $attribute) {
431 $attr[$attribute->name] = $attribute->value;
435 if (@$attr["http-equiv"] == 'refresh') {
436 $path = $attr["content"];
437 $pathinfo = explode(";", $path);
438 foreach ($pathinfo as $value) {
439 if (substr(strtolower($value), 0, 4) == "url=") {
440 return $this->finalUrl(substr($value, 4), ++$depth);
452 * @param int $redirects The recursion counter for internal use - default 0
454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
456 public function fetch(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
458 $ret = $this->fetchFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
460 return $ret->getBody();
466 * @param int $redirects The recursion counter for internal use - default 0
468 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
470 public function fetchFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
476 'timeout' => $timeout,
477 'accept_content' => $accept_content,
478 'cookiejar' => $cookiejar
486 public function getUserAgent()
489 FRIENDICA_PLATFORM . " '" .
490 FRIENDICA_CODENAME . "' " .
491 FRIENDICA_VERSION . '-' .
492 DB_UPDATE_VERSION . '; ' .