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