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