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;
26 use Friendica\Core\Config\IConfig;
27 use Friendica\Core\System;
28 use Friendica\Util\Network;
29 use Friendica\Util\Profiler;
30 use GuzzleHttp\Client;
31 use GuzzleHttp\Cookie\FileCookieJar;
32 use GuzzleHttp\Exception\RequestException;
33 use GuzzleHttp\Exception\TransferException;
34 use GuzzleHttp\RequestOptions;
35 use Psr\Http\Message\ResponseInterface;
36 use Psr\Log\LoggerInterface;
39 * Performs HTTP requests to a given URL
41 class HTTPClient implements IHTTPClient
43 /** @var LoggerInterface */
54 public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, string $userAgent, Client $client)
56 $this->logger = $logger;
57 $this->profiler = $profiler;
58 $this->config = $config;
59 $this->userAgent = $userAgent;
60 $this->client = $client;
63 protected function request(string $method, string $url, array $opts = [])
65 $this->profiler->startRecording('network');
67 if (Network::isLocalLink($url)) {
68 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
71 if (strlen($url) > 1000) {
72 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
73 $this->profiler->stopRecording();
74 return CurlResult::createErrorCurl(substr($url, 0, 200));
78 $parts = parse_url($url);
79 $path_parts = explode('/', $parts['path'] ?? '');
80 foreach ($path_parts as $part) {
81 if (strlen($part) <> mb_strlen($part)) {
82 $parts2[] = rawurlencode($part);
87 $parts['path'] = implode('/', $parts2);
88 $url = Network::unparseURL($parts);
90 if (Network::isUrlBlocked($url)) {
91 $this->logger->info('Domain is blocked.', ['url' => $url]);
92 $this->profiler->stopRecording();
93 return CurlResult::createErrorCurl($url);
98 if (!empty($opts['cookiejar'])) {
99 $jar = new FileCookieJar($opts['cookiejar']);
100 $conf[RequestOptions::COOKIES] = $jar;
103 if (!empty($opts['accept_content'])) {
104 array_push($curlOptions[CURLOPT_HTTPHEADER], 'Accept: ' . $opts['accept_content']);
107 if (!empty($opts['header'])) {
108 $curlOptions[CURLOPT_HTTPHEADER] = array_merge($opts['header'], $curlOptions[CURLOPT_HTTPHEADER]);
111 $curlOptions[CURLOPT_USERAGENT] = $this->userAgent;
113 if (!empty($opts['headers'])) {
114 $this->logger->notice('Wrong option \'headers\' used.');
115 $curlOptions[CURLOPT_HTTPHEADER] = array_merge($opts['headers'], $curlOptions[CURLOPT_HTTPHEADER]);
118 if (!empty($opts['timeout'])) {
119 $curlOptions[CURLOPT_TIMEOUT] = $opts['timeout'];
122 $onHeaders = function (ResponseInterface $response) use ($opts) {
123 if (!empty($opts['content_length']) &&
124 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
125 throw new TransferException('The file is too big!');
130 $response = $this->client->$method($url, [
131 'on_headers' => $onHeaders,
132 'curl' => $curlOptions,
134 return new GuzzleResponse($response, $url);
135 } catch (TransferException $exception) {
136 if ($exception instanceof RequestException &&
137 $exception->hasResponse()) {
138 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
140 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), '');
143 $this->profiler->stopRecording();
149 * @throws HTTPException\InternalServerErrorException
151 public function head(string $url, array $opts = [])
153 return $this->request('head', $url, $opts);
159 public function get(string $url, array $opts = [])
161 return $this->request('get', $url, $opts);
167 * @param int $redirects The recursion counter for internal use - default 0
169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
171 public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
173 $this->profiler->startRecording('network');
175 if (Network::isLocalLink($url)) {
176 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
179 if (Network::isUrlBlocked($url)) {
180 $this->logger->info('Domain is blocked.' . ['url' => $url]);
181 $this->profiler->stopRecording();
182 return CurlResult::createErrorCurl($url);
185 $ch = curl_init($url);
187 if (($redirects > 8) || (!$ch)) {
188 $this->profiler->stopRecording();
189 return CurlResult::createErrorCurl($url);
192 $this->logger->debug('Post_url: start.', ['url' => $url]);
194 curl_setopt($ch, CURLOPT_HEADER, true);
195 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
196 curl_setopt($ch, CURLOPT_POST, 1);
197 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
198 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
200 if ($this->config->get('system', 'ipv4_resolve', false)) {
201 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
204 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
206 if (intval($timeout)) {
207 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
209 $curl_time = $this->config->get('system', 'curl_timeout', 60);
210 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
213 if (!empty($headers)) {
214 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
217 $check_cert = $this->config->get('system', 'verifyssl');
218 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
221 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
224 $proxy = $this->config->get('system', 'proxy');
226 if (!empty($proxy)) {
227 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
228 curl_setopt($ch, CURLOPT_PROXY, $proxy);
229 $proxyuser = $this->config->get('system', 'proxyuser');
230 if (!empty($proxyuser)) {
231 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
235 // don't let curl abort the entire application
236 // if it throws any errors.
238 $s = @curl_exec($ch);
240 $curl_info = curl_getinfo($ch);
242 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
244 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
246 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
248 $this->profiler->stopRecording();
249 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
254 $this->profiler->stopRecording();
256 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
257 if ($curlResponse->getReturnCode() == 417) {
260 if (empty($headers)) {
261 $headers = ['Expect:'];
263 if (!in_array('Expect:', $headers)) {
264 array_push($headers, 'Expect:');
267 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
268 return $this->post($url, $params, $headers, $redirects, $timeout);
271 $this->logger->debug('Post_url: End.', ['url' => $url]);
273 return $curlResponse;
279 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
281 if (Network::isLocalLink($url)) {
282 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
285 if (Network::isUrlBlocked($url)) {
286 $this->logger->info('Domain is blocked.', ['url' => $url]);
290 if (Network::isRedirectBlocked($url)) {
291 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
295 $url = Network::stripTrackingQueryParams($url);
301 $url = trim($url, "'");
303 $this->profiler->startRecording('network');
306 curl_setopt($ch, CURLOPT_URL, $url);
307 curl_setopt($ch, CURLOPT_HEADER, 1);
308 curl_setopt($ch, CURLOPT_NOBODY, 1);
309 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
310 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
311 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
312 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
315 $curl_info = @curl_getinfo($ch);
316 $http_code = $curl_info['http_code'];
319 $this->profiler->stopRecording();
321 if ($http_code == 0) {
325 if (in_array($http_code, ['301', '302'])) {
326 if (!empty($curl_info['redirect_url'])) {
327 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
328 } elseif (!empty($curl_info['location'])) {
329 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
333 // Check for redirects in the meta elements of the body if there are no redirects in the header.
335 return $this->finalUrl($url, ++$depth, true);
338 // if the file is too large then exit
339 if ($curl_info["download_content_length"] > 1000000) {
343 // if it isn't a HTML file then exit
344 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
348 $this->profiler->startRecording('network');
351 curl_setopt($ch, CURLOPT_URL, $url);
352 curl_setopt($ch, CURLOPT_HEADER, 0);
353 curl_setopt($ch, CURLOPT_NOBODY, 0);
354 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
355 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
356 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
357 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
359 $body = curl_exec($ch);
362 $this->profiler->stopRecording();
364 if (trim($body) == "") {
368 // Check for redirect in meta elements
369 $doc = new DOMDocument();
370 @$doc->loadHTML($body);
372 $xpath = new DomXPath($doc);
374 $list = $xpath->query("//meta[@content]");
375 foreach ($list as $node) {
377 if ($node->attributes->length) {
378 foreach ($node->attributes as $attribute) {
379 $attr[$attribute->name] = $attribute->value;
383 if (@$attr["http-equiv"] == 'refresh') {
384 $path = $attr["content"];
385 $pathinfo = explode(";", $path);
386 foreach ($pathinfo as $value) {
387 if (substr(strtolower($value), 0, 4) == "url=") {
388 return $this->finalUrl(substr($value, 4), ++$depth);
400 public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
402 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
404 return $ret->getBody();
410 public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
415 'timeout' => $timeout,
416 'accept_content' => $accept_content,
417 'cookiejar' => $cookiejar