Imported Upstream version 17.25.4
[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 #include <fstream>
15
16 #include <zypp/base/Gettext.h>
17 #include <zypp/base/LogTools.h>
18 #include <zypp/base/DefaultIntegral.h>
19 #include <zypp/parser/xml/XmlEscape.h>
20
21 #include <zypp/ManagedFile.h>
22 #include <zypp/PublicKey.h>
23 #include <zypp/MediaSetAccess.h>
24 #include <zypp/RepoInfo.h>
25 #include <zypp/Glob.h>
26 #include <zypp/TriBool.h>
27 #include <zypp/Pathname.h>
28 #include <zypp/ZConfig.h>
29 #include <zypp/repo/RepoMirrorList.h>
30 #include <zypp/ExternalProgram.h>
31 #include <zypp/media/MediaAccess.h>
32
33 #include <zypp/base/IOStream.h>
34 #include <zypp/base/InputStream.h>
35 #include <zypp/parser/xml/Reader.h>
36
37
38 #include <zypp/base/StrMatcher.h>
39 #include <zypp/KeyRing.h>
40 #include <zypp/TmpPath.h>
41 #include <zypp/ZYppFactory.h>
42 #include <zypp/ZYppCallbacks.h>
43
44 using std::endl;
45 using zypp::xml::escape;
46
47 ///////////////////////////////////////////////////////////////////
48 namespace zypp
49 { /////////////////////////////////////////////////////////////////
50
51   namespace
52   {
53     repo::RepoType probeCache( const Pathname & path_r )
54     {
55       repo::RepoType ret = repo::RepoType::NONE;
56       if ( PathInfo(path_r).isDir() )
57       {
58         if ( PathInfo(path_r/"/repodata/repomd.xml").isFile() )
59         { ret = repo::RepoType::RPMMD; }
60         else if ( PathInfo(path_r/"/content").isFile() )
61         { ret = repo::RepoType::YAST2; }
62         else if ( PathInfo(path_r/"/cookie").isFile() )
63         { ret = repo::RepoType::RPMPLAINDIR; }
64       }
65       DBG << "Probed cached type " << ret << " at " << path_r << endl;
66       return ret;
67     }
68   } // namespace
69
70   ///////////////////////////////////////////////////////////////////
71   //
72   //    CLASS NAME : RepoInfo::Impl
73   //
74   /** RepoInfo implementation. */
75   struct RepoInfo::Impl
76   {
77     Impl()
78       : _rawGpgCheck( indeterminate )
79       , _rawRepoGpgCheck( indeterminate )
80       , _rawPkgGpgCheck( indeterminate )
81       , _validRepoSignature( indeterminate )
82       , _type(repo::RepoType::NONE_e)
83       , keeppackages(indeterminate)
84       , _mirrorListForceMetalink(false)
85       , emptybaseurls(false)
86     {}
87
88     ~Impl()
89     {}
90
91   public:
92     static const unsigned defaultPriority = 99;
93     static const unsigned noPriority = unsigned(-1);
94
95     void setType( const repo::RepoType & t )
96     { _type = t; }
97
98     void setProbedType( const repo::RepoType & t ) const
99     {
100       if ( _type == repo::RepoType::NONE && t != repo::RepoType::NONE )
101       { const_cast<Impl*>(this)->_type = t; }
102     }
103
104     repo::RepoType type() const
105     {
106       if ( _type == repo::RepoType::NONE )
107         setProbedType( probeCache( metadataPath() / path ) );
108       return _type;
109     }
110
111   public:
112     /** Path to a license tarball in case it exists in the repo. */
113     Pathname licenseTgz( const std::string & name_r ) const
114     {
115       Pathname ret;
116       if ( !metadataPath().empty() )
117       {
118         std::string licenseStem( "license" );
119         if ( !name_r.empty() )
120         {
121           licenseStem += "-";
122           licenseStem += name_r;
123         }
124
125         filesystem::Glob g;
126         // TODO: REPOMD: this assumes we know the name of the tarball. In fact
127         // we'd need to get the file from repomd.xml (<data type="license[-name_r]">)
128         g.add( metadataPath() / path / ("repodata/*"+licenseStem+".tar.gz") );
129         if ( g.empty() )
130           g.add( metadataPath() / path / (licenseStem+".tar.gz") );
131
132         if ( !g.empty() )
133           ret = *g.begin();
134       }
135       return ret;
136     }
137
138     const RepoVariablesReplacedUrlList & baseUrls() const
139     {
140       const Url & mlurl( _mirrorListUrl.transformed() );        // Variables replaced!
141       if ( _baseUrls.empty() && ! mlurl.asString().empty() )
142       {
143         emptybaseurls = true;
144         DBG << "MetadataPath: " << metadataPath() << endl;
145         repo::RepoMirrorList rmurls( mlurl, metadataPath(), _mirrorListForceMetalink );
146         _baseUrls.raw().insert( _baseUrls.raw().end(), rmurls.getUrls().begin(), rmurls.getUrls().end() );
147       }
148       return _baseUrls;
149     }
150
151     RepoVariablesReplacedUrlList & baseUrls()
152     { return _baseUrls; }
153
154     bool baseurl2dump() const
155     { return !emptybaseurls && !_baseUrls.empty(); }
156
157
158     const RepoVariablesReplacedUrlList & gpgKeyUrls() const
159     { return _gpgKeyUrls; }
160
161     RepoVariablesReplacedUrlList & gpgKeyUrls()
162     { return _gpgKeyUrls; }
163
164
165     const std::set<std::string> & contentKeywords() const
166     { hasContent()/*init if not yet done*/; return _keywords.second; }
167
168     void addContent( const std::string & keyword_r )
169     { _keywords.second.insert( keyword_r ); if ( ! hasContent() ) _keywords.first = true; }
170
171     bool hasContent() const
172     {
173       if ( !_keywords.first && ! metadataPath().empty() )
174       {
175         // HACK directly check master index file until RepoManager offers
176         // some content probing and zypper uses it.
177         /////////////////////////////////////////////////////////////////
178         MIL << "Empty keywords...." << metadataPath() << endl;
179         Pathname master;
180         if ( PathInfo( (master=metadataPath()/"/repodata/repomd.xml") ).isFile() )
181         {
182           //MIL << "GO repomd.." << endl;
183           xml::Reader reader( master );
184           while ( reader.seekToNode( 2, "content" ) )
185           {
186             _keywords.second.insert( reader.nodeText().asString() );
187             reader.seekToEndNode( 2, "content" );
188           }
189           _keywords.first = true;       // valid content in _keywords even if empty
190         }
191         else if ( PathInfo( (master=metadataPath()/"/content") ).isFile() )
192         {
193           //MIL << "GO content.." << endl;
194           iostr::forEachLine( InputStream( master ),
195                             [this]( int num_r, std::string line_r )->bool
196                             {
197                               if ( str::startsWith( line_r, "REPOKEYWORDS" ) )
198                               {
199                                 std::vector<std::string> words;
200                                 if ( str::split( line_r, std::back_inserter(words) ) > 1
201                                   && words[0].length() == 12 /*"REPOKEYWORDS"*/ )
202                                 {
203                                   this->_keywords.second.insert( ++words.begin(), words.end() );
204                                 }
205                                 return true; // mult. occurrances are ok.
206                               }
207                               return( ! str::startsWith( line_r, "META " ) );   // no need to parse into META section.
208                             } );
209           _keywords.first = true;       // valid content in _keywords even if empty
210         }
211         /////////////////////////////////////////////////////////////////
212       }
213       return _keywords.first;
214     }
215
216     bool hasContent( const std::string & keyword_r ) const
217     { return( hasContent() && _keywords.second.find( keyword_r ) != _keywords.second.end() ); }
218
219     /** Signature check result needs to be stored/retrieved from _metadataPath.
220      * Don't call them from outside validRepoSignature/setValidRepoSignature
221      */
222     //@{
223     TriBool internalValidRepoSignature() const
224     {
225       if ( ! indeterminate(_validRepoSignature) )
226         return _validRepoSignature;
227       // check metadata:
228       if ( ! metadataPath().empty() )
229       {
230         // A missing ".repo_gpgcheck" might be plaindir(no Downloader) or not yet refreshed signed repo!
231         TriBool linkval = triBoolFromPath( metadataPath() / ".repo_gpgcheck" );
232         return linkval;
233       }
234       return indeterminate;
235     }
236
237     void internalSetValidRepoSignature( TriBool value_r )
238     {
239       if ( PathInfo(metadataPath()).isDir() )
240       {
241         Pathname gpgcheckFile( metadataPath() / ".repo_gpgcheck" );
242         if ( PathInfo(gpgcheckFile).isExist() )
243         {
244           TriBool linkval( indeterminate );
245           if ( triBoolFromPath( gpgcheckFile, linkval ) && linkval == value_r )
246             return;     // existing symlink fits value_r
247           else
248             filesystem::unlink( gpgcheckFile ); // will write a new one
249         }
250         filesystem::symlink( asString(value_r), gpgcheckFile );
251       }
252       _validRepoSignature = value_r;
253     }
254
255     /** We definitely have a symlink pointing to "indeterminate" (for repoGpgCheckIsMandatory)?
256      * I.e. user accepted the unsigned repo in Downloader. A test whether `internalValidRepoSignature`
257      * is indeterminate would include not yet checked repos, which is unwanted here.
258      */
259     bool internalUnsignedConfirmed() const
260     {
261       TriBool linkval( true );  // want to see it being switched to indeterminate
262       return triBoolFromPath( metadataPath() / ".repo_gpgcheck", linkval ) && indeterminate(linkval);
263     }
264
265     bool triBoolFromPath( const Pathname & path_r, TriBool & ret_r ) const
266     {
267       static const Pathname truePath( "true" );
268       static const Pathname falsePath( "false" );
269       static const Pathname indeterminatePath( "indeterminate" );
270
271       // Quiet readlink;
272       static const ssize_t bufsiz = 63;
273       static char buf[bufsiz+1];
274       ssize_t ret = ::readlink( path_r.c_str(), buf, bufsiz );
275       buf[ret == -1 ? 0 : ret] = '\0';
276
277       Pathname linkval( buf );
278
279       bool known = true;
280       if ( linkval == truePath )
281         ret_r = true;
282       else if ( linkval == falsePath )
283         ret_r = false;
284       else if ( linkval == indeterminatePath )
285         ret_r = indeterminate;
286       else
287         known = false;
288       return known;
289     }
290
291     TriBool triBoolFromPath( const Pathname & path_r ) const
292     { TriBool ret(indeterminate); triBoolFromPath( path_r, ret ); return ret; }
293
294     //@}
295
296   private:
297     TriBool _rawGpgCheck;       ///< default gpgcheck behavior: Y/N/ZConf
298     TriBool _rawRepoGpgCheck;   ///< need to check repo sign.: Y/N/(ZConf(Y/N/gpgCheck))
299     TriBool _rawPkgGpgCheck;    ///< need to check pkg sign.: Y/N/(ZConf(Y/N/gpgCheck))
300
301   public:
302     TriBool rawGpgCheck() const                 { return _rawGpgCheck; }
303     TriBool rawRepoGpgCheck() const             { return _rawRepoGpgCheck; }
304     TriBool rawPkgGpgCheck() const              { return _rawPkgGpgCheck; }
305
306     void rawGpgCheck( TriBool val_r )           { _rawGpgCheck = val_r; }
307     void rawRepoGpgCheck( TriBool val_r )       { _rawRepoGpgCheck = val_r; }
308     void rawPkgGpgCheck( TriBool val_r )        { _rawPkgGpgCheck = val_r; }
309
310     bool cfgGpgCheck() const
311     { return indeterminate(_rawGpgCheck) ? ZConfig::instance().gpgCheck() : (bool)_rawGpgCheck; }
312     TriBool cfgRepoGpgCheck() const
313     { return indeterminate(_rawGpgCheck) && indeterminate(_rawRepoGpgCheck) ? ZConfig::instance().repoGpgCheck() : _rawRepoGpgCheck; }
314     TriBool cfgPkgGpgCheck() const
315     { return indeterminate(_rawGpgCheck) && indeterminate(_rawPkgGpgCheck) ? ZConfig::instance().pkgGpgCheck() : _rawPkgGpgCheck; }
316
317   private:
318     TriBool _validRepoSignature; ///< have  signed and valid repo metadata
319     repo::RepoType _type;
320   public:
321     TriBool keeppackages;
322     RepoVariablesReplacedUrl _mirrorListUrl;
323     bool                     _mirrorListForceMetalink;
324     Pathname path;
325     std::string service;
326     std::string targetDistro;
327
328     void metadataPath( Pathname new_r )
329     { _metadataPath = std::move( new_r ); }
330
331     void packagesPath( Pathname new_r )
332     { _packagesPath = std::move( new_r ); }
333
334     bool usesAutoMethadataPaths() const
335     { return str::hasSuffix( _metadataPath.asString(), "/%AUTO%" ); }
336
337     Pathname metadataPath() const
338     {
339       if ( usesAutoMethadataPaths() )
340         return _metadataPath.dirname() / "%RAW%";
341       return _metadataPath;
342     }
343
344     Pathname packagesPath() const
345     {
346       if ( _packagesPath.empty() && usesAutoMethadataPaths() )
347         return _metadataPath.dirname() / "%PKG%";
348       return _packagesPath;
349     }
350
351     DefaultIntegral<unsigned,defaultPriority> priority;
352     mutable bool emptybaseurls;
353
354   private:
355     Pathname _metadataPath;
356     Pathname _packagesPath;
357
358     mutable RepoVariablesReplacedUrlList _baseUrls;
359     mutable std::pair<FalseBool, std::set<std::string> > _keywords;
360
361     RepoVariablesReplacedUrlList _gpgKeyUrls;
362
363     friend Impl * rwcowClone<Impl>( const Impl * rhs );
364     /** clone for RWCOW_pointer */
365     Impl * clone() const
366     { return new Impl( *this ); }
367   };
368   ///////////////////////////////////////////////////////////////////
369
370   /** \relates RepoInfo::Impl Stream output */
371   inline std::ostream & operator<<( std::ostream & str, const RepoInfo::Impl & obj )
372   {
373     return str << "RepoInfo::Impl";
374   }
375
376   ///////////////////////////////////////////////////////////////////
377   //
378   //    CLASS NAME : RepoInfo
379   //
380   ///////////////////////////////////////////////////////////////////
381
382   const RepoInfo RepoInfo::noRepo;
383
384   RepoInfo::RepoInfo()
385   : _pimpl( new Impl() )
386   {}
387
388   RepoInfo::~RepoInfo()
389   {}
390
391   unsigned RepoInfo::priority() const
392   { return _pimpl->priority; }
393
394   unsigned RepoInfo::defaultPriority()
395   { return Impl::defaultPriority; }
396
397   unsigned RepoInfo::noPriority()
398   { return Impl::noPriority; }
399
400   void RepoInfo::setPriority( unsigned newval_r )
401   { _pimpl->priority = newval_r ? newval_r : Impl::defaultPriority; }
402
403
404   bool RepoInfo::gpgCheck() const
405   { return _pimpl->cfgGpgCheck(); }
406
407   void RepoInfo::setGpgCheck( TriBool value_r )
408   { _pimpl->rawGpgCheck( value_r ); }
409
410   void RepoInfo::setGpgCheck( bool value_r ) // deprecated legacy and for squid
411   { setGpgCheck( TriBool(value_r) ); }
412
413
414   bool RepoInfo::repoGpgCheck() const
415   { return gpgCheck() || bool(_pimpl->cfgRepoGpgCheck()); }
416
417   bool RepoInfo::repoGpgCheckIsMandatory() const
418   {
419     bool ret = ( gpgCheck() && indeterminate(_pimpl->cfgRepoGpgCheck()) ) || bool(_pimpl->cfgRepoGpgCheck());
420     if ( ret && _pimpl->internalUnsignedConfirmed() )   // relax if unsigned repo was confirmed in the past
421       ret = false;
422     return ret;
423   }
424
425   void RepoInfo::setRepoGpgCheck( TriBool value_r )
426   { _pimpl->rawRepoGpgCheck( value_r ); }
427
428
429   bool RepoInfo::pkgGpgCheck() const
430   { return bool(_pimpl->cfgPkgGpgCheck()) || ( gpgCheck() && !bool(validRepoSignature())/*enforced*/ ) ; }
431
432   bool RepoInfo::pkgGpgCheckIsMandatory() const
433   { return bool(_pimpl->cfgPkgGpgCheck()) || ( gpgCheck() && indeterminate(_pimpl->cfgPkgGpgCheck()) && !bool(validRepoSignature())/*enforced*/ ); }
434
435   void RepoInfo::setPkgGpgCheck( TriBool value_r )
436   { _pimpl->rawPkgGpgCheck( value_r ); }
437
438
439   void RepoInfo::getRawGpgChecks( TriBool & g_r, TriBool & r_r, TriBool & p_r ) const
440   {
441     g_r = _pimpl->rawGpgCheck();
442     r_r = _pimpl->rawRepoGpgCheck();
443     p_r = _pimpl->rawPkgGpgCheck();
444   }
445
446
447   TriBool RepoInfo::validRepoSignature() const
448   {
449     TriBool ret( _pimpl->internalValidRepoSignature() );
450     if ( ret && !repoGpgCheck() ) ret = false;  // invalidate any old signature if repoGpgCheck is off
451     return ret;
452   }
453
454   void RepoInfo::setValidRepoSignature( TriBool value_r )
455   { _pimpl->internalSetValidRepoSignature( value_r ); }
456
457   ///////////////////////////////////////////////////////////////////
458   namespace
459   {
460     inline bool changeGpgCheckTo( TriBool & lhs, TriBool rhs )
461     { if ( ! sameTriboolState( lhs, rhs ) ) { lhs = rhs; return true; } return false; }
462
463     inline bool changeGpgCheckTo( TriBool ogpg[3], TriBool g, TriBool r, TriBool p )
464     {
465       bool changed = false;
466       if ( changeGpgCheckTo( ogpg[0], g ) ) changed = true;
467       if ( changeGpgCheckTo( ogpg[1], r ) ) changed = true;
468       if ( changeGpgCheckTo( ogpg[2], p ) ) changed = true;
469       return changed;
470     }
471   } // namespace
472   ///////////////////////////////////////////////////////////////////
473   bool RepoInfo::setGpgCheck( GpgCheck mode_r )
474   {
475     TriBool ogpg[3];    // Gpg RepoGpg PkgGpg
476     getRawGpgChecks( ogpg[0], ogpg[1], ogpg[2] );
477
478     bool changed = false;
479     switch ( mode_r )
480     {
481       case GpgCheck::On:
482         changed = changeGpgCheckTo( ogpg, true,          indeterminate, indeterminate );
483         break;
484       case GpgCheck::Strict:
485         changed = changeGpgCheckTo( ogpg, true,          true,          true          );
486         break;
487       case GpgCheck::AllowUnsigned:
488         changed = changeGpgCheckTo( ogpg, true,          false,         false         );
489         break;
490       case GpgCheck::AllowUnsignedRepo:
491         changed = changeGpgCheckTo( ogpg, true,          false,         indeterminate );
492         break;
493       case GpgCheck::AllowUnsignedPackage:
494         changed = changeGpgCheckTo( ogpg, true,          indeterminate, false         );
495         break;
496       case GpgCheck::Default:
497         changed = changeGpgCheckTo( ogpg, indeterminate, indeterminate, indeterminate );
498         break;
499       case GpgCheck::Off:
500         changed = changeGpgCheckTo( ogpg, false,         indeterminate, indeterminate );
501         break;
502       case GpgCheck::indeterminate:     // no change
503         break;
504     }
505
506     if ( changed )
507     {
508       setGpgCheck    ( ogpg[0] );
509       setRepoGpgCheck( ogpg[1] );
510       setPkgGpgCheck ( ogpg[2] );
511     }
512     return changed;
513   }
514
515   void RepoInfo::setMirrorListUrl( const Url & url_r )  // Raw
516   { _pimpl->_mirrorListUrl.raw() = url_r; _pimpl->_mirrorListForceMetalink = false; }
517
518   void  RepoInfo::setMetalinkUrl( const Url & url_r )   // Raw
519   { _pimpl->_mirrorListUrl.raw() = url_r; _pimpl->_mirrorListForceMetalink = true; }
520
521   void RepoInfo::setGpgKeyUrls( url_set urls )
522   { _pimpl->gpgKeyUrls().raw().swap( urls ); }
523
524   void RepoInfo::setGpgKeyUrl( const Url & url_r )
525   {
526     _pimpl->gpgKeyUrls().raw().clear();
527     _pimpl->gpgKeyUrls().raw().push_back( url_r );
528   }
529
530   Pathname RepoInfo::provideKey(const std::string &keyID_r, const Pathname &targetDirectory_r) const
531   {
532     if ( keyID_r.empty() )
533       return Pathname();
534
535     MIL << "Check for " << keyID_r << " at " << targetDirectory_r << endl;
536     std::string keyIDStr( keyID_r.size() > 8 ? keyID_r.substr( keyID_r.size()-8 ) : keyID_r );  // print short ID in Jobreports
537     filesystem::TmpDir tmpKeyRingDir;
538     KeyRing tempKeyRing(tmpKeyRingDir.path());
539
540     // translator: %1% is a gpg key ID like 3DBDC284
541     //             %2% is a cache directories path
542     JobReport::info( str::Format(_("Looking for gpg key ID %1% in cache %2%.") ) % keyIDStr % targetDirectory_r );
543     filesystem::dirForEach(targetDirectory_r,
544                            StrMatcher(".key", Match::STRINGEND),
545                            [&tempKeyRing]( const Pathname & dir_r, const std::string & str_r ){
546       try {
547
548         // deprecate a month old keys
549         PathInfo fileInfo ( dir_r/str_r );
550         if ( Date::now() - fileInfo.mtime() > Date::month ) {
551           //if unlink fails, the file will be overriden in the next step, no need
552           //to show a error
553           filesystem::unlink( dir_r/str_r );
554         } else {
555           tempKeyRing.multiKeyImport(dir_r/str_r, true);
556         }
557       } catch (const KeyRingException& e) {
558         ZYPP_CAUGHT(e);
559         ERR << "Error importing cached key from file '"<<dir_r/str_r<<"'."<<endl;
560       }
561       return true;
562     });
563
564     // no key in the cache is what we are looking for, lets download
565     // all keys specified in gpgkey= entries
566     if ( !tempKeyRing.isKeyTrusted(keyID_r) ) {
567       if ( ! gpgKeyUrlsEmpty() ) {
568         // translator: %1% is a gpg key ID like 3DBDC284
569         //             %2% is a repositories name
570         JobReport::info( str::Format(_("Looking for gpg key ID %1% in repository %2%.") ) % keyIDStr % asUserString() );
571         for ( const Url &url : gpgKeyUrls() ) {
572           try {
573             JobReport::info( "  gpgkey=" + url.asString() );
574             ManagedFile f = MediaSetAccess::provideOptionalFileFromUrl( url );
575             if ( f->empty() )
576               continue;
577
578             PublicKey key(f);
579             if ( !key.isValid() )
580               continue;
581
582             // import all keys into our temporary keyring
583             tempKeyRing.multiKeyImport(f, true);
584
585           } catch ( const std::exception & e ) {
586             //ignore and continue to next url
587             ZYPP_CAUGHT(e);
588             MIL << "Key import from url:'"<<url<<"' failed." << endl;
589           }
590         }
591       }
592       else {
593         // translator: %1% is a repositories name
594         JobReport::info( str::Format(_("Repository %1% does not define additional 'gpgkey=' URLs.") ) % asUserString() );
595       }
596     }
597
598     filesystem::assert_dir( targetDirectory_r );
599
600     //now write all keys into their own files in cache, override existing ones to always have
601     //up to date key data
602     for ( const auto & key: tempKeyRing.trustedPublicKeyData()) {
603       MIL << "KEY ID in KEYRING: " << key.id() << endl;
604
605       Pathname keyFile = targetDirectory_r/(str::Format("%1%.key") % key.rpmName()).asString();
606
607       std::ofstream fout( keyFile.c_str(), std::ios_base::out | std::ios_base::trunc );
608
609       if (!fout)
610         ZYPP_THROW(Exception(str::form("Cannot open file %s",keyFile.c_str())));
611
612       tempKeyRing.dumpTrustedPublicKey( key.id(), fout );
613     }
614
615     // key is STILL not known, we give up
616     if ( !tempKeyRing.isKeyTrusted(keyID_r) ) {
617       return Pathname();
618     }
619
620     PublicKeyData keyData( tempKeyRing.trustedPublicKeyData( keyID_r ) );
621     if ( !keyData ) {
622       ERR << "Error when exporting key from temporary keychain." << endl;
623       return Pathname();
624     }
625
626     return targetDirectory_r/(str::Format("%1%.key") % keyData.rpmName()).asString();
627   }
628
629   void RepoInfo::addBaseUrl( const Url & url_r )
630   {
631     for ( const auto & url : _pimpl->baseUrls().raw() ) // Raw unique!
632       if ( url == url_r )
633         return;
634     _pimpl->baseUrls().raw().push_back( url_r );
635   }
636
637   void RepoInfo::setBaseUrl( const Url & url_r )
638   {
639     _pimpl->baseUrls().raw().clear();
640     _pimpl->baseUrls().raw().push_back( url_r );
641   }
642
643   void RepoInfo::setBaseUrls( url_set urls )
644   { _pimpl->baseUrls().raw().swap( urls ); }
645
646   void RepoInfo::setPath( const Pathname &path )
647   { _pimpl->path = path; }
648
649   void RepoInfo::setType( const repo::RepoType &t )
650   { _pimpl->setType( t ); }
651
652   void RepoInfo::setProbedType( const repo::RepoType &t ) const
653   { _pimpl->setProbedType( t ); }
654
655
656   void RepoInfo::setMetadataPath( const Pathname &path )
657   { _pimpl->metadataPath( path ); }
658
659   void RepoInfo::setPackagesPath( const Pathname &path )
660   { _pimpl->packagesPath( path ); }
661
662   void RepoInfo::setKeepPackages( bool keep )
663   { _pimpl->keeppackages = keep; }
664
665   void RepoInfo::setService( const std::string& name )
666   { _pimpl->service = name; }
667
668   void RepoInfo::setTargetDistribution( const std::string & targetDistribution )
669   { _pimpl->targetDistro = targetDistribution; }
670
671   bool RepoInfo::keepPackages() const
672   { return indeterminate(_pimpl->keeppackages) ? false : (bool)_pimpl->keeppackages; }
673
674   Pathname RepoInfo::metadataPath() const
675   { return _pimpl->metadataPath(); }
676
677   Pathname RepoInfo::packagesPath() const
678   { return _pimpl->packagesPath(); }
679
680   bool RepoInfo::usesAutoMethadataPaths() const
681   { return _pimpl->usesAutoMethadataPaths(); }
682
683   repo::RepoType RepoInfo::type() const
684   { return _pimpl->type(); }
685
686   Url RepoInfo::mirrorListUrl() const                   // Variables replaced!
687   { return _pimpl->_mirrorListUrl.transformed(); }
688
689   Url RepoInfo::rawMirrorListUrl() const                // Raw
690   { return _pimpl->_mirrorListUrl.raw(); }
691
692   bool RepoInfo::gpgKeyUrlsEmpty() const
693   { return _pimpl->gpgKeyUrls().empty(); }
694
695   RepoInfo::urls_size_type RepoInfo::gpgKeyUrlsSize() const
696   { return _pimpl->gpgKeyUrls().size(); }
697
698   RepoInfo::url_set RepoInfo::gpgKeyUrls() const        // Variables replaced!
699   { return _pimpl->gpgKeyUrls().transformed(); }
700
701   RepoInfo::url_set RepoInfo::rawGpgKeyUrls() const     // Raw
702   { return _pimpl->gpgKeyUrls().raw(); }
703
704   Url RepoInfo::gpgKeyUrl() const                       // Variables replaced!
705   { return( _pimpl->gpgKeyUrls().empty() ? Url() : *_pimpl->gpgKeyUrls().transformedBegin() ); }
706
707   Url RepoInfo::rawGpgKeyUrl() const                    // Raw
708   { return( _pimpl->gpgKeyUrls().empty() ? Url() : *_pimpl->gpgKeyUrls().rawBegin() ) ; }
709
710   RepoInfo::url_set RepoInfo::baseUrls() const          // Variables replaced!
711   { return _pimpl->baseUrls().transformed(); }
712
713   RepoInfo::url_set RepoInfo::rawBaseUrls() const       // Raw
714   { return _pimpl->baseUrls().raw(); }
715
716   Pathname RepoInfo::path() const
717   { return _pimpl->path; }
718
719   std::string RepoInfo::service() const
720   { return _pimpl->service; }
721
722   std::string RepoInfo::targetDistribution() const
723   { return _pimpl->targetDistro; }
724
725   Url RepoInfo::rawUrl() const
726   { return( _pimpl->baseUrls().empty() ? Url() : *_pimpl->baseUrls().rawBegin() ); }
727
728   RepoInfo::urls_const_iterator RepoInfo::baseUrlsBegin() const
729   { return _pimpl->baseUrls().transformedBegin(); }
730
731   RepoInfo::urls_const_iterator RepoInfo::baseUrlsEnd() const
732   { return _pimpl->baseUrls().transformedEnd(); }
733
734   RepoInfo::urls_size_type RepoInfo::baseUrlsSize() const
735   { return _pimpl->baseUrls().size(); }
736
737   bool RepoInfo::baseUrlsEmpty() const
738   { return _pimpl->baseUrls().empty(); }
739
740   bool RepoInfo::baseUrlSet() const
741   { return _pimpl->baseurl2dump(); }
742
743   const std::set<std::string> & RepoInfo::contentKeywords() const
744   { return _pimpl->contentKeywords(); }
745
746   void RepoInfo::addContent( const std::string & keyword_r )
747   { _pimpl->addContent( keyword_r ); }
748
749   bool RepoInfo::hasContent() const
750   { return _pimpl->hasContent(); }
751
752   bool RepoInfo::hasContent( const std::string & keyword_r ) const
753   { return _pimpl->hasContent( keyword_r ); }
754
755   ///////////////////////////////////////////////////////////////////
756
757   bool RepoInfo::hasLicense() const
758   { return hasLicense( std::string() ); }
759
760   bool RepoInfo::hasLicense( const std::string & name_r ) const
761   { return !_pimpl->licenseTgz( name_r ).empty(); }
762
763
764   bool RepoInfo::needToAcceptLicense() const
765   { return needToAcceptLicense( std::string() ); }
766
767   bool RepoInfo::needToAcceptLicense( const std::string & name_r ) const
768   {
769     const Pathname & licenseTgz( _pimpl->licenseTgz( name_r ) );
770     if ( licenseTgz.empty() )
771       return false;     // no licenses at all
772
773     ExternalProgram::Arguments cmd;
774     cmd.push_back( "tar" );
775     cmd.push_back( "-t" );
776     cmd.push_back( "-z" );
777     cmd.push_back( "-f" );
778     cmd.push_back( licenseTgz.asString() );
779     ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
780
781     bool accept = true;
782     static const std::string noAcceptanceFile = "no-acceptance-needed\n";
783     for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() )
784     {
785       if ( output == noAcceptanceFile )
786       {
787         accept = false;
788       }
789     }
790     prog.close();
791     MIL << "License(" << name_r << ") in " << name() << " has to be accepted: " << (accept?"true":"false" ) << endl;
792     return accept;
793   }
794
795
796   std::string RepoInfo::getLicense( const Locale & lang_r )
797   { return const_cast<const RepoInfo *>(this)->getLicense( std::string(), lang_r ); }
798
799   std::string RepoInfo::getLicense( const Locale & lang_r ) const
800   { return getLicense( std::string(), lang_r ); }
801
802   std::string RepoInfo::getLicense( const std::string & name_r, const Locale & lang_r ) const
803   {
804     LocaleSet avlocales( getLicenseLocales( name_r ) );
805     if ( avlocales.empty() )
806       return std::string();
807
808     Locale getLang( Locale::bestMatch( avlocales, lang_r ) );
809     if ( !getLang && avlocales.find( Locale::noCode ) == avlocales.end() )
810     {
811       WAR << "License(" << name_r << ") in " << name() << " contains no fallback text!" << endl;
812       // Using the fist locale instead of returning no text at all.
813       // So the user might recognize that there is a license, even if he
814       // can't read it.
815       getLang = *avlocales.begin();
816     }
817
818     // now extract the license file.
819     static const std::string licenseFileFallback( "license.txt" );
820     std::string licenseFile( !getLang ? licenseFileFallback
821                                       : str::form( "license.%s.txt", getLang.c_str() ) );
822
823     ExternalProgram::Arguments cmd;
824     cmd.push_back( "tar" );
825     cmd.push_back( "-x" );
826     cmd.push_back( "-z" );
827     cmd.push_back( "-O" );
828     cmd.push_back( "-f" );
829     cmd.push_back( _pimpl->licenseTgz( name_r ).asString() ); // if it not exists, avlocales was empty.
830     cmd.push_back( licenseFile );
831
832     std::string ret;
833     ExternalProgram prog( cmd, ExternalProgram::Discard_Stderr );
834     for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() )
835     {
836       ret += output;
837     }
838     prog.close();
839     return ret;
840   }
841
842
843   LocaleSet RepoInfo::getLicenseLocales() const
844   { return getLicenseLocales( std::string() ); }
845
846   LocaleSet RepoInfo::getLicenseLocales( const std::string & name_r ) const
847   {
848     const Pathname & licenseTgz( _pimpl->licenseTgz( name_r ) );
849     if ( licenseTgz.empty() )
850       return LocaleSet();
851
852     ExternalProgram::Arguments cmd;
853     cmd.push_back( "tar" );
854     cmd.push_back( "-t" );
855     cmd.push_back( "-z" );
856     cmd.push_back( "-f" );
857     cmd.push_back( licenseTgz.asString() );
858
859     LocaleSet ret;
860     ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
861     for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() )
862     {
863       static const C_Str license( "license." );
864       static const C_Str dotTxt( ".txt\n" );
865       if ( str::hasPrefix( output, license ) && str::hasSuffix( output, dotTxt ) )
866       {
867         if ( output.size() <= license.size() +  dotTxt.size() ) // license.txt
868           ret.insert( Locale() );
869         else
870           ret.insert( Locale( std::string( output.c_str()+license.size(), output.size()- license.size() - dotTxt.size() ) ) );
871       }
872     }
873     prog.close();
874     return ret;
875   }
876
877   ///////////////////////////////////////////////////////////////////
878
879   std::ostream & RepoInfo::dumpOn( std::ostream & str ) const
880   {
881     RepoInfoBase::dumpOn(str);
882     if ( _pimpl->baseurl2dump() )
883     {
884       for ( const auto & url : _pimpl->baseUrls().raw() )
885       {
886         str << "- url         : " << url << std::endl;
887       }
888     }
889
890     // print if non empty value
891     auto strif( [&] ( const std::string & tag_r, const std::string & value_r ) {
892       if ( ! value_r.empty() )
893         str << tag_r << value_r << std::endl;
894     });
895
896     strif( (_pimpl->_mirrorListForceMetalink ? "- metalink    : " : "- mirrorlist  : "), rawMirrorListUrl().asString() );
897     strif( "- path        : ", path().asString() );
898     str << "- type        : " << type() << std::endl;
899     str << "- priority    : " << priority() << std::endl;
900
901     // Yes No Default(Y) Default(N)
902 #define OUTS(T,B) ( indeterminate(T) ? (std::string("D(")+(B?"Y":"N")+")") : ((bool)T?"Y":"N") )
903     str << "- gpgcheck    : " << OUTS(_pimpl->rawGpgCheck(),gpgCheck())
904                               << " repo" << OUTS(_pimpl->rawRepoGpgCheck(),repoGpgCheck()) << (repoGpgCheckIsMandatory() ? "* ": " " )
905                               << "sig" << asString( validRepoSignature(), "?", "Y", "N" )
906                               << " pkg" << OUTS(_pimpl->rawPkgGpgCheck(),pkgGpgCheck()) << (pkgGpgCheckIsMandatory() ? "* ": " " )
907                               << std::endl;
908 #undef OUTS
909
910     for ( const auto & url : _pimpl->gpgKeyUrls().raw() )
911     {
912       str << "- gpgkey      : " << url << std::endl;
913     }
914
915     if ( ! indeterminate(_pimpl->keeppackages) )
916       str << "- keeppackages: " << keepPackages() << std::endl;
917
918     strif( "- service     : ", service() );
919     strif( "- targetdistro: ", targetDistribution() );
920     strif( "- filePath:     ", filepath().asString() );
921     strif( "- metadataPath: ", metadataPath().asString() );
922     strif( "- packagesPath: ", packagesPath().asString() );
923
924     return str;
925   }
926
927   std::ostream & RepoInfo::dumpAsIniOn( std::ostream & str ) const
928   {
929     RepoInfoBase::dumpAsIniOn(str);
930
931     if ( _pimpl->baseurl2dump() )
932     {
933       str << "baseurl=";
934       std::string indent;
935       for ( const auto & url : _pimpl->baseUrls().raw() )
936       {
937         str << indent << hotfix1050625::asString( url ) << endl;
938         if ( indent.empty() ) indent = "        ";      // "baseurl="
939       }
940     }
941
942     if ( ! _pimpl->path.empty() )
943       str << "path="<< path() << endl;
944
945     if ( ! (rawMirrorListUrl().asString().empty()) )
946       str << (_pimpl->_mirrorListForceMetalink ? "metalink=" : "mirrorlist=") << hotfix1050625::asString( rawMirrorListUrl() ) << endl;
947
948     if ( type() != repo::RepoType::NONE )
949       str << "type=" << type().asString() << endl;
950
951     if ( priority() != defaultPriority() )
952       str << "priority=" << priority() << endl;
953
954     if ( ! indeterminate(_pimpl->rawGpgCheck()) )
955       str << "gpgcheck=" << (_pimpl->rawGpgCheck() ? "1" : "0") << endl;
956
957     if ( ! indeterminate(_pimpl->rawRepoGpgCheck()) )
958       str << "repo_gpgcheck=" << (_pimpl->rawRepoGpgCheck() ? "1" : "0") << endl;
959
960     if ( ! indeterminate(_pimpl->rawPkgGpgCheck()) )
961       str << "pkg_gpgcheck=" << (_pimpl->rawPkgGpgCheck() ? "1" : "0") << endl;
962
963     {
964       std::string indent( "gpgkey=");
965       for ( const auto & url : _pimpl->gpgKeyUrls().raw() )
966       {
967         str << indent << url << endl;
968         if ( indent[0] != ' ' )
969           indent = "       ";
970       }
971     }
972
973     if (!indeterminate(_pimpl->keeppackages))
974       str << "keeppackages=" << keepPackages() << endl;
975
976     if( ! service().empty() )
977       str << "service=" << service() << endl;
978
979     return str;
980   }
981
982   std::ostream & RepoInfo::dumpAsXmlOn( std::ostream & str, const std::string & content ) const
983   {
984     std::string tmpstr;
985     str
986       << "<repo"
987       << " alias=\"" << escape(alias()) << "\""
988       << " name=\"" << escape(name()) << "\"";
989     if (type() != repo::RepoType::NONE)
990       str << " type=\"" << type().asString() << "\"";
991     str
992       << " priority=\"" << priority() << "\""
993       << " enabled=\"" << enabled() << "\""
994       << " autorefresh=\"" << autorefresh() << "\""
995       << " gpgcheck=\"" << gpgCheck() << "\""
996       << " repo_gpgcheck=\"" << repoGpgCheck() << "\""
997       << " pkg_gpgcheck=\"" << pkgGpgCheck() << "\"";
998     if (!(tmpstr = gpgKeyUrl().asString()).empty())
999       str << " gpgkey=\"" << escape(tmpstr) << "\"";
1000     if (!(tmpstr = mirrorListUrl().asString()).empty())
1001       str << (_pimpl->_mirrorListForceMetalink ? " metalink=\"" : " mirrorlist=\"") << escape(tmpstr) << "\"";
1002     str << ">" << endl;
1003
1004     if ( _pimpl->baseurl2dump() )
1005     {
1006       for_( it, baseUrlsBegin(), baseUrlsEnd() )        // !transform iterator replaces variables
1007         str << "<url>" << escape((*it).asString()) << "</url>" << endl;
1008     }
1009
1010     str << "</repo>" << endl;
1011     return str;
1012   }
1013
1014
1015   std::ostream & operator<<( std::ostream & str, const RepoInfo & obj )
1016   {
1017     return obj.dumpOn(str);
1018   }
1019
1020   std::ostream & operator<<( std::ostream & str, const RepoInfo::GpgCheck & obj )
1021   {
1022     switch ( obj )
1023     {
1024 #define OUTS( V ) case RepoInfo::V: return str << #V; break
1025       OUTS( GpgCheck::On );
1026       OUTS( GpgCheck::Strict );
1027       OUTS( GpgCheck::AllowUnsigned );
1028       OUTS( GpgCheck::AllowUnsignedRepo );
1029       OUTS( GpgCheck::AllowUnsignedPackage );
1030       OUTS( GpgCheck::Default );
1031       OUTS( GpgCheck::Off );
1032       OUTS( GpgCheck::indeterminate );
1033 #undef OUTS
1034     }
1035     return str << "GpgCheck::UNKNOWN";
1036   }
1037
1038   /////////////////////////////////////////////////////////////////
1039 } // namespace zypp
1040 ///////////////////////////////////////////////////////////////////