16 #include <zypp/base/Logger.h> 17 #include <zypp/ExternalProgram.h> 18 #include <zypp/base/String.h> 19 #include <zypp/base/Gettext.h> 20 #include <zypp-core/parser/Sysconfig> 21 #include <zypp/base/Gettext.h> 24 #include <zypp-curl/ProxyInfo> 25 #include <zypp-curl/auth/CurlAuthData> 26 #include <zypp-media/auth/CredentialManager> 27 #include <zypp-curl/CurlConfig> 28 #include <zypp-curl/private/curlhelper_p.h> 34 #include <sys/types.h> 36 #include <sys/mount.h> 59 time_t _timeStart = 0;
64 double _dnlTotal = 0.0;
65 double _dnlLast = 0.0;
70 double _drateTotal= 0.0;
71 double _drateLast = 0.0;
73 void updateStats(
double dltotal = 0.0,
double dlnow = 0.0 );
75 int reportProgress()
const;
101 , fileSizeExceeded ( false )
103 , _expectedFileSize( expectedFileSize_r )
114 if ( dlnow && dlnow !=
_dnlNow )
172 static const std::string
_value(
174 "X-ZYpp-AnonymousId: %s",
186 static const std::string
_value(
188 "X-ZYpp-DistributionFlavor: %s",
200 static const std::string
_value(
202 "ZYpp " LIBZYPP_VERSION_STRING
" (curl %s) %s" 203 , curl_version_info(CURLVERSION_NOW)->version
219 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
224 #define SET_OPTION(opt,val) do { \ 225 ret = curl_easy_setopt ( _curl, opt, val ); \ 227 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \ 231 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val) 232 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val) 233 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val) 235 MediaCurl::MediaCurl(
const Url & url_r,
236 const Pathname & attach_point_hint_r )
246 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
248 globalInitCurlOnce();
254 char *atemp = ::strdup( apath.
asString().c_str());
257 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
259 WAR <<
"attach point " << ainfo.
path()
260 <<
" is not useable for " << url_r.
getScheme() << endl;
263 else if( atest != NULL)
273 return internal::clearQueryString(
url);
285 curl_version_info_data *curl_info = NULL;
286 curl_info = curl_version_info(CURLVERSION_NOW);
288 if (curl_info->protocols)
290 const char *
const *proto;
293 for(proto=curl_info->protocols; !found && *proto; ++proto)
295 if( scheme == std::string((
const char *)*proto))
300 std::string msg(
"Unsupported protocol '");
314 curl_easy_setopt(
_curl, CURLOPT_VERBOSE, 1L);
315 curl_easy_setopt(
_curl, CURLOPT_DEBUGFUNCTION, log_curl);
320 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
322 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
324 ZYPP_THROW(MediaCurlSetOptException(
_url,
"Error setting error buffer"));
332 TransferSettings vol_settings(
_settings);
340 vol_settings.addHeader(
"Pragma:");
343 _settings.setConnectTimeout(CONNECT_TIMEOUT);
352 catch (
const MediaException &e )
365 switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
367 case 4:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
break;
368 case 6:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
break;
391 #if CURLVERSION_AT_LEAST(7,19,4) 394 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
396 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
405 if( !
_settings.clientCertificatePath().empty() )
409 if( !
_settings.clientKeyPath().empty() )
414 #ifdef CURLSSLOPT_ALLOW_BEAST 416 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
425 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
442 const auto cred = cm.getCred(
_url );
443 if ( cred && cred->valid() ) {
460 std::string use_auth =
_settings.authType();
461 if (use_auth.empty())
462 use_auth =
"digest,basic";
463 long auth = CurlAuthData::auth_type_str2long(use_auth);
464 if( auth != CURLAUTH_NONE)
466 DBG <<
"Enabling HTTP authentication methods: " << use_auth
467 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
476 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
484 std::string proxyuserpwd =
_settings.proxyUserPassword();
486 if ( proxyuserpwd.empty() )
489 CurlConfig::parseConfig(curlconf);
490 if ( curlconf.proxyuserpwd.empty() )
491 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
494 proxyuserpwd = curlconf.proxyuserpwd;
495 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
500 DBG <<
"Proxy: using provided proxy-user '" <<
_settings.proxyUsername() <<
"'" << endl;
503 if ( ! proxyuserpwd.empty() )
505 SET_OPTION(CURLOPT_PROXYUSERPWD, curlUnEscape( proxyuserpwd ).c_str());
508 #if CURLVERSION_AT_LEAST(7,19,4) 509 else if (
_settings.proxy() == EXPLICITLY_NO_PROXY )
513 DBG <<
"Proxy: explicitly NOPROXY" << endl;
519 DBG <<
"Proxy: not explicitly set" << endl;
520 DBG <<
"Proxy: libcurl may look into the environment" << endl;
531 #if CURLVERSION_AT_LEAST(7,15,5) 544 MIL <<
"No cookies requested" << endl;
549 #if CURLVERSION_AT_LEAST(7,18,0) 554 for (
const auto &header : vol_settings.headers() )
584 _curl = curl_easy_init();
621 curl_easy_cleanup(
_curl );
661 const auto &filename = srcFile.
filename();
677 catch (MediaUnauthorizedException & ex_r)
688 catch (MediaException & excpt_r)
691 if(
typeid(excpt_r) ==
typeid( media::MediaFileNotFoundException ) ||
692 typeid(excpt_r) ==
typeid( media::MediaNotAFileException ) )
696 report->finish(fileurl, reason, excpt_r.asUserHistory());
718 catch (MediaUnauthorizedException & ex_r)
726 catch (MediaException & excpt_r)
740 bool timeout_reached)
const 745 if (filename.
empty())
754 case CURLE_UNSUPPORTED_PROTOCOL:
755 err =
" Unsupported protocol";
758 err +=
" or redirect (";
763 case CURLE_URL_MALFORMAT:
764 case CURLE_URL_MALFORMAT_USER:
767 case CURLE_LOGIN_DENIED:
769 MediaUnauthorizedException(
url,
"Login failed.",
_curlError,
""));
771 case CURLE_HTTP_RETURNED_ERROR:
773 long httpReturnCode = 0;
774 CURLcode infoRet = curl_easy_getinfo(
_curl,
775 CURLINFO_RESPONSE_CODE,
777 if ( infoRet == CURLE_OK )
779 std::string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
780 switch ( httpReturnCode )
786 DBG << msg <<
" Login failed (URL: " <<
url.
asString() <<
")" << std::endl;
787 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
802 if (
url.
getHost().find(
".suse.com") != std::string::npos )
803 msg403 =
_(
"Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
804 else if (
url.
asString().find(
"novell.com") != std::string::npos)
805 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
818 std::string msg =
"Unable to retrieve HTTP response:";
824 case CURLE_FTP_COULDNT_RETR_FILE:
825 #if CURLVERSION_AT_LEAST(7,16,0) 826 case CURLE_REMOTE_FILE_NOT_FOUND:
828 case CURLE_FTP_ACCESS_DENIED:
829 case CURLE_TFTP_NOTFOUND:
830 err =
"File not found";
833 case CURLE_BAD_PASSWORD_ENTERED:
834 case CURLE_FTP_USER_PASSWORD_INCORRECT:
835 err =
"Login failed";
837 case CURLE_COULDNT_RESOLVE_PROXY:
838 case CURLE_COULDNT_RESOLVE_HOST:
839 case CURLE_COULDNT_CONNECT:
840 case CURLE_FTP_CANT_GET_HOST:
841 err =
"Connection failed";
843 case CURLE_WRITE_ERROR:
846 case CURLE_PARTIAL_FILE:
847 case CURLE_OPERATION_TIMEDOUT:
848 timeout_reached =
true;
850 case CURLE_ABORTED_BY_CALLBACK:
851 if( timeout_reached )
853 err =
"Timeout reached";
861 case CURLE_SSL_PEER_CERTIFICATE:
907 std::string urlBuffer( curlUrl.
asString());
908 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
921 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
923 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
926 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
927 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
933 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
937 AutoFILE file { ::fopen(
"/dev/null",
"w" ) };
939 ERR <<
"fopen failed for /dev/null" << endl;
940 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
941 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
947 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
954 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, (*file) );
957 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
958 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
964 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
971 CURLcode ok = curl_easy_perform(
_curl );
972 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
977 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
987 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
996 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1008 catch (
const MediaFileNotFoundException &e ) {
1012 catch (
const MediaException &e ) {
1017 return ( ok == CURLE_OK );
1023 #if DETECT_DIR_INDEX 1036 bool not_a_file =
false;
1038 CURLcode ret = curl_easy_getinfo(
_curl,
1039 CURLINFO_EFFECTIVE_URL,
1041 if ( ret == CURLE_OK && ptr != NULL)
1046 std::string path( eurl.getPathName());
1047 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1049 DBG <<
"Effective url (" 1051 <<
") seems to provide the index of a directory" 1070 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
1080 ERR <<
"out of memory for temp file name" << endl;
1084 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1087 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1092 file = ::fdopen( tmp_fd,
"we" );
1095 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1098 tmp_fd.resetDispose();
1101 DBG <<
"dest: " << dest << endl;
1102 DBG <<
"temp: " << destNew << endl;
1107 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1108 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(target).mtime());
1112 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1113 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1121 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1122 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1126 long httpReturnCode = 0;
1127 CURLcode infoRet = curl_easy_getinfo(
_curl,
1128 CURLINFO_RESPONSE_CODE,
1130 bool modified =
true;
1131 if (infoRet == CURLE_OK)
1134 if ( httpReturnCode == 304
1137 DBG <<
" Not modified.";
1144 WAR <<
"Could not get the response code." << endl;
1147 if (modified || infoRet != CURLE_OK)
1152 ERR <<
"Failed to chmod file " << destNew << endl;
1156 if ( ::fclose( file ) )
1158 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1163 if (
rename( destNew, dest ) != 0 ) {
1164 ERR <<
"Rename failed" << endl;
1167 destNew.resetDispose();
1203 std::string urlBuffer( curlUrl.
asString());
1204 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1205 urlBuffer.c_str() );
1210 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1218 report->start(
url, dest);
1219 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1220 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1223 ret = curl_easy_perform(
_curl );
1224 #if CURLVERSION_AT_LEAST(7,19,4) 1229 if ( ftell(file) == 0 && ret == 0 )
1231 long httpReturnCode = 33;
1232 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1234 long conditionUnmet = 33;
1235 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1237 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1238 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1239 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1240 ret = curl_easy_perform(
_curl );
1246 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1247 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1253 <<
", temp file size " << ftell(file)
1254 <<
" bytes." << endl;
1261 if ( progressData.fileSizeExceeded )
1262 ZYPP_THROW(MediaFileSizeExceededException(
url, progressData._expectedFileSize));
1266 catch (
const MediaException &e ) {
1272 #if DETECT_DIR_INDEX 1277 #endif // DETECT_DIR_INDEX 1287 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1288 Pathname filename = dirname + it->name;
1291 switch ( it->type ) {
1298 getDir( filename, recurse_r );
1302 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1316 const Pathname & dirname,
bool dots )
const 1324 const Pathname & dirname,
bool dots )
const 1351 long httpReturnCode = 0;
1352 if ( curl_easy_getinfo( pdata->
curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1353 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1364 return pdata ? pdata->
curl : 0;
1371 long auth_info = CURLAUTH_NONE;
1374 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1376 if(infoRet == CURLE_OK)
1378 return CurlAuthData::auth_type_long2str(auth_info);
1401 CredentialManager cm(CredManagerOptions(
ZConfig::instance().repoManagerRoot()));
1402 CurlAuthData_Ptr credentials;
1405 AuthData_Ptr cmcred = cm.getCred(
_url);
1407 if (cmcred && firstTry)
1409 credentials.reset(
new CurlAuthData(*cmcred));
1410 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1416 CurlAuthData_Ptr curlcred;
1417 curlcred.reset(
new CurlAuthData());
1425 curlcred->setUsername(cmcred->username());
1434 curlcred->setAuthType(availAuthTypes);
1437 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1439 DBG <<
"callback answer: retry" << endl
1440 <<
"CurlAuthData: " << *curlcred << endl;
1442 if (curlcred->valid())
1444 credentials = curlcred;
1458 DBG <<
"callback answer: cancel" << endl;
1470 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_USERPWD,
_settings.userPassword().c_str());
1474 if (credentials->authType() == CURLAUTH_NONE)
1475 credentials->setAuthType(availAuthTypes);
1478 if (credentials->authType() != CURLAUTH_NONE)
1481 const_cast<MediaCurl*
>(
this)->
_settings.setAuthType(credentials->authTypeAsString());
1482 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1488 credentials->setUrl(
_url);
1489 cm.addCred(*credentials);
std::string getScheme() const
Returns the scheme name of the URL.
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
std::string targetDistribution() const
This is register.target attribute of the installed base product.
ProgressData()
Ctor no range [0,0](0).
const Pathname & path() const
Return current Pathname.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
static ZConfig & instance()
Singleton ctor.
const char * distributionFlavorHeader()
Store and operate with byte count.
Pathname extend(const std::string &r) const
Append string r to the last component of the path.
int reportProgress() const
const char * anonymousIdHeader()
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
AutoDispose<int> calling ::close
bool empty() const
Test for an empty path.
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
int assert_file_mode(const Pathname &path, unsigned mode)
Like assert_file but enforce mode even if the file already exists.
double _dnlTotal
Bytes to download or 0 if unknown.
std::string asString() const
Returns a default string representation of the Url object.
std::string getQueryParam(const std::string ¶m, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
std::string trim(const std::string &s, const Trim trim_r)
int unlink(const Pathname &path)
Like 'unlink'.
const std::string & asString() const
String representation.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
Pathname dirname() const
Return all but the last component od this path.
double _dnlLast
Bytes downloaded at period start.
std::list< DirEntry > DirContent
Returned by readdir.
bool isValid() const
Verifies the Url.
std::string numstring(char n, int w=0)
const char * agentString()
void resetDispose()
Set no dispose function.
zypp::ByteCount _expectedFileSize
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
int rmdir(const Pathname &path)
Like 'rmdir'.
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
Base class for Exception.
double _drateLast
Download rate in last period.
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
time_t _timeStart
Start total stats.
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
double _dnlNow
Bytes downloaded now.
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Wrapper class for ::stat/::lstat.
AutoDispose<FILE*> calling ::fclose
void updateStats(double dltotal=0.0, double dlnow=0.0)
double _drateTotal
Download rate so far.
std::string anonymousUniqueId() const
anonymous unique id
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
time_t _timeRcv
Start of no-data timeout.
Easy-to use interface to the ZYPP dependency resolver.
std::string distributionFlavor() const
This is flavor attribute of the installed base product but does not require the target to be loaded a...
time_t _timeLast
Start last period(~1sec)
const char * c_str() const
zypp::callback::SendReport< zypp::media::DownloadProgressReport > * report
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.