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 Psr\Log\LoggerInterface;
34 * Performs HTTP requests to a given URL
36 class HTTPRequest implements IHTTPRequest
38 /** @var LoggerInterface */
47 public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App\BaseURL $baseUrl)
49 $this->logger = $logger;
50 $this->profiler = $profiler;
51 $this->config = $config;
52 $this->baseUrl = $baseUrl->get();
58 * @param int $redirects The recursion counter for internal use - default 0
60 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
62 public function get(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
64 $stamp1 = microtime(true);
66 if (strlen($url) > 1000) {
67 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
68 return CurlResult::createErrorCurl(substr($url, 0, 200));
72 $parts = parse_url($url);
73 $path_parts = explode('/', $parts['path'] ?? '');
74 foreach ($path_parts as $part) {
75 if (strlen($part) <> mb_strlen($part)) {
76 $parts2[] = rawurlencode($part);
81 $parts['path'] = implode('/', $parts2);
82 $url = Network::unparseURL($parts);
84 if (Network::isUrlBlocked($url)) {
85 $this->logger->info('Domain is blocked.', ['url' => $url]);
86 return CurlResult::createErrorCurl($url);
89 $ch = @curl_init($url);
91 if (($redirects > 8) || (!$ch)) {
92 return CurlResult::createErrorCurl($url);
95 @curl_setopt($ch, CURLOPT_HEADER, true);
97 if (!empty($opts['cookiejar'])) {
98 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
99 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
102 // These settings aren't needed. We're following the location already.
103 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
104 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
106 if (!empty($opts['accept_content'])) {
110 ['Accept: ' . $opts['accept_content']]
114 if (!empty($opts['header'])) {
115 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
118 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
119 @curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
121 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
124 @curl_setopt($ch, 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 curl_setopt($ch, CURLOPT_ENCODING, '');
132 if (!empty($opts['headers'])) {
133 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
136 if (!empty($opts['nobody'])) {
137 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
140 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
142 if (!empty($opts['timeout'])) {
143 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
145 $curl_time = $this->config->get('system', 'curl_timeout', 60);
146 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
149 // by default we will allow self-signed certs
150 // but you can override this
152 $check_cert = $this->config->get('system', 'verifyssl');
153 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
156 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
159 $proxy = $this->config->get('system', 'proxy');
161 if (!empty($proxy)) {
162 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
163 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
164 $proxyuser = $this->config->get('system', 'proxyuser');
166 if (!empty($proxyuser)) {
167 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
171 if ($this->config->get('system', 'ipv4_resolve', false)) {
172 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
176 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
179 // don't let curl abort the entire application
180 // if it throws any errors.
182 $s = @curl_exec($ch);
183 $curl_info = @curl_getinfo($ch);
185 // Special treatment for HTTP Code 416
186 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
187 if (($curl_info['http_code'] == 416) && ($range > 0)) {
188 @curl_setopt($ch, CURLOPT_RANGE, '');
189 $s = @curl_exec($ch);
190 $curl_info = @curl_getinfo($ch);
193 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
195 if ($curlResponse->isRedirectUrl()) {
197 $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
199 return $this->get($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
204 $this->profiler->saveTimestamp($stamp1, 'network');
206 return $curlResponse;
212 * @param int $redirects The recursion counter for internal use - default 0
214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
218 $stamp1 = microtime(true);
220 if (Network::isUrlBlocked($url)) {
221 $this->logger->info('Domain is blocked.' . ['url' => $url]);
222 return CurlResult::createErrorCurl($url);
225 $ch = curl_init($url);
227 if (($redirects > 8) || (!$ch)) {
228 return CurlResult::createErrorCurl($url);
231 $this->logger->debug('Post_url: start.', ['url' => $url]);
233 curl_setopt($ch, CURLOPT_HEADER, true);
234 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
235 curl_setopt($ch, CURLOPT_POST, 1);
236 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
237 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
239 if ($this->config->get('system', 'ipv4_resolve', false)) {
240 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
243 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
245 if (intval($timeout)) {
246 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
248 $curl_time = $this->config->get('system', 'curl_timeout', 60);
249 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
252 if (!empty($headers)) {
253 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
256 $check_cert = $this->config->get('system', 'verifyssl');
257 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
260 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
263 $proxy = $this->config->get('system', 'proxy');
265 if (!empty($proxy)) {
266 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
267 curl_setopt($ch, CURLOPT_PROXY, $proxy);
268 $proxyuser = $this->config->get('system', 'proxyuser');
269 if (!empty($proxyuser)) {
270 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
274 // don't let curl abort the entire application
275 // if it throws any errors.
277 $s = @curl_exec($ch);
279 $curl_info = curl_getinfo($ch);
281 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
283 if ($curlResponse->isRedirectUrl()) {
285 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
287 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
292 $this->profiler->saveTimestamp($stamp1, 'network');
294 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
295 if ($curlResponse->getReturnCode() == 417) {
298 if (empty($headers)) {
299 $headers = ['Expect:'];
301 if (!in_array('Expect:', $headers)) {
302 array_push($headers, 'Expect:');
305 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
306 return $this->post($url, $params, $headers, $redirects, $timeout);
309 $this->logger->debug('Post_url: End.', ['url' => $url]);
311 return $curlResponse;
317 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
319 if (Network::isUrlBlocked($url)) {
320 $this->logger->info('Domain is blocked.', ['url' => $url]);
324 $url = Network::stripTrackingQueryParams($url);
330 $url = trim($url, "'");
332 $stamp1 = microtime(true);
335 curl_setopt($ch, CURLOPT_URL, $url);
336 curl_setopt($ch, CURLOPT_HEADER, 1);
337 curl_setopt($ch, CURLOPT_NOBODY, 1);
338 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
339 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
340 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
341 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
344 $curl_info = @curl_getinfo($ch);
345 $http_code = $curl_info['http_code'];
348 $this->profiler->saveTimestamp($stamp1, "network");
350 if ($http_code == 0) {
354 if (in_array($http_code, ['301', '302'])) {
355 if (!empty($curl_info['redirect_url'])) {
356 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
357 } elseif (!empty($curl_info['location'])) {
358 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
362 // Check for redirects in the meta elements of the body if there are no redirects in the header.
364 return $this->finalUrl($url, ++$depth, true);
367 // if the file is too large then exit
368 if ($curl_info["download_content_length"] > 1000000) {
372 // if it isn't a HTML file then exit
373 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
377 $stamp1 = microtime(true);
380 curl_setopt($ch, CURLOPT_URL, $url);
381 curl_setopt($ch, CURLOPT_HEADER, 0);
382 curl_setopt($ch, CURLOPT_NOBODY, 0);
383 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
384 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
385 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
386 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
388 $body = curl_exec($ch);
391 $this->profiler->saveTimestamp($stamp1, "network");
393 if (trim($body) == "") {
397 // Check for redirect in meta elements
398 $doc = new DOMDocument();
399 @$doc->loadHTML($body);
401 $xpath = new DomXPath($doc);
403 $list = $xpath->query("//meta[@content]");
404 foreach ($list as $node) {
406 if ($node->attributes->length) {
407 foreach ($node->attributes as $attribute) {
408 $attr[$attribute->name] = $attribute->value;
412 if (@$attr["http-equiv"] == 'refresh') {
413 $path = $attr["content"];
414 $pathinfo = explode(";", $path);
415 foreach ($pathinfo as $value) {
416 if (substr(strtolower($value), 0, 4) == "url=") {
417 return $this->finalUrl(substr($value, 4), ++$depth);
429 * @param int $redirects The recursion counter for internal use - default 0
431 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
433 public function fetch(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
435 $ret = $this->fetchFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
437 return $ret->getBody();
443 * @param int $redirects The recursion counter for internal use - default 0
445 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
447 public function fetchFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
453 'timeout' => $timeout,
454 'accept_content' => $accept_content,
455 'cookiejar' => $cookiejar
464 public function getUserAgent()
467 FRIENDICA_PLATFORM . " '" .
468 FRIENDICA_CODENAME . "' " .
469 FRIENDICA_VERSION . '-' .
470 DB_UPDATE_VERSION . '; ' .