3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL 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\HTTPClient\Client;
24 use Friendica\Core\System;
25 use Friendica\Network\HTTPClient\Response\CurlResult;
26 use Friendica\Network\HTTPClient\Response\GuzzleResponse;
27 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
28 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
29 use Friendica\Util\Network;
30 use Friendica\Util\Profiler;
31 use GuzzleHttp\Client;
32 use GuzzleHttp\Cookie\FileCookieJar;
33 use GuzzleHttp\Exception\RequestException;
34 use GuzzleHttp\Exception\TransferException;
35 use GuzzleHttp\RequestOptions;
36 use mattwright\URLResolver;
37 use Psr\Http\Message\ResponseInterface;
38 use Psr\Log\InvalidArgumentException;
39 use Psr\Log\LoggerInterface;
42 * Performs HTTP requests to a given URL
44 class HttpClient implements ICanSendHttpRequests
46 /** @var LoggerInterface */
52 /** @var URLResolver */
55 public function __construct(LoggerInterface $logger, Profiler $profiler, Client $client, URLResolver $resolver)
57 $this->logger = $logger;
58 $this->profiler = $profiler;
59 $this->client = $client;
60 $this->resolver = $resolver;
66 public function request(string $method, string $url, array $opts = []): ICanHandleHttpResponses
68 $this->profiler->startRecording('network');
69 $this->logger->debug('Request start.', ['url' => $url, 'method' => $method]);
71 $host = parse_url($url, PHP_URL_HOST);
73 throw new \InvalidArgumentException('Unable to retrieve the host in URL: ' . $url);
76 if(!filter_var($host, FILTER_VALIDATE_IP) && !@dns_get_record($host . '.', DNS_A + DNS_AAAA) && !gethostbyname($host)) {
77 $this->logger->debug('URL cannot be resolved.', ['url' => $url, 'callstack' => System::callstack(20)]);
78 $this->profiler->stopRecording();
79 return CurlResult::createErrorCurl($this->logger, $url);
82 if (Network::isLocalLink($url)) {
83 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
86 if (strlen($url) > 1000) {
87 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
88 $this->profiler->stopRecording();
89 return CurlResult::createErrorCurl($this->logger, substr($url, 0, 200));
93 $parts = parse_url($url);
94 $path_parts = explode('/', $parts['path'] ?? '');
95 foreach ($path_parts as $part) {
96 if (strlen($part) <> mb_strlen($part)) {
97 $parts2[] = rawurlencode($part);
102 $parts['path'] = implode('/', $parts2);
103 $url = Network::unparseURL($parts);
105 if (Network::isUrlBlocked($url)) {
106 $this->logger->info('Domain is blocked.', ['url' => $url]);
107 $this->profiler->stopRecording();
108 return CurlResult::createErrorCurl($this->logger, $url);
113 if (!empty($opts[HttpClientOptions::COOKIEJAR])) {
114 $jar = new FileCookieJar($opts[HttpClientOptions::COOKIEJAR]);
115 $conf[RequestOptions::COOKIES] = $jar;
120 if (!empty($opts[HttpClientOptions::ACCEPT_CONTENT])) {
121 $headers['Accept'] = $opts[HttpClientOptions::ACCEPT_CONTENT];
124 if (!empty($opts[HttpClientOptions::LEGACY_HEADER])) {
125 $this->logger->notice('Wrong option \'headers\' used.');
126 $headers = array_merge($opts[HttpClientOptions::LEGACY_HEADER], $headers);
129 if (!empty($opts[HttpClientOptions::HEADERS])) {
130 $headers = array_merge($opts[HttpClientOptions::HEADERS], $headers);
133 $conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $headers);
135 if (!empty($opts[HttpClientOptions::TIMEOUT])) {
136 $conf[RequestOptions::TIMEOUT] = $opts[HttpClientOptions::TIMEOUT];
139 if (isset($opts[HttpClientOptions::VERIFY])) {
140 $conf[RequestOptions::VERIFY] = $opts[HttpClientOptions::VERIFY];
143 if (!empty($opts[HttpClientOptions::BODY])) {
144 $conf[RequestOptions::BODY] = $opts[HttpClientOptions::BODY];
147 if (!empty($opts[HttpClientOptions::FORM_PARAMS])) {
148 $conf[RequestOptions::FORM_PARAMS] = $opts[HttpClientOptions::FORM_PARAMS];
151 if (!empty($opts[HttpClientOptions::AUTH])) {
152 $conf[RequestOptions::AUTH] = $opts[HttpClientOptions::AUTH];
155 $conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
156 if (!empty($opts[HttpClientOptions::CONTENT_LENGTH]) &&
157 (int)$response->getHeaderLine('Content-Length') > $opts[HttpClientOptions::CONTENT_LENGTH]) {
158 throw new TransferException('The file is too big!');
162 if (empty($conf[HttpClientOptions::HEADERS]['Accept']) && in_array($method, ['get', 'head'])) {
163 $this->logger->info('Accept header was missing, using default.', ['url' => $url, 'callstack' => System::callstack()]);
164 $conf[HttpClientOptions::HEADERS]['Accept'] = HttpClientAccept::DEFAULT;
167 $conf['sink'] = tempnam(System::getTempPath(), 'http-');
170 $this->logger->debug('http request config.', ['url' => $url, 'method' => $method, 'options' => $conf]);
172 $response = $this->client->request($method, $url, $conf);
173 return new GuzzleResponse($response, $url);
174 } catch (TransferException $exception) {
175 if ($exception instanceof RequestException &&
176 $exception->hasResponse()) {
177 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
179 return new CurlResult($this->logger, $url, '', ['http_code' => 500], $exception->getCode(), '');
181 } catch (InvalidArgumentException | \InvalidArgumentException $argumentException) {
182 $this->logger->info('Invalid Argument for HTTP call.', ['url' => $url, 'method' => $method, 'exception' => $argumentException]);
183 return new CurlResult($this->logger, $url, '', ['http_code' => 500], $argumentException->getCode(), $argumentException->getMessage());
185 unlink($conf['sink']);
186 $this->logger->debug('Request stop.', ['url' => $url, 'method' => $method]);
187 $this->profiler->stopRecording();
193 public function head(string $url, array $opts = []): ICanHandleHttpResponses
195 return $this->request('head', $url, $opts);
201 public function get(string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ICanHandleHttpResponses
203 // In case there is no
204 $opts[HttpClientOptions::ACCEPT_CONTENT] = $opts[HttpClientOptions::ACCEPT_CONTENT] ?? $accept_content;
206 return $this->request('get', $url, $opts);
212 public function post(string $url, $params, array $headers = [], int $timeout = 0): ICanHandleHttpResponses
216 if (!is_array($params)) {
217 $opts[HttpClientOptions::BODY] = $params;
219 $opts[HttpClientOptions::FORM_PARAMS] = $params;
222 if (!empty($headers)) {
223 $opts[HttpClientOptions::HEADERS] = $headers;
226 if (!empty($timeout)) {
227 $opts[HttpClientOptions::TIMEOUT] = $timeout;
230 return $this->request('post', $url, $opts);
236 public function finalUrl(string $url): string
238 $this->profiler->startRecording('network');
240 if (Network::isLocalLink($url)) {
241 $this->logger->debug('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
244 if (Network::isUrlBlocked($url)) {
245 $this->logger->info('Domain is blocked.', ['url' => $url]);
249 if (Network::isRedirectBlocked($url)) {
250 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
254 $url = Network::stripTrackingQueryParams($url);
256 $url = trim($url, "'");
258 $urlResult = $this->resolver->resolveURL($url);
260 if ($urlResult->didErrorOccur()) {
261 throw new TransferException($urlResult->getErrorMessageString(), $urlResult->getHTTPStatusCode() ?? 0);
264 return $urlResult->getUrl();
270 public function fetch(string $url, string $accept_content = HttpClientAccept::DEFAULT, int $timeout = 0, string $cookiejar = ''): string
272 $ret = $this->fetchFull($url, $accept_content, $timeout, $cookiejar);
274 return $ret->getBody();
280 public function fetchFull(string $url, string $accept_content = HttpClientAccept::DEFAULT, int $timeout = 0, string $cookiejar = ''): ICanHandleHttpResponses
286 HttpClientOptions::TIMEOUT => $timeout,
287 HttpClientOptions::COOKIEJAR => $cookiejar