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