keep orphaned cache dirs for one day
[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() );
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() );
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();
501
502     void refreshService( const std::string & alias );
503     void refreshService( const ServiceInfo & service )
504     {  refreshService( service.alias() ); }
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       for ( RepoInfo & repoInfo : repositories_in_dir(_options.knownReposPath) )
641       {
642         // set the metadata path for the repo
643         repoInfo.setMetadataPath( rawcache_path_for_repoinfo(_options, repoInfo) );
644         // set the downloaded packages path for the repo
645         repoInfo.setPackagesPath( packagescache_path_for_repoinfo(_options, repoInfo) );
646
647         _repos.insert( repoInfo );
648         repoEscAliases.push_back(repoInfo.escaped_alias());
649       }
650       repoEscAliases.sort();
651
652       // delete metadata folders without corresponding repo (e.g. old tmp directories)
653       for ( const Pathname & cachePath : { _options.repoRawCachePath
654                                          , _options.repoSolvCachePath } )
655       {
656         std::list<std::string> entries;
657         if ( filesystem::readdir( entries, cachePath, false ) == 0 )
658         {
659           entries.sort();
660           std::set<std::string> oldfiles;
661           set_difference( entries.begin(), entries.end(), repoEscAliases.begin(), repoEscAliases.end(),
662                           std::inserter( oldfiles, oldfiles.end() ) );
663           for ( const std::string & old : oldfiles )
664           {
665             if ( old == Repository::systemRepoAlias() ) // don't remove the @System solv file
666               continue;
667             filesystem::recursive_rmdir( cachePath / old );
668           }
669         }
670       }
671     }
672     MIL << "end construct known repos" << endl;
673   }
674
675   ///////////////////////////////////////////////////////////////////
676
677   RepoStatus RepoManager::Impl::metadataStatus( const RepoInfo & info ) const
678   {
679     Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
680     Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
681
682     RepoType repokind = info.type();
683     // If unknown, probe the local metadata
684     if ( repokind == RepoType::NONE )
685       repokind = probe( productdatapath.asUrl() );
686
687     RepoStatus status;
688     switch ( repokind.toEnum() )
689     {
690       case RepoType::RPMMD_e :
691         status = RepoStatus( productdatapath/"repodata/repomd.xml");
692         break;
693
694       case RepoType::YAST2_e :
695         status = RepoStatus( productdatapath/"content" ) && RepoStatus( mediarootpath/"media.1/media" );
696         break;
697
698       case RepoType::RPMPLAINDIR_e :
699         status = RepoStatus::fromCookieFile( productdatapath/"cookie" );
700         break;
701
702       case RepoType::NONE_e :
703         // Return default RepoStatus in case of RepoType::NONE
704         // indicating it should be created?
705         // ZYPP_THROW(RepoUnknownTypeException());
706         break;
707     }
708     return status;
709   }
710
711
712   void RepoManager::Impl::touchIndexFile( const RepoInfo & info )
713   {
714     Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
715
716     RepoType repokind = info.type();
717     if ( repokind.toEnum() == RepoType::NONE_e )
718       // unknown, probe the local metadata
719       repokind = probe( productdatapath.asUrl() );
720     // if still unknown, just return
721     if (repokind == RepoType::NONE_e)
722       return;
723
724     Pathname p;
725     switch ( repokind.toEnum() )
726     {
727       case RepoType::RPMMD_e :
728         p = Pathname(productdatapath + "/repodata/repomd.xml");
729         break;
730
731       case RepoType::YAST2_e :
732         p = Pathname(productdatapath + "/content");
733         break;
734
735       case RepoType::RPMPLAINDIR_e :
736         p = Pathname(productdatapath + "/cookie");
737         break;
738
739       case RepoType::NONE_e :
740       default:
741         break;
742     }
743
744     // touch the file, ignore error (they are logged anyway)
745     filesystem::touch(p);
746   }
747
748
749   RepoManager::RefreshCheckStatus RepoManager::Impl::checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy )
750   {
751     assert_alias(info);
752     try
753     {
754       MIL << "Going to try to check whether refresh is needed for " << url << endl;
755
756       // first check old (cached) metadata
757       Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
758       filesystem::assert_dir( mediarootpath );
759       RepoStatus oldstatus = metadataStatus( info );
760
761       if ( oldstatus.empty() )
762       {
763         MIL << "No cached metadata, going to refresh" << endl;
764         return REFRESH_NEEDED;
765       }
766
767       {
768         if ( url.schemeIsVolatile() )
769         {
770           MIL << "never refresh CD/DVD" << endl;
771           return REPO_UP_TO_DATE;
772         }
773         if ( url.schemeIsLocal() )
774         {
775           policy = RefreshIfNeededIgnoreDelay;
776         }
777       }
778
779       // now we've got the old (cached) status, we can decide repo.refresh.delay
780       if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
781       {
782         // difference in seconds
783         double diff = difftime(
784           (Date::ValueType)Date::now(),
785           (Date::ValueType)oldstatus.timestamp()) / 60;
786
787         DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
788         DBG << "current time: " << (Date::ValueType)Date::now() << endl;
789         DBG << "last refresh = " << diff << " minutes ago" << endl;
790
791         if ( diff < ZConfig::instance().repo_refresh_delay() )
792         {
793           if ( diff < 0 )
794           {
795             WAR << "Repository '" << info.alias() << "' was refreshed in the future!" << endl;
796           }
797           else
798           {
799             MIL << "Repository '" << info.alias()
800                 << "' has been refreshed less than repo.refresh.delay ("
801                 << ZConfig::instance().repo_refresh_delay()
802                 << ") minutes ago. Advising to skip refresh" << endl;
803             return REPO_CHECK_DELAYED;
804           }
805         }
806       }
807
808       // To test the new matadta create temp dir as sibling of mediarootpath
809       filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
810
811       repo::RepoType repokind = info.type();
812       // if unknown: probe it
813       if ( repokind == RepoType::NONE )
814         repokind = probe( url, info.path() );
815
816       // retrieve newstatus
817       RepoStatus newstatus;
818       switch ( repokind.toEnum() )
819       {
820         case RepoType::RPMMD_e:
821         {
822           MediaSetAccess media( url );
823           newstatus = yum::Downloader( info, mediarootpath ).status( media );
824         }
825         break;
826
827         case RepoType::YAST2_e:
828         {
829           MediaSetAccess media( url );
830           newstatus = susetags::Downloader( info, mediarootpath ).status( media );
831         }
832         break;
833
834         case RepoType::RPMPLAINDIR_e:
835           newstatus = RepoStatus( MediaMounter(url).getPathName(info.path()) ); // dir status
836           break;
837
838         default:
839         case RepoType::NONE_e:
840           ZYPP_THROW( RepoUnknownTypeException( info ) );
841           break;
842       }
843
844       // check status
845       bool refresh = false;
846       if ( oldstatus == newstatus )
847       {
848         MIL << "repo has not changed" << endl;
849         if ( policy == RefreshForced )
850         {
851           MIL << "refresh set to forced" << endl;
852           refresh = true;
853         }
854       }
855       else
856       {
857         MIL << "repo has changed, going to refresh" << endl;
858         refresh = true;
859       }
860
861       if (!refresh)
862         touchIndexFile(info);
863
864       return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
865
866     }
867     catch ( const Exception &e )
868     {
869       ZYPP_CAUGHT(e);
870       ERR << "refresh check failed for " << url << endl;
871       ZYPP_RETHROW(e);
872     }
873
874     return REFRESH_NEEDED; // default
875   }
876
877
878   void RepoManager::Impl::refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progress )
879   {
880     assert_alias(info);
881     assert_urls(info);
882
883     // we will throw this later if no URL checks out fine
884     RepoException rexception(_PL("Valid metadata not found at specified URL",
885                                  "Valid metadata not found at specified URLs",
886                                  info.baseUrlsSize() ) );
887
888     // try urls one by one
889     for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
890     {
891       try
892       {
893         Url url(*it);
894
895         // check whether to refresh metadata
896         // if the check fails for this url, it throws, so another url will be checked
897         if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
898           return;
899
900         MIL << "Going to refresh metadata from " << url << endl;
901
902         repo::RepoType repokind = info.type();
903
904         // if the type is unknown, try probing.
905         if ( repokind == RepoType::NONE )
906         {
907           // unknown, probe it
908           repokind = probe( *it, info.path() );
909
910           if (repokind.toEnum() != RepoType::NONE_e)
911           {
912             // Adjust the probed type in RepoInfo
913             info.setProbedType( repokind ); // lazy init!
914             //save probed type only for repos in system
915             for_( it, repoBegin(), repoEnd() )
916             {
917               if ( info.alias() == (*it).alias() )
918               {
919                 RepoInfo modifiedrepo = info;
920                 modifiedrepo.setType( repokind );
921                 modifyRepository( info.alias(), modifiedrepo );
922                 break;
923               }
924             }
925           }
926         }
927
928         Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
929         if( filesystem::assert_dir(mediarootpath) )
930         {
931           Exception ex(str::form( _("Can't create %s"), mediarootpath.c_str()) );
932           ZYPP_THROW(ex);
933         }
934
935         // create temp dir as sibling of mediarootpath
936         filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
937         if( tmpdir.path().empty() )
938         {
939           Exception ex(_("Can't create metadata cache directory."));
940           ZYPP_THROW(ex);
941         }
942
943         if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
944              ( repokind.toEnum() == RepoType::YAST2_e ) )
945         {
946           MediaSetAccess media(url);
947           shared_ptr<repo::Downloader> downloader_ptr;
948
949           MIL << "Creating downloader for [ " << info.alias() << " ]" << endl;
950
951           if ( repokind.toEnum() == RepoType::RPMMD_e )
952             downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
953           else
954             downloader_ptr.reset( new susetags::Downloader(info, mediarootpath) );
955
956           /**
957            * Given a downloader, sets the other repos raw metadata
958            * path as cache paths for the fetcher, so if another
959            * repo has the same file, it will not download it
960            * but copy it from the other repository
961            */
962           for_( it, repoBegin(), repoEnd() )
963           {
964             Pathname cachepath(rawcache_path_for_repoinfo( _options, *it ));
965             if ( PathInfo(cachepath).isExist() )
966               downloader_ptr->addCachePath(cachepath);
967           }
968
969           downloader_ptr->download( media, tmpdir.path() );
970         }
971         else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
972         {
973           MediaMounter media( url );
974           RepoStatus newstatus = RepoStatus( media.getPathName( info.path() ) );        // dir status
975
976           Pathname productpath( tmpdir.path() / info.path() );
977           filesystem::assert_dir( productpath );
978           newstatus.saveToCookieFile( productpath/"cookie" );
979         }
980         else
981         {
982           ZYPP_THROW(RepoUnknownTypeException());
983         }
984
985         // ok we have the metadata, now exchange
986         // the contents
987         filesystem::exchange( tmpdir.path(), mediarootpath );
988
989         // we are done.
990         return;
991       }
992       catch ( const Exception &e )
993       {
994         ZYPP_CAUGHT(e);
995         ERR << "Trying another url..." << endl;
996
997         // remember the exception caught for the *first URL*
998         // if all other URLs fail, the rexception will be thrown with the
999         // cause of the problem of the first URL remembered
1000         if (it == info.baseUrlsBegin())
1001           rexception.remember(e);
1002       }
1003     } // for every url
1004     ERR << "No more urls..." << endl;
1005     ZYPP_THROW(rexception);
1006   }
1007
1008   ////////////////////////////////////////////////////////////////////////////
1009
1010   void RepoManager::Impl::cleanMetadata( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1011   {
1012     ProgressData progress(100);
1013     progress.sendTo(progressfnc);
1014
1015     filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_options, info));
1016     progress.toMax();
1017   }
1018
1019
1020   void RepoManager::Impl::cleanPackages( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1021   {
1022     ProgressData progress(100);
1023     progress.sendTo(progressfnc);
1024
1025     filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_options, info));
1026     progress.toMax();
1027   }
1028
1029
1030   void RepoManager::Impl::buildCache( const RepoInfo & info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
1031   {
1032     assert_alias(info);
1033     Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1034     Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
1035
1036     if( filesystem::assert_dir(_options.repoCachePath) )
1037     {
1038       Exception ex(str::form( _("Can't create %s"), _options.repoCachePath.c_str()) );
1039       ZYPP_THROW(ex);
1040     }
1041     RepoStatus raw_metadata_status = metadataStatus(info);
1042     if ( raw_metadata_status.empty() )
1043     {
1044        /* if there is no cache at this point, we refresh the raw
1045           in case this is the first time - if it's !autorefresh,
1046           we may still refresh */
1047       refreshMetadata(info, RefreshIfNeeded, progressrcv );
1048       raw_metadata_status = metadataStatus(info);
1049     }
1050
1051     bool needs_cleaning = false;
1052     if ( isCached( info ) )
1053     {
1054       MIL << info.alias() << " is already cached." << endl;
1055       RepoStatus cache_status = cacheStatus(info);
1056
1057       if ( cache_status == raw_metadata_status )
1058       {
1059         MIL << info.alias() << " cache is up to date with metadata." << endl;
1060         if ( policy == BuildIfNeeded ) {
1061           return;
1062         }
1063         else {
1064           MIL << info.alias() << " cache rebuild is forced" << endl;
1065         }
1066       }
1067
1068       needs_cleaning = true;
1069     }
1070
1071     ProgressData progress(100);
1072     callback::SendReport<ProgressReport> report;
1073     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1074     progress.name(str::form(_("Building repository '%s' cache"), info.label().c_str()));
1075     progress.toMin();
1076
1077     if (needs_cleaning)
1078     {
1079       cleanCache(info);
1080     }
1081
1082     MIL << info.alias() << " building cache..." << info.type() << endl;
1083
1084     Pathname base = solv_path_for_repoinfo( _options, info);
1085
1086     if( filesystem::assert_dir(base) )
1087     {
1088       Exception ex(str::form( _("Can't create %s"), base.c_str()) );
1089       ZYPP_THROW(ex);
1090     }
1091
1092     if( ! PathInfo(base).userMayW() )
1093     {
1094       Exception ex(str::form( _("Can't create cache at %s - no writing permissions."), base.c_str()) );
1095       ZYPP_THROW(ex);
1096     }
1097     Pathname solvfile = base / "solv";
1098
1099     // do we have type?
1100     repo::RepoType repokind = info.type();
1101
1102     // if the type is unknown, try probing.
1103     switch ( repokind.toEnum() )
1104     {
1105       case RepoType::NONE_e:
1106         // unknown, probe the local metadata
1107         repokind = probe( productdatapath.asUrl() );
1108       break;
1109       default:
1110       break;
1111     }
1112
1113     MIL << "repo type is " << repokind << endl;
1114
1115     switch ( repokind.toEnum() )
1116     {
1117       case RepoType::RPMMD_e :
1118       case RepoType::YAST2_e :
1119       case RepoType::RPMPLAINDIR_e :
1120       {
1121         // Take care we unlink the solvfile on exception
1122         ManagedFile guard( solvfile, filesystem::unlink );
1123         scoped_ptr<MediaMounter> forPlainDirs;
1124
1125         ExternalProgram::Arguments cmd;
1126         cmd.push_back( "repo2solv.sh" );
1127         // repo2solv expects -o as 1st arg!
1128         cmd.push_back( "-o" );
1129         cmd.push_back( solvfile.asString() );
1130         cmd.push_back( "-X" );  // autogenerate pattern from pattern-package
1131
1132         if ( repokind == RepoType::RPMPLAINDIR )
1133         {
1134           forPlainDirs.reset( new MediaMounter( *info.baseUrlsBegin() ) );
1135           // recusive for plaindir as 2nd arg!
1136           cmd.push_back( "-R" );
1137           // FIXME this does only work form dir: URLs
1138           cmd.push_back( forPlainDirs->getPathName( info.path() ).c_str() );
1139         }
1140         else
1141           cmd.push_back( productdatapath.asString() );
1142
1143         ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
1144         std::string errdetail;
1145
1146         for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1147           WAR << "  " << output;
1148           if ( errdetail.empty() ) {
1149             errdetail = prog.command();
1150             errdetail += '\n';
1151           }
1152           errdetail += output;
1153         }
1154
1155         int ret = prog.close();
1156         if ( ret != 0 )
1157         {
1158           RepoException ex(str::form( _("Failed to cache repo (%d)."), ret ));
1159           ex.remember( errdetail );
1160           ZYPP_THROW(ex);
1161         }
1162
1163         // We keep it.
1164         guard.resetDispose();
1165       }
1166       break;
1167       default:
1168         ZYPP_THROW(RepoUnknownTypeException( _("Unhandled repository type") ));
1169       break;
1170     }
1171     // update timestamp and checksum
1172     setCacheStatus(info, raw_metadata_status);
1173     MIL << "Commit cache.." << endl;
1174     progress.toMax();
1175   }
1176
1177   ////////////////////////////////////////////////////////////////////////////
1178
1179   repo::RepoType RepoManager::Impl::probe( const Url & url, const Pathname & path  ) const
1180   {
1181     MIL << "going to probe the repo type at " << url << " (" << path << ")" << endl;
1182
1183     if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName()/path ).isDir() )
1184     {
1185       // Handle non existing local directory in advance, as
1186       // MediaSetAccess does not support it.
1187       MIL << "Probed type NONE (not exists) at " << url << " (" << path << ")" << endl;
1188       return repo::RepoType::NONE;
1189     }
1190
1191     // prepare exception to be thrown if the type could not be determined
1192     // due to a media exception. We can't throw right away, because of some
1193     // problems with proxy servers returning an incorrect error
1194     // on ftp file-not-found(bnc #335906). Instead we'll check another types
1195     // before throwing.
1196
1197     // TranslatorExplanation '%s' is an URL
1198     RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
1199     bool gotMediaException = false;
1200     try
1201     {
1202       MediaSetAccess access(url);
1203       try
1204       {
1205         if ( access.doesFileExist(path/"/repodata/repomd.xml") )
1206         {
1207           MIL << "Probed type RPMMD at " << url << " (" << path << ")" << endl;
1208           return repo::RepoType::RPMMD;
1209         }
1210       }
1211       catch ( const media::MediaException &e )
1212       {
1213         ZYPP_CAUGHT(e);
1214         DBG << "problem checking for repodata/repomd.xml file" << endl;
1215         enew.remember(e);
1216         gotMediaException = true;
1217       }
1218
1219       try
1220       {
1221         if ( access.doesFileExist(path/"/content") )
1222         {
1223           MIL << "Probed type YAST2 at " << url << " (" << path << ")" << endl;
1224           return repo::RepoType::YAST2;
1225         }
1226       }
1227       catch ( const media::MediaException &e )
1228       {
1229         ZYPP_CAUGHT(e);
1230         DBG << "problem checking for content file" << endl;
1231         enew.remember(e);
1232         gotMediaException = true;
1233       }
1234
1235       // if it is a non-downloading URL denoting a directory
1236       if ( ! url.schemeIsDownloading() )
1237       {
1238         MediaMounter media( url );
1239         if ( PathInfo(media.getPathName()/path).isDir() )
1240         {
1241           // allow empty dirs for now
1242           MIL << "Probed type RPMPLAINDIR at " << url << " (" << path << ")" << endl;
1243           return repo::RepoType::RPMPLAINDIR;
1244         }
1245       }
1246     }
1247     catch ( const Exception &e )
1248     {
1249       ZYPP_CAUGHT(e);
1250       // TranslatorExplanation '%s' is an URL
1251       Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
1252       enew.remember(e);
1253       ZYPP_THROW(enew);
1254     }
1255
1256     if (gotMediaException)
1257       ZYPP_THROW(enew);
1258
1259     MIL << "Probed type NONE at " << url << " (" << path << ")" << endl;
1260     return repo::RepoType::NONE;
1261   }
1262
1263   ////////////////////////////////////////////////////////////////////////////
1264
1265   void RepoManager::Impl::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
1266   {
1267     MIL << "Going to clean up garbage in cache dirs" << endl;
1268
1269     ProgressData progress(300);
1270     progress.sendTo(progressrcv);
1271     progress.toMin();
1272
1273     std::list<Pathname> cachedirs;
1274     cachedirs.push_back(_options.repoRawCachePath);
1275     cachedirs.push_back(_options.repoPackagesCachePath);
1276     cachedirs.push_back(_options.repoSolvCachePath);
1277
1278     for_( dir, cachedirs.begin(), cachedirs.end() )
1279     {
1280       if ( PathInfo(*dir).isExist() )
1281       {
1282         std::list<Pathname> entries;
1283         if ( filesystem::readdir( entries, *dir, false ) != 0 )
1284           // TranslatorExplanation '%s' is a pathname
1285           ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir->c_str())));
1286
1287         unsigned sdircount   = entries.size();
1288         unsigned sdircurrent = 1;
1289         for_( subdir, entries.begin(), entries.end() )
1290         {
1291           // if it does not belong known repo, make it disappear
1292           bool found = false;
1293           for_( r, repoBegin(), repoEnd() )
1294             if ( subdir->basename() == r->escaped_alias() )
1295             { found = true; break; }
1296
1297           if ( ! found && ( Date::now()-PathInfo(*subdir).mtime() > Date::day ) )
1298             filesystem::recursive_rmdir( *subdir );
1299
1300           progress.set( progress.val() + sdircurrent * 100 / sdircount );
1301           ++sdircurrent;
1302         }
1303       }
1304       else
1305         progress.set( progress.val() + 100 );
1306     }
1307     progress.toMax();
1308   }
1309
1310   ////////////////////////////////////////////////////////////////////////////
1311
1312   void RepoManager::Impl::cleanCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1313   {
1314     ProgressData progress(100);
1315     progress.sendTo(progressrcv);
1316     progress.toMin();
1317
1318     MIL << "Removing raw metadata cache for " << info.alias() << endl;
1319     filesystem::recursive_rmdir(solv_path_for_repoinfo(_options, info));
1320
1321     progress.toMax();
1322   }
1323
1324   ////////////////////////////////////////////////////////////////////////////
1325
1326   void RepoManager::Impl::loadFromCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1327   {
1328     assert_alias(info);
1329     Pathname solvfile = solv_path_for_repoinfo(_options, info) / "solv";
1330
1331     if ( ! PathInfo(solvfile).isExist() )
1332       ZYPP_THROW(RepoNotCachedException(info));
1333
1334     sat::Pool::instance().reposErase( info.alias() );
1335     try
1336     {
1337       Repository repo = sat::Pool::instance().addRepoSolv( solvfile, info );
1338       // test toolversion in order to rebuild solv file in case
1339       // it was written by an old libsolv-tool parser.
1340       //
1341       // Known version strings used:
1342       //  - <no string>
1343       //  - "1.0"
1344       //
1345       sat::LookupRepoAttr toolversion( sat::SolvAttr::repositoryToolVersion, repo );
1346       if ( toolversion.begin().asString().empty() )
1347       {
1348         repo.eraseFromPool();
1349         ZYPP_THROW(Exception("Solv-file was created by old parser."));
1350       }
1351       // else: up-to-date (or even newer).
1352     }
1353     catch ( const Exception & exp )
1354     {
1355       ZYPP_CAUGHT( exp );
1356       MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1357       cleanCache( info, progressrcv );
1358       buildCache( info, BuildIfNeeded, progressrcv );
1359
1360       sat::Pool::instance().addRepoSolv( solvfile, info );
1361     }
1362   }
1363
1364   ////////////////////////////////////////////////////////////////////////////
1365
1366   void RepoManager::Impl::addRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1367   {
1368     assert_alias(info);
1369
1370     ProgressData progress(100);
1371     callback::SendReport<ProgressReport> report;
1372     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1373     progress.name(str::form(_("Adding repository '%s'"), info.label().c_str()));
1374     progress.toMin();
1375
1376     MIL << "Try adding repo " << info << endl;
1377
1378     RepoInfo tosave = info;
1379     if ( _repos.find(tosave) != _repos.end() )
1380       ZYPP_THROW(RepoAlreadyExistsException(info));
1381
1382     // check the first url for now
1383     if ( _options.probe )
1384     {
1385       DBG << "unknown repository type, probing" << endl;
1386
1387       RepoType probedtype;
1388       probedtype = probe( *tosave.baseUrlsBegin(), info.path() );
1389       if ( tosave.baseUrlsSize() > 0 )
1390       {
1391         if ( probedtype == RepoType::NONE )
1392           ZYPP_THROW(RepoUnknownTypeException());
1393         else
1394           tosave.setType(probedtype);
1395       }
1396     }
1397
1398     progress.set(50);
1399
1400     // assert the directory exists
1401     filesystem::assert_dir(_options.knownReposPath);
1402
1403     Pathname repofile = generateNonExistingName(
1404         _options.knownReposPath, generateFilename(tosave));
1405     // now we have a filename that does not exists
1406     MIL << "Saving repo in " << repofile << endl;
1407
1408     std::ofstream file(repofile.c_str());
1409     if (!file)
1410     {
1411       // TranslatorExplanation '%s' is a filename
1412       ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1413     }
1414
1415     tosave.dumpAsIniOn(file);
1416     tosave.setFilepath(repofile);
1417     tosave.setMetadataPath( metadataPath( tosave ) );
1418     tosave.setPackagesPath( packagesPath( tosave ) );
1419     {
1420       // We chould fix the API as we must injet those paths
1421       // into the repoinfo in order to keep it usable.
1422       RepoInfo & oinfo( const_cast<RepoInfo &>(info) );
1423       oinfo.setMetadataPath( metadataPath( tosave ) );
1424       oinfo.setPackagesPath( packagesPath( tosave ) );
1425     }
1426     _repos.insert(tosave);
1427
1428     progress.set(90);
1429
1430     // check for credentials in Urls
1431     bool havePasswords = false;
1432     for_( urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd() )
1433       if ( urlit->hasCredentialsInAuthority() )
1434       {
1435         havePasswords = true;
1436         break;
1437       }
1438     // save the credentials
1439     if ( havePasswords )
1440     {
1441       media::CredentialManager cm(
1442           media::CredManagerOptions(_options.rootDir) );
1443
1444       for_(urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd())
1445         if (urlit->hasCredentialsInAuthority())
1446           //! \todo use a method calling UI callbacks to ask where to save creds?
1447           cm.saveInUser(media::AuthData(*urlit));
1448     }
1449
1450     HistoryLog().addRepository(tosave);
1451
1452     progress.toMax();
1453     MIL << "done" << endl;
1454   }
1455
1456
1457   void RepoManager::Impl::addRepositories( const Url & url, const ProgressData::ReceiverFnc & progressrcv )
1458   {
1459     std::list<RepoInfo> repos = readRepoFile(url);
1460     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1461           it != repos.end();
1462           ++it )
1463     {
1464       // look if the alias is in the known repos.
1465       for_ ( kit, repoBegin(), repoEnd() )
1466       {
1467         if ( (*it).alias() == (*kit).alias() )
1468         {
1469           ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1470           ZYPP_THROW(RepoAlreadyExistsException(*it));
1471         }
1472       }
1473     }
1474
1475     std::string filename = Pathname(url.getPathName()).basename();
1476
1477     if ( filename == Pathname() )
1478     {
1479       // TranslatorExplanation '%s' is an URL
1480       ZYPP_THROW(RepoException(str::form( _("Invalid repo file name at '%s'"), url.asString().c_str() )));
1481     }
1482
1483     // assert the directory exists
1484     filesystem::assert_dir(_options.knownReposPath);
1485
1486     Pathname repofile = generateNonExistingName(_options.knownReposPath, filename);
1487     // now we have a filename that does not exists
1488     MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1489
1490     std::ofstream file(repofile.c_str());
1491     if (!file)
1492     {
1493       // TranslatorExplanation '%s' is a filename
1494       ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1495     }
1496
1497     for ( std::list<RepoInfo>::iterator it = repos.begin();
1498           it != repos.end();
1499           ++it )
1500     {
1501       MIL << "Saving " << (*it).alias() << endl;
1502       it->setFilepath(repofile.asString());
1503       it->dumpAsIniOn(file);
1504       _repos.insert(*it);
1505
1506       HistoryLog(_options.rootDir).addRepository(*it);
1507     }
1508
1509     MIL << "done" << endl;
1510   }
1511
1512   ////////////////////////////////////////////////////////////////////////////
1513
1514   void RepoManager::Impl::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1515   {
1516     ProgressData progress;
1517     callback::SendReport<ProgressReport> report;
1518     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1519     progress.name(str::form(_("Removing repository '%s'"), info.label().c_str()));
1520
1521     MIL << "Going to delete repo " << info.alias() << endl;
1522
1523     for_( it, repoBegin(), repoEnd() )
1524     {
1525       // they can be the same only if the provided is empty, that means
1526       // the provided repo has no alias
1527       // then skip
1528       if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1529         continue;
1530
1531       // TODO match by url
1532
1533       // we have a matcing repository, now we need to know
1534       // where it does come from.
1535       RepoInfo todelete = *it;
1536       if (todelete.filepath().empty())
1537       {
1538         ZYPP_THROW(RepoException( _("Can't figure out where the repo is stored.") ));
1539       }
1540       else
1541       {
1542         // figure how many repos are there in the file:
1543         std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1544         if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1545         {
1546           // easy, only this one, just delete the file
1547           if ( filesystem::unlink(todelete.filepath()) != 0 )
1548           {
1549             // TranslatorExplanation '%s' is a filename
1550             ZYPP_THROW(RepoException(str::form( _("Can't delete '%s'"), todelete.filepath().c_str() )));
1551           }
1552           MIL << todelete.alias() << " sucessfully deleted." << endl;
1553         }
1554         else
1555         {
1556           // there are more repos in the same file
1557           // write them back except the deleted one.
1558           //TmpFile tmp;
1559           //std::ofstream file(tmp.path().c_str());
1560
1561           // assert the directory exists
1562           filesystem::assert_dir(todelete.filepath().dirname());
1563
1564           std::ofstream file(todelete.filepath().c_str());
1565           if (!file)
1566           {
1567             // TranslatorExplanation '%s' is a filename
1568             ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), todelete.filepath().c_str() )));
1569           }
1570           for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1571                 fit != filerepos.end();
1572                 ++fit )
1573           {
1574             if ( (*fit).alias() != todelete.alias() )
1575               (*fit).dumpAsIniOn(file);
1576           }
1577         }
1578
1579         CombinedProgressData cSubprogrcv(progress, 20);
1580         CombinedProgressData mSubprogrcv(progress, 40);
1581         CombinedProgressData pSubprogrcv(progress, 40);
1582         // now delete it from cache
1583         if ( isCached(todelete) )
1584           cleanCache( todelete, cSubprogrcv);
1585         // now delete metadata (#301037)
1586         cleanMetadata( todelete, mSubprogrcv );
1587         cleanPackages( todelete, pSubprogrcv );
1588         _repos.erase(todelete);
1589         MIL << todelete.alias() << " sucessfully deleted." << endl;
1590         HistoryLog(_options.rootDir).removeRepository(todelete);
1591         return;
1592       } // else filepath is empty
1593
1594     }
1595     // should not be reached on a sucess workflow
1596     ZYPP_THROW(RepoNotFoundException(info));
1597   }
1598
1599   ////////////////////////////////////////////////////////////////////////////
1600
1601   void RepoManager::Impl::modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, const ProgressData::ReceiverFnc & progressrcv )
1602   {
1603     RepoInfo toedit = getRepositoryInfo(alias);
1604     RepoInfo newinfo( newinfo_r ); // need writable copy to upadte housekeeping data
1605
1606     // check if the new alias already exists when renaming the repo
1607     if ( alias != newinfo.alias() && hasRepo( newinfo.alias() ) )
1608     {
1609       ZYPP_THROW(RepoAlreadyExistsException(newinfo));
1610     }
1611
1612     if (toedit.filepath().empty())
1613     {
1614       ZYPP_THROW(RepoException( _("Can't figure out where the repo is stored.") ));
1615     }
1616     else
1617     {
1618       // figure how many repos are there in the file:
1619       std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1620
1621       // there are more repos in the same file
1622       // write them back except the deleted one.
1623       //TmpFile tmp;
1624       //std::ofstream file(tmp.path().c_str());
1625
1626       // assert the directory exists
1627       filesystem::assert_dir(toedit.filepath().dirname());
1628
1629       std::ofstream file(toedit.filepath().c_str());
1630       if (!file)
1631       {
1632         // TranslatorExplanation '%s' is a filename
1633         ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), toedit.filepath().c_str() )));
1634       }
1635       for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1636             fit != filerepos.end();
1637             ++fit )
1638       {
1639           // if the alias is different, dump the original
1640           // if it is the same, dump the provided one
1641           if ( (*fit).alias() != toedit.alias() )
1642             (*fit).dumpAsIniOn(file);
1643           else
1644             newinfo.dumpAsIniOn(file);
1645       }
1646
1647       newinfo.setFilepath(toedit.filepath());
1648       _repos.erase(toedit);
1649       _repos.insert(newinfo);
1650       HistoryLog(_options.rootDir).modifyRepository(toedit, newinfo);
1651       MIL << "repo " << alias << " modified" << endl;
1652     }
1653   }
1654
1655   ////////////////////////////////////////////////////////////////////////////
1656
1657   RepoInfo RepoManager::Impl::getRepositoryInfo( const std::string & alias, const ProgressData::ReceiverFnc & progressrcv )
1658   {
1659     RepoConstIterator it( findAlias( alias, _repos ) );
1660     if ( it != _repos.end() )
1661       return *it;
1662     RepoInfo info;
1663     info.setAlias( alias );
1664     ZYPP_THROW( RepoNotFoundException(info) );
1665   }
1666
1667
1668   RepoInfo RepoManager::Impl::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
1669   {
1670     for_( it, repoBegin(), repoEnd() )
1671     {
1672       for_( urlit, (*it).baseUrlsBegin(), (*it).baseUrlsEnd() )
1673       {
1674         if ( (*urlit).asString(urlview) == url.asString(urlview) )
1675           return *it;
1676       }
1677     }
1678     RepoInfo info;
1679     info.setBaseUrl( url );
1680     ZYPP_THROW( RepoNotFoundException(info) );
1681   }
1682
1683   ////////////////////////////////////////////////////////////////////////////
1684   //
1685   // Services
1686   //
1687   ////////////////////////////////////////////////////////////////////////////
1688
1689   void RepoManager::Impl::addService( const ServiceInfo & service )
1690   {
1691     assert_alias( service );
1692
1693     // check if service already exists
1694     if ( hasService( service.alias() ) )
1695       ZYPP_THROW( ServiceAlreadyExistsException( service ) );
1696
1697     // Writable ServiceInfo is needed to save the location
1698     // of the .service file. Finaly insert into the service list.
1699     ServiceInfo toSave( service );
1700     saveService( toSave );
1701     _services.insert( toSave );
1702
1703     // check for credentials in Url (username:password, not ?credentials param)
1704     if ( toSave.url().hasCredentialsInAuthority() )
1705     {
1706       media::CredentialManager cm(
1707           media::CredManagerOptions(_options.rootDir) );
1708
1709       //! \todo use a method calling UI callbacks to ask where to save creds?
1710       cm.saveInUser(media::AuthData(toSave.url()));
1711     }
1712
1713     MIL << "added service " << toSave.alias() << endl;
1714   }
1715
1716   ////////////////////////////////////////////////////////////////////////////
1717
1718   void RepoManager::Impl::removeService( const std::string & alias )
1719   {
1720     MIL << "Going to delete repo " << alias << endl;
1721
1722     const ServiceInfo & service = getService( alias );
1723
1724     Pathname location = service.filepath();
1725     if( location.empty() )
1726     {
1727       ZYPP_THROW(RepoException( _("Can't figure out where the service is stored.") ));
1728     }
1729
1730     ServiceSet tmpSet;
1731     parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1732
1733     // only one service definition in the file
1734     if ( tmpSet.size() == 1 )
1735     {
1736       if ( filesystem::unlink(location) != 0 )
1737       {
1738         // TranslatorExplanation '%s' is a filename
1739         ZYPP_THROW(RepoException(str::form( _("Can't delete '%s'"), location.c_str() )));
1740       }
1741       MIL << alias << " sucessfully deleted." << endl;
1742     }
1743     else
1744     {
1745       filesystem::assert_dir(location.dirname());
1746
1747       std::ofstream file(location.c_str());
1748       if( !file )
1749       {
1750         // TranslatorExplanation '%s' is a filename
1751         ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), location.c_str() )));
1752       }
1753
1754       for_(it, tmpSet.begin(), tmpSet.end())
1755       {
1756         if( it->alias() != alias )
1757           it->dumpAsIniOn(file);
1758       }
1759
1760       MIL << alias << " sucessfully deleted from file " << location <<  endl;
1761     }
1762
1763     // now remove all repositories added by this service
1764     RepoCollector rcollector;
1765     getRepositoriesInService( alias,
1766                               boost::make_function_output_iterator( bind( &RepoCollector::collect, &rcollector, _1 ) ) );
1767     // cannot do this directly in getRepositoriesInService - would invalidate iterators
1768     for_(rit, rcollector.repos.begin(), rcollector.repos.end())
1769       removeRepository(*rit);
1770   }
1771
1772   ////////////////////////////////////////////////////////////////////////////
1773
1774   void RepoManager::Impl::refreshServices()
1775   {
1776     // copy the set of services since refreshService
1777     // can eventually invalidate the iterator
1778     ServiceSet services( serviceBegin(), serviceEnd() );
1779     for_( it, services.begin(), services.end() )
1780     {
1781       if ( !it->enabled() )
1782         continue;
1783
1784       try {
1785         refreshService(*it);
1786       }
1787       catch ( const repo::ServicePluginInformalException & e )
1788       { ;/* ignore ServicePluginInformalException */ }
1789     }
1790   }
1791
1792   void RepoManager::Impl::refreshService( const std::string & alias )
1793   {
1794     ServiceInfo service( getService( alias ) );
1795     assert_alias( service );
1796     assert_url( service );
1797     // NOTE: It might be necessary to modify and rewrite the service info.
1798     // Either when probing the type, or when adjusting the repositories
1799     // enable/disable state.:
1800     bool serviceModified = false;
1801     MIL << "Going to refresh service '" << service.alias() << "', url: "<< service.url() << endl;
1802
1803     //! \todo add callbacks for apps (start, end, repo removed, repo added, repo changed)
1804
1805     // if the type is unknown, try probing.
1806     if ( service.type() == repo::ServiceType::NONE )
1807     {
1808       repo::ServiceType type = probeService( service.url() );
1809       if ( type != ServiceType::NONE )
1810       {
1811         service.setProbedType( type ); // lazy init!
1812         serviceModified = true;
1813       }
1814     }
1815
1816     // get target distro identifier
1817     std::string servicesTargetDistro = _options.servicesTargetDistro;
1818     if ( servicesTargetDistro.empty() )
1819     {
1820       servicesTargetDistro = Target::targetDistribution( Pathname() );
1821     }
1822     DBG << "ServicesTargetDistro: " << servicesTargetDistro << endl;
1823
1824     // parse it
1825     RepoCollector collector(servicesTargetDistro);
1826     // FIXME Ugly hack: ServiceRepos may throw ServicePluginInformalException
1827     // which is actually a notification. Using an exception for this
1828     // instead of signal/callback is bad. Needs to be fixed here, in refreshServices()
1829     // and in zypper.
1830     std::pair<DefaultIntegral<bool,false>, repo::ServicePluginInformalException> uglyHack;
1831     try {
1832       ServiceRepos repos(service, bind( &RepoCollector::collect, &collector, _1 ));
1833     }
1834     catch ( const repo::ServicePluginInformalException & e )
1835     {
1836       /* ignore ServicePluginInformalException and throw later */
1837       uglyHack.first = true;
1838       uglyHack.second = e;
1839     }
1840
1841     // set service alias and base url for all collected repositories
1842     for_( it, collector.repos.begin(), collector.repos.end() )
1843     {
1844       // if the repo url was not set by the repoindex parser, set service's url
1845       Url url;
1846
1847       if ( it->baseUrlsEmpty() )
1848         url = service.url();
1849       else
1850       {
1851         // service repo can contain only one URL now, so no need to iterate.
1852         url = *it->baseUrlsBegin();
1853       }
1854
1855       // libzypp currently has problem with separate url + path handling
1856       // so just append the path to the baseurl
1857       if ( !it->path().empty() )
1858       {
1859         Pathname path(url.getPathName());
1860         path /= it->path();
1861         url.setPathName( path.asString() );
1862         it->setPath("");
1863       }
1864
1865       // Prepend service alias:
1866       it->setAlias( str::form( "%s:%s", service.alias().c_str(), it->alias().c_str() ) );
1867
1868       // save the url
1869       it->setBaseUrl( url );
1870       // set refrence to the parent service
1871       it->setService( service.alias() );
1872     }
1873
1874     ////////////////////////////////////////////////////////////////////////////
1875     // Now compare collected repos with the ones in the system...
1876     //
1877     RepoInfoList oldRepos;
1878     getRepositoriesInService( service.alias(), std::back_inserter( oldRepos ) );
1879
1880     // find old repositories to remove...
1881     for_( it, oldRepos.begin(), oldRepos.end() )
1882     {
1883       if ( ! foundAliasIn( it->alias(), collector.repos ) )
1884       {
1885         if ( it->enabled() && ! service.repoToDisableFind( it->alias() ) )
1886         {
1887           DBG << "Service removes enabled repo " << it->alias() << endl;
1888           service.addRepoToEnable( it->alias() );
1889           serviceModified = true;
1890         }
1891         else
1892         {
1893           DBG << "Service removes disabled repo " << it->alias() << endl;
1894         }
1895         removeRepository( *it );
1896       }
1897     }
1898
1899     ////////////////////////////////////////////////////////////////////////////
1900     // create missing repositories and modify exising ones if needed...
1901     for_( it, collector.repos.begin(), collector.repos.end() )
1902     {
1903       // Service explicitly requests the repo being enabled?
1904       // Service explicitly requests the repo being disabled?
1905       // And hopefully not both ;) If so, enable wins.
1906       bool beEnabled = service.repoToEnableFind( it->alias() );
1907       bool beDisabled = service.repoToDisableFind( it->alias() );
1908
1909       // Make sure the service repo is created with the
1910       // appropriate enable
1911       if ( beEnabled ) it->setEnabled(true);
1912       if ( beDisabled ) it->setEnabled(false);
1913
1914       if ( beEnabled )
1915       {
1916         // Remove from enable request list.
1917         // NOTE: repoToDisable is handled differently.
1918         //       It gets cleared on each refresh.
1919         service.delRepoToEnable( it->alias() );
1920         serviceModified = true;
1921       }
1922
1923       RepoInfoList::iterator oldRepo( findAlias( it->alias(), oldRepos ) );
1924       if ( oldRepo == oldRepos.end() )
1925       {
1926         // Not found in oldRepos ==> a new repo to add
1927
1928         // At that point check whether a repo with the same alias
1929         // exists outside this service. Maybe forcefully re-alias
1930         // the existing repo?
1931         DBG << "Service adds repo " << it->alias() << " " << (it->enabled()?"enabled":"disabled") << endl;
1932         addRepository( *it );
1933
1934         // save repo credentials
1935         // ma@: task for modifyRepository?
1936       }
1937       else
1938       {
1939         // ==> an exising repo to check
1940         bool oldRepoModified = false;
1941
1942         // changed enable?
1943         if ( beEnabled )
1944         {
1945           if ( ! oldRepo->enabled() )
1946           {
1947             DBG << "Service repo " << it->alias() << " gets enabled" << endl;
1948             oldRepo->setEnabled( true );
1949             oldRepoModified = true;
1950           }
1951           else
1952           {
1953             DBG << "Service repo " << it->alias() << " stays enabled" << endl;
1954           }
1955         }
1956         else if ( beDisabled )
1957         {
1958           if ( oldRepo->enabled() )
1959           {
1960             DBG << "Service repo " << it->alias() << " gets disabled" << endl;
1961             oldRepo->setEnabled( false );
1962             oldRepoModified = true;
1963           }
1964           else
1965           {
1966             DBG << "Service repo " << it->alias() << " stays disabled" << endl;
1967           }
1968         }
1969         else
1970         {
1971           DBG << "Service repo " << it->alias() << " stays " <<  (oldRepo->enabled()?"enabled":"disabled") << endl;
1972         }
1973
1974         // changed url?
1975         // service repo can contain only one URL now, so no need to iterate.
1976         if ( oldRepo->url() != it->url() )
1977         {
1978           DBG << "Service repo " << it->alias() << " gets new URL " << it->url() << endl;
1979           oldRepo->setBaseUrl( it->url() );
1980           oldRepoModified = true;
1981         }
1982
1983         // save if modified:
1984         if ( oldRepoModified )
1985         {
1986           modifyRepository( oldRepo->alias(), *oldRepo );
1987         }
1988       }
1989     }
1990
1991     // Unlike reposToEnable, reposToDisable is always cleared after refresh.
1992     if ( ! service.reposToDisableEmpty() )
1993     {
1994       service.clearReposToDisable();
1995       serviceModified = true;
1996     }
1997
1998     ////////////////////////////////////////////////////////////////////////////
1999     // save service if modified:
2000     if ( serviceModified )
2001     {
2002       // write out modified service file.
2003       modifyService( service.alias(), service );
2004     }
2005
2006     if ( uglyHack.first )
2007     {
2008       throw( uglyHack.second ); // intentionally not ZYPP_THROW
2009     }
2010   }
2011
2012   ////////////////////////////////////////////////////////////////////////////
2013
2014   void RepoManager::Impl::modifyService( const std::string & oldAlias, const ServiceInfo & newService )
2015   {
2016     MIL << "Going to modify service " << oldAlias << endl;
2017
2018     // we need a writable copy to link it to the file where
2019     // it is saved if we modify it
2020     ServiceInfo service(newService);
2021
2022     if ( service.type() == ServiceType::PLUGIN )
2023     {
2024         MIL << "Not modifying plugin service '" << oldAlias << "'" << endl;
2025         return;
2026     }
2027
2028     const ServiceInfo & oldService = getService(oldAlias);
2029
2030     Pathname location = oldService.filepath();
2031     if( location.empty() )
2032     {
2033       ZYPP_THROW(RepoException( _("Can't figure out where the service is stored.") ));
2034     }
2035
2036     // remember: there may multiple services being defined in one file:
2037     ServiceSet tmpSet;
2038     parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
2039
2040     filesystem::assert_dir(location.dirname());
2041     std::ofstream file(location.c_str());
2042     for_(it, tmpSet.begin(), tmpSet.end())
2043     {
2044       if( *it != oldAlias )
2045         it->dumpAsIniOn(file);
2046     }
2047     service.dumpAsIniOn(file);
2048     file.close();
2049     service.setFilepath(location);
2050
2051     _services.erase(oldAlias);
2052     _services.insert(service);
2053
2054     // changed properties affecting also repositories
2055     if( oldAlias != service.alias()                    // changed alias
2056         || oldService.enabled() != service.enabled()   // changed enabled status
2057       )
2058     {
2059       std::vector<RepoInfo> toModify;
2060       getRepositoriesInService(oldAlias, std::back_inserter(toModify));
2061       for_( it, toModify.begin(), toModify.end() )
2062       {
2063         if (oldService.enabled() && !service.enabled())
2064           it->setEnabled(false);
2065         else if (!oldService.enabled() && service.enabled())
2066         {
2067           //! \todo do nothing? the repos will be enabled on service refresh
2068           //! \todo how to know the service needs a (auto) refresh????
2069         }
2070         else
2071           it->setService(service.alias());
2072         modifyRepository(it->alias(), *it);
2073       }
2074     }
2075
2076     //! \todo refresh the service automatically if url is changed?
2077   }
2078
2079   ////////////////////////////////////////////////////////////////////////////
2080
2081   repo::ServiceType RepoManager::Impl::probeService( const Url & url ) const
2082   {
2083     try
2084     {
2085       MediaSetAccess access(url);
2086       if ( access.doesFileExist("/repo/repoindex.xml") )
2087         return repo::ServiceType::RIS;
2088     }
2089     catch ( const media::MediaException &e )
2090     {
2091       ZYPP_CAUGHT(e);
2092       // TranslatorExplanation '%s' is an URL
2093       RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
2094       enew.remember(e);
2095       ZYPP_THROW(enew);
2096     }
2097     catch ( const Exception &e )
2098     {
2099       ZYPP_CAUGHT(e);
2100       // TranslatorExplanation '%s' is an URL
2101       Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
2102       enew.remember(e);
2103       ZYPP_THROW(enew);
2104     }
2105
2106     return repo::ServiceType::NONE;
2107   }
2108
2109   ///////////////////////////////////////////////////////////////////
2110   //
2111   //    CLASS NAME : RepoManager
2112   //
2113   ///////////////////////////////////////////////////////////////////
2114
2115   RepoManager::RepoManager( const RepoManagerOptions & opt )
2116   : _pimpl( new Impl(opt) )
2117   {}
2118
2119   RepoManager::~RepoManager()
2120   {}
2121
2122   bool RepoManager::repoEmpty() const
2123   { return _pimpl->repoEmpty(); }
2124
2125   RepoManager::RepoSizeType RepoManager::repoSize() const
2126   { return _pimpl->repoSize(); }
2127
2128   RepoManager::RepoConstIterator RepoManager::repoBegin() const
2129   { return _pimpl->repoBegin(); }
2130
2131   RepoManager::RepoConstIterator RepoManager::repoEnd() const
2132   { return _pimpl->repoEnd(); }
2133
2134   RepoInfo RepoManager::getRepo( const std::string & alias ) const
2135   { return _pimpl->getRepo( alias ); }
2136
2137   bool RepoManager::hasRepo( const std::string & alias ) const
2138   { return _pimpl->hasRepo( alias ); }
2139
2140   std::string RepoManager::makeStupidAlias( const Url & url_r )
2141   {
2142     std::string ret( url_r.getScheme() );
2143     if ( ret.empty() )
2144       ret = "repo-";
2145     else
2146       ret += "-";
2147
2148     std::string host( url_r.getHost() );
2149     if ( ! host.empty() )
2150     {
2151       ret += host;
2152       ret += "-";
2153     }
2154
2155     static Date::ValueType serial = Date::now();
2156     ret += Digest::digest( Digest::sha1(), str::hexstring( ++serial ) +url_r.asCompleteString() ).substr(0,8);
2157     return ret;
2158   }
2159
2160   RepoStatus RepoManager::metadataStatus( const RepoInfo & info ) const
2161   { return _pimpl->metadataStatus( info ); }
2162
2163   RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata( const RepoInfo &info, const Url &url, RawMetadataRefreshPolicy policy )
2164   { return _pimpl->checkIfToRefreshMetadata( info, url, policy ); }
2165
2166   Pathname RepoManager::metadataPath( const RepoInfo &info ) const
2167   { return _pimpl->metadataPath( info ); }
2168
2169   Pathname RepoManager::packagesPath( const RepoInfo &info ) const
2170   { return _pimpl->packagesPath( info ); }
2171
2172   void RepoManager::refreshMetadata( const RepoInfo &info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2173   { return _pimpl->refreshMetadata( info, policy, progressrcv ); }
2174
2175   void RepoManager::cleanMetadata( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2176   { return _pimpl->cleanMetadata( info, progressrcv ); }
2177
2178   void RepoManager::cleanPackages( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2179   { return _pimpl->cleanPackages( info, progressrcv ); }
2180
2181   RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
2182   { return _pimpl->cacheStatus( info ); }
2183
2184   void RepoManager::buildCache( const RepoInfo &info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2185   { return _pimpl->buildCache( info, policy, progressrcv ); }
2186
2187   void RepoManager::cleanCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2188   { return _pimpl->cleanCache( info, progressrcv ); }
2189
2190   bool RepoManager::isCached( const RepoInfo &info ) const
2191   { return _pimpl->isCached( info ); }
2192
2193   void RepoManager::loadFromCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2194   { return _pimpl->loadFromCache( info, progressrcv ); }
2195
2196   void RepoManager::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
2197   { return _pimpl->cleanCacheDirGarbage( progressrcv ); }
2198
2199   repo::RepoType RepoManager::probe( const Url & url, const Pathname & path ) const
2200   { return _pimpl->probe( url, path ); }
2201
2202   repo::RepoType RepoManager::probe( const Url & url ) const
2203   { return _pimpl->probe( url ); }
2204
2205   void RepoManager::addRepository( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2206   { return _pimpl->addRepository( info, progressrcv ); }
2207
2208   void RepoManager::addRepositories( const Url &url, const ProgressData::ReceiverFnc & progressrcv )
2209   { return _pimpl->addRepositories( url, progressrcv ); }
2210
2211   void RepoManager::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
2212   { return _pimpl->removeRepository( info, progressrcv ); }
2213
2214   void RepoManager::modifyRepository( const std::string &alias, const RepoInfo & newinfo, const ProgressData::ReceiverFnc & progressrcv )
2215   { return _pimpl->modifyRepository( alias, newinfo, progressrcv ); }
2216
2217   RepoInfo RepoManager::getRepositoryInfo( const std::string &alias, const ProgressData::ReceiverFnc & progressrcv )
2218   { return _pimpl->getRepositoryInfo( alias, progressrcv ); }
2219
2220   RepoInfo RepoManager::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
2221   { return _pimpl->getRepositoryInfo( url, urlview, progressrcv ); }
2222
2223   bool RepoManager::serviceEmpty() const
2224   { return _pimpl->serviceEmpty(); }
2225
2226   RepoManager::ServiceSizeType RepoManager::serviceSize() const
2227   { return _pimpl->serviceSize(); }
2228
2229   RepoManager::ServiceConstIterator RepoManager::serviceBegin() const
2230   { return _pimpl->serviceBegin(); }
2231
2232   RepoManager::ServiceConstIterator RepoManager::serviceEnd() const
2233   { return _pimpl->serviceEnd(); }
2234
2235   ServiceInfo RepoManager::getService( const std::string & alias ) const
2236   { return _pimpl->getService( alias ); }
2237
2238   bool RepoManager::hasService( const std::string & alias ) const
2239   { return _pimpl->hasService( alias ); }
2240
2241   repo::ServiceType RepoManager::probeService( const Url &url ) const
2242   { return _pimpl->probeService( url ); }
2243
2244   void RepoManager::addService( const std::string & alias, const Url& url )
2245   { return _pimpl->addService( alias, url ); }
2246
2247   void RepoManager::addService( const ServiceInfo & service )
2248   { return _pimpl->addService( service ); }
2249
2250   void RepoManager::removeService( const std::string & alias )
2251   { return _pimpl->removeService( alias ); }
2252
2253   void RepoManager::removeService( const ServiceInfo & service )
2254   { return _pimpl->removeService( service ); }
2255
2256   void RepoManager::refreshServices()
2257   { return _pimpl->refreshServices(); }
2258
2259   void RepoManager::refreshService( const std::string & alias )
2260   { return _pimpl->refreshService( alias ); }
2261
2262   void RepoManager::refreshService( const ServiceInfo & service )
2263   { return _pimpl->refreshService( service ); }
2264
2265   void RepoManager::modifyService( const std::string & oldAlias, const ServiceInfo & service )
2266   { return _pimpl->modifyService( oldAlias, service ); }
2267
2268   ////////////////////////////////////////////////////////////////////////////
2269
2270   std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
2271   { return str << *obj._pimpl; }
2272
2273   /////////////////////////////////////////////////////////////////
2274 } // namespace zypp
2275 ///////////////////////////////////////////////////////////////////