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