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