1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp-curl/curlhelper.cc
12 #include "private/curlhelper_p.h"
14 #include <zypp/APIConfig.h>
16 #include <zypp-core/fs/PathInfo.h>
17 #include <zypp-core/Pathname.h>
18 #include <zypp-core/base/LogTools.h>
19 #include <zypp-core/base/String.h>
20 #include <zypp-core/base/StringV.h>
21 #include <zypp-curl/ProxyInfo>
22 #include <zypp-curl/auth/CurlAuthData>
23 #include <zypp-media/MediaException>
27 #define TRANSFER_TIMEOUT_MAX 60 * 60
36 const long & ZYPP_MEDIA_CURL_DEBUG()
38 static const long ret = [](){
39 const char * env = getenv("ZYPP_MEDIA_CURL_DEBUG");
40 return env && *env ? str::strtonum<ulong>( env ) : 0;
45 int ZYPP_MEDIA_CURL_IPRESOLVE()
49 if ( const char * envp = getenv( "ZYPP_MEDIA_CURL_IPRESOLVE" ) ) {
50 WAR << "env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp << "'" << std::endl;
51 if ( strcmp( envp, "4" ) == 0 ) ret = 4;
52 else if ( strcmp( envp, "6" ) == 0 ) ret = 6;
64 void globalInitCurlOnce()
66 // function-level static <=> std::call_once
67 static bool once __attribute__ ((__unused__)) = ( [] {
68 MIL << "global_init libcurl: " << curl_version_info(CURLVERSION_NOW)->version << endl;
69 if ( curl_global_init( CURL_GLOBAL_ALL ) != 0 )
70 WAR << "curl global init failed" << std::endl;
74 int log_curl( CURL * curl, curl_infotype info, char * ptr, size_t len, void * max_lvl )
76 if ( max_lvl == nullptr )
79 long maxlvl = *((long *)max_lvl);
80 const char * pfx = "";
81 bool isContent = true; // otherwise it's data
84 case CURLINFO_TEXT: if ( maxlvl < 1 ) return 0; pfx = "*"; break;
85 case CURLINFO_HEADER_IN: if ( maxlvl < 2 ) return 0; pfx = "<"; break;
86 case CURLINFO_HEADER_OUT: if ( maxlvl < 2 ) return 0; pfx = ">"; break;
87 case CURLINFO_SSL_DATA_IN: if ( maxlvl < 3 ) return 0; isContent = false; pfx = "<[SSL]"; break;
88 case CURLINFO_SSL_DATA_OUT: if ( maxlvl < 3 ) return 0; isContent = false; pfx = ">[SSL]"; break;
89 case CURLINFO_DATA_IN: if ( maxlvl < 3 ) return 0; isContent = false; pfx = "<[DTA]"; break;
90 case CURLINFO_DATA_OUT: if ( maxlvl < 3 ) return 0; isContent = false; pfx = ">[DTA]"; break;
96 // We'd like to keep all log messages within function `log_curl`
97 // because this tag to grep for is known and communicate to users.
99 std::vector<std::string_view> lines; // don't want log from within the lambda
100 strv::split( std::string_view( ptr, len ), "\n", [&lines]( std::string_view line, unsigned, bool last ) {
101 if ( last ) return; // empty word after final \n
102 line = strv::rtrim( line, "\r" );
103 lines.push_back( line );
105 for ( const auto & line : lines ) {
106 if ( str::hasPrefix( line, "Authorization:" ) ) {
107 std::string_view::size_type pos { line.find( " ", 15 ) }; // Authorization: <type> <credentials>
108 if ( pos == std::string::npos )
110 DBG << curl << " " << pfx << " " << line.substr( 0, pos ) << " <credentials removed>" << endl;
113 DBG << curl << " " << pfx << " " << line << endl;
117 DBG << curl << " " << pfx << " " << len << " byte" << endl;
119 hexdumpOn( DBG << curl << " " << pfx << " ", ptr, len );
124 void setupZYPP_MEDIA_CURL_DEBUG( CURL *curl )
127 INT << "Got a NULL curl handle" << endl;
130 if ( env::ZYPP_MEDIA_CURL_DEBUG() > 0 ) {
131 curl_easy_setopt( curl, CURLOPT_VERBOSE, 1L );
132 curl_easy_setopt( curl, CURLOPT_DEBUGFUNCTION, log_curl );
133 curl_easy_setopt( curl, CURLOPT_DEBUGDATA, &env::ZYPP_MEDIA_CURL_DEBUG() );
137 size_t log_redirects_curl( char *ptr, size_t size, size_t nmemb, void *userdata)
139 //INT << "got header: " << std::string(ptr, ptr + size*nmemb) << endl;
141 char * lstart = ptr, * lend = ptr;
143 size_t max = size * nmemb;
144 while (pos + 1 < max)
147 for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
149 // look for "Location"
150 if ( strncasecmp( lstart, "Location:", 9 ) == 0 )
152 std::string line { lstart, *(lend-1)=='\r' ? lend-1 : lend };
153 DBG << "redirecting to " << line << std::endl;
155 *reinterpret_cast<std::string *>( userdata ) = line;
160 // continue with the next line
174 * Fills the settings structure using options passed on the url
175 * for example ?timeout=x&proxy=foo
177 void fillSettingsFromUrl( const Url &url, media::TransferSettings &s )
180 const std::string & param { url.getQueryParam("timeout") };
181 if( ! param.empty() )
183 long num = str::strtonum<long>(param);
184 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX )
189 std::string param { url.getUsername() };
190 if ( ! param.empty() )
192 s.setUsername( std::move(param) );
193 param = url.getPassword();
194 if ( ! param.empty() )
195 s.setPassword( std::move(param) );
199 // if there is no username, set anonymous auth
200 if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
201 s.setAnonymousAuth();
204 if ( url.getScheme() == "https" )
206 s.setVerifyPeerEnabled( false );
207 s.setVerifyHostEnabled( false );
209 const std::string & verify { url.getQueryParam("ssl_verify") };
210 if( verify.empty() || verify == "yes" )
212 s.setVerifyPeerEnabled( true );
213 s.setVerifyHostEnabled( true );
215 else if ( verify == "no" )
217 s.setVerifyPeerEnabled( false );
218 s.setVerifyHostEnabled( false );
222 std::vector<std::string> flags;
223 str::split( verify, std::back_inserter(flags), "," );
224 for ( const auto & flag : flags )
226 if ( flag == "host" )
227 s.setVerifyHostEnabled( true );
228 else if ( flag == "peer" )
229 s.setVerifyPeerEnabled( true );
231 ZYPP_THROW( media::MediaBadUrlException(url, "Unknown ssl_verify flag "+flag) );
236 Pathname ca_path { url.getQueryParam("ssl_capath") };
237 if( ! ca_path.empty() )
239 if( ! PathInfo(ca_path).isDir() || ! ca_path.absolute() )
240 ZYPP_THROW(media::MediaBadUrlException(url, "Invalid ssl_capath path"));
242 s.setCertificateAuthoritiesPath( std::move(ca_path) );
246 Pathname client_cert { url.getQueryParam("ssl_clientcert") };
247 if( ! client_cert.empty() )
249 if( ! PathInfo(client_cert).isFile() || ! client_cert.absolute() )
250 ZYPP_THROW(media::MediaBadUrlException(url, "Invalid ssl_clientcert file"));
252 s.setClientCertificatePath( std::move(client_cert) );
256 Pathname client_key { url.getQueryParam("ssl_clientkey") };
257 if( ! client_key.empty() )
259 if( ! PathInfo(client_key).isFile() || ! client_key.absolute() )
260 ZYPP_THROW(media::MediaBadUrlException(url, "Invalid ssl_clientkey file"));
262 s.setClientKeyPath( std::move(client_key) );
266 std::string param { url.getQueryParam( "proxy" ) };
267 if ( ! param.empty() )
269 if ( param == EXPLICITLY_NO_PROXY ) {
270 // Workaround TransferSettings shortcoming: With an
271 // empty proxy string, code will continue to look for
272 // valid proxy settings. So set proxy to some non-empty
273 // string, to indicate it has been explicitly disabled.
274 s.setProxy(EXPLICITLY_NO_PROXY);
275 s.setProxyEnabled(false);
278 const std::string & proxyport { url.getQueryParam( "proxyport" ) };
279 if ( ! proxyport.empty() ) {
283 s.setProxy( std::move(param) );
284 s.setProxyEnabled( true );
289 std::string param { url.getQueryParam( "proxyuser" ) };
290 if ( ! param.empty() )
292 s.setProxyUsername( std::move(param) );
293 s.setProxyPassword( url.getQueryParam( "proxypass" ) );
297 // HTTP authentication type
298 std::string param { url.getQueryParam("auth") };
299 if ( ! param.empty() && (url.getScheme() == "http" || url.getScheme() == "https") )
303 media::CurlAuthData::auth_type_str2long (param ); // check if we know it
305 catch ( const media::MediaException & ex_r )
307 DBG << "Rethrowing as MediaUnauthorizedException.";
308 ZYPP_THROW(media::MediaUnauthorizedException(url, ex_r.msg(), "", ""));
310 s.setAuthType( std::move(param) );
315 const std::string & param { url.getQueryParam("head_requests") };
316 if( ! param.empty() && param == "no" )
317 s.setHeadRequestsAllowed( false );
322 * Reads the system proxy configuration and fills the settings
323 * structure proxy information
325 void fillSettingsSystemProxy( const Url& url, media::TransferSettings &s )
327 media::ProxyInfo proxy_info;
328 if ( proxy_info.useProxyFor( url ) )
330 // We must extract any 'user:pass' from the proxy url
331 // otherwise they won't make it into curl (.curlrc wins).
333 Url u( proxy_info.proxy( url ) );
334 s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
335 // don't overwrite explicit auth settings
336 if ( s.proxyUsername().empty() )
338 s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
339 s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
341 s.setProxyEnabled( true );
343 catch (...) {} // no proxy if URL is malformed
347 void curlEscape( std::string & str_r,
348 const char char_r, const std::string & escaped_r ) {
349 for ( std::string::size_type pos = str_r.find( char_r );
350 pos != std::string::npos; pos = str_r.find( char_r, pos ) ) {
351 str_r.replace( pos, 1, escaped_r );
355 std::string curlEscapedPath( std::string path_r ) {
356 curlEscape( path_r, ' ', "%20" );
360 std::string curlUnEscape( std::string text_r ) {
361 char * tmp = curl_unescape( text_r.c_str(), 0 );
362 std::string ret( tmp );
367 Url clearQueryString(const Url &url)
370 curlUrl.setUsername( "" );
371 curlUrl.setPassword( "" );
372 curlUrl.setPathParams( "" );
373 curlUrl.setFragment( "" );
374 curlUrl.delQueryParam("cookies");
375 curlUrl.delQueryParam("proxy");
376 curlUrl.delQueryParam("proxyport");
377 curlUrl.delQueryParam("proxyuser");
378 curlUrl.delQueryParam("proxypass");
379 curlUrl.delQueryParam("ssl_capath");
380 curlUrl.delQueryParam("ssl_verify");
381 curlUrl.delQueryParam("ssl_clientcert");
382 curlUrl.delQueryParam("timeout");
383 curlUrl.delQueryParam("auth");
384 curlUrl.delQueryParam("username");
385 curlUrl.delQueryParam("password");
386 curlUrl.delQueryParam("mediahandler");
387 curlUrl.delQueryParam("credentials");
388 curlUrl.delQueryParam("head_requests");
392 // bsc#933839: propagate proxy settings passed in the repo URL
393 // boo#1127591: propagate ssl settings passed in the repo URL
394 zypp::Url propagateQueryParams( zypp::Url url_r, const zypp::Url & template_r )
396 using namespace std::literals::string_literals;
397 for ( const std::string ¶m : { "proxy"s, "proxyport"s, "proxyuser"s, "proxypass"s, "ssl_capath"s, "ssl_verify"s } )
399 const std::string & value( template_r.getQueryParam( param ) );
400 if ( ! value.empty() )
401 url_r.setQueryParam( param, value );