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;
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 = [], &$redirects = 0)
75 $this->profiler->startRecording('network');
77 if (Network::isLocalLink($url)) {
78 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
81 if (strlen($url) > 1000) {
82 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
83 $this->profiler->stopRecording();
84 return CurlResult::createErrorCurl(substr($url, 0, 200));
88 $parts = parse_url($url);
89 $path_parts = explode('/', $parts['path'] ?? '');
90 foreach ($path_parts as $part) {
91 if (strlen($part) <> mb_strlen($part)) {
92 $parts2[] = rawurlencode($part);
97 $parts['path'] = implode('/', $parts2);
98 $url = Network::unparseURL($parts);
100 if (Network::isUrlBlocked($url)) {
101 $this->logger->info('Domain is blocked.', ['url' => $url]);
102 $this->profiler->stopRecording();
103 return CurlResult::createErrorCurl($url);
106 $ch = @curl_init($url);
108 if (($redirects > 8) || (!$ch)) {
109 $this->profiler->stopRecording();
110 return CurlResult::createErrorCurl($url);
113 @curl_setopt($ch, CURLOPT_HEADER, true);
115 if (!empty($opts['cookiejar'])) {
116 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
117 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
120 // These settings aren't needed. We're following the location already.
121 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
122 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
124 if (!empty($opts['accept_content'])) {
128 ['Accept: ' . $opts['accept_content']]
132 if (!empty($opts['header'])) {
133 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
136 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
137 @curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
139 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
142 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
145 // Without this setting it seems as if some webservers send compressed content
146 // This seems to confuse curl so that it shows this uncompressed.
147 /// @todo We could possibly set this value to "gzip" or something similar
148 curl_setopt($ch, CURLOPT_ENCODING, '');
150 if (!empty($opts['headers'])) {
151 $this->logger->notice('Wrong option \'headers\' used.');
152 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
155 if (!empty($opts['nobody'])) {
156 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
159 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
161 if (!empty($opts['timeout'])) {
162 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
164 $curl_time = $this->config->get('system', 'curl_timeout', 60);
165 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
168 // by default we will allow self-signed certs
169 // but you can override this
171 $check_cert = $this->config->get('system', 'verifyssl');
172 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
175 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
178 $proxy = $this->config->get('system', 'proxy');
180 if (!empty($proxy)) {
181 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
182 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
183 $proxyuser = $this->config->get('system', 'proxyuser');
185 if (!empty($proxyuser)) {
186 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
190 if ($this->config->get('system', 'ipv4_resolve', false)) {
191 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
194 $s = @curl_exec($ch);
195 $curl_info = @curl_getinfo($ch);
197 // Special treatment for HTTP Code 416
198 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
199 if (($curl_info['http_code'] == 416) && ($range > 0)) {
200 @curl_setopt($ch, CURLOPT_RANGE, '');
201 $s = @curl_exec($ch);
202 $curl_info = @curl_getinfo($ch);
205 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
207 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
209 $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
211 $this->profiler->stopRecording();
212 return $this->get($curlResponse->getRedirectUrl(), $opts, $redirects);
217 $this->profiler->stopRecording();
219 return $curlResponse;
225 * @param int $redirects The recursion counter for internal use - default 0
227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
229 public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
231 $this->profiler->startRecording('network');
233 if (Network::isLocalLink($url)) {
234 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
237 if (Network::isUrlBlocked($url)) {
238 $this->logger->info('Domain is blocked.' . ['url' => $url]);
239 $this->profiler->stopRecording();
240 return CurlResult::createErrorCurl($url);
243 $ch = curl_init($url);
245 if (($redirects > 8) || (!$ch)) {
246 $this->profiler->stopRecording();
247 return CurlResult::createErrorCurl($url);
250 $this->logger->debug('Post_url: start.', ['url' => $url]);
252 curl_setopt($ch, CURLOPT_HEADER, true);
253 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
254 curl_setopt($ch, CURLOPT_POST, 1);
255 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
256 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
258 if ($this->config->get('system', 'ipv4_resolve', false)) {
259 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
262 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
264 if (intval($timeout)) {
265 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
267 $curl_time = $this->config->get('system', 'curl_timeout', 60);
268 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
271 if (!empty($headers)) {
272 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
275 $check_cert = $this->config->get('system', 'verifyssl');
276 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
279 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
282 $proxy = $this->config->get('system', 'proxy');
284 if (!empty($proxy)) {
285 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
286 curl_setopt($ch, CURLOPT_PROXY, $proxy);
287 $proxyuser = $this->config->get('system', 'proxyuser');
288 if (!empty($proxyuser)) {
289 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
293 // don't let curl abort the entire application
294 // if it throws any errors.
296 $s = @curl_exec($ch);
298 $curl_info = curl_getinfo($ch);
300 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
302 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
304 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
306 $this->profiler->stopRecording();
307 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
312 $this->profiler->stopRecording();
314 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
315 if ($curlResponse->getReturnCode() == 417) {
318 if (empty($headers)) {
319 $headers = ['Expect:'];
321 if (!in_array('Expect:', $headers)) {
322 array_push($headers, 'Expect:');
325 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
326 return $this->post($url, $params, $headers, $redirects, $timeout);
329 $this->logger->debug('Post_url: End.', ['url' => $url]);
331 return $curlResponse;
337 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
339 if (Network::isLocalLink($url)) {
340 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
343 if (Network::isUrlBlocked($url)) {
344 $this->logger->info('Domain is blocked.', ['url' => $url]);
348 if (Network::isRedirectBlocked($url)) {
349 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
353 $url = Network::stripTrackingQueryParams($url);
359 $url = trim($url, "'");
361 $this->profiler->startRecording('network');
364 curl_setopt($ch, CURLOPT_URL, $url);
365 curl_setopt($ch, CURLOPT_HEADER, 1);
366 curl_setopt($ch, CURLOPT_NOBODY, 1);
367 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
368 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
369 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
370 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
373 $curl_info = @curl_getinfo($ch);
374 $http_code = $curl_info['http_code'];
377 $this->profiler->stopRecording();
379 if ($http_code == 0) {
383 if (in_array($http_code, ['301', '302'])) {
384 if (!empty($curl_info['redirect_url'])) {
385 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
386 } elseif (!empty($curl_info['location'])) {
387 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
391 // Check for redirects in the meta elements of the body if there are no redirects in the header.
393 return $this->finalUrl($url, ++$depth, true);
396 // if the file is too large then exit
397 if ($curl_info["download_content_length"] > 1000000) {
401 // if it isn't a HTML file then exit
402 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
406 $this->profiler->startRecording('network');
409 curl_setopt($ch, CURLOPT_URL, $url);
410 curl_setopt($ch, CURLOPT_HEADER, 0);
411 curl_setopt($ch, CURLOPT_NOBODY, 0);
412 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
413 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
414 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
415 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
417 $body = curl_exec($ch);
420 $this->profiler->stopRecording();
422 if (trim($body) == "") {
426 // Check for redirect in meta elements
427 $doc = new DOMDocument();
428 @$doc->loadHTML($body);
430 $xpath = new DomXPath($doc);
432 $list = $xpath->query("//meta[@content]");
433 foreach ($list as $node) {
435 if ($node->attributes->length) {
436 foreach ($node->attributes as $attribute) {
437 $attr[$attribute->name] = $attribute->value;
441 if (@$attr["http-equiv"] == 'refresh') {
442 $path = $attr["content"];
443 $pathinfo = explode(";", $path);
444 foreach ($pathinfo as $value) {
445 if (substr(strtolower($value), 0, 4) == "url=") {
446 return $this->finalUrl(substr($value, 4), ++$depth);
458 * @param int $redirects The recursion counter for internal use - default 0
460 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
462 public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
464 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar, $redirects);
466 return $ret->getBody();
472 * @param int $redirects The recursion counter for internal use - default 0
474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
476 public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
481 'timeout' => $timeout,
482 'accept_content' => $accept_content,
483 'cookiejar' => $cookiejar
492 public function getUserAgent()
495 FRIENDICA_PLATFORM . " '" .
496 FRIENDICA_CODENAME . "' " .
497 FRIENDICA_VERSION . '-' .
498 DB_UPDATE_VERSION . '; ' .