15#include <rpm/rpmcli.h> 
   16#include <rpm/rpmlog.h> 
   38#include <zypp-core/base/DtorReset> 
   43#include <zypp-common/PublicKey.h> 
   44#include <zypp-core/ui/ProgressData> 
   55#include <zypp-common/KeyManager.h> 
   63#define WARNINGMAILPATH         "/var/log/YaST2/" 
   64#define FILEFORBACKUPFILES      "YaSTBackupModifiedFiles" 
   65#define MAXRPMMESSAGELINES      10000 
   67#define WORKAROUNDRPMPWDBUG 
   69#undef ZYPP_BASE_LOGGER_LOGGROUP 
   70#define ZYPP_BASE_LOGGER_LOGGROUP "librpmDb" 
   82      static bool val = [](){
 
   83        const char * 
env = getenv(
"ZYPP_RPM_DEBUG");
 
 
   95const char* quoteInFilename_m = 
"\'\"";
 
   96inline std::string rpmQuoteFilename( 
const Pathname & path_r )
 
   98  std::string path( path_r.
asString() );
 
   99  for ( std::string::size_type pos = path.find_first_of( quoteInFilename_m );
 
  100        pos != std::string::npos;
 
  101        pos = path.find_first_of( quoteInFilename_m, pos ) )
 
  103    path.insert( pos, 
"\\" );
 
  114  inline Pathname workaroundRpmPwdBug( Pathname path_r )
 
  116#if defined(WORKAROUNDRPMPWDBUG) 
  120      AutoDispose<char*> cwd( ::get_current_dir_name(), ::free );
 
  122        return Pathname( cwd ) / path_r;
 
  123      WAR << 
"Can't get cwd!" << endl;
 
  145    MIL << 
"trusted key added to zypp Keyring. Importing..." << endl;
 
  146    _rpmdb.importPubkey( key );
 
 
  151    MIL << 
"Trusted key removed from zypp Keyring. Removing..." << endl;
 
  152    _rpmdb.removePubkey( key );
 
 
 
  160unsigned diffFiles(
const std::string& file1, 
const std::string& file2, std::string& out, 
int maxlines)
 
  181    if (maxlines<0?
true:count<maxlines)
 
 
  194#define FAILIFNOTINITIALIZED if( ! initialized() ) { ZYPP_THROW(RpmDbNotOpenException()); } 
  213  setenv( 
"RPM_IgnoreFailedSymlinks", 
"1", 1 );
 
 
  225  MIL << 
"~RpmDb()" << endl;
 
  228  MIL  << 
"~RpmDb() end" << endl;
 
 
  262  if ( root_r.
empty() )
 
  270  if ( dbPath_r != 
"/var/lib/rpm" && ! 
PathInfo( root_r/
"/var/lib/rpm" ).isExist() )
 
  272    WAR << 
"Inject missing /var/lib/rpm compat symlink to " << dbPath_r << endl;
 
  286    if ( root_r == 
_root ) {
 
  294  MIL << 
"Calling initDatabase: " << 
dumpPath( root_r, dbPath_r )
 
  295      << ( doRebuild_r ? 
" (rebuilddb)" : 
"" ) << endl;
 
  309  MIL << 
"Synchronizing keys with zypp keyring" << endl;
 
  317  librpmDb::dbRelease( 
true );
 
  319  MIL << 
"InitDatabase: " << *
this << endl;
 
 
  338  MIL << 
"closeDatabase: " << *
this << endl;
 
 
  369  MIL << 
"RpmDb::rebuildDatabase" << *
this << endl;
 
  383    opts.push_back(
"--rebuilddb");
 
  384    opts.push_back(
"-vv");
 
  394    tics.
range( hdrTotal );
 
  397    return report->progress( tics_r.
reportValue(), mydbpath );
 
  405    static const std::string debugPrefix    { 
"D:" };
 
  406    static const std::string progressPrefix { 
"D:  read h#" };
 
  407    static const std::string ignoreSuffix   { 
"digest: OK" };
 
  422        WAR << 
"User requested abort." << endl;
 
 
  446  void computeKeyRingSync( std::set<Edition> & rpmKeys_r, std::list<PublicKeyData> & zyppKeys_r )
 
  453        : _inRpmKeys( nullptr )
 
  454        , _inZyppKeys( nullptr )
 
  457      void updateIf( 
const Edition & rpmKey_r )
 
  459        std::string keyRelease( rpmKey_r.
release() );
 
  460        int comp = _release.compare( keyRelease );
 
  464          _release.swap( keyRelease );
 
  465          _inRpmKeys  = &rpmKey_r;
 
  466          _inZyppKeys = 
nullptr;
 
  467          if ( !keyRelease.empty() )
 
  468            DBG << 
"Old key in Z: gpg-pubkey-" << rpmKey_r.
version() << 
"-" <<  keyRelease << endl;
 
  470        else if ( comp == 0 )
 
  474            _inRpmKeys = &rpmKey_r;
 
  478          DBG << 
"Old key in R: gpg-pubkey-" << rpmKey_r.
version() << 
"-" <<  keyRelease << endl;
 
  481      void updateIf( 
const PublicKeyData & zyppKey_r )
 
  483        std::string keyRelease( zyppKey_r.gpgPubkeyRelease() );
 
  484        int comp = _release.compare( keyRelease );
 
  488          _release.swap( keyRelease );
 
  489          _inRpmKeys  = 
nullptr;
 
  490          _inZyppKeys = &zyppKey_r;
 
  491          if ( !keyRelease.empty() )
 
  492            DBG << 
"Old key in R: gpg-pubkey-" << zyppKey_r.gpgPubkeyVersion() << 
"-" << keyRelease << endl;
 
  494        else if ( comp == 0 )
 
  498            _inZyppKeys = &zyppKey_r;
 
  502          DBG << 
"Old key in Z: gpg-pubkey-" << zyppKey_r.gpgPubkeyVersion() << 
"-" << keyRelease << endl;
 
  505      std::string _release;
 
  507      const PublicKeyData * _inZyppKeys;
 
  512    std::map<std::string,Key> _keymap;
 
  514    for_( it, rpmKeys_r.begin(), rpmKeys_r.end() )
 
  516      _keymap[(*it).version()].updateIf( *it );
 
  519    for_( it, zyppKeys_r.begin(), zyppKeys_r.end() )
 
  521      _keymap[(*it).gpgPubkeyVersion()].updateIf( *it );
 
  525    std::set<Edition> rpmKeys;
 
  526    std::list<PublicKeyData> zyppKeys;
 
  527    for_( it, _keymap.begin(), _keymap.end() )
 
  529      DBG << 
"gpg-pubkey-" << (*it).first << 
"-" << (*it).second._release << 
" " 
  530          << ( (*it).second._inRpmKeys  ? 
"R" : 
"_" )
 
  531          << ( (*it).second._inZyppKeys ? 
"Z" : 
"_" ) << endl;
 
  532      if ( ! (*it).second._inRpmKeys )
 
  534        zyppKeys.push_back( *(*it).second._inZyppKeys );
 
  536      if ( ! (*it).second._inZyppKeys )
 
  538        rpmKeys.insert( *(*it).second._inRpmKeys );
 
  541    rpmKeys_r.swap( rpmKeys );
 
  542    zyppKeys_r.swap( zyppKeys );
 
  549  MIL << 
"Going to sync trusted keys..." << endl;
 
  551  std::list<PublicKeyData> zyppKeys( 
getZYpp()->keyRing()->trustedPublicKeyData() );
 
  563    MIL << 
"Removing excess keys in zypp trusted keyring" << std::endl;
 
  567    for ( 
const PublicKeyData & keyData : zyppKeys )
 
  569      if ( ! rpmKeys.count( keyData.gpgPubkeyEdition() ) )
 
  571        DBG << 
"Excess key in Z to delete: gpg-pubkey-" << keyData.gpgPubkeyEdition() << endl;
 
  572        getZYpp()->keyRing()->deleteKey( keyData.id(), 
true );
 
  573        if ( !dirty ) dirty = 
true;
 
  577      zyppKeys = 
getZYpp()->keyRing()->trustedPublicKeyData();
 
  580  computeKeyRingSync( rpmKeys, zyppKeys );
 
  581  MIL << (mode_r & 
SYNC_TO_KEYRING   ? 
"" : 
"(skip) ") << 
"Rpm keys to export into zypp trusted keyring: " << rpmKeys.size() << endl;
 
  582  MIL << (mode_r & 
SYNC_FROM_KEYRING ? 
"" : 
"(skip) ") << 
"Zypp trusted keys to import into rpm database: " << zyppKeys.size() << endl;
 
  588    MIL << 
"Exporting rpm keyring into zypp trusted keyring" <<endl;
 
  595      std::ofstream tmpos( tmpfile.
path().
c_str() );
 
  596      for_( it, rpmKeys.begin(), rpmKeys.end() )
 
  600        getData( 
"gpg-pubkey", *it, result );
 
  601        tmpos << result->tag_description() << endl;
 
  606      getZYpp()->keyRing()->multiKeyImport( tmpfile.
path(), 
true );
 
  610      std::set<Edition> missingKeys;
 
  611      for ( 
const Edition & key : rpmKeys )
 
  613        if ( 
getZYpp()->keyRing()->isKeyTrusted( key.version() ) ) 
 
  615        ERR << 
"Could not import key:" << 
str::Format(
"gpg-pubkey-%s") % key << 
" into zypp keyring (V3 key?)" << endl;
 
  616        missingKeys.insert( key );
 
  618      if ( ! missingKeys.empty() )
 
  624      ERR << 
"Could not import keys into zypp keyring: " << endl;
 
  632    MIL << 
"Importing zypp trusted keyring" << std::endl;
 
  633    for_( it, zyppKeys.begin(), zyppKeys.end() )
 
  645  MIL << 
"Trusted keys synced." << endl;
 
 
  667    WAR << 
"Key " << pubkey_r << 
" can not be imported. (READONLY MODE)" << endl;
 
  672  Edition keyEd( pubkey_r.gpgPubkeyVersion(), pubkey_r.gpgPubkeyRelease() );
 
  674  bool hasOldkeys = 
false;
 
  676  for_( it, rpmKeys.begin(), rpmKeys.end() )
 
  683    if ( keyEd == *it && !pubkey_r.hasSubkeys() ) 
 
  685      MIL << 
"Key " << pubkey_r << 
" is already in the rpm trusted keyring. (skip import)" << endl;
 
  689    if ( keyEd.
version() != (*it).version() )
 
  692    if ( keyEd.
release() < (*it).release() )
 
  694      MIL << 
"Key " << pubkey_r << 
" is older than one in the rpm trusted keyring. (skip import)" << endl;
 
  702  MIL << 
"Key " << pubkey_r << 
" will be imported into the rpm trusted keyring." << (hasOldkeys?
"(update)":
"(new)") << endl;
 
  708    std::string keyName( 
"gpg-pubkey-" + keyEd.
version() );
 
  710    opts.push_back ( 
"-e" );
 
  711    opts.push_back ( 
"--allmatches" );
 
  712    opts.push_back ( 
"--" );
 
  713    opts.push_back ( keyName.c_str() );
 
  724      ERR << 
"Failed to remove key " << pubkey_r << 
" from RPM trusted keyring (ignored)" << endl;
 
  728      MIL << 
"Key " << pubkey_r << 
" has been removed from RPM trusted keyring" << endl;
 
  734  opts.push_back ( 
"--import" );
 
  735  opts.push_back ( 
"--" );
 
  736  std::string pubkeypath( pubkey_r.path().asString() );
 
  737  opts.push_back ( pubkeypath.c_str() );
 
  741  std::vector<std::string> excplines;
 
  747      excplines.push_back( std::move(line) );
 
  763    MIL << 
"Key " << pubkey_r << 
" imported in rpm trusted keyring." << endl;
 
 
  780  std::set<Edition>::const_iterator found_edition = rpm_keys.end();
 
  781  std::string pubkeyVersion( pubkey_r.gpgPubkeyVersion() );
 
  783  for_( it, rpm_keys.begin(), rpm_keys.end() )
 
  785    if ( (*it).version() == pubkeyVersion )
 
  793  if (found_edition == rpm_keys.end())
 
  795      WAR << 
"Key " << pubkey_r.id() << 
" is not in rpm db" << endl;
 
  799  std::string rpm_name(
"gpg-pubkey-" + found_edition->asString());
 
  802  opts.push_back ( 
"-e" );
 
  803  opts.push_back ( 
"--" );
 
  804  opts.push_back ( rpm_name.c_str() );
 
  808  std::vector<std::string> excplines;
 
  814      excplines.push_back( std::move(line) );
 
  830    MIL << 
"Key " << pubkey_r << 
" has been removed from RPM trusted keyring" << endl;
 
 
  842  std::list<PublicKey> ret;
 
  845  for ( it.findByName( 
"gpg-pubkey" ); *it; ++it )
 
  847    Edition edition = it->tag_edition();
 
  852      getData( 
"gpg-pubkey", edition, result );
 
  859        os << result->tag_description();
 
  868      catch ( std::exception & e )
 
  870        ERR << 
"Could not dump key " << edition.
asString() << 
" in tmp file " << file.
path() << endl;
 
 
  880    std::set<Edition> ret;
 
  883    for ( it.findByName( 
"gpg-pubkey" ); *it; ++it )
 
  885      Edition edition = it->tag_edition();
 
  887        ret.insert( edition );
 
 
  904  std::list<FileInfo> result;
 
  910    found = it.findPackage( name_r );
 
  914    found = it.findPackage( name_r, edition_r );
 
 
  931bool RpmDb::hasFile( 
const std::string & file_r, 
const std::string & name_r )
 const 
  937    res = it.findByFile( file_r );
 
  941      res = (it->tag_name() == name_r);
 
 
  960  if (it.findByFile( file_r ))
 
  962    return it->tag_name();
 
 
  978  return it.findByProvides( tag_r );
 
 
  992  return it.findByRequiredBy( tag_r );
 
 
 1006  return it.findByConflicts( tag_r );
 
 
 1020  return it.findPackage( name_r );
 
 
 1034  return it.findPackage( name_r, ed_r );
 
 
 1049  it.findPackage( name_r );
 
 
 1069  it.findPackage( name_r, ed_r  );
 
 
 1080  struct RpmlogCapture : 
public std::vector<std::string>
 
 1084      rpmlogSetCallback( rpmLogCB, 
this );
 
 1085      _oldMask = rpmlogSetMask( RPMLOG_UPTO( RPMLOG_PRI(RPMLOG_INFO) ) );
 
 1088    RpmlogCapture(
const RpmlogCapture &) = 
delete;
 
 1089    RpmlogCapture(RpmlogCapture &&) = 
delete;
 
 1090    RpmlogCapture &operator=(
const RpmlogCapture &) = 
delete;
 
 1091    RpmlogCapture &operator=(RpmlogCapture &&) = 
delete;
 
 1094      rpmlogSetCallback( 
nullptr, 
nullptr );
 
 1095      rpmlogSetMask( _oldMask );
 
 1098    static int rpmLogCB( rpmlogRec rec_r, rpmlogCallbackData data_r )
 
 1099    { 
return reinterpret_cast<RpmlogCapture*
>(data_r)->rpmLog( rec_r ); }
 
 1101    int rpmLog( rpmlogRec rec_r )
 
 1103      std::string l { ::rpmlogRecMessage( rec_r ) };  
 
 1105      push_back( std::move(l) );
 
 1113  std::ostream & 
operator<<( std::ostream & str, 
const RpmlogCapture & obj )
 
 1116    for ( 
const auto & l : obj ) {
 
 1117      if ( sep ) str << sep; 
else sep = 
'\n';
 
 1125                                               const Pathname & root_r,                 
 
 1126                                               bool  requireGPGSig_r,                   
 
 1129    PathInfo file( path_r );
 
 1130    if ( ! file.isFile() )
 
 1132      ERR << 
"Not a file: " << file << endl;
 
 1136    FD_t fd = ::Fopen( file.asString().c_str(), 
"r.ufdio" );
 
 1137    if ( fd == 0 || ::Ferror(fd) )
 
 1139      ERR << 
"Can't open file for reading: " << file << 
" (" << ::Fstrerror(fd) << 
")" << endl;
 
 1144    rpmts ts = ::rpmtsCreate();
 
 1145    ::rpmtsSetRootDir( ts, root_r.
c_str() );
 
 1146    ::rpmtsSetVSFlags( ts, RPMVSF_DEFAULT );
 
 1147#ifdef HAVE_RPM_VERIFY_TRANSACTION_STEP 
 1148    ::rpmtsSetVfyFlags( ts, RPMVSF_DEFAULT );
 
 1151    RpmlogCapture vresult;
 
 1152    LocaleGuard guard( LC_ALL, 
"C" );   
 
 1153    static rpmQVKArguments_s qva = ([](){ rpmQVKArguments_s qva; memset( &qva, 0, 
sizeof(rpmQVKArguments_s) ); 
return qva; })();
 
 1154    int res = ::rpmVerifySignatures( &qva, ts, fd, path_r.
basename().c_str() );
 
 1163    typedef std::map<std::string_view,RpmDb::CheckPackageResult> ResultMap;
 
 1164    static const ResultMap resultMap {
 
 1172    auto getresult = []( 
const ResultMap & resultMap, ResultMap::key_type key )->ResultMap::mapped_type {
 
 1173      auto it = resultMap.find( key );
 
 1178    unsigned count[7] = { 0, 0, 0, 0, 0, 0, 0 };
 
 1183      SawHeaderSig     = (1 << 0),  
 
 1184      SawHeaderDigest  = (1 << 1),  
 
 1185      SawPayloadDigest = (1 << 2),  
 
 1187      SawDigest        = (1 << 4),  
 
 1189    unsigned saw = SawNone;
 
 1191    static const str::regex rx( 
"^ *(Header|Payload)? .*(Signature, key|digest).*: ([A-Z]+)" );
 
 1193    for ( 
const std::string & line : vresult )
 
 1195      if ( line[0] != 
' ' ) 
 
 1201        lineres = getresult( resultMap, what[3] );
 
 1205        if ( what[1][0] == 
'H' ) {
 
 1206          saw |= ( what[2][0] == 
'S' ? SawHeaderSig :SawHeaderDigest );
 
 1208        else if ( what[1][0] == 
'P' ) {
 
 1209          if ( what[2][0] == 
'd' ) saw |= SawPayloadDigest;
 
 1212          saw |= ( what[2][0] == 
'S' ? SawSig : SawDigest );
 
 1217      detail_r.push_back( RpmDb::CheckPackageDetail::value_type( lineres, line ) );
 
 1239      bool isSigned = (saw & SawHeaderSig) && ( (saw & SawPayloadDigest) || (saw & SawSig) );
 
 1240      if ( not isSigned ) {
 
 1241        std::string message { 
"    " };
 
 1242        if ( not (saw & SawHeaderSig) )
 
 1243          message += 
_(
"Package header is not signed!");
 
 1245          message += 
_(
"Package payload is not signed!");
 
 1247        detail_r.push_back( RpmDb::CheckPackageDetail::value_type( 
RpmDb::CHK_NOSIG, std::move(message) ) );
 
 1248        if ( requireGPGSig_r )
 
 1257      bool didReadHeader = 
false;
 
 1258      std::unordered_map< std::string, std::string> fprs;
 
 1261      str::regex rxexpr( 
"key ID ([a-fA-F0-9]{8}):" );
 
 1262      for ( 
auto &detail : detail_r ) {
 
 1263        auto &line = detail.second;
 
 1267          if ( !didReadHeader ) {
 
 1268            didReadHeader = 
true;
 
 1273              auto keyMgr = zypp::KeyManagerCtx::createForOpenPGP();
 
 1274              const auto &addFprs = [&]( 
auto tag ){
 
 1275                const auto &list1 = keyMgr.readSignatureFingerprints( header->blob_val( tag ) );
 
 1276                for ( 
const auto &
id : list1 ) {
 
 1277                  if ( 
id.size() <= 8 )
 
 1281                  fprs.insert( std::make_pair( lowerId.substr( lowerId.size() - 8 ), lowerId ) );
 
 1285              addFprs( RPMTAG_SIGGPG );
 
 1286              addFprs( RPMTAG_SIGPGP );
 
 1287              addFprs( RPMTAG_RSAHEADER );
 
 1288              addFprs( RPMTAG_DSAHEADER );
 
 1291              ERR << 
"Failed to read package signatures." << std::endl;
 
 1302            if ( 
const auto &i = fprs.find( keyId ); i != fprs.end() ) {
 
 1309      WAR << path_r << 
" (" << requireGPGSig_r << 
" -> " << ret << 
")" << endl;
 
 1310      WAR << vresult << endl;
 
 1313      DBG << path_r << 
" [0-Signature is OK]" << endl;
 
 1324{ 
return doCheckPackageSig( path_r, 
root(), 
false, detail_r ); }
 
 
 1330{ 
return doCheckPackageSig( path_r, 
root(), 
true, detail_r ); }
 
 
 1345  opts.push_back (
"-V");
 
 1346  opts.push_back (
"--nodeps");
 
 1347  opts.push_back (
"--noscripts");
 
 1348  opts.push_back (
"--nomd5");
 
 1349  opts.push_back (
"--");
 
 1350  opts.push_back (packageName.c_str());
 
 1371    if (line.length() > 12 &&
 
 1372        (line[0] == 
'S' || line[0] == 
's' ||
 
 1373         (line[0] == 
'.' && line[7] == 
'T')))
 
 1376      std::string filename;
 
 1378      filename.assign(line, 11, line.length() - 11);
 
 
 1418#if defined(WORKAROUNDRPMPWDBUG) 
 1419  args.push_back(
"#/");         
 
 1421  args.push_back(
"rpm");
 
 1422  args.push_back(
"--root");
 
 1423  args.push_back(
_root.asString().c_str());
 
 1424  args.push_back(
"--dbpath");
 
 1425  args.push_back(
_dbPath.asString().c_str());
 
 1427    args.push_back(
"-vv");
 
 1428  const char* argv[args.size() + opts.size() + 1];
 
 1430  const char** p = argv;
 
 1431  p = 
copy (args.begin (), args.end (), p);
 
 1432  p = 
copy (opts.begin (), opts.end (), p);
 
 1438  librpmDb::dbRelease( 
true );
 
 
 1458    process->setBlocking( 
false );
 
 1459    FILE * inputfile = 
process->inputFile();
 
 1464      const auto &readResult = 
io::receiveUpto( inputfile, 
'\n', 5 * 1000, 
false );
 
 1465      switch ( readResult.first ) {
 
 1471          line += readResult.second;
 
 1476          line += readResult.second;
 
 1477          if ( line.size() && line.back() == 
'\n')
 
 1482          line += readResult.second;
 
 1484          if ( line.size() && line.back() == 
'\n')
 
 1488            L_DBG(
"RPM_DEBUG") << line << endl;
 
 
 1532void RpmDb::processConfigFiles(
const std::string& line, 
const std::string& name, 
const char* typemsg, 
const char* difffailmsg, 
const char* diffgenmsg)
 
 1534  std::string msg = line.substr(9);
 
 1535  std::string::size_type pos1 = std::string::npos;
 
 1536  std::string::size_type pos2 = std::string::npos;
 
 1537  std::string file1s, file2s;
 
 1541  pos1 = msg.find (typemsg);
 
 1544    if ( pos1 == std::string::npos )
 
 1547    pos2 = pos1 + strlen (typemsg);
 
 1549    if (pos2 >= msg.length() )
 
 1552    file1 = msg.substr (0, pos1);
 
 1553    file2 = msg.substr (pos2);
 
 1560      file1 = 
_root + file1;
 
 1561      file2 = 
_root + file2;
 
 1571        ERR << 
"Could not create " << file.
asString() << endl;
 
 1575      std::ofstream notify(file.
asString().c_str(), std::ios::out|std::ios::app);
 
 1578        ERR << 
"Could not open " <<  file << endl;
 
 1584      notify << 
str::form(
_(
"Changed configuration files for %s:"), name.c_str()) << endl;
 
 1587        ERR << 
"diff failed" << endl;
 
 1589                            file1s.c_str(), file2s.c_str()) << endl;
 
 1594                            file1s.c_str(), file2s.c_str()) << endl;
 
 1599          if (out.substr(0,4) == 
"--- ")
 
 1601            out.replace(4, file1.
asString().length(), file1s);
 
 1603          std::string::size_type pos = out.find(
"\n+++ ");
 
 1604          if (pos != std::string::npos)
 
 1606            out.replace(pos+5, file2.
asString().length(), file2s);
 
 1609        notify << out << endl;
 
 1612      notify.open(
"/var/lib/update-messages/yast2-packagemanager.rpmdb.configfiles");
 
 1617      WAR << 
"rpm created " << file2 << 
" but it is not different from " << file2 << endl;
 
 
 1637  report->start(filename);
 
 1652        report->finish( excpt_r );
 
 
 1668  MIL << 
"RpmDb::installPackage(" << filename << 
"," << flags << 
")" << endl;
 
 1676      ERR << 
"backup of " << filename.
asString() << 
" failed" << endl;
 
 1679    report->progress( 0 ); 
 
 1684#if defined(WORKAROUNDDUMPPOSTTRANS_BUG_1216091) 
 1685  if ( postTransCollector_r && 
_root == 
"/" ) {
 
 1687  if ( postTransCollector_r ) {
 
 1689    opts.push_back(
"--define");           
 
 1690    opts.push_back(
"_dump_posttrans 1");  
 
 1693    opts.push_back(
"-i");
 
 1695    opts.push_back(
"-U");
 
 1697  opts.push_back(
"--percent");
 
 1698  opts.push_back(
"--noglob");
 
 1702    opts.push_back(
"--ignorearch");
 
 1705    opts.push_back(
"--nodigest");
 
 1707    opts.push_back(
"--nosignature");
 
 1709    opts.push_back (
"--excludedocs");
 
 1711    opts.push_back (
"--noscripts");
 
 1713    opts.push_back (
"--force");
 
 1715    opts.push_back (
"--nodeps");
 
 1717    opts.push_back (
"--ignoresize");
 
 1719    opts.push_back (
"--justdb");
 
 1721    opts.push_back (
"--test");
 
 1723    opts.push_back (
"--noposttrans");
 
 1725  opts.push_back(
"--");
 
 1728  std::string quotedFilename( rpmQuoteFilename( workaroundRpmPwdBug( filename ) ) );
 
 1729  opts.push_back ( quotedFilename.c_str() );
 
 1734  unsigned    lineno = 0;
 
 1737  cmdout.
set( 
"line",   std::cref(line) );
 
 1738  cmdout.
set( 
"lineno", lineno );
 
 1742  std::vector<std::string> configwarnings;      
 
 1750      sscanf( line.c_str() + 2, 
"%d", &percent );
 
 1751      report->progress( percent );
 
 1759    cmdout.
set( 
"lineno", lineno );
 
 1760    report->report( cmdout );
 
 1763      if ( line.find( 
" scriptlet failed, " ) == std::string::npos )    
 
 1767    rpmmsg += line+
'\n';
 
 1770      configwarnings.push_back(line);
 
 1773    rpmmsg += 
"[truncated]\n";
 
 1776  if ( postTransCollector_r && rpm_status == 0 ) {
 
 1782  for (std::vector<std::string>::iterator it = configwarnings.begin();
 
 1783       it != configwarnings.end(); ++it)
 
 1787                       _(
"rpm saved %s as %s, but it was impossible to determine the difference"),
 
 1789                       _(
"rpm saved %s as %s.\nHere are the first 25 lines of difference:\n"));
 
 1792                       _(
"rpm created %s as %s, but it was impossible to determine the difference"),
 
 1794                       _(
"rpm created %s as %s.\nHere are the first 25 lines of difference:\n"));
 
 1797  if ( rpm_status != 0 )
 
 1802    std::ostringstream sstr;
 
 1803    sstr << 
"rpm output:" << endl << rpmmsg << endl;
 
 1804    historylog.
comment(sstr.str());
 
 1807    if ( not rpmmsg.empty() )
 
 1808      excpt.addHistory( rpmmsg );
 
 1811  else if ( ! rpmmsg.empty() )
 
 1816    std::ostringstream sstr;
 
 1817    sstr << 
"Additional rpm output:" << endl << rpmmsg << endl;
 
 1818    historylog.
comment(sstr.str());
 
 1822    report->finishInfo(
str::form( 
"%s:\n%s\n", 
_(
"Additional rpm output"),  rpmmsg.c_str() ));
 
 
 1839                 + 
"-" + package->edition().version()
 
 1840                 + 
"-" + package->edition().release()
 
 1841                 + 
"." + package->arch().asString(), flags, postTransCollector_r );
 
 
 1848  report->start( name_r );
 
 1863        report->finish( excpt_r );
 
 
 1879  MIL << 
"RpmDb::doRemovePackage(" << name_r << 
"," << flags << 
")" << endl;
 
 1888      ERR << 
"backup of " << name_r << 
" failed" << endl;
 
 1890    report->progress( 0 );
 
 1894    report->progress( 100 );
 
 1899#if defined(WORKAROUNDDUMPPOSTTRANS_BUG_1216091) 
 1900  if ( postTransCollector_r && 
_root == 
"/" ) {
 
 1902  if ( postTransCollector_r ) {
 
 1904    opts.push_back(
"--define");           
 
 1905    opts.push_back(
"_dump_posttrans 1");  
 
 1907  opts.push_back(
"-e");
 
 1908  opts.push_back(
"--allmatches");
 
 1911    opts.push_back(
"--noscripts");
 
 1913    opts.push_back(
"--nodeps");
 
 1915    opts.push_back(
"--justdb");
 
 1917    opts.push_back (
"--test");
 
 1920    WAR << 
"IGNORE OPTION: 'rpm -e' does not support '--force'" << endl;
 
 1923  opts.push_back(
"--");
 
 1924  opts.push_back(name_r.c_str());
 
 1929  unsigned    lineno = 0;
 
 1932  cmdout.
set( 
"line",   std::cref(line) );
 
 1933  cmdout.
set( 
"lineno", lineno );
 
 1944  report->progress( 5 );
 
 1952    cmdout.
set( 
"lineno", lineno );
 
 1953    report->report( cmdout );
 
 1956      if ( line.find( 
" scriptlet failed, " ) == std::string::npos )    
 
 1959    rpmmsg += line+
'\n';
 
 1962    rpmmsg += 
"[truncated]\n";
 
 1963  report->progress( 50 );
 
 1965  if ( postTransCollector_r && rpm_status == 0 ) {
 
 1971  if ( rpm_status != 0 )
 
 1974        str::form(
"%s remove failed", name_r.c_str()), 
true );
 
 1975    std::ostringstream sstr;
 
 1976    sstr << 
"rpm output:" << endl << rpmmsg << endl;
 
 1977    historylog.
comment(sstr.str());
 
 1980    if ( not rpmmsg.empty() )
 
 1981      excpt.addHistory( rpmmsg );
 
 1984  else if ( ! rpmmsg.empty() )
 
 1987        str::form(
"%s removed ok", name_r.c_str()), 
true );
 
 1989    std::ostringstream sstr;
 
 1990    sstr << 
"Additional rpm output:" << endl << rpmmsg << endl;
 
 1991    historylog.
comment(sstr.str());
 
 1995    report->finishInfo(
str::form( 
"%s:\n%s\n", 
_(
"Additional rpm output"),  rpmmsg.c_str() ));
 
 
 2008  MIL << 
"RpmDb::runposttrans(" << filename_r << 
")" << endl;
 
 2011  opts.push_back(
"-vv");  
 
 2012  opts.push_back(
"--runposttrans");
 
 2013  opts.push_back(filename_r.
c_str());
 
 2020  static const str::regex rx( 
"^D: (%.*): (scriptlet start|running .* scriptlet)" );
 
 2032        output_r( 
"RIPOFF:"+what[1] );
 
 2049  if ( rpm_status != 0 ) {
 
 2050    WAR << 
"rpm --runposttrans returned " << rpm_status << endl;
 
 
 2085    INT << 
"_backuppath empty" << endl;
 
 2093    ERR << 
"Error while getting changed files for package " <<
 
 2094    packageName << endl;
 
 2100    DBG <<  
"package " <<  packageName << 
" not changed -> no backup" << endl;
 
 2111    time_t currentTime = time(0);
 
 2112    struct tm *currentLocalTime = localtime(¤tTime);
 
 2114    int date = (currentLocalTime->tm_year + 1900) * 10000
 
 2115               + (currentLocalTime->tm_mon + 1) * 100
 
 2116               + currentLocalTime->tm_mday;
 
 2122                       + 
str::form(
"%s-%d-%d.tar.gz",packageName.c_str(), date, num);
 
 2125    while ( 
PathInfo(backupFilename).isExist() && num++ < 1000);
 
 2130      ERR << filestobackupfile.
asString() << 
" already exists and is no file" << endl;
 
 2134    std::ofstream fp ( filestobackupfile.
asString().c_str(), std::ios::out|std::ios::trunc );
 
 2138      ERR << 
"could not open " << filestobackupfile.
asString() << endl;
 
 2142    for (FileList::const_iterator cit = 
fileList.begin();
 
 2145      std::string name = *cit;
 
 2146      if ( name[0] == 
'/' )
 
 2149        name = name.substr( 1 );
 
 2151      DBG << 
"saving file "<< name << endl;
 
 2156    const char* 
const argv[] =
 
 2161        _root.asString().c_str(),
 
 2162        "--ignore-failed-read",
 
 2166        filestobackupfile.
asString().c_str(),
 
 2182    int ret = tar.
close();
 
 2186      ERR << 
"tar failed: " << tarmsg << endl;
 
 2191      MIL << 
"tar backup ok" << endl;
 
 
 2212#define OUTS(E,S) case RpmDb::E: return str << "["<< (unsigned)obj << "-"<< S << "]"; break 
 2224    OUTS( 
CHK_ERROR,               
_(
"File does not exist or signature can't be checked") );
 
 
 2234  for ( 
const auto & el : obj )
 
 2235    str << el.second << endl;
 
 
#define MAXRPMMESSAGELINES
#define FAILIFNOTINITIALIZED
#define FILEFORBACKUPFILES
Store and operate on date (time_t).
std::string form(const std::string &format_r) const
Return string representation according to format as localtime.
static Date now()
Return the current time.
Assign a vaiable a certain value when going out of scope.
Edition represents [epoch:]version[-release]
std::string version() const
Version.
std::string release() const
Release.
static const Edition noedition
Value representing noedition ("") This is in fact a valid Edition.
Base class for Exception.
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
void addHistory(const std::string &msg_r)
Add some message text to the history.
void moveToHistory(TContainer &&msgc_r)
addHistory from string container types (oldest first) moving
Execute a program and give access to its io An object of this class encapsulates the execution of an ...
int close() override
Wait for the progamm to complete.
Stderr_Disposition
Define symbols for different policies on the handling of stderr.
Writing the zypp history file.
void comment(const std::string &comment, bool timestamp=false)
Log a comment (even multiline).
std::string asString() const
TraitsType::constPtrType constPtr
std::string basename() const
Return the last component of this path.
Maintain [min,max] and counter (value) for progress counting.
value_type reportValue() const
void sendTo(const ReceiverFnc &fnc_r)
Set ReceiverFnc.
bool toMax()
Set counter value to current max value (unless no range).
bool incr(value_type val_r=1)
Increment counter value (default by 1).
bool toMin()
Set counter value to current min value.
void range(value_type max_r)
Set new [0,max].
static ZConfig & instance()
Singleton ctor.
ZYpp::Ptr getZYpp()
Convenience to get the Pointer to the ZYpp instance.
friend std::ostream & operator<<(std::ostream &str, const ReferenceCounted &obj)
Stream output via dumpOn.
Typesafe passing of user data via callbacks.
bool set(const std::string &key_r, AnyType val_r)
Set the value for key (nonconst version always returns true).
std::string receiveLine()
Read one line from the input stream.
Wrapper class for stat/lstat.
bool isExist() const
Return whether valid stat info exists.
const char * c_str() const
String representation.
const std::string & asString() const
String representation.
std::string basename() const
Return the last component of this path.
bool empty() const
Test for an empty path.
bool relative() const
Test for a relative path.
Provide a new empty temporary file and delete it when no longer needed.
Regular expression match result.
Extract and remember posttrans scripts for later execution.
void collectPosttransInfo(const Pathname &rpmPackage_r, const std::vector< std::string > &runposttrans_r)
Extract and remember a packages posttrans script or dump_posttrans lines for later execution.
bool hasPosttransScript(const Pathname &rpmPackage_r)
Test whether a package defines a posttrans script.
Interface to the rpm program.
void getData(const std::string &name_r, RpmHeader::constPtr &result_r) const
Get an installed packages data from rpmdb.
void doRebuildDatabase(callback::SendReport< RebuildDBReport > &report)
bool queryChangedFiles(FileList &fileList, const std::string &packageName)
determine which files of an installed package have been modified.
std::string error_message
Error message from running rpm as external program.
bool hasRequiredBy(const std::string &tag_r) const
Return true if at least one package requires a certain tag.
std::vector< const char * > RpmArgVec
std::string whoOwnsFile(const std::string &file_r) const
Return name of package owning file or empty string if no installed package owns file.
void exportTrustedKeysInZyppKeyRing()
insert all rpm trusted keys into zypp trusted keyring
void importPubkey(const PublicKey &pubkey_r)
Import ascii armored public key in file pubkey_r.
void installPackage(const Pathname &filename, RpmInstFlags flags=RPMINST_NONE)
install rpm package
Pathname _backuppath
/var/adm/backup
std::ostream & dumpOn(std::ostream &str) const override
Dump debug info.
void run_rpm(const RpmArgVec &options, ExternalProgram::Stderr_Disposition stderr_disp=ExternalProgram::Stderr_To_Stdout)
Run rpm with the specified arguments and handle stderr.
void initDatabase(Pathname root_r=Pathname(), bool doRebuild_r=false)
Prepare access to the rpm database below root_r.
int runposttrans(const Pathname &filename_r, const std::function< void(const std::string &)> &output_r)
Run collected posttrans and transfiletrigger(postun|in) if rpm --runposttrans is supported.
ExternalProgram * process
The connection to the rpm process.
SyncTrustedKeyBits
Sync mode for syncTrustedKeys.
@ SYNC_TO_KEYRING
export rpm trusted keys into zypp trusted keyring
@ SYNC_FROM_KEYRING
import zypp trusted keys into rpm database.
~RpmDb() override
Destructor.
std::list< PublicKey > pubkeys() const
Return the long ids of all installed public keys.
std::set< Edition > pubkeyEditions() const
Return the edition of all installed public keys.
int systemStatus()
Return the exit status of the general rpm process, closing the connection if not already done.
std::set< std::string > FileList
CheckPackageResult checkPackageSignature(const Pathname &path_r, CheckPackageDetail &detail_r)
Check signature of rpm file on disk (strict check returning CHK_NOSIG if file is unsigned).
bool backupPackage(const std::string &packageName)
create tar.gz of all changed files in a Package
bool hasProvides(const std::string &tag_r) const
Return true if at least one package provides a certain tag.
void systemKill()
Forcably kill the system process.
const Pathname & root() const
void removePubkey(const PublicKey &pubkey_r)
Remove a public key from the rpm database.
void removePackage(const std::string &name_r, RpmInstFlags flags=RPMINST_NONE)
remove rpm package
db_const_iterator dbConstIterator() const
std::list< FileInfo > fileList(const std::string &name_r, const Edition &edition_r) const
return complete file list for installed package name_r (in FileInfo.filename) if edition_r !...
const Pathname & dbPath() const
Pathname _dbPath
Directory that contains the rpmdb.
void closeDatabase()
Block further access to the rpm database and go back to uninitialized state.
void setBackupPath(const Pathname &path)
set path where package backups are stored
bool _packagebackups
create package backups?
CheckPackageResult checkPackage(const Pathname &path_r, CheckPackageDetail &detail_r)
Check signature of rpm file on disk (legacy version returning CHK_OK if file is unsigned,...
void importZyppKeyRingTrustedKeys()
iterates through zypp keyring and import all non-existent keys into rpm keyring
void doInstallPackage(const Pathname &filename, RpmInstFlags flags, RpmPostTransCollector *postTransCollector_r, callback::SendReport< RpmInstallReport > &report)
Pathname _root
Root directory for all operations.
bool hasConflicts(const std::string &tag_r) const
Return true if at least one package conflicts with a certain tag.
int exit_code
The exit code of the rpm process, or -1 if not yet known.
void syncTrustedKeys(SyncTrustedKeyBits mode_r=SYNC_BOTH)
Sync trusted keys stored in rpm database and zypp trusted keyring.
void processConfigFiles(const std::string &line, const std::string &name, const char *typemsg, const char *difffailmsg, const char *diffgenmsg)
handle rpm messages like "/etc/testrc saved as /etc/testrc.rpmorig"
CheckPackageResult
checkPackage result
bool hasPackage(const std::string &name_r) const
Return true if package is installed.
void doRemovePackage(const std::string &name_r, RpmInstFlags flags, RpmPostTransCollector *postTransCollector_r, callback::SendReport< RpmRemoveReport > &report)
bool systemReadLine(std::string &line)
Read a line from the general rpm query.
void rebuildDatabase()
Rebuild the rpm database (rpm –rebuilddb).
bool hasFile(const std::string &file_r, const std::string &name_r="") const
Return true if at least one package owns a certain file (name_r empty) Return true if package name_r ...
Just inherits Exception to separate media exceptions.
static bool globalInit()
Initialize lib librpm (read configfiles etc.).
static librpmDb::constPtr dbOpenCreate(const Pathname &root_r, const Pathname &dbPath_r=Pathname())
Assert the rpmdb below the system at root_r exists.
static Pathname suggestedDbPath(const Pathname &root_r)
String related utilities and Regular expression matching.
@ Edition
Editions with v-r setparator highlighted.
Namespace intended to collect all environment variables we use.
Types and functions for filesystem operations.
int symlink(const Pathname &oldpath, const Pathname &newpath)
Like 'symlink'.
int copy(const Pathname &file, const Pathname &dest)
Like 'cp file dest'.
Pathname expandlink(const Pathname &path_r)
Recursively follows the symlink pointed to by path_r and returns the Pathname to the real file or dir...
int unlink(const Pathname &path)
Like 'unlink'.
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
std::pair< ReceiveUpToResult, std::string > receiveUpto(FILE *file, char c, timeout_type timeout, bool failOnUnblockError)
std::string & replaceAll(std::string &str_r, const std::string &from_r, const std::string &to_r)
Replace all occurrences of from_r with to_r in str_r (inplace).
std::string numstring(char n, int w=0)
bool hasPrefix(const C_Str &str_r, const C_Str &prefix_r)
Return whether str_r has prefix prefix_r.
std::string toLower(const std::string &s)
Return lowercase version of s.
bool startsWith(const C_Str &str_r, const C_Str &prefix_r)
alias for hasPrefix
bool endsWith(const C_Str &str_r, const C_Str &prefix_r)
alias for hasSuffix
bool regex_match(const std::string &s, smatch &matches, const regex ®ex)
\relates regex \ingroup ZYPP_STR_REGEX    \relates regex \ingroup ZYPP_STR_REGEX
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.
unsigned diffFiles(const std::string &file1, const std::string &file2, std::string &out, int maxlines)
std::ostream & operator<<(std::ostream &str, const librpmDb::db_const_iterator &obj)
_dumpPath dumpPath(const Pathname &root_r, const Pathname &sub_r)
dumpPath iomaip to dump '(root_r)sub_r' output,
static shared_ptr< KeyRingSignalReceiver > sKeyRingReceiver
Easy-to use interface to the ZYPP dependency resolver.
Temporarily connect a ReceiveReport then restore the previous one.
KeyRingSignalReceiver & operator=(const KeyRingSignalReceiver &)=delete
void trustedKeyRemoved(const PublicKey &key) override
KeyRingSignalReceiver & operator=(KeyRingSignalReceiver &&)=delete
KeyRingSignalReceiver(const KeyRingSignalReceiver &)=delete
KeyRingSignalReceiver(RpmDb &rpmdb)
void trustedKeyAdded(const PublicKey &key) override
~KeyRingSignalReceiver() override
KeyRingSignalReceiver(KeyRingSignalReceiver &&)=delete
Detailed rpm signature check log messages A single multiline message if CHK_OK.
Wrapper providing a librpmDb::db_const_iterator for this RpmDb.
#define for_(IT, BEG, END)
Convenient for-loops using iterator.
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.