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