libzypp  17.29.1
RpmDb.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
12 #include "librpm.h"
13 extern "C"
14 {
15 #include <rpm/rpmcli.h>
16 #include <rpm/rpmlog.h>
17 }
18 #include <cstdlib>
19 #include <cstdio>
20 #include <ctime>
21 
22 #include <iostream>
23 #include <fstream>
24 #include <sstream>
25 #include <list>
26 #include <map>
27 #include <set>
28 #include <string>
29 #include <vector>
30 #include <algorithm>
31 
32 #include <zypp-core/base/StringV.h>
33 #include <zypp/base/Logger.h>
34 #include <zypp/base/String.h>
35 #include <zypp/base/Gettext.h>
36 #include <zypp/base/LocaleGuard.h>
37 #include <zypp-core/base/DtorReset>
38 
39 #include <zypp/Date.h>
40 #include <zypp/Pathname.h>
41 #include <zypp/PathInfo.h>
42 #include <zypp/PublicKey.h>
43 #include <zypp-core/ui/ProgressData>
44 
45 #include <zypp/target/rpm/RpmDb.h>
47 
48 #include <zypp/HistoryLog.h>
51 #include <zypp/TmpPath.h>
52 #include <zypp/KeyRing.h>
53 #include <zypp/KeyManager.h>
54 #include <zypp/ZYppFactory.h>
55 #include <zypp/ZConfig.h>
56 #include <zypp/base/IOTools.h>
57 
58 using std::endl;
59 using namespace zypp::filesystem;
60 
61 #define WARNINGMAILPATH "/var/log/YaST2/"
62 #define FILEFORBACKUPFILES "YaSTBackupModifiedFiles"
63 #define MAXRPMMESSAGELINES 10000
64 
65 #define WORKAROUNDRPMPWDBUG
66 
67 #undef ZYPP_BASE_LOGGER_LOGGROUP
68 #define ZYPP_BASE_LOGGER_LOGGROUP "librpmDb"
69 
70 namespace zypp
71 {
72  namespace zypp_readonly_hack
73  {
74  bool IGotIt(); // in readonly-mode
75  }
76  namespace env
77  {
78  inline bool ZYPP_RPM_DEBUG()
79  {
80  static bool val = [](){
81  const char * env = getenv("ZYPP_RPM_DEBUG");
82  return( env && str::strToBool( env, true ) );
83  }();
84  return val;
85  }
86  } // namespace env
87 namespace target
88 {
89 namespace rpm
90 {
91  const callback::UserData::ContentType InstallResolvableReport::contentRpmout( "rpmout","installpkg" );
92  const callback::UserData::ContentType RemoveResolvableReport::contentRpmout( "rpmout","removepkg" );
93 
94 namespace
95 {
96 #if 1 // No more need to escape whitespace since rpm-4.4.2.3
97 const char* quoteInFilename_m = "\'\"";
98 #else
99 const char* quoteInFilename_m = " \t\'\"";
100 #endif
101 inline std::string rpmQuoteFilename( const Pathname & path_r )
102 {
103  std::string path( path_r.asString() );
104  for ( std::string::size_type pos = path.find_first_of( quoteInFilename_m );
105  pos != std::string::npos;
106  pos = path.find_first_of( quoteInFilename_m, pos ) )
107  {
108  path.insert( pos, "\\" );
109  pos += 2; // skip '\\' and the quoted char.
110  }
111  return path;
112 }
113 
114 
119  inline Pathname workaroundRpmPwdBug( Pathname path_r )
120  {
121 #if defined(WORKAROUNDRPMPWDBUG)
122  if ( path_r.relative() )
123  {
124  // try to prepend cwd
125  AutoDispose<char*> cwd( ::get_current_dir_name(), ::free );
126  if ( cwd )
127  return Pathname( cwd ) / path_r;
128  WAR << "Can't get cwd!" << endl;
129  }
130 #endif
131  return path_r; // no problem with absolute pathnames
132  }
133 }
134 
136 {
137  KeyRingSignalReceiver(RpmDb &rpmdb) : _rpmdb(rpmdb)
138  {
139  connect();
140  }
141 
143  {
144  disconnect();
145  }
146 
147  virtual void trustedKeyAdded( const PublicKey &key )
148  {
149  MIL << "trusted key added to zypp Keyring. Importing..." << endl;
150  _rpmdb.importPubkey( key );
151  }
152 
153  virtual void trustedKeyRemoved( const PublicKey &key )
154  {
155  MIL << "Trusted key removed from zypp Keyring. Removing..." << endl;
156  _rpmdb.removePubkey( key );
157  }
158 
160 };
161 
162 static shared_ptr<KeyRingSignalReceiver> sKeyRingReceiver;
163 
164 unsigned diffFiles(const std::string file1, const std::string file2, std::string& out, int maxlines)
165 {
166  const char* argv[] =
167  {
168  "diff",
169  "-u",
170  file1.c_str(),
171  file2.c_str(),
172  NULL
173  };
174  ExternalProgram prog(argv,ExternalProgram::Discard_Stderr, false, -1, true);
175 
176  //if(!prog)
177  //return 2;
178 
179  std::string line;
180  int count = 0;
181  for (line = prog.receiveLine(), count=0;
182  !line.empty();
183  line = prog.receiveLine(), count++ )
184  {
185  if (maxlines<0?true:count<maxlines)
186  out+=line;
187  }
188 
189  return prog.close();
190 }
191 
192 
193 
194 /******************************************************************
195  **
196  **
197  ** FUNCTION NAME : stringPath
198  ** FUNCTION TYPE : inline std::string
199 */
200 inline std::string stringPath( const Pathname & root_r, const Pathname & sub_r )
201 {
202  return librpmDb::stringPath( root_r, sub_r );
203 }
204 
206 //
207 // CLASS NAME : RpmDb
208 //
210 
211 #define FAILIFNOTINITIALIZED if( ! initialized() ) { ZYPP_THROW(RpmDbNotOpenException()); }
212 
214 
216 //
217 //
218 // METHOD NAME : RpmDb::RpmDb
219 // METHOD TYPE : Constructor
220 //
221 RpmDb::RpmDb()
222  : _backuppath ("/var/adm/backup")
223  , _packagebackups(false)
224 {
225  process = 0;
226  exit_code = -1;
228  // Some rpm versions are patched not to abort installation if
229  // symlink creation failed.
230  setenv( "RPM_IgnoreFailedSymlinks", "1", 1 );
231  sKeyRingReceiver.reset(new KeyRingSignalReceiver(*this));
232 }
233 
235 //
236 //
237 // METHOD NAME : RpmDb::~RpmDb
238 // METHOD TYPE : Destructor
239 //
241 {
242  MIL << "~RpmDb()" << endl;
243  closeDatabase();
244  delete process;
245  MIL << "~RpmDb() end" << endl;
246  sKeyRingReceiver.reset();
247 }
248 
250 //
251 //
252 // METHOD NAME : RpmDb::dumpOn
253 // METHOD TYPE : std::ostream &
254 //
255 std::ostream & RpmDb::dumpOn( std::ostream & str ) const
256 {
257  return str << "RpmDb[" << stringPath( _root, _dbPath ) << "]";
258 }
259 
261 //
262 //
263 // METHOD NAME : RpmDb::initDatabase
264 // METHOD TYPE : PMError
265 //
266 void RpmDb::initDatabase( Pathname root_r, bool doRebuild_r )
267 {
269  // Check arguments
271  bool quickinit( root_r.empty() );
272 
273  if ( root_r.empty() )
274  root_r = "/";
275 
276  const Pathname & dbPath_r { librpmDb::suggestedDbPath( root_r ) }; // also asserts root_r is absolute
277 
278  // The rpmdb compat symlink.
279  // Required at least until rpmdb2solv takes a dppath argument.
280  // Otherwise it creates a db at "/var/lib/rpm".
281  if ( dbPath_r != "/var/lib/rpm" && ! PathInfo( root_r/"/var/lib/rpm" ).isExist() )
282  {
283  WAR << "Inject missing /var/lib/rpm compat symlink to " << dbPath_r << endl;
284  filesystem::assert_dir( root_r/"/var/lib" );
285  filesystem::symlink( "../../"/dbPath_r, root_r/"/var/lib/rpm" );
286  }
287 
289  // Check whether already initialized
291  if ( initialized() )
292  {
293  // Just check for a changing root because the librpmDb::suggestedDbPath
294  // may indeed change: rpm %post moving the db from /var/lib/rpm
295  // to /usr/lib/sysimage/rpm. We continue to use the old dbpath
296  // (via the compat symlink) until a re-init.
297  if ( root_r == _root ) {
298  MIL << "Calling initDatabase: already initialized at " << stringPath( _root, _dbPath ) << endl;
299  return;
300  }
301  else
302  ZYPP_THROW(RpmDbAlreadyOpenException(_root, _dbPath, root_r, dbPath_r));
303  }
304 
305  MIL << "Calling initDatabase: " << stringPath( root_r, dbPath_r )
306  << ( doRebuild_r ? " (rebuilddb)" : "" )
307  << ( quickinit ? " (quickinit)" : "" ) << endl;
308 
310  // init database
313 
314  if ( quickinit )
315  {
316  MIL << "QUICK initDatabase (no systemRoot set)" << endl;
317  return;
318  }
319 
320  try
321  {
322  // creates dbdir and empty rpm database if not present
323  librpmDb::dbAccess( root_r );
324  }
325  catch (const RpmException & excpt_r)
326  {
327  ZYPP_CAUGHT(excpt_r);
329  ZYPP_RETHROW(excpt_r);
330  }
331 
332  _root = root_r;
333  _dbPath = dbPath_r;
334 
335  if ( doRebuild_r )
336  rebuildDatabase();
337 
338  MIL << "Synchronizing keys with zypp keyring" << endl;
339  syncTrustedKeys();
340 
341  // Close the database in case any write acces (create/convert)
342  // happened during init. This should drop any lock acquired
343  // by librpm. On demand it will be reopened readonly and should
344  // not hold any lock.
345  librpmDb::dbRelease( true );
346 
347  MIL << "InitDatabase: " << *this << endl;
348 }
349 
351 //
352 //
353 // METHOD NAME : RpmDb::closeDatabase
354 // METHOD TYPE : PMError
355 //
357 {
358  if ( ! initialized() )
359  {
360  return;
361  }
362 
363  MIL << "Calling closeDatabase: " << *this << endl;
364 
366  // Block further database access
369 
371  // Uninit
373  _root = _dbPath = Pathname();
374 
375  MIL << "closeDatabase: " << *this << endl;
376 }
377 
379 //
380 //
381 // METHOD NAME : RpmDb::rebuildDatabase
382 // METHOD TYPE : PMError
383 //
385 {
387 
388  report->start( root() + dbPath() );
389 
390  try
391  {
392  doRebuildDatabase(report);
393  }
394  catch (RpmException & excpt_r)
395  {
396  report->finish(root() + dbPath(), RebuildDBReport::FAILED, excpt_r.asUserHistory());
397  ZYPP_RETHROW(excpt_r);
398  }
399  report->finish(root() + dbPath(), RebuildDBReport::NO_ERROR, "");
400 }
401 
403 {
405  MIL << "RpmDb::rebuildDatabase" << *this << endl;
406 
407  const Pathname mydbpath { root()/dbPath() }; // the configured path used in reports
408  {
409  // For --rebuilddb take care we're using the real db directory
410  // and not a symlink. Otherwise rpm will rename the symlink and
411  // replace it with a real directory containing the converted db.
412  DtorReset guardRoot { _root };
413  DtorReset guardDbPath{ _dbPath };
414  _root = "/";
415  _dbPath = filesystem::expandlink( mydbpath );
416 
417  // run rpm
418  RpmArgVec opts;
419  opts.push_back("--rebuilddb");
420  opts.push_back("-vv");
422  }
423 
424  // generate and report progress
425  ProgressData tics;
426  {
427  ProgressData::value_type hdrTotal = 0;
428  for ( librpmDb::db_const_iterator it; *it; ++it, ++hdrTotal )
429  {;}
430  tics.range( hdrTotal );
431  }
432  tics.sendTo( [&report,&mydbpath]( const ProgressData & tics_r ) -> bool {
433  return report->progress( tics_r.reportValue(), mydbpath );
434  } );
435  tics.toMin();
436 
437  std::string line;
438  std::string errmsg;
439  while ( systemReadLine( line ) )
440  {
441  static const std::string debugPrefix { "D:" };
442  static const std::string progressPrefix { "D: read h#" };
443  static const std::string ignoreSuffix { "digest: OK" };
444 
445  if ( ! str::startsWith( line, debugPrefix ) )
446  {
447  if ( ! str::endsWith( line, ignoreSuffix ) )
448  {
449  errmsg += line;
450  errmsg += '\n';
451  WAR << line << endl;
452  }
453  }
454  else if ( str::startsWith( line, progressPrefix ) )
455  {
456  if ( ! tics.incr() )
457  {
458  WAR << "User requested abort." << endl;
459  systemKill();
460  }
461  }
462  }
463 
464  if ( systemStatus() != 0 )
465  {
466  //TranslatorExplanation after semicolon is error message
467  ZYPP_THROW(RpmSubprocessException(std::string(_("RPM failed: ")) + (errmsg.empty() ? error_message: errmsg) ) );
468  }
469  else
470  {
471  tics.toMax();
472  }
473 }
474 
476 namespace
477 {
482  void computeKeyRingSync( std::set<Edition> & rpmKeys_r, std::list<PublicKeyData> & zyppKeys_r )
483  {
485  // Remember latest release and where it ocurred
486  struct Key
487  {
488  Key()
489  : _inRpmKeys( nullptr )
490  , _inZyppKeys( nullptr )
491  {}
492 
493  void updateIf( const Edition & rpmKey_r )
494  {
495  std::string keyRelease( rpmKey_r.release() );
496  int comp = _release.compare( keyRelease );
497  if ( comp < 0 )
498  {
499  // update to newer release
500  _release.swap( keyRelease );
501  _inRpmKeys = &rpmKey_r;
502  _inZyppKeys = nullptr;
503  if ( !keyRelease.empty() )
504  DBG << "Old key in Z: gpg-pubkey-" << rpmKey_r.version() << "-" << keyRelease << endl;
505  }
506  else if ( comp == 0 )
507  {
508  // stay with this release
509  if ( ! _inRpmKeys )
510  _inRpmKeys = &rpmKey_r;
511  }
512  // else: this is an old release
513  else
514  DBG << "Old key in R: gpg-pubkey-" << rpmKey_r.version() << "-" << keyRelease << endl;
515  }
516 
517  void updateIf( const PublicKeyData & zyppKey_r )
518  {
519  std::string keyRelease( zyppKey_r.gpgPubkeyRelease() );
520  int comp = _release.compare( keyRelease );
521  if ( comp < 0 )
522  {
523  // update to newer release
524  _release.swap( keyRelease );
525  _inRpmKeys = nullptr;
526  _inZyppKeys = &zyppKey_r;
527  if ( !keyRelease.empty() )
528  DBG << "Old key in R: gpg-pubkey-" << zyppKey_r.gpgPubkeyVersion() << "-" << keyRelease << endl;
529  }
530  else if ( comp == 0 )
531  {
532  // stay with this release
533  if ( ! _inZyppKeys )
534  _inZyppKeys = &zyppKey_r;
535  }
536  // else: this is an old release
537  else
538  DBG << "Old key in Z: gpg-pubkey-" << zyppKey_r.gpgPubkeyVersion() << "-" << keyRelease << endl;
539  }
540 
541  std::string _release;
542  const Edition * _inRpmKeys;
543  const PublicKeyData * _inZyppKeys;
544  };
546 
547  // collect keys by ID(version) and latest creation(release)
548  std::map<std::string,Key> _keymap;
549 
550  for_( it, rpmKeys_r.begin(), rpmKeys_r.end() )
551  {
552  _keymap[(*it).version()].updateIf( *it );
553  }
554 
555  for_( it, zyppKeys_r.begin(), zyppKeys_r.end() )
556  {
557  _keymap[(*it).gpgPubkeyVersion()].updateIf( *it );
558  }
559 
560  // compute missing keys
561  std::set<Edition> rpmKeys;
562  std::list<PublicKeyData> zyppKeys;
563  for_( it, _keymap.begin(), _keymap.end() )
564  {
565  DBG << "gpg-pubkey-" << (*it).first << "-" << (*it).second._release << " "
566  << ( (*it).second._inRpmKeys ? "R" : "_" )
567  << ( (*it).second._inZyppKeys ? "Z" : "_" ) << endl;
568  if ( ! (*it).second._inRpmKeys )
569  {
570  zyppKeys.push_back( *(*it).second._inZyppKeys );
571  }
572  if ( ! (*it).second._inZyppKeys )
573  {
574  rpmKeys.insert( *(*it).second._inRpmKeys );
575  }
576  }
577  rpmKeys_r.swap( rpmKeys );
578  zyppKeys_r.swap( zyppKeys );
579  }
580 } // namespace
582 
584 {
585  MIL << "Going to sync trusted keys..." << endl;
586  std::set<Edition> rpmKeys( pubkeyEditions() );
587  std::list<PublicKeyData> zyppKeys( getZYpp()->keyRing()->trustedPublicKeyData() );
588 
589  if ( ! ( mode_r & SYNC_FROM_KEYRING ) )
590  {
591  // bsc#1064380: We relief PK from removing excess keys in the zypp keyring
592  // when re-acquiring the zyppp lock. For now we remove all excess keys.
593  // TODO: Once we can safely assume that all PK versions are updated we
594  // can think about re-importing newer key versions found in the zypp keyring and
595  // removing only excess ones (but case is not very likely). Unfixed PK versions
596  // however will remove the newer version found in the zypp keyring and by doing
597  // this, the key here will be removed via callback as well (keys are deleted
598  // via gpg id, regardless of the edition).
599  MIL << "Removing excess keys in zypp trusted keyring" << std::endl;
600  // Temporarily disconnect to prevent the attempt to pass back the delete request.
602  bool dirty = false;
603  for ( const PublicKeyData & keyData : zyppKeys )
604  {
605  if ( ! rpmKeys.count( keyData.gpgPubkeyEdition() ) )
606  {
607  DBG << "Excess key in Z to delete: gpg-pubkey-" << keyData.gpgPubkeyEdition() << endl;
608  getZYpp()->keyRing()->deleteKey( keyData.id(), /*trusted*/true );
609  if ( !dirty ) dirty = true;
610  }
611  }
612  if ( dirty )
613  zyppKeys = getZYpp()->keyRing()->trustedPublicKeyData();
614  }
615 
616  computeKeyRingSync( rpmKeys, zyppKeys );
617  MIL << (mode_r & SYNC_TO_KEYRING ? "" : "(skip) ") << "Rpm keys to export into zypp trusted keyring: " << rpmKeys.size() << endl;
618  MIL << (mode_r & SYNC_FROM_KEYRING ? "" : "(skip) ") << "Zypp trusted keys to import into rpm database: " << zyppKeys.size() << endl;
619 
621  if ( (mode_r & SYNC_TO_KEYRING) && ! rpmKeys.empty() )
622  {
623  // export to zypp keyring
624  MIL << "Exporting rpm keyring into zypp trusted keyring" <<endl;
625  // Temporarily disconnect to prevent the attempt to re-import the exported keys.
627  librpmDb::db_const_iterator keepDbOpen; // just to keep a ref.
628 
629  TmpFile tmpfile( getZYpp()->tmpPath() );
630  {
631  std::ofstream tmpos( tmpfile.path().c_str() );
632  for_( it, rpmKeys.begin(), rpmKeys.end() )
633  {
634  // we export the rpm key into a file
635  RpmHeader::constPtr result;
636  getData( "gpg-pubkey", *it, result );
637  tmpos << result->tag_description() << endl;
638  }
639  }
640  try
641  {
642  getZYpp()->keyRing()->multiKeyImport( tmpfile.path(), true /*trusted*/);
643  // bsc#1096217: Try to spot and report legacy V3 keys found in the rpm database.
644  // Modern rpm does not import those keys, but when migrating a pre SLE12 system
645  // we may find them. rpm>4.13 even complains on sderr if sucha key is present.
646  std::set<Edition> missingKeys;
647  for ( const Edition & key : rpmKeys )
648  {
649  if ( getZYpp()->keyRing()->isKeyTrusted( key.version() ) ) // key.version is the gpgkeys short ID
650  continue;
651  ERR << "Could not import key:" << str::Format("gpg-pubkey-%s") % key << " into zypp keyring (V3 key?)" << endl;
652  missingKeys.insert( key );
653  }
654  if ( ! missingKeys.empty() )
655  callback::SendReport<KeyRingReport>()->reportNonImportedKeys(missingKeys);
656  }
657  catch ( const Exception & excpt )
658  {
659  ZYPP_CAUGHT( excpt );
660  ERR << "Could not import keys into zypp keyring: " << endl;
661  }
662  }
663 
665  if ( (mode_r & SYNC_FROM_KEYRING) && ! zyppKeys.empty() )
666  {
667  // import from zypp keyring
668  MIL << "Importing zypp trusted keyring" << std::endl;
669  for_( it, zyppKeys.begin(), zyppKeys.end() )
670  {
671  try
672  {
673  importPubkey( getZYpp()->keyRing()->exportTrustedPublicKey( *it ) );
674  }
675  catch ( const RpmException & exp )
676  {
677  ZYPP_CAUGHT( exp );
678  }
679  }
680  }
681  MIL << "Trusted keys synced." << endl;
682 }
683 
686 
689 
691 //
692 //
693 // METHOD NAME : RpmDb::importPubkey
694 // METHOD TYPE : PMError
695 //
696 void RpmDb::importPubkey( const PublicKey & pubkey_r )
697 {
699 
700  // bnc#828672: On the fly key import in READONLY
702  {
703  WAR << "Key " << pubkey_r << " can not be imported. (READONLY MODE)" << endl;
704  return;
705  }
706 
707  // check if the key is already in the rpm database
708  Edition keyEd( pubkey_r.gpgPubkeyVersion(), pubkey_r.gpgPubkeyRelease() );
709  std::set<Edition> rpmKeys = pubkeyEditions();
710  bool hasOldkeys = false;
711 
712  for_( it, rpmKeys.begin(), rpmKeys.end() )
713  {
714  // bsc#1008325: Keys using subkeys for signing don't get a higher release
715  // if new subkeys are added, because the primary key remains unchanged.
716  // For now always re-import keys with subkeys. Here we don't want to export the
717  // keys in the rpm database to check whether the subkeys are the same. The calling
718  // code should take care, we don't re-import the same kesy over and over again.
719  if ( keyEd == *it && !pubkey_r.hasSubkeys() ) // quick test (Edition is IdStringType!)
720  {
721  MIL << "Key " << pubkey_r << " is already in the rpm trusted keyring. (skip import)" << endl;
722  return;
723  }
724 
725  if ( keyEd.version() != (*it).version() )
726  continue; // different key ID (version)
727 
728  if ( keyEd.release() < (*it).release() )
729  {
730  MIL << "Key " << pubkey_r << " is older than one in the rpm trusted keyring. (skip import)" << endl;
731  return;
732  }
733  else
734  {
735  hasOldkeys = true;
736  }
737  }
738  MIL << "Key " << pubkey_r << " will be imported into the rpm trusted keyring." << (hasOldkeys?"(update)":"(new)") << endl;
739 
740  if ( hasOldkeys )
741  {
742  // We must explicitly delete old key IDs first (all releases,
743  // that's why we don't call removePubkey here).
744  std::string keyName( "gpg-pubkey-" + keyEd.version() );
745  RpmArgVec opts;
746  opts.push_back ( "-e" );
747  opts.push_back ( "--allmatches" );
748  opts.push_back ( "--" );
749  opts.push_back ( keyName.c_str() );
751 
752  std::string line;
753  while ( systemReadLine( line ) )
754  {
755  ( str::startsWith( line, "error:" ) ? WAR : DBG ) << line << endl;
756  }
757 
758  if ( systemStatus() != 0 )
759  {
760  ERR << "Failed to remove key " << pubkey_r << " from RPM trusted keyring (ignored)" << endl;
761  }
762  else
763  {
764  MIL << "Key " << pubkey_r << " has been removed from RPM trusted keyring" << endl;
765  }
766  }
767 
768  // import the new key
769  RpmArgVec opts;
770  opts.push_back ( "--import" );
771  opts.push_back ( "--" );
772  std::string pubkeypath( pubkey_r.path().asString() );
773  opts.push_back ( pubkeypath.c_str() );
775 
776  std::string line;
777  std::vector<std::string> excplines;
778  while ( systemReadLine( line ) )
779  {
780  if ( str::startsWith( line, "error:" ) )
781  {
782  WAR << line << endl;
783  excplines.push_back( std::move(line) );
784  }
785  else
786  DBG << line << endl;
787  }
788 
789  if ( systemStatus() != 0 )
790  {
791  // Translator: %1% is a gpg public key
792  RpmSubprocessException excp( str::Format(_("Failed to import public key %1%") ) % pubkey_r.asString() );
793  excp.moveToHistory( excplines );
794  excp.addHistory( std::move(error_message) );
795  ZYPP_THROW( std::move(excp) );
796  }
797  else
798  {
799  MIL << "Key " << pubkey_r << " imported in rpm trusted keyring." << endl;
800  }
801 }
802 
804 //
805 //
806 // METHOD NAME : RpmDb::removePubkey
807 // METHOD TYPE : PMError
808 //
809 void RpmDb::removePubkey( const PublicKey & pubkey_r )
810 {
812 
813  // check if the key is in the rpm database and just
814  // return if it does not.
815  std::set<Edition> rpm_keys = pubkeyEditions();
816  std::set<Edition>::const_iterator found_edition = rpm_keys.end();
817  std::string pubkeyVersion( pubkey_r.gpgPubkeyVersion() );
818 
819  for_( it, rpm_keys.begin(), rpm_keys.end() )
820  {
821  if ( (*it).version() == pubkeyVersion )
822  {
823  found_edition = it;
824  break;
825  }
826  }
827 
828  // the key does not exist, cannot be removed
829  if (found_edition == rpm_keys.end())
830  {
831  WAR << "Key " << pubkey_r.id() << " is not in rpm db" << endl;
832  return;
833  }
834 
835  std::string rpm_name("gpg-pubkey-" + found_edition->asString());
836 
837  RpmArgVec opts;
838  opts.push_back ( "-e" );
839  opts.push_back ( "--" );
840  opts.push_back ( rpm_name.c_str() );
842 
843  std::string line;
844  std::vector<std::string> excplines;
845  while ( systemReadLine( line ) )
846  {
847  if ( str::startsWith( line, "error:" ) )
848  {
849  WAR << line << endl;
850  excplines.push_back( std::move(line) );
851  }
852  else
853  DBG << line << endl;
854  }
855 
856  if ( systemStatus() != 0 )
857  {
858  // Translator: %1% is a gpg public key
859  RpmSubprocessException excp( str::Format(_("Failed to remove public key %1%") ) % pubkey_r.asString() );
860  excp.moveToHistory( excplines );
861  excp.addHistory( std::move(error_message) );
862  ZYPP_THROW( std::move(excp) );
863  }
864  else
865  {
866  MIL << "Key " << pubkey_r << " has been removed from RPM trusted keyring" << endl;
867  }
868 }
869 
871 //
872 //
873 // METHOD NAME : RpmDb::pubkeys
874 // METHOD TYPE : std::set<Edition>
875 //
876 std::list<PublicKey> RpmDb::pubkeys() const
877 {
878  std::list<PublicKey> ret;
879 
881  for ( it.findByName( "gpg-pubkey" ); *it; ++it )
882  {
883  Edition edition = it->tag_edition();
884  if (edition != Edition::noedition)
885  {
886  // we export the rpm key into a file
887  RpmHeader::constPtr result;
888  getData( "gpg-pubkey", edition, result );
889  TmpFile file(getZYpp()->tmpPath());
890  std::ofstream os;
891  try
892  {
893  os.open(file.path().asString().c_str());
894  // dump rpm key into the tmp file
895  os << result->tag_description();
896  //MIL << "-----------------------------------------------" << endl;
897  //MIL << result->tag_description() <<endl;
898  //MIL << "-----------------------------------------------" << endl;
899  os.close();
900  // read the public key from the dumped file
901  PublicKey key(file);
902  ret.push_back(key);
903  }
904  catch ( std::exception & e )
905  {
906  ERR << "Could not dump key " << edition.asString() << " in tmp file " << file.path() << endl;
907  // just ignore the key
908  }
909  }
910  }
911  return ret;
912 }
913 
914 std::set<Edition> RpmDb::pubkeyEditions() const
915  {
916  std::set<Edition> ret;
917 
919  for ( it.findByName( "gpg-pubkey" ); *it; ++it )
920  {
921  Edition edition = it->tag_edition();
922  if (edition != Edition::noedition)
923  ret.insert( edition );
924  }
925  return ret;
926  }
927 
928 
930 //
931 //
932 // METHOD NAME : RpmDb::fileList
933 // METHOD TYPE : bool
934 //
935 // DESCRIPTION :
936 //
937 std::list<FileInfo>
938 RpmDb::fileList( const std::string & name_r, const Edition & edition_r ) const
939 {
940  std::list<FileInfo> result;
941 
943  bool found;
944  if (edition_r == Edition::noedition)
945  {
946  found = it.findPackage( name_r );
947  }
948  else
949  {
950  found = it.findPackage( name_r, edition_r );
951  }
952  if (!found)
953  return result;
954 
955  return result;
956 }
957 
958 
960 //
961 //
962 // METHOD NAME : RpmDb::hasFile
963 // METHOD TYPE : bool
964 //
965 // DESCRIPTION :
966 //
967 bool RpmDb::hasFile( const std::string & file_r, const std::string & name_r ) const
968 {
970  bool res;
971  do
972  {
973  res = it.findByFile( file_r );
974  if (!res) break;
975  if (!name_r.empty())
976  {
977  res = (it->tag_name() == name_r);
978  }
979  ++it;
980  }
981  while (res && *it);
982  return res;
983 }
984 
986 //
987 //
988 // METHOD NAME : RpmDb::whoOwnsFile
989 // METHOD TYPE : std::string
990 //
991 // DESCRIPTION :
992 //
993 std::string RpmDb::whoOwnsFile( const std::string & file_r) const
994 {
996  if (it.findByFile( file_r ))
997  {
998  return it->tag_name();
999  }
1000  return "";
1001 }
1002 
1004 //
1005 //
1006 // METHOD NAME : RpmDb::hasProvides
1007 // METHOD TYPE : bool
1008 //
1009 // DESCRIPTION :
1010 //
1011 bool RpmDb::hasProvides( const std::string & tag_r ) const
1012 {
1014  return it.findByProvides( tag_r );
1015 }
1016 
1018 //
1019 //
1020 // METHOD NAME : RpmDb::hasRequiredBy
1021 // METHOD TYPE : bool
1022 //
1023 // DESCRIPTION :
1024 //
1025 bool RpmDb::hasRequiredBy( const std::string & tag_r ) const
1026 {
1028  return it.findByRequiredBy( tag_r );
1029 }
1030 
1032 //
1033 //
1034 // METHOD NAME : RpmDb::hasConflicts
1035 // METHOD TYPE : bool
1036 //
1037 // DESCRIPTION :
1038 //
1039 bool RpmDb::hasConflicts( const std::string & tag_r ) const
1040 {
1042  return it.findByConflicts( tag_r );
1043 }
1044 
1046 //
1047 //
1048 // METHOD NAME : RpmDb::hasPackage
1049 // METHOD TYPE : bool
1050 //
1051 // DESCRIPTION :
1052 //
1053 bool RpmDb::hasPackage( const std::string & name_r ) const
1054 {
1056  return it.findPackage( name_r );
1057 }
1058 
1060 //
1061 //
1062 // METHOD NAME : RpmDb::hasPackage
1063 // METHOD TYPE : bool
1064 //
1065 // DESCRIPTION :
1066 //
1067 bool RpmDb::hasPackage( const std::string & name_r, const Edition & ed_r ) const
1068 {
1070  return it.findPackage( name_r, ed_r );
1071 }
1072 
1074 //
1075 //
1076 // METHOD NAME : RpmDb::getData
1077 // METHOD TYPE : PMError
1078 //
1079 // DESCRIPTION :
1080 //
1081 void RpmDb::getData( const std::string & name_r,
1082  RpmHeader::constPtr & result_r ) const
1083 {
1085  it.findPackage( name_r );
1086  result_r = *it;
1087  if (it.dbError())
1088  ZYPP_THROW(*(it.dbError()));
1089 }
1090 
1092 //
1093 //
1094 // METHOD NAME : RpmDb::getData
1095 // METHOD TYPE : void
1096 //
1097 // DESCRIPTION :
1098 //
1099 void RpmDb::getData( const std::string & name_r, const Edition & ed_r,
1100  RpmHeader::constPtr & result_r ) const
1101 {
1103  it.findPackage( name_r, ed_r );
1104  result_r = *it;
1105  if (it.dbError())
1106  ZYPP_THROW(*(it.dbError()));
1107 }
1108 
1110 namespace
1111 {
1112  struct RpmlogCapture : public std::string
1113  {
1114  RpmlogCapture() : _cap(this)
1115  {
1116  rpmlogSetCallback( rpmLogCB, this );
1117  _oldMask = rpmlogSetMask( RPMLOG_UPTO( RPMLOG_PRI(RPMLOG_INFO) ) );
1118  }
1119 
1120  ~RpmlogCapture()
1121  {
1122  rpmlogSetCallback( nullptr, nullptr );
1123  rpmlogSetMask( _oldMask );
1124  }
1125 
1126  static int rpmLogCB( rpmlogRec rec_r, rpmlogCallbackData data_r )
1127  { return reinterpret_cast<RpmlogCapture*>(data_r)->rpmLog( rec_r ); }
1128 
1129  int rpmLog( rpmlogRec rec_r )
1130  {
1131  if ( _cap ) (*_cap) += rpmlogRecMessage( rec_r );
1132  return 0;
1133  }
1134 
1135  private:
1136  std::string * _cap;
1137  int _oldMask = 0;
1138  };
1139 
1140  RpmDb::CheckPackageResult doCheckPackageSig( const Pathname & path_r, // rpm file to check
1141  const Pathname & root_r, // target root
1142  bool requireGPGSig_r, // whether no gpg signature is to be reported
1143  RpmDb::CheckPackageDetail & detail_r ) // detailed result
1144  {
1145  PathInfo file( path_r );
1146  if ( ! file.isFile() )
1147  {
1148  ERR << "Not a file: " << file << endl;
1149  return RpmDb::CHK_ERROR;
1150  }
1151 
1152  FD_t fd = ::Fopen( file.asString().c_str(), "r.ufdio" );
1153  if ( fd == 0 || ::Ferror(fd) )
1154  {
1155  ERR << "Can't open file for reading: " << file << " (" << ::Fstrerror(fd) << ")" << endl;
1156  if ( fd )
1157  ::Fclose( fd );
1158  return RpmDb::CHK_ERROR;
1159  }
1160  rpmts ts = ::rpmtsCreate();
1161  ::rpmtsSetRootDir( ts, root_r.c_str() );
1162  ::rpmtsSetVSFlags( ts, RPMVSF_DEFAULT );
1163 
1164  rpmQVKArguments_s qva;
1165  memset( &qva, 0, sizeof(rpmQVKArguments_s) );
1166 #ifndef HAVE_RPM_VERIFY_TRANSACTION_STEP
1167  // Legacy: In rpm >= 4.15 qva_flags symbols don't exist
1168  // and qva_flags is not used in signature checking at all.
1169  qva.qva_flags = (VERIFY_DIGEST|VERIFY_SIGNATURE);
1170 #else
1171  ::rpmtsSetVfyFlags( ts, RPMVSF_DEFAULT );
1172 #endif
1173  RpmlogCapture vresult;
1174  LocaleGuard guard( LC_ALL, "C" ); // bsc#1076415: rpm log output is localized, but we need to parse it :(
1175  int res = ::rpmVerifySignatures( &qva, ts, fd, path_r.basename().c_str() );
1176  guard.restore();
1177 
1178  ts = rpmtsFree(ts);
1179  ::Fclose( fd );
1180 
1181  // results per line...
1182  // Header V3 RSA/SHA256 Signature, key ID 3dbdc284: OK
1183  // Header SHA1 digest: OK (a60386347863affefef484ff1f26c889373eb094)
1184  // V3 RSA/SHA256 Signature, key ID 3dbdc284: OK
1185  // MD5 digest: OK (fd5259fe677a406951dcb2e9d08c4dcc)
1186  //
1187  std::vector<std::string> lines;
1188  str::split( vresult, std::back_inserter(lines), "\n" );
1189  unsigned count[7] = { 0, 0, 0, 0, 0, 0, 0 };
1190 
1191  for ( unsigned i = 1; i < lines.size(); ++i )
1192  {
1193  std::string &line( lines[i] );
1194 
1196  if ( line.find( ": OK" ) != std::string::npos )
1197  {
1198  lineres = RpmDb::CHK_OK;
1199  if ( line.find( "Signature, key ID" ) == std::string::npos )
1200  ++count[RpmDb::CHK_NOSIG]; // Valid but no gpg signature -> CHK_NOSIG
1201  }
1202  else if ( line.find( ": NOKEY" ) != std::string::npos )
1203  { lineres = RpmDb::CHK_NOKEY; }
1204  else if ( line.find( ": BAD" ) != std::string::npos )
1205  { lineres = RpmDb::CHK_FAIL; }
1206  else if ( line.find( ": UNKNOWN" ) != std::string::npos )
1207  { lineres = RpmDb::CHK_NOTFOUND; }
1208  else if ( line.find( ": NOTRUSTED" ) != std::string::npos )
1209  { lineres = RpmDb::CHK_NOTTRUSTED; }
1210  else if ( line.find( ": NOTFOUND" ) != std::string::npos )
1211  { continue; } // just collect details for signatures found (#229)
1212 
1213  ++count[lineres];
1214  detail_r.push_back( RpmDb::CheckPackageDetail::value_type( lineres, std::move(line) ) );
1215  }
1216 
1218 
1219  if ( count[RpmDb::CHK_FAIL] )
1220  ret = RpmDb::CHK_FAIL;
1221 
1222  else if ( count[RpmDb::CHK_NOTFOUND] )
1223  ret = RpmDb::CHK_NOTFOUND;
1224 
1225  else if ( count[RpmDb::CHK_NOKEY] )
1226  ret = RpmDb::CHK_NOKEY;
1227 
1228  else if ( count[RpmDb::CHK_NOTTRUSTED] )
1229  ret = RpmDb::CHK_NOTTRUSTED;
1230 
1231  else if ( ret == RpmDb::CHK_OK )
1232  {
1233  if ( count[RpmDb::CHK_OK] == count[RpmDb::CHK_NOSIG] )
1234  {
1235  detail_r.push_back( RpmDb::CheckPackageDetail::value_type( RpmDb::CHK_NOSIG, std::string(" ")+_("Package is not signed!") ) );
1236  if ( requireGPGSig_r )
1237  ret = RpmDb::CHK_NOSIG;
1238  }
1239  }
1240 
1241  if ( ret != RpmDb::CHK_OK )
1242  {
1243 
1244  bool didReadHeader = false;
1245  std::unordered_map< std::string, std::string> fprs;
1246 
1247  // we replace the data only if the key IDs are actually only 8 bytes
1248  str::regex rxexpr( "key ID ([a-fA-F0-9]{8}):" );
1249  for ( auto &detail : detail_r ) {
1250  auto &line = detail.second;
1251  str::smatch what;
1252  if ( str::regex_match( line, what, rxexpr ) ) {
1253 
1254  if ( !didReadHeader ) {
1255  didReadHeader = true;
1256 
1257  // Get signature info from the package header, RPM always prints only the 8 byte ID
1258  auto header = RpmHeader::readPackage( path_r, RpmHeader::NOVERIFY );
1259  if ( header ) {
1260  auto keyMgr = zypp::KeyManagerCtx::createForOpenPGP();
1261  const auto &addFprs = [&]( auto tag ){
1262  const auto &list1 = keyMgr.readSignatureFingerprints( header->blob_val( tag ) );
1263  for ( const auto &id : list1 ) {
1264  if ( id.size() <= 8 )
1265  continue;
1266 
1267  const auto &lowerId = str::toLower( id );
1268  fprs.insert( std::make_pair( lowerId.substr( lowerId.size() - 8 ), lowerId ) );
1269  }
1270  };
1271 
1272  addFprs( RPMTAG_SIGGPG );
1273  addFprs( RPMTAG_SIGPGP );
1274  addFprs( RPMTAG_RSAHEADER );
1275  addFprs( RPMTAG_DSAHEADER );
1276 
1277  } else {
1278  ERR << "Failed to read package signatures." << std::endl;
1279  }
1280  }
1281 
1282  // if we have no keys we can substiture we can leave the loop right away
1283  if ( !fprs.size() )
1284  break;
1285 
1286  {
1287  // replace the short key ID with the long ones parsed from the header
1288  const auto &keyId = str::toLower( what[1] );
1289  if ( const auto &i = fprs.find( keyId ); i != fprs.end() ) {
1290  str::replaceAll( line, keyId, i->second );
1291  }
1292  }
1293  }
1294  }
1295 
1296  WAR << path_r << " (" << requireGPGSig_r << " -> " << ret << ")" << endl;
1297  WAR << vresult;
1298  }
1299  else
1300  DBG << path_r << " [0-Signature is OK]" << endl;
1301  return ret;
1302  }
1303 
1304 } // namespace
1306 //
1307 // METHOD NAME : RpmDb::checkPackage
1308 // METHOD TYPE : RpmDb::CheckPackageResult
1309 //
1311 { return doCheckPackageSig( path_r, root(), false/*requireGPGSig_r*/, detail_r ); }
1312 
1314 { CheckPackageDetail dummy; return checkPackage( path_r, dummy ); }
1315 
1317 { return doCheckPackageSig( path_r, root(), true/*requireGPGSig_r*/, detail_r ); }
1318 
1319 
1320 // determine changed files of installed package
1321 bool
1322 RpmDb::queryChangedFiles(FileList & fileList, const std::string& packageName)
1323 {
1324  bool ok = true;
1325 
1326  fileList.clear();
1327 
1328  if ( ! initialized() ) return false;
1329 
1330  RpmArgVec opts;
1331 
1332  opts.push_back ("-V");
1333  opts.push_back ("--nodeps");
1334  opts.push_back ("--noscripts");
1335  opts.push_back ("--nomd5");
1336  opts.push_back ("--");
1337  opts.push_back (packageName.c_str());
1338 
1340 
1341  if ( process == NULL )
1342  return false;
1343 
1344  /* from rpm manpage
1345  5 MD5 sum
1346  S File size
1347  L Symlink
1348  T Mtime
1349  D Device
1350  U User
1351  G Group
1352  M Mode (includes permissions and file type)
1353  */
1354 
1355  std::string line;
1356  while (systemReadLine(line))
1357  {
1358  if (line.length() > 12 &&
1359  (line[0] == 'S' || line[0] == 's' ||
1360  (line[0] == '.' && line[7] == 'T')))
1361  {
1362  // file has been changed
1363  std::string filename;
1364 
1365  filename.assign(line, 11, line.length() - 11);
1366  fileList.insert(filename);
1367  }
1368  }
1369 
1370  systemStatus();
1371  // exit code ignored, rpm returns 1 no matter if package is installed or
1372  // not
1373 
1374  return ok;
1375 }
1376 
1377 
1378 /****************************************************************/
1379 /* private member-functions */
1380 /****************************************************************/
1381 
1382 /*--------------------------------------------------------------*/
1383 /* Run rpm with the specified arguments, handling stderr */
1384 /* as specified by disp */
1385 /*--------------------------------------------------------------*/
1386 void
1389 {
1390  if ( process )
1391  {
1392  delete process;
1393  process = NULL;
1394  }
1395  exit_code = -1;
1396 
1397  if ( ! initialized() )
1398  {
1400  }
1401 
1402  RpmArgVec args;
1403 
1404  // always set root and dbpath
1405 #if defined(WORKAROUNDRPMPWDBUG)
1406  args.push_back("#/"); // chdir to / to workaround bnc#819354
1407 #endif
1408  args.push_back("rpm");
1409  args.push_back("--root");
1410  args.push_back(_root.asString().c_str());
1411  args.push_back("--dbpath");
1412  args.push_back(_dbPath.asString().c_str());
1413  if ( env::ZYPP_RPM_DEBUG() )
1414  args.push_back("-vv");
1415  const char* argv[args.size() + opts.size() + 1];
1416 
1417  const char** p = argv;
1418  p = copy (args.begin (), args.end (), p);
1419  p = copy (opts.begin (), opts.end (), p);
1420  *p = 0;
1421 
1422  // Invalidate all outstanding database handles in case
1423  // the database gets modified.
1424  librpmDb::dbRelease( true );
1425 
1426  // Launch the program with default locale
1427  process = new ExternalProgram(argv, disp, false, -1, true);
1428  return;
1429 }
1430 
1431 /*--------------------------------------------------------------*/
1432 /* Read a line from the rpm process */
1433 /*--------------------------------------------------------------*/
1434 bool RpmDb::systemReadLine( std::string & line )
1435 {
1436  line.erase();
1437 
1438  if ( process == NULL )
1439  return false;
1440 
1441  if ( process->inputFile() )
1442  {
1443  process->setBlocking( false );
1444  FILE * inputfile = process->inputFile();
1445  do {
1446  // Check every 5 seconds if the process is still running to prevent against
1447  // daemons launched in rpm %post that do not close their filedescriptors,
1448  // causing us to block for infinity. (bnc#174548)
1449  const auto &readResult = io::receiveUpto( inputfile, '\n', 5 * 1000, false );
1450  switch ( readResult.first ) {
1452  if ( !process->running() )
1453  return false;
1454 
1455  // we might have received a partial line, lets not forget about it
1456  line += readResult.second;
1457  }
1460  line += readResult.second;
1461  if ( line.size() && line.back() == '\n')
1462  line.pop_back();
1463  return line.size(); // in case of pending output
1464  }
1466  line += readResult.second;
1467 
1468  if ( line.size() && line.back() == '\n')
1469  line.pop_back();
1470 
1471  if ( env::ZYPP_RPM_DEBUG() )
1472  L_DBG("RPM_DEBUG") << line << endl;
1473  return true; // complete line
1474  }
1475  }
1476  } while( true );
1477  }
1478  return false;
1479 }
1480 
1481 /*--------------------------------------------------------------*/
1482 /* Return the exit status of the rpm process, closing the */
1483 /* connection if not already done */
1484 /*--------------------------------------------------------------*/
1485 int
1487 {
1488  if ( process == NULL )
1489  return -1;
1490 
1491  exit_code = process->close();
1492  if (exit_code == 0)
1493  error_message = "";
1494  else
1496  process->kill();
1497  delete process;
1498  process = 0;
1499 
1500  // DBG << "exit code " << exit_code << endl;
1501 
1502  return exit_code;
1503 }
1504 
1505 /*--------------------------------------------------------------*/
1506 /* Forcably kill the rpm process */
1507 /*--------------------------------------------------------------*/
1508 void
1510 {
1511  if (process) process->kill();
1512 }
1513 
1514 
1515 // generate diff mails for config files
1516 void RpmDb::processConfigFiles(const std::string& line, const std::string& name, const char* typemsg, const char* difffailmsg, const char* diffgenmsg)
1517 {
1518  std::string msg = line.substr(9);
1519  std::string::size_type pos1 = std::string::npos;
1520  std::string::size_type pos2 = std::string::npos;
1521  std::string file1s, file2s;
1522  Pathname file1;
1523  Pathname file2;
1524 
1525  pos1 = msg.find (typemsg);
1526  for (;;)
1527  {
1528  if ( pos1 == std::string::npos )
1529  break;
1530 
1531  pos2 = pos1 + strlen (typemsg);
1532 
1533  if (pos2 >= msg.length() )
1534  break;
1535 
1536  file1 = msg.substr (0, pos1);
1537  file2 = msg.substr (pos2);
1538 
1539  file1s = file1.asString();
1540  file2s = file2.asString();
1541 
1542  if (!_root.empty() && _root != "/")
1543  {
1544  file1 = _root + file1;
1545  file2 = _root + file2;
1546  }
1547 
1548  std::string out;
1549  int ret = diffFiles (file1.asString(), file2.asString(), out, 25);
1550  if (ret)
1551  {
1552  Pathname file = _root + WARNINGMAILPATH;
1553  if (filesystem::assert_dir(file) != 0)
1554  {
1555  ERR << "Could not create " << file.asString() << endl;
1556  break;
1557  }
1558  file += Date(Date::now()).form("config_diff_%Y_%m_%d.log");
1559  std::ofstream notify(file.asString().c_str(), std::ios::out|std::ios::app);
1560  if (!notify)
1561  {
1562  ERR << "Could not open " << file << endl;
1563  break;
1564  }
1565 
1566  // Translator: %s = name of an rpm package. A list of diffs follows
1567  // this message.
1568  notify << str::form(_("Changed configuration files for %s:"), name.c_str()) << endl;
1569  if (ret>1)
1570  {
1571  ERR << "diff failed" << endl;
1572  notify << str::form(difffailmsg,
1573  file1s.c_str(), file2s.c_str()) << endl;
1574  }
1575  else
1576  {
1577  notify << str::form(diffgenmsg,
1578  file1s.c_str(), file2s.c_str()) << endl;
1579 
1580  // remove root for the viewer's pleasure (#38240)
1581  if (!_root.empty() && _root != "/")
1582  {
1583  if (out.substr(0,4) == "--- ")
1584  {
1585  out.replace(4, file1.asString().length(), file1s);
1586  }
1587  std::string::size_type pos = out.find("\n+++ ");
1588  if (pos != std::string::npos)
1589  {
1590  out.replace(pos+5, file2.asString().length(), file2s);
1591  }
1592  }
1593  notify << out << endl;
1594  }
1595  notify.close();
1596  notify.open("/var/lib/update-messages/yast2-packagemanager.rpmdb.configfiles");
1597  notify.close();
1598  }
1599  else
1600  {
1601  WAR << "rpm created " << file2 << " but it is not different from " << file2 << endl;
1602  }
1603  break;
1604  }
1605 }
1606 
1608 //
1609 //
1610 // METHOD NAME : RpmDb::installPackage
1611 // METHOD TYPE : PMError
1612 //
1613 void RpmDb::installPackage( const Pathname & filename, RpmInstFlags flags )
1614 {
1616 
1617  report->start(filename);
1618 
1619  do
1620  try
1621  {
1622  doInstallPackage(filename, flags, report);
1623  report->finish();
1624  break;
1625  }
1626  catch (RpmException & excpt_r)
1627  {
1628  RpmInstallReport::Action user = report->problem( excpt_r );
1629 
1630  if ( user == RpmInstallReport::ABORT )
1631  {
1632  report->finish( excpt_r );
1633  ZYPP_RETHROW(excpt_r);
1634  }
1635  else if ( user == RpmInstallReport::IGNORE )
1636  {
1637  break;
1638  }
1639  }
1640  while (true);
1641 }
1642 
1643 void RpmDb::doInstallPackage( const Pathname & filename, RpmInstFlags flags, callback::SendReport<RpmInstallReport> & report )
1644 {
1646  HistoryLog historylog;
1647 
1648  MIL << "RpmDb::installPackage(" << filename << "," << flags << ")" << endl;
1649 
1650  // backup
1651  if ( _packagebackups )
1652  {
1653  // FIXME report->progress( pd.init( -2, 100 ) ); // allow 1% for backup creation.
1654  if ( ! backupPackage( filename ) )
1655  {
1656  ERR << "backup of " << filename.asString() << " failed" << endl;
1657  }
1658  // FIXME status handling
1659  report->progress( 0 ); // allow 1% for backup creation.
1660  }
1661 
1662  // run rpm
1663  RpmArgVec opts;
1664  if (flags & RPMINST_NOUPGRADE)
1665  opts.push_back("-i");
1666  else
1667  opts.push_back("-U");
1668 
1669  opts.push_back("--percent");
1670  opts.push_back("--noglob");
1671 
1672  // ZConfig defines cross-arch installation
1673  if ( ! ZConfig::instance().systemArchitecture().compatibleWith( ZConfig::instance().defaultSystemArchitecture() ) )
1674  opts.push_back("--ignorearch");
1675 
1676  if (flags & RPMINST_NODIGEST)
1677  opts.push_back("--nodigest");
1678  if (flags & RPMINST_NOSIGNATURE)
1679  opts.push_back("--nosignature");
1680  if (flags & RPMINST_EXCLUDEDOCS)
1681  opts.push_back ("--excludedocs");
1682  if (flags & RPMINST_NOSCRIPTS)
1683  opts.push_back ("--noscripts");
1684  if (flags & RPMINST_FORCE)
1685  opts.push_back ("--force");
1686  if (flags & RPMINST_NODEPS)
1687  opts.push_back ("--nodeps");
1688  if (flags & RPMINST_IGNORESIZE)
1689  opts.push_back ("--ignoresize");
1690  if (flags & RPMINST_JUSTDB)
1691  opts.push_back ("--justdb");
1692  if (flags & RPMINST_TEST)
1693  opts.push_back ("--test");
1694  if (flags & RPMINST_NOPOSTTRANS)
1695  opts.push_back ("--noposttrans");
1696 
1697  opts.push_back("--");
1698 
1699  // rpm requires additional quoting of special chars:
1700  std::string quotedFilename( rpmQuoteFilename( workaroundRpmPwdBug( filename ) ) );
1701  opts.push_back ( quotedFilename.c_str() );
1703 
1704  // forward additional rpm output via report;
1705  std::string line;
1706  unsigned lineno = 0;
1708  // Key "solvable" injected by RpmInstallPackageReceiver
1709  cmdout.set( "line", std::cref(line) );
1710  cmdout.set( "lineno", lineno );
1711 
1712  // LEGACY: collect and forward additional rpm output in finish
1713  std::string rpmmsg;
1714  std::vector<std::string> configwarnings; // TODO: immediately process lines rather than collecting
1715 
1716  while ( systemReadLine( line ) )
1717  {
1718  if ( str::startsWith( line, "%%" ) )
1719  {
1720  int percent;
1721  sscanf( line.c_str() + 2, "%d", &percent );
1722  report->progress( percent );
1723  continue;
1724  }
1725  ++lineno;
1726  cmdout.set( "lineno", lineno );
1727  report->report( cmdout );
1728 
1729  if ( lineno >= MAXRPMMESSAGELINES ) {
1730  if ( line.find( " scriptlet failed, " ) == std::string::npos ) // always log %script errors
1731  continue;
1732  }
1733 
1734  rpmmsg += line+'\n';
1735 
1736  if ( str::startsWith( line, "warning:" ) )
1737  configwarnings.push_back(line);
1738  }
1739  if ( lineno >= MAXRPMMESSAGELINES )
1740  rpmmsg += "[truncated]\n";
1741 
1742  int rpm_status = systemStatus();
1743 
1744  // evaluate result
1745  for (std::vector<std::string>::iterator it = configwarnings.begin();
1746  it != configwarnings.end(); ++it)
1747  {
1748  processConfigFiles(*it, Pathname::basename(filename), " saved as ",
1749  // %s = filenames
1750  _("rpm saved %s as %s, but it was impossible to determine the difference"),
1751  // %s = filenames
1752  _("rpm saved %s as %s.\nHere are the first 25 lines of difference:\n"));
1753  processConfigFiles(*it, Pathname::basename(filename), " created as ",
1754  // %s = filenames
1755  _("rpm created %s as %s, but it was impossible to determine the difference"),
1756  // %s = filenames
1757  _("rpm created %s as %s.\nHere are the first 25 lines of difference:\n"));
1758  }
1759 
1760  if ( rpm_status != 0 )
1761  {
1762  historylog.comment(
1763  str::form("%s install failed", Pathname::basename(filename).c_str()),
1764  true /*timestamp*/);
1765  std::ostringstream sstr;
1766  sstr << "rpm output:" << endl << rpmmsg << endl;
1767  historylog.comment(sstr.str());
1768  // TranslatorExplanation the colon is followed by an error message
1769  auto excpt { RpmSubprocessException(_("RPM failed: ") + error_message ) };
1770  if ( not rpmmsg.empty() )
1771  excpt.addHistory( rpmmsg );
1772  ZYPP_THROW(std::move(excpt));
1773  }
1774  else if ( ! rpmmsg.empty() )
1775  {
1776  historylog.comment(
1777  str::form("%s installed ok", Pathname::basename(filename).c_str()),
1778  true /*timestamp*/);
1779  std::ostringstream sstr;
1780  sstr << "Additional rpm output:" << endl << rpmmsg << endl;
1781  historylog.comment(sstr.str());
1782 
1783  // report additional rpm output in finish (LEGACY! Lines are immediately reported as InstallResolvableReport::contentRpmout)
1784  // TranslatorExplanation Text is followed by a ':' and the actual output.
1785  report->finishInfo(str::form( "%s:\n%s\n", _("Additional rpm output"), rpmmsg.c_str() ));
1786  }
1787 }
1788 
1790 //
1791 //
1792 // METHOD NAME : RpmDb::removePackage
1793 // METHOD TYPE : PMError
1794 //
1795 void RpmDb::removePackage( Package::constPtr package, RpmInstFlags flags )
1796 {
1797  // 'rpm -e' does not like epochs
1798  return removePackage( package->name()
1799  + "-" + package->edition().version()
1800  + "-" + package->edition().release()
1801  + "." + package->arch().asString(), flags );
1802 }
1803 
1805 //
1806 //
1807 // METHOD NAME : RpmDb::removePackage
1808 // METHOD TYPE : PMError
1809 //
1810 void RpmDb::removePackage( const std::string & name_r, RpmInstFlags flags )
1811 {
1813 
1814  report->start( name_r );
1815 
1816  do
1817  try
1818  {
1819  doRemovePackage(name_r, flags, report);
1820  report->finish();
1821  break;
1822  }
1823  catch (RpmException & excpt_r)
1824  {
1825  RpmRemoveReport::Action user = report->problem( excpt_r );
1826 
1827  if ( user == RpmRemoveReport::ABORT )
1828  {
1829  report->finish( excpt_r );
1830  ZYPP_RETHROW(excpt_r);
1831  }
1832  else if ( user == RpmRemoveReport::IGNORE )
1833  {
1834  break;
1835  }
1836  }
1837  while (true);
1838 }
1839 
1840 
1841 void RpmDb::doRemovePackage( const std::string & name_r, RpmInstFlags flags, callback::SendReport<RpmRemoveReport> & report )
1842 {
1844  HistoryLog historylog;
1845 
1846  MIL << "RpmDb::doRemovePackage(" << name_r << "," << flags << ")" << endl;
1847 
1848  // backup
1849  if ( _packagebackups )
1850  {
1851  // FIXME solve this status report somehow
1852  // report->progress( pd.init( -2, 100 ) ); // allow 1% for backup creation.
1853  if ( ! backupPackage( name_r ) )
1854  {
1855  ERR << "backup of " << name_r << " failed" << endl;
1856  }
1857  report->progress( 0 );
1858  }
1859  else
1860  {
1861  report->progress( 100 );
1862  }
1863 
1864  // run rpm
1865  RpmArgVec opts;
1866  opts.push_back("-e");
1867  opts.push_back("--allmatches");
1868 
1869  if (flags & RPMINST_NOSCRIPTS)
1870  opts.push_back("--noscripts");
1871  if (flags & RPMINST_NODEPS)
1872  opts.push_back("--nodeps");
1873  if (flags & RPMINST_JUSTDB)
1874  opts.push_back("--justdb");
1875  if (flags & RPMINST_TEST)
1876  opts.push_back ("--test");
1877  if (flags & RPMINST_FORCE)
1878  {
1879  WAR << "IGNORE OPTION: 'rpm -e' does not support '--force'" << endl;
1880  }
1881 
1882  opts.push_back("--");
1883  opts.push_back(name_r.c_str());
1885 
1886  // forward additional rpm output via report;
1887  std::string line;
1888  unsigned lineno = 0;
1890  // Key "solvable" injected by RpmInstallPackageReceiver
1891  cmdout.set( "line", std::cref(line) );
1892  cmdout.set( "lineno", lineno );
1893 
1894 
1895  // LEGACY: collect and forward additional rpm output in finish
1896  std::string rpmmsg;
1897 
1898  // got no progress from command, so we fake it:
1899  // 5 - command started
1900  // 50 - command completed
1901  // 100 if no error
1902  report->progress( 5 );
1903  while (systemReadLine(line))
1904  {
1905  ++lineno;
1906  cmdout.set( "lineno", lineno );
1907  report->report( cmdout );
1908 
1909  if ( lineno >= MAXRPMMESSAGELINES ) {
1910  if ( line.find( " scriptlet failed, " ) == std::string::npos ) // always log %script errors
1911  continue;
1912  }
1913  rpmmsg += line+'\n';
1914  }
1915  if ( lineno >= MAXRPMMESSAGELINES )
1916  rpmmsg += "[truncated]\n";
1917  report->progress( 50 );
1918  int rpm_status = systemStatus();
1919 
1920  if ( rpm_status != 0 )
1921  {
1922  historylog.comment(
1923  str::form("%s remove failed", name_r.c_str()), true /*timestamp*/);
1924  std::ostringstream sstr;
1925  sstr << "rpm output:" << endl << rpmmsg << endl;
1926  historylog.comment(sstr.str());
1927  // TranslatorExplanation the colon is followed by an error message
1928  auto excpt { RpmSubprocessException(_("RPM failed: ") + error_message ) };
1929  if ( not rpmmsg.empty() )
1930  excpt.addHistory( rpmmsg );
1931  ZYPP_THROW(std::move(excpt));
1932  }
1933  else if ( ! rpmmsg.empty() )
1934  {
1935  historylog.comment(
1936  str::form("%s removed ok", name_r.c_str()), true /*timestamp*/);
1937 
1938  std::ostringstream sstr;
1939  sstr << "Additional rpm output:" << endl << rpmmsg << endl;
1940  historylog.comment(sstr.str());
1941 
1942  // report additional rpm output in finish (LEGACY! Lines are immediately reported as RemoveResolvableReport::contentRpmout)
1943  // TranslatorExplanation Text is followed by a ':' and the actual output.
1944  report->finishInfo(str::form( "%s:\n%s\n", _("Additional rpm output"), rpmmsg.c_str() ));
1945  }
1946 }
1947 
1949 //
1950 //
1951 // METHOD NAME : RpmDb::backupPackage
1952 // METHOD TYPE : bool
1953 //
1954 bool RpmDb::backupPackage( const Pathname & filename )
1955 {
1957  if ( ! h )
1958  return false;
1959 
1960  return backupPackage( h->tag_name() );
1961 }
1962 
1964 //
1965 //
1966 // METHOD NAME : RpmDb::backupPackage
1967 // METHOD TYPE : bool
1968 //
1969 bool RpmDb::backupPackage(const std::string& packageName)
1970 {
1971  HistoryLog progresslog;
1972  bool ret = true;
1973  Pathname backupFilename;
1974  Pathname filestobackupfile = _root+_backuppath+FILEFORBACKUPFILES;
1975 
1976  if (_backuppath.empty())
1977  {
1978  INT << "_backuppath empty" << endl;
1979  return false;
1980  }
1981 
1983 
1984  if (!queryChangedFiles(fileList, packageName))
1985  {
1986  ERR << "Error while getting changed files for package " <<
1987  packageName << endl;
1988  return false;
1989  }
1990 
1991  if (fileList.size() <= 0)
1992  {
1993  DBG << "package " << packageName << " not changed -> no backup" << endl;
1994  return true;
1995  }
1996 
1998  {
1999  return false;
2000  }
2001 
2002  {
2003  // build up archive name
2004  time_t currentTime = time(0);
2005  struct tm *currentLocalTime = localtime(&currentTime);
2006 
2007  int date = (currentLocalTime->tm_year + 1900) * 10000
2008  + (currentLocalTime->tm_mon + 1) * 100
2009  + currentLocalTime->tm_mday;
2010 
2011  int num = 0;
2012  do
2013  {
2014  backupFilename = _root + _backuppath
2015  + str::form("%s-%d-%d.tar.gz",packageName.c_str(), date, num);
2016 
2017  }
2018  while ( PathInfo(backupFilename).isExist() && num++ < 1000);
2019 
2020  PathInfo pi(filestobackupfile);
2021  if (pi.isExist() && !pi.isFile())
2022  {
2023  ERR << filestobackupfile.asString() << " already exists and is no file" << endl;
2024  return false;
2025  }
2026 
2027  std::ofstream fp ( filestobackupfile.asString().c_str(), std::ios::out|std::ios::trunc );
2028 
2029  if (!fp)
2030  {
2031  ERR << "could not open " << filestobackupfile.asString() << endl;
2032  return false;
2033  }
2034 
2035  for (FileList::const_iterator cit = fileList.begin();
2036  cit != fileList.end(); ++cit)
2037  {
2038  std::string name = *cit;
2039  if ( name[0] == '/' )
2040  {
2041  // remove slash, file must be relative to -C parameter of tar
2042  name = name.substr( 1 );
2043  }
2044  DBG << "saving file "<< name << endl;
2045  fp << name << endl;
2046  }
2047  fp.close();
2048 
2049  const char* const argv[] =
2050  {
2051  "tar",
2052  "-czhP",
2053  "-C",
2054  _root.asString().c_str(),
2055  "--ignore-failed-read",
2056  "-f",
2057  backupFilename.asString().c_str(),
2058  "-T",
2059  filestobackupfile.asString().c_str(),
2060  NULL
2061  };
2062 
2063  // execute tar in inst-sys (we dont know if there is a tar below _root !)
2064  ExternalProgram tar(argv, ExternalProgram::Stderr_To_Stdout, false, -1, true);
2065 
2066  std::string tarmsg;
2067 
2068  // TODO: it is probably possible to start tar with -v and watch it adding
2069  // files to report progress
2070  for (std::string output = tar.receiveLine(); output.length() ;output = tar.receiveLine())
2071  {
2072  tarmsg+=output;
2073  }
2074 
2075  int ret = tar.close();
2076 
2077  if ( ret != 0)
2078  {
2079  ERR << "tar failed: " << tarmsg << endl;
2080  ret = false;
2081  }
2082  else
2083  {
2084  MIL << "tar backup ok" << endl;
2085  progresslog.comment(
2086  str::form(_("created backup %s"), backupFilename.asString().c_str())
2087  , /*timestamp*/true);
2088  }
2089 
2090  filesystem::unlink(filestobackupfile);
2091  }
2092 
2093  return ret;
2094 }
2095 
2097 {
2098  _backuppath = path;
2099 }
2100 
2101 std::ostream & operator<<( std::ostream & str, RpmDb::CheckPackageResult obj )
2102 {
2103  switch ( obj )
2104  {
2105 #define OUTS(E,S) case RpmDb::E: return str << "["<< (unsigned)obj << "-"<< S << "]"; break
2106  // translators: possible rpm package signature check result [brief]
2107  OUTS( CHK_OK, _("Signature is OK") );
2108  // translators: possible rpm package signature check result [brief]
2109  OUTS( CHK_NOTFOUND, _("Unknown type of signature") );
2110  // translators: possible rpm package signature check result [brief]
2111  OUTS( CHK_FAIL, _("Signature does not verify") );
2112  // translators: possible rpm package signature check result [brief]
2113  OUTS( CHK_NOTTRUSTED, _("Signature is OK, but key is not trusted") );
2114  // translators: possible rpm package signature check result [brief]
2115  OUTS( CHK_NOKEY, _("Signatures public key is not available") );
2116  // translators: possible rpm package signature check result [brief]
2117  OUTS( CHK_ERROR, _("File does not exist or signature can't be checked") );
2118  // translators: possible rpm package signature check result [brief]
2119  OUTS( CHK_NOSIG, _("File is unsigned") );
2120 #undef OUTS
2121  }
2122  return str << "UnknowSignatureCheckError("+str::numstring(obj)+")";
2123 }
2124 
2125 std::ostream & operator<<( std::ostream & str, const RpmDb::CheckPackageDetail & obj )
2126 {
2127  for ( const auto & el : obj )
2128  str << el.second << endl;
2129  return str;
2130 }
2131 
2132 } // namespace rpm
2133 } // namespace target
2134 } // namespace zypp
#define MAXRPMMESSAGELINES
Definition: RpmDb.cc:63
#define WARNINGMAILPATH
Definition: RpmDb.cc:61
std::string * _cap
Definition: RpmDb.cc:1136
int _oldMask
Definition: RpmDb.cc:1137
#define FAILIFNOTINITIALIZED
Definition: RpmDb.cc:211
#define OUTS(E, S)
#define FILEFORBACKUPFILES
Definition: RpmDb.cc:62
Store and operate on date (time_t).
Definition: Date.h:33
std::string form(const std::string &format_r) const
Return string representation according to format as localtime.
Definition: Date.h:112
static Date now()
Return the current time.
Definition: Date.h:78
Assign a vaiable a certain value when going out of scope.
Definition: dtorreset.h:50
Edition represents [epoch:]version[-release]
Definition: Edition.h:61
std::string version() const
Version.
Definition: Edition.cc:94
std::string release() const
Release.
Definition: Edition.cc:110
static const Edition noedition
Value representing noedition ("") This is in fact a valid Edition.
Definition: Edition.h:73
Base class for Exception.
Definition: Exception.h:146
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Definition: Exception.cc:91
void addHistory(const std::string &msg_r)
Add some message text to the history.
Definition: Exception.cc:140
void moveToHistory(TContainer &&msgc_r)
addHistory from string container types (oldest first) moving
Definition: Exception.h:237
Execute a program and give access to its io An object of this class encapsulates the execution of an ...
bool kill()
Kill the program.
const std::string & execError() const
Some detail telling why the execution failed, if it failed.
bool running()
Return whether program is running.
int close()
Wait for the progamm to complete.
Stderr_Disposition
Define symbols for different policies on the handling of stderr.
Writing the zypp history file.
Definition: HistoryLog.h:57
void comment(const std::string &comment, bool timestamp=false)
Log a comment (even multiline).
Definition: HistoryLog.cc:188
std::string asString() const
Definition: IdStringType.h:106
static KeyManagerCtx createForOpenPGP()
Creates a new KeyManagerCtx for PGP using a volatile temp.
Definition: KeyManager.cc:270
TraitsType::constPtrType constPtr
Definition: Package.h:38
Maintain [min,max] and counter (value) for progress counting.
Definition: progressdata.h:131
value_type reportValue() const
Definition: progressdata.h:319
long long value_type
Definition: progressdata.h:133
void sendTo(const ReceiverFnc &fnc_r)
Set ReceiverFnc.
Definition: progressdata.h:226
bool toMax()
Set counter value to current max value (unless no range).
Definition: progressdata.h:273
bool incr(value_type val_r=1)
Increment counter value (default by 1).
Definition: progressdata.h:261
bool toMin()
Set counter value to current min value.
Definition: progressdata.h:269
void range(value_type max_r)
Set new [0,max].
Definition: progressdata.h:213
Class representing one GPG Public Keys data.
Definition: PublicKey.h:207
Class representing one GPG Public Key (PublicKeyData + ASCII armored in a tempfile).
Definition: PublicKey.h:359
Pathname path() const
File containing the ASCII armored key.
Definition: PublicKey.cc:645
std::string gpgPubkeyRelease() const
Definition: PublicKey.cc:692
std::string asString() const
Definition: PublicKey.cc:695
std::string id() const
Definition: PublicKey.cc:662
std::string gpgPubkeyVersion() const
Definition: PublicKey.cc:689
bool hasSubkeys() const
!<
Definition: PublicKey.h:417
static ZConfig & instance()
Singleton ctor.
Definition: Resolver.cc:126
Typesafe passing of user data via callbacks.
Definition: UserData.h:39
bool set(const std::string &key_r, AnyType val_r)
Set the value for key (nonconst version always returns true).
Definition: UserData.h:118
zypp::ContentType ContentType
Definition: UserData.h:50
FILE * inputFile() const
Return the input stream.
void setBlocking(bool mode)
Set the blocking mode of the input stream.
std::string receiveLine()
Read one line from the input stream.
Wrapper class for ::stat/::lstat.
Definition: PathInfo.h:221
const std::string & asString() const
Return current Pathname as String.
Definition: PathInfo.h:248
bool isExist() const
Return whether valid stat info exists.
Definition: PathInfo.h:281
const std::string & asString() const
String representation.
Definition: Pathname.h:91
std::string basename() const
Return the last component of this path.
Definition: Pathname.h:128
bool empty() const
Test for an empty path.
Definition: Pathname.h:114
const char * c_str() const
String representation.
Definition: Pathname.h:110
bool relative() const
Test for a relative path.
Definition: Pathname.h:118
Provide a new empty temporary file and delete it when no longer needed.
Definition: TmpPath.h:128
Pathname path() const
Definition: TmpPath.cc:146
Interface to the rpm program.
Definition: RpmDb.h:48
void getData(const std::string &name_r, RpmHeader::constPtr &result_r) const
Get an installed packages data from rpmdb.
Definition: RpmDb.cc:1081
void doRebuildDatabase(callback::SendReport< RebuildDBReport > &report)
Definition: RpmDb.cc:402
bool queryChangedFiles(FileList &fileList, const std::string &packageName)
determine which files of an installed package have been modified.
Definition: RpmDb.cc:1322
std::string error_message
Error message from running rpm as external program.
Definition: RpmDb.h:319
bool hasRequiredBy(const std::string &tag_r) const
Return true if at least one package requires a certain tag.
Definition: RpmDb.cc:1025
virtual std::ostream & dumpOn(std::ostream &str) const
Dump debug info.
Definition: RpmDb.cc:255
std::string whoOwnsFile(const std::string &file_r) const
Return name of package owning file or empty string if no installed package owns file.
Definition: RpmDb.cc:993
void exportTrustedKeysInZyppKeyRing()
insert all rpm trusted keys into zypp trusted keyring
Definition: RpmDb.cc:687
void importPubkey(const PublicKey &pubkey_r)
Import ascii armored public key in file pubkey_r.
Definition: RpmDb.cc:696
void installPackage(const Pathname &filename, RpmInstFlags flags=RPMINST_NONE)
install rpm package
Definition: RpmDb.cc:1613
Pathname _backuppath
/var/adm/backup
Definition: RpmDb.h:322
void run_rpm(const RpmArgVec &options, ExternalProgram::Stderr_Disposition stderr_disp=ExternalProgram::Stderr_To_Stdout)
Run rpm with the specified arguments and handle stderr.
Definition: RpmDb.cc:1387
void initDatabase(Pathname root_r=Pathname(), bool doRebuild_r=false)
Prepare access to the rpm database below root_r.
Definition: RpmDb.cc:266
bool initialized() const
Definition: RpmDb.h:105
ExternalProgram * process
The connection to the rpm process.
Definition: RpmDb.h:276
SyncTrustedKeyBits
Sync mode for syncTrustedKeys.
Definition: RpmDb.h:253
@ SYNC_TO_KEYRING
export rpm trusted keys into zypp trusted keyring
Definition: RpmDb.h:254
@ SYNC_FROM_KEYRING
import zypp trusted keys into rpm database.
Definition: RpmDb.h:255
std::list< PublicKey > pubkeys() const
Return the long ids of all installed public keys.
Definition: RpmDb.cc:876
std::set< Edition > pubkeyEditions() const
Return the edition of all installed public keys.
Definition: RpmDb.cc:914
int systemStatus()
Return the exit status of the general rpm process, closing the connection if not already done.
Definition: RpmDb.cc:1486
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).
Definition: RpmDb.cc:1316
bool backupPackage(const std::string &packageName)
create tar.gz of all changed files in a Package
Definition: RpmDb.cc:1969
bool hasProvides(const std::string &tag_r) const
Return true if at least one package provides a certain tag.
Definition: RpmDb.cc:1011
void systemKill()
Forcably kill the system process.
Definition: RpmDb.cc:1509
void removePubkey(const PublicKey &pubkey_r)
Remove a public key from the rpm database.
Definition: RpmDb.cc:809
void removePackage(const std::string &name_r, RpmInstFlags flags=RPMINST_NONE)
remove rpm package
Definition: RpmDb.cc:1810
void doInstallPackage(const Pathname &filename, RpmInstFlags flags, callback::SendReport< RpmInstallReport > &report)
Definition: RpmDb.cc:1643
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 !...
Definition: RpmDb.cc:938
Pathname _dbPath
Directory that contains the rpmdb.
Definition: RpmDb.h:71
void closeDatabase()
Block further access to the rpm database and go back to uninitialized state.
Definition: RpmDb.cc:356
void setBackupPath(const Pathname &path)
set path where package backups are stored
Definition: RpmDb.cc:2096
void doRemovePackage(const std::string &name_r, RpmInstFlags flags, callback::SendReport< RpmRemoveReport > &report)
Definition: RpmDb.cc:1841
bool _packagebackups
create package backups?
Definition: RpmDb.h:325
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,...
Definition: RpmDb.cc:1310
void importZyppKeyRingTrustedKeys()
iterates through zypp keyring and import all non-existent keys into rpm keyring
Definition: RpmDb.cc:684
Pathname _root
Root directory for all operations.
Definition: RpmDb.h:66
bool hasConflicts(const std::string &tag_r) const
Return true if at least one package conflicts with a certain tag.
Definition: RpmDb.cc:1039
const Pathname & dbPath() const
Definition: RpmDb.h:97
std::vector< const char * > RpmArgVec
Definition: RpmDb.h:278
int exit_code
The exit code of the rpm process, or -1 if not yet known.
Definition: RpmDb.h:313
void syncTrustedKeys(SyncTrustedKeyBits mode_r=SYNC_BOTH)
Sync trusted keys stored in rpm database and zypp trusted keyring.
Definition: RpmDb.cc:583
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"
Definition: RpmDb.cc:1516
const Pathname & root() const
Definition: RpmDb.h:89
CheckPackageResult
checkPackage result
Definition: RpmDb.h:352
~RpmDb()
Destructor.
Definition: RpmDb.cc:240
bool hasPackage(const std::string &name_r) const
Return true if package is installed.
Definition: RpmDb.cc:1053
std::set< std::string > FileList
Definition: RpmDb.h:345
bool systemReadLine(std::string &line)
Read a line from the general rpm query.
Definition: RpmDb.cc:1434
void rebuildDatabase()
Rebuild the rpm database (rpm –rebuilddb).
Definition: RpmDb.cc:384
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 ...
Definition: RpmDb.cc:967
Just inherits Exception to separate media exceptions.
Definition: RpmException.h:38
static RpmHeader::constPtr readPackage(const Pathname &path, VERIFICATION verification=VERIFY)
Get an accessible packages data from disk.
Definition: RpmHeader.cc:210
intrusive_ptr< const RpmHeader > constPtr
Definition: RpmHeader.h:65
Subclass to retrieve database content.
Definition: librpmDb.h:336
bool findByProvides(const std::string &tag_r)
Reset to iterate all packages that provide a certain tag.
Definition: librpmDb.cc:743
bool findByName(const std::string &name_r)
Reset to iterate all packages with a certain name.
Definition: librpmDb.cc:776
bool findByFile(const std::string &file_r)
Reset to iterate all packages that own a certain file.
Definition: librpmDb.cc:732
bool findByRequiredBy(const std::string &tag_r)
Reset to iterate all packages that require a certain tag.
Definition: librpmDb.cc:754
bool findPackage(const std::string &name_r)
Find package by name.
Definition: librpmDb.cc:787
shared_ptr< RpmException > dbError() const
Return any database error.
Definition: librpmDb.cc:692
bool findByConflicts(const std::string &tag_r)
Reset to iterate all packages that conflict with a certain tag.
Definition: librpmDb.cc:765
static bool globalInit()
Initialize lib librpm (read configfiles etc.).
Definition: librpmDb.cc:111
static unsigned dbRelease(bool force_r=false)
If there are no outstanding references to the database (e.g.
Definition: librpmDb.cc:277
static void dbAccess()
Access the database at the current default location.
Definition: librpmDb.cc:244
static unsigned blockAccess()
Blocks further access to rpmdb.
Definition: librpmDb.cc:314
static Pathname suggestedDbPath(const Pathname &root_r)
Definition: librpmDb.cc:190
static void unblockAccess()
Allow access to rpmdb e.g.
Definition: librpmDb.cc:327
String related utilities and Regular expression matching.
bool ZYPP_RPM_DEBUG()
Definition: RpmDb.cc:78
Types and functions for filesystem operations.
Definition: Glob.cc:24
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...
Definition: PathInfo.cc:945
int unlink(const Pathname &path)
Like 'unlink'.
Definition: PathInfo.cc:700
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
Definition: PathInfo.cc:319
int symlink(const Pathname &oldpath, const Pathname &newpath)
Like 'symlink'.
Definition: PathInfo.cc:855
std::pair< ReceiveUpToResult, std::string > receiveUpto(FILE *file, char c, timeout_type timeout, bool failOnUnblockError)
Definition: IOTools.cc:85
@ Timeout
Definition: IOTools.h:71
@ Success
Definition: IOTools.h:70
@ Error
Definition: IOTools.h:73
@ EndOfFile
Definition: IOTools.h:72
std::ostream & copy(std::istream &from_r, std::ostream &to_r)
Copy istream to ostream.
Definition: IOStream.h:50
static double currentTime()
SolvableIdType size_type
Definition: PoolMember.h:126
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).
Definition: String.cc:330
std::string numstring(char n, int w=0)
Definition: String.h:289
bool startsWith(const C_Str &str_r, const C_Str &prefix_r)
alias for hasPrefix
Definition: String.h:1085
bool endsWith(const C_Str &str_r, const C_Str &prefix_r)
alias for hasSuffix
Definition: String.h:1092
bool regex_match(const std::string &s, smatch &matches, const regex &regex)
\relates regex \ingroup ZYPP_STR_REGEX \relates regex \ingroup ZYPP_STR_REGEX
Definition: Regex.h:70
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
Definition: String.cc:36
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
Definition: String.h:429
unsigned split(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \t", const Trim trim_r=NO_TRIM)
Split line_r into words.
Definition: String.h:531
std::string toLower(const std::string &s)
Return lowercase version of s.
Definition: String.cc:177
std::ostream & operator<<(std::ostream &str, const librpmDb::db_const_iterator &obj)
Definition: librpmDb.cc:706
static shared_ptr< KeyRingSignalReceiver > sKeyRingReceiver
Definition: RpmDb.cc:162
std::string stringPath(const Pathname &root_r, const Pathname &sub_r)
Definition: RpmDb.cc:200
unsigned diffFiles(const std::string file1, const std::string file2, std::string &out, int maxlines)
Definition: RpmDb.cc:164
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:2
Temporarily connect a ReceiveReport then restore the previous one.
Definition: Callback.h:285
Convenient building of std::string with boost::format.
Definition: String.h:253
static const UserData::ContentType contentRpmout
"rpmout/installpkg": Additional rpm output (sent immediately).
virtual void trustedKeyRemoved(const PublicKey &key)
Definition: RpmDb.cc:153
virtual void trustedKeyAdded(const PublicKey &key)
Definition: RpmDb.cc:147
static const UserData::ContentType contentRpmout
"rpmout/removepkg": Additional rpm output (sent immediately).
Detailed rpm signature check log messages A single multiline message if CHK_OK.
Definition: RpmDb.h:367
#define for_(IT, BEG, END)
Convenient for-loops using iterator.
Definition: Easy.h:28
#define nullptr
Definition: Easy.h:55
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:430
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
Definition: Exception.h:426
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:418
#define _(MSG)
Definition: Gettext.h:37
#define DBG
Definition: Logger.h:95
#define MIL
Definition: Logger.h:96
#define ERR
Definition: Logger.h:98
#define WAR
Definition: Logger.h:97
#define L_DBG(GROUP)
Definition: Logger.h:104
#define INT
Definition: Logger.h:100