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 $onRedirect = function(
201 RequestInterface $request,
202 ResponseInterface $response,
205 $this->logger->notice('Curl redirect.', ['url' => $request->getUri(), 'to' => $uri]);
208 $onHeaders = function (ResponseInterface $response) use ($opts) {
209 if (!empty($opts['content_length']) &&
210 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
211 throw new TransferException('The file is too big!');
215 $client = new Client([
216 'allow_redirect' => [
218 'on_redirect' => $onRedirect,
219 'track_redirect' => true,
223 'on_headers' => $onHeaders,
224 'sink' => tempnam(get_temppath(), 'guzzle'),
225 'curl' => $curlOptions
229 $response = $client->get($url);
230 return new GuzzleResponse($response, $url);
231 } catch (TransferException $exception) {
232 if ($exception instanceof RequestException &&
233 $exception->hasResponse()) {
234 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), $exception->getMessage());
236 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), $exception->getMessage());
239 $this->profiler->stopRecording();
246 * @param int $redirects The recursion counter for internal use - default 0
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
252 $this->profiler->startRecording('network');
254 if (Network::isLocalLink($url)) {
255 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
258 if (Network::isUrlBlocked($url)) {
259 $this->logger->info('Domain is blocked.' . ['url' => $url]);
260 $this->profiler->stopRecording();
261 return CurlResult::createErrorCurl($url);
264 $ch = curl_init($url);
266 if (($redirects > 8) || (!$ch)) {
267 $this->profiler->stopRecording();
268 return CurlResult::createErrorCurl($url);
271 $this->logger->debug('Post_url: start.', ['url' => $url]);
273 curl_setopt($ch, CURLOPT_HEADER, true);
274 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
275 curl_setopt($ch, CURLOPT_POST, 1);
276 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
277 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
279 if ($this->config->get('system', 'ipv4_resolve', false)) {
280 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
283 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
285 if (intval($timeout)) {
286 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
288 $curl_time = $this->config->get('system', 'curl_timeout', 60);
289 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
292 if (!empty($headers)) {
293 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
296 $check_cert = $this->config->get('system', 'verifyssl');
297 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
300 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
303 $proxy = $this->config->get('system', 'proxy');
305 if (!empty($proxy)) {
306 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
307 curl_setopt($ch, CURLOPT_PROXY, $proxy);
308 $proxyuser = $this->config->get('system', 'proxyuser');
309 if (!empty($proxyuser)) {
310 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
314 // don't let curl abort the entire application
315 // if it throws any errors.
317 $s = @curl_exec($ch);
319 $curl_info = curl_getinfo($ch);
321 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
323 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
325 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
327 $this->profiler->stopRecording();
328 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
333 $this->profiler->stopRecording();
335 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
336 if ($curlResponse->getReturnCode() == 417) {
339 if (empty($headers)) {
340 $headers = ['Expect:'];
342 if (!in_array('Expect:', $headers)) {
343 array_push($headers, 'Expect:');
346 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
347 return $this->post($url, $params, $headers, $redirects, $timeout);
350 $this->logger->debug('Post_url: End.', ['url' => $url]);
352 return $curlResponse;
358 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
360 if (Network::isLocalLink($url)) {
361 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
364 if (Network::isUrlBlocked($url)) {
365 $this->logger->info('Domain is blocked.', ['url' => $url]);
369 if (Network::isRedirectBlocked($url)) {
370 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
374 $url = Network::stripTrackingQueryParams($url);
380 $url = trim($url, "'");
382 $this->profiler->startRecording('network');
385 curl_setopt($ch, CURLOPT_URL, $url);
386 curl_setopt($ch, CURLOPT_HEADER, 1);
387 curl_setopt($ch, CURLOPT_NOBODY, 1);
388 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
389 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
390 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
391 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
394 $curl_info = @curl_getinfo($ch);
395 $http_code = $curl_info['http_code'];
398 $this->profiler->stopRecording();
400 if ($http_code == 0) {
404 if (in_array($http_code, ['301', '302'])) {
405 if (!empty($curl_info['redirect_url'])) {
406 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
407 } elseif (!empty($curl_info['location'])) {
408 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
412 // Check for redirects in the meta elements of the body if there are no redirects in the header.
414 return $this->finalUrl($url, ++$depth, true);
417 // if the file is too large then exit
418 if ($curl_info["download_content_length"] > 1000000) {
422 // if it isn't a HTML file then exit
423 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
427 $this->profiler->startRecording('network');
430 curl_setopt($ch, CURLOPT_URL, $url);
431 curl_setopt($ch, CURLOPT_HEADER, 0);
432 curl_setopt($ch, CURLOPT_NOBODY, 0);
433 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
434 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
435 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
436 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
438 $body = curl_exec($ch);
441 $this->profiler->stopRecording();
443 if (trim($body) == "") {
447 // Check for redirect in meta elements
448 $doc = new DOMDocument();
449 @$doc->loadHTML($body);
451 $xpath = new DomXPath($doc);
453 $list = $xpath->query("//meta[@content]");
454 foreach ($list as $node) {
456 if ($node->attributes->length) {
457 foreach ($node->attributes as $attribute) {
458 $attr[$attribute->name] = $attribute->value;
462 if (@$attr["http-equiv"] == 'refresh') {
463 $path = $attr["content"];
464 $pathinfo = explode(";", $path);
465 foreach ($pathinfo as $value) {
466 if (substr(strtolower($value), 0, 4) == "url=") {
467 return $this->finalUrl(substr($value, 4), ++$depth);
479 * @param int $redirects The recursion counter for internal use - default 0
481 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
483 public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
485 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar, $redirects);
487 return $ret->getBody();
493 * @param int $redirects The recursion counter for internal use - default 0
495 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
497 public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
502 'timeout' => $timeout,
503 'accept_content' => $accept_content,
504 'cookiejar' => $cookiejar
512 public function getUserAgent()
515 FRIENDICA_PLATFORM . " '" .
516 FRIENDICA_CODENAME . "' " .
517 FRIENDICA_VERSION . '-' .
518 DB_UPDATE_VERSION . '; ' .