Imported Upstream version 14.34.0
[platform/upstream/libzypp.git] / zypp / RepoInfo.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/RepoInfo.cc
10  *
11 */
12 #include <iostream>
13 #include <vector>
14
15 #include "zypp/base/LogTools.h"
16 #include "zypp/base/DefaultIntegral.h"
17 #include "zypp/parser/xml/XmlEscape.h"
18
19 #include "zypp/RepoInfo.h"
20 #include "zypp/TriBool.h"
21 #include "zypp/Pathname.h"
22 #include "zypp/repo/RepoMirrorList.h"
23 #include "zypp/ExternalProgram.h"
24 #include "zypp/media/MediaAccess.h"
25
26 #include "zypp/base/IOStream.h"
27 #include "zypp/base/InputStream.h"
28 #include "zypp/parser/xml/Reader.h"
29
30 using std::endl;
31 using zypp::xml::escape;
32
33 ///////////////////////////////////////////////////////////////////
34 namespace zypp
35 { /////////////////////////////////////////////////////////////////
36
37   ///////////////////////////////////////////////////////////////////
38   //
39   //    CLASS NAME : RepoInfo::Impl
40   //
41   /** RepoInfo implementation. */
42   struct RepoInfo::Impl
43   {
44     Impl()
45       : gpgcheck(indeterminate)
46       , keeppackages(indeterminate)
47       , type(repo::RepoType::NONE_e)
48       , emptybaseurls(false)
49     {}
50
51     ~Impl()
52     {}
53
54   public:
55     static const unsigned defaultPriority = 99;
56
57     void setProbedType( const repo::RepoType & t ) const
58     {
59       if ( type == repo::RepoType::NONE
60            && t != repo::RepoType::NONE )
61       {
62         // lazy init!
63         const_cast<Impl*>(this)->type = t;
64       }
65     }
66
67   public:
68     Pathname licenseTgz() const
69     { return metadatapath.empty() ? Pathname() : metadatapath / path / "license.tar.gz"; }
70
71     Url mirrorListUrl() const
72     { return replacer(mirrorlist_url); }
73
74     void mirrorListUrl( const Url & url_r )
75     { mirrorlist_url = url_r; }
76
77     const Url & rawMirrorListUrl() const
78     { return mirrorlist_url; }
79
80     const url_set & baseUrls() const
81     {
82       if ( _baseUrls.empty() && ! mirrorListUrl().asString().empty() )
83       {
84         emptybaseurls = true;
85         DBG << "MetadataPath: " << metadatapath << endl;
86         repo::RepoMirrorList rmurls( mirrorListUrl(), metadatapath );
87         _baseUrls.insert( _baseUrls.end(), rmurls.getUrls().begin(), rmurls.getUrls().end() );
88       }
89       return _baseUrls;
90     }
91
92     url_set & baseUrls()
93     { return _baseUrls; }
94
95     bool baseurl2dump() const
96     { return !emptybaseurls && !_baseUrls.empty(); }
97
98
99     void addContent( const std::string & keyword_r )
100     { _keywords.insert( keyword_r ); }
101
102     bool hasContent( const std::string & keyword_r ) const
103     {
104       if ( _keywords.empty() && ! metadatapath.empty() )
105       {
106         // HACK directly check master index file until RepoManager offers
107         // some content probing ans zypepr uses it.
108         /////////////////////////////////////////////////////////////////
109         MIL << "Empty keywords...." << metadatapath << endl;
110         Pathname master;
111         if ( PathInfo( (master=metadatapath/"/repodata/repomd.xml") ).isFile() )
112         {
113           //MIL << "GO repomd.." << endl;
114           xml::Reader reader( master );
115           while ( reader.seekToNode( 2, "content" ) )
116           {
117             _keywords.insert( reader.nodeText().asString() );
118             reader.seekToEndNode( 2, "content" );
119           }
120           _keywords.insert( "" );       // valid content in _keywords even if empty
121         }
122         else if ( PathInfo( (master=metadatapath/"/content") ).isFile() )
123         {
124           //MIL << "GO content.." << endl;
125           iostr::forEachLine( InputStream( master ),
126                             [this]( int num_r, std::string line_r )->bool
127                             {
128                               if ( str::startsWith( line_r, "REPOKEYWORDS" ) )
129                               {
130                                 std::vector<std::string> words;
131                                 if ( str::split( line_r, std::back_inserter(words) ) > 1
132                                   && words[0].length() == 12 /*"REPOKEYWORDS"*/ )
133                                 {
134                                   this->_keywords.insert( ++words.begin(), words.end() );
135                                 }
136                                 return true; // mult. occurrances are ok.
137                               }
138                               return( ! str::startsWith( line_r, "META " ) );   // no need to parse into META section.
139                             } );
140           _keywords.insert( "" );
141         }
142         /////////////////////////////////////////////////////////////////
143       }
144       return( _keywords.find( keyword_r ) != _keywords.end() );
145
146     }
147
148   public:
149     TriBool gpgcheck;
150     TriBool keeppackages;
151     Url gpgkey_url;
152     repo::RepoType type;
153     Pathname path;
154     std::string service;
155     std::string targetDistro;
156     Pathname metadatapath;
157     Pathname packagespath;
158     DefaultIntegral<unsigned,defaultPriority> priority;
159     mutable bool emptybaseurls;
160     repo::RepoVariablesUrlReplacer replacer;
161
162   private:
163     Url mirrorlist_url;
164     mutable url_set _baseUrls;
165     mutable std::set<std::string> _keywords;
166
167     friend Impl * rwcowClone<Impl>( const Impl * rhs );
168     /** clone for RWCOW_pointer */
169     Impl * clone() const
170     { return new Impl( *this ); }
171   };
172   ///////////////////////////////////////////////////////////////////
173
174   /** \relates RepoInfo::Impl Stream output */
175   inline std::ostream & operator<<( std::ostream & str, const RepoInfo::Impl & obj )
176   {
177     return str << "RepoInfo::Impl";
178   }
179
180   ///////////////////////////////////////////////////////////////////
181   //
182   //    CLASS NAME : RepoInfo
183   //
184   ///////////////////////////////////////////////////////////////////
185
186   const RepoInfo RepoInfo::noRepo;
187
188   ///////////////////////////////////////////////////////////////////
189   //
190   //    METHOD NAME : RepoInfo::RepoInfo
191   //    METHOD TYPE : Ctor
192   //
193   RepoInfo::RepoInfo()
194   : _pimpl( new Impl() )
195   {}
196
197   ///////////////////////////////////////////////////////////////////
198   //
199   //    METHOD NAME : RepoInfo::~RepoInfo
200   //    METHOD TYPE : Dtor
201   //
202   RepoInfo::~RepoInfo()
203   {
204     //MIL << std::endl;
205   }
206
207   unsigned RepoInfo::priority() const
208   { return _pimpl->priority; }
209
210   unsigned RepoInfo::defaultPriority()
211   { return Impl::defaultPriority; }
212
213   void RepoInfo::setPriority( unsigned newval_r )
214   { _pimpl->priority = newval_r ? newval_r : Impl::defaultPriority; }
215
216   void RepoInfo::setGpgCheck( bool check )
217   { _pimpl->gpgcheck = check; }
218
219   void RepoInfo::setMirrorListUrl( const Url & url_r )
220   { _pimpl->mirrorListUrl( url_r ); }
221
222   void RepoInfo::setGpgKeyUrl( const Url & url_r )
223   { _pimpl->gpgkey_url = url_r; }
224
225   void RepoInfo::addBaseUrl( const Url & url_r )
226   {
227     for ( const auto & url : _pimpl->baseUrls() )       // unique!
228       if ( url == url_r )
229         return;
230     _pimpl->baseUrls().push_back( url_r );
231   }
232
233   void RepoInfo::setBaseUrl( const Url & url_r )
234   {
235     _pimpl->baseUrls().clear();
236     _pimpl->baseUrls().push_back( url_r );
237   }
238
239   void RepoInfo::setPath( const Pathname &path )
240   { _pimpl->path = path; }
241
242   void RepoInfo::setType( const repo::RepoType &t )
243   { _pimpl->type = t; }
244
245   void RepoInfo::setProbedType( const repo::RepoType &t ) const
246   { _pimpl->setProbedType( t ); }
247
248
249   void RepoInfo::setMetadataPath( const Pathname &path )
250   { _pimpl->metadatapath = path; }
251
252   void RepoInfo::setPackagesPath( const Pathname &path )
253   { _pimpl->packagespath = path; }
254
255   void RepoInfo::setKeepPackages( bool keep )
256   { _pimpl->keeppackages = keep; }
257
258   void RepoInfo::setService( const std::string& name )
259   { _pimpl->service = name; }
260
261   void RepoInfo::setTargetDistribution( const std::string & targetDistribution )
262   { _pimpl->targetDistro = targetDistribution; }
263
264   bool RepoInfo::gpgCheck() const
265   { return indeterminate(_pimpl->gpgcheck) ? true : (bool)_pimpl->gpgcheck; }
266
267   bool RepoInfo::keepPackages() const
268   { return indeterminate(_pimpl->keeppackages) ? false : (bool)_pimpl->keeppackages; }
269
270   Pathname RepoInfo::metadataPath() const
271   { return _pimpl->metadatapath; }
272
273   Pathname RepoInfo::packagesPath() const
274   { return _pimpl->packagespath; }
275
276   repo::RepoType RepoInfo::type() const
277   { return _pimpl->type; }
278
279   Url RepoInfo::mirrorListUrl() const
280   { return _pimpl->mirrorListUrl(); }
281
282   Url RepoInfo::rawMirrorListUrl() const
283   { return _pimpl->rawMirrorListUrl(); }
284
285   Url RepoInfo::gpgKeyUrl() const
286   { return _pimpl->gpgkey_url; }
287
288   RepoInfo::url_set RepoInfo::baseUrls() const
289   { return url_set( baseUrlsBegin(), baseUrlsEnd() ); } // Variables replaced!
290
291   Pathname RepoInfo::path() const
292   { return _pimpl->path; }
293
294   std::string RepoInfo::service() const
295   { return _pimpl->service; }
296
297   std::string RepoInfo::targetDistribution() const
298   { return _pimpl->targetDistro; }
299
300   Url RepoInfo::rawUrl() const
301   { return( _pimpl->baseUrls().empty() ? Url() : *_pimpl->baseUrls().begin() ); }
302
303   RepoInfo::urls_const_iterator RepoInfo::baseUrlsBegin() const
304   {
305     return make_transform_iterator( _pimpl->baseUrls().begin(),
306                                     _pimpl->replacer );
307   }
308
309   RepoInfo::urls_const_iterator RepoInfo::baseUrlsEnd() const
310   {
311     return make_transform_iterator( _pimpl->baseUrls().end(),
312                                     _pimpl->replacer );
313   }
314
315   RepoInfo::urls_size_type RepoInfo::baseUrlsSize() const
316   { return _pimpl->baseUrls().size(); }
317
318   bool RepoInfo::baseUrlsEmpty() const
319   { return _pimpl->baseUrls().empty(); }
320
321   bool RepoInfo::baseUrlSet() const
322   { return _pimpl->baseurl2dump(); }
323
324
325   void RepoInfo::addContent( const std::string & keyword_r )
326   { _pimpl->addContent( keyword_r ); }
327
328   bool RepoInfo::hasContent( const std::string & keyword_r ) const
329   { return _pimpl->hasContent( keyword_r ); }
330
331   ///////////////////////////////////////////////////////////////////
332
333   bool RepoInfo::hasLicense() const
334   {
335     Pathname licenseTgz( _pimpl->licenseTgz() );
336     return ! licenseTgz.empty() &&  PathInfo(licenseTgz).isFile();
337   }
338
339   bool RepoInfo::needToAcceptLicense() const
340   {
341     static const std::string noAcceptanceFile = "no-acceptance-needed\n";
342     bool accept = true;
343
344     Pathname licenseTgz( _pimpl->licenseTgz() );
345     if ( licenseTgz.empty() || ! PathInfo( licenseTgz ).isFile() )
346       return false;     // no licenses at all
347
348     ExternalProgram::Arguments cmd;
349     cmd.push_back( "tar" );
350     cmd.push_back( "-t" );
351     cmd.push_back( "-z" );
352     cmd.push_back( "-f" );
353     cmd.push_back( licenseTgz.asString() );
354
355     ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
356     for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() )
357     {
358       if ( output == noAcceptanceFile )
359       {
360         accept = false;
361       }
362     }
363     MIL << "License for " << name() << " has to be accepted: " << (accept?"true":"false" ) << endl;
364     return accept;
365   }
366
367   std::string RepoInfo::getLicense( const Locale & lang_r )
368   { return const_cast<const RepoInfo *>(this)->getLicense( lang_r );  }
369
370   std::string RepoInfo::getLicense( const Locale & lang_r ) const
371   {
372     LocaleSet avlocales( getLicenseLocales() );
373     if ( avlocales.empty() )
374       return std::string();
375
376     Locale getLang( Locale::bestMatch( avlocales, lang_r ) );
377     if ( getLang == Locale::noCode
378          && avlocales.find( Locale::noCode ) == avlocales.end() )
379     {
380       WAR << "License.tar.gz contains no fallback text! " << *this << endl;
381       // Using the fist locale instead of returning no text at all.
382       // So the user might recognize that there is a license, even if he
383       // can't read it.
384       getLang = *avlocales.begin();
385     }
386
387     // now extract the license file.
388     static const std::string licenseFileFallback( "license.txt" );
389     std::string licenseFile( getLang == Locale::noCode
390                              ? licenseFileFallback
391                              : str::form( "license.%s.txt", getLang.code().c_str() ) );
392
393     ExternalProgram::Arguments cmd;
394     cmd.push_back( "tar" );
395     cmd.push_back( "-x" );
396     cmd.push_back( "-z" );
397     cmd.push_back( "-O" );
398     cmd.push_back( "-f" );
399     cmd.push_back( _pimpl->licenseTgz().asString() ); // if it not exists, avlocales was empty.
400     cmd.push_back( licenseFile );
401
402     std::string ret;
403     ExternalProgram prog( cmd, ExternalProgram::Discard_Stderr );
404     for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() )
405     {
406       ret += output;
407     }
408     prog.close();
409     return ret;
410   }
411
412   LocaleSet RepoInfo::getLicenseLocales() const
413   {
414     Pathname licenseTgz( _pimpl->licenseTgz() );
415     if ( licenseTgz.empty() || ! PathInfo( licenseTgz ).isFile() )
416       return LocaleSet();
417
418     ExternalProgram::Arguments cmd;
419     cmd.push_back( "tar" );
420     cmd.push_back( "-t" );
421     cmd.push_back( "-z" );
422     cmd.push_back( "-f" );
423     cmd.push_back( licenseTgz.asString() );
424
425     LocaleSet ret;
426     ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
427     for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() )
428     {
429       static const C_Str license( "license." );
430       static const C_Str dotTxt( ".txt\n" );
431       if ( str::hasPrefix( output, license ) && str::hasSuffix( output, dotTxt ) )
432       {
433         if ( output.size() <= license.size() +  dotTxt.size() ) // license.txt
434           ret.insert( Locale() );
435         else
436           ret.insert( Locale( std::string( output.c_str()+license.size(), output.size()- license.size() - dotTxt.size() ) ) );
437       }
438     }
439     prog.close();
440     return ret;
441   }
442
443   ///////////////////////////////////////////////////////////////////
444
445   std::ostream & RepoInfo::dumpOn( std::ostream & str ) const
446   {
447     RepoInfoBase::dumpOn(str);
448     if ( _pimpl->baseurl2dump() )
449     {
450       for ( const auto & url : _pimpl->baseUrls() )
451       {
452         str << "- url         : " << url << std::endl;
453       }
454     }
455
456     // print if non empty value
457     auto strif( [&] ( const std::string & tag_r, const std::string & value_r ) {
458       if ( ! value_r.empty() )
459         str << tag_r << value_r << std::endl;
460     });
461
462     strif( "- mirrorlist  : ", _pimpl->rawMirrorListUrl().asString() );
463     strif( "- path        : ", path().asString() );
464     str << "- type        : " << type() << std::endl;
465     str << "- priority    : " << priority() << std::endl;
466     str << "- gpgcheck    : " << gpgCheck() << std::endl;
467     strif( "- gpgkey      : ", gpgKeyUrl().asString() );
468
469     if ( ! indeterminate(_pimpl->keeppackages) )
470       str << "- keeppackages: " << keepPackages() << std::endl;
471
472     strif( "- service     : ", service() );
473     strif( "- targetdistro: ", targetDistribution() );
474     strif( "- metadataPath: ", metadataPath().asString() );
475     strif( "- packagesPath: ", packagesPath().asString() );
476
477     return str;
478   }
479
480   std::ostream & RepoInfo::dumpAsIniOn( std::ostream & str ) const
481   {
482     RepoInfoBase::dumpAsIniOn(str);
483
484     if ( _pimpl->baseurl2dump() )
485     {
486       str << "baseurl=";
487       std::string indent;
488       for ( const auto & url : _pimpl->baseUrls() )
489       {
490         str << indent << url << endl;
491         if ( indent.empty() ) indent = "        ";      // "baseurl="
492       }
493     }
494
495     if ( ! _pimpl->path.empty() )
496       str << "path="<< path() << endl;
497
498     if ( ! (_pimpl->rawMirrorListUrl().asString().empty()) )
499       str << "mirrorlist=" << _pimpl->rawMirrorListUrl() << endl;
500
501     str << "type=" << type().asString() << endl;
502
503     if ( priority() != defaultPriority() )
504       str << "priority=" << priority() << endl;
505
506     if (!indeterminate(_pimpl->gpgcheck))
507       str << "gpgcheck=" << (gpgCheck() ? "1" : "0") << endl;
508     if ( ! (gpgKeyUrl().asString().empty()) )
509       str << "gpgkey=" <<gpgKeyUrl() << endl;
510
511     if (!indeterminate(_pimpl->keeppackages))
512       str << "keeppackages=" << keepPackages() << endl;
513
514     if( ! service().empty() )
515       str << "service=" << service() << endl;
516
517     return str;
518   }
519
520   std::ostream & RepoInfo::dumpAsXmlOn( std::ostream & str, const std::string & content ) const
521   {
522     std::string tmpstr;
523     str
524       << "<repo"
525       << " alias=\"" << escape(alias()) << "\""
526       << " name=\"" << escape(name()) << "\"";
527     if (type() != repo::RepoType::NONE)
528       str << " type=\"" << type().asString() << "\"";
529     str
530       << " priority=\"" << priority() << "\""
531       << " enabled=\"" << enabled() << "\""
532       << " autorefresh=\"" << autorefresh() << "\""
533       << " gpgcheck=\"" << gpgCheck() << "\"";
534     if (!(tmpstr = gpgKeyUrl().asString()).empty())
535       str << " gpgkey=\"" << escape(tmpstr) << "\"";
536     if (!(tmpstr = mirrorListUrl().asString()).empty())
537       str << " mirrorlist=\"" << escape(tmpstr) << "\"";
538     str << ">" << endl;
539
540     if ( _pimpl->baseurl2dump() )
541     {
542       for_( it, baseUrlsBegin(), baseUrlsEnd() )        // !transform iterator replaces variables
543         str << "<url>" << escape((*it).asString()) << "</url>" << endl;
544     }
545
546     str << "</repo>" << endl;
547     return str;
548   }
549
550
551   std::ostream & operator<<( std::ostream & str, const RepoInfo & obj )
552   {
553     return obj.dumpOn(str);
554   }
555
556
557   /////////////////////////////////////////////////////////////////
558 } // namespace zypp
559 ///////////////////////////////////////////////////////////////////