libzypp  17.31.9
curlhelper.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
12 #include "private/curlhelper_p.h"
13 
14 #include <zypp/APIConfig.h>
15 
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>
24 #include <list>
25 #include <string>
26 
27 using std::endl;
28 using namespace zypp;
29 
30 namespace zypp
31 {
32  namespace env
33  {
34  const long & ZYPP_MEDIA_CURL_DEBUG()
35  {
36  static const long ret = [](){
37  const char * env = getenv("ZYPP_MEDIA_CURL_DEBUG");
38  return env && *env ? str::strtonum<ulong>( env ) : 0;
39  }();
40  return ret;
41  }
42 
44  {
45  static int _v = [](){
46  int ret = 0;
47  if ( const char * envp = getenv( "ZYPP_MEDIA_CURL_IPRESOLVE" ) ) {
48  WAR << "env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp << "'" << std::endl;
49  if ( strcmp( envp, "4" ) == 0 ) ret = 4;
50  else if ( strcmp( envp, "6" ) == 0 ) ret = 6;
51  }
52  return ret;
53  }();
54  return _v;
55  }
56  } // namespace env
57 } // namespace zypp
58 
59 namespace internal
60 {
61 
63 {
64  // function-level static <=> std::call_once
65  static bool once __attribute__ ((__unused__)) = ( [] {
66  if ( curl_global_init( CURL_GLOBAL_ALL ) != 0 )
67  WAR << "curl global init failed" << std::endl;
68  } (), true );
69 }
70 
71 int log_curl( CURL * curl, curl_infotype info, char * ptr, size_t len, void * max_lvl )
72 {
73  if ( max_lvl == nullptr )
74  return 0;
75 
76  long maxlvl = *((long *)max_lvl);
77  const char * pfx = "";
78  bool isContent = true; // otherwise it's data
79  switch( info )
80  {
81  case CURLINFO_TEXT: if ( maxlvl < 1 ) return 0; pfx = "*"; break;
82  case CURLINFO_HEADER_IN: if ( maxlvl < 2 ) return 0; pfx = "<"; break;
83  case CURLINFO_HEADER_OUT: if ( maxlvl < 2 ) return 0; pfx = ">"; break;
84  case CURLINFO_SSL_DATA_IN: if ( maxlvl < 3 ) return 0; isContent = false; pfx = "<[SSL]"; break;
85  case CURLINFO_SSL_DATA_OUT: if ( maxlvl < 3 ) return 0; isContent = false; pfx = ">[SSL]"; break;
86  case CURLINFO_DATA_IN: if ( maxlvl < 3 ) return 0; isContent = false; pfx = "<[DTA]"; break;
87  case CURLINFO_DATA_OUT: if ( maxlvl < 3 ) return 0; isContent = false; pfx = ">[DTA]"; break;
88 
89  default:
90  return 0;
91  }
92 
93  // We'd like to keep all log messages within function `log_curl`
94  // because this tag to grep for is known and communicate to users.
95  if ( isContent ) {
96  std::vector<std::string_view> lines; // don't want log from within the lambda
97  strv::split( std::string_view( ptr, len ), "\n", [&lines]( std::string_view line, unsigned, bool last ) {
98  if ( last ) return; // empty word after final \n
99  line = strv::rtrim( line, "\r" );
100  lines.push_back( line );
101  });
102  for ( const auto & line : lines ) {
103  if ( str::hasPrefix( line, "Authorization:" ) ) {
104  std::string_view::size_type pos { line.find( " ", 15 ) }; // Authorization: <type> <credentials>
105  if ( pos == std::string::npos )
106  pos = 15;
107  DBG << curl << " " << pfx << " " << line.substr( 0, pos ) << " <credentials removed>" << endl;
108  }
109  else
110  DBG << curl << " " << pfx << " " << line << endl;
111  }
112  } else {
113  if ( maxlvl < 4 )
114  DBG << curl << " " << pfx << " " << len << " byte" << endl;
115  else
116  hexdumpOn( DBG << curl << " " << pfx << " ", ptr, len );
117  }
118  return 0;
119 }
120 
121 void setupZYPP_MEDIA_CURL_DEBUG( CURL *curl )
122 {
123  if ( not curl ) {
124  INT << "Got a NULL curl handle" << endl;
125  return;
126  }
127  if ( env::ZYPP_MEDIA_CURL_DEBUG() > 0 ) {
128  curl_easy_setopt( curl, CURLOPT_VERBOSE, 1L );
129  curl_easy_setopt( curl, CURLOPT_DEBUGFUNCTION, log_curl );
130  curl_easy_setopt( curl, CURLOPT_DEBUGDATA, &env::ZYPP_MEDIA_CURL_DEBUG() );
131  }
132 }
133 
134 size_t log_redirects_curl( char *ptr, size_t size, size_t nmemb, void *userdata)
135 {
136  //INT << "got header: " << std::string(ptr, ptr + size*nmemb) << endl;
137 
138  char * lstart = ptr, * lend = ptr;
139  size_t pos = 0;
140  size_t max = size * nmemb;
141  while (pos + 1 < max)
142  {
143  // get line
144  for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
145 
146  // look for "Location"
147  if ( strncasecmp( lstart, "Location:", 9 ) == 0 )
148  {
149  std::string line { lstart, *(lend-1)=='\r' ? lend-1 : lend };
150  DBG << "redirecting to " << line << std::endl;
151  if ( userdata ) {
152  *reinterpret_cast<std::string *>( userdata ) = line;
153  }
154  return max;
155  }
156 
157  // continue with the next line
158  if (pos + 1 < max)
159  {
160  ++lend;
161  ++pos;
162  }
163  else
164  break;
165  }
166 
167  return max;
168 }
169 
175 {
176  {
177  const std::string & param { url.getQueryParam("timeout") };
178  if( ! param.empty() )
179  {
180  long num = str::strtonum<long>(param);
181  if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX )
182  s.setTimeout( num );
183  }
184  }
185  {
186  std::string param { url.getUsername() };
187  if ( ! param.empty() )
188  {
189  s.setUsername( std::move(param) );
190  param = url.getPassword();
191  if ( ! param.empty() )
192  s.setPassword( std::move(param) );
193  }
194  else
195  {
196  // if there is no username, set anonymous auth
197  if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
198  s.setAnonymousAuth();
199  }
200  }
201  if ( url.getScheme() == "https" )
202  {
203  s.setVerifyPeerEnabled( false );
204  s.setVerifyHostEnabled( false );
205 
206  const std::string & verify { url.getQueryParam("ssl_verify") };
207  if( verify.empty() || verify == "yes" )
208  {
209  s.setVerifyPeerEnabled( true );
210  s.setVerifyHostEnabled( true );
211  }
212  else if ( verify == "no" )
213  {
214  s.setVerifyPeerEnabled( false );
215  s.setVerifyHostEnabled( false );
216  }
217  else
218  {
219  std::vector<std::string> flags;
220  str::split( verify, std::back_inserter(flags), "," );
221  for ( const auto & flag : flags )
222  {
223  if ( flag == "host" )
224  s.setVerifyHostEnabled( true );
225  else if ( flag == "peer" )
226  s.setVerifyPeerEnabled( true );
227  else
228  ZYPP_THROW( media::MediaBadUrlException(url, "Unknown ssl_verify flag "+flag) );
229  }
230  }
231  }
232  {
233  Pathname ca_path { url.getQueryParam("ssl_capath") };
234  if( ! ca_path.empty() )
235  {
236  if( ! PathInfo(ca_path).isDir() || ! ca_path.absolute() )
237  ZYPP_THROW(media::MediaBadUrlException(url, "Invalid ssl_capath path"));
238  else
239  s.setCertificateAuthoritiesPath( std::move(ca_path) );
240  }
241  }
242  {
243  Pathname client_cert { url.getQueryParam("ssl_clientcert") };
244  if( ! client_cert.empty() )
245  {
246  if( ! PathInfo(client_cert).isFile() || ! client_cert.absolute() )
247  ZYPP_THROW(media::MediaBadUrlException(url, "Invalid ssl_clientcert file"));
248  else
249  s.setClientCertificatePath( std::move(client_cert) );
250  }
251  }
252  {
253  Pathname client_key { url.getQueryParam("ssl_clientkey") };
254  if( ! client_key.empty() )
255  {
256  if( ! PathInfo(client_key).isFile() || ! client_key.absolute() )
257  ZYPP_THROW(media::MediaBadUrlException(url, "Invalid ssl_clientkey file"));
258  else
259  s.setClientKeyPath( std::move(client_key) );
260  }
261  }
262  {
263  std::string param { url.getQueryParam( "proxy" ) };
264  if ( ! param.empty() )
265  {
266  if ( param == EXPLICITLY_NO_PROXY ) {
267  // Workaround TransferSettings shortcoming: With an
268  // empty proxy string, code will continue to look for
269  // valid proxy settings. So set proxy to some non-empty
270  // string, to indicate it has been explicitly disabled.
272  s.setProxyEnabled(false);
273  }
274  else {
275  const std::string & proxyport { url.getQueryParam( "proxyport" ) };
276  if ( ! proxyport.empty() ) {
277  param += ":";
278  param += proxyport;
279  }
280  s.setProxy( std::move(param) );
281  s.setProxyEnabled( true );
282  }
283  }
284  }
285  {
286  std::string param { url.getQueryParam( "proxyuser" ) };
287  if ( ! param.empty() )
288  {
289  s.setProxyUsername( std::move(param) );
290  s.setProxyPassword( url.getQueryParam( "proxypass" ) );
291  }
292  }
293  {
294  // HTTP authentication type
295  std::string param { url.getQueryParam("auth") };
296  if ( ! param.empty() && (url.getScheme() == "http" || url.getScheme() == "https") )
297  {
298  try
299  {
300  media::CurlAuthData::auth_type_str2long (param ); // check if we know it
301  }
302  catch ( const media::MediaException & ex_r )
303  {
304  DBG << "Rethrowing as MediaUnauthorizedException.";
305  ZYPP_THROW(media::MediaUnauthorizedException(url, ex_r.msg(), "", ""));
306  }
307  s.setAuthType( std::move(param) );
308  }
309  }
310  {
311  // workarounds
312  const std::string & param { url.getQueryParam("head_requests") };
313  if( ! param.empty() && param == "no" )
314  s.setHeadRequestsAllowed( false );
315  }
316 }
317 
323 {
324  media::ProxyInfo proxy_info;
325  if ( proxy_info.useProxyFor( url ) )
326  {
327  // We must extract any 'user:pass' from the proxy url
328  // otherwise they won't make it into curl (.curlrc wins).
329  try {
330  Url u( proxy_info.proxy( url ) );
332  // don't overwrite explicit auth settings
333  if ( s.proxyUsername().empty() )
334  {
335  s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
336  s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
337  }
338  s.setProxyEnabled( true );
339  }
340  catch (...) {} // no proxy if URL is malformed
341  }
342 }
343 
344 void curlEscape( std::string & str_r,
345  const char char_r, const std::string & escaped_r ) {
346  for ( std::string::size_type pos = str_r.find( char_r );
347  pos != std::string::npos; pos = str_r.find( char_r, pos ) ) {
348  str_r.replace( pos, 1, escaped_r );
349  }
350 }
351 
352 std::string curlEscapedPath( std::string path_r ) {
353  curlEscape( path_r, ' ', "%20" );
354  return path_r;
355 }
356 
357 std::string curlUnEscape( std::string text_r ) {
358  char * tmp = curl_unescape( text_r.c_str(), 0 );
359  std::string ret( tmp );
360  curl_free( tmp );
361  return ret;
362 }
363 
365 {
366  Url curlUrl (url);
367  curlUrl.setUsername( "" );
368  curlUrl.setPassword( "" );
369  curlUrl.setPathParams( "" );
370  curlUrl.setFragment( "" );
371  curlUrl.delQueryParam("cookies");
372  curlUrl.delQueryParam("proxy");
373  curlUrl.delQueryParam("proxyport");
374  curlUrl.delQueryParam("proxyuser");
375  curlUrl.delQueryParam("proxypass");
376  curlUrl.delQueryParam("ssl_capath");
377  curlUrl.delQueryParam("ssl_verify");
378  curlUrl.delQueryParam("ssl_clientcert");
379  curlUrl.delQueryParam("timeout");
380  curlUrl.delQueryParam("auth");
381  curlUrl.delQueryParam("username");
382  curlUrl.delQueryParam("password");
383  curlUrl.delQueryParam("mediahandler");
384  curlUrl.delQueryParam("credentials");
385  curlUrl.delQueryParam("head_requests");
386  return curlUrl;
387 }
388 
389 // bsc#933839: propagate proxy settings passed in the repo URL
390 // boo#1127591: propagate ssl settings passed in the repo URL
391 zypp::Url propagateQueryParams( zypp::Url url_r, const zypp::Url & template_r )
392 {
393  using namespace std::literals::string_literals;
394  for ( const std::string &param : { "proxy"s, "proxyport"s, "proxyuser"s, "proxypass"s, "ssl_capath"s, "ssl_verify"s } )
395  {
396  const std::string & value( template_r.getQueryParam( param ) );
397  if ( ! value.empty() )
398  url_r.setQueryParam( param, value );
399  }
400  return url_r;
401 }
402 
403 }
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:533
void setPassword(const std::string &pass, EEncoding eflag=zypp::url::E_DECODED)
Set the password in the URL authority.
Definition: Url.cc:739
void globalInitCurlOnce()
Definition: curlhelper.cc:62
size_t log_redirects_curl(char *ptr, size_t size, size_t nmemb, void *userdata)
Definition: curlhelper.cc:134
void setQueryParam(const std::string &param, const std::string &value)
Set or add value for the specified query parameter.
Definition: Url.cc:838
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:428
zypp::Url propagateQueryParams(zypp::Url url_r, const zypp::Url &template_r)
Definition: curlhelper.cc:391
Flag to request encoded string(s).
Definition: UrlUtils.h:53
void setPassword(const std::string &val_r)
sets the auth password
Holds transfer setting.
const std::string & proxyUsername() const
proxy auth username
#define INT
Definition: Logger.h:100
Url clearQueryString(const Url &url)
Definition: curlhelper.cc:364
bool useProxyFor(const Url &url_r) const
Return true if enabled and url_r does not match noProxy.
Definition: proxyinfo.cc:55
static const ViewOption WITH_SCHEME
Option to include scheme name in the URL string.
Definition: UrlBase.h:51
static const ViewOption WITH_HOST
Option to include hostname in the URL string.
Definition: UrlBase.h:74
void setPathParams(const std::string &params)
Set the path parameters.
Definition: Url.cc:791
void setUsername(const std::string &val_r)
sets the auth username
std::string curlEscapedPath(std::string path_r)
Definition: curlhelper.cc:352
void setHeadRequestsAllowed(bool allowed)
set whether HEAD requests are allowed
void setUsername(const std::string &user, EEncoding eflag=zypp::url::E_DECODED)
Set the username in the URL authority.
Definition: Url.cc:730
void setFragment(const std::string &fragment, EEncoding eflag=zypp::url::E_DECODED)
Set the fragment string in the URL.
Definition: Url.cc:722
const std::string & username() const
auth username
void setAnonymousAuth()
sets anonymous authentication (ie: for ftp)
int ZYPP_MEDIA_CURL_IPRESOLVE()
4/6 to force IPv4/v6
Definition: curlhelper.cc:43
void curlEscape(std::string &str_r, const char char_r, const std::string &escaped_r)
Definition: curlhelper.cc:344
unsigned split(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \, const Trim trim_r=NO_TRIM)
Split line_r into words.
Definition: String.h:531
std::string getQueryParam(const std::string &param, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
Definition: Url.cc:660
void setAuthType(const std::string &val_r)
set the allowed authentication types
void setProxy(const std::string &val_r)
proxy to use if it is enabled
Just inherits Exception to separate media exceptions.
#define WAR
Definition: Logger.h:97
const long & ZYPP_MEDIA_CURL_DEBUG()
const long& for setting CURLOPT_DEBUGDATA Returns a reference to a static variable, so it&#39;s safe to pass ...
Definition: curlhelper.cc:34
void fillSettingsFromUrl(const Url &url, media::TransferSettings &s)
Fills the settings structure using options passed on the url for example ?timeout=x&proxy=foo.
Definition: curlhelper.cc:174
void setTimeout(long t)
set the transfer timeout
std::string proxy(const Url &url) const
Definition: proxyinfo.cc:43
std::ostream & hexdumpOn(std::ostream &outs, const unsigned char *ptr, size_t size)
hexdump data on stream
Definition: LogTools.h:445
SolvableIdType size_type
Definition: PoolMember.h:126
std::string rtrim(const std::string &s)
Definition: String.h:511
struct zypp::media::MediaBlock __attribute__
void setProxyPassword(const std::string &val_r)
sets the proxy password
std::string curlUnEscape(std::string text_r)
Definition: curlhelper.cc:357
void setupZYPP_MEDIA_CURL_DEBUG(CURL *curl)
Setup CURLOPT_VERBOSE and CURLOPT_DEBUGFUNCTION according to env::ZYPP_MEDIA_CURL_DEBUG.
Definition: curlhelper.cc:121
static long auth_type_str2long(std::string &auth_type_str)
Converts a string of comma separated list of authetication type names into a long of ORed CURLAUTH_* ...
Definition: curlauthdata.cc:50
Wrapper class for ::stat/::lstat.
Definition: PathInfo.h:220
void setClientCertificatePath(const Pathname &val_r)
Sets the SSL client certificate file.
void fillSettingsSystemProxy(const Url &url, media::TransferSettings &s)
Reads the system proxy configuration and fills the settings structure proxy information.
Definition: curlhelper.cc:322
void setProxyUsername(const std::string &val_r)
sets the proxy user
void setCertificateAuthoritiesPath(const Pathname &val_r)
Sets the SSL certificate authorities path.
#define EXPLICITLY_NO_PROXY
Definition: curlhelper_p.h:25
static const ViewOption WITH_PORT
Option to include port number in the URL string.
Definition: UrlBase.h:81
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:1
int log_curl(CURL *curl, curl_infotype info, char *ptr, size_t len, void *max_lvl)
Definition: curlhelper.cc:71
bool hasPrefix(const C_Str &str_r, const C_Str &prefix_r)
Return whether str_r has prefix prefix_r.
Definition: String.h:1027
#define TRANSFER_TIMEOUT_MAX
Definition: curlhelper_p.h:22
void setVerifyPeerEnabled(bool enabled)
Sets whether to verify host for ssl.
void setClientKeyPath(const Pathname &val_r)
Sets the SSL client key file.
std::string getPassword(EEncoding eflag=zypp::url::E_DECODED) const
Returns the password from the URL authority.
Definition: Url.cc:580
void setVerifyHostEnabled(bool enabled)
Sets whether to verify host for ssl.
Url manipulation class.
Definition: Url.h:91
void setProxyEnabled(bool enabled)
whether the proxy is used or not
#define DBG
Definition: Logger.h:95
void delQueryParam(const std::string &param)
remove the specified query parameter.
Definition: Url.cc:845
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
Definition: Url.cc:572
const std::string & msg() const
Return the message string provided to the ctor.
Definition: Exception.h:195