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;
25 use Friendica\Core\Config\IConfig;
26 use Friendica\Core\Logger;
27 use Friendica\Core\System;
28 use Friendica\Util\Network;
29 use Friendica\Util\Profiler;
30 use Psr\Log\LoggerInterface;
33 * Performs HTTP requests to a given URL
37 /** @var LoggerInterface */
46 public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App\BaseURL $baseUrl)
48 $this->logger = $logger;
49 $this->profiler = $profiler;
50 $this->config = $config;
51 $this->baseUrl = $baseUrl->get();
57 * @param string $url URL to fetch
58 * @param bool $binary default false
59 * TRUE if asked to return binary results (file download)
60 * @param array $opts (optional parameters) assoziative array with:
61 * 'accept_content' => supply Accept: header with 'accept_content' as the value
62 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
63 * 'http_auth' => username:password
64 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
65 * 'nobody' => only return the header
66 * 'cookiejar' => path to cookie jar file
67 * 'header' => header array
68 * @param int $redirects The recursion counter for internal use - default 0
71 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
73 public function curl(string $url, bool $binary = false, 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->userAgent);
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 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
147 if (!empty($opts['nobody'])) {
148 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
151 if (!empty($opts['timeout'])) {
152 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
154 $curl_time = $this->config->get('system', 'curl_timeout', 60);
155 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
158 // by default we will allow self-signed certs
159 // but you can override this
161 $check_cert = $this->config->get('system', 'verifyssl');
162 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
165 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
168 $proxy = $this->config->get('system', 'proxy');
170 if (!empty($proxy)) {
171 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
172 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
173 $proxyuser = $this->config->get('system', 'proxyuser');
175 if (!empty($proxyuser)) {
176 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
180 if ($this->config->get('system', 'ipv4_resolve', false)) {
181 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
185 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
188 // don't let curl abort the entire application
189 // if it throws any errors.
191 $s = @curl_exec($ch);
192 $curl_info = @curl_getinfo($ch);
194 // Special treatment for HTTP Code 416
195 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
196 if (($curl_info['http_code'] == 416) && ($range > 0)) {
197 @curl_setopt($ch, CURLOPT_RANGE, '');
198 $s = @curl_exec($ch);
199 $curl_info = @curl_getinfo($ch);
202 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
204 if ($curlResponse->isRedirectUrl()) {
206 $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
208 return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
213 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
215 return $curlResponse;
219 * Send POST request to $url
221 * @param string $url URL to post
222 * @param mixed $params array of POST variables
223 * @param array $headers HTTP headers
224 * @param int $redirects Recursion counter for internal use - default = 0
225 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
227 * @return CurlResult The content
228 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
232 $stamp1 = microtime(true);
234 if (Network::isUrlBlocked($url)) {
235 $this->logger->info('Domain is blocked.' . ['url' => $url]);
236 return CurlResult::createErrorCurl($url);
239 $ch = curl_init($url);
241 if (($redirects > 8) || (!$ch)) {
242 return CurlResult::createErrorCurl($url);
245 $this->logger->debug('Post_url: start.', ['url' => $url]);
247 curl_setopt($ch, CURLOPT_HEADER, true);
248 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
249 curl_setopt($ch, CURLOPT_POST, 1);
250 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
251 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
253 if ($this->config->get('system', 'ipv4_resolve', false)) {
254 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
257 if (intval($timeout)) {
258 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
260 $curl_time = $this->config->get('system', 'curl_timeout', 60);
261 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
264 if (!empty($headers)) {
265 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
268 $check_cert = $this->config->get('system', 'verifyssl');
269 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
272 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
275 $proxy = $this->config->get('system', 'proxy');
277 if (!empty($proxy)) {
278 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
279 curl_setopt($ch, CURLOPT_PROXY, $proxy);
280 $proxyuser = $this->config->get('system', 'proxyuser');
281 if (!empty($proxyuser)) {
282 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
286 // don't let curl abort the entire application
287 // if it throws any errors.
289 $s = @curl_exec($ch);
291 $curl_info = curl_getinfo($ch);
293 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
295 if ($curlResponse->isRedirectUrl()) {
297 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
299 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
304 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
306 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
307 if ($curlResponse->getReturnCode() == 417) {
310 if (empty($headers)) {
311 $headers = ['Expect:'];
313 if (!in_array('Expect:', $headers)) {
314 array_push($headers, 'Expect:');
317 Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
318 return self::post($url, $params, $headers, $redirects, $timeout);
321 Logger::log('post_url: end ' . $url, Logger::DATA);
323 return $curlResponse;
329 * If binary flag is true, return binary results.
330 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
331 * to preserve cookies from one request to the next.
333 * @param string $url URL to fetch
334 * @param bool $binary default false
335 * TRUE if asked to return binary results (file download)
336 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
337 * @param string $accept_content supply Accept: header with 'accept_content' as the value
338 * @param string $cookiejar Path to cookie jar file
339 * @param int $redirects The recursion counter for internal use - default 0
341 * @return string The fetched content
342 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
344 public function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
346 $ret = $this->fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
348 return $ret->getBody();
352 * Curl wrapper with array of return values.
354 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
355 * all the information collected during the fetch.
357 * @param string $url URL to fetch
358 * @param bool $binary default false
359 * TRUE if asked to return binary results (file download)
360 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
361 * @param string $accept_content supply Accept: header with 'accept_content' as the value
362 * @param string $cookiejar Path to cookie jar file
363 * @param int $redirects The recursion counter for internal use - default 0
365 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
366 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
368 public function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
374 'timeout' => $timeout,
375 'accept_content' => $accept_content,
376 'cookiejar' => $cookiejar
383 * Returns the current UserAgent as a String
385 * @return string the UserAgent as a String
387 public function getUserAgent()
390 FRIENDICA_PLATFORM . " '" .
391 FRIENDICA_CODENAME . "' " .
392 FRIENDICA_VERSION . '-' .
393 DB_UPDATE_VERSION . '; ' .