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();
57 * @throws HTTPException\InternalServerErrorException
59 public function head(string $url, array $opts = [])
61 $opts['nobody'] = true;
63 return $this->get($url, $opts);
69 * @param int $redirects The recursion counter for internal use - default 0
71 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
73 public function get(string $url, array $opts = [], int &$redirects = 0)
75 $stamp1 = microtime(true);
77 if (strlen($url) > 1000) {
78 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
79 return CurlResult::createErrorCurl(substr($url, 0, 200));
83 $parts = parse_url($url);
84 $path_parts = explode('/', $parts['path'] ?? '');
85 foreach ($path_parts as $part) {
86 if (strlen($part) <> mb_strlen($part)) {
87 $parts2[] = rawurlencode($part);
92 $parts['path'] = implode('/', $parts2);
93 $url = Network::unparseURL($parts);
95 if (Network::isUrlBlocked($url)) {
96 $this->logger->info('Domain is blocked.', ['url' => $url]);
97 return CurlResult::createErrorCurl($url);
100 $ch = @curl_init($url);
102 if (($redirects > 8) || (!$ch)) {
103 return CurlResult::createErrorCurl($url);
106 @curl_setopt($ch, CURLOPT_HEADER, true);
108 if (!empty($opts['cookiejar'])) {
109 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
110 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
113 // These settings aren't needed. We're following the location already.
114 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
115 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
117 if (!empty($opts['accept_content'])) {
121 ['Accept: ' . $opts['accept_content']]
125 if (!empty($opts['header'])) {
126 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
129 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
130 @curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
132 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
135 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
138 // Without this setting it seems as if some webservers send compressed content
139 // This seems to confuse curl so that it shows this uncompressed.
140 /// @todo We could possibly set this value to "gzip" or something similar
141 curl_setopt($ch, CURLOPT_ENCODING, '');
143 if (!empty($opts['headers'])) {
144 $this->logger->warning('Wrong option \'headers\' used.');
145 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
148 if (!empty($opts['nobody'])) {
149 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
152 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
154 if (!empty($opts['timeout'])) {
155 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
157 $curl_time = $this->config->get('system', 'curl_timeout', 60);
158 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
161 // by default we will allow self-signed certs
162 // but you can override this
164 $check_cert = $this->config->get('system', 'verifyssl');
165 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
168 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
171 $proxy = $this->config->get('system', 'proxy');
173 if (!empty($proxy)) {
174 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
175 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
176 $proxyuser = $this->config->get('system', 'proxyuser');
178 if (!empty($proxyuser)) {
179 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
183 if ($this->config->get('system', 'ipv4_resolve', false)) {
184 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
187 $logger = $this->logger;
189 $s = @curl_exec($ch);
190 $curl_info = @curl_getinfo($ch);
192 // Special treatment for HTTP Code 416
193 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
194 if (($curl_info['http_code'] == 416) && ($range > 0)) {
195 @curl_setopt($ch, CURLOPT_RANGE, '');
196 $s = @curl_exec($ch);
197 $curl_info = @curl_getinfo($ch);
200 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
202 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
204 $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
206 return $this->get($curlResponse->getRedirectUrl(), $opts, $redirects);
211 $this->profiler->saveTimestamp($stamp1, 'network');
213 return $curlResponse;
219 * @param int $redirects The recursion counter for internal use - default 0
221 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
223 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
225 $stamp1 = microtime(true);
227 if (Network::isUrlBlocked($url)) {
228 $this->logger->info('Domain is blocked.' . ['url' => $url]);
229 return CurlResult::createErrorCurl($url);
232 $ch = curl_init($url);
234 if (($redirects > 8) || (!$ch)) {
235 return CurlResult::createErrorCurl($url);
238 $this->logger->debug('Post_url: start.', ['url' => $url]);
240 curl_setopt($ch, CURLOPT_HEADER, true);
241 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
242 curl_setopt($ch, CURLOPT_POST, 1);
243 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
244 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
246 if ($this->config->get('system', 'ipv4_resolve', false)) {
247 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
250 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
252 if (intval($timeout)) {
253 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
255 $curl_time = $this->config->get('system', 'curl_timeout', 60);
256 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
259 if (!empty($headers)) {
260 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
263 $check_cert = $this->config->get('system', 'verifyssl');
264 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
267 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
270 $proxy = $this->config->get('system', 'proxy');
272 if (!empty($proxy)) {
273 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
274 curl_setopt($ch, CURLOPT_PROXY, $proxy);
275 $proxyuser = $this->config->get('system', 'proxyuser');
276 if (!empty($proxyuser)) {
277 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
281 // don't let curl abort the entire application
282 // if it throws any errors.
284 $s = @curl_exec($ch);
286 $curl_info = curl_getinfo($ch);
288 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
290 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
292 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
294 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
299 $this->profiler->saveTimestamp($stamp1, 'network');
301 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
302 if ($curlResponse->getReturnCode() == 417) {
305 if (empty($headers)) {
306 $headers = ['Expect:'];
308 if (!in_array('Expect:', $headers)) {
309 array_push($headers, 'Expect:');
312 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
313 return $this->post($url, $params, $headers, $redirects, $timeout);
316 $this->logger->debug('Post_url: End.', ['url' => $url]);
318 return $curlResponse;
324 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
326 if (Network::isUrlBlocked($url)) {
327 $this->logger->info('Domain is blocked.', ['url' => $url]);
331 if (Network::isRedirectBlocked($url)) {
332 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
336 $url = Network::stripTrackingQueryParams($url);
342 $url = trim($url, "'");
344 $stamp1 = microtime(true);
347 curl_setopt($ch, CURLOPT_URL, $url);
348 curl_setopt($ch, CURLOPT_HEADER, 1);
349 curl_setopt($ch, CURLOPT_NOBODY, 1);
350 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
351 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
352 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
353 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
356 $curl_info = @curl_getinfo($ch);
357 $http_code = $curl_info['http_code'];
360 $this->profiler->saveTimestamp($stamp1, "network");
362 if ($http_code == 0) {
366 if (in_array($http_code, ['301', '302'])) {
367 if (!empty($curl_info['redirect_url'])) {
368 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
369 } elseif (!empty($curl_info['location'])) {
370 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
374 // Check for redirects in the meta elements of the body if there are no redirects in the header.
376 return $this->finalUrl($url, ++$depth, true);
379 // if the file is too large then exit
380 if ($curl_info["download_content_length"] > 1000000) {
384 // if it isn't a HTML file then exit
385 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
389 $stamp1 = microtime(true);
392 curl_setopt($ch, CURLOPT_URL, $url);
393 curl_setopt($ch, CURLOPT_HEADER, 0);
394 curl_setopt($ch, CURLOPT_NOBODY, 0);
395 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
396 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
397 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
398 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
400 $body = curl_exec($ch);
403 $this->profiler->saveTimestamp($stamp1, "network");
405 if (trim($body) == "") {
409 // Check for redirect in meta elements
410 $doc = new DOMDocument();
411 @$doc->loadHTML($body);
413 $xpath = new DomXPath($doc);
415 $list = $xpath->query("//meta[@content]");
416 foreach ($list as $node) {
418 if ($node->attributes->length) {
419 foreach ($node->attributes as $attribute) {
420 $attr[$attribute->name] = $attribute->value;
424 if (@$attr["http-equiv"] == 'refresh') {
425 $path = $attr["content"];
426 $pathinfo = explode(";", $path);
427 foreach ($pathinfo as $value) {
428 if (substr(strtolower($value), 0, 4) == "url=") {
429 return $this->finalUrl(substr($value, 4), ++$depth);
441 * @param int $redirects The recursion counter for internal use - default 0
443 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
445 public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
447 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar, $redirects);
449 return $ret->getBody();
455 * @param int $redirects The recursion counter for internal use - default 0
457 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
459 public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
464 'timeout' => $timeout,
465 'accept_content' => $accept_content,
466 'cookiejar' => $cookiejar
475 public function getUserAgent()
478 FRIENDICA_PLATFORM . " '" .
479 FRIENDICA_CODENAME . "' " .
480 FRIENDICA_VERSION . '-' .
481 DB_UPDATE_VERSION . '; ' .