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;
64 * @throws HTTPException\InternalServerErrorException
66 protected function request(string $method, string $url, array $opts = []): IHTTPResult
68 $this->profiler->startRecording('network');
70 if (Network::isLocalLink($url)) {
71 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
74 if (strlen($url) > 1000) {
75 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
76 $this->profiler->stopRecording();
77 return CurlResult::createErrorCurl(substr($url, 0, 200));
81 $parts = parse_url($url);
82 $path_parts = explode('/', $parts['path'] ?? '');
83 foreach ($path_parts as $part) {
84 if (strlen($part) <> mb_strlen($part)) {
85 $parts2[] = rawurlencode($part);
90 $parts['path'] = implode('/', $parts2);
91 $url = Network::unparseURL($parts);
93 if (Network::isUrlBlocked($url)) {
94 $this->logger->info('Domain is blocked.', ['url' => $url]);
95 $this->profiler->stopRecording();
96 return CurlResult::createErrorCurl($url);
101 if (!empty($opts['cookiejar'])) {
102 $jar = new FileCookieJar($opts['cookiejar']);
103 $conf[RequestOptions::COOKIES] = $jar;
108 if (!empty($opts['accept_content'])) {
109 array_push($header, 'Accept: ' . $opts['accept_content']);
112 if (!empty($opts['header'])) {
113 $header = array_merge($opts['header'], $header);
116 if (!empty($opts['headers'])) {
117 $this->logger->notice('Wrong option \'headers\' used.');
118 $header = array_merge($opts['headers'], $header);
121 $conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $header);
123 if (!empty($opts['timeout'])) {
124 $conf[RequestOptions::TIMEOUT] = $opts['timeout'];
127 $conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
128 if (!empty($opts['content_length']) &&
129 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
130 throw new TransferException('The file is too big!');
135 $response = $this->client->$method($url, $conf);
136 return new GuzzleResponse($response, $url);
137 } catch (TransferException $exception) {
138 if ($exception instanceof RequestException &&
139 $exception->hasResponse()) {
140 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
142 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), '');
145 $this->profiler->stopRecording();
151 * @throws HTTPException\InternalServerErrorException
153 public function head(string $url, array $opts = []): IHTTPResult
155 return $this->request('head', $url, $opts);
161 public function get(string $url, array $opts = []): IHTTPResult
163 return $this->request('get', $url, $opts);
169 * @param int $redirects The recursion counter for internal use - default 0
171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
173 public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
175 $this->profiler->startRecording('network');
177 if (Network::isLocalLink($url)) {
178 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
181 if (Network::isUrlBlocked($url)) {
182 $this->logger->info('Domain is blocked.' . ['url' => $url]);
183 $this->profiler->stopRecording();
184 return CurlResult::createErrorCurl($url);
187 $ch = curl_init($url);
189 if (($redirects > 8) || (!$ch)) {
190 $this->profiler->stopRecording();
191 return CurlResult::createErrorCurl($url);
194 $this->logger->debug('Post_url: start.', ['url' => $url]);
196 curl_setopt($ch, CURLOPT_HEADER, true);
197 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
198 curl_setopt($ch, CURLOPT_POST, 1);
199 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
200 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
202 if ($this->config->get('system', 'ipv4_resolve', false)) {
203 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
206 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
208 if (intval($timeout)) {
209 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
211 $curl_time = $this->config->get('system', 'curl_timeout', 60);
212 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
215 if (!empty($headers)) {
216 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
219 $check_cert = $this->config->get('system', 'verifyssl');
220 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
223 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
226 $proxy = $this->config->get('system', 'proxy');
228 if (!empty($proxy)) {
229 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
230 curl_setopt($ch, CURLOPT_PROXY, $proxy);
231 $proxyuser = $this->config->get('system', 'proxyuser');
232 if (!empty($proxyuser)) {
233 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
237 // don't let curl abort the entire application
238 // if it throws any errors.
240 $s = @curl_exec($ch);
242 $curl_info = curl_getinfo($ch);
244 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
246 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
248 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
250 $this->profiler->stopRecording();
251 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
256 $this->profiler->stopRecording();
258 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
259 if ($curlResponse->getReturnCode() == 417) {
262 if (empty($headers)) {
263 $headers = ['Expect:'];
265 if (!in_array('Expect:', $headers)) {
266 array_push($headers, 'Expect:');
269 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
270 return $this->post($url, $params, $headers, $redirects, $timeout);
273 $this->logger->debug('Post_url: End.', ['url' => $url]);
275 return $curlResponse;
281 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
283 if (Network::isLocalLink($url)) {
284 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
287 if (Network::isUrlBlocked($url)) {
288 $this->logger->info('Domain is blocked.', ['url' => $url]);
292 if (Network::isRedirectBlocked($url)) {
293 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
297 $url = Network::stripTrackingQueryParams($url);
303 $url = trim($url, "'");
305 $this->profiler->startRecording('network');
308 curl_setopt($ch, CURLOPT_URL, $url);
309 curl_setopt($ch, CURLOPT_HEADER, 1);
310 curl_setopt($ch, CURLOPT_NOBODY, 1);
311 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
312 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
313 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
314 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
317 $curl_info = @curl_getinfo($ch);
318 $http_code = $curl_info['http_code'];
321 $this->profiler->stopRecording();
323 if ($http_code == 0) {
327 if (in_array($http_code, ['301', '302'])) {
328 if (!empty($curl_info['redirect_url'])) {
329 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
330 } elseif (!empty($curl_info['location'])) {
331 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
335 // Check for redirects in the meta elements of the body if there are no redirects in the header.
337 return $this->finalUrl($url, ++$depth, true);
340 // if the file is too large then exit
341 if ($curl_info["download_content_length"] > 1000000) {
345 // if it isn't a HTML file then exit
346 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
350 $this->profiler->startRecording('network');
353 curl_setopt($ch, CURLOPT_URL, $url);
354 curl_setopt($ch, CURLOPT_HEADER, 0);
355 curl_setopt($ch, CURLOPT_NOBODY, 0);
356 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
357 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
358 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
359 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
361 $body = curl_exec($ch);
364 $this->profiler->stopRecording();
366 if (trim($body) == "") {
370 // Check for redirect in meta elements
371 $doc = new DOMDocument();
372 @$doc->loadHTML($body);
374 $xpath = new DomXPath($doc);
376 $list = $xpath->query("//meta[@content]");
377 foreach ($list as $node) {
379 if ($node->attributes->length) {
380 foreach ($node->attributes as $attribute) {
381 $attr[$attribute->name] = $attribute->value;
385 if (@$attr["http-equiv"] == 'refresh') {
386 $path = $attr["content"];
387 $pathinfo = explode(";", $path);
388 foreach ($pathinfo as $value) {
389 if (substr(strtolower($value), 0, 4) == "url=") {
390 return $this->finalUrl(substr($value, 4), ++$depth);
402 public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
404 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
406 return $ret->getBody();
412 public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
417 'timeout' => $timeout,
418 'accept_content' => $accept_content,
419 'cookiejar' => $cookiejar