<commit_before>/*
    qgpgmecryptoconfig.cpp

    This file is part of libkleopatra, the KDE keymanagement library
    Copyright (c) 2004 Klarlvdalens Datakonsult AB

    Libkleopatra is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.

    Libkleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "qgpgmecryptoconfig.h"
#include <kdebug.h>
#include <kprocio.h>
#include <errno.h>
#include <kmessagebox.h>
#include <klocale.h>

#include <assert.h>
#include <ktempfile.h>
#include <qfile.h>
#include <stdlib.h>
#include <qtextcodec.h>

// Just for the Q_ASSERT in the dtor. Not thread-safe, but who would
// have 2 threads talking to gpgconf anyway? :)
static bool s_duringClear = false;

#define GPGCONF_FLAG_GROUP 1
#define GPGCONF_FLAG_OPTIONAL 2
#define GPGCONF_FLAG_LIST 4
#define GPGCONF_FLAG_RUNTIME 8
#define GPGCONF_FLAG_DEFAULT 16 // fixed default value available
#define GPGCONF_FLAG_DEFAULT_DESC 32 // runtime default value available
#define GPGCONF_FLAG_NOARG_DESC 64 // option with optional arg; special meaning if no arg set
// Change size of mFlags bitfield if adding new values here

QGpgMECryptoConfig::QGpgMECryptoConfig()
 : mComponents( 7 ), mParsed( false )
{
    mComponents.setAutoDelete( true );
}

QGpgMECryptoConfig::~QGpgMECryptoConfig()
{
}

void QGpgMECryptoConfig::runGpgConf( bool showErrors )
{
  // Run gpgconf --list-components to make the list of components

  KProcIO proc( QTextCodec::codecForName( "utf8" ) );
  proc << "gpgconf"; // must be in the PATH
  proc << "--list-components";

  QObject::connect( &proc, SIGNAL( readReady(KProcIO*) ),
                    this, SLOT( slotCollectStdOut(KProcIO*) ) );

  // run the process:
  int rc = 0;
  if ( !proc.start( KProcess::Block ) )
    rc = -1;
  else
    rc = ( proc.normalExit() ) ? proc.exitStatus() : -2 ;

  // handle errors, if any (and if requested)
  if ( showErrors && rc != 0 ) {
    QString wmsg = i18n("<qt>Failed to execute gpgconf:<br>%1</qt>");
    if ( rc == -1 )
        wmsg = wmsg.arg( i18n( "program not found" ) );
    else if ( rc == -2 )
        wmsg = wmsg.arg( i18n( "program cannot be executed" ) );
    else
        wmsg = wmsg.arg( strerror(rc) );
    kdWarning(5150) << wmsg << endl; // to see it from test_cryptoconfig.cpp
    KMessageBox::error(0, wmsg);
  }
  mParsed = true;
}

void QGpgMECryptoConfig::slotCollectStdOut( KProcIO* proc )
{
  QString line;
  int result;
  while( ( result = proc->readln(line) ) != -1 ) {
    //kdDebug(5150) << "GOT LINE:" << line << endl;
    // Format: NAME:DESCRIPTION
    QStringList lst = QStringList::split( ':', line, true );
    if ( lst.count() >= 2 ) {
      mComponents.insert( lst[0], new QGpgMECryptoConfigComponent( this, lst[0], lst[1] ) );
    } else {
      kdWarning(5150) << "Parse error on gpgconf --list-components output: " << line << endl;
    }
  }
}

QStringList QGpgMECryptoConfig::componentList() const
{
  if ( !mParsed )
    const_cast<QGpgMECryptoConfig*>( this )->runGpgConf( true );
  QDictIterator<QGpgMECryptoConfigComponent> it( mComponents );
  QStringList names;
  for( ; it.current(); ++it )
    names.push_back( it.currentKey() );
  return names;
}

Kleo::CryptoConfigComponent* QGpgMECryptoConfig::component( const QString& name ) const
{
  if ( !mParsed )
    const_cast<QGpgMECryptoConfig*>( this )->runGpgConf( false );
  return mComponents.find( name );
}

void QGpgMECryptoConfig::sync( bool runtime )
{
  QDictIterator<QGpgMECryptoConfigComponent> it( mComponents );
  for( ; it.current(); ++it )
    it.current()->sync( runtime );
}

void QGpgMECryptoConfig::clear()
{
  s_duringClear = true;
  mComponents.clear();
  s_duringClear = false;
  mParsed = false; // next call to componentList/component will need to run gpgconf again
}

////

QGpgMECryptoConfigComponent::QGpgMECryptoConfigComponent( QGpgMECryptoConfig*, const QString& name, const QString& description )
  : mGroups( 7 ), mName( name ), mDescription( description )
{
  mGroups.setAutoDelete( true );
  runGpgConf();
}

QGpgMECryptoConfigComponent::~QGpgMECryptoConfigComponent()
{
}

void QGpgMECryptoConfigComponent::runGpgConf()
{
  // Run gpgconf --list-options <component>, and create all groups and entries for that component

  KProcIO proc( QTextCodec::codecForName( "utf8" ) );
  proc << "gpgconf"; // must be in the PATH
  proc << "--list-options";
  proc << mName;

  //kdDebug(5150) << "Running gpgconf --list-options " << mName << endl;

  QObject::connect( &proc, SIGNAL( readReady(KProcIO*) ),
                    this, SLOT( slotCollectStdOut(KProcIO*) ) );
  mCurrentGroup = 0;

  // run the process:
  int rc = 0;
  if ( !proc.start( KProcess::Block ) )
    rc = -1;
  else
    rc = ( proc.normalExit() ) ? proc.exitStatus() : -1 ;

  if( rc != 0 ) // Can it really be non-0, when gpg-config --list-components worked?
    kdWarning(5150) << k_funcinfo << ":" << strerror( rc ) << endl;
  else {
    if ( mCurrentGroup && !mCurrentGroup->mEntries.isEmpty() ) // only add non-empty groups
      mGroups.insert( mCurrentGroupName, mCurrentGroup );
  }
}

void QGpgMECryptoConfigComponent::slotCollectStdOut( KProcIO* proc )
{
  QString line;
  int result;
  while( ( result = proc->readln(line) ) != -1 ) {
    //kdDebug(5150) << "GOT LINE:" << line << endl;
    // Format: NAME:FLAGS:LEVEL:DESCRIPTION:TYPE:ALT-TYPE:ARGNAME:DEFAULT:ARGDEF:VALUE
    QStringList lst = QStringList::split( ':', line, true );
    if ( lst.count() >= 10 ) {
      int flags = lst[1].toInt();
      int level = lst[2].toInt();
      if ( level > 2 ) // invisible or internal -> skip it;
        continue;<commit_msg>forward port: comment fix and better error message<commit_after>/*
    qgpgmecryptoconfig.cpp

    This file is part of libkleopatra, the KDE keymanagement library
    Copyright (c) 2004 Klarlvdalens Datakonsult AB

    Libkleopatra is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.

    Libkleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "qgpgmecryptoconfig.h"
#include <kdebug.h>
#include <kprocio.h>
#include <errno.h>
#include <kmessagebox.h>
#include <klocale.h>

#include <assert.h>
#include <ktempfile.h>
#include <qfile.h>
#include <stdlib.h>
#include <qtextcodec.h>

// Just for the Q_ASSERT in the dtor. Not thread-safe, but who would
// have 2 threads talking to gpgconf anyway? :)
static bool s_duringClear = false;

#define GPGCONF_FLAG_GROUP 1
#define GPGCONF_FLAG_OPTIONAL 2
#define GPGCONF_FLAG_LIST 4
#define GPGCONF_FLAG_RUNTIME 8
#define GPGCONF_FLAG_DEFAULT 16 // fixed default value available
#define GPGCONF_FLAG_DEFAULT_DESC 32 // runtime default value available
#define GPGCONF_FLAG_NOARG_DESC 64 // option with optional arg; special meaning if no arg set
// Change size of mFlags bitfield if adding new values here

QGpgMECryptoConfig::QGpgMECryptoConfig()
 : mComponents( 7 ), mParsed( false )
{
    mComponents.setAutoDelete( true );
}

QGpgMECryptoConfig::~QGpgMECryptoConfig()
{
}

void QGpgMECryptoConfig::runGpgConf( bool showErrors )
{
  // Run gpgconf --list-components to make the list of components

  KProcIO proc( QTextCodec::codecForName( "utf8" ) );
  proc << "gpgconf"; // must be in the PATH
  proc << "--list-components";

  QObject::connect( &proc, SIGNAL( readReady(KProcIO*) ),
                    this, SLOT( slotCollectStdOut(KProcIO*) ) );

  // run the process:
  int rc = 0;
  if ( !proc.start( KProcess::Block ) )
    rc = -1;
  else
    rc = ( proc.normalExit() ) ? proc.exitStatus() : -2 ;

  // handle errors, if any (and if requested)
  if ( showErrors && rc != 0 ) {
    QString wmsg = i18n("<qt>Failed to execute gpgconf:<br>%1</qt>");
    if ( rc == -1 )
        wmsg = wmsg.arg( i18n( "program not found" ) );
    else if ( rc == -2 )
        wmsg = wmsg.arg( i18n( "program cannot be executed" ) );
    else
        wmsg = wmsg.arg( strerror(rc) );
    kdWarning(5150) << wmsg << endl; // to see it from test_cryptoconfig.cpp
    KMessageBox::error(0, wmsg);
  }
  mParsed = true;
}

void QGpgMECryptoConfig::slotCollectStdOut( KProcIO* proc )
{
  QString line;
  int result;
  while( ( result = proc->readln(line) ) != -1 ) {
    //kdDebug(5150) << "GOT LINE:" << line << endl;
    // Format: NAME:DESCRIPTION
    QStringList lst = QStringList::split( ':', line, true );
    if ( lst.count() >= 2 ) {
      mComponents.insert( lst[0], new QGpgMECryptoConfigComponent( this, lst[0], lst[1] ) );
    } else {
      kdWarning(5150) << "Parse error on gpgconf --list-components output: " << line << endl;
    }
  }
}

QStringList QGpgMECryptoConfig::componentList() const
{
  if ( !mParsed )
    const_cast<QGpgMECryptoConfig*>( this )->runGpgConf( true );
  QDictIterator<QGpgMECryptoConfigComponent> it( mComponents );
  QStringList names;
  for( ; it.current(); ++it )
    names.push_back( it.currentKey() );
  return names;
}

Kleo::CryptoConfigComponent* QGpgMECryptoConfig::component( const QString& name ) const
{
  if ( !mParsed )
    const_cast<QGpgMECryptoConfig*>( this )->runGpgConf( false );
  return mComponents.find( name );
}

void QGpgMECryptoConfig::sync( bool runtime )
{
  QDictIterator<QGpgMECryptoConfigComponent> it( mComponents );
  for( ; it.current(); ++it )
    it.current()->sync( runtime );
}

void QGpgMECryptoConfig::clear()
{
  s_duringClear = true;
  mComponents.clear();
  s_duringClear = false;
  mParsed = false; // next call to componentList/component will need to run gpgconf again
}

////

QGpgMECryptoConfigComponent::QGpgMECryptoConfigComponent( QGpgMECryptoConfig*, const QString& name, const QString& description )
  : mGroups( 7 ), mName( name ), mDescription( description )
{
  mGroups.setAutoDelete( true );
  runGpgConf();
}

QGpgMECryptoConfigComponent::~QGpgMECryptoConfigComponent()
{
}

void QGpgMECryptoConfigComponent::runGpgConf()
{
  // Run gpgconf --list-options <component>, and create all groups and entries for that component

  KProcIO proc( QTextCodec::codecForName( "utf8" ) );
  proc << "gpgconf"; // must be in the PATH
  proc << "--list-options";
  proc << mName;

  //kdDebug(5150) << "Running gpgconf --list-options " << mName << endl;

  QObject::connect( &proc, SIGNAL( readReady(KProcIO*) ),
                    this, SLOT( slotCollectStdOut(KProcIO*) ) );
  mCurrentGroup = 0;

  // run the process:
  int rc = 0;
  if ( !proc.start( KProcess::Block ) )
    rc = -1;
  else
    rc = ( proc.normalExit() ) ? proc.exitStatus() : -1 ;

  if( rc != 0 ) // can happen when using the wrong version of gpg...
    kdWarning(5150) << "Running 'gpgconf --list-options " << mName << "' failed. " << strerror( rc ) << ", but try that command to see the real output" << endl;
  else {
    if ( mCurrentGroup && !mCurrentGroup->mEntries.isEmpty() ) // only add non-empty groups
      mGroups.insert( mCurrentGroupName, mCurrentGroup );
  }
}

void QGpgMECryptoConfigComponent::slotCollectStdOut( KProcIO* proc )
{
  QString line;
  int result;
  while( ( result = proc->readln(line) ) != -1 ) {
    //kdDebug(5150) << "GOT LINE:" << line << endl;
    // Format: NAME:FLAGS:LEVEL:DESCRIPTION:TYPE:ALT-TYPE:ARGNAME:DEFAULT:ARGDEF:VALUE
    QStringList lst = QStringList::split( ':', line, true );
    if ( lst.count() >= 10 ) {
      int flags = lst[1].toInt();
      int level = lst[2].toInt();
      if ( level > 2 ) // invisible or internal -> skip it;
        continue;
{'fraction_non_alphanumeric': 0.11664968709067093, 'fraction_numerical': 0.012880221219618687, 'mean_word_length': 3.5266798418972334, 'pattern_counts': {'":': 1, '<': 135, '<?xml version=': 0, '>': 59, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2976702', 'n_tokens_mistral': 4609, 'n_tokens_neox': 4513, 'n_words': 1423}