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