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