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 )
166 static const std::string
_value(
168 "X-ZYpp-AnonymousId: %s",
180 static const std::string
_value(
182 "X-ZYpp-DistributionFlavor: %s",
194 static const std::string
_value(
196 "ZYpp " LIBZYPP_VERSION_STRING
" (curl %s) %s"
197 , curl_version_info(CURLVERSION_NOW)->version
213 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
218 #define SET_OPTION(opt,val) do { \
219 ret = curl_easy_setopt ( _curl, opt, val ); \
221 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
225 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
226 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
227 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
229 MediaCurl::MediaCurl(
const Url & url_r,
230 const Pathname & attach_point_hint_r )
240 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
242 globalInitCurlOnce();
248 char *atemp = ::strdup( apath.
asString().c_str());
251 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
253 WAR <<
"attach point " << ainfo.
path()
254 <<
" is not useable for " << url_r.
getScheme() << endl;
257 else if( atest != NULL)
267 return internal::clearQueryString(
url);
279 curl_version_info_data *curl_info = NULL;
280 curl_info = curl_version_info(CURLVERSION_NOW);
282 if (curl_info->protocols)
284 const char *
const *proto;
287 for(proto=curl_info->protocols; !found && *proto; ++proto)
289 if( scheme == std::string((
const char *)*proto))
294 std::string msg(
"Unsupported protocol '");
308 curl_easy_setopt(
_curl, CURLOPT_VERBOSE, 1L);
309 curl_easy_setopt(
_curl, CURLOPT_DEBUGFUNCTION, log_curl);
314 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
316 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
318 ZYPP_THROW(MediaCurlSetOptException(
_url,
"Error setting error buffer"));
326 TransferSettings vol_settings(
_settings);
334 vol_settings.addHeader(
"Pragma:");
337 _settings.setConnectTimeout(CONNECT_TIMEOUT);
346 catch (
const MediaException &e )
359 switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
361 case 4:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
break;
362 case 6:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
break;
385 #if CURLVERSION_AT_LEAST(7,19,4)
388 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
390 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
399 if( !
_settings.clientCertificatePath().empty() )
403 if( !
_settings.clientKeyPath().empty() )
408 #ifdef CURLSSLOPT_ALLOW_BEAST
410 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
419 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
436 const auto cred = cm.getCred(
_url );
437 if ( cred && cred->valid() ) {
454 std::string use_auth =
_settings.authType();
455 if (use_auth.empty())
456 use_auth =
"digest,basic";
457 long auth = CurlAuthData::auth_type_str2long(use_auth);
458 if( auth != CURLAUTH_NONE)
460 DBG <<
"Enabling HTTP authentication methods: " << use_auth
461 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
470 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
478 std::string proxyuserpwd =
_settings.proxyUserPassword();
480 if ( proxyuserpwd.empty() )
483 CurlConfig::parseConfig(curlconf);
484 if ( curlconf.proxyuserpwd.empty() )
485 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
488 proxyuserpwd = curlconf.proxyuserpwd;
489 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
494 DBG <<
"Proxy: using provided proxy-user '" <<
_settings.proxyUsername() <<
"'" << endl;
497 if ( ! proxyuserpwd.empty() )
499 SET_OPTION(CURLOPT_PROXYUSERPWD, curlUnEscape( proxyuserpwd ).c_str());
502 #if CURLVERSION_AT_LEAST(7,19,4)
503 else if (
_settings.proxy() == EXPLICITLY_NO_PROXY )
507 DBG <<
"Proxy: explicitly NOPROXY" << endl;
513 DBG <<
"Proxy: not explicitly set" << endl;
514 DBG <<
"Proxy: libcurl may look into the environment" << endl;
525 #if CURLVERSION_AT_LEAST(7,15,5)
538 MIL <<
"No cookies requested" << endl;
543 #if CURLVERSION_AT_LEAST(7,18,0)
548 for (
const auto &header : vol_settings.headers() )
578 _curl = curl_easy_init();
615 curl_easy_cleanup(
_curl );
655 const auto &filename = srcFile.
filename();
671 catch (MediaUnauthorizedException & ex_r)
682 catch (MediaException & excpt_r)
685 if(
typeid(excpt_r) ==
typeid( media::MediaFileNotFoundException ) ||
686 typeid(excpt_r) ==
typeid( media::MediaNotAFileException ) )
690 report->finish(fileurl, reason, excpt_r.asUserHistory());
712 catch (MediaUnauthorizedException & ex_r)
720 catch (MediaException & excpt_r)
734 bool timeout_reached)
const
739 if (filename.
empty())
748 case CURLE_UNSUPPORTED_PROTOCOL:
749 err =
" Unsupported protocol";
752 err +=
" or redirect (";
757 case CURLE_URL_MALFORMAT:
758 case CURLE_URL_MALFORMAT_USER:
761 case CURLE_LOGIN_DENIED:
763 MediaUnauthorizedException(
url,
"Login failed.",
_curlError,
""));
765 case CURLE_HTTP_RETURNED_ERROR:
767 long httpReturnCode = 0;
768 CURLcode infoRet = curl_easy_getinfo(
_curl,
769 CURLINFO_RESPONSE_CODE,
771 if ( infoRet == CURLE_OK )
773 std::string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
774 switch ( httpReturnCode )
780 DBG << msg <<
" Login failed (URL: " <<
url.
asString() <<
")" << std::endl;
781 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
796 if (
url.
getHost().find(
".suse.com") != std::string::npos )
797 msg403 =
_(
"Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
798 else if (
url.
asString().find(
"novell.com") != std::string::npos)
799 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
812 std::string msg =
"Unable to retrieve HTTP response:";
818 case CURLE_FTP_COULDNT_RETR_FILE:
819 #if CURLVERSION_AT_LEAST(7,16,0)
820 case CURLE_REMOTE_FILE_NOT_FOUND:
822 case CURLE_FTP_ACCESS_DENIED:
823 case CURLE_TFTP_NOTFOUND:
824 err =
"File not found";
827 case CURLE_BAD_PASSWORD_ENTERED:
828 case CURLE_FTP_USER_PASSWORD_INCORRECT:
829 err =
"Login failed";
831 case CURLE_COULDNT_RESOLVE_PROXY:
832 case CURLE_COULDNT_RESOLVE_HOST:
833 case CURLE_COULDNT_CONNECT:
834 case CURLE_FTP_CANT_GET_HOST:
835 err =
"Connection failed";
837 case CURLE_WRITE_ERROR:
840 case CURLE_PARTIAL_FILE:
841 case CURLE_OPERATION_TIMEDOUT:
842 timeout_reached =
true;
844 case CURLE_ABORTED_BY_CALLBACK:
845 if( timeout_reached )
847 err =
"Timeout reached";
855 case CURLE_SSL_PEER_CERTIFICATE:
901 std::string urlBuffer( curlUrl.
asString());
902 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
915 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
917 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
920 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
921 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
927 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
931 AutoFILE file { ::fopen(
"/dev/null",
"w" ) };
933 ERR <<
"fopen failed for /dev/null" << endl;
934 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
935 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
941 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
948 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, (*file) );
951 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
952 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
958 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
965 CURLcode ok = curl_easy_perform(
_curl );
966 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
971 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
981 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
990 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1002 catch (
const MediaFileNotFoundException &e ) {
1006 catch (
const MediaException &e ) {
1011 return ( ok == CURLE_OK );
1017 #if DETECT_DIR_INDEX
1030 bool not_a_file =
false;
1032 CURLcode ret = curl_easy_getinfo(
_curl,
1033 CURLINFO_EFFECTIVE_URL,
1035 if ( ret == CURLE_OK && ptr != NULL)
1040 std::string path( eurl.getPathName());
1041 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1043 DBG <<
"Effective url ("
1045 <<
") seems to provide the index of a directory"
1064 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
1074 ERR <<
"out of memory for temp file name" << endl;
1078 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1081 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1086 file = ::fdopen( tmp_fd,
"we" );
1089 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1092 tmp_fd.resetDispose();
1095 DBG <<
"dest: " << dest << endl;
1096 DBG <<
"temp: " << destNew << endl;
1101 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1102 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(target).mtime());
1106 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1107 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1115 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1116 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1120 long httpReturnCode = 0;
1121 CURLcode infoRet = curl_easy_getinfo(
_curl,
1122 CURLINFO_RESPONSE_CODE,
1124 bool modified =
true;
1125 if (infoRet == CURLE_OK)
1128 if ( httpReturnCode == 304
1131 DBG <<
" Not modified.";
1138 WAR <<
"Could not get the response code." << endl;
1141 if (modified || infoRet != CURLE_OK)
1146 ERR <<
"Failed to chmod file " << destNew << endl;
1150 if ( ::fclose( file ) )
1152 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1157 if (
rename( destNew, dest ) != 0 ) {
1158 ERR <<
"Rename failed" << endl;
1161 destNew.resetDispose();
1197 std::string urlBuffer( curlUrl.
asString());
1198 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1199 urlBuffer.c_str() );
1204 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1212 report->start(
url, dest);
1213 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1214 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1217 ret = curl_easy_perform(
_curl );
1218 #if CURLVERSION_AT_LEAST(7,19,4)
1223 if ( ftell(file) == 0 && ret == 0 )
1225 long httpReturnCode = 33;
1226 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1228 long conditionUnmet = 33;
1229 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1231 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1232 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1233 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1234 ret = curl_easy_perform(
_curl );
1240 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1241 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1247 <<
", temp file size " << ftell(file)
1248 <<
" bytes." << endl;
1260 catch (
const MediaException &e ) {
1266 #if DETECT_DIR_INDEX
1281 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1282 Pathname filename = dirname + it->name;
1285 switch ( it->type ) {
1292 getDir( filename, recurse_r );
1296 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1310 const Pathname & dirname,
bool dots )
const
1318 const Pathname & dirname,
bool dots )
const
1345 long httpReturnCode = 0;
1346 if ( curl_easy_getinfo( pdata->
curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1347 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1358 return pdata ? pdata->
curl : 0;
1365 long auth_info = CURLAUTH_NONE;
1368 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1370 if(infoRet == CURLE_OK)
1372 return CurlAuthData::auth_type_long2str(auth_info);
1395 CredentialManager cm(CredManagerOptions(
ZConfig::instance().repoManagerRoot()));
1396 CurlAuthData_Ptr credentials;
1399 AuthData_Ptr cmcred = cm.getCred(
_url);
1401 if (cmcred && firstTry)
1403 credentials.reset(
new CurlAuthData(*cmcred));
1404 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1410 CurlAuthData_Ptr curlcred;
1411 curlcred.reset(
new CurlAuthData());
1419 curlcred->setUsername(cmcred->username());
1428 curlcred->setAuthType(availAuthTypes);
1431 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1433 DBG <<
"callback answer: retry" << endl
1434 <<
"CurlAuthData: " << *curlcred << endl;
1436 if (curlcred->valid())
1438 credentials = curlcred;
1452 DBG <<
"callback answer: cancel" << endl;
1464 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_USERPWD,
_settings.userPassword().c_str());
1468 if (credentials->authType() == CURLAUTH_NONE)
1469 credentials->setAuthType(availAuthTypes);
1472 if (credentials->authType() != CURLAUTH_NONE)
1475 const_cast<MediaCurl*
>(
this)->
_settings.setAuthType(credentials->authTypeAsString());
1476 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1482 credentials->setUrl(
_url);
1483 cm.addCred(*credentials);
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
void resetDispose()
Set no dispose function.
Store and operate with byte count.
Base class for Exception.
const char * c_str() const
ProgressData()
Ctor no range [0,0](0).
std::string distributionFlavor() const
This is flavor attribute of the installed base product but does not require the target to be loaded a...
std::string anonymousUniqueId() const
anonymous unique id
std::string targetDistribution() const
This is register.target attribute of the installed base product.
std::string getScheme() const
Returns the scheme name of the URL.
std::string asString() const
Returns a default string representation of the Url object.
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
std::string getQueryParam(const std::string ¶m, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
bool isValid() const
Verifies the Url.
static ZConfig & instance()
Singleton ctor.
Wrapper class for ::stat/::lstat.
const Pathname & path() const
Return current Pathname.
Pathname extend(const std::string &r) const
Append string r to the last component of the path.
Pathname dirname() const
Return all but the last component od this path.
const std::string & asString() const
String representation.
bool empty() const
Test for an empty path.
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
const char * agentString()
const char * distributionFlavorHeader()
const char * anonymousIdHeader()
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
int unlink(const Pathname &path)
Like 'unlink'.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
int rmdir(const Pathname &path)
Like 'rmdir'.
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
int assert_file_mode(const Pathname &path, unsigned mode)
Like assert_file but enforce mode even if the file already exists.
std::list< DirEntry > DirContent
Returned by readdir.
std::string numstring(char n, int w=0)
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
std::string trim(const std::string &s, const Trim trim_r)
Easy-to use interface to the ZYPP dependency resolver.
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
zypp::ByteCount _expectedFileSize
void updateStats(double dltotal=0.0, double dlnow=0.0)
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
time_t _timeRcv
Start of no-data timeout.
time_t _timeLast
Start last period(~1sec)
int reportProgress() const
double _drateLast
Download rate in last period.
double _dnlTotal
Bytes to download or 0 if unknown.
double _dnlNow
Bytes downloaded now.
double _drateTotal
Download rate so far.
zypp::callback::SendReport< zypp::media::DownloadProgressReport > * report
double _dnlLast
Bytes downloaded at period start.
time_t _timeStart
Start total stats.
AutoDispose<int> calling ::close
AutoDispose<FILE*> calling ::fclose
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.