Imported Upstream version 14.45.0
[platform/upstream/libzypp.git] / zypp / RepoManager.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/RepoManager.cc
10  *
11 */
12
13 #include <cstdlib>
14 #include <iostream>
15 #include <fstream>
16 #include <sstream>
17 #include <list>
18 #include <map>
19 #include <algorithm>
20
21 #include "zypp/base/InputStream.h"
22 #include "zypp/base/LogTools.h"
23 #include "zypp/base/Gettext.h"
24 #include "zypp/base/DefaultIntegral.h"
25 #include "zypp/base/Function.h"
26 #include "zypp/base/Regex.h"
27 #include "zypp/PathInfo.h"
28 #include "zypp/TmpPath.h"
29
30 #include "zypp/ServiceInfo.h"
31 #include "zypp/repo/RepoException.h"
32 #include "zypp/RepoManager.h"
33
34 #include "zypp/media/MediaManager.h"
35 #include "zypp/media/CredentialManager.h"
36 #include "zypp/MediaSetAccess.h"
37 #include "zypp/ExternalProgram.h"
38 #include "zypp/ManagedFile.h"
39
40 #include "zypp/parser/RepoFileReader.h"
41 #include "zypp/parser/ServiceFileReader.h"
42 #include "zypp/repo/ServiceRepos.h"
43 #include "zypp/repo/yum/Downloader.h"
44 #include "zypp/repo/susetags/Downloader.h"
45 #include "zypp/repo/PluginServices.h"
46
47 #include "zypp/Target.h" // for Target::targetDistribution() for repo index services
48 #include "zypp/ZYppFactory.h" // to get the Target from ZYpp instance
49 #include "zypp/HistoryLog.h" // to write history :O)
50
51 #include "zypp/ZYppCallbacks.h"
52
53 #include "sat/Pool.h"
54
55 using std::endl;
56 using std::string;
57 using namespace zypp::repo;
58
59 #define OPT_PROGRESS const ProgressData::ReceiverFnc & = ProgressData::ReceiverFnc()
60
61 ///////////////////////////////////////////////////////////////////
62 namespace zypp
63 {
64   ///////////////////////////////////////////////////////////////////
65   namespace
66   {
67     ///////////////////////////////////////////////////////////////////
68     /// \class UrlCredentialExtractor
69     /// \brief Extract credentials in \ref Url authority and store them via \ref CredentialManager.
70     ///
71     /// Lazy init CredentialManager and save collected credentials when
72     /// going out of scope.
73     ///
74     /// Methods return whether a password has been collected/extracted.
75     ///
76     /// \code
77     /// UrlCredentialExtractor( "/rootdir" ).collect( oneUrlOrUrlContainer );
78     /// \endcode
79     /// \code
80     /// {
81     ///   UrlCredentialExtractor extractCredentials;
82     ///   extractCredentials.collect( oneUrlOrUrlContainer );
83     ///   extractCredentials.extract( oneMoreUrlOrUrlContainer );
84     ///   ....
85     /// }
86     /// \endcode
87     ///
88     class UrlCredentialExtractor
89     {
90     public:
91       UrlCredentialExtractor( Pathname & root_r )
92       : _root( root_r )
93       {}
94
95       ~UrlCredentialExtractor()
96       { if ( _cmPtr ) _cmPtr->save(); }
97
98       /** Remember credentials stored in URL authority leaving the password in \a url_r. */
99       bool collect( const Url & url_r )
100       {
101         bool ret = url_r.hasCredentialsInAuthority();
102         if ( ret )
103         {
104           if ( !_cmPtr ) _cmPtr.reset( new media::CredentialManager( _root ) );
105           _cmPtr->addUserCred( url_r );
106         }
107         return ret;
108       }
109       /** \overload operating on Url container */
110       template<class TContainer>
111       bool collect( const TContainer & urls_r )
112       { bool ret = false; for ( const Url & url : urls_r ) { if ( collect( url ) && !ret ) ret = true; } return ret; }
113
114       /** Remember credentials stored in URL authority stripping the passowrd from \a url_r. */
115       bool extract( Url & url_r )
116       {
117         bool ret = collect( url_r );
118         if ( ret )
119           url_r.setPassword( std::string() );
120         return ret;
121       }
122       /** \overload operating on Url container */
123       template<class TContainer>
124       bool extract( TContainer & urls_r )
125       { bool ret = false; for ( Url & url : urls_r ) { if ( extract( url ) && !ret ) ret = true; } return ret; }
126
127     private:
128       const Pathname & _root;
129       scoped_ptr<media::CredentialManager> _cmPtr;
130     };
131   } // namespace
132   ///////////////////////////////////////////////////////////////////
133
134   ///////////////////////////////////////////////////////////////////
135   namespace
136   {
137     /** Simple media mounter to access non-downloading URLs e.g. for non-local plaindir repos.
138      * \ingroup g_RAII
139      */
140     class MediaMounter
141     {
142       public:
143         /** Ctor provides media access. */
144         MediaMounter( const Url & url_r )
145         {
146           media::MediaManager mediamanager;
147           _mid = mediamanager.open( url_r );
148           mediamanager.attach( _mid );
149         }
150
151         /** Ctor releases the media. */
152         ~MediaMounter()
153         {
154           media::MediaManager mediamanager;
155           mediamanager.release( _mid );
156           mediamanager.close( _mid );
157         }
158
159         /** Convert a path relative to the media into an absolute path.
160          *
161          * Called without argument it returns the path to the medias root directory.
162         */
163         Pathname getPathName( const Pathname & path_r = Pathname() ) const
164         {
165           media::MediaManager mediamanager;
166           return mediamanager.localPath( _mid, path_r );
167         }
168
169       private:
170         media::MediaAccessId _mid;
171     };
172     ///////////////////////////////////////////////////////////////////
173
174     /** Check if alias_r is present in repo/service container. */
175     template <class Iterator>
176     inline bool foundAliasIn( const std::string & alias_r, Iterator begin_r, Iterator end_r )
177     {
178       for_( it, begin_r, end_r )
179         if ( it->alias() == alias_r )
180           return true;
181       return false;
182     }
183     /** \overload */
184     template <class Container>
185     inline bool foundAliasIn( const std::string & alias_r, const Container & cont_r )
186     { return foundAliasIn( alias_r, cont_r.begin(), cont_r.end() ); }
187
188     /** Find alias_r in repo/service container. */
189     template <class Iterator>
190     inline Iterator findAlias( const std::string & alias_r, Iterator begin_r, Iterator end_r )
191     {
192       for_( it, begin_r, end_r )
193         if ( it->alias() == alias_r )
194           return it;
195       return end_r;
196     }
197     /** \overload */
198     template <class Container>
199     inline typename Container::iterator findAlias( const std::string & alias_r, Container & cont_r )
200     { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
201     /** \overload */
202     template <class Container>
203     inline typename Container::const_iterator findAlias( const std::string & alias_r, const Container & cont_r )
204     { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
205
206
207     /** \short Generate a related filename from a repo/service infos alias */
208     inline std::string filenameFromAlias( const std::string & alias_r, const std::string & stem_r )
209     {
210       std::string filename( alias_r );
211       // replace slashes with underscores
212       str::replaceAll( filename, "/", "_" );
213
214       filename = Pathname(filename).extend("."+stem_r).asString();
215       MIL << "generating filename for " << stem_r << " [" << alias_r << "] : '" << filename << "'" << endl;
216       return filename;
217     }
218
219     /**
220      * \short Simple callback to collect the results
221      *
222      * Classes like RepoFileReader call the callback
223      * once per each repo in a file.
224      *
225      * Passing this functor as callback, you can collect
226      * all results at the end, without dealing with async
227      * code.
228      *
229      * If targetDistro is set, all repos with non-empty RepoInfo::targetDistribution()
230      * will be skipped.
231      *
232      * \todo do this through a separate filter
233      */
234     struct RepoCollector : private base::NonCopyable
235     {
236       RepoCollector()
237       {}
238
239       RepoCollector(const std::string & targetDistro_)
240         : targetDistro(targetDistro_)
241       {}
242
243       bool collect( const RepoInfo &repo )
244       {
245         // skip repositories meant for other distros than specified
246         if (!targetDistro.empty()
247             && !repo.targetDistribution().empty()
248             && repo.targetDistribution() != targetDistro)
249         {
250           MIL
251             << "Skipping repository meant for '" << repo.targetDistribution()
252             << "' distribution (current distro is '"
253             << targetDistro << "')." << endl;
254
255           return true;
256         }
257
258         repos.push_back(repo);
259         return true;
260       }
261
262       RepoInfoList repos;
263       std::string targetDistro;
264     };
265     ////////////////////////////////////////////////////////////////////////////
266
267     /**
268      * Reads RepoInfo's from a repo file.
269      *
270      * \param file pathname of the file to read.
271      */
272     std::list<RepoInfo> repositories_in_file( const Pathname & file )
273     {
274       MIL << "repo file: " << file << endl;
275       RepoCollector collector;
276       parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
277       return std::move(collector.repos);
278     }
279
280     ////////////////////////////////////////////////////////////////////////////
281
282     /**
283      * \short List of RepoInfo's from a directory
284      *
285      * Goes trough every file ending with ".repo" in a directory and adds all
286      * RepoInfo's contained in that file.
287      *
288      * \param dir pathname of the directory to read.
289      */
290     std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
291     {
292       MIL << "directory " << dir << endl;
293       std::list<RepoInfo> repos;
294       bool nonroot( geteuid() != 0 );
295       if ( nonroot && ! PathInfo(dir).userMayRX() )
296       {
297         JobReport::warning( str::FormatNAC(_("Cannot read repo directory '%1%': Permission denied")) % dir );
298       }
299       else
300       {
301         std::list<Pathname> entries;
302         if ( filesystem::readdir( entries, dir, false ) != 0 )
303         {
304           // TranslatorExplanation '%s' is a pathname
305           ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
306         }
307
308         str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
309         for ( std::list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
310         {
311           if ( str::regex_match(it->extension(), allowedRepoExt) )
312           {
313             if ( nonroot && ! PathInfo(*it).userMayR() )
314             {
315               JobReport::warning( str::FormatNAC(_("Cannot read repo file '%1%': Permission denied")) % *it );
316             }
317             else
318             {
319               const std::list<RepoInfo> & tmp( repositories_in_file( *it ) );
320               repos.insert( repos.end(), tmp.begin(), tmp.end() );
321             }
322           }
323         }
324       }
325       return repos;
326     }
327
328     ////////////////////////////////////////////////////////////////////////////
329
330     inline void assert_alias( const RepoInfo & info )
331     {
332       if ( info.alias().empty() )
333         ZYPP_THROW( RepoNoAliasException( info ) );
334       // bnc #473834. Maybe we can match the alias against a regex to define
335       // and check for valid aliases
336       if ( info.alias()[0] == '.')
337         ZYPP_THROW(RepoInvalidAliasException(
338           info, _("Repository alias cannot start with dot.")));
339     }
340
341     inline void assert_alias( const ServiceInfo & info )
342     {
343       if ( info.alias().empty() )
344         ZYPP_THROW( ServiceNoAliasException( info ) );
345       // bnc #473834. Maybe we can match the alias against a regex to define
346       // and check for valid aliases
347       if ( info.alias()[0] == '.')
348         ZYPP_THROW(ServiceInvalidAliasException(
349           info, _("Service alias cannot start with dot.")));
350     }
351
352     ////////////////////////////////////////////////////////////////////////////
353
354     inline void assert_urls( const RepoInfo & info )
355     {
356       if ( info.baseUrlsEmpty() )
357         ZYPP_THROW( RepoNoUrlException( info ) );
358     }
359
360     inline void assert_url( const ServiceInfo & info )
361     {
362       if ( ! info.url().isValid() )
363         ZYPP_THROW( ServiceNoUrlException( info ) );
364     }
365
366     ////////////////////////////////////////////////////////////////////////////
367
368     /**
369      * \short Calculates the raw cache path for a repository, this is usually
370      * /var/cache/zypp/alias
371      */
372     inline Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
373     {
374       assert_alias(info);
375       return opt.repoRawCachePath / info.escaped_alias();
376     }
377
378     /**
379      * \short Calculates the raw product metadata path for a repository, this is
380      * inside the raw cache dir, plus an optional path where the metadata is.
381      *
382      * It should be different only for repositories that are not in the root of
383      * the media.
384      * for example /var/cache/zypp/alias/addondir
385      */
386     inline Pathname rawproductdata_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
387     {
388       assert_alias(info);
389       return opt.repoRawCachePath / info.escaped_alias() / info.path();
390     }
391
392     /**
393      * \short Calculates the packages cache path for a repository
394      */
395     inline Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
396     {
397       assert_alias(info);
398       return opt.repoPackagesCachePath / info.escaped_alias();
399     }
400
401     /**
402      * \short Calculates the solv cache path for a repository
403      */
404     inline Pathname solv_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info)
405     {
406       assert_alias(info);
407       return opt.repoSolvCachePath / info.escaped_alias();
408     }
409
410     ////////////////////////////////////////////////////////////////////////////
411
412     /** Functor collecting ServiceInfos into a ServiceSet. */
413     class ServiceCollector
414     {
415     public:
416       typedef std::set<ServiceInfo> ServiceSet;
417
418       ServiceCollector( ServiceSet & services_r )
419       : _services( services_r )
420       {}
421
422       bool operator()( const ServiceInfo & service_r ) const
423       {
424         _services.insert( service_r );
425         return true;
426       }
427
428     private:
429       ServiceSet & _services;
430     };
431     ////////////////////////////////////////////////////////////////////////////
432
433   } // namespace
434   ///////////////////////////////////////////////////////////////////
435
436   std::list<RepoInfo> readRepoFile( const Url & repo_file )
437   {
438     // no interface to download a specific file, using workaround:
439     //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
440     Url url(repo_file);
441     Pathname path(url.getPathName());
442     url.setPathName ("/");
443     MediaSetAccess access(url);
444     Pathname local = access.provideFile(path);
445
446     DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
447
448     return repositories_in_file(local);
449   }
450
451   ///////////////////////////////////////////////////////////////////
452   //
453   //    class RepoManagerOptions
454   //
455   ////////////////////////////////////////////////////////////////////
456
457   RepoManagerOptions::RepoManagerOptions( const Pathname & root_r )
458   {
459     repoCachePath         = Pathname::assertprefix( root_r, ZConfig::instance().repoCachePath() );
460     repoRawCachePath      = Pathname::assertprefix( root_r, ZConfig::instance().repoMetadataPath() );
461     repoSolvCachePath     = Pathname::assertprefix( root_r, ZConfig::instance().repoSolvfilesPath() );
462     repoPackagesCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoPackagesPath() );
463     knownReposPath        = Pathname::assertprefix( root_r, ZConfig::instance().knownReposPath() );
464     knownServicesPath     = Pathname::assertprefix( root_r, ZConfig::instance().knownServicesPath() );
465     pluginsPath           = Pathname::assertprefix( root_r, ZConfig::instance().pluginsPath() );
466     probe                 = ZConfig::instance().repo_add_probe();
467
468     rootDir = root_r;
469   }
470
471   RepoManagerOptions RepoManagerOptions::makeTestSetup( const Pathname & root_r )
472   {
473     RepoManagerOptions ret;
474     ret.repoCachePath         = root_r;
475     ret.repoRawCachePath      = root_r/"raw";
476     ret.repoSolvCachePath     = root_r/"solv";
477     ret.repoPackagesCachePath = root_r/"packages";
478     ret.knownReposPath        = root_r/"repos.d";
479     ret.knownServicesPath     = root_r/"services.d";
480     ret.pluginsPath           = root_r/"plugins";
481     ret.rootDir = root_r;
482     return ret;
483   }
484
485   std:: ostream & operator<<( std::ostream & str, const RepoManagerOptions & obj )
486   {
487 #define OUTS(X) str << "  " #X "\t" << obj.X << endl
488     str << "RepoManagerOptions (" << obj.rootDir << ") {" << endl;
489     OUTS( repoRawCachePath );
490     OUTS( repoSolvCachePath );
491     OUTS( repoPackagesCachePath );
492     OUTS( knownReposPath );
493     OUTS( knownServicesPath );
494     OUTS( pluginsPath );
495     str << "}" << endl;
496 #undef OUTS
497     return str;
498   }
499
500   ///////////////////////////////////////////////////////////////////
501   /// \class RepoManager::Impl
502   /// \brief RepoManager implementation.
503   ///
504   ///////////////////////////////////////////////////////////////////
505   struct RepoManager::Impl
506   {
507   public:
508     Impl( const RepoManagerOptions &opt )
509       : _options(opt)
510     {
511       init_knownServices();
512       init_knownRepositories();
513     }
514
515     ~Impl()
516     {
517       // trigger appdata refresh if some repos change
518       if ( _reposDirty && geteuid() == 0 && ( _options.rootDir.empty() || _options.rootDir == "/" ) )
519       {
520         try {
521           std::list<Pathname> entries;
522           filesystem::readdir( entries, _options.pluginsPath/"appdata", false );
523           if ( ! entries.empty() )
524           {
525             ExternalProgram::Arguments cmd;
526             cmd.push_back( "<" );               // discard stdin
527             cmd.push_back( ">" );               // discard stdout
528             cmd.push_back( "PROGRAM" );         // [2] - fix index below if changing!
529             for ( const auto & rinfo : repos() )
530             {
531               if ( ! rinfo.enabled() )
532                 continue;
533               cmd.push_back( "-R" );
534               cmd.push_back( rinfo.alias() );
535               cmd.push_back( "-t" );
536               cmd.push_back( rinfo.type().asString() );
537               cmd.push_back( "-p" );
538               cmd.push_back( rinfo.metadataPath().asString() );
539             }
540
541             for_( it, entries.begin(), entries.end() )
542             {
543               PathInfo pi( *it );
544               //DBG << "/tmp/xx ->" << pi << endl;
545               if ( pi.isFile() && pi.userMayRX() )
546               {
547                 // trigger plugin
548                 cmd[2] = pi.asString();         // [2] - PROGRAM
549                 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
550               }
551             }
552           }
553         }
554         catch (...) {}  // no throw in dtor
555       }
556     }
557
558   public:
559     bool repoEmpty() const              { return repos().empty(); }
560     RepoSizeType repoSize() const       { return repos().size(); }
561     RepoConstIterator repoBegin() const { return repos().begin(); }
562     RepoConstIterator repoEnd() const   { return repos().end(); }
563
564     bool hasRepo( const std::string & alias ) const
565     { return foundAliasIn( alias, repos() ); }
566
567     RepoInfo getRepo( const std::string & alias ) const
568     {
569       RepoConstIterator it( findAlias( alias, repos() ) );
570       return it == repos().end() ? RepoInfo::noRepo : *it;
571     }
572
573   public:
574     Pathname metadataPath( const RepoInfo & info ) const
575     { return rawcache_path_for_repoinfo( _options, info ); }
576
577     Pathname packagesPath( const RepoInfo & info ) const
578     { return packagescache_path_for_repoinfo( _options, info ); }
579
580     RepoStatus metadataStatus( const RepoInfo & info ) const;
581
582     RefreshCheckStatus checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy );
583
584     void refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, OPT_PROGRESS );
585
586     void cleanMetadata( const RepoInfo & info, OPT_PROGRESS );
587
588     void cleanPackages( const RepoInfo & info, OPT_PROGRESS );
589
590     void buildCache( const RepoInfo & info, CacheBuildPolicy policy, OPT_PROGRESS );
591
592     repo::RepoType probe( const Url & url, const Pathname & path = Pathname() ) const;
593     repo::RepoType probeCache( const Pathname & path_r ) const;
594
595     void cleanCacheDirGarbage( OPT_PROGRESS );
596
597     void cleanCache( const RepoInfo & info, OPT_PROGRESS );
598
599     bool isCached( const RepoInfo & info ) const
600     { return PathInfo(solv_path_for_repoinfo( _options, info ) / "solv").isExist(); }
601
602     RepoStatus cacheStatus( const RepoInfo & info ) const
603     { return RepoStatus::fromCookieFile(solv_path_for_repoinfo(_options, info) / "cookie"); }
604
605     void loadFromCache( const RepoInfo & info, OPT_PROGRESS );
606
607     void addRepository( const RepoInfo & info, OPT_PROGRESS );
608
609     void addRepositories( const Url & url, OPT_PROGRESS );
610
611     void removeRepository( const RepoInfo & info, OPT_PROGRESS );
612
613     void modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, OPT_PROGRESS );
614
615     RepoInfo getRepositoryInfo( const std::string & alias, OPT_PROGRESS );
616     RepoInfo getRepositoryInfo( const Url & url, const url::ViewOption & urlview, OPT_PROGRESS );
617
618   public:
619     bool serviceEmpty() const                   { return _services.empty(); }
620     ServiceSizeType serviceSize() const         { return _services.size(); }
621     ServiceConstIterator serviceBegin() const   { return _services.begin(); }
622     ServiceConstIterator serviceEnd() const     { return _services.end(); }
623
624     bool hasService( const std::string & alias ) const
625     { return foundAliasIn( alias, _services ); }
626
627     ServiceInfo getService( const std::string & alias ) const
628     {
629       ServiceConstIterator it( findAlias( alias, _services ) );
630       return it == _services.end() ? ServiceInfo::noService : *it;
631     }
632
633   public:
634     void addService( const ServiceInfo & service );
635     void addService( const std::string & alias, const Url & url )
636     { addService( ServiceInfo( alias, url ) ); }
637
638     void removeService( const std::string & alias );
639     void removeService( const ServiceInfo & service )
640     { removeService( service.alias() ); }
641
642     void refreshServices( const RefreshServiceOptions & options_r );
643
644     void refreshService( const std::string & alias, const RefreshServiceOptions & options_r );
645     void refreshService( const ServiceInfo & service, const RefreshServiceOptions & options_r )
646     {  refreshService( service.alias(), options_r ); }
647
648     void modifyService( const std::string & oldAlias, const ServiceInfo & newService );
649
650     repo::ServiceType probeService( const Url & url ) const;
651
652   private:
653     void saveService( ServiceInfo & service ) const;
654
655     Pathname generateNonExistingName( const Pathname & dir, const std::string & basefilename ) const;
656
657     std::string generateFilename( const RepoInfo & info ) const
658     { return filenameFromAlias( info.alias(), "repo" ); }
659
660     std::string generateFilename( const ServiceInfo & info ) const
661     { return filenameFromAlias( info.alias(), "service" ); }
662
663     void setCacheStatus( const RepoInfo & info, const RepoStatus & status )
664     {
665       Pathname base = solv_path_for_repoinfo( _options, info );
666       filesystem::assert_dir(base);
667       status.saveToCookieFile( base / "cookie" );
668     }
669
670     void touchIndexFile( const RepoInfo & info );
671
672     template<typename OutputIterator>
673     void getRepositoriesInService( const std::string & alias, OutputIterator out ) const
674     {
675       MatchServiceAlias filter( alias );
676       std::copy( boost::make_filter_iterator( filter, repos().begin(), repos().end() ),
677                  boost::make_filter_iterator( filter, repos().end(), repos().end() ),
678                  out);
679     }
680
681   private:
682     void init_knownServices();
683     void init_knownRepositories();
684
685     const RepoSet & repos() const { return _reposX; }
686     RepoSet & reposManip()        { if ( ! _reposDirty ) _reposDirty = true; return _reposX; }
687
688   private:
689     RepoManagerOptions  _options;
690     RepoSet             _reposX;
691     ServiceSet          _services;
692
693     DefaultIntegral<bool,false> _reposDirty;
694
695   private:
696     friend Impl * rwcowClone<Impl>( const Impl * rhs );
697     /** clone for RWCOW_pointer */
698     Impl * clone() const
699     { return new Impl( *this ); }
700   };
701   ///////////////////////////////////////////////////////////////////
702
703   /** \relates RepoManager::Impl Stream output */
704   inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
705   { return str << "RepoManager::Impl"; }
706
707   ///////////////////////////////////////////////////////////////////
708
709   void RepoManager::Impl::saveService( ServiceInfo & service ) const
710   {
711     filesystem::assert_dir( _options.knownServicesPath );
712     Pathname servfile = generateNonExistingName( _options.knownServicesPath,
713                                                  generateFilename( service ) );
714     service.setFilepath( servfile );
715
716     MIL << "saving service in " << servfile << endl;
717
718     std::ofstream file( servfile.c_str() );
719     if ( !file )
720     {
721       // TranslatorExplanation '%s' is a filename
722       ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), servfile.c_str() )));
723     }
724     service.dumpAsIniOn( file );
725     MIL << "done" << endl;
726   }
727
728   /**
729    * Generate a non existing filename in a directory, using a base
730    * name. For example if a directory contains 3 files
731    *
732    * |-- bar
733    * |-- foo
734    * `-- moo
735    *
736    * If you try to generate a unique filename for this directory,
737    * based on "ruu" you will get "ruu", but if you use the base
738    * "foo" you will get "foo_1"
739    *
740    * \param dir Directory where the file needs to be unique
741    * \param basefilename string to base the filename on.
742    */
743   Pathname RepoManager::Impl::generateNonExistingName( const Pathname & dir,
744                                                        const std::string & basefilename ) const
745   {
746     std::string final_filename = basefilename;
747     int counter = 1;
748     while ( PathInfo(dir + final_filename).isExist() )
749     {
750       final_filename = basefilename + "_" + str::numstring(counter);
751       ++counter;
752     }
753     return dir + Pathname(final_filename);
754   }
755
756   ////////////////////////////////////////////////////////////////////////////
757
758   void RepoManager::Impl::init_knownServices()
759   {
760     Pathname dir = _options.knownServicesPath;
761     std::list<Pathname> entries;
762     if (PathInfo(dir).isExist())
763     {
764       if ( filesystem::readdir( entries, dir, false ) != 0 )
765       {
766         // TranslatorExplanation '%s' is a pathname
767         ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
768       }
769
770       //str::regex allowedServiceExt("^\\.service(_[0-9]+)?$");
771       for_(it, entries.begin(), entries.end() )
772       {
773         parser::ServiceFileReader(*it, ServiceCollector(_services));
774       }
775     }
776
777     repo::PluginServices(_options.pluginsPath/"services", ServiceCollector(_services));
778   }
779
780   ///////////////////////////////////////////////////////////////////
781   namespace {
782     /** Delete \a cachePath_r subdirs not matching known aliases in \a repoEscAliases_r (must be sorted!)
783      * \note bnc#891515: Auto-cleanup only zypp.conf default locations. Otherwise
784      * we'd need some magic file to identify zypp cache directories. Without this
785      * we may easily remove user data (zypper --pkg-cache-dir . download ...)
786      */
787     inline void cleanupNonRepoMetadtaFolders( const Pathname & cachePath_r,
788                                               const Pathname & defaultCachePath_r,
789                                               const std::list<std::string> & repoEscAliases_r )
790     {
791       if ( cachePath_r != defaultCachePath_r )
792         return;
793
794       std::list<std::string> entries;
795       if ( filesystem::readdir( entries, cachePath_r, false ) == 0 )
796       {
797         entries.sort();
798         std::set<std::string> oldfiles;
799         set_difference( entries.begin(), entries.end(), repoEscAliases_r.begin(), repoEscAliases_r.end(),
800                         std::inserter( oldfiles, oldfiles.end() ) );
801         for ( const std::string & old : oldfiles )
802         {
803           if ( old == Repository::systemRepoAlias() )   // don't remove the @System solv file
804             continue;
805           filesystem::recursive_rmdir( cachePath_r / old );
806         }
807       }
808     }
809   } // namespace
810   ///////////////////////////////////////////////////////////////////
811   void RepoManager::Impl::init_knownRepositories()
812   {
813     MIL << "start construct known repos" << endl;
814
815     if ( PathInfo(_options.knownReposPath).isExist() )
816     {
817       std::list<std::string> repoEscAliases;
818       std::list<RepoInfo> orphanedRepos;
819       for ( RepoInfo & repoInfo : repositories_in_dir(_options.knownReposPath) )
820       {
821         // set the metadata path for the repo
822         repoInfo.setMetadataPath( rawcache_path_for_repoinfo(_options, repoInfo) );
823         // set the downloaded packages path for the repo
824         repoInfo.setPackagesPath( packagescache_path_for_repoinfo(_options, repoInfo) );
825         // remember it
826         _reposX.insert( repoInfo );     // direct access via _reposX in ctor! no reposManip.
827
828         // detect orphaned repos belonging to a deleted service
829         const std::string & serviceAlias( repoInfo.service() );
830         if ( ! ( serviceAlias.empty() || hasService( serviceAlias ) ) )
831         {
832           WAR << "Schedule orphaned service repo for deletion: " << repoInfo << endl;
833           orphanedRepos.push_back( repoInfo );
834           continue;     // don't remember it in repoEscAliases
835         }
836
837         repoEscAliases.push_back(repoInfo.escaped_alias());
838       }
839
840       // Cleanup orphanded service repos:
841       if ( ! orphanedRepos.empty() )
842       {
843         for ( auto & repoInfo : orphanedRepos )
844         {
845           MIL << "Delete orphaned service repo " << repoInfo.alias() << endl;
846           // translators: Cleanup a repository previously owned by a meanwhile unknown (deleted) service.
847           //   %1% = service name
848           //   %2% = repository name
849           JobReport::warning( str::FormatNAC(_("Unknown service '%1%': Removing orphaned service repository '%2%'"))
850                               % repoInfo.service()
851                               % repoInfo.alias() );
852           try {
853             removeRepository( repoInfo );
854           }
855           catch ( const Exception & caugth )
856           {
857             JobReport::error( caugth.asUserHistory() );
858           }
859         }
860       }
861
862       // delete metadata folders without corresponding repo (e.g. old tmp directories)
863       //
864       // bnc#891515: Auto-cleanup only zypp.conf default locations. Otherwise
865       // we'd need somemagic file to identify zypp cache directories. Without this
866       // we may easily remove user data (zypper --pkg-cache-dir . download ...)
867       repoEscAliases.sort();
868       RepoManagerOptions defaultCache( _options.rootDir );
869       cleanupNonRepoMetadtaFolders( _options.repoRawCachePath,          defaultCache.repoRawCachePath,          repoEscAliases );
870       cleanupNonRepoMetadtaFolders( _options.repoSolvCachePath,         defaultCache.repoSolvCachePath,         repoEscAliases );
871       cleanupNonRepoMetadtaFolders( _options.repoPackagesCachePath,     defaultCache.repoPackagesCachePath,     repoEscAliases );
872     }
873     MIL << "end construct known repos" << endl;
874   }
875
876   ///////////////////////////////////////////////////////////////////
877
878   RepoStatus RepoManager::Impl::metadataStatus( const RepoInfo & info ) const
879   {
880     Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
881     Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
882
883     RepoType repokind = info.type();
884     // If unknown, probe the local metadata
885     if ( repokind == RepoType::NONE )
886       repokind = probeCache( productdatapath );
887
888     RepoStatus status;
889     switch ( repokind.toEnum() )
890     {
891       case RepoType::RPMMD_e :
892         status = RepoStatus( productdatapath/"repodata/repomd.xml");
893         break;
894
895       case RepoType::YAST2_e :
896         status = RepoStatus( productdatapath/"content" ) && RepoStatus( mediarootpath/"media.1/media" );
897         break;
898
899       case RepoType::RPMPLAINDIR_e :
900         status = RepoStatus::fromCookieFile( productdatapath/"cookie" );
901         break;
902
903       case RepoType::NONE_e :
904         // Return default RepoStatus in case of RepoType::NONE
905         // indicating it should be created?
906         // ZYPP_THROW(RepoUnknownTypeException());
907         break;
908     }
909     return status;
910   }
911
912
913   void RepoManager::Impl::touchIndexFile( const RepoInfo & info )
914   {
915     Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
916
917     RepoType repokind = info.type();
918     if ( repokind.toEnum() == RepoType::NONE_e )
919       // unknown, probe the local metadata
920       repokind = probeCache( productdatapath );
921     // if still unknown, just return
922     if (repokind == RepoType::NONE_e)
923       return;
924
925     Pathname p;
926     switch ( repokind.toEnum() )
927     {
928       case RepoType::RPMMD_e :
929         p = Pathname(productdatapath + "/repodata/repomd.xml");
930         break;
931
932       case RepoType::YAST2_e :
933         p = Pathname(productdatapath + "/content");
934         break;
935
936       case RepoType::RPMPLAINDIR_e :
937         p = Pathname(productdatapath + "/cookie");
938         break;
939
940       case RepoType::NONE_e :
941       default:
942         break;
943     }
944
945     // touch the file, ignore error (they are logged anyway)
946     filesystem::touch(p);
947   }
948
949
950   RepoManager::RefreshCheckStatus RepoManager::Impl::checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy )
951   {
952     assert_alias(info);
953     try
954     {
955       MIL << "Going to try to check whether refresh is needed for " << url << endl;
956
957       // first check old (cached) metadata
958       Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
959       filesystem::assert_dir( mediarootpath );
960       RepoStatus oldstatus = metadataStatus( info );
961
962       if ( oldstatus.empty() )
963       {
964         MIL << "No cached metadata, going to refresh" << endl;
965         return REFRESH_NEEDED;
966       }
967
968       {
969         if ( url.schemeIsVolatile() )
970         {
971           MIL << "never refresh CD/DVD" << endl;
972           return REPO_UP_TO_DATE;
973         }
974         if ( url.schemeIsLocal() )
975         {
976           policy = RefreshIfNeededIgnoreDelay;
977         }
978       }
979
980       // now we've got the old (cached) status, we can decide repo.refresh.delay
981       if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
982       {
983         // difference in seconds
984         double diff = difftime(
985           (Date::ValueType)Date::now(),
986           (Date::ValueType)oldstatus.timestamp()) / 60;
987
988         DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
989         DBG << "current time: " << (Date::ValueType)Date::now() << endl;
990         DBG << "last refresh = " << diff << " minutes ago" << endl;
991
992         if ( diff < ZConfig::instance().repo_refresh_delay() )
993         {
994           if ( diff < 0 )
995           {
996             WAR << "Repository '" << info.alias() << "' was refreshed in the future!" << endl;
997           }
998           else
999           {
1000             MIL << "Repository '" << info.alias()
1001                 << "' has been refreshed less than repo.refresh.delay ("
1002                 << ZConfig::instance().repo_refresh_delay()
1003                 << ") minutes ago. Advising to skip refresh" << endl;
1004             return REPO_CHECK_DELAYED;
1005           }
1006         }
1007       }
1008
1009       repo::RepoType repokind = info.type();
1010       // if unknown: probe it
1011       if ( repokind == RepoType::NONE )
1012         repokind = probe( url, info.path() );
1013
1014       // retrieve newstatus
1015       RepoStatus newstatus;
1016       switch ( repokind.toEnum() )
1017       {
1018         case RepoType::RPMMD_e:
1019         {
1020           MediaSetAccess media( url );
1021           newstatus = yum::Downloader( info, mediarootpath ).status( media );
1022         }
1023         break;
1024
1025         case RepoType::YAST2_e:
1026         {
1027           MediaSetAccess media( url );
1028           newstatus = susetags::Downloader( info, mediarootpath ).status( media );
1029         }
1030         break;
1031
1032         case RepoType::RPMPLAINDIR_e:
1033           newstatus = RepoStatus( MediaMounter(url).getPathName(info.path()) ); // dir status
1034           break;
1035
1036         default:
1037         case RepoType::NONE_e:
1038           ZYPP_THROW( RepoUnknownTypeException( info ) );
1039           break;
1040       }
1041
1042       // check status
1043       bool refresh = false;
1044       if ( oldstatus == newstatus )
1045       {
1046         MIL << "repo has not changed" << endl;
1047         if ( policy == RefreshForced )
1048         {
1049           MIL << "refresh set to forced" << endl;
1050           refresh = true;
1051         }
1052       }
1053       else
1054       {
1055         MIL << "repo has changed, going to refresh" << endl;
1056         refresh = true;
1057       }
1058
1059       if (!refresh)
1060         touchIndexFile(info);
1061
1062       return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
1063
1064     }
1065     catch ( const Exception &e )
1066     {
1067       ZYPP_CAUGHT(e);
1068       ERR << "refresh check failed for " << url << endl;
1069       ZYPP_RETHROW(e);
1070     }
1071
1072     return REFRESH_NEEDED; // default
1073   }
1074
1075
1076   void RepoManager::Impl::refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progress )
1077   {
1078     assert_alias(info);
1079     assert_urls(info);
1080
1081     // we will throw this later if no URL checks out fine
1082     RepoException rexception( info, _PL("Valid metadata not found at specified URL",
1083                                         "Valid metadata not found at specified URLs",
1084                                         info.baseUrlsSize() ) );
1085
1086     // Suppress (interactive) media::MediaChangeReport if we in have multiple basurls (>1)
1087     media::ScopedDisableMediaChangeReport guard( info.baseUrlsSize() > 1 );
1088
1089     // try urls one by one
1090     for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
1091     {
1092       try
1093       {
1094         Url url(*it);
1095
1096         // check whether to refresh metadata
1097         // if the check fails for this url, it throws, so another url will be checked
1098         if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
1099           return;
1100
1101         MIL << "Going to refresh metadata from " << url << endl;
1102
1103         repo::RepoType repokind = info.type();
1104
1105         // if the type is unknown, try probing.
1106         if ( repokind == RepoType::NONE )
1107         {
1108           // unknown, probe it
1109           repokind = probe( *it, info.path() );
1110
1111           if (repokind.toEnum() != RepoType::NONE_e)
1112           {
1113             // Adjust the probed type in RepoInfo
1114             info.setProbedType( repokind ); // lazy init!
1115             //save probed type only for repos in system
1116             for_( it, repoBegin(), repoEnd() )
1117             {
1118               if ( info.alias() == (*it).alias() )
1119               {
1120                 RepoInfo modifiedrepo = info;
1121                 modifiedrepo.setType( repokind );
1122                 modifyRepository( info.alias(), modifiedrepo );
1123                 break;
1124               }
1125             }
1126           }
1127         }
1128
1129         Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1130         if( filesystem::assert_dir(mediarootpath) )
1131         {
1132           Exception ex(str::form( _("Can't create %s"), mediarootpath.c_str()) );
1133           ZYPP_THROW(ex);
1134         }
1135
1136         // create temp dir as sibling of mediarootpath
1137         filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
1138         if( tmpdir.path().empty() )
1139         {
1140           Exception ex(_("Can't create metadata cache directory."));
1141           ZYPP_THROW(ex);
1142         }
1143
1144         if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
1145              ( repokind.toEnum() == RepoType::YAST2_e ) )
1146         {
1147           MediaSetAccess media(url);
1148           shared_ptr<repo::Downloader> downloader_ptr;
1149
1150           MIL << "Creating downloader for [ " << info.alias() << " ]" << endl;
1151
1152           if ( repokind.toEnum() == RepoType::RPMMD_e )
1153             downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
1154           else
1155             downloader_ptr.reset( new susetags::Downloader(info, mediarootpath) );
1156
1157           /**
1158            * Given a downloader, sets the other repos raw metadata
1159            * path as cache paths for the fetcher, so if another
1160            * repo has the same file, it will not download it
1161            * but copy it from the other repository
1162            */
1163           for_( it, repoBegin(), repoEnd() )
1164           {
1165             Pathname cachepath(rawcache_path_for_repoinfo( _options, *it ));
1166             if ( PathInfo(cachepath).isExist() )
1167               downloader_ptr->addCachePath(cachepath);
1168           }
1169
1170           downloader_ptr->download( media, tmpdir.path() );
1171         }
1172         else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
1173         {
1174           MediaMounter media( url );
1175           RepoStatus newstatus = RepoStatus( media.getPathName( info.path() ) );        // dir status
1176
1177           Pathname productpath( tmpdir.path() / info.path() );
1178           filesystem::assert_dir( productpath );
1179           newstatus.saveToCookieFile( productpath/"cookie" );
1180         }
1181         else
1182         {
1183           ZYPP_THROW(RepoUnknownTypeException( info ));
1184         }
1185
1186         // ok we have the metadata, now exchange
1187         // the contents
1188         filesystem::exchange( tmpdir.path(), mediarootpath );
1189         reposManip();   // remember to trigger appdata refresh
1190
1191         // we are done.
1192         return;
1193       }
1194       catch ( const Exception &e )
1195       {
1196         ZYPP_CAUGHT(e);
1197         ERR << "Trying another url..." << endl;
1198
1199         // remember the exception caught for the *first URL*
1200         // if all other URLs fail, the rexception will be thrown with the
1201         // cause of the problem of the first URL remembered
1202         if (it == info.baseUrlsBegin())
1203           rexception.remember(e);
1204         else
1205           rexception.addHistory(  e.asUserString() );
1206
1207       }
1208     } // for every url
1209     ERR << "No more urls..." << endl;
1210     ZYPP_THROW(rexception);
1211   }
1212
1213   ////////////////////////////////////////////////////////////////////////////
1214
1215   void RepoManager::Impl::cleanMetadata( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1216   {
1217     ProgressData progress(100);
1218     progress.sendTo(progressfnc);
1219
1220     filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_options, info));
1221     progress.toMax();
1222   }
1223
1224
1225   void RepoManager::Impl::cleanPackages( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1226   {
1227     ProgressData progress(100);
1228     progress.sendTo(progressfnc);
1229
1230     filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_options, info));
1231     progress.toMax();
1232   }
1233
1234
1235   void RepoManager::Impl::buildCache( const RepoInfo & info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
1236   {
1237     assert_alias(info);
1238     Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1239     Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
1240
1241     if( filesystem::assert_dir(_options.repoCachePath) )
1242     {
1243       Exception ex(str::form( _("Can't create %s"), _options.repoCachePath.c_str()) );
1244       ZYPP_THROW(ex);
1245     }
1246     RepoStatus raw_metadata_status = metadataStatus(info);
1247     if ( raw_metadata_status.empty() )
1248     {
1249        /* if there is no cache at this point, we refresh the raw
1250           in case this is the first time - if it's !autorefresh,
1251           we may still refresh */
1252       refreshMetadata(info, RefreshIfNeeded, progressrcv );
1253       raw_metadata_status = metadataStatus(info);
1254     }
1255
1256     bool needs_cleaning = false;
1257     if ( isCached( info ) )
1258     {
1259       MIL << info.alias() << " is already cached." << endl;
1260       RepoStatus cache_status = cacheStatus(info);
1261
1262       if ( cache_status == raw_metadata_status )
1263       {
1264         MIL << info.alias() << " cache is up to date with metadata." << endl;
1265         if ( policy == BuildIfNeeded ) {
1266           return;
1267         }
1268         else {
1269           MIL << info.alias() << " cache rebuild is forced" << endl;
1270         }
1271       }
1272
1273       needs_cleaning = true;
1274     }
1275
1276     ProgressData progress(100);
1277     callback::SendReport<ProgressReport> report;
1278     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1279     progress.name(str::form(_("Building repository '%s' cache"), info.label().c_str()));
1280     progress.toMin();
1281
1282     if (needs_cleaning)
1283     {
1284       cleanCache(info);
1285     }
1286
1287     MIL << info.alias() << " building cache..." << info.type() << endl;
1288
1289     Pathname base = solv_path_for_repoinfo( _options, info);
1290
1291     if( filesystem::assert_dir(base) )
1292     {
1293       Exception ex(str::form( _("Can't create %s"), base.c_str()) );
1294       ZYPP_THROW(ex);
1295     }
1296
1297     if( ! PathInfo(base).userMayW() )
1298     {
1299       Exception ex(str::form( _("Can't create cache at %s - no writing permissions."), base.c_str()) );
1300       ZYPP_THROW(ex);
1301     }
1302     Pathname solvfile = base / "solv";
1303
1304     // do we have type?
1305     repo::RepoType repokind = info.type();
1306
1307     // if the type is unknown, try probing.
1308     switch ( repokind.toEnum() )
1309     {
1310       case RepoType::NONE_e:
1311         // unknown, probe the local metadata
1312         repokind = probeCache( productdatapath );
1313       break;
1314       default:
1315       break;
1316     }
1317
1318     MIL << "repo type is " << repokind << endl;
1319
1320     switch ( repokind.toEnum() )
1321     {
1322       case RepoType::RPMMD_e :
1323       case RepoType::YAST2_e :
1324       case RepoType::RPMPLAINDIR_e :
1325       {
1326         // Take care we unlink the solvfile on exception
1327         ManagedFile guard( solvfile, filesystem::unlink );
1328         scoped_ptr<MediaMounter> forPlainDirs;
1329
1330         ExternalProgram::Arguments cmd;
1331         cmd.push_back( "repo2solv.sh" );
1332         // repo2solv expects -o as 1st arg!
1333         cmd.push_back( "-o" );
1334         cmd.push_back( solvfile.asString() );
1335         cmd.push_back( "-X" );  // autogenerate pattern from pattern-package
1336
1337         if ( repokind == RepoType::RPMPLAINDIR )
1338         {
1339           forPlainDirs.reset( new MediaMounter( *info.baseUrlsBegin() ) );
1340           // recusive for plaindir as 2nd arg!
1341           cmd.push_back( "-R" );
1342           // FIXME this does only work form dir: URLs
1343           cmd.push_back( forPlainDirs->getPathName( info.path() ).c_str() );
1344         }
1345         else
1346           cmd.push_back( productdatapath.asString() );
1347
1348         ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
1349         std::string errdetail;
1350
1351         for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1352           WAR << "  " << output;
1353           if ( errdetail.empty() ) {
1354             errdetail = prog.command();
1355             errdetail += '\n';
1356           }
1357           errdetail += output;
1358         }
1359
1360         int ret = prog.close();
1361         if ( ret != 0 )
1362         {
1363           RepoException ex(str::form( _("Failed to cache repo (%d)."), ret ));
1364           ex.remember( errdetail );
1365           ZYPP_THROW(ex);
1366         }
1367
1368         // We keep it.
1369         guard.resetDispose();
1370       }
1371       break;
1372       default:
1373         ZYPP_THROW(RepoUnknownTypeException( info, _("Unhandled repository type") ));
1374       break;
1375     }
1376     // update timestamp and checksum
1377     setCacheStatus(info, raw_metadata_status);
1378     MIL << "Commit cache.." << endl;
1379     progress.toMax();
1380   }
1381
1382   ////////////////////////////////////////////////////////////////////////////
1383
1384
1385   /** Probe the metadata type of a repository located at \c url.
1386    * Urls here may be rewritten by \ref MediaSetAccess to reflect the correct media number.
1387    *
1388    * \note Metadata in local cache directories must be probed using \ref probeCache as
1389    * a cache path must not be rewritten (bnc#946129)
1390    */
1391   repo::RepoType RepoManager::Impl::probe( const Url & url, const Pathname & path  ) const
1392   {
1393     MIL << "going to probe the repo type at " << url << " (" << path << ")" << endl;
1394
1395     if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName()/path ).isDir() )
1396     {
1397       // Handle non existing local directory in advance, as
1398       // MediaSetAccess does not support it.
1399       MIL << "Probed type NONE (not exists) at " << url << " (" << path << ")" << endl;
1400       return repo::RepoType::NONE;
1401     }
1402
1403     // prepare exception to be thrown if the type could not be determined
1404     // due to a media exception. We can't throw right away, because of some
1405     // problems with proxy servers returning an incorrect error
1406     // on ftp file-not-found(bnc #335906). Instead we'll check another types
1407     // before throwing.
1408
1409     // TranslatorExplanation '%s' is an URL
1410     RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
1411     bool gotMediaException = false;
1412     try
1413     {
1414       MediaSetAccess access(url);
1415       try
1416       {
1417         if ( access.doesFileExist(path/"/repodata/repomd.xml") )
1418         {
1419           MIL << "Probed type RPMMD at " << url << " (" << path << ")" << endl;
1420           return repo::RepoType::RPMMD;
1421         }
1422       }
1423       catch ( const media::MediaException &e )
1424       {
1425         ZYPP_CAUGHT(e);
1426         DBG << "problem checking for repodata/repomd.xml file" << endl;
1427         enew.remember(e);
1428         gotMediaException = true;
1429       }
1430
1431       try
1432       {
1433         if ( access.doesFileExist(path/"/content") )
1434         {
1435           MIL << "Probed type YAST2 at " << url << " (" << path << ")" << endl;
1436           return repo::RepoType::YAST2;
1437         }
1438       }
1439       catch ( const media::MediaException &e )
1440       {
1441         ZYPP_CAUGHT(e);
1442         DBG << "problem checking for content file" << endl;
1443         enew.remember(e);
1444         gotMediaException = true;
1445       }
1446
1447       // if it is a non-downloading URL denoting a directory
1448       if ( ! url.schemeIsDownloading() )
1449       {
1450         MediaMounter media( url );
1451         if ( PathInfo(media.getPathName()/path).isDir() )
1452         {
1453           // allow empty dirs for now
1454           MIL << "Probed type RPMPLAINDIR at " << url << " (" << path << ")" << endl;
1455           return repo::RepoType::RPMPLAINDIR;
1456         }
1457       }
1458     }
1459     catch ( const Exception &e )
1460     {
1461       ZYPP_CAUGHT(e);
1462       // TranslatorExplanation '%s' is an URL
1463       Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
1464       enew.remember(e);
1465       ZYPP_THROW(enew);
1466     }
1467
1468     if (gotMediaException)
1469       ZYPP_THROW(enew);
1470
1471     MIL << "Probed type NONE at " << url << " (" << path << ")" << endl;
1472     return repo::RepoType::NONE;
1473   }
1474
1475   /** Probe Metadata in a local cache directory
1476    *
1477    * \note Metadata in local cache directories must not be probed using \ref probe as
1478    * a cache path must not be rewritten (bnc#946129)
1479    */
1480   repo::RepoType RepoManager::Impl::probeCache( const Pathname & path_r ) const
1481   {
1482     MIL << "going to probe the cached repo at " << path_r << endl;
1483
1484     repo::RepoType ret = repo::RepoType::NONE;
1485
1486     if ( PathInfo(path_r/"/repodata/repomd.xml").isFile() )
1487     { ret = repo::RepoType::RPMMD; }
1488     else if ( PathInfo(path_r/"/content").isFile() )
1489     { ret = repo::RepoType::YAST2; }
1490     else if ( PathInfo(path_r).isDir() )
1491     { ret = repo::RepoType::RPMPLAINDIR; }
1492
1493     MIL << "Probed cached type " << ret << " at " << path_r << endl;
1494     return ret;
1495   }
1496
1497   ////////////////////////////////////////////////////////////////////////////
1498
1499   void RepoManager::Impl::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
1500   {
1501     MIL << "Going to clean up garbage in cache dirs" << endl;
1502
1503     ProgressData progress(300);
1504     progress.sendTo(progressrcv);
1505     progress.toMin();
1506
1507     std::list<Pathname> cachedirs;
1508     cachedirs.push_back(_options.repoRawCachePath);
1509     cachedirs.push_back(_options.repoPackagesCachePath);
1510     cachedirs.push_back(_options.repoSolvCachePath);
1511
1512     for_( dir, cachedirs.begin(), cachedirs.end() )
1513     {
1514       if ( PathInfo(*dir).isExist() )
1515       {
1516         std::list<Pathname> entries;
1517         if ( filesystem::readdir( entries, *dir, false ) != 0 )
1518           // TranslatorExplanation '%s' is a pathname
1519           ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir->c_str())));
1520
1521         unsigned sdircount   = entries.size();
1522         unsigned sdircurrent = 1;
1523         for_( subdir, entries.begin(), entries.end() )
1524         {
1525           // if it does not belong known repo, make it disappear
1526           bool found = false;
1527           for_( r, repoBegin(), repoEnd() )
1528             if ( subdir->basename() == r->escaped_alias() )
1529             { found = true; break; }
1530
1531           if ( ! found && ( Date::now()-PathInfo(*subdir).mtime() > Date::day ) )
1532             filesystem::recursive_rmdir( *subdir );
1533
1534           progress.set( progress.val() + sdircurrent * 100 / sdircount );
1535           ++sdircurrent;
1536         }
1537       }
1538       else
1539         progress.set( progress.val() + 100 );
1540     }
1541     progress.toMax();
1542   }
1543
1544   ////////////////////////////////////////////////////////////////////////////
1545
1546   void RepoManager::Impl::cleanCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1547   {
1548     ProgressData progress(100);
1549     progress.sendTo(progressrcv);
1550     progress.toMin();
1551
1552     MIL << "Removing raw metadata cache for " << info.alias() << endl;
1553     filesystem::recursive_rmdir(solv_path_for_repoinfo(_options, info));
1554
1555     progress.toMax();
1556   }
1557
1558   ////////////////////////////////////////////////////////////////////////////
1559
1560   void RepoManager::Impl::loadFromCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1561   {
1562     assert_alias(info);
1563     Pathname solvfile = solv_path_for_repoinfo(_options, info) / "solv";
1564
1565     if ( ! PathInfo(solvfile).isExist() )
1566       ZYPP_THROW(RepoNotCachedException(info));
1567
1568     sat::Pool::instance().reposErase( info.alias() );
1569     try
1570     {
1571       Repository repo = sat::Pool::instance().addRepoSolv( solvfile, info );
1572       // test toolversion in order to rebuild solv file in case
1573       // it was written by an old libsolv-tool parser.
1574       //
1575       // Known version strings used:
1576       //  - <no string>
1577       //  - "1.0"
1578       //
1579       sat::LookupRepoAttr toolversion( sat::SolvAttr::repositoryToolVersion, repo );
1580       if ( toolversion.begin().asString().empty() )
1581       {
1582         repo.eraseFromPool();
1583         ZYPP_THROW(Exception("Solv-file was created by old parser."));
1584       }
1585       // else: up-to-date (or even newer).
1586     }
1587     catch ( const Exception & exp )
1588     {
1589       ZYPP_CAUGHT( exp );
1590       MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1591       cleanCache( info, progressrcv );
1592       buildCache( info, BuildIfNeeded, progressrcv );
1593
1594       sat::Pool::instance().addRepoSolv( solvfile, info );
1595     }
1596   }
1597
1598   ////////////////////////////////////////////////////////////////////////////
1599
1600   void RepoManager::Impl::addRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1601   {
1602     assert_alias(info);
1603
1604     ProgressData progress(100);
1605     callback::SendReport<ProgressReport> report;
1606     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1607     progress.name(str::form(_("Adding repository '%s'"), info.label().c_str()));
1608     progress.toMin();
1609
1610     MIL << "Try adding repo " << info << endl;
1611
1612     RepoInfo tosave = info;
1613     if ( repos().find(tosave) != repos().end() )
1614       ZYPP_THROW(RepoAlreadyExistsException(info));
1615
1616     // check the first url for now
1617     if ( _options.probe )
1618     {
1619       DBG << "unknown repository type, probing" << endl;
1620
1621       RepoType probedtype;
1622       probedtype = probe( *tosave.baseUrlsBegin(), info.path() );
1623       if ( tosave.baseUrlsSize() > 0 )
1624       {
1625         if ( probedtype == RepoType::NONE )
1626           ZYPP_THROW(RepoUnknownTypeException(info));
1627         else
1628           tosave.setType(probedtype);
1629       }
1630     }
1631
1632     progress.set(50);
1633
1634     // assert the directory exists
1635     filesystem::assert_dir(_options.knownReposPath);
1636
1637     Pathname repofile = generateNonExistingName(
1638         _options.knownReposPath, generateFilename(tosave));
1639     // now we have a filename that does not exists
1640     MIL << "Saving repo in " << repofile << endl;
1641
1642     std::ofstream file(repofile.c_str());
1643     if (!file)
1644     {
1645       // TranslatorExplanation '%s' is a filename
1646       ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1647     }
1648
1649     tosave.dumpAsIniOn(file);
1650     tosave.setFilepath(repofile);
1651     tosave.setMetadataPath( metadataPath( tosave ) );
1652     tosave.setPackagesPath( packagesPath( tosave ) );
1653     {
1654       // We chould fix the API as we must injet those paths
1655       // into the repoinfo in order to keep it usable.
1656       RepoInfo & oinfo( const_cast<RepoInfo &>(info) );
1657       oinfo.setMetadataPath( metadataPath( tosave ) );
1658       oinfo.setPackagesPath( packagesPath( tosave ) );
1659     }
1660     reposManip().insert(tosave);
1661
1662     progress.set(90);
1663
1664     // check for credentials in Urls
1665     UrlCredentialExtractor( _options.rootDir ).collect( tosave.baseUrls() );
1666
1667     HistoryLog(_options.rootDir).addRepository(tosave);
1668
1669     progress.toMax();
1670     MIL << "done" << endl;
1671   }
1672
1673
1674   void RepoManager::Impl::addRepositories( const Url & url, const ProgressData::ReceiverFnc & progressrcv )
1675   {
1676     std::list<RepoInfo> repos = readRepoFile(url);
1677     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1678           it != repos.end();
1679           ++it )
1680     {
1681       // look if the alias is in the known repos.
1682       for_ ( kit, repoBegin(), repoEnd() )
1683       {
1684         if ( (*it).alias() == (*kit).alias() )
1685         {
1686           ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1687           ZYPP_THROW(RepoAlreadyExistsException(*it));
1688         }
1689       }
1690     }
1691
1692     std::string filename = Pathname(url.getPathName()).basename();
1693
1694     if ( filename == Pathname() )
1695     {
1696       // TranslatorExplanation '%s' is an URL
1697       ZYPP_THROW(RepoException(str::form( _("Invalid repo file name at '%s'"), url.asString().c_str() )));
1698     }
1699
1700     // assert the directory exists
1701     filesystem::assert_dir(_options.knownReposPath);
1702
1703     Pathname repofile = generateNonExistingName(_options.knownReposPath, filename);
1704     // now we have a filename that does not exists
1705     MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1706
1707     std::ofstream file(repofile.c_str());
1708     if (!file)
1709     {
1710       // TranslatorExplanation '%s' is a filename
1711       ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1712     }
1713
1714     for ( std::list<RepoInfo>::iterator it = repos.begin();
1715           it != repos.end();
1716           ++it )
1717     {
1718       MIL << "Saving " << (*it).alias() << endl;
1719       it->setFilepath(repofile.asString());
1720       it->dumpAsIniOn(file);
1721       reposManip().insert(*it);
1722
1723       HistoryLog(_options.rootDir).addRepository(*it);
1724     }
1725
1726     MIL << "done" << endl;
1727   }
1728
1729   ////////////////////////////////////////////////////////////////////////////
1730
1731   void RepoManager::Impl::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1732   {
1733     ProgressData progress;
1734     callback::SendReport<ProgressReport> report;
1735     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1736     progress.name(str::form(_("Removing repository '%s'"), info.label().c_str()));
1737
1738     MIL << "Going to delete repo " << info.alias() << endl;
1739
1740     for_( it, repoBegin(), repoEnd() )
1741     {
1742       // they can be the same only if the provided is empty, that means
1743       // the provided repo has no alias
1744       // then skip
1745       if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1746         continue;
1747
1748       // TODO match by url
1749
1750       // we have a matcing repository, now we need to know
1751       // where it does come from.
1752       RepoInfo todelete = *it;
1753       if (todelete.filepath().empty())
1754       {
1755         ZYPP_THROW(RepoException( todelete, _("Can't figure out where the repo is stored.") ));
1756       }
1757       else
1758       {
1759         // figure how many repos are there in the file:
1760         std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1761         if ( filerepos.size() == 0      // bsc#984494: file may have already been deleted
1762           ||(filerepos.size() == 1 && filerepos.front().alias() == todelete.alias() ) )
1763         {
1764           // easy: file does not exist, contains no or only the repo to delete: delete the file
1765           int ret = filesystem::unlink( todelete.filepath() );
1766           if ( ! ( ret == 0 || ret == ENOENT ) )
1767           {
1768             // TranslatorExplanation '%s' is a filename
1769             ZYPP_THROW(RepoException( todelete, str::form( _("Can't delete '%s'"), todelete.filepath().c_str() )));
1770           }
1771           MIL << todelete.alias() << " successfully deleted." << endl;
1772         }
1773         else
1774         {
1775           // there are more repos in the same file
1776           // write them back except the deleted one.
1777           //TmpFile tmp;
1778           //std::ofstream file(tmp.path().c_str());
1779
1780           // assert the directory exists
1781           filesystem::assert_dir(todelete.filepath().dirname());
1782
1783           std::ofstream file(todelete.filepath().c_str());
1784           if (!file)
1785           {
1786             // TranslatorExplanation '%s' is a filename
1787             ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), todelete.filepath().c_str() )));
1788           }
1789           for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1790                 fit != filerepos.end();
1791                 ++fit )
1792           {
1793             if ( (*fit).alias() != todelete.alias() )
1794               (*fit).dumpAsIniOn(file);
1795           }
1796         }
1797
1798         CombinedProgressData cSubprogrcv(progress, 20);
1799         CombinedProgressData mSubprogrcv(progress, 40);
1800         CombinedProgressData pSubprogrcv(progress, 40);
1801         // now delete it from cache
1802         if ( isCached(todelete) )
1803           cleanCache( todelete, cSubprogrcv);
1804         // now delete metadata (#301037)
1805         cleanMetadata( todelete, mSubprogrcv );
1806         cleanPackages( todelete, pSubprogrcv );
1807         reposManip().erase(todelete);
1808         MIL << todelete.alias() << " successfully deleted." << endl;
1809         HistoryLog(_options.rootDir).removeRepository(todelete);
1810         return;
1811       } // else filepath is empty
1812
1813     }
1814     // should not be reached on a sucess workflow
1815     ZYPP_THROW(RepoNotFoundException(info));
1816   }
1817
1818   ////////////////////////////////////////////////////////////////////////////
1819
1820   void RepoManager::Impl::modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, const ProgressData::ReceiverFnc & progressrcv )
1821   {
1822     RepoInfo toedit = getRepositoryInfo(alias);
1823     RepoInfo newinfo( newinfo_r ); // need writable copy to upadte housekeeping data
1824
1825     // check if the new alias already exists when renaming the repo
1826     if ( alias != newinfo.alias() && hasRepo( newinfo.alias() ) )
1827     {
1828       ZYPP_THROW(RepoAlreadyExistsException(newinfo));
1829     }
1830
1831     if (toedit.filepath().empty())
1832     {
1833       ZYPP_THROW(RepoException( toedit, _("Can't figure out where the repo is stored.") ));
1834     }
1835     else
1836     {
1837       // figure how many repos are there in the file:
1838       std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1839
1840       // there are more repos in the same file
1841       // write them back except the deleted one.
1842       //TmpFile tmp;
1843       //std::ofstream file(tmp.path().c_str());
1844
1845       // assert the directory exists
1846       filesystem::assert_dir(toedit.filepath().dirname());
1847
1848       std::ofstream file(toedit.filepath().c_str());
1849       if (!file)
1850       {
1851         // TranslatorExplanation '%s' is a filename
1852         ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), toedit.filepath().c_str() )));
1853       }
1854       for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1855             fit != filerepos.end();
1856             ++fit )
1857       {
1858           // if the alias is different, dump the original
1859           // if it is the same, dump the provided one
1860           if ( (*fit).alias() != toedit.alias() )
1861             (*fit).dumpAsIniOn(file);
1862           else
1863             newinfo.dumpAsIniOn(file);
1864       }
1865
1866       newinfo.setFilepath(toedit.filepath());
1867       reposManip().erase(toedit);
1868       reposManip().insert(newinfo);
1869       // check for credentials in Urls
1870       UrlCredentialExtractor( _options.rootDir ).collect( newinfo.baseUrls() );
1871       HistoryLog(_options.rootDir).modifyRepository(toedit, newinfo);
1872       MIL << "repo " << alias << " modified" << endl;
1873     }
1874   }
1875
1876   ////////////////////////////////////////////////////////////////////////////
1877
1878   RepoInfo RepoManager::Impl::getRepositoryInfo( const std::string & alias, const ProgressData::ReceiverFnc & progressrcv )
1879   {
1880     RepoConstIterator it( findAlias( alias, repos() ) );
1881     if ( it != repos().end() )
1882       return *it;
1883     RepoInfo info;
1884     info.setAlias( alias );
1885     ZYPP_THROW( RepoNotFoundException(info) );
1886   }
1887
1888
1889   RepoInfo RepoManager::Impl::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
1890   {
1891     for_( it, repoBegin(), repoEnd() )
1892     {
1893       for_( urlit, (*it).baseUrlsBegin(), (*it).baseUrlsEnd() )
1894       {
1895         if ( (*urlit).asString(urlview) == url.asString(urlview) )
1896           return *it;
1897       }
1898     }
1899     RepoInfo info;
1900     info.setBaseUrl( url );
1901     ZYPP_THROW( RepoNotFoundException(info) );
1902   }
1903
1904   ////////////////////////////////////////////////////////////////////////////
1905   //
1906   // Services
1907   //
1908   ////////////////////////////////////////////////////////////////////////////
1909
1910   void RepoManager::Impl::addService( const ServiceInfo & service )
1911   {
1912     assert_alias( service );
1913
1914     // check if service already exists
1915     if ( hasService( service.alias() ) )
1916       ZYPP_THROW( ServiceAlreadyExistsException( service ) );
1917
1918     // Writable ServiceInfo is needed to save the location
1919     // of the .service file. Finaly insert into the service list.
1920     ServiceInfo toSave( service );
1921     saveService( toSave );
1922     _services.insert( toSave );
1923
1924     // check for credentials in Url
1925     UrlCredentialExtractor( _options.rootDir ).collect( toSave.url() );
1926
1927     MIL << "added service " << toSave.alias() << endl;
1928   }
1929
1930   ////////////////////////////////////////////////////////////////////////////
1931
1932   void RepoManager::Impl::removeService( const std::string & alias )
1933   {
1934     MIL << "Going to delete service " << alias << endl;
1935
1936     const ServiceInfo & service = getService( alias );
1937
1938     Pathname location = service.filepath();
1939     if( location.empty() )
1940     {
1941       ZYPP_THROW(ServiceException( service, _("Can't figure out where the service is stored.") ));
1942     }
1943
1944     ServiceSet tmpSet;
1945     parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1946
1947     // only one service definition in the file
1948     if ( tmpSet.size() == 1 )
1949     {
1950       if ( filesystem::unlink(location) != 0 )
1951       {
1952         // TranslatorExplanation '%s' is a filename
1953         ZYPP_THROW(ServiceException( service, str::form( _("Can't delete '%s'"), location.c_str() ) ));
1954       }
1955       MIL << alias << " successfully deleted." << endl;
1956     }
1957     else
1958     {
1959       filesystem::assert_dir(location.dirname());
1960
1961       std::ofstream file(location.c_str());
1962       if( !file )
1963       {
1964         // TranslatorExplanation '%s' is a filename
1965         ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), location.c_str() )));
1966       }
1967
1968       for_(it, tmpSet.begin(), tmpSet.end())
1969       {
1970         if( it->alias() != alias )
1971           it->dumpAsIniOn(file);
1972       }
1973
1974       MIL << alias << " successfully deleted from file " << location <<  endl;
1975     }
1976
1977     // now remove all repositories added by this service
1978     RepoCollector rcollector;
1979     getRepositoriesInService( alias,
1980                               boost::make_function_output_iterator( bind( &RepoCollector::collect, &rcollector, _1 ) ) );
1981     // cannot do this directly in getRepositoriesInService - would invalidate iterators
1982     for_(rit, rcollector.repos.begin(), rcollector.repos.end())
1983       removeRepository(*rit);
1984   }
1985
1986   ////////////////////////////////////////////////////////////////////////////
1987
1988   void RepoManager::Impl::refreshServices( const RefreshServiceOptions & options_r )
1989   {
1990     // copy the set of services since refreshService
1991     // can eventually invalidate the iterator
1992     ServiceSet services( serviceBegin(), serviceEnd() );
1993     for_( it, services.begin(), services.end() )
1994     {
1995       if ( !it->enabled() )
1996         continue;
1997
1998       try {
1999         refreshService(*it, options_r);
2000       }
2001       catch ( const repo::ServicePluginInformalException & e )
2002       { ;/* ignore ServicePluginInformalException */ }
2003     }
2004   }
2005
2006   void RepoManager::Impl::refreshService( const std::string & alias, const RefreshServiceOptions & options_r )
2007   {
2008     ServiceInfo service( getService( alias ) );
2009     assert_alias( service );
2010     assert_url( service );
2011     // NOTE: It might be necessary to modify and rewrite the service info.
2012     // Either when probing the type, or when adjusting the repositories
2013     // enable/disable state.:
2014     bool serviceModified = false;
2015     MIL << "Going to refresh service '" << service.alias() << "', url: "<< service.url() << ", opts: " << options_r << endl;
2016
2017     //! \todo add callbacks for apps (start, end, repo removed, repo added, repo changed)
2018
2019     // if the type is unknown, try probing.
2020     if ( service.type() == repo::ServiceType::NONE )
2021     {
2022       repo::ServiceType type = probeService( service.url() );
2023       if ( type != ServiceType::NONE )
2024       {
2025         service.setProbedType( type ); // lazy init!
2026         serviceModified = true;
2027       }
2028     }
2029
2030     // get target distro identifier
2031     std::string servicesTargetDistro = _options.servicesTargetDistro;
2032     if ( servicesTargetDistro.empty() )
2033     {
2034       servicesTargetDistro = Target::targetDistribution( Pathname() );
2035     }
2036     DBG << "ServicesTargetDistro: " << servicesTargetDistro << endl;
2037
2038     // parse it
2039     RepoCollector collector(servicesTargetDistro);
2040     // FIXME Ugly hack: ServiceRepos may throw ServicePluginInformalException
2041     // which is actually a notification. Using an exception for this
2042     // instead of signal/callback is bad. Needs to be fixed here, in refreshServices()
2043     // and in zypper.
2044     std::pair<DefaultIntegral<bool,false>, repo::ServicePluginInformalException> uglyHack;
2045     try {
2046       ServiceRepos repos(service, bind( &RepoCollector::collect, &collector, _1 ));
2047     }
2048     catch ( const repo::ServicePluginInformalException & e )
2049     {
2050       /* ignore ServicePluginInformalException and throw later */
2051       uglyHack.first = true;
2052       uglyHack.second = e;
2053     }
2054
2055     ////////////////////////////////////////////////////////////////////////////
2056     // On the fly remember the new repo states as defined the reopoindex.xml.
2057     // Move into ServiceInfo later.
2058     ServiceInfo::RepoStates newRepoStates;
2059
2060     // set service alias and base url for all collected repositories
2061     for_( it, collector.repos.begin(), collector.repos.end() )
2062     {
2063       // First of all: Prepend service alias:
2064       it->setAlias( str::form( "%s:%s", service.alias().c_str(), it->alias().c_str() ) );
2065       // set reference to the parent service
2066       it->setService( service.alias() );
2067
2068       // remember the new parsed repo state
2069       newRepoStates[it->alias()] = *it;
2070
2071       // - If the repo url was not set by the repoindex parser, set service's url.
2072       // - Libzypp currently has problem with separate url + path handling so just
2073       //   append a path, if set, to the baseurls
2074       // - Credentials in the url authority will be extracted later, either if the
2075       //   repository is added or if we check for changed urls.
2076       Pathname path;
2077       if ( !it->path().empty() )
2078       {
2079         if ( it->path() != "/" )
2080           path = it->path();
2081         it->setPath("");
2082       }
2083
2084       if ( it->baseUrlsEmpty() )
2085       {
2086         Url url( service.rawUrl() );
2087         if ( !path.empty() )
2088           url.setPathName( url.getPathName() / path );
2089         it->setBaseUrl( std::move(url) );
2090       }
2091       else if ( !path.empty() )
2092       {
2093         RepoInfo::url_set urls( it->rawBaseUrls() );
2094         for ( Url & url : urls )
2095         {
2096           url.setPathName( url.getPathName() / path );
2097         }
2098         it->setBaseUrls( std::move(urls) );
2099       }
2100     }
2101
2102     ////////////////////////////////////////////////////////////////////////////
2103     // Now compare collected repos with the ones in the system...
2104     //
2105     RepoInfoList oldRepos;
2106     getRepositoriesInService( service.alias(), std::back_inserter( oldRepos ) );
2107
2108     ////////////////////////////////////////////////////////////////////////////
2109     // find old repositories to remove...
2110     for_( oldRepo, oldRepos.begin(), oldRepos.end() )
2111     {
2112       if ( ! foundAliasIn( oldRepo->alias(), collector.repos ) )
2113       {
2114         if ( oldRepo->enabled() )
2115         {
2116           // Currently enabled. If this was a user modification remember the state.
2117           const auto & last = service.repoStates().find( oldRepo->alias() );
2118           if ( last != service.repoStates().end() && ! last->second.enabled )
2119           {
2120             DBG << "Service removes user enabled repo " << oldRepo->alias() << endl;
2121             service.addRepoToEnable( oldRepo->alias() );
2122             serviceModified = true;
2123           }
2124           else
2125             DBG << "Service removes enabled repo " << oldRepo->alias() << endl;
2126         }
2127         else
2128           DBG << "Service removes disabled repo " << oldRepo->alias() << endl;
2129
2130         removeRepository( *oldRepo );
2131       }
2132     }
2133
2134     ////////////////////////////////////////////////////////////////////////////
2135     // create missing repositories and modify existing ones if needed...
2136     UrlCredentialExtractor urlCredentialExtractor( _options.rootDir );  // To collect any credentials stored in repo URLs
2137     for_( it, collector.repos.begin(), collector.repos.end() )
2138     {
2139       // User explicitly requested the repo being enabled?
2140       // User explicitly requested the repo being disabled?
2141       // And hopefully not both ;) If so, enable wins.
2142
2143       TriBool toBeEnabled( indeterminate );     // indeterminate - follow the service request
2144       DBG << "Service request to " << (it->enabled()?"enable":"disable") << " service repo " << it->alias() << endl;
2145
2146       if ( options_r.testFlag( RefreshService_restoreStatus ) )
2147       {
2148         DBG << "Opt RefreshService_restoreStatus " << it->alias() << endl;
2149         // this overrides any pending request!
2150         // Remove from enable request list.
2151         // NOTE: repoToDisable is handled differently.
2152         //       It gets cleared on each refresh.
2153         service.delRepoToEnable( it->alias() );
2154         // toBeEnabled stays indeterminate!
2155       }
2156       else
2157       {
2158         if ( service.repoToEnableFind( it->alias() ) )
2159         {
2160           DBG << "User request to enable service repo " << it->alias() << endl;
2161           toBeEnabled = true;
2162           // Remove from enable request list.
2163           // NOTE: repoToDisable is handled differently.
2164           //       It gets cleared on each refresh.
2165           service.delRepoToEnable( it->alias() );
2166           serviceModified = true;
2167         }
2168         else if ( service.repoToDisableFind( it->alias() ) )
2169         {
2170           DBG << "User request to disable service repo " << it->alias() << endl;
2171           toBeEnabled = false;
2172         }
2173       }
2174
2175       RepoInfoList::iterator oldRepo( findAlias( it->alias(), oldRepos ) );
2176       if ( oldRepo == oldRepos.end() )
2177       {
2178         // Not found in oldRepos ==> a new repo to add
2179
2180         // Make sure the service repo is created with the appropriate enablement
2181         if ( ! indeterminate(toBeEnabled) )
2182           it->setEnabled( toBeEnabled );
2183
2184         DBG << "Service adds repo " << it->alias() << " " << (it->enabled()?"enabled":"disabled") << endl;
2185         addRepository( *it );
2186       }
2187       else
2188       {
2189         // ==> an exising repo to check
2190         bool oldRepoModified = false;
2191
2192         if ( indeterminate(toBeEnabled) )
2193         {
2194           // No user request: check for an old user modificaton otherwise follow service request.
2195           // NOTE: Assert toBeEnabled is boolean afterwards!
2196           if ( oldRepo->enabled() == it->enabled() )
2197             toBeEnabled = it->enabled();        // service requests no change to the system
2198           else if (options_r.testFlag( RefreshService_restoreStatus ) )
2199           {
2200             toBeEnabled = it->enabled();        // RefreshService_restoreStatus forced
2201             DBG << "Opt RefreshService_restoreStatus " << it->alias() <<  " forces " << (toBeEnabled?"enabled":"disabled") << endl;
2202           }
2203           else
2204           {
2205             const auto & last = service.repoStates().find( oldRepo->alias() );
2206             if ( last == service.repoStates().end() || last->second.enabled != it->enabled() )
2207               toBeEnabled = it->enabled();      // service request has changed since last refresh -> follow
2208             else
2209             {
2210               toBeEnabled = oldRepo->enabled(); // service request unchaned since last refresh -> keep user modification
2211               DBG << "User modified service repo " << it->alias() <<  " may stay " << (toBeEnabled?"enabled":"disabled") << endl;
2212             }
2213           }
2214         }
2215
2216         // changed enable?
2217         if ( toBeEnabled == oldRepo->enabled() )
2218         {
2219           DBG << "Service repo " << it->alias() << " stays " <<  (oldRepo->enabled()?"enabled":"disabled") << endl;
2220         }
2221         else if ( toBeEnabled )
2222         {
2223           DBG << "Service repo " << it->alias() << " gets enabled" << endl;
2224           oldRepo->setEnabled( true );
2225           oldRepoModified = true;
2226         }
2227         else
2228         {
2229           DBG << "Service repo " << it->alias() << " gets disabled" << endl;
2230           oldRepo->setEnabled( false );
2231           oldRepoModified = true;
2232         }
2233
2234         // all other attributes follow the service request:
2235
2236         // changed name (raw!)
2237         if ( oldRepo->rawName() != it->rawName() )
2238         {
2239           DBG << "Service repo " << it->alias() << " gets new NAME " << it->rawName() << endl;
2240           oldRepo->setName( it->rawName() );
2241           oldRepoModified = true;
2242         }
2243
2244         // changed autorefresh
2245         if ( oldRepo->autorefresh() != it->autorefresh() )
2246         {
2247           DBG << "Service repo " << it->alias() << " gets new AUTOREFRESH " << it->autorefresh() << endl;
2248           oldRepo->setAutorefresh( it->autorefresh() );
2249           oldRepoModified = true;
2250         }
2251
2252         // changed priority?
2253         if ( oldRepo->priority() != it->priority() )
2254         {
2255           DBG << "Service repo " << it->alias() << " gets new PRIORITY " << it->priority() << endl;
2256           oldRepo->setPriority( it->priority() );
2257           oldRepoModified = true;
2258         }
2259
2260         // changed url?
2261         {
2262           RepoInfo::url_set newUrls( it->rawBaseUrls() );
2263           urlCredentialExtractor.extract( newUrls );    // Extract! to prevent passwds from disturbing the comparison below
2264           if ( oldRepo->rawBaseUrls() != newUrls )
2265           {
2266             DBG << "Service repo " << it->alias() << " gets new URLs " << newUrls << endl;
2267             oldRepo->setBaseUrls( std::move(newUrls) );
2268             oldRepoModified = true;
2269           }
2270         }
2271
2272         // changed gpg check settings?
2273         // ATM only plugin services can set GPG values.
2274         if ( service.type() == ServiceType::PLUGIN )
2275         {
2276           TriBool ogpg[3];      // Gpg RepoGpg PkgGpg
2277           TriBool ngpg[3];
2278           oldRepo->getRawGpgChecks( ogpg[0], ogpg[1], ogpg[2] );
2279           it->     getRawGpgChecks( ngpg[0], ngpg[1], ngpg[2] );
2280 #define Z_CHKGPG(I,N)                                                                           \
2281           if ( ! sameTriboolState( ogpg[I], ngpg[I] ) )                                         \
2282           {                                                                                     \
2283             DBG << "Service repo " << it->alias() << " gets new "#N"Check " << ngpg[I] << endl; \
2284             oldRepo->set##N##Check( ngpg[I] );                                                  \
2285             oldRepoModified = true;                                                             \
2286           }
2287           Z_CHKGPG( 0, Gpg );
2288           Z_CHKGPG( 1, RepoGpg );
2289           Z_CHKGPG( 2, PkgGpg );
2290 #undef Z_CHKGPG
2291         }
2292
2293         // save if modified:
2294         if ( oldRepoModified )
2295         {
2296           modifyRepository( oldRepo->alias(), *oldRepo );
2297         }
2298       }
2299     }
2300
2301     // Unlike reposToEnable, reposToDisable is always cleared after refresh.
2302     if ( ! service.reposToDisableEmpty() )
2303     {
2304       service.clearReposToDisable();
2305       serviceModified = true;
2306     }
2307
2308     // Remember original service request for next refresh
2309     if ( service.repoStates() != newRepoStates )
2310     {
2311       service.setRepoStates( std::move(newRepoStates) );
2312       serviceModified = true;
2313     }
2314
2315     ////////////////////////////////////////////////////////////////////////////
2316     // save service if modified: (unless a plugin service)
2317     if ( serviceModified && service.type() != ServiceType::PLUGIN )
2318     {
2319       // write out modified service file.
2320       modifyService( service.alias(), service );
2321     }
2322
2323     if ( uglyHack.first )
2324     {
2325       throw( uglyHack.second ); // intentionally not ZYPP_THROW
2326     }
2327   }
2328
2329   ////////////////////////////////////////////////////////////////////////////
2330
2331   void RepoManager::Impl::modifyService( const std::string & oldAlias, const ServiceInfo & newService )
2332   {
2333     MIL << "Going to modify service " << oldAlias << endl;
2334
2335     // we need a writable copy to link it to the file where
2336     // it is saved if we modify it
2337     ServiceInfo service(newService);
2338
2339     if ( service.type() == ServiceType::PLUGIN )
2340     {
2341       ZYPP_THROW(ServicePluginImmutableException( service ));
2342     }
2343
2344     const ServiceInfo & oldService = getService(oldAlias);
2345
2346     Pathname location = oldService.filepath();
2347     if( location.empty() )
2348     {
2349       ZYPP_THROW(ServiceException( oldService, _("Can't figure out where the service is stored.") ));
2350     }
2351
2352     // remember: there may multiple services being defined in one file:
2353     ServiceSet tmpSet;
2354     parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
2355
2356     filesystem::assert_dir(location.dirname());
2357     std::ofstream file(location.c_str());
2358     for_(it, tmpSet.begin(), tmpSet.end())
2359     {
2360       if( *it != oldAlias )
2361         it->dumpAsIniOn(file);
2362     }
2363     service.dumpAsIniOn(file);
2364     file.close();
2365     service.setFilepath(location);
2366
2367     _services.erase(oldAlias);
2368     _services.insert(service);
2369     // check for credentials in Urls
2370     UrlCredentialExtractor( _options.rootDir ).collect( service.url() );
2371
2372
2373     // changed properties affecting also repositories
2374     if ( oldAlias != service.alias()                    // changed alias
2375       || oldService.enabled() != service.enabled() )    // changed enabled status
2376     {
2377       std::vector<RepoInfo> toModify;
2378       getRepositoriesInService(oldAlias, std::back_inserter(toModify));
2379       for_( it, toModify.begin(), toModify.end() )
2380       {
2381         if ( oldService.enabled() != service.enabled() )
2382         {
2383           if ( service.enabled() )
2384           {
2385             // reset to last refreshs state
2386             const auto & last = service.repoStates().find( it->alias() );
2387             if ( last != service.repoStates().end() )
2388               it->setEnabled( last->second.enabled );
2389           }
2390           else
2391             it->setEnabled( false );
2392         }
2393
2394         if ( oldAlias != service.alias() )
2395           it->setService(service.alias());
2396
2397         modifyRepository(it->alias(), *it);
2398       }
2399     }
2400
2401     //! \todo refresh the service automatically if url is changed?
2402   }
2403
2404   ////////////////////////////////////////////////////////////////////////////
2405
2406   repo::ServiceType RepoManager::Impl::probeService( const Url & url ) const
2407   {
2408     try
2409     {
2410       MediaSetAccess access(url);
2411       if ( access.doesFileExist("/repo/repoindex.xml") )
2412         return repo::ServiceType::RIS;
2413     }
2414     catch ( const media::MediaException &e )
2415     {
2416       ZYPP_CAUGHT(e);
2417       // TranslatorExplanation '%s' is an URL
2418       RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
2419       enew.remember(e);
2420       ZYPP_THROW(enew);
2421     }
2422     catch ( const Exception &e )
2423     {
2424       ZYPP_CAUGHT(e);
2425       // TranslatorExplanation '%s' is an URL
2426       Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
2427       enew.remember(e);
2428       ZYPP_THROW(enew);
2429     }
2430
2431     return repo::ServiceType::NONE;
2432   }
2433
2434   ///////////////////////////////////////////////////////////////////
2435   //
2436   //    CLASS NAME : RepoManager
2437   //
2438   ///////////////////////////////////////////////////////////////////
2439
2440   RepoManager::RepoManager( const RepoManagerOptions & opt )
2441   : _pimpl( new Impl(opt) )
2442   {}
2443
2444   RepoManager::~RepoManager()
2445   {}
2446
2447   bool RepoManager::repoEmpty() const
2448   { return _pimpl->repoEmpty(); }
2449
2450   RepoManager::RepoSizeType RepoManager::repoSize() const
2451   { return _pimpl->repoSize(); }
2452
2453   RepoManager::RepoConstIterator RepoManager::repoBegin() const
2454   { return _pimpl->repoBegin(); }
2455
2456   RepoManager::RepoConstIterator RepoManager::repoEnd() const
2457   { return _pimpl->repoEnd(); }
2458
2459   RepoInfo RepoManager::getRepo( const std::string & alias ) const
2460   { return _pimpl->getRepo( alias ); }
2461
2462   bool RepoManager::hasRepo( const std::string & alias ) const
2463   { return _pimpl->hasRepo( alias ); }
2464
2465   std::string RepoManager::makeStupidAlias( const Url & url_r )
2466   {
2467     std::string ret( url_r.getScheme() );
2468     if ( ret.empty() )
2469       ret = "repo-";
2470     else
2471       ret += "-";
2472
2473     std::string host( url_r.getHost() );
2474     if ( ! host.empty() )
2475     {
2476       ret += host;
2477       ret += "-";
2478     }
2479
2480     static Date::ValueType serial = Date::now();
2481     ret += Digest::digest( Digest::sha1(), str::hexstring( ++serial ) +url_r.asCompleteString() ).substr(0,8);
2482     return ret;
2483   }
2484
2485   RepoStatus RepoManager::metadataStatus( const RepoInfo & info ) const
2486   { return _pimpl->metadataStatus( info ); }
2487
2488   RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata( const RepoInfo &info, const Url &url, RawMetadataRefreshPolicy policy )
2489   { return _pimpl->checkIfToRefreshMetadata( info, url, policy ); }
2490
2491   Pathname RepoManager::metadataPath( const RepoInfo &info ) const
2492   { return _pimpl->metadataPath( info ); }
2493
2494   Pathname RepoManager::packagesPath( const RepoInfo &info ) const
2495   { return _pimpl->packagesPath( info ); }
2496
2497   void RepoManager::refreshMetadata( const RepoInfo &info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2498   { return _pimpl->refreshMetadata( info, policy, progressrcv ); }
2499
2500   void RepoManager::cleanMetadata( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2501   { return _pimpl->cleanMetadata( info, progressrcv ); }
2502
2503   void RepoManager::cleanPackages( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2504   { return _pimpl->cleanPackages( info, progressrcv ); }
2505
2506   RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
2507   { return _pimpl->cacheStatus( info ); }
2508
2509   void RepoManager::buildCache( const RepoInfo &info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2510   { return _pimpl->buildCache( info, policy, progressrcv ); }
2511
2512   void RepoManager::cleanCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2513   { return _pimpl->cleanCache( info, progressrcv ); }
2514
2515   bool RepoManager::isCached( const RepoInfo &info ) const
2516   { return _pimpl->isCached( info ); }
2517
2518   void RepoManager::loadFromCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2519   { return _pimpl->loadFromCache( info, progressrcv ); }
2520
2521   void RepoManager::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
2522   { return _pimpl->cleanCacheDirGarbage( progressrcv ); }
2523
2524   repo::RepoType RepoManager::probe( const Url & url, const Pathname & path ) const
2525   { return _pimpl->probe( url, path ); }
2526
2527   repo::RepoType RepoManager::probe( const Url & url ) const
2528   { return _pimpl->probe( url ); }
2529
2530   void RepoManager::addRepository( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2531   { return _pimpl->addRepository( info, progressrcv ); }
2532
2533   void RepoManager::addRepositories( const Url &url, const ProgressData::ReceiverFnc & progressrcv )
2534   { return _pimpl->addRepositories( url, progressrcv ); }
2535
2536   void RepoManager::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
2537   { return _pimpl->removeRepository( info, progressrcv ); }
2538
2539   void RepoManager::modifyRepository( const std::string &alias, const RepoInfo & newinfo, const ProgressData::ReceiverFnc & progressrcv )
2540   { return _pimpl->modifyRepository( alias, newinfo, progressrcv ); }
2541
2542   RepoInfo RepoManager::getRepositoryInfo( const std::string &alias, const ProgressData::ReceiverFnc & progressrcv )
2543   { return _pimpl->getRepositoryInfo( alias, progressrcv ); }
2544
2545   RepoInfo RepoManager::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
2546   { return _pimpl->getRepositoryInfo( url, urlview, progressrcv ); }
2547
2548   bool RepoManager::serviceEmpty() const
2549   { return _pimpl->serviceEmpty(); }
2550
2551   RepoManager::ServiceSizeType RepoManager::serviceSize() const
2552   { return _pimpl->serviceSize(); }
2553
2554   RepoManager::ServiceConstIterator RepoManager::serviceBegin() const
2555   { return _pimpl->serviceBegin(); }
2556
2557   RepoManager::ServiceConstIterator RepoManager::serviceEnd() const
2558   { return _pimpl->serviceEnd(); }
2559
2560   ServiceInfo RepoManager::getService( const std::string & alias ) const
2561   { return _pimpl->getService( alias ); }
2562
2563   bool RepoManager::hasService( const std::string & alias ) const
2564   { return _pimpl->hasService( alias ); }
2565
2566   repo::ServiceType RepoManager::probeService( const Url &url ) const
2567   { return _pimpl->probeService( url ); }
2568
2569   void RepoManager::addService( const std::string & alias, const Url& url )
2570   { return _pimpl->addService( alias, url ); }
2571
2572   void RepoManager::addService( const ServiceInfo & service )
2573   { return _pimpl->addService( service ); }
2574
2575   void RepoManager::removeService( const std::string & alias )
2576   { return _pimpl->removeService( alias ); }
2577
2578   void RepoManager::removeService( const ServiceInfo & service )
2579   { return _pimpl->removeService( service ); }
2580
2581   void RepoManager::refreshServices( const RefreshServiceOptions & options_r )
2582   { return _pimpl->refreshServices( options_r ); }
2583
2584   void RepoManager::refreshService( const std::string & alias, const RefreshServiceOptions & options_r )
2585   { return _pimpl->refreshService( alias, options_r ); }
2586
2587   void RepoManager::refreshService( const ServiceInfo & service, const RefreshServiceOptions & options_r )
2588   { return _pimpl->refreshService( service, options_r ); }
2589
2590   void RepoManager::modifyService( const std::string & oldAlias, const ServiceInfo & service )
2591   { return _pimpl->modifyService( oldAlias, service ); }
2592
2593   ////////////////////////////////////////////////////////////////////////////
2594
2595   std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
2596   { return str << *obj._pimpl; }
2597
2598   /////////////////////////////////////////////////////////////////
2599 } // namespace zypp
2600 ///////////////////////////////////////////////////////////////////