Imported Upstream version 15.0.0
[platform/upstream/libzypp.git] / zypp / target / rpm / RpmDb.cc
index a207cf5..67b47e1 100644 (file)
 using namespace std;
 using namespace zypp::filesystem;
 
+#define WARNINGMAILPATH                "/var/log/YaST2/"
+#define FILEFORBACKUPFILES     "YaSTBackupModifiedFiles"
+#define MAXRPMMESSAGELINES     10000
+
+#define WORKAROUNDRPMPWDBUG
+
 namespace zypp
 {
+  namespace zypp_readonly_hack
+  {
+    bool IGotIt(); // in readonly-mode
+  }
 namespace target
 {
 namespace rpm
@@ -75,6 +85,26 @@ inline string rpmQuoteFilename( const Pathname & path_r )
   }
   return path;
 }
+
+
+  /** Workaround bnc#827609 - rpm needs a readable pwd so we
+   * chdir to /. Turn realtive pathnames into absolute ones
+   * by prepending cwd so rpm still finds them
+   */
+  inline Pathname workaroundRpmPwdBug( Pathname path_r )
+  {
+#if defined(WORKAROUNDRPMPWDBUG)
+    if ( path_r.relative() )
+    {
+      // try to prepend cwd
+      AutoDispose<char*> cwd( ::get_current_dir_name(), ::free );
+      if ( cwd )
+       return Pathname( cwd ) / path_r;
+      WAR << "Can't get cwd!" << endl;
+    }
+#endif
+    return path_r;     // no problem with absolute pathnames
+  }
 }
 
 struct KeyRingSignalReceiver : callback::ReceiveReport<KeyRingSignals>
@@ -193,83 +223,7 @@ ostream & operator<<( ostream & str, const RpmDb::DbStateInfoBits & obj )
   return str;
 }
 
-///////////////////////////////////////////////////////////////////
-//     CLASS NAME : RpmDbPtr
-//     CLASS NAME : RpmDbconstPtr
-///////////////////////////////////////////////////////////////////
 
-#define WARNINGMAILPATH "/var/log/YaST2/"
-#define FILEFORBACKUPFILES "YaSTBackupModifiedFiles"
-
-///////////////////////////////////////////////////////////////////
-//
-//     CLASS NAME : RpmDb::Packages
-/**
- * Helper class for RpmDb::getPackages() to build the
- * list<Package::Ptr> returned. We have to assert, that there
- * is a unique entry for every string.
- *
- * In the first step we build the _list list which contains all
- * packages (even those which are contained in multiple versions).
- *
- * At the end buildIndex() is called to build the _index is created
- * and points to the last installed versions of all packages.
- * Operations changing the rpmdb
- * content (install/remove package) should set _valid to false. The
- * next call to RpmDb::getPackages() will then reread the the rpmdb.
- *
- * Note that outside RpmDb::getPackages() _list and _index are always
- * in sync. So you may use lookup(PkgName) to retrieve a specific
- * Package::Ptr.
- **/
-class RpmDb::Packages
-{
-public:
-  list<Package::Ptr>        _list;
-  map<string,Package::Ptr> _index;
-  bool                      _valid;
-  Packages() : _valid( false )
-  {}
-  void clear()
-  {
-    _list.clear();
-    _index.clear();
-    _valid = false;
-  }
-  Package::Ptr lookup( const string & name_r ) const
-  {
-    map<string,Package::Ptr>::const_iterator got = _index.find( name_r );
-    if ( got != _index.end() )
-      return got->second;
-    return Package::Ptr();
-  }
-  void buildIndex()
-  {
-    _index.clear();
-    for ( list<Package::Ptr>::iterator iter = _list.begin();
-          iter != _list.end(); ++iter )
-    {
-      string name = (*iter)->name();
-      Package::Ptr & nptr = _index[name]; // be shure to get a reference!
-
-      if ( nptr )
-      {
-        WAR << "Multiple entries for package '" << name << "' in rpmdb" << endl;
-        if ( nptr->installtime() > (*iter)->installtime() )
-          continue;
-        else
-          nptr = *iter;
-      }
-      else
-      {
-        nptr = *iter;
-      }
-    }
-    _valid = true;
-  }
-};
-
-///////////////////////////////////////////////////////////////////
 
 ///////////////////////////////////////////////////////////////////
 //
@@ -289,7 +243,6 @@ public:
 //
 RpmDb::RpmDb()
     : _dbStateInfo( DbSI_NO_INIT )
-    , _packages( * new Packages ) // delete in destructor
 #warning Check for obsolete memebers
     , _backuppath ("/var/adm/backup")
     , _packagebackups(false)
@@ -297,7 +250,7 @@ RpmDb::RpmDb()
 {
   process = 0;
   exit_code = -1;
-
+  librpmDb::globalInit();
   // Some rpm versions are patched not to abort installation if
   // symlink creation failed.
   setenv( "RPM_IgnoreFailedSymlinks", "1", 1 );
@@ -314,9 +267,7 @@ RpmDb::~RpmDb()
 {
   MIL << "~RpmDb()" << endl;
   closeDatabase();
-
   delete process;
-  delete &_packages;
   MIL  << "~RpmDb() end" << endl;
   sKeyRingReceiver.reset();
 }
@@ -380,6 +331,8 @@ void RpmDb::initDatabase( Pathname root_r, Pathname dbPath_r, bool doRebuild_r )
   ///////////////////////////////////////////////////////////////////
   // Check arguments
   ///////////////////////////////////////////////////////////////////
+  bool quickinit( root_r.empty() );
+
   if ( root_r.empty() )
     root_r = "/";
 
@@ -393,7 +346,8 @@ void RpmDb::initDatabase( Pathname root_r, Pathname dbPath_r, bool doRebuild_r )
   }
 
   MIL << "Calling initDatabase: " << stringPath( root_r, dbPath_r )
-      << ( doRebuild_r ? " (rebuilddb)" : "" ) << endl;
+      << ( doRebuild_r ? " (rebuilddb)" : "" )
+      << ( quickinit ? " (quickinit)" : "" ) << endl;
 
   ///////////////////////////////////////////////////////////////////
   // Check whether already initialized
@@ -414,6 +368,13 @@ void RpmDb::initDatabase( Pathname root_r, Pathname dbPath_r, bool doRebuild_r )
   // init database
   ///////////////////////////////////////////////////////////////////
   librpmDb::unblockAccess();
+
+  if ( quickinit )
+  {
+    MIL << "QUICK initDatabase (no systemRoot set)" << endl;
+    return;
+  }
+
   DbStateInfoBits info = DbSI_NO_INIT;
   try
   {
@@ -465,10 +426,8 @@ void RpmDb::initDatabase( Pathname root_r, Pathname dbPath_r, bool doRebuild_r )
     }
   }
 
-  MIL << "Syncronizing keys with zypp keyring" << endl;
-  // we do this one by one now.
-  importZyppKeyRingTrustedKeys();
-  exportTrustedKeysInZyppKeyRing();
+  MIL << "Synchronizing keys with zypp keyring" << endl;
+  syncTrustedKeys();
 
   // Close the database in case any write acces (create/convert)
   // happened during init. This should drop any lock acquired
@@ -757,9 +716,6 @@ void RpmDb::modifyDatabase()
     removeV3( _root + _dbPath, dbsi_has( _dbStateInfo, DbSI_MADE_V3TOV4 ) );
     dbsi_clr( _dbStateInfo, DbSI_HAVE_V3 );
   }
-
-  // invalidate Packages list
-  _packages._valid = false;
 }
 
 ///////////////////////////////////////////////////////////////////
@@ -780,7 +736,6 @@ void RpmDb::closeDatabase()
   ///////////////////////////////////////////////////////////////////
   // Block further database access
   ///////////////////////////////////////////////////////////////////
-  _packages.clear();
   librpmDb::blockAccess();
 
   ///////////////////////////////////////////////////////////////////
@@ -851,8 +806,6 @@ void RpmDb::doRebuildDatabase(callback::SendReport<RebuildDBReport> & report)
 
   // don't call modifyDatabase because it would remove the old
   // rpm3 database, if the current database is a temporary one.
-  // But do invalidate packages list.
-  _packages._valid = false;
   run_rpm (opts, ExternalProgram::Stderr_To_Stdout);
 
   // progress report: watch this file growing
@@ -899,97 +852,179 @@ void RpmDb::doRebuildDatabase(callback::SendReport<RebuildDBReport> & report)
   }
 }
 
-void RpmDb::importZyppKeyRingTrustedKeys()
+///////////////////////////////////////////////////////////////////
+namespace
 {
-  MIL << "Importing zypp trusted keyring" << std::endl;
-
-  std::list<PublicKey> zypp_keys;
-  zypp_keys = getZYpp()->keyRing()->trustedPublicKeys();
-  /* The pubkeys() call below is expensive.  It calls gpg2 for each
-     gpg-pubkey in the rpm db.  Useless if we don't have any keys in
-     zypp yet.  */
-  if (zypp_keys.empty())
-    return;
-
-  std::list<PublicKey> rpm_keys = pubkeys();
-  for_( it, zypp_keys.begin(), zypp_keys.end() )
+  /** \ref RpmDb::syncTrustedKeys helper
+   * Compute which keys need to be exprted to / imported from the zypp keyring.
+   * Return result via argument list.
+   */
+  void computeKeyRingSync( std::set<Edition> & rpmKeys_r, std::list<PublicKeyData> & zyppKeys_r )
+  {
+    ///////////////////////////////////////////////////////////////////
+    // Remember latest release and where it ocurred
+    struct Key
     {
-      // we find only the left part of the long gpg key, as rpm does not support long ids
-      std::list<PublicKey>::iterator ik = find( rpm_keys.begin(), rpm_keys.end(), (*it));
-      if ( ik != rpm_keys.end() )
-        {
-          MIL << "Key " << (*it).id() << " (" << (*it).name() << ") is already in rpm database." << std::endl;
-        }
-      else
-        {
-          // now import the key in rpm
-          try
-            {
-              importPubkey( *it );
-              MIL << "Trusted key " << (*it).id() << " (" << (*it).name() << ") imported in rpm database." << std::endl;
-            }
-          catch (RpmException &e)
-            {
-              ERR << "Could not import key " << (*it).id() << " (" << (*it).name() << " from " << (*it).path() << " in rpm database" << std::endl;
-            }
-        }
-    }
-}
+      Key()
+       : _inRpmKeys( nullptr )
+       , _inZyppKeys( nullptr )
+      {}
 
-void RpmDb::exportTrustedKeysInZyppKeyRing()
-{
-  MIL << "Exporting rpm keyring into zypp trusted keyring" <<endl;
+      void updateIf( const Edition & rpmKey_r )
+      {
+       std::string keyRelease( rpmKey_r.release() );
+       int comp = _release.compare( keyRelease );
+       if ( comp < 0 )
+       {
+         // update to newer release
+         _release.swap( keyRelease );
+         _inRpmKeys  = &rpmKey_r;
+         _inZyppKeys = nullptr;
+         if ( !keyRelease.empty() )
+           DBG << "Old key in R: gpg-pubkey-" << rpmKey_r.version() << "-" <<  keyRelease << endl;
+       }
+       else if ( comp == 0 )
+       {
+         // stay with this release
+         if ( ! _inRpmKeys )
+           _inRpmKeys = &rpmKey_r;
+       }
+       // else: this is an old release
+       else
+         DBG << "Old key in R: gpg-pubkey-" << rpmKey_r.version() << "-" <<  keyRelease << endl;
+      }
 
-  set<Edition>    rpm_keys( pubkeyEditions() );
-  list<PublicKey> zypp_keys( getZYpp()->keyRing()->trustedPublicKeys() );
+      void updateIf( const PublicKeyData & zyppKey_r )
+      {
+       std::string keyRelease( zyppKey_r.gpgPubkeyRelease() );
+       int comp = _release.compare( keyRelease );
+       if ( comp < 0 )
+       {
+         // update to newer release
+         _release.swap( keyRelease );
+         _inRpmKeys  = nullptr;
+         _inZyppKeys = &zyppKey_r;
+         if ( !keyRelease.empty() )
+           DBG << "Old key in Z: gpg-pubkey-" << zyppKey_r.gpgPubkeyVersion() << "-" << keyRelease << endl;
+       }
+       else if ( comp == 0 )
+       {
+         // stay with this release
+         if ( ! _inZyppKeys )
+           _inZyppKeys = &zyppKey_r;
+       }
+       // else: this is an old release
+       else
+         DBG << "Old key in Z: gpg-pubkey-" << zyppKey_r.gpgPubkeyVersion() << "-" << keyRelease << endl;
+      }
 
-  for_( it, rpm_keys.begin(), rpm_keys.end() )
-  {
-    // search the zypp key into the rpm keys
-    // long id is edition version + release
-    string id = str::toUpper( (*it).version() + (*it).release());
-    list<PublicKey>::iterator ik( find( zypp_keys.begin(), zypp_keys.end(), id) );
-    if ( ik != zypp_keys.end() )
+      std::string _release;
+      const Edition * _inRpmKeys;
+      const PublicKeyData * _inZyppKeys;
+    };
+    ///////////////////////////////////////////////////////////////////
+
+    // collect keys by ID(version) and latest creation(release)
+    std::map<std::string,Key> _keymap;
+
+    for_( it, rpmKeys_r.begin(), rpmKeys_r.end() )
     {
-      MIL << "Key " << (*it) << " is already in zypp database." << endl;
+      _keymap[(*it).version()].updateIf( *it );
     }
-    else
+
+    for_( it, zyppKeys_r.begin(), zyppKeys_r.end() )
     {
-      // we export the rpm key into a file
-      RpmHeader::constPtr result( new RpmHeader() );
-      getData( string("gpg-pubkey"), *it, result );
-      TmpFile file(getZYpp()->tmpPath());
-      ofstream os;
-      try
+      _keymap[(*it).gpgPubkeyVersion()].updateIf( *it );
+    }
+
+    // compute missing keys
+    std::set<Edition> rpmKeys;
+    std::list<PublicKeyData> zyppKeys;
+    for_( it, _keymap.begin(), _keymap.end() )
+    {
+      DBG << "gpg-pubkey-" << (*it).first << "-" << (*it).second._release << " "
+          << ( (*it).second._inRpmKeys  ? "R" : "_" )
+         << ( (*it).second._inZyppKeys ? "Z" : "_" ) << endl;
+      if ( ! (*it).second._inRpmKeys )
       {
-        os.open(file.path().asString().c_str());
-        // dump rpm key into the tmp file
-        os << result->tag_description();
-        //MIL << "-----------------------------------------------" << endl;
-        //MIL << result->tag_description() <<endl;
-        //MIL << "-----------------------------------------------" << endl;
-        os.close();
+       zyppKeys.push_back( *(*it).second._inZyppKeys );
       }
-      catch (exception &e)
+      if ( ! (*it).second._inZyppKeys )
       {
-        ERR << "Could not dump key " << (*it) << " in tmp file " << file.path() << endl;
-        // just ignore the key
+       rpmKeys.insert( *(*it).second._inRpmKeys );
       }
+    }
+    rpmKeys_r.swap( rpmKeys );
+    zyppKeys_r.swap( zyppKeys );
+  }
+} // namespace
+///////////////////////////////////////////////////////////////////
+
+void RpmDb::syncTrustedKeys( SyncTrustedKeyBits mode_r )
+{
+  MIL << "Going to sync trusted keys..." << endl;
+  std::set<Edition> rpmKeys( pubkeyEditions() );
+  std::list<PublicKeyData> zyppKeys( getZYpp()->keyRing()->trustedPublicKeyData() );
+  computeKeyRingSync( rpmKeys, zyppKeys );
+  MIL << (mode_r & SYNC_TO_KEYRING   ? "" : "(skip) ") << "Rpm keys to export into zypp trusted keyring: " << rpmKeys.size() << endl;
+  MIL << (mode_r & SYNC_FROM_KEYRING ? "" : "(skip) ") << "Zypp trusted keys to import into rpm database: " << zyppKeys.size() << endl;
 
-      // now import the key in zypp
+  ///////////////////////////////////////////////////////////////////
+  if ( (mode_r & SYNC_TO_KEYRING) &&  ! rpmKeys.empty() )
+  {
+    // export to zypp keyring
+    MIL << "Exporting rpm keyring into zypp trusted keyring" <<endl;
+    // Temporarily disconnect to prevent the attemt to re-import the exported keys.
+    callback::TempConnect<KeyRingSignals> tempDisconnect;
+    librpmDb::db_const_iterator keepDbOpen; // just to keep a ref.
+
+    TmpFile tmpfile( getZYpp()->tmpPath() );
+    {
+      ofstream tmpos( tmpfile.path().c_str() );
+      for_( it, rpmKeys.begin(), rpmKeys.end() )
+      {
+       // we export the rpm key into a file
+       RpmHeader::constPtr result;
+       getData( string("gpg-pubkey"), *it, result );
+       tmpos << result->tag_description() << endl;
+      }
+    }
+    try
+    {
+      getZYpp()->keyRing()->multiKeyImport( tmpfile.path(), true /*trusted*/);
+    }
+    catch (Exception &e)
+    {
+      ERR << "Could not import keys into in zypp keyring" << endl;
+    }
+  }
+
+  ///////////////////////////////////////////////////////////////////
+  if ( (mode_r & SYNC_FROM_KEYRING) && ! zyppKeys.empty() )
+  {
+    // import from zypp keyring
+    MIL << "Importing zypp trusted keyring" << std::endl;
+    for_( it, zyppKeys.begin(), zyppKeys.end() )
+    {
       try
       {
-        getZYpp()->keyRing()->importKey( PublicKey(file), true /*trusted*/);
-        MIL << "Trusted key " << (*it) << " imported in zypp keyring." << endl;
+       importPubkey( getZYpp()->keyRing()->exportTrustedPublicKey( *it ) );
       }
-      catch (Exception &e)
+      catch ( const RpmException & exp )
       {
-        ERR << "Could not import key " << (*it) << " in zypp keyring" << endl;
+       ZYPP_CAUGHT( exp );
       }
     }
   }
+  MIL << "Trusted keys synced." << endl;
 }
 
+void RpmDb::importZyppKeyRingTrustedKeys()
+{ syncTrustedKeys( SYNC_FROM_KEYRING ); }
+
+void RpmDb::exportTrustedKeysInZyppKeyRing()
+{ syncTrustedKeys( SYNC_TO_KEYRING ); }
+
 ///////////////////////////////////////////////////////////////////
 //
 //
@@ -1000,37 +1035,72 @@ void RpmDb::importPubkey( const PublicKey & pubkey_r )
 {
   FAILIFNOTINITIALIZED;
 
-  // check if the key is already in the rpm database and just
-  // return if it does.
-  set<Edition> rpm_keys = pubkeyEditions();
-  string keyshortid = pubkey_r.id().substr(8,8);
-  MIL << "Comparing '" << keyshortid << "' to: ";
-  for ( set<Edition>::const_iterator it = rpm_keys.begin(); it != rpm_keys.end(); ++it)
-  {
-    string id = str::toUpper( (*it).version() );
-    MIL <<  ", '" << id << "'";
-    if ( id == keyshortid )
-    {
-        // they match id
-        // now check if timestamp is different
-        Date date = Date(str::strtonum<Date::ValueType>("0x" + (*it).release()));
-        if (  date == pubkey_r.created() )
-        {
+  // bnc#828672: On the fly key import in READONLY
+  if ( zypp_readonly_hack::IGotIt() )
+  {
+    WAR << "Key " << pubkey_r << " can not be imported. (READONLY MODE)" << endl;
+    return;
+  }
 
-            MIL << endl << "Key " << pubkey_r << " is already in the rpm trusted keyring." << endl;
-            return;
-        }
-        else
-        {
-            MIL << endl << "Key " << pubkey_r << " has another version in keyring. ( " << date << " & " << pubkey_r.created() << ")" << endl;
+  // check if the key is already in the rpm database
+  Edition keyEd( pubkey_r.gpgPubkeyVersion(), pubkey_r.gpgPubkeyRelease() );
+  set<Edition> rpmKeys = pubkeyEditions();
+  bool hasOldkeys = false;
 
-        }
+  for_( it, rpmKeys.begin(), rpmKeys.end() )
+  {
+    if ( keyEd == *it ) // quick test (Edition is IdStringType!)
+    {
+      MIL << "Key " << pubkey_r << " is already in the rpm trusted keyring. (skip import)" << endl;
+      return;
+    }
+
+    if ( keyEd.version() != (*it).version() )
+      continue; // different key ID (version)
+
+    if ( keyEd.release() < (*it).release() )
+    {
+      MIL << "Key " << pubkey_r << " is older than one in the rpm trusted keyring. (skip import)" << endl;
+      return;
+    }
+    else
+    {
+      hasOldkeys = true;
+    }
+  }
+  MIL << "Key " << pubkey_r << " will be imported into the rpm trusted keyring." << (hasOldkeys?"(update)":"(new)") << endl;
+
+  if ( hasOldkeys )
+  {
+    // We must explicitly delete old key IDs first (all releases,
+    // that's why we don't call removePubkey here).
+    std::string keyName( "gpg-pubkey-" + keyEd.version() );
+    RpmArgVec opts;
+    opts.push_back ( "-e" );
+    opts.push_back ( "--allmatches" );
+    opts.push_back ( "--" );
+    opts.push_back ( keyName.c_str() );
+    // don't call modifyDatabase because it would remove the old
+    // rpm3 database, if the current database is a temporary one.
+    run_rpm( opts, ExternalProgram::Stderr_To_Stdout );
+
+    string line;
+    while ( systemReadLine( line ) )
+    {
+      ( str::startsWith( line, "error:" ) ? WAR : DBG ) << line << endl;
+    }
 
+    if ( systemStatus() != 0 )
+    {
+      ERR << "Failed to remove key " << pubkey_r << " from RPM trusted keyring (ignored)" << endl;
+    }
+    else
+    {
+      MIL << "Key " << pubkey_r << " has been removed from RPM trusted keyring" << endl;
     }
   }
-  // key does not exists, lets import it
-  MIL <<  endl;
 
+  // import the new key
   RpmArgVec opts;
   opts.push_back ( "--import" );
   opts.push_back ( "--" );
@@ -1038,26 +1108,15 @@ void RpmDb::importPubkey( const PublicKey & pubkey_r )
 
   // don't call modifyDatabase because it would remove the old
   // rpm3 database, if the current database is a temporary one.
-  // But do invalidate packages list.
-  _packages._valid = false;
   run_rpm( opts, ExternalProgram::Stderr_To_Stdout );
 
   string line;
   while ( systemReadLine( line ) )
   {
-    if ( line.substr( 0, 6 ) == "error:" )
-    {
-      WAR << line << endl;
-    }
-    else
-    {
-      DBG << line << endl;
-    }
+    ( str::startsWith( line, "error:" ) ? WAR : DBG ) << line << endl;
   }
 
-  int rpm_status = systemStatus();
-
-  if ( rpm_status != 0 )
+  if ( systemStatus() != 0 )
   {
     //TranslatorExplanation first %s is file name, second is error message
     ZYPP_THROW(RpmSubprocessException(boost::str(boost::format(
@@ -1083,16 +1142,12 @@ void RpmDb::removePubkey( const PublicKey & pubkey_r )
   // check if the key is in the rpm database and just
   // return if it does not.
   set<Edition> rpm_keys = pubkeyEditions();
-
-  // search the key
   set<Edition>::const_iterator found_edition = rpm_keys.end();
+  std::string pubkeyVersion( pubkey_r.gpgPubkeyVersion() );
 
-  for ( set<Edition>::const_iterator it = rpm_keys.begin(); it != rpm_keys.end(); ++it)
+  for_( it, rpm_keys.begin(), rpm_keys.end() )
   {
-    string id = str::toUpper( (*it).version() );
-    string keyshortid = pubkey_r.id().substr(8,8);
-    MIL << "Comparing '" << id << "' to '" << keyshortid << "'" << endl;
-    if ( id == keyshortid )
+    if ( (*it).version() == pubkeyVersion )
     {
        found_edition = it;
        break;
@@ -1115,8 +1170,6 @@ void RpmDb::removePubkey( const PublicKey & pubkey_r )
 
   // don't call modifyDatabase because it would remove the old
   // rpm3 database, if the current database is a temporary one.
-  // But do invalidate packages list.
-  _packages._valid = false;
   run_rpm( opts, ExternalProgram::Stderr_To_Stdout );
 
   string line;
@@ -1164,7 +1217,7 @@ list<PublicKey> RpmDb::pubkeys() const
     if (edition != Edition::noedition)
     {
       // we export the rpm key into a file
-      RpmHeader::constPtr result = new RpmHeader();
+      RpmHeader::constPtr result;
       getData( string("gpg-pubkey"), edition, result );
       TmpFile file(getZYpp()->tmpPath());
       ofstream os;
@@ -1205,239 +1258,6 @@ set<Edition> RpmDb::pubkeyEditions() const
     return ret;
   }
 
-///////////////////////////////////////////////////////////////////
-//
-//
-//     METHOD NAME : RpmDb::packagesValid
-//     METHOD TYPE : bool
-//
-bool RpmDb::packagesValid() const
-{
-  return( _packages._valid || ! initialized() );
-}
-
-///////////////////////////////////////////////////////////////////
-//
-//
-//     METHOD NAME : RpmDb::getPackages
-//     METHOD TYPE : const list<Package::Ptr> &
-//
-//     DESCRIPTION :
-//
-const list<Package::Ptr> & RpmDb::getPackages()
-{
-  callback::SendReport<ScanDBReport> report;
-
-  report->start ();
-
-  try
-  {
-    const list<Package::Ptr> & ret = doGetPackages(report);
-    report->finish(ScanDBReport::NO_ERROR, "");
-    return ret;
-  }
-  catch (RpmException & excpt_r)
-  {
-    report->finish(ScanDBReport::FAILED, excpt_r.asUserHistory ());
-    ZYPP_RETHROW(excpt_r);
-  }
-#warning fixme
-  static const list<Package::Ptr> empty_list;
-  return empty_list;
-}
-
-#warning FIX READING RPM DATBASE TO POOL
-#if 0 // obsolete helper
-inline static void insertCaps( Capabilities &capset, capability::CapabilityImplPtrSet ptrset, CapFactory &factory )
-{
-  for ( capability::CapabilityImplPtrSet::const_iterator it = ptrset.begin();
-        it != ptrset.end();
-        ++it )
-  {
-    capset.insert( factory.fromImpl(*it) );
-  }
-}
-#endif
-
-//
-// make Package::Ptr from RpmHeader
-// return NULL on error
-//
-Package::Ptr RpmDb::makePackageFromHeader( const RpmHeader::constPtr header,
-                                           set<string> * filerequires,
-                                           const Pathname & location,
-                                          Repository repo )
-{
-  if ( ! header )
-    return 0;
-
-  if ( header->isSrc() )
-  {
-    WAR << "Can't make Package from SourcePackage header" << endl;
-    return 0;
-  }
-
-  Package::Ptr pptr;
-#warning FIX READING RPM DATBASE TO POOL
-#if 0
-  string name = header->tag_name();
-
-  // create dataprovider
-  detail::ResImplTraits<RPMPackageImpl>::Ptr impl( new RPMPackageImpl( header ) );
-
-  impl->setRepository( repo );
-  if (!location.empty())
-    impl->setLocation( OnMediaLocation(location,1) );
-
-  Edition edition;
-  try
-  {
-    edition = Edition( header->tag_version(),
-                       header->tag_release(),
-                       header->tag_epoch());
-  }
-  catch (Exception & excpt_r)
-  {
-    ZYPP_CAUGHT( excpt_r );
-    WAR << "Package " << name << " has bad edition '"
-    << (header->tag_epoch()==0?"":(header->tag_epoch()+":"))
-    << header->tag_version()
-    << (header->tag_release().empty()?"":(string("-") + header->tag_release())) << "'";
-    return pptr;
-  }
-
-  Arch arch;
-  try
-  {
-    arch = Arch( header->tag_arch() );
-  }
-  catch (Exception & excpt_r)
-  {
-    ZYPP_CAUGHT( excpt_r );
-    WAR << "Package " << name << " has bad architecture '" << header->tag_arch() << "'";
-    return pptr;
-  }
-
-  // Collect basic Resolvable data
-  NVRAD dataCollect( header->tag_name(),
-                     edition,
-                     arch );
-
-  list<string> filenames = impl->filenames();
-  CapFactory capfactory;
-  insertCaps( dataCollect[Dep::PROVIDES], header->tag_provides( filerequires ), capfactory );
-
-  for (list<string>::const_iterator filename = filenames.begin();
-       filename != filenames.end();
-       ++filename)
-  {
-    if ( capability::isInterestingFileSpec( *filename ) )
-    {
-      try
-      {
-        dataCollect[Dep::PROVIDES].insert(capfactory.fromImpl(capability::buildFile(ResKind::package, *filename) ));
-      }
-      catch (Exception & excpt_r)
-      {
-        ZYPP_CAUGHT( excpt_r );
-        WAR << "Ignoring invalid capability: " << *filename << endl;
-      }
-    }
-  }
-
-  insertCaps( dataCollect[Dep::REQUIRES], header->tag_requires( filerequires ), capfactory );
-  insertCaps( dataCollect[Dep::PREREQUIRES], header->tag_prerequires( filerequires ), capfactory );
-  insertCaps( dataCollect[Dep::CONFLICTS], header->tag_conflicts( filerequires ), capfactory );
-  insertCaps( dataCollect[Dep::OBSOLETES], header->tag_obsoletes( filerequires ), capfactory );
-  insertCaps( dataCollect[Dep::ENHANCES], header->tag_enhances( filerequires ), capfactory );
-  insertCaps( dataCollect[Dep::SUPPLEMENTS], header->tag_supplements( filerequires ), capfactory );
-
-  try
-  {
-    // create package from dataprovider
-    pptr = detail::makeResolvableFromImpl( dataCollect, impl );
-  }
-  catch (Exception & excpt_r)
-  {
-    ZYPP_CAUGHT( excpt_r );
-    ERR << "Can't create Package::Ptr" << endl;
-  }
-#endif
-  return pptr;
-}
-
-const list<Package::Ptr> & RpmDb::doGetPackages(callback::SendReport<ScanDBReport> & report)
-{
-  if ( packagesValid() )
-  {
-    return _packages._list;
-  }
-
-  _packages.clear();
-
-  ///////////////////////////////////////////////////////////////////
-  // Collect package data.
-  ///////////////////////////////////////////////////////////////////
-  unsigned expect = 0;
-  librpmDb::constPtr dbptr;
-  librpmDb::dbAccess( dbptr );
-  expect = dbptr->size();
-  DBG << "Expecting " << expect << " packages" << endl;
-
-  librpmDb::db_const_iterator iter;
-  unsigned current = 0;
-  Pathname location;
-
-  for ( iter.findAll(); *iter; ++iter, ++current, report->progress( (100*current)/expect))
-  {
-
-    string name = iter->tag_name();
-    if ( name == string( "gpg-pubkey" ) )
-    {
-      DBG << "Ignoring pseudo package " << name << endl;
-      // pseudo package filtered, as we can't handle multiple instances
-      // of 'gpg-pubkey-VERS-REL'.
-      continue;
-    }
-
-    Package::Ptr pptr = makePackageFromHeader( *iter, &_filerequires, location, Repository() );
-    if ( ! pptr )
-    {
-      WAR << "Failed to make package from database header '" << name << "'" << endl;
-      continue;
-    }
-
-    _packages._list.push_back( pptr );
-  }
-  _packages.buildIndex();
-  DBG << "Found installed packages: " << _packages._list.size() << endl;
-
-#warning FILEREQUIRES HACK SHOULD BE DONE WHEN WRITING THE RPMDB SOLV FILE
-#if 0
-  ///////////////////////////////////////////////////////////////////
-  // Evaluate filerequires collected so far
-  ///////////////////////////////////////////////////////////////////
-  for ( set<string>::iterator it = _filerequires.begin(); it != _filerequires.end(); ++it )
-    {
-
-      for ( iter.findByFile( *it ); *iter; ++iter )
-      {
-        Package::Ptr pptr = _packages.lookup( iter->tag_name() );
-        if ( !pptr )
-        {
-          WAR << "rpmdb.findByFile returned unknown package " << *iter << endl;
-          continue;
-        }
-        pptr->injectProvides(_f.parse(ResKind::package, *it));
-      }
-    }
-#endif
-
-  ///////////////////////////////////////////////////////////////////
-  // Build final packages list
-  ///////////////////////////////////////////////////////////////////
-  return _packages._list;
-}
 
 ///////////////////////////////////////////////////////////////////
 //
@@ -1646,7 +1466,7 @@ RpmDb::checkPackageResult RpmDb::checkPackage( const Pathname & path_r )
   ::rpmtsSetRootDir( ts, root().asString().c_str() );
   ::rpmtsSetVSFlags( ts, RPMVSF_DEFAULT );
   int res = ::rpmReadPackageFile( ts, fd, path_r.asString().c_str(), NULL );
-  ts = ::rpmtsFree(ts);
+  ts = rpmtsFree(ts);
 
   ::Fclose( fd );
 
@@ -1762,6 +1582,9 @@ RpmDb::run_rpm (const RpmArgVec& opts,
   RpmArgVec args;
 
   // always set root and dbpath
+#if defined(WORKAROUNDRPMPWDBUG)
+  args.push_back("#/");                // chdir to / to workaround bnc#819354
+#endif
   args.push_back("rpm");
   args.push_back("--root");
   args.push_back(_root.asString().c_str());
@@ -1787,23 +1610,73 @@ RpmDb::run_rpm (const RpmArgVec& opts,
 /*--------------------------------------------------------------*/
 /* Read a line from the rpm process                            */
 /*--------------------------------------------------------------*/
-bool
-RpmDb::systemReadLine(string &line)
+bool RpmDb::systemReadLine( string & line )
 {
   line.erase();
 
   if ( process == NULL )
     return false;
 
-  line = process->receiveLine();
+  if ( process->inputFile() )
+  {
+    process->setBlocking( false );
+    FILE * inputfile = process->inputFile();
+    int    inputfileFd = ::fileno( inputfile );
+    do
+    {
+      /* Watch inputFile to see when it has input. */
+      fd_set rfds;
+      FD_ZERO( &rfds );
+      FD_SET( inputfileFd, &rfds );
 
-  if (line.length() == 0)
-    return false;
+      /* Wait up to 5 seconds. */
+      struct timeval tv;
+      tv.tv_sec = 5;
+      tv.tv_usec = 0;
+
+      int retval = select( inputfileFd+1, &rfds, NULL, NULL, &tv );
 
-  if (line[line.length() - 1] == '\n')
-    line.erase(line.length() - 1);
+      if ( retval == -1 )
+      {
+       ERR << "select error: " << strerror(errno) << endl;
+       if ( errno != EINTR )
+         return false;
+      }
+      else if ( retval )
+      {
+       // Data is available now.
+       static size_t linebuffer_size = 0;      // static because getline allocs
+       static char * linebuffer = 0;           // and reallocs if buffer is too small
+       ssize_t nread = getline( &linebuffer, &linebuffer_size, inputfile );
+       if ( nread == -1 )
+       {
+         if ( ::feof( inputfile ) )
+           return line.size(); // in case of pending output
+       }
+       else
+       {
+         if ( nread > 0 )
+         {
+           if ( linebuffer[nread-1] == '\n' )
+             --nread;
+           line += string( linebuffer, nread );
+         }
+
+         if ( ! ::ferror( inputfile ) || ::feof( inputfile ) )
+           return true; // complete line
+       }
+       clearerr( inputfile );
+      }
+      else
+      {
+       // No data within time.
+       if ( ! process->running() )
+         return false;
+      }
+    } while ( true );
+  }
 
-  return true;
+  return false;
 }
 
 /*--------------------------------------------------------------*/
@@ -1987,10 +1860,6 @@ void RpmDb::doInstallPackage( const Pathname & filename, RpmInstFlags flags, cal
     // FIXME status handling
     report->progress( 0 ); // allow 1% for backup creation.
   }
-  else
-  {
-    report->progress( 100 );
-  }
 
   // run rpm
   RpmArgVec opts;
@@ -2000,6 +1869,7 @@ void RpmDb::doInstallPackage( const Pathname & filename, RpmInstFlags flags, cal
     opts.push_back("-U");
 
   opts.push_back("--percent");
+  opts.push_back("--noglob");
 
   // ZConfig defines cross-arch installation
   if ( ! ZConfig::instance().systemArchitecture().compatibleWith( ZConfig::instance().defaultSystemArchitecture() ) )
@@ -2023,11 +1893,13 @@ void RpmDb::doInstallPackage( const Pathname & filename, RpmInstFlags flags, cal
     opts.push_back ("--justdb");
   if (flags & RPMINST_TEST)
     opts.push_back ("--test");
+  if (flags & RPMINST_NOPOSTTRANS)
+    opts.push_back ("--noposttrans");
 
   opts.push_back("--");
 
   // rpm requires additional quoting of special chars:
-  string quotedFilename( rpmQuoteFilename( filename ) );
+  string quotedFilename( rpmQuoteFilename( workaroundRpmPwdBug( filename ) ) );
   opts.push_back ( quotedFilename.c_str() );
 
   modifyDatabase(); // BEFORE run_rpm
@@ -2036,10 +1908,15 @@ void RpmDb::doInstallPackage( const Pathname & filename, RpmInstFlags flags, cal
   string line;
   string rpmmsg;
   vector<string> configwarnings;
-  vector<string> errorlines;
 
+  unsigned linecnt = 0;
   while (systemReadLine(line))
   {
+    if ( linecnt < MAXRPMMESSAGELINES )
+      ++linecnt;
+    else
+      continue;
+
     if (line.substr(0,2)=="%%")
     {
       int percent;
@@ -2054,6 +1931,9 @@ void RpmDb::doInstallPackage( const Pathname & filename, RpmInstFlags flags, cal
       configwarnings.push_back(line);
     }
   }
+  if ( linecnt > MAXRPMMESSAGELINES )
+    rpmmsg += "[truncated]\n";
+
   int rpm_status = systemStatus();
 
   // evaluate result
@@ -2206,10 +2086,17 @@ void RpmDb::doRemovePackage( const string & name_r, RpmInstFlags flags, callback
   // 50 - command completed
   // 100 if no error
   report->progress( 5 );
+  unsigned linecnt = 0;
   while (systemReadLine(line))
   {
+    if ( linecnt < MAXRPMMESSAGELINES )
+      ++linecnt;
+    else
+      continue;
     rpmmsg += line+'\n';
   }
+  if ( linecnt > MAXRPMMESSAGELINES )
+    rpmmsg += "[truncated]\n";
   report->progress( 50 );
   int rpm_status = systemStatus();