qca-gnupg-2.0.0-beta3/0000755000175000017500000000000011003741251013773 5ustar justinjustinqca-gnupg-2.0.0-beta3/gpgproc/0000755000175000017500000000000011003741243015435 5ustar justinjustinqca-gnupg-2.0.0-beta3/gpgproc/gpgproc.cpp0000644000175000017500000004370010776337271017630 0ustar justinjustin/* * Copyright (C) 2003-2007 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #include "gpgproc.h" #include "sprocess.h" #ifdef Q_OS_MAC #define QT_PIPE_HACK #endif #define QPROC_SIGNAL_RELAY using namespace QCA; namespace gpgQCAPlugin { void releaseAndDeleteLater(QObject *owner, QObject *obj) { obj->disconnect(owner); obj->setParent(0); obj->deleteLater(); } //---------------------------------------------------------------------------- // SafeTimer //---------------------------------------------------------------------------- SafeTimer::SafeTimer(QObject *parent) : QObject(parent) { timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SIGNAL(timeout())); } SafeTimer::~SafeTimer() { releaseAndDeleteLater(this, timer); } int SafeTimer::interval() const { return timer->interval(); } bool SafeTimer::isActive() const { return timer->isActive(); } bool SafeTimer::isSingleShot() const { return timer->isSingleShot(); } void SafeTimer::setInterval(int msec) { timer->setInterval(msec); } void SafeTimer::setSingleShot(bool singleShot) { timer->setSingleShot(singleShot); } int SafeTimer::timerId() const { return timer->timerId(); } void SafeTimer::start(int msec) { timer->start(msec); } void SafeTimer::start() { timer->start(); } void SafeTimer::stop() { timer->stop(); } //---------------------------------------------------------------------------- // QProcessSignalRelay //---------------------------------------------------------------------------- class QProcessSignalRelay : public QObject { Q_OBJECT public: QProcessSignalRelay(QProcess *proc, QObject *parent = 0) :QObject(parent) { qRegisterMetaType("QProcess::ProcessError"); connect(proc, SIGNAL(started()), SLOT(proc_started()), Qt::QueuedConnection); connect(proc, SIGNAL(readyReadStandardOutput()), SLOT(proc_readyReadStandardOutput()), Qt::QueuedConnection); connect(proc, SIGNAL(readyReadStandardError()), SLOT(proc_readyReadStandardError()), Qt::QueuedConnection); connect(proc, SIGNAL(bytesWritten(qint64)), SLOT(proc_bytesWritten(qint64)), Qt::QueuedConnection); connect(proc, SIGNAL(finished(int)), SLOT(proc_finished(int)), Qt::QueuedConnection); connect(proc, SIGNAL(error(QProcess::ProcessError)), SLOT(proc_error(QProcess::ProcessError)), Qt::QueuedConnection); } signals: void started(); void readyReadStandardOutput(); void readyReadStandardError(); void bytesWritten(qint64); void finished(int); void error(QProcess::ProcessError); public slots: void proc_started() { emit started(); } void proc_readyReadStandardOutput() { emit readyReadStandardOutput(); } void proc_readyReadStandardError() { emit readyReadStandardError(); } void proc_bytesWritten(qint64 x) { emit bytesWritten(x); } void proc_finished(int x) { emit finished(x); } void proc_error(QProcess::ProcessError x) { emit error(x); } }; //---------------------------------------------------------------------------- // GPGProc //---------------------------------------------------------------------------- enum ResetMode { ResetSession = 0, ResetSessionAndData = 1, ResetAll = 2 }; class GPGProc::Private : public QObject { Q_OBJECT public: GPGProc *q; QString bin; QStringList args; GPGProc::Mode mode; SProcess *proc; #ifdef QPROC_SIGNAL_RELAY QProcessSignalRelay *proc_relay; #endif QPipe pipeAux, pipeCommand, pipeStatus; QByteArray statusBuf; QStringList statusLines; GPGProc::Error error; int exitCode; SafeTimer startTrigger, doneTrigger; QByteArray pre_stdin, pre_aux; #ifdef QPIPE_SECURE SecureArray pre_command; #else QByteArray pre_command; #endif bool pre_stdin_close, pre_aux_close, pre_command_close; bool need_status, fin_process, fin_process_success, fin_status; QByteArray leftover_stdout; QByteArray leftover_stderr; Private(GPGProc *_q) : QObject(_q), q(_q), pipeAux(this), pipeCommand(this), pipeStatus(this), startTrigger(this), doneTrigger(this) { qRegisterMetaType("gpgQCAPlugin::GPGProc::Error"); proc = 0; #ifdef QPROC_SIGNAL_RELAY proc_relay = 0; #endif startTrigger.setSingleShot(true); doneTrigger.setSingleShot(true); connect(&pipeAux.writeEnd(), SIGNAL(bytesWritten(int)), SLOT(aux_written(int))); connect(&pipeAux.writeEnd(), SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(aux_error(QCA::QPipeEnd::Error))); connect(&pipeCommand.writeEnd(), SIGNAL(bytesWritten(int)), SLOT(command_written(int))); connect(&pipeCommand.writeEnd(), SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(command_error(QCA::QPipeEnd::Error))); connect(&pipeStatus.readEnd(), SIGNAL(readyRead()), SLOT(status_read())); connect(&pipeStatus.readEnd(), SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(status_error(QCA::QPipeEnd::Error))); connect(&startTrigger, SIGNAL(timeout()), SLOT(doStart())); connect(&doneTrigger, SIGNAL(timeout()), SLOT(doTryDone())); reset(ResetSessionAndData); } ~Private() { reset(ResetSession); } void closePipes() { #ifdef QT_PIPE_HACK pipeAux.readEnd().reset(); pipeCommand.readEnd().reset(); pipeStatus.writeEnd().reset(); #endif pipeAux.reset(); pipeCommand.reset(); pipeStatus.reset(); } void reset(ResetMode mode) { #ifndef QT_PIPE_HACK closePipes(); #endif if(proc) { proc->disconnect(this); if(proc->state() != QProcess::NotRunning) proc->terminate(); proc->setParent(0); #ifdef QPROC_SIGNAL_RELAY releaseAndDeleteLater(this, proc_relay); proc_relay = 0; delete proc; // should be safe to do thanks to relay #else proc->deleteLater(); #endif proc = 0; } #ifdef QT_PIPE_HACK closePipes(); #endif startTrigger.stop(); doneTrigger.stop(); pre_stdin.clear(); pre_aux.clear(); pre_command.clear(); pre_stdin_close = false; pre_aux_close = false; pre_command_close = false; need_status = false; fin_process = false; fin_status = false; if(mode >= ResetSessionAndData) { statusBuf.clear(); statusLines.clear(); leftover_stdout.clear(); leftover_stderr.clear(); error = GPGProc::FailedToStart; exitCode = -1; } } bool setupPipes(bool makeAux) { if(makeAux && !pipeAux.create()) { closePipes(); emit q->debug("Error creating pipeAux"); return false; } #ifdef QPIPE_SECURE if(!pipeCommand.create(true)) // secure #else if(!pipeCommand.create()) #endif { closePipes(); emit q->debug("Error creating pipeCommand"); return false; } if(!pipeStatus.create()) { closePipes(); emit q->debug("Error creating pipeStatus"); return false; } return true; } void setupArguments() { QStringList fullargs; fullargs += "--no-tty"; if(mode == ExtendedMode) { fullargs += "--enable-special-filenames"; fullargs += "--status-fd"; fullargs += QString::number(pipeStatus.writeEnd().idAsInt()); fullargs += "--command-fd"; fullargs += QString::number(pipeCommand.readEnd().idAsInt()); } for(int n = 0; n < args.count(); ++n) { QString a = args[n]; if(mode == ExtendedMode && a == "-&?") fullargs += QString("-&") + QString::number(pipeAux.readEnd().idAsInt()); else fullargs += a; } QString fullcmd = fullargs.join(" "); emit q->debug(QString("Running: [") + bin + ' ' + fullcmd + ']'); args = fullargs; } public slots: void doStart() { #ifdef Q_OS_WIN // Note: for unix, inheritability is set in SProcess if(pipeAux.readEnd().isValid()) pipeAux.readEnd().setInheritable(true); if(pipeCommand.readEnd().isValid()) pipeCommand.readEnd().setInheritable(true); if(pipeStatus.writeEnd().isValid()) pipeStatus.writeEnd().setInheritable(true); #endif setupArguments(); proc->start(bin, args); // FIXME: From reading the source to Qt on both windows // and unix platforms, we know that fork/CreateProcess // are called in start. However this is not guaranteed // from an API perspective. We should probably call // QProcess::waitForStarted() to synchronously ensure // fork/CreateProcess are called before closing these // pipes. pipeAux.readEnd().close(); pipeCommand.readEnd().close(); pipeStatus.writeEnd().close(); } void aux_written(int x) { emit q->bytesWrittenAux(x); } void aux_error(QCA::QPipeEnd::Error) { emit q->debug("Aux: Pipe error"); reset(ResetSession); emit q->error(GPGProc::ErrorWrite); } void command_written(int x) { emit q->bytesWrittenCommand(x); } void command_error(QCA::QPipeEnd::Error) { emit q->debug("Command: Pipe error"); reset(ResetSession); emit q->error(GPGProc::ErrorWrite); } void status_read() { if(readAndProcessStatusData()) emit q->readyReadStatusLines(); } void status_error(QCA::QPipeEnd::Error e) { if(e == QPipeEnd::ErrorEOF) emit q->debug("Status: Closed (EOF)"); else emit q->debug("Status: Closed (gone)"); fin_status = true; doTryDone(); } void proc_started() { emit q->debug("Process started"); // Note: we don't close these here anymore. instead we // do it just after calling proc->start(). // close these, we don't need them /*pipeAux.readEnd().close(); pipeCommand.readEnd().close(); pipeStatus.writeEnd().close();*/ // do the pre* stuff if(!pre_stdin.isEmpty()) { proc->write(pre_stdin); pre_stdin.clear(); } if(!pre_aux.isEmpty()) { pipeAux.writeEnd().write(pre_aux); pre_aux.clear(); } if(!pre_command.isEmpty()) { #ifdef QPIPE_SECURE pipeCommand.writeEnd().writeSecure(pre_command); #else pipeCommand.writeEnd().write(pre_command); #endif pre_command.clear(); } if(pre_stdin_close) proc->closeWriteChannel(); if(pre_aux_close) pipeAux.writeEnd().close(); if(pre_command_close) pipeCommand.writeEnd().close(); } void proc_readyReadStandardOutput() { emit q->readyReadStdout(); } void proc_readyReadStandardError() { emit q->readyReadStderr(); } void proc_bytesWritten(qint64 lx) { int x = (int)lx; emit q->bytesWrittenStdin(x); } void proc_finished(int x) { emit q->debug(QString("Process finished: %1").arg(x)); exitCode = x; fin_process = true; fin_process_success = true; if(need_status && !fin_status) { pipeStatus.readEnd().finalize(); fin_status = true; if(readAndProcessStatusData()) { doneTrigger.start(); emit q->readyReadStatusLines(); return; } } doTryDone(); } void proc_error(QProcess::ProcessError x) { QMap errmap; errmap[QProcess::FailedToStart] = "FailedToStart"; errmap[QProcess::Crashed] = "Crashed"; errmap[QProcess::Timedout] = "Timedout"; errmap[QProcess::WriteError] = "WriteError"; errmap[QProcess::ReadError] = "ReadError"; errmap[QProcess::UnknownError] = "UnknownError"; emit q->debug(QString("Process error: %1").arg(errmap[x])); if(x == QProcess::FailedToStart) error = GPGProc::FailedToStart; else if(x == QProcess::WriteError) error = GPGProc::ErrorWrite; else error = GPGProc::UnexpectedExit; fin_process = true; fin_process_success = false; #ifdef QT_PIPE_HACK // If the process fails to start, then the ends of the pipes // intended for the child process are still open. Some Mac // users experience a lockup if we close our ends of the pipes // when the child's ends are still open. If we ensure the // child's ends are closed, we prevent this lockup. I have no // idea why the problem even happens or why this fix should // work. pipeAux.readEnd().reset(); pipeCommand.readEnd().reset(); pipeStatus.writeEnd().reset(); #endif if(need_status && !fin_status) { pipeStatus.readEnd().finalize(); fin_status = true; if(readAndProcessStatusData()) { doneTrigger.start(); emit q->readyReadStatusLines(); return; } } doTryDone(); } void doTryDone() { if(!fin_process) return; if(need_status && !fin_status) return; emit q->debug("Done"); // get leftover data proc->setReadChannel(QProcess::StandardOutput); leftover_stdout = proc->readAll(); proc->setReadChannel(QProcess::StandardError); leftover_stderr = proc->readAll(); reset(ResetSession); if(fin_process_success) emit q->finished(exitCode); else emit q->error(error); } private: bool readAndProcessStatusData() { QByteArray buf = pipeStatus.readEnd().read(); if(buf.isEmpty()) return false; return processStatusData(buf); } // return true if there are newly parsed lines available bool processStatusData(const QByteArray &buf) { statusBuf.append(buf); // extract all lines QStringList list; while(1) { int n = statusBuf.indexOf('\n'); if(n == -1) break; // extract the string from statusbuf ++n; char *p = (char *)statusBuf.data(); QByteArray cs(p, n); int newsize = statusBuf.size() - n; memmove(p, p + n, newsize); statusBuf.resize(newsize); // convert to string without newline QString str = QString::fromUtf8(cs); str.truncate(str.length() - 1); // ensure it has a proper header if(str.left(9) != "[GNUPG:] ") continue; // take it off str = str.mid(9); // add to the list list += str; } if(list.isEmpty()) return false; statusLines += list; return true; } }; GPGProc::GPGProc(QObject *parent) :QObject(parent) { d = new Private(this); } GPGProc::~GPGProc() { delete d; } void GPGProc::reset() { d->reset(ResetAll); } bool GPGProc::isActive() const { return (d->proc ? true : false); } void GPGProc::start(const QString &bin, const QStringList &args, Mode mode) { if(isActive()) d->reset(ResetSessionAndData); if(mode == ExtendedMode) { if(!d->setupPipes(args.contains("-&?"))) { d->error = FailedToStart; // emit later QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection, Q_ARG(gpgQCAPlugin::GPGProc::Error, d->error)); return; } d->need_status = true; emit debug("Pipe setup complete"); } d->proc = new SProcess(d); #ifdef Q_OS_UNIX QList plist; if(d->pipeAux.readEnd().isValid()) plist += d->pipeAux.readEnd().id(); if(d->pipeCommand.readEnd().isValid()) plist += d->pipeCommand.readEnd().id(); if(d->pipeStatus.writeEnd().isValid()) plist += d->pipeStatus.writeEnd().id(); d->proc->setInheritPipeList(plist); #endif // enable the pipes we want if(d->pipeAux.writeEnd().isValid()) d->pipeAux.writeEnd().enable(); if(d->pipeCommand.writeEnd().isValid()) d->pipeCommand.writeEnd().enable(); if(d->pipeStatus.readEnd().isValid()) d->pipeStatus.readEnd().enable(); #ifdef QPROC_SIGNAL_RELAY d->proc_relay = new QProcessSignalRelay(d->proc, d); connect(d->proc_relay, SIGNAL(started()), d, SLOT(proc_started())); connect(d->proc_relay, SIGNAL(readyReadStandardOutput()), d, SLOT(proc_readyReadStandardOutput())); connect(d->proc_relay, SIGNAL(readyReadStandardError()), d, SLOT(proc_readyReadStandardError())); connect(d->proc_relay, SIGNAL(bytesWritten(qint64)), d, SLOT(proc_bytesWritten(qint64))); connect(d->proc_relay, SIGNAL(finished(int)), d, SLOT(proc_finished(int))); connect(d->proc_relay, SIGNAL(error(QProcess::ProcessError)), d, SLOT(proc_error(QProcess::ProcessError))); #else connect(d->proc, SIGNAL(started()), d, SLOT(proc_started())); connect(d->proc, SIGNAL(readyReadStandardOutput()), d, SLOT(proc_readyReadStandardOutput())); connect(d->proc, SIGNAL(readyReadStandardError()), d, SLOT(proc_readyReadStandardError())); connect(d->proc, SIGNAL(bytesWritten(qint64)), d, SLOT(proc_bytesWritten(qint64))); connect(d->proc, SIGNAL(finished(int)), d, SLOT(proc_finished(int))); connect(d->proc, SIGNAL(error(QProcess::ProcessError)), d, SLOT(proc_error(QProcess::ProcessError))); #endif d->bin = bin; d->args = args; d->mode = mode; d->startTrigger.start(); } QByteArray GPGProc::readStdout() { if(d->proc) { d->proc->setReadChannel(QProcess::StandardOutput); return d->proc->readAll(); } else { QByteArray a = d->leftover_stdout; d->leftover_stdout.clear(); return a; } } QByteArray GPGProc::readStderr() { if(d->proc) { d->proc->setReadChannel(QProcess::StandardError); return d->proc->readAll(); } else { QByteArray a = d->leftover_stderr; d->leftover_stderr.clear(); return a; } } QStringList GPGProc::readStatusLines() { QStringList out = d->statusLines; d->statusLines.clear(); return out; } void GPGProc::writeStdin(const QByteArray &a) { if(!d->proc || a.isEmpty()) return; if(d->proc->state() == QProcess::Running) d->proc->write(a); else d->pre_stdin += a; } void GPGProc::writeAux(const QByteArray &a) { if(!d->proc || a.isEmpty()) return; if(d->proc->state() == QProcess::Running) d->pipeAux.writeEnd().write(a); else d->pre_aux += a; } #ifdef QPIPE_SECURE void GPGProc::writeCommand(const SecureArray &a) #else void GPGProc::writeCommand(const QByteArray &a) #endif { if(!d->proc || a.isEmpty()) return; if(d->proc->state() == QProcess::Running) #ifdef QPIPE_SECURE d->pipeCommand.writeEnd().writeSecure(a); #else d->pipeCommand.writeEnd().write(a); #endif else d->pre_command += a; } void GPGProc::closeStdin() { if(!d->proc) return; if(d->proc->state() == QProcess::Running) d->proc->closeWriteChannel(); else d->pre_stdin_close = true; } void GPGProc::closeAux() { if(!d->proc) return; if(d->proc->state() == QProcess::Running) d->pipeAux.writeEnd().close(); else d->pre_aux_close = true; } void GPGProc::closeCommand() { if(!d->proc) return; if(d->proc->state() == QProcess::Running) d->pipeCommand.writeEnd().close(); else d->pre_command_close = true; } } #include "gpgproc.moc" qca-gnupg-2.0.0-beta3/gpgproc/sprocess.cpp0000644000175000017500000000273110627650175020023 0ustar justinjustin/* * Copyright (C) 2003-2005 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #include "sprocess.h" #ifdef Q_OS_UNIX # include # include #endif namespace gpgQCAPlugin { //---------------------------------------------------------------------------- // SProcess //---------------------------------------------------------------------------- SProcess::SProcess(QObject *parent) :QProcess(parent) { } SProcess::~SProcess() { } #ifdef Q_OS_UNIX void SProcess::setInheritPipeList(const QList &list) { pipeList = list; } void SProcess::setupChildProcess() { // set the pipes to be inheritable for(int n = 0; n < pipeList.count(); ++n) ::fcntl(pipeList[n], F_SETFD, (::fcntl(pipeList[n], F_GETFD) & ~FD_CLOEXEC)); } #endif } qca-gnupg-2.0.0-beta3/gpgproc/gpgproc.h0000644000175000017500000000612410776337271017274 0ustar justinjustin/* * Copyright (C) 2003-2005 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #ifndef GPGPROC_H #define GPGPROC_H #include "qpipe.h" class QTimer; namespace gpgQCAPlugin { // FIXME: Even though deleting an object during a metacall event is supposed // to be legal with Qt, it is unfortunately buggy (at least before Qt 4.4). // This function performs the following steps: // obj->disconnect(owner); // to prevent future signals to owner // obj->setParent(0); // to prevent delete if parent is deleted // obj->deleteLater(); // now we can forget about the object void releaseAndDeleteLater(QObject *owner, QObject *obj); class SafeTimer : public QObject { Q_OBJECT public: SafeTimer(QObject *parent = 0); ~SafeTimer(); int interval() const; bool isActive() const; bool isSingleShot() const; void setInterval(int msec); void setSingleShot(bool singleShot); int timerId() const; public slots: void start(int msec); void start(); void stop(); signals: void timeout(); private: QTimer *timer; }; // GPGProc - executes gpg and provides access to all 6 channels. NormalMode // enables stdout, stderr, and stdin. ExtendedMode has those 3 plus status // aux, and command. The aux channel is connected to the '-&?' argument. // The debug() signal, as well as stderr, can be used for diagnostic text. class GPGProc : public QObject { Q_OBJECT public: enum Error { FailedToStart, UnexpectedExit, ErrorWrite }; enum Mode { NormalMode, ExtendedMode }; GPGProc(QObject *parent = 0); ~GPGProc(); void reset(); bool isActive() const; void start(const QString &bin, const QStringList &args, Mode m = ExtendedMode); QByteArray readStdout(); QByteArray readStderr(); QStringList readStatusLines(); void writeStdin(const QByteArray &a); void writeAux(const QByteArray &a); #ifdef QPIPE_SECURE void writeCommand(const QCA::SecureArray &a); #else void writeCommand(const QByteArray &a); #endif void closeStdin(); void closeAux(); void closeCommand(); Q_SIGNALS: void error(gpgQCAPlugin::GPGProc::Error error); void finished(int exitCode); void readyReadStdout(); void readyReadStderr(); void readyReadStatusLines(); void bytesWrittenStdin(int bytes); void bytesWrittenAux(int bytes); void bytesWrittenCommand(int bytes); void debug(const QString &str); // not signal-safe private: class Private; friend class Private; Private *d; }; } #endif qca-gnupg-2.0.0-beta3/gpgproc/sprocess.h0000644000175000017500000000224310627650175017466 0ustar justinjustin/* * Copyright (C) 2003-2005 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #ifndef SPROCESS_H #define SPROCESS_H #include #include namespace gpgQCAPlugin { class SProcess : public QProcess { Q_OBJECT public: SProcess(QObject *parent = 0); ~SProcess(); #ifdef Q_OS_UNIX void setInheritPipeList(const QList &); protected: virtual void setupChildProcess(); private: QList pipeList; #endif }; } #endif qca-gnupg-2.0.0-beta3/gpgproc/gpgproc.pri0000644000175000017500000000015210412723655017622 0ustar justinjustinHEADERS += \ $$PWD/sprocess.h \ $$PWD/gpgproc.h SOURCES += \ $$PWD/sprocess.cpp \ $$PWD/gpgproc.cpp qca-gnupg-2.0.0-beta3/gpgproc/README0000644000175000017500000000056610250535674016340 0ustar justinjustinGPGProc launches a single instance of GPG and provides a friendly API to work with all six possible pipe channels. Theoretically, it should be possible to build any GPG front end with it, even though qca-gnupg uses it for only a handful of operations. If you are writing a Qt-based GPG front end, please use this class. GPGProc works on both Windows and Unix platforms. qca-gnupg-2.0.0-beta3/configure0000755000175000017500000010734111003741251015710 0ustar justinjustin#!/bin/sh # # Generated by qconf 1.4 ( http://delta.affinix.com/qconf/ ) # show_usage() { cat </dev/null` if echo $WHICH | grep 'shell built-in command' >/dev/null 2>&1; then WHICH=which elif [ -z "$WHICH" ]; then if which which >/dev/null 2>&1; then WHICH=which else for a in /usr/ucb /usr/bin /bin /usr/local/bin; do if [ -x $a/which ]; then WHICH=$a/which break; fi done fi fi if [ -z "$WHICH" ]; then OLD_IFS=$IFS IFS=: for a in $PATH; do if [ -x $a/$1 ]; then echo "$a/$1" IFS=$OLD_IFS export IFS HOME=$OLD_HOME export HOME return 0 fi done IFS=$OLD_IFS export IFS else a=`"$WHICH" "$1" 2>/dev/null` if [ ! -z "$a" -a -x "$a" ]; then echo "$a" HOME=$OLD_HOME export HOME return 0 fi fi HOME=$OLD_HOME export HOME return 1 } WHICH=which_command # find a make command if [ -z "$MAKE" ]; then MAKE= for mk in gmake make; do if $WHICH $mk >/dev/null 2>&1; then MAKE=`$WHICH $mk` break fi done if [ -z "$MAKE" ]; then echo "You don't seem to have 'make' or 'gmake' in your PATH." echo "Cannot proceed." exit 1 fi fi show_qt_info() { printf "Be sure you have a proper Qt 4.0 build environment set up. This means not\n" printf "just Qt, but also a C++ compiler, a make tool, and any other packages\n" printf "necessary for compiling C++ programs.\n" printf "\n" printf "If you are certain everything is installed, then it could be that Qt 4 is not\n" printf "being recognized or that a different version of Qt is being detected by\n" printf "mistake (for example, this could happen if \$QTDIR is pointing to a Qt 3\n" printf "installation). At least one of the following conditions must be satisfied:\n" printf "\n" printf " 1) --qtdir is set to the location of Qt\n" printf " 2) \$QTDIR is set to the location of Qt\n" printf " 3) QtCore is in the pkg-config database\n" printf " 4) qmake is in the \$PATH\n" printf "\n" printf "This script will use the first one it finds to be true, checked in the above\n" printf "order. #3 and #4 are the recommended options. #1 and #2 are mainly for\n" printf "overriding the system configuration.\n" printf "\n" } while [ $# -gt 0 ]; do optarg=`expr "x$1" : 'x[^=]*=\(.*\)'` case "$1" in --qtdir=*) EX_QTDIR=$optarg shift ;; --static) QC_STATIC="Y" shift ;; --release) QC_RELEASE="Y" shift ;; --debug) QC_DEBUG="Y" shift ;; --debug-and-release) QC_DEBUG_AND_RELEASE="Y" shift ;; --no-separate-debug-info) QC_NO_SEPARATE_DEBUG_INFO="Y" shift ;; --separate-debug-info) QC_SEPARATE_DEBUG_INFO="Y" shift ;; --universal) QC_UNIVERSAL="Y" shift ;; --mac-sdk=*) QC_MAC_SDK=$optarg shift ;; --plugins-path=*) QC_PLUGINS_PATH=$optarg shift ;; --with-qca=*) QC_WITH_QCA=$optarg shift ;; --verbose) QC_VERBOSE="Y" shift ;; --help) show_usage; exit ;; *) show_usage; exit ;; esac done echo "Configuring qca-gnupg ..." if [ "$QC_VERBOSE" = "Y" ]; then echo echo EX_QTDIR=$EX_QTDIR echo QC_STATIC=$QC_STATIC echo QC_RELEASE=$QC_RELEASE echo QC_DEBUG=$QC_DEBUG echo QC_DEBUG_AND_RELEASE=$QC_DEBUG_AND_RELEASE echo QC_NO_SEPARATE_DEBUG_INFO=$QC_NO_SEPARATE_DEBUG_INFO echo QC_SEPARATE_DEBUG_INFO=$QC_SEPARATE_DEBUG_INFO echo QC_UNIVERSAL=$QC_UNIVERSAL echo QC_MAC_SDK=$QC_MAC_SDK echo QC_PLUGINS_PATH=$QC_PLUGINS_PATH echo QC_WITH_QCA=$QC_WITH_QCA echo fi printf "Verifying Qt 4 build environment ... " # run qmake -v and check version qmake_check_v4() { if [ -x "$1" ]; then if echo `$1 -v 2>&1` | grep "Qt version 4\." >/dev/null 2>&1; then return 0 elif [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: $1 not for Qt 4" fi fi return 1 } if [ "$QC_VERBOSE" = "Y" ]; then echo fi qm="" names="qmake-qt4 qmake4 qmake" # qt4 check: --qtdir if [ -z "$qm" ] && [ ! -z "$EX_QTDIR" ]; then for n in $names; do qstr=$EX_QTDIR/bin/$n if qmake_check_v4 "$qstr"; then qm=$qstr break; fi done fi if [ -z "$qm" ] && [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: qmake not found via --qtdir" fi # qt4 check: QTDIR if [ -z "$qm" ] && [ ! -z "$QTDIR" ]; then for n in $names; do qstr=$QTDIR/bin/$n if qmake_check_v4 "$qstr"; then qm=$qstr break; fi done fi if [ -z "$qm" ] && [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: qmake not found via \$QTDIR" fi # qt4 check: pkg-config if [ -z "$qm" ]; then str=`pkg-config QtCore --variable=exec_prefix 2>/dev/null` if [ ! -z "$str" ]; then for n in $names; do qstr=$str/bin/$n if qmake_check_v4 "$qstr"; then qm=$qstr break; fi done fi fi if [ -z "$qm" ] && [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: qmake not found via pkg-config" fi # qt4 check: PATH if [ -z "$qm" ]; then for n in $names; do qstr=`$WHICH $n 2>/dev/null` if qmake_check_v4 "$qstr"; then qm=$qstr break; fi done fi if [ -z "$qm" ] && [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: qmake not found via \$PATH" fi if [ -z "$qm" ]; then if [ "$QC_VERBOSE" = "Y" ]; then echo " -> fail" else echo "fail" fi printf "\n" printf "Reason: Unable to find the 'qmake' tool for Qt 4.\n" printf "\n" show_qt_info exit 1; fi if [ "$QC_VERBOSE" = "Y" ]; then echo qmake found in $qm fi gen_files() { cat >$1/modules.cpp <getenv("QC_RELEASE") == "Y") opt_release = true; if(conf->getenv("QC_DEBUG") == "Y") opt_debug = true; if(conf->getenv("QC_DEBUG_AND_RELEASE") == "Y") opt_debug_and_release = true; //if(conf->getenv("QC_NO_FRAMEWORK") == "Y") // opt_no_framework = true; //if(conf->getenv("QC_FRAMEWORK") == "Y") // opt_framework = true; if(conf->getenv("QC_NO_SEPARATE_DEBUG_INFO") == "Y") opt_no_separate_debug_info = true; if(conf->getenv("QC_SEPARATE_DEBUG_INFO") == "Y") opt_separate_debug_info = true; #ifndef Q_OS_MAC if(opt_debug_and_release) { printf("\nError: The --debug-and-release option is for mac only.\n"); exit(1); } #endif // sanity check exclusive options int x; // build mode x = 0; if(opt_release) ++x; if(opt_debug) ++x; if(opt_debug_and_release) ++x; if(x > 1) { printf("\nError: Use only one of --release, --debug, or --debug-and-release.\n"); exit(1); } // framework /*x = 0; if(opt_no_framework) ++x; if(opt_framework) ++x; if(x > 1) { printf("\nError: Use only one of --framework or --no-framework.\n"); exit(1); }*/ // debug info x = 0; if(opt_no_separate_debug_info) ++x; if(opt_separate_debug_info) ++x; if(x > 1) { printf("\nError: Use only one of --separate-debug-info or --no-separate-debug-info\n"); exit(1); } // now process the options if(opt_release) qc_buildmode_release = true; else if(opt_debug) qc_buildmode_debug = true; else if(opt_debug_and_release) { qc_buildmode_release = true; qc_buildmode_debug = true; } else // default qc_buildmode_release = true; /*if(opt_framework) qc_buildmode_framework = true; else if(opt_no_framework) { // nothing to do } else // default { // nothing to do }*/ if(opt_separate_debug_info) qc_buildmode_separate_debug_info = true; else if(opt_no_separate_debug_info) { // nothing to do } else // default { #ifndef Q_OS_MAC qc_buildmode_separate_debug_info = true; #endif } // make the string QStringList opts; if(qc_buildmode_release && qc_buildmode_debug) { opts += "debug_and_release"; opts += "build_all"; } else if(qc_buildmode_release) opts += "release"; else // qc_buildmode_debug opts += "debug"; //if(qc_buildmode_framework) // opts += "lib_bundle"; if(qc_buildmode_separate_debug_info) opts += "separate_debug_info"; QString str = QString("CONFIG += ") + opts.join(" ") + '\n'; conf->addExtra(str); return true; } }; #line 1 "universal.qcm" /* -----BEGIN QCMOD----- name: Mac universal binary support section: project arg: universal,Build with Mac universal binary support. arg: mac-sdk=[path],Path to Mac universal SDK (PPC host only). -----END QCMOD----- */ #define QC_UNIVERSAL bool qc_universal_enabled = false; QString qc_universal_sdk; //---------------------------------------------------------------------------- // qc_universal //---------------------------------------------------------------------------- class qc_universal : public ConfObj { public: qc_universal(Conf *c) : ConfObj(c) {} QString name() const { return "Mac universal binary support"; } QString shortname() const { return "universal"; } QString checkString() const { return QString(); } bool exec() { #ifdef Q_OS_MAC if(qc_getenv("QC_UNIVERSAL") == "Y") { qc_universal_enabled = true; QString str = "contains(QT_CONFIG,x86):contains(QT_CONFIG,ppc) {\n" " CONFIG += x86 ppc\n" "}\n"; QString sdk = qc_getenv("QC_MAC_SDK"); if(!sdk.isEmpty()) { str += QString("QMAKE_MAC_SDK = %1\n").arg(sdk); qc_universal_sdk = sdk; } conf->addExtra(str); } #endif return true; } }; #line 1 "qca.qcm" /* -----BEGIN QCMOD----- name: QCA >= 2.0 arg: with-qca=[path],Specify path to QCA tree, mainly for building against an uninstalled QCA. -----END QCMOD----- */ // based on crypto.prf. any changes made to that file need to be tracked here. static QString internal_crypto_prf(const QString &incdir, const QString &libdir) { QString out = QString( "CONFIG *= qt\n" "INCLUDEPATH += %1/QtCrypto\n" "LIBS += -L%2\n" "\n" "LINKAGE = -lqca\n" "CONFIG(debug, debug|release) {\n" " windows:LINKAGE = -lqcad\n" " mac:LINKAGE = -lqca_debug\n" "}\n" "LIBS += \$\$LINKAGE\n" ).arg(incdir, libdir); return out; } //---------------------------------------------------------------------------- // qc_qca //---------------------------------------------------------------------------- class qc_qca : public ConfObj { public: qc_qca(Conf *c) : ConfObj(c) {} QString name() const { return "QCA >= 2.0"; } QString shortname() const { return "qca"; } bool exec() { // get the build mode #ifdef BUILDMODE bool release = buildmode_release; bool debug = buildmode_debug; #else // else, default to just release mode bool release = true; bool debug = false; #endif // test for "crypto" feature and check qca version number QString qca_prefix, qca_incdir, qca_libdir, qca_crypto_prf; qca_prefix = conf->getenv("QC_WITH_QCA"); QString proextra; if(!qca_prefix.isEmpty()) { qca_incdir = qca_prefix + "/include"; qca_libdir = qca_prefix + "/lib"; qca_crypto_prf = internal_crypto_prf(qca_incdir, qca_libdir); proextra = "CONFIG += qt\n" "QT -= gui\n"; proextra += qca_crypto_prf; } else { proextra = "CONFIG += qt crypto\n" "QT -= gui\n"; } QString str = "#include \n" "\n" "int main()\n" "{\n" " unsigned long x = QCA_VERSION;\n" " if(x >= 0x020000 && x < 0x030000) return 0; else return 1;\n" "}\n"; if(release) { int ret; if(!conf->doCompileAndLink(str, QStringList(), QString(), proextra + "CONFIG += release\n", &ret)) return false; if(ret != 0) return false; } if(debug) { int ret; if(!conf->doCompileAndLink(str, QStringList(), QString(), proextra + "CONFIG += debug\n", &ret)) return false; if(ret != 0) return false; } if(!qca_prefix.isEmpty()) conf->addExtra(qca_crypto_prf); else conf->addExtra("CONFIG += crypto\n"); return true; } }; #line 1 "qcapluginpath.qcm" /* -----BEGIN QCMOD----- name: qcapluginpath section: project arg: plugins-path=[path],Path to install to. Default: qtdir/plugins -----END QCMOD----- */ class qc_qcapluginpath : public ConfObj { public: qc_qcapluginpath(Conf *c) : ConfObj(c) {} QString name() const { return "qcapluginpath"; } QString shortname() const { return "qcapluginpath"; } // no output QString checkString() const { return QString(); } bool exec() { QString plugins_path = conf->getenv("QC_PLUGINS_PATH"); // default to qtdir if(plugins_path.isEmpty()) plugins_path = QLibraryInfo::location(QLibraryInfo::PluginsPath); // install into plugins path QString str; str += QString( "target.path=%1/crypto\n" "INSTALLS += target\n" ).arg(plugins_path); conf->addExtra(str); return true; } }; EOT cat >$1/modules_new.cpp <required = true; o->disabled = false; o = new qc_universal(conf); o->required = true; o->disabled = false; o = new qc_qca(conf); o->required = true; o->disabled = false; o = new qc_qcapluginpath(conf); o->required = true; o->disabled = false; EOT cat >$1/conf4.h < class Conf; enum VersionMode { VersionMin, VersionExact, VersionMax, VersionAny }; // ConfObj // // Subclass ConfObj to create a new configuration module. class ConfObj { public: Conf *conf; bool required; bool disabled; bool success; ConfObj(Conf *c); virtual ~ConfObj(); // long or descriptive name of what is being checked/performed // example: "KDE >= 3.3" virtual QString name() const = 0; // short name // example: "kde" virtual QString shortname() const = 0; // string to display during check // default: "Checking for [name] ..." virtual QString checkString() const; // string to display after check // default: "yes" or "no", based on result of exec() virtual QString resultString() const; // this is where the checking code goes virtual bool exec() = 0; }; // Conf // // Interact with this class from your ConfObj to perform detection // operations and to output configuration parameters. class Conf { public: bool debug_enabled; QString qmake_path; QString maketool; QString DEFINES; QString INCLUDEPATH; QString LIBS; QString extra; QList list; QMap vars; Conf(); ~Conf(); QString getenv(const QString &var); QString qvar(const QString &s); bool exec(); void debug(const QString &s); QString expandIncludes(const QString &inc); QString expandLibs(const QString &lib); int doCommand(const QString &s, QByteArray *out = 0); int doCommand(const QString &prog, const QStringList &args, QByteArray *out = 0); bool doCompileAndLink(const QString &filedata, const QStringList &incs, const QString &libs, const QString &proextra, int *retcode = 0); bool checkHeader(const QString &path, const QString &h); bool findHeader(const QString &h, const QStringList &ext, QString *inc); bool checkLibrary(const QString &path, const QString &name); bool findLibrary(const QString &name, QString *lib); QString findProgram(const QString &prog); bool findSimpleLibrary(const QString &incvar, const QString &libvar, const QString &incname, const QString &libname, QString *incpath, QString *libs); bool findFooConfig(const QString &path, QString *version, QStringList *incs, QString *libs, QString *otherflags); bool findPkgConfig(const QString &name, VersionMode mode, const QString &req_version, QString *version, QStringList *incs, QString *libs, QString *otherflags); void addDefine(const QString &str); void addLib(const QString &str); void addIncludePath(const QString &str); void addExtra(const QString &str); private: bool first_debug; friend class ConfObj; void added(ConfObj *o); }; #endif EOT cat >$1/conf4.cpp < #include class MocTestObject : public QObject { Q_OBJECT public: MocTestObject() {} }; QString qc_getenv(const QString &var) { char *p = ::getenv(var.toLatin1().data()); if(!p) return QString(); return QString(p); } QStringList qc_pathlist() { QStringList list; QString path = qc_getenv("PATH"); if(!path.isEmpty()) list = path.split(':', QString::SkipEmptyParts); return list; } QString qc_findprogram(const QString &prog) { QString out; QStringList list = qc_pathlist(); for(int n = 0; n < list.count(); ++n) { QFileInfo fi(list[n] + '/' + prog); if(fi.exists() && fi.isExecutable()) { out = fi.filePath(); break; } } return out; } QString qc_findself(const QString &argv0) { if(argv0.contains('/')) return argv0; else return qc_findprogram(argv0); } int qc_runcommand(const QString &command, QByteArray *out, bool showOutput) { QString fullcmd = command; if(!showOutput) fullcmd += " 2>/dev/null"; FILE *f = popen(fullcmd.toLatin1().data(), "r"); if(!f) return -1; if(out) out->clear(); while(1) { char c = (char)fgetc(f); if(feof(f)) break; if(out) out->append(c); if(showOutput) fputc(c, stdout); } int ret = pclose(f); if(ret == -1) return -1; return ret; } int qc_runprogram(const QString &prog, const QStringList &args, QByteArray *out, bool showOutput) { QString fullcmd = prog; QString argstr = args.join(" "); if(!argstr.isEmpty()) fullcmd += QString(" ") + argstr; return qc_runcommand(fullcmd, out, showOutput); // TODO: use QProcess once it is fixed /* QProcess process; if(showOutput) process.setReadChannelMode(ForwardedChannels); process.start(prog, args); process.waitForFinished(-1); return process.exitCode(); */ } bool qc_removedir(const QString &dirPath) { QDir dir(dirPath); if(!dir.exists()) return false; QStringList list = dir.entryList(); foreach(QString s, list) { if(s == "." || s == "..") continue; QFileInfo fi(dir.filePath(s)); if(fi.isDir()) { if(!qc_removedir(fi.filePath())) return false; } else { if(!dir.remove(s)) return false; } } QString dirName = dir.dirName(); if(!dir.cdUp()) return false; if(!dir.rmdir(dirName)) return false; return true; } void qc_splitcflags(const QString &cflags, QStringList *incs, QStringList *otherflags) { incs->clear(); otherflags->clear(); QStringList cflagsList = cflags.split(" "); for(int n = 0; n < cflagsList.count(); ++n) { QString str = cflagsList[n]; if(str.startsWith("-I")) { // we want everything except the leading "-I" incs->append(str.remove(0, 2)); } else { // we want whatever is left otherflags->append(str); } } } QString qc_escapeArg(const QString &str) { QString out; for(int n = 0; n < (int)str.length(); ++n) { if(str[n] == '-') out += '_'; else out += str[n]; } return out; } //---------------------------------------------------------------------------- // ConfObj //---------------------------------------------------------------------------- ConfObj::ConfObj(Conf *c) { conf = c; conf->added(this); required = false; disabled = false; success = false; } ConfObj::~ConfObj() { } QString ConfObj::checkString() const { return QString("Checking for %1 ...").arg(name()); } QString ConfObj::resultString() const { if(success) return "yes"; else return "no"; } //---------------------------------------------------------------------------- // qc_internal_pkgconfig //---------------------------------------------------------------------------- class qc_internal_pkgconfig : public ConfObj { public: QString pkgname, desc; VersionMode mode; QString req_ver; qc_internal_pkgconfig(Conf *c, const QString &_name, const QString &_desc, VersionMode _mode, const QString &_req_ver) : ConfObj(c) { pkgname = _name; desc = _desc; mode = _mode; req_ver = _req_ver; } QString name() const { return desc; } QString shortname() const { return pkgname; } bool exec() { QStringList incs; QString version, libs, other; if(!conf->findPkgConfig(pkgname, mode, req_ver, &version, &incs, &libs, &other)) return false; for(int n = 0; n < incs.count(); ++n) conf->addIncludePath(incs[n]); if(!libs.isEmpty()) conf->addLib(libs); //if(!other.isEmpty()) // conf->addExtra(QString("QMAKE_CFLAGS += %1\n").arg(other)); return true; } }; //---------------------------------------------------------------------------- // Conf //---------------------------------------------------------------------------- Conf::Conf() { // TODO: no more vars? //vars.insert("QMAKE_INCDIR_X11", new QString(X11_INC)); //vars.insert("QMAKE_LIBDIR_X11", new QString(X11_LIBDIR)); //vars.insert("QMAKE_LIBS_X11", new QString(X11_LIB)); //vars.insert("QMAKE_CC", CC); debug_enabled = false; } Conf::~Conf() { qDeleteAll(list); } void Conf::added(ConfObj *o) { list.append(o); } QString Conf::getenv(const QString &var) { return qc_getenv(var); } void Conf::debug(const QString &s) { if(debug_enabled) { if(first_debug) printf("\n"); first_debug = false; printf(" * %s\n", qPrintable(s)); } } bool Conf::exec() { for(int n = 0; n < list.count(); ++n) { ConfObj *o = list[n]; // if this was a disabled-by-default option, check if it was enabled if(o->disabled) { QString v = QString("QC_ENABLE_") + qc_escapeArg(o->shortname()); if(getenv(v) != "Y") continue; } // and the opposite? else { QString v = QString("QC_DISABLE_") + qc_escapeArg(o->shortname()); if(getenv(v) == "Y") continue; } bool output = true; QString check = o->checkString(); if(check.isEmpty()) output = false; if(output) { printf("%s", check.toLatin1().data()); fflush(stdout); } first_debug = true; bool ok = o->exec(); o->success = ok; if(output) { QString result = o->resultString(); if(!first_debug) printf(" -> %s\n", result.toLatin1().data()); else printf(" %s\n", result.toLatin1().data()); } if(!ok && o->required) { printf("\nError: need %s!\n", o->name().toLatin1().data()); return false; } } return true; } QString Conf::qvar(const QString &s) { return vars.value(s); } QString Conf::expandIncludes(const QString &inc) { return QString("-I") + inc; } QString Conf::expandLibs(const QString &lib) { return QString("-L") + lib; } int Conf::doCommand(const QString &s, QByteArray *out) { debug(QString("[%1]").arg(s)); int r = qc_runcommand(s, out, debug_enabled); debug(QString("returned: %1").arg(r)); return r; } int Conf::doCommand(const QString &prog, const QStringList &args, QByteArray *out) { QString fullcmd = prog; QString argstr = args.join(" "); if(!argstr.isEmpty()) fullcmd += QString(" ") + argstr; debug(QString("[%1]").arg(fullcmd)); int r = qc_runprogram(prog, args, out, debug_enabled); debug(QString("returned: %1").arg(r)); return r; } bool Conf::doCompileAndLink(const QString &filedata, const QStringList &incs, const QString &libs, const QString &proextra, int *retcode) { QDir tmp(".qconftemp"); if(!tmp.mkdir("atest")) { debug("unable to create atest dir"); return false; } QDir dir(tmp.filePath("atest")); if(!dir.exists()) { debug("atest dir does not exist"); return false; } QString fname = dir.filePath("atest.cpp"); QString out = "atest"; QFile f(fname); if(!f.open(QFile::WriteOnly | QFile::Truncate)) { debug("unable to open atest.cpp for writing"); return false; } if(f.write(filedata.toLatin1()) == -1) { debug("error writing to atest.cpp"); return false; } f.close(); debug(QString("Wrote atest.cpp:\n%1").arg(filedata)); QString pro = QString( "CONFIG += console\n" "CONFIG -= qt app_bundle\n" "SOURCES += atest.cpp\n"); QString inc = incs.join(" "); if(!inc.isEmpty()) pro += "INCLUDEPATH += " + inc + '\n'; if(!libs.isEmpty()) pro += "LIBS += " + libs + '\n'; pro += proextra; fname = dir.filePath("atest.pro"); f.setFileName(fname); if(!f.open(QFile::WriteOnly | QFile::Truncate)) { debug("unable to open atest.pro for writing"); return false; } if(f.write(pro.toLatin1()) == -1) { debug("error writing to atest.pro"); return false; } f.close(); debug(QString("Wrote atest.pro:\n%1").arg(pro)); QString oldpath = QDir::currentPath(); QDir::setCurrent(dir.path()); bool ok = false; int r = doCommand(qmake_path, QStringList() << "atest.pro"); if(r == 0) { r = doCommand(maketool, QStringList()); if(r == 0) { ok = true; if(retcode) *retcode = doCommand(QString("./") + out, QStringList()); } r = doCommand(maketool, QStringList() << "distclean"); if(r != 0) debug("error during atest distclean"); } QDir::setCurrent(oldpath); // cleanup //dir.remove("atest.pro"); //dir.remove("atest.cpp"); //tmp.rmdir("atest"); // remove whole dir since distclean doesn't always work qc_removedir(tmp.filePath("atest")); if(!ok) return false; return true; } bool Conf::checkHeader(const QString &path, const QString &h) { QFileInfo fi(path + '/' + h); if(fi.exists()) return true; return false; } bool Conf::findHeader(const QString &h, const QStringList &ext, QString *inc) { if(checkHeader("/usr/include", h)) { *inc = ""; return true; } QStringList dirs; dirs += "/usr/local/include"; dirs += ext; for(QStringList::ConstIterator it = dirs.begin(); it != dirs.end(); ++it) { if(checkHeader(*it, h)) { *inc = *it; return true; } } return false; } bool Conf::checkLibrary(const QString &path, const QString &name) { QString str = //"#include \n" "int main()\n" "{\n" //" printf(\"library checker running\\\\n\");\n" " return 0;\n" "}\n"; QString libs; if(!path.isEmpty()) libs += QString("-L") + path + ' '; libs += QString("-l") + name; if(!doCompileAndLink(str, QStringList(), libs, QString())) return false; return true; } bool Conf::findLibrary(const QString &name, QString *lib) { if(checkLibrary("", name)) { *lib = ""; return true; } if(checkLibrary("/usr/local/lib", name)) { *lib = "/usr/local/lib"; return true; } return false; } QString Conf::findProgram(const QString &prog) { return qc_findprogram(prog); } bool Conf::findSimpleLibrary(const QString &incvar, const QString &libvar, const QString &incname, const QString &libname, QString *incpath, QString *libs) { QString inc, lib; QString s; s = getenv(incvar); if(!s.isEmpty()) { if(!checkHeader(s, incname)) return false; inc = s; } else { if(!findHeader(incname, QStringList(), &s)) return false; inc = s; } s = getenv(libvar); if(!s.isEmpty()) { if(!checkLibrary(s, libname)) return false; lib = s; } else { if(!findLibrary(libname, &s)) return false; lib = s; } QString lib_out; if(!lib.isEmpty()) lib_out += QString("-L") + s; lib_out += QString("-l") + libname; *incpath = inc; *libs = lib_out; return true; } bool Conf::findFooConfig(const QString &path, QString *version, QStringList *incs, QString *libs, QString *otherflags) { QStringList args; QByteArray out; int ret; args += "--version"; ret = doCommand(path, args, &out); if(ret != 0) return false; QString version_out = QString::fromLatin1(out).trimmed(); args.clear(); args += "--libs"; ret = doCommand(path, args, &out); if(ret != 0) return false; QString libs_out = QString::fromLatin1(out).trimmed(); args.clear(); args += "--cflags"; ret = doCommand(path, args, &out); if(ret != 0) return false; QString cflags = QString::fromLatin1(out).trimmed(); QStringList incs_out, otherflags_out; qc_splitcflags(cflags, &incs_out, &otherflags_out); *version = version_out; *incs = incs_out; *libs = libs_out; *otherflags = otherflags_out.join(" "); return true; } bool Conf::findPkgConfig(const QString &name, VersionMode mode, const QString &req_version, QString *version, QStringList *incs, QString *libs, QString *otherflags) { QStringList args; QByteArray out; int ret; args += name; args += "--exists"; ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; if(mode != VersionAny) { args.clear(); args += name; if(mode == VersionMin) args += QString("--atleast-version=%1").arg(req_version); else if(mode == VersionMax) args += QString("--max-version=%1").arg(req_version); else args += QString("--exact-version=%1").arg(req_version); ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; } args.clear(); args += name; args += "--modversion"; ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; QString version_out = QString::fromLatin1(out).trimmed(); args.clear(); args += name; args += "--libs"; ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; QString libs_out = QString::fromLatin1(out).trimmed(); args.clear(); args += name; args += "--cflags"; ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; QString cflags = QString::fromLatin1(out).trimmed(); QStringList incs_out, otherflags_out; qc_splitcflags(cflags, &incs_out, &otherflags_out); *version = version_out; *incs = incs_out; *libs = libs_out; *otherflags = otherflags_out.join(" "); return true; } void Conf::addDefine(const QString &str) { if(DEFINES.isEmpty()) DEFINES = str; else DEFINES += QString(" ") + str; debug(QString("DEFINES += %1").arg(str)); } void Conf::addLib(const QString &str) { if(LIBS.isEmpty()) LIBS = str; else LIBS += QString(" ") + str; debug(QString("LIBS += %1").arg(str)); } void Conf::addIncludePath(const QString &str) { if(INCLUDEPATH.isEmpty()) INCLUDEPATH = str; else INCLUDEPATH += QString(" ") + str; debug(QString("INCLUDEPATH += %1").arg(str)); } void Conf::addExtra(const QString &str) { extra += str + '\n'; debug(QString("extra += %1").arg(str)); } //---------------------------------------------------------------------------- // main //---------------------------------------------------------------------------- #include "conf4.moc" #ifdef HAVE_MODULES # include"modules.cpp" #endif int main() { Conf *conf = new Conf; ConfObj *o; o = 0; #ifdef HAVE_MODULES # include"modules_new.cpp" #endif conf->debug_enabled = (qc_getenv("QC_VERBOSE") == "Y") ? true: false; if(conf->debug_enabled) printf(" -> ok\n"); else printf("ok\n"); QString confCommand = qc_getenv("QC_COMMAND"); QString proName = qc_getenv("QC_PROFILE"); conf->qmake_path = qc_getenv("QC_QMAKE"); conf->maketool = qc_getenv("QC_MAKETOOL"); if(conf->debug_enabled) printf("conf command: [%s]\n", qPrintable(confCommand)); QString confPath = qc_findself(confCommand); if(confPath.isEmpty()) { printf("Error: cannot find myself; rerun with an absolute path\n"); return 1; } QString srcdir = QFileInfo(confPath).absolutePath(); QString builddir = QDir::current().absolutePath(); QString proPath = QDir(srcdir).filePath(proName); if(conf->debug_enabled) { printf("conf path: [%s]\n", qPrintable(confPath)); printf("srcdir: [%s]\n", qPrintable(srcdir)); printf("builddir: [%s]\n", qPrintable(builddir)); printf("profile: [%s]\n", qPrintable(proPath)); printf("qmake path: [%s]\n", qPrintable(conf->qmake_path)); printf("make tool: [%s]\n", qPrintable(conf->maketool)); printf("\n"); } bool success = false; if(conf->exec()) { QFile f("conf.pri"); if(!f.open(QFile::WriteOnly | QFile::Truncate)) { printf("Error writing %s\n", qPrintable(f.fileName())); return 1; } QString str; str += "# qconf\n\n"; QString var; var = qc_getenv("PREFIX"); if(!var.isEmpty()) str += QString("PREFIX = %1\n").arg(var); var = qc_getenv("BINDIR"); if(!var.isEmpty()) str += QString("BINDIR = %1\n").arg(var); var = qc_getenv("INCDIR"); if(!var.isEmpty()) str += QString("INCDIR = %1\n").arg(var); var = qc_getenv("LIBDIR"); if(!var.isEmpty()) str += QString("LIBDIR = %1\n").arg(var); var = qc_getenv("DATADIR"); if(!var.isEmpty()) str += QString("DATADIR = %1\n").arg(var); str += '\n'; if(qc_getenv("QC_STATIC") == "Y") str += "CONFIG += staticlib\n"; // TODO: don't need this? //str += "QT_PATH_PLUGINS = " + QString(qInstallPathPlugins()) + '\n'; if(!conf->DEFINES.isEmpty()) str += "DEFINES += " + conf->DEFINES + '\n'; if(!conf->INCLUDEPATH.isEmpty()) str += "INCLUDEPATH += " + conf->INCLUDEPATH + '\n'; if(!conf->LIBS.isEmpty()) str += "LIBS += " + conf->LIBS + '\n'; if(!conf->extra.isEmpty()) str += conf->extra; str += '\n'; QByteArray cs = str.toLatin1(); f.write(cs); f.close(); success = true; } QString qmake_path = conf->qmake_path; delete conf; if(!success) return 1; // run qmake on the project file int ret = qc_runprogram(qmake_path, QStringList() << proPath, 0, true); if(ret != 0) return 1; return 0; } EOT cat >$1/conf4.pro </dev/null $MAKE clean >/dev/null 2>&1 $MAKE >../conf.log 2>&1 ) if [ "$?" != "0" ]; then rm -rf .qconftemp if [ "$QC_VERBOSE" = "Y" ]; then echo " -> fail" else echo "fail" fi printf "\n" printf "Reason: There was an error compiling 'conf'. See conf.log for details.\n" printf "\n" show_qt_info if [ "$QC_VERBOSE" = "Y" ]; then echo "conf.log:" cat conf.log fi exit 1; fi QC_COMMAND=$0 export QC_COMMAND QC_PROFILE=qca-gnupg.pro export QC_PROFILE QC_QMAKE=$qm export QC_QMAKE QC_MAKETOOL=$MAKE export QC_MAKETOOL .qconftemp/conf ret="$?" if [ "$ret" = "1" ]; then rm -rf .qconftemp echo exit 1; else if [ "$ret" != "0" ]; then rm -rf .qconftemp if [ "$QC_VERBOSE" = "Y" ]; then echo " -> fail" else echo "fail" fi echo echo "Reason: Unexpected error launching 'conf'" echo exit 1; fi fi rm -rf .qconftemp echo echo "Good, your configure finished. Now run $MAKE." echo qca-gnupg-2.0.0-beta3/qca-gnupg.pro0000644000175000017500000000111510712727775016422 0ustar justinjustinTEMPLATE = lib CONFIG += plugin QT -= gui DESTDIR = lib VERSION = 2.0.0 unix:include(conf.pri) windows:CONFIG += crypto windows:include(conf_win.pri) CONFIG += create_prl windows:LIBS += -ladvapi32 GPG_BASE = . GPGPROC_BASE = $$GPG_BASE/gpgproc include($$GPGPROC_BASE/gpgproc.pri) INCLUDEPATH += $$GPGPROC_BASE INCLUDEPATH += $$GPG_BASE HEADERS += \ $$GPG_BASE/gpgop.h SOURCES += \ $$GPG_BASE/gpgop.cpp \ $$GPG_BASE/qca-gnupg.cpp !debug_and_release|build_pass { CONFIG(debug, debug|release) { mac:TARGET = $$member(TARGET, 0)_debug windows:TARGET = $$member(TARGET, 0)d } } qca-gnupg-2.0.0-beta3/gpgop.h0000644000175000017500000001176010776557777015327 0ustar justinjustin/* * Copyright (C) 2003-2005 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #ifndef GPGOP_H #define GPGOP_H #include #include "qpipe.h" namespace gpgQCAPlugin { class GpgOp : public QObject { Q_OBJECT public: enum Type { Check, // --version SecretKeyringFile, // --list-secret-keys PublicKeyringFile, // --list-public-keys SecretKeys, // --fixed-list-mode --with-colons --list-secret-keys PublicKeys, // --fixed-list-mode --with-colons --list-public-keys Encrypt, // --encrypt Decrypt, // --decrypt Sign, // --sign SignAndEncrypt, // --sign --encrypt SignClearsign, // --clearsign SignDetached, // --detach-sign Verify, // --verify VerifyDetached, // --verify Import, // --import Export, // --export DeleteKey // --delete-key }; enum VerifyResult { VerifyGood, // good sig VerifyBad, // bad sig VerifyNoKey // we don't have signer's public key }; enum Error { ErrorProcess, // startup, process, or ipc error ErrorPassphrase, // passphrase was either wrong or not provided ErrorFormat, // input format was bad ErrorSignerExpired, // signing key is expired ErrorEncryptExpired, // encrypting key is expired ErrorEncryptUntrusted, // encrypting key is untrusted ErrorEncryptInvalid, // encrypting key is invalid in some way ErrorDecryptNoKey, // missing decrypt key ErrorUnknown // other error }; class Event { public: enum Type { None, ReadyRead, BytesWritten, Finished, NeedPassphrase, NeedCard, ReadyReadDiagnosticText }; Type type; int written; // BytesWritten QString keyId; // NeedPassphrase Event() : type(None), written(0) {} }; class KeyItem { public: enum Type { RSA, DSA, ElGamal, Unknown }; enum Caps { Encrypt = 0x01, Sign = 0x02, Certify = 0x04, Auth = 0x08 }; QString id; Type type; int bits; QDateTime creationDate; QDateTime expirationDate; int caps; // flags OR'd together QString fingerprint; KeyItem() : type(Unknown), bits(0), caps(0) {} }; class Key { public: QList keyItems; // first item is primary QStringList userIds; bool isTrusted; Key() : isTrusted(false) {} }; typedef QList KeyList; explicit GpgOp(const QString &bin, QObject *parent = 0); ~GpgOp(); void reset(); bool isActive() const; Type op() const; void setAsciiFormat(bool b); void setDisableAgent(bool b); void setAlwaysTrust(bool b); void setKeyrings(const QString &pubfile, const QString &secfile); // for keylists and import void doCheck(); void doSecretKeyringFile(); void doPublicKeyringFile(); void doSecretKeys(); void doPublicKeys(); void doEncrypt(const QStringList &recip_ids); void doDecrypt(); void doSign(const QString &signer_id); void doSignAndEncrypt(const QString &signer_id, const QStringList &recip_ids); void doSignClearsign(const QString &signer_id); void doSignDetached(const QString &signer_id); void doVerify(); void doVerifyDetached(const QByteArray &sig); void doImport(const QByteArray &in); void doExport(const QString &key_id); void doDeleteKey(const QString &key_fingerprint); #ifdef QPIPE_SECURE void submitPassphrase(const QCA::SecureArray &a); #else void submitPassphrase(const QByteArray &a); #endif void cardOkay(); // for encrypt, decrypt, sign, verify, export QByteArray read(); void write(const QByteArray &in); void endWrite(); QString readDiagnosticText(); // for synchronous operation Event waitForEvent(int msecs = -1); // results bool success() const; Error errorCode() const; KeyList keys() const; // Keys QString keyringFile() const; // KeyringFile QString encryptedToId() const; // Decrypt (for ErrorDecryptNoKey) bool wasSigned() const; // Decrypt QString signerId() const; // Verify QDateTime timestamp() const; // Verify VerifyResult verifyResult() const; // Verify Q_SIGNALS: void readyRead(); void bytesWritten(int bytes); void finished(); void needPassphrase(const QString &keyId); void needCard(); void readyReadDiagnosticText(); private: class Private; friend class Private; Private *d; }; } #endif qca-gnupg-2.0.0-beta3/qca-gnupg.cpp0000644000175000017500000010437110776560170016406 0ustar justinjustin/* * Copyright (C) 2003-2008 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include #include #include #include #include #include #include #include #ifdef Q_OS_MAC #include #endif #ifdef Q_OS_WIN # include #endif #include "gpgop.h" // for SafeTimer and release function #include "gpgproc.h" using namespace QCA; namespace gpgQCAPlugin { static int qVersionInt() { static int out = -1; if(out == -1) { QString str = QString::fromLatin1(qVersion()); QStringList parts = str.split('.', QString::KeepEmptyParts); Q_ASSERT(parts.count() == 3); out = 0; for(int n = 0; n < 3; ++n) { bool ok; int x = parts[n].toInt(&ok); Q_ASSERT(ok); Q_ASSERT(x > 0 && x <= 0xff); out <<= x; } } return out; } #ifdef Q_OS_LINUX static bool qt_buggy_fsw() { // FIXME: just a guess that this is fixed in 4.3.5 and 4.4.0 if(qVersionInt() < 0x040305) return true; else return false; } #else static bool qt_buggy_fsw() { return false; } #endif // begin ugly hack for qca 2.0.0 with broken dirwatch support // hacks: // 1) we must construct with a valid file to watch. passing an empty // string doesn't work. this means we can't create the objects in // advance. instead we'll use new/delete as necessary. // 2) there's a wrong internal connect() statement in the qca source. // assuming fixed internals for qca 2.0.0, we can fix that connect from // here... #include // some structures below to give accessible interface to qca 2.0.0 internals class DirWatch2 : public QObject { Q_OBJECT public: explicit DirWatch2(const QString &dir = QString(), QObject *parent = 0) { Q_UNUSED(dir); Q_UNUSED(parent); } ~DirWatch2() { } QString dirName() const { return QString(); } void setDirName(const QString &dir) { Q_UNUSED(dir); } Q_SIGNALS: void changed(); public: Q_DISABLE_COPY(DirWatch2) class Private; friend class Private; Private *d; }; /*class FileWatch2 : public QObject { Q_OBJECT public: explicit FileWatch2(const QString &file = QString(), QObject *parent = 0) { Q_UNUSED(file); Q_UNUSED(parent); } ~FileWatch2() { } QString fileName() const { return QString(); } void setFileName(const QString &file) { Q_UNUSED(file); } Q_SIGNALS: void changed(); public: Q_DISABLE_COPY(FileWatch2) class Private; friend class Private; Private *d; };*/ class QFileSystemWatcherRelay2 : public QObject { Q_OBJECT public: }; class DirWatch2::Private : public QObject { Q_OBJECT public: DirWatch2 *q; QFileSystemWatcher *watcher; QFileSystemWatcherRelay2 *watcher_relay; QString dirName; private slots: void watcher_changed(const QString &path) { Q_UNUSED(path); } }; /*class FileWatch2::Private : public QObject { Q_OBJECT public: FileWatch2 *q; QFileSystemWatcher *watcher; QFileSystemWatcherRelay2 *watcher_relay; QString fileName; private slots: void watcher_changed(const QString &path) { Q_UNUSED(path); } };*/ static void hack_fix(DirWatch *dw) { DirWatch2 *dw2 = reinterpret_cast(dw); QObject::connect(dw2->d->watcher_relay, SIGNAL(directoryChanged(const QString &)), dw2->d, SLOT(watcher_changed(const QString &))); fprintf(stderr, "qca-gnupg: patching DirWatch to fix failed connect\n"); } // end ugly hack #ifdef Q_OS_WIN static QString find_reg_gpgProgram() { HKEY root; root = HKEY_CURRENT_USER; HKEY hkey; const char *path = "Software\\GNU\\GnuPG"; if(RegOpenKeyExA(HKEY_CURRENT_USER, path, 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) { if(RegOpenKeyExA(HKEY_LOCAL_MACHINE, path, 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) return QString(); } char szValue[256]; DWORD dwLen = 256; if(RegQueryValueExA(hkey, "gpgProgram", NULL, NULL, (LPBYTE)szValue, &dwLen) != ERROR_SUCCESS) { RegCloseKey(hkey); return QString(); } RegCloseKey(hkey); return QString::fromLatin1(szValue); } #endif static QString find_bin() { QString bin = "gpg"; #ifdef Q_OS_WIN QString s = find_reg_gpgProgram(); if(!s.isNull()) bin = s; #endif #ifdef Q_OS_MAC // mac-gpg QFileInfo fi("/usr/local/bin/gpg"); if(fi.exists()) bin = fi.filePath(); #endif return bin; } static QString escape_string(const QString &in) { QString out; for(int n = 0; n < in.length(); ++n) { if(in[n] == '\\') out += "\\\\"; else if(in[n] == ':') out += "\\c"; else out += in[n]; } return out; } static QString unescape_string(const QString &in) { QString out; for(int n = 0; n < in.length(); ++n) { if(in[n] == '\\') { if(n + 1 < in.length()) { if(in[n + 1] == '\\') out += '\\'; else if(in[n + 1] == 'c') out += ':'; ++n; } } else out += in[n]; } return out; } static void gpg_waitForFinished(GpgOp *gpg) { while(1) { GpgOp::Event e = gpg->waitForEvent(-1); if(e.type == GpgOp::Event::Finished) break; } } Q_GLOBAL_STATIC(QMutex, ksl_mutex) class MyKeyStoreList; static MyKeyStoreList *keyStoreList = 0; static void gpg_keyStoreLog(const QString &str); class MyPGPKeyContext : public PGPKeyContext { public: PGPKeyContextProps _props; // keys loaded externally (not from the keyring) need to have these // values cached, since we can't extract them later QByteArray cacheExportBinary; QString cacheExportAscii; MyPGPKeyContext(Provider *p) : PGPKeyContext(p) { // zero out the props _props.isSecret = false; _props.inKeyring = true; _props.isTrusted = false; } virtual Provider::Context *clone() const { return new MyPGPKeyContext(*this); } void set(const GpgOp::Key &i, bool isSecret, bool inKeyring, bool isTrusted) { const GpgOp::KeyItem &ki = i.keyItems.first(); _props.keyId = ki.id; _props.userIds = i.userIds; _props.isSecret = isSecret; _props.creationDate = ki.creationDate; _props.expirationDate = ki.expirationDate; _props.fingerprint = ki.fingerprint.toLower(); _props.inKeyring = inKeyring; _props.isTrusted = isTrusted; } virtual const PGPKeyContextProps *props() const { return &_props; } virtual QByteArray toBinary() const { if(_props.inKeyring) { GpgOp gpg(find_bin()); gpg.setAsciiFormat(false); gpg.doExport(_props.keyId); gpg_waitForFinished(&gpg); gpg_keyStoreLog(gpg.readDiagnosticText()); if(!gpg.success()) return QByteArray(); return gpg.read(); } else return cacheExportBinary; } virtual QString toAscii() const { if(_props.inKeyring) { GpgOp gpg(find_bin()); gpg.setAsciiFormat(true); gpg.doExport(_props.keyId); gpg_waitForFinished(&gpg); gpg_keyStoreLog(gpg.readDiagnosticText()); if(!gpg.success()) return QString(); return QString::fromLocal8Bit(gpg.read()); } else return cacheExportAscii; } static void cleanup_temp_keyring(const QString &name) { QFile::remove(name); QFile::remove(name + '~'); // remove possible backup file } virtual ConvertResult fromBinary(const QByteArray &a) { GpgOp::Key key; bool sec = false; // temporary keyrings QString pubname, secname; QTemporaryFile pubtmp(QDir::tempPath() + QLatin1String("/qca_gnupg_tmp.XXXXXX.gpg")); if(!pubtmp.open()) return ErrorDecode; QTemporaryFile sectmp(QDir::tempPath() + QLatin1String("/qca_gnupg_tmp.XXXXXX.gpg")); if(!sectmp.open()) return ErrorDecode; pubname = pubtmp.fileName(); secname = sectmp.fileName(); // we turn off autoRemove so that we can close the files // without them getting deleted pubtmp.setAutoRemove(false); sectmp.setAutoRemove(false); pubtmp.close(); sectmp.close(); // import key into temporary keyring GpgOp gpg(find_bin()); gpg.setKeyrings(pubname, secname); gpg.doImport(a); gpg_waitForFinished(&gpg); gpg_keyStoreLog(gpg.readDiagnosticText()); // comment this out. apparently gpg will report failure for // an import if there are trust issues, even though the // key actually did get imported /*if(!gpg.success()) { cleanup_temp_keyring(pubname); cleanup_temp_keyring(secname); return ErrorDecode; }*/ // now extract the key from gpg like normal // is it a public key? gpg.doPublicKeys(); gpg_waitForFinished(&gpg); gpg_keyStoreLog(gpg.readDiagnosticText()); if(!gpg.success()) { cleanup_temp_keyring(pubname); cleanup_temp_keyring(secname); return ErrorDecode; } GpgOp::KeyList pubkeys = gpg.keys(); if(!pubkeys.isEmpty()) { key = pubkeys.first(); } else { // is it a secret key? gpg.doSecretKeys(); gpg_waitForFinished(&gpg); gpg_keyStoreLog(gpg.readDiagnosticText()); if(!gpg.success()) { cleanup_temp_keyring(pubname); cleanup_temp_keyring(secname); return ErrorDecode; } GpgOp::KeyList seckeys = gpg.keys(); if(!seckeys.isEmpty()) { key = seckeys.first(); sec = true; } else { // no keys found cleanup_temp_keyring(pubname); cleanup_temp_keyring(secname); return ErrorDecode; } } // export binary/ascii and cache gpg.setAsciiFormat(false); gpg.doExport(key.keyItems.first().id); gpg_waitForFinished(&gpg); gpg_keyStoreLog(gpg.readDiagnosticText()); if(!gpg.success()) { cleanup_temp_keyring(pubname); cleanup_temp_keyring(secname); return ErrorDecode; } cacheExportBinary = gpg.read(); gpg.setAsciiFormat(true); gpg.doExport(key.keyItems.first().id); gpg_waitForFinished(&gpg); gpg_keyStoreLog(gpg.readDiagnosticText()); if(!gpg.success()) { cleanup_temp_keyring(pubname); cleanup_temp_keyring(secname); return ErrorDecode; } cacheExportAscii = QString::fromLocal8Bit(gpg.read()); // all done cleanup_temp_keyring(pubname); cleanup_temp_keyring(secname); set(key, sec, false, false); return ConvertGood; } virtual ConvertResult fromAscii(const QString &s) { // GnuPG does ascii/binary detection for imports, so for // simplicity we consider an ascii import to just be a // binary import that happens to be comprised of ascii return fromBinary(s.toLocal8Bit()); } }; class MyKeyStoreEntry : public KeyStoreEntryContext { public: KeyStoreEntry::Type item_type; PGPKey pub, sec; QString _storeId, _storeName; MyKeyStoreEntry(const PGPKey &_pub, const PGPKey &_sec, Provider *p) : KeyStoreEntryContext(p) { pub = _pub; sec = _sec; if(!sec.isNull()) item_type = KeyStoreEntry::TypePGPSecretKey; else item_type = KeyStoreEntry::TypePGPPublicKey; } MyKeyStoreEntry(const MyKeyStoreEntry &from) : KeyStoreEntryContext(from) { } ~MyKeyStoreEntry() { } virtual Provider::Context *clone() const { return new MyKeyStoreEntry(*this); } virtual KeyStoreEntry::Type type() const { return item_type; } virtual QString name() const { return pub.primaryUserId(); } virtual QString id() const { return pub.keyId(); } virtual QString storeId() const { return _storeId; } virtual QString storeName() const { return _storeName; } virtual PGPKey pgpSecretKey() const { return sec; } virtual PGPKey pgpPublicKey() const { return pub; } virtual QString serialize() const { // we only serialize the key id. this means the keyring // must be available to restore the data QStringList out; out += escape_string("qca-gnupg-1"); out += escape_string(pub.keyId()); return out.join(":"); } }; // since keyring files are often modified by creating a new copy and // overwriting the original file, this messes up Qt's file watching // capability since the original file goes away. to work around this // problem, we'll watch the directories containing the keyring files // instead of watching the actual files themselves. // // FIXME: consider moving this logic into FileWatch class RingWatch : public QObject { Q_OBJECT public: class DirItem { public: DirWatch *dirWatch; SafeTimer *changeTimer; }; class FileItem { public: DirWatch *dirWatch; QString fileName; bool exists; qint64 size; QDateTime lastModified; }; QList dirs; QList files; RingWatch(QObject *parent = 0) : QObject(parent) { } ~RingWatch() { clear(); } void add(const QString &filePath) { QFileInfo fi(filePath); QString path = fi.absolutePath(); // watching this path already? DirWatch *dirWatch = 0; foreach(const DirItem &di, dirs) { if(di.dirWatch->dirName() == path) { dirWatch = di.dirWatch; break; } } // if not, make a watcher if(!dirWatch) { //printf("creating dirwatch for [%s]\n", qPrintable(path)); DirItem di; di.dirWatch = new DirWatch(path, this); connect(di.dirWatch, SIGNAL(changed()), SLOT(dirChanged())); if(qcaVersion() == 0x020000) hack_fix(di.dirWatch); di.changeTimer = new SafeTimer(this); di.changeTimer->setSingleShot(true); connect(di.changeTimer, SIGNAL(timeout()), SLOT(handleChanged())); dirWatch = di.dirWatch; dirs += di; } FileItem i; i.dirWatch = dirWatch; i.fileName = fi.fileName(); i.exists = fi.exists(); if(i.exists) { i.size = fi.size(); i.lastModified = fi.lastModified(); } files += i; //printf("watching [%s] in [%s]\n", qPrintable(fi.fileName()), qPrintable(i.dirWatch->dirName())); } void clear() { files.clear(); foreach(const DirItem &di, dirs) { delete di.changeTimer; delete di.dirWatch; } dirs.clear(); } signals: void changed(const QString &filePath); private slots: void dirChanged() { DirWatch *dirWatch = (DirWatch *)sender(); int at = -1; for(int n = 0; n < dirs.count(); ++n) { if(dirs[n].dirWatch == dirWatch) { at = n; break; } } if(at == -1) return; // we get a ton of change notifications for the dir when // something happens.. let's collect them and only // report after 100ms if(!dirs[at].changeTimer->isActive()) dirs[at].changeTimer->start(100); } void handleChanged() { SafeTimer *t = (SafeTimer *)sender(); int at = -1; for(int n = 0; n < dirs.count(); ++n) { if(dirs[n].changeTimer == t) { at = n; break; } } if(at == -1) return; DirWatch *dirWatch = dirs[at].dirWatch; QString dir = dirWatch->dirName(); // see which files changed QStringList changeList; for(int n = 0; n < files.count(); ++n) { FileItem &i = files[n]; QString filePath = dir + '/' + i.fileName; QFileInfo fi(filePath); // if the file didn't exist, and still doesn't, skip if(!i.exists && !fi.exists()) continue; // size/lastModified should only get checked here if // the file existed and still exists if(fi.exists() != i.exists || fi.size() != i.size || fi.lastModified() != i.lastModified) { changeList += filePath; i.exists = fi.exists(); if(i.exists) { i.size = fi.size(); i.lastModified = fi.lastModified(); } } } foreach(const QString &s, changeList) emit changed(s); } }; class MyKeyStoreList : public KeyStoreListContext { Q_OBJECT public: int init_step; bool initialized; GpgOp gpg; GpgOp::KeyList pubkeys, seckeys; QString pubring, secring; bool pubdirty, secdirty; RingWatch ringWatch; QMutex ringMutex; MyKeyStoreList(Provider *p) : KeyStoreListContext(p), initialized(false), gpg(find_bin(), this), pubdirty(false), secdirty(false), ringWatch(this) { QMutexLocker locker(ksl_mutex()); keyStoreList = this; connect(&gpg, SIGNAL(finished()), SLOT(gpg_finished())); connect(&ringWatch, SIGNAL(changed(const QString &)), SLOT(ring_changed(const QString &))); } ~MyKeyStoreList() { QMutexLocker locker(ksl_mutex()); keyStoreList = 0; } virtual Provider::Context *clone() const { return 0; } static MyKeyStoreList *instance() { QMutexLocker locker(ksl_mutex()); return keyStoreList; } void ext_keyStoreLog(const QString &str) { if(str.isEmpty()) return; // FIXME: collect and emit in one pass QMetaObject::invokeMethod(this, "diagnosticText", Qt::QueuedConnection, Q_ARG(QString, str)); } virtual void start() { // kick start our init procedure: // ensure gpg is installed // obtain keyring file names for monitoring // cache initial keyrings init_step = 0; gpg.doCheck(); } virtual QList keyStores() { // we just support one fixed keyring, if any QList list; if(initialized) list += 0; return list; } virtual KeyStore::Type type(int) const { return KeyStore::PGPKeyring; } virtual QString storeId(int) const { return "qca-gnupg"; } virtual QString name(int) const { return "GnuPG Keyring"; } virtual QList entryTypes(int) const { QList list; list += KeyStoreEntry::TypePGPSecretKey; list += KeyStoreEntry::TypePGPPublicKey; return list; } virtual QList entryList(int) { QMutexLocker locker(&ringMutex); QList out; foreach(const GpgOp::Key &pkey, pubkeys) { PGPKey pub, sec; QString id = pkey.keyItems.first().id; MyPGPKeyContext *kc = new MyPGPKeyContext(provider()); // not secret, in keyring kc->set(pkey, false, true, pkey.isTrusted); pub.change(kc); // optional sec = getSecKey(id, pkey.userIds); MyKeyStoreEntry *c = new MyKeyStoreEntry(pub, sec, provider()); c->_storeId = storeId(0); c->_storeName = name(0); out.append(c); } return out; } virtual KeyStoreEntryContext *entry(int, const QString &entryId) { QMutexLocker locker(&ringMutex); PGPKey pub = getPubKey(entryId); if(pub.isNull()) return 0; // optional PGPKey sec = getSecKey(entryId, static_cast(pub.context())->_props.userIds); MyKeyStoreEntry *c = new MyKeyStoreEntry(pub, sec, provider()); c->_storeId = storeId(0); c->_storeName = name(0); return c; } virtual KeyStoreEntryContext *entryPassive(const QString &serialized) { QMutexLocker locker(&ringMutex); QStringList parts = serialized.split(':'); if(parts.count() < 2) return 0; if(unescape_string(parts[0]) != "qca-gnupg-1") return 0; QString entryId = unescape_string(parts[1]); if(entryId.isEmpty()) return 0; PGPKey pub = getPubKey(entryId); if(pub.isNull()) return 0; // optional PGPKey sec = getSecKey(entryId, static_cast(pub.context())->_props.userIds); MyKeyStoreEntry *c = new MyKeyStoreEntry(pub, sec, provider()); c->_storeId = storeId(0); c->_storeName = name(0); return c; } // TODO: cache should reflect this change immediately virtual QString writeEntry(int, const PGPKey &key) { const MyPGPKeyContext *kc = static_cast(key.context()); QByteArray buf = kc->toBinary(); GpgOp gpg(find_bin()); gpg.doImport(buf); gpg_waitForFinished(&gpg); gpg_keyStoreLog(gpg.readDiagnosticText()); if(!gpg.success()) return QString(); return kc->_props.keyId; } // TODO: cache should reflect this change immediately virtual bool removeEntry(int, const QString &entryId) { ringMutex.lock(); PGPKey pub = getPubKey(entryId); ringMutex.unlock(); const MyPGPKeyContext *kc = static_cast(pub.context()); QString fingerprint = kc->_props.fingerprint; GpgOp gpg(find_bin()); gpg.doDeleteKey(fingerprint); gpg_waitForFinished(&gpg); gpg_keyStoreLog(gpg.readDiagnosticText()); return gpg.success(); } // internal PGPKey getPubKey(const QString &keyId) const { int at = -1; for(int n = 0; n < pubkeys.count(); ++n) { if(pubkeys[n].keyItems.first().id == keyId) { at = n; break; } } if(at == -1) return PGPKey(); const GpgOp::Key &pkey = pubkeys[at]; PGPKey pub; MyPGPKeyContext *kc = new MyPGPKeyContext(provider()); // not secret, in keyring kc->set(pkey, false, true, pkey.isTrusted); pub.change(kc); return pub; } // internal PGPKey getSecKey(const QString &keyId, const QStringList &userIdsOverride) const { Q_UNUSED(userIdsOverride); int at = -1; for(int n = 0; n < seckeys.count(); ++n) { if(seckeys[n].keyItems.first().id == keyId) { at = n; break; } } if(at == -1) return PGPKey(); const GpgOp::Key &skey = seckeys[at]; PGPKey sec; MyPGPKeyContext *kc = new MyPGPKeyContext(provider()); // secret, in keyring, trusted kc->set(skey, true, true, true); //kc->_props.userIds = userIdsOverride; sec.change(kc); return sec; } PGPKey publicKeyFromId(const QString &keyId) { QMutexLocker locker(&ringMutex); int at = -1; for(int n = 0; n < pubkeys.count(); ++n) { const GpgOp::Key &pkey = pubkeys[n]; for(int k = 0; k < pkey.keyItems.count(); ++k) { const GpgOp::KeyItem &ki = pkey.keyItems[k]; if(ki.id == keyId) { at = n; break; } } if(at != -1) break; } if(at == -1) return PGPKey(); const GpgOp::Key &pkey = pubkeys[at]; PGPKey pub; MyPGPKeyContext *kc = new MyPGPKeyContext(provider()); // not secret, in keyring kc->set(pkey, false, true, pkey.isTrusted); pub.change(kc); return pub; } PGPKey secretKeyFromId(const QString &keyId) { QMutexLocker locker(&ringMutex); int at = -1; for(int n = 0; n < seckeys.count(); ++n) { const GpgOp::Key &skey = seckeys[n]; for(int k = 0; k < skey.keyItems.count(); ++k) { const GpgOp::KeyItem &ki = skey.keyItems[k]; if(ki.id == keyId) { at = n; break; } } if(at != -1) break; } if(at == -1) return PGPKey(); const GpgOp::Key &skey = seckeys[at]; PGPKey sec; MyPGPKeyContext *kc = new MyPGPKeyContext(provider()); // secret, in keyring, trusted kc->set(skey, true, true, true); sec.change(kc); return sec; } private slots: void gpg_finished() { gpg_keyStoreLog(gpg.readDiagnosticText()); if(!initialized) { // any steps that fail during init, just give up completely if(!gpg.success()) { ringWatch.clear(); emit busyEnd(); return; } // check if(init_step == 0) { // obtain keyring file names for monitoring init_step = 1; gpg.doSecretKeyringFile(); } // secret keyring filename else if(init_step == 1) { secring = gpg.keyringFile(); if(qt_buggy_fsw()) fprintf(stderr, "qca-gnupg: disabling keyring monitoring due to buggy Qt version\n"); if(!secring.isEmpty()) { if(!qt_buggy_fsw()) ringWatch.add(secring); } // obtain keyring file names for monitoring init_step = 2; gpg.doPublicKeyringFile(); } // public keyring filename else if(init_step == 2) { pubring = gpg.keyringFile(); if(!pubring.isEmpty()) { if(!qt_buggy_fsw()) ringWatch.add(pubring); } // cache initial keyrings init_step = 3; gpg.doSecretKeys(); } else if(init_step == 3) { ringMutex.lock(); seckeys = gpg.keys(); ringMutex.unlock(); // cache initial keyrings init_step = 4; gpg.doPublicKeys(); } else if(init_step == 4) { ringMutex.lock(); pubkeys = gpg.keys(); ringMutex.unlock(); initialized = true; handleDirtyRings(); emit busyEnd(); } } else { if(!gpg.success()) return; GpgOp::Type op = gpg.op(); if(op == GpgOp::SecretKeys) { ringMutex.lock(); seckeys = gpg.keys(); ringMutex.unlock(); secdirty = false; } else if(op == GpgOp::PublicKeys) { ringMutex.lock(); pubkeys = gpg.keys(); ringMutex.unlock(); pubdirty = false; } if(!secdirty && !pubdirty) { emit storeUpdated(0); return; } handleDirtyRings(); } } void ring_changed(const QString &filePath) { ext_keyStoreLog(QString("ring_changed: [%1]\n").arg(filePath)); if(filePath == secring) sec_changed(); else if(filePath == pubring) pub_changed(); } private: void pub_changed() { pubdirty = true; handleDirtyRings(); } void sec_changed() { secdirty = true; handleDirtyRings(); } void handleDirtyRings() { if(!initialized || gpg.isActive()) return; if(secdirty) gpg.doSecretKeys(); else if(pubdirty) gpg.doPublicKeys(); } }; static void gpg_keyStoreLog(const QString &str) { MyKeyStoreList *ksl = MyKeyStoreList::instance(); if(ksl) ksl->ext_keyStoreLog(str); } static PGPKey publicKeyFromId(const QString &id) { MyKeyStoreList *ksl = MyKeyStoreList::instance(); if(!ksl) return PGPKey(); return ksl->publicKeyFromId(id); } static PGPKey secretKeyFromId(const QString &id) { MyKeyStoreList *ksl = MyKeyStoreList::instance(); if(!ksl) return PGPKey(); return ksl->secretKeyFromId(id); } class MyOpenPGPContext : public SMSContext { public: MyOpenPGPContext(Provider *p) : SMSContext(p, "openpgp") { // TODO } virtual Provider::Context *clone() const { return 0; } virtual MessageContext *createMessage(); }; class MyMessageContext : public MessageContext { Q_OBJECT public: MyOpenPGPContext *sms; QString signerId; QStringList recipIds; Operation op; SecureMessage::SignMode signMode; SecureMessage::Format format; QByteArray in, out, sig; int wrote; bool ok, wasSigned; GpgOp::Error op_err; SecureMessageSignature signer; GpgOp gpg; bool _finished; QString dtext; PasswordAsker asker; TokenAsker tokenAsker; MyMessageContext(MyOpenPGPContext *_sms, Provider *p) : MessageContext(p, "pgpmsg"), gpg(find_bin()) { sms = _sms; wrote = 0; ok = false; wasSigned = false; connect(&gpg, SIGNAL(readyRead()), SLOT(gpg_readyRead())); connect(&gpg, SIGNAL(bytesWritten(int)), SLOT(gpg_bytesWritten(int))); connect(&gpg, SIGNAL(finished()), SLOT(gpg_finished())); connect(&gpg, SIGNAL(needPassphrase(const QString &)), SLOT(gpg_needPassphrase(const QString &))); connect(&gpg, SIGNAL(needCard()), SLOT(gpg_needCard())); connect(&gpg, SIGNAL(readyReadDiagnosticText()), SLOT(gpg_readyReadDiagnosticText())); connect(&asker, SIGNAL(responseReady()), SLOT(asker_responseReady())); connect(&tokenAsker, SIGNAL(responseReady()), SLOT(tokenAsker_responseReady())); } virtual Provider::Context *clone() const { return 0; } virtual bool canSignMultiple() const { return false; } virtual SecureMessage::Type type() const { return SecureMessage::OpenPGP; } virtual void reset() { wrote = 0; ok = false; wasSigned = false; } virtual void setupEncrypt(const SecureMessageKeyList &keys) { recipIds.clear(); for(int n = 0; n < keys.count(); ++n) recipIds += keys[n].pgpPublicKey().keyId(); } virtual void setupSign(const SecureMessageKeyList &keys, SecureMessage::SignMode m, bool, bool) { signerId = keys.first().pgpSecretKey().keyId(); signMode = m; } virtual void setupVerify(const QByteArray &detachedSig) { sig = detachedSig; } virtual void start(SecureMessage::Format f, Operation op) { _finished = false; format = f; this->op = op; if(getProperty("pgp-always-trust").toBool()) gpg.setAlwaysTrust(true); if(format == SecureMessage::Ascii) gpg.setAsciiFormat(true); else gpg.setAsciiFormat(false); if(op == Encrypt) { gpg.doEncrypt(recipIds); } else if(op == Decrypt) { gpg.doDecrypt(); } else if(op == Sign) { if(signMode == SecureMessage::Message) { gpg.doSign(signerId); } else if(signMode == SecureMessage::Clearsign) { gpg.doSignClearsign(signerId); } else // SecureMessage::Detached { gpg.doSignDetached(signerId); } } else if(op == Verify) { if(!sig.isEmpty()) gpg.doVerifyDetached(sig); else gpg.doDecrypt(); } else if(op == SignAndEncrypt) { gpg.doSignAndEncrypt(signerId, recipIds); } } virtual void update(const QByteArray &in) { gpg.write(in); //this->in.append(in); } virtual QByteArray read() { QByteArray a = out; out.clear(); return a; } virtual int written() { int x = wrote; wrote = 0; return x; } virtual void end() { gpg.endWrite(); } void seterror() { gpg.reset(); _finished = true; ok = false; op_err = GpgOp::ErrorUnknown; } void complete() { _finished = true; dtext = gpg.readDiagnosticText(); ok = gpg.success(); if(ok) { if(op == Sign && signMode == SecureMessage::Detached) sig = gpg.read(); else out = gpg.read(); } if(ok) { if(gpg.wasSigned()) { QString signerId = gpg.signerId(); QDateTime ts = gpg.timestamp(); GpgOp::VerifyResult vr = gpg.verifyResult(); SecureMessageSignature::IdentityResult ir; Validity v; if(vr == GpgOp::VerifyGood) { ir = SecureMessageSignature::Valid; v = ValidityGood; } else if(vr == GpgOp::VerifyBad) { ir = SecureMessageSignature::InvalidSignature; v = ValidityGood; // good key, bad sig } else // GpgOp::VerifyNoKey { ir = SecureMessageSignature::NoKey; v = ErrorValidityUnknown; } SecureMessageKey key; PGPKey pub = publicKeyFromId(signerId); if(pub.isNull()) { MyPGPKeyContext *kc = new MyPGPKeyContext(provider()); kc->_props.keyId = signerId; pub.change(kc); } key.setPGPPublicKey(pub); signer = SecureMessageSignature(ir, v, key, ts); wasSigned = true; } } else op_err = gpg.errorCode(); } virtual bool finished() const { return _finished; } virtual bool waitForFinished(int msecs) { // FIXME Q_UNUSED(msecs); while(1) { // TODO: handle token prompt events GpgOp::Event e = gpg.waitForEvent(-1); if(e.type == GpgOp::Event::NeedPassphrase) { // TODO QString keyId; PGPKey sec = secretKeyFromId(e.keyId); if(!sec.isNull()) keyId = sec.keyId(); else keyId = e.keyId; QStringList out; out += escape_string("qca-gnupg-1"); out += escape_string(keyId); QString serialized = out.join(":"); KeyStoreEntry kse; KeyStoreEntryContext *c = keyStoreList->entryPassive(serialized); if(c) kse.change(c); asker.ask(Event::StylePassphrase, KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), kse, 0); asker.waitForResponse(); if(!asker.accepted()) { seterror(); return true; } gpg.submitPassphrase(asker.password()); } else if(e.type == GpgOp::Event::NeedCard) { tokenAsker.ask(KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), KeyStoreEntry(), 0); if(!tokenAsker.accepted()) { seterror(); return true; } gpg.cardOkay(); } else if(e.type == GpgOp::Event::Finished) break; } complete(); return true; } virtual bool success() const { return ok; } virtual SecureMessage::Error errorCode() const { SecureMessage::Error e = SecureMessage::ErrorUnknown; if(op_err == GpgOp::ErrorProcess) e = SecureMessage::ErrorUnknown; else if(op_err == GpgOp::ErrorPassphrase) e = SecureMessage::ErrorPassphrase; else if(op_err == GpgOp::ErrorFormat) e = SecureMessage::ErrorFormat; else if(op_err == GpgOp::ErrorSignerExpired) e = SecureMessage::ErrorSignerExpired; else if(op_err == GpgOp::ErrorEncryptExpired) e = SecureMessage::ErrorEncryptExpired; else if(op_err == GpgOp::ErrorEncryptUntrusted) e = SecureMessage::ErrorEncryptUntrusted; else if(op_err == GpgOp::ErrorEncryptInvalid) e = SecureMessage::ErrorEncryptInvalid; else if(op_err == GpgOp::ErrorDecryptNoKey) e = SecureMessage::ErrorUnknown; else if(op_err == GpgOp::ErrorUnknown) e = SecureMessage::ErrorUnknown; return e; } virtual QByteArray signature() const { return sig; } virtual QString hashName() const { // TODO return "sha1"; } virtual SecureMessageSignatureList signers() const { SecureMessageSignatureList list; if(ok && wasSigned) list += signer; return list; } virtual QString diagnosticText() const { return dtext; } private slots: void gpg_readyRead() { emit updated(); } void gpg_bytesWritten(int bytes) { wrote += bytes; } void gpg_finished() { complete(); emit updated(); } void gpg_needPassphrase(const QString &in_keyId) { // FIXME: copied from above, clean up later QString keyId; PGPKey sec = secretKeyFromId(in_keyId); if(!sec.isNull()) keyId = sec.keyId(); else keyId = in_keyId; //emit keyStoreList->storeNeedPassphrase(0, 0, keyId); QStringList out; out += escape_string("qca-gnupg-1"); out += escape_string(keyId); QString serialized = out.join(":"); KeyStoreEntry kse; KeyStoreEntryContext *c = keyStoreList->entryPassive(serialized); if(c) kse.change(c); asker.ask(Event::StylePassphrase, KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), kse, 0); } void gpg_needCard() { tokenAsker.ask(KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), KeyStoreEntry(), 0); } void gpg_readyReadDiagnosticText() { // TODO ? } void asker_responseReady() { if(!asker.accepted()) { seterror(); emit updated(); return; } SecureArray a = asker.password(); gpg.submitPassphrase(a); } void tokenAsker_responseReady() { if(!tokenAsker.accepted()) { seterror(); emit updated(); return; } gpg.cardOkay(); } }; MessageContext *MyOpenPGPContext::createMessage() { return new MyMessageContext(this, provider()); } } using namespace gpgQCAPlugin; class gnupgProvider : public QCA::Provider { public: virtual void init() { } virtual int qcaVersion() const { return QCA_VERSION; } virtual QString name() const { return "qca-gnupg"; } virtual QStringList features() const { QStringList list; list += "pgpkey"; list += "openpgp"; list += "keystorelist"; return list; } virtual Context *createContext(const QString &type) { if(type == "pgpkey") return new MyPGPKeyContext(this); else if(type == "openpgp") return new MyOpenPGPContext(this); else if(type == "keystorelist") return new MyKeyStoreList(this); else return 0; } }; class gnupgPlugin : public QObject, public QCAPlugin { Q_OBJECT Q_INTERFACES(QCAPlugin) public: virtual QCA::Provider *createProvider() { return new gnupgProvider; } }; #include "qca-gnupg.moc" Q_EXPORT_PLUGIN2(qca_gnupg, gnupgPlugin) qca-gnupg-2.0.0-beta3/qca-gnupg.qc0000644000175000017500000000046210627155324016217 0ustar justinjustin qca-gnupg qca-gnupg.pro ../../qcm qca-gnupg-2.0.0-beta3/COPYING0000644000175000017500000006347610703542367015063 0ustar justinjustin GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! qca-gnupg-2.0.0-beta3/configwin.bat0000644000175000017500000000235110703727256016466 0ustar justinjustin@echo off REM write conf_win.pri if "%1"=="rd" goto debug_and_release if "%1"=="r" goto release if "%1"=="d" goto debug if "%1"=="rds" goto debug_and_release_static if "%1"=="rs" goto release_static if "%1"=="ds" goto debug_static goto usage :usage echo usage: configwin [mode] echo modes: echo rd release and debug, dynamic echo r release, dynamic echo d debug, dynamic echo rds release and debug, static echo rs release static echo ds debug static goto end :debug_and_release echo Configuring for release and debug, dynamic echo CONFIG += debug_and_release build_all > conf_win.pri goto done :release echo Configuring for release, dynamic echo CONFIG += release > conf_win.pri goto done :debug echo Configuring for debug, dynamic echo CONFIG += debug > conf_win.pri goto done :debug_and_release_static echo Configuring for release and debug, static echo CONFIG += debug_and_release build_all staticlib > conf_win.pri goto done :release_static echo Configuring for release, static echo CONFIG += release staticlib > conf_win.pri goto done :debug_static echo Configuring for debug, static echo CONFIG += debug staticlib > conf_win.pri goto done :done echo Wrote conf_win.pri :end qca-gnupg-2.0.0-beta3/README0000644000175000017500000000077510703542367014701 0ustar justinjustinQCA GnuPG plugin version 2.0.0 ------------------------------ Date: October 11th, 2007 Website: http://delta.affinix.com/qca/ Mailing List: Delta Project Author: Justin Karneges This plugin provides features based on GnuPG. Requirements: GnuPG 1.x or 2.x (runtime dependency only) Installing ---------- For Unix/Linux/Mac: ./configure make make install For Windows: configwin rd qmake nmake (or make) copy lib\*.dll qtdir\plugins\crypto qca-gnupg-2.0.0-beta3/CMakeLists.txt0000644000175000017500000000124110547371645016553 0ustar justinjustin# QCA GnuPG # we don't moc gpgporc/sprocess.cpp SET(QCA_GNUPG_MOC_SOURCES qca-gnupg.cpp gpgop.cpp gpgproc/gpgproc.cpp) MY_AUTOMOC( QCA_GNUPG_MOC_SOURCES ) QT4_WRAP_CPP( EXTRA_GNUPG_SOURCES gpgop.h ) QT4_WRAP_CPP( EXTRA_GNUPG_SOURCES gpgproc/gpgproc.h ) QT4_WRAP_CPP( EXTRA_GNUPG_SOURCES gpgproc/sprocess.h ) ADD_LIBRARY(qca-gnupg SHARED ${QCA_GNUPG_MOC_SOURCES} gpgproc/sprocess.cpp ${EXTRA_GNUPG_SOURCES} ) INCLUDE_DIRECTORIES(gpgproc) TARGET_LINK_LIBRARIES(qca-gnupg ${QT_QTCORE_LIBRARY} qca) #TODO perhaps search adavapi on win32 IF (WIN32) TARGET_LINK_LIBRARIES(qca-gnupg advapi32) ENDIF (WIN32) INSTALL(TARGETS qca-gnupg LIBRARY DESTINATION ${qca_PLUGINSDIR}) qca-gnupg-2.0.0-beta3/gpgop.cpp0000644000175000017500000007644110776557777015671 0ustar justinjustin/* * Copyright (C) 2003-2005 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * */ #include "gpgop.h" #include "gpgproc.h" #include namespace gpgQCAPlugin { //---------------------------------------------------------------------------- // LineConverter //---------------------------------------------------------------------------- class LineConverter { public: enum Mode { Read, Write }; void setup(Mode m) { state = Normal; mode = m; #ifdef Q_OS_WIN write_conv = true; #else write_conv = false; #endif prebytes = 0; list.clear(); } QByteArray update(const QByteArray &buf) { if(mode == Read) { QByteArray out; if(state == Normal) { out = buf; } else { out.resize(buf.size() + 1); out[0] = '\r'; memcpy(out.data() + 1, buf.data(), buf.size()); } int n = 0; while(1) { n = out.indexOf('\r', n); // not found if(n == -1) { break; } // found, not last character if(n < (buf.size() - 1)) { if(out[n + 1] == '\n') { // clip out the '\r' memmove(out.data() + n, out.data() + n + 1, out.size() - n - 1); out.resize(out.size() - 1); } } // found, last character else { state = Partial; break; } ++n; } return out; } else { if(write_conv) { QByteArray out; int prev = 0; int at = 0; while(1) { int n = buf.indexOf('\n', at); if(n == -1) break; int chunksize = n - at; int oldsize = out.size(); out.resize(oldsize + chunksize + 2); memcpy(out.data() + oldsize, buf.data() + at, chunksize); memcpy(out.data() + oldsize + chunksize, "\r\n", 2); list.append(prebytes + n + 1 - prev); prebytes = 0; prev = n; at = n + 1; } if(at < buf.size()) { int chunksize = buf.size() - at; int oldsize = out.size(); out.resize(oldsize + chunksize); memcpy(out.data() + oldsize, buf.data() + at, chunksize); } prebytes += buf.size() - prev; return out; } else return buf; } } QByteArray final() { if(mode == Read) { QByteArray out; if(state == Partial) { out.resize(1); out[0] = '\r'; } return out; } else { return QByteArray(); } } QByteArray process(const QByteArray &buf) { return update(buf) + final(); } int writtenToActual(int bytes) { if(write_conv) { int n = 0; int counter = bytes; while(counter > 0) { if(!list.isEmpty() && bytes >= list.first()) { ++n; counter -= list.takeFirst(); } else { if(list.isEmpty()) prebytes -= counter; else list.first() -= counter; if(prebytes < 0) { bytes += prebytes; prebytes = 0; } break; } } return bytes - n; } else return bytes; } private: enum State { Normal, Partial }; Mode mode; State state; bool write_conv; public: int prebytes; QList list; }; //---------------------------------------------------------------------------- // GpgAction //---------------------------------------------------------------------------- static QDateTime getTimestamp(const QString &s) { if(s.isEmpty()) return QDateTime(); if(s.contains('T')) { return QDateTime::fromString(s, Qt::ISODate); } else { QDateTime dt; dt.setTime_t(s.toInt()); return dt; } } static QByteArray getCString(const QByteArray &a) { QByteArray out; // convert the "backslash" C-string syntax for(int n = 0; n < a.size(); ++n) { if(a[n] == '\\' && n + 1 < a.size()) { ++n; unsigned char c = (unsigned char)a[n]; if(c == '\\') { out += '\\'; } else if(c == 'x' && n + 2 < a.size()) { ++n; QByteArray hex = a.mid(n, 2); ++n; // only skip one, loop will skip the next bool ok; uint val = hex.toInt(&ok, 16); if(ok) { out += (unsigned char)val; } else { out += "\\x"; out += hex; } } } else { out += a[n]; } } return out; } static bool stringToKeyList(const QString &outstr, GpgOp::KeyList *_keylist, QString *_keyring) { GpgOp::KeyList keyList; QStringList lines = outstr.split('\n'); if(lines.count() < 1) return false; QStringList::ConstIterator it = lines.begin(); // first line is keyring file QString keyring = *(it++); // if the second line isn't a divider, we are dealing // with a new version of gnupg that doesn't give us // the keyring file on gpg --list-keys --with-colons if(it == lines.end() || (*it).isEmpty() || (*it).at(0) != '-') { // first line wasn't the keyring name... keyring.clear(); // ...so read the first line again it--; } else { // this was the divider line - skip it it++; } for(; it != lines.end(); ++it) { QStringList f = (*it).split(':'); if(f.count() < 1) continue; QString type = f[0]; bool key = false; // key or not bool primary = false; // primary key or sub key bool sec = false; // private key or not if(type == "pub") { key = true; primary = true; } else if(type == "sec") { key = true; primary = true; sec = true; } else if(type == "sub") { key = true; } else if(type == "ssb") { key = true; sec = true; } if(key) { if(primary) { keyList += GpgOp::Key(); QString trust = f[1]; if(trust == "f" || trust == "u") keyList.last().isTrusted = true; } int key_type = f[3].toInt(); QString caps = f[11]; GpgOp::KeyItem item; item.bits = f[2].toInt(); if(key_type == 1) item.type = GpgOp::KeyItem::RSA; else if(key_type == 16) item.type = GpgOp::KeyItem::ElGamal; else if(key_type == 17) item.type = GpgOp::KeyItem::DSA; else item.type = GpgOp::KeyItem::Unknown; item.id = f[4]; item.creationDate = getTimestamp(f[5]); item.expirationDate = getTimestamp(f[6]); if(caps.contains('e')) item.caps |= GpgOp::KeyItem::Encrypt; if(caps.contains('s')) item.caps |= GpgOp::KeyItem::Sign; if(caps.contains('c')) item.caps |= GpgOp::KeyItem::Certify; if(caps.contains('a')) item.caps |= GpgOp::KeyItem::Auth; keyList.last().keyItems += item; } else if(type == "uid") { QByteArray uid = getCString(f[9].toLatin1()); keyList.last().userIds.append(QString::fromUtf8(uid)); } else if(type == "fpr") { QString s = f[9]; keyList.last().keyItems.last().fingerprint = s; } } if(_keylist) *_keylist = keyList; if(_keyring) *_keyring = keyring; return true; } static bool findKeyringFilename(const QString &outstr, QString *_keyring) { QStringList lines = outstr.split('\n'); if(lines.count() < 1) return false; *_keyring = lines[0]; return true; } class GpgAction : public QObject { Q_OBJECT public: class Input { public: QString bin; GpgOp::Type op; bool opt_ascii, opt_noagent, opt_alwaystrust; QString opt_pubfile, opt_secfile; QStringList recip_ids; QString signer_id; QByteArray sig; QByteArray inkey; QString export_key_id; QString delete_key_fingerprint; Input() : opt_ascii(false), opt_noagent(false), opt_alwaystrust(false) {} }; class Output { public: bool success; GpgOp::Error errorCode; GpgOp::KeyList keys; QString keyringFile; QString encryptedToId; bool wasSigned; QString signerId; QDateTime timestamp; GpgOp::VerifyResult verifyResult; Output() : success(false), errorCode(GpgOp::ErrorUnknown), wasSigned(false) {} }; Input input; Output output; GPGProc proc; bool collectOutput, allowInput; LineConverter readConv, writeConv; bool readText, writeText; QByteArray buf_stdout, buf_stderr; bool useAux; QString passphraseKeyId; bool signing, signPartDone, decryptGood, signGood; GpgOp::Error curError; bool badPassphrase; bool need_submitPassphrase, need_cardOkay; QString diagnosticText; SafeTimer dtextTimer; #ifdef GPG_PROFILE QTime timer; #endif GpgAction(QObject *parent = 0) : QObject(parent), proc(this), dtextTimer(this) { dtextTimer.setSingleShot(true); connect(&proc, SIGNAL(error(gpgQCAPlugin::GPGProc::Error)), SLOT(proc_error(gpgQCAPlugin::GPGProc::Error))); connect(&proc, SIGNAL(finished(int)), SLOT(proc_finished(int))); connect(&proc, SIGNAL(readyReadStdout()), SLOT(proc_readyReadStdout())); connect(&proc, SIGNAL(readyReadStderr()), SLOT(proc_readyReadStderr())); connect(&proc, SIGNAL(readyReadStatusLines()), SLOT(proc_readyReadStatusLines())); connect(&proc, SIGNAL(bytesWrittenStdin(int)), SLOT(proc_bytesWrittenStdin(int))); connect(&proc, SIGNAL(bytesWrittenAux(int)), SLOT(proc_bytesWrittenAux(int))); connect(&proc, SIGNAL(bytesWrittenCommand(int)), SLOT(proc_bytesWrittenCommand(int))); connect(&proc, SIGNAL(debug(const QString &)), SLOT(proc_debug(const QString &))); connect(&dtextTimer, SIGNAL(timeout()), SLOT(t_dtext())); reset(); } ~GpgAction() { reset(); } void reset() { collectOutput = true; allowInput = false; readConv.setup(LineConverter::Read); writeConv.setup(LineConverter::Write); readText = false; writeText = false; useAux = false; passphraseKeyId = QString(); signing = false; signPartDone = false; decryptGood = false; signGood = false; curError = GpgOp::ErrorUnknown; badPassphrase = false; need_submitPassphrase = false; need_cardOkay = false; diagnosticText = QString(); dtextTimer.stop(); output = Output(); proc.reset(); } void start() { reset(); QStringList args; bool extra = false; if(input.opt_ascii) args += "--armor"; if(input.opt_noagent) args += "--no-use-agent"; if(input.opt_alwaystrust) args += "--always-trust"; if(!input.opt_pubfile.isEmpty() && !input.opt_secfile.isEmpty()) { args += "--no-default-keyring"; args += "--keyring"; args += input.opt_pubfile; args += "--secret-keyring"; args += input.opt_secfile; } switch(input.op) { case GpgOp::Check: { args += "--version"; readText = true; break; } case GpgOp::SecretKeyringFile: { args += "--list-secret-keys"; readText = true; break; } case GpgOp::PublicKeyringFile: { args += "--list-public-keys"; readText = true; break; } case GpgOp::SecretKeys: { args += "--fixed-list-mode"; args += "--with-colons"; args += "--with-fingerprint"; args += "--with-fingerprint"; args += "--list-secret-keys"; readText = true; break; } case GpgOp::PublicKeys: { args += "--fixed-list-mode"; args += "--with-colons"; args += "--with-fingerprint"; args += "--with-fingerprint"; args += "--list-public-keys"; readText = true; break; } case GpgOp::Encrypt: { args += "--encrypt"; // recipients for(QStringList::ConstIterator it = input.recip_ids.begin(); it != input.recip_ids.end(); ++it) { args += "--recipient"; args += QString("0x") + *it; } extra = true; collectOutput = false; allowInput = true; if(input.opt_ascii) readText = true; break; } case GpgOp::Decrypt: { args += "--decrypt"; extra = true; collectOutput = false; allowInput = true; if(input.opt_ascii) writeText = true; break; } case GpgOp::Sign: { args += "--default-key"; args += QString("0x") + input.signer_id; args += "--sign"; extra = true; collectOutput = false; allowInput = true; if(input.opt_ascii) readText = true; signing = true; break; } case GpgOp::SignAndEncrypt: { args += "--default-key"; args += QString("0x") + input.signer_id; args += "--sign"; args += "--encrypt"; // recipients for(QStringList::ConstIterator it = input.recip_ids.begin(); it != input.recip_ids.end(); ++it) { args += "--recipient"; args += QString("0x") + *it; } extra = true; collectOutput = false; allowInput = true; if(input.opt_ascii) readText = true; signing = true; break; } case GpgOp::SignClearsign: { args += "--default-key"; args += QString("0x") + input.signer_id; args += "--clearsign"; extra = true; collectOutput = false; allowInput = true; if(input.opt_ascii) readText = true; signing = true; break; } case GpgOp::SignDetached: { args += "--default-key"; args += QString("0x") + input.signer_id; args += "--detach-sign"; extra = true; collectOutput = false; allowInput = true; if(input.opt_ascii) readText = true; signing = true; break; } case GpgOp::Verify: { args += "--verify"; args += "-"; //krazy:exclude=doublequote_chars extra = true; allowInput = true; if(input.opt_ascii) writeText = true; break; } case GpgOp::VerifyDetached: { args += "--verify"; args += "-"; //krazy:exclude=doublequote_chars args += "-&?"; extra = true; allowInput = true; useAux = true; break; } case GpgOp::Import: { args += "--import"; readText = true; if(input.opt_ascii) writeText = true; break; } case GpgOp::Export: { args += "--export"; args += QString("0x") + input.export_key_id; collectOutput = false; if(input.opt_ascii) readText = true; break; } case GpgOp::DeleteKey: { args += "--batch"; args += "--delete-key"; args += QString("0x") + input.delete_key_fingerprint; break; } } #ifdef GPG_PROFILE timer.start(); printf("<< launch >>\n"); #endif proc.start(input.bin, args, extra ? GPGProc::ExtendedMode : GPGProc::NormalMode); // detached sig if(input.op == GpgOp::VerifyDetached) { QByteArray a = input.sig; if(input.opt_ascii) { LineConverter conv; conv.setup(LineConverter::Write); a = conv.process(a); } proc.writeStdin(a); proc.closeStdin(); } // import if(input.op == GpgOp::Import) { QByteArray a = input.inkey; if(writeText) { LineConverter conv; conv.setup(LineConverter::Write); a = conv.process(a); } proc.writeStdin(a); proc.closeStdin(); } } #ifdef QPIPE_SECURE void submitPassphrase(const QCA::SecureArray &a) #else void submitPassphrase(const QByteArray &a) #endif { if(!need_submitPassphrase) return; need_submitPassphrase = false; #ifdef QPIPE_SECURE QCA::SecureArray b; #else QByteArray b; #endif // filter out newlines, since that's the delimiter used // to indicate a submitted passphrase b.resize(a.size()); int at = 0; for(int n = 0; n < a.size(); ++n) { if(a[n] != '\n') b[at++] = a[n]; } b.resize(at); // append newline b.resize(b.size() + 1); b[b.size() - 1] = '\n'; proc.writeCommand(b); } public slots: QByteArray read() { if(collectOutput) return QByteArray(); QByteArray a = proc.readStdout(); if(readText) a = readConv.update(a); if(!proc.isActive()) a += readConv.final(); return a; } void write(const QByteArray &in) { if(!allowInput) return; QByteArray a = in; if(writeText) a = writeConv.update(in); if(useAux) proc.writeAux(a); else proc.writeStdin(a); } void endWrite() { if(!allowInput) return; if(useAux) proc.closeAux(); else proc.closeStdin(); } void cardOkay() { if(need_cardOkay) { need_cardOkay = false; submitCommand("\n"); } } QString readDiagnosticText() { QString s = diagnosticText; diagnosticText = QString(); return s; } signals: void readyRead(); void bytesWritten(int bytes); void finished(); void needPassphrase(const QString &keyId); void needCard(); void readyReadDiagnosticText(); private: void submitCommand(const QByteArray &a) { proc.writeCommand(a); } // since str is taken as a value, it is ok to use the same variable for 'rest' QString nextArg(QString str, QString *rest = 0) { QString out; int n = str.indexOf(' '); if(n == -1) { if(rest) *rest = QString(); return str; } else { if(rest) *rest = str.mid(n + 1); return str.mid(0, n); } } void processStatusLine(const QString &line) { diagnosticText += QString("{") + line + "}\n"; ensureDTextEmit(); if(!proc.isActive()) return; QString s, rest; s = nextArg(line, &rest); if(s == "NODATA") { // only set this if it'll make it better if(curError == GpgOp::ErrorUnknown) curError = GpgOp::ErrorFormat; } else if(s == "UNEXPECTED") { if(curError == GpgOp::ErrorUnknown) curError = GpgOp::ErrorFormat; } else if(s == "KEYEXPIRED") { if(curError == GpgOp::ErrorUnknown) { if(input.op == GpgOp::SignAndEncrypt) { if(!signPartDone) curError = GpgOp::ErrorSignerExpired; else curError = GpgOp::ErrorEncryptExpired; } else { if(signing) curError = GpgOp::ErrorSignerExpired; else curError = GpgOp::ErrorEncryptExpired; } } } else if(s == "INV_RECP") { int r = nextArg(rest).toInt(); if(curError == GpgOp::ErrorUnknown) { if(r == 10) curError = GpgOp::ErrorEncryptUntrusted; else curError = GpgOp::ErrorEncryptInvalid; } } else if(s == "NO_SECKEY") { output.encryptedToId = nextArg(rest); if(curError == GpgOp::ErrorUnknown) curError = GpgOp::ErrorDecryptNoKey; } else if(s == "DECRYPTION_OKAY") { decryptGood = true; // message could be encrypted with several keys if(curError == GpgOp::ErrorDecryptNoKey) curError = GpgOp::ErrorUnknown; } else if(s == "SIG_CREATED") { signGood = true; } else if(s == "USERID_HINT") { passphraseKeyId = nextArg(rest); } else if(s == "GET_HIDDEN") { QString arg = nextArg(rest); if(arg == "passphrase.enter") { need_submitPassphrase = true; // for signal-safety, emit later QMetaObject::invokeMethod(this, "needPassphrase", Qt::QueuedConnection, Q_ARG(QString, passphraseKeyId)); } } else if(s == "GET_LINE") { QString arg = nextArg(rest); if(arg == "cardctrl.insert_card.okay") { need_cardOkay = true; QMetaObject::invokeMethod(this, "needCard", Qt::QueuedConnection); } } else if(s == "GET_BOOL") { QString arg = nextArg(rest); if(arg == "untrusted_key.override") submitCommand("no\n"); } else if(s == "GOOD_PASSPHRASE") { badPassphrase = false; // a trick to determine what KEYEXPIRED should apply to signPartDone = true; } else if(s == "BAD_PASSPHRASE") { badPassphrase = true; } else if(s == "GOODSIG") { output.wasSigned = true; output.signerId = nextArg(rest); output.verifyResult = GpgOp::VerifyGood; } else if(s == "BADSIG") { output.wasSigned = true; output.signerId = nextArg(rest); output.verifyResult = GpgOp::VerifyBad; } else if(s == "ERRSIG") { output.wasSigned = true; QStringList list = rest.split(' ', QString::SkipEmptyParts); output.signerId = list[0]; output.timestamp = getTimestamp(list[4]); output.verifyResult = GpgOp::VerifyNoKey; } else if(s == "VALIDSIG") { QStringList list = rest.split(' ', QString::SkipEmptyParts); output.timestamp = getTimestamp(list[2]); } } void processResult(int code) { #ifdef GPG_PROFILE printf("<< launch: %d >>\n", timer.elapsed()); #endif // put stdout and stderr into QStrings QString outstr = QString::fromLatin1(buf_stdout); QString errstr = QString::fromLatin1(buf_stderr); if(collectOutput) diagnosticText += QString("stdout: [%1]\n").arg(outstr); diagnosticText += QString("stderr: [%1]\n").arg(errstr); ensureDTextEmit(); if(badPassphrase) { output.errorCode = GpgOp::ErrorPassphrase; } else if(curError != GpgOp::ErrorUnknown) { output.errorCode = curError; } else if(code == 0) { if(input.op == GpgOp::SecretKeyringFile || input.op == GpgOp::PublicKeyringFile) { if(findKeyringFilename(outstr, &output.keyringFile)) output.success = true; } else if(input.op == GpgOp::SecretKeys || input.op == GpgOp::PublicKeys) { if(stringToKeyList(outstr, &output.keys, &output.keyringFile)) output.success = true; } else output.success = true; } else { // decrypt and sign success based on status only. // this is mainly because gpg uses fatal return // values if there is trouble with gpg-agent, even // though the operation otherwise works. if(input.op == GpgOp::Decrypt && decryptGood) output.success = true; if(signing && signGood) output.success = true; // gpg will indicate failure for bad sigs, but we don't // consider this to be operation failure. bool signedMakesItGood = false; if(input.op == GpgOp::Verify || input.op == GpgOp::VerifyDetached) signedMakesItGood = true; if(signedMakesItGood && output.wasSigned) output.success = true; } emit finished(); } void ensureDTextEmit() { if(!dtextTimer.isActive()) dtextTimer.start(); } private slots: void t_dtext() { emit readyReadDiagnosticText(); } void proc_error(gpgQCAPlugin::GPGProc::Error e) { QString str; if(e == GPGProc::FailedToStart) str = "FailedToStart"; else if(e == GPGProc::UnexpectedExit) str = "UnexpectedExit"; else if(e == GPGProc::ErrorWrite) str = "ErrorWrite"; diagnosticText += QString("GPG Process Error: %1\n").arg(str); ensureDTextEmit(); output.errorCode = GpgOp::ErrorProcess; emit finished(); } void proc_finished(int exitCode) { diagnosticText += QString("GPG Process Finished: exitStatus=%1\n").arg(exitCode); ensureDTextEmit(); processResult(exitCode); } void proc_readyReadStdout() { if(collectOutput) { QByteArray a = proc.readStdout(); if(readText) a = readConv.update(a); buf_stdout.append(a); } else emit readyRead(); } void proc_readyReadStderr() { buf_stderr.append(proc.readStderr()); } void proc_readyReadStatusLines() { QStringList lines = proc.readStatusLines(); for(int n = 0; n < lines.count(); ++n) processStatusLine(lines[n]); } void proc_bytesWrittenStdin(int bytes) { if(!useAux) { int actual = writeConv.writtenToActual(bytes); emit bytesWritten(actual); } } void proc_bytesWrittenAux(int bytes) { if(useAux) { int actual = writeConv.writtenToActual(bytes); emit bytesWritten(actual); } } void proc_bytesWrittenCommand(int) { // don't care about this } void proc_debug(const QString &str) { diagnosticText += "GPGProc: " + str + '\n'; ensureDTextEmit(); } }; //---------------------------------------------------------------------------- // GpgOp //---------------------------------------------------------------------------- enum ResetMode { ResetSession = 0, ResetSessionAndData = 1, ResetAll = 2 }; class GpgOp::Private : public QObject { Q_OBJECT public: QCA::Synchronizer sync; GpgOp *q; GpgAction *act; QString bin; GpgOp::Type op; GpgAction::Output output; QByteArray result; QString diagnosticText; QList eventList; bool waiting; bool opt_ascii, opt_noagent, opt_alwaystrust; QString opt_pubfile, opt_secfile; #ifdef GPG_PROFILE QTime timer; #endif Private(GpgOp *_q) : QObject(_q), sync(_q), q(_q) { act = 0; waiting = false; reset(ResetAll); } ~Private() { reset(ResetAll); } void reset(ResetMode mode) { if(act) { releaseAndDeleteLater(this, act); act = 0; } if(mode >= ResetSessionAndData) { output = GpgAction::Output(); result.clear(); diagnosticText = QString(); eventList.clear(); } if(mode >= ResetAll) { opt_ascii = false; opt_noagent = false; opt_alwaystrust = false; opt_pubfile = QString(); opt_secfile = QString(); } } void make_act(GpgOp::Type _op) { reset(ResetSessionAndData); op = _op; act = new GpgAction(this); connect(act, SIGNAL(readyRead()), SLOT(act_readyRead())); connect(act, SIGNAL(bytesWritten(int)), SLOT(act_bytesWritten(int))); connect(act, SIGNAL(needPassphrase(const QString &)), SLOT(act_needPassphrase(const QString &))); connect(act, SIGNAL(needCard()), SLOT(act_needCard())); connect(act, SIGNAL(finished()), SLOT(act_finished())); connect(act, SIGNAL(readyReadDiagnosticText()), SLOT(act_readyReadDiagnosticText())); act->input.bin = bin; act->input.op = op; act->input.opt_ascii = opt_ascii; act->input.opt_noagent = opt_noagent; act->input.opt_alwaystrust = opt_alwaystrust; act->input.opt_pubfile = opt_pubfile; act->input.opt_secfile = opt_secfile; } void eventReady(const GpgOp::Event &e) { eventList += e; sync.conditionMet(); } void eventReady(GpgOp::Event::Type type) { GpgOp::Event e; e.type = type; eventReady(e); } void eventReady(GpgOp::Event::Type type, int written) { GpgOp::Event e; e.type = type; e.written = written; eventReady(e); } void eventReady(GpgOp::Event::Type type, const QString &keyId) { GpgOp::Event e; e.type = type; e.keyId = keyId; eventReady(e); } public slots: void act_readyRead() { if(waiting) eventReady(GpgOp::Event::ReadyRead); else emit q->readyRead(); } void act_bytesWritten(int bytes) { if(waiting) eventReady(GpgOp::Event::BytesWritten, bytes); else emit q->bytesWritten(bytes); } void act_needPassphrase(const QString &keyId) { if(waiting) eventReady(GpgOp::Event::NeedPassphrase, keyId); else emit q->needPassphrase(keyId); } void act_needCard() { if(waiting) eventReady(GpgOp::Event::NeedCard); else emit q->needCard(); } void act_readyReadDiagnosticText() { QString s = act->readDiagnosticText(); //printf("dtext ready: [%s]\n", qPrintable(s)); diagnosticText += s; if(waiting) eventReady(GpgOp::Event::ReadyReadDiagnosticText); else emit q->readyReadDiagnosticText(); } void act_finished() { #ifdef GPG_PROFILE if(op == GpgOp::Encrypt) printf("<< doEncrypt: %d >>\n", timer.elapsed()); #endif result = act->read(); diagnosticText += act->readDiagnosticText(); output = act->output; QMap errmap; errmap[GpgOp::ErrorProcess] = "ErrorProcess"; errmap[GpgOp::ErrorPassphrase] = "ErrorPassphrase"; errmap[GpgOp::ErrorFormat] = "ErrorFormat"; errmap[GpgOp::ErrorSignerExpired] = "ErrorSignerExpired"; errmap[GpgOp::ErrorEncryptExpired] = "ErrorEncryptExpired"; errmap[GpgOp::ErrorEncryptUntrusted] = "ErrorEncryptUntrusted"; errmap[GpgOp::ErrorEncryptInvalid] = "ErrorEncryptInvalid"; errmap[GpgOp::ErrorDecryptNoKey] = "ErrorDecryptNoKey"; errmap[GpgOp::ErrorUnknown] = "ErrorUnknown"; if(output.success) diagnosticText += "GpgAction success\n"; else diagnosticText += QString("GpgAction error: %1\n").arg(errmap[output.errorCode]); if(output.wasSigned) { QString s; if(output.verifyResult == GpgOp::VerifyGood) s = "VerifyGood"; else if(output.verifyResult == GpgOp::VerifyBad) s = "VerifyBad"; else s = "VerifyNoKey"; diagnosticText += QString("wasSigned: verifyResult: %1\n").arg(s); } //printf("diagnosticText:\n%s", qPrintable(diagnosticText)); reset(ResetSession); if(waiting) eventReady(GpgOp::Event::Finished); else emit q->finished(); } }; GpgOp::GpgOp(const QString &bin, QObject *parent) :QObject(parent) { d = new Private(this); d->bin = bin; } GpgOp::~GpgOp() { delete d; } void GpgOp::reset() { d->reset(ResetAll); } bool GpgOp::isActive() const { return (d->act ? true : false); } GpgOp::Type GpgOp::op() const { return d->op; } void GpgOp::setAsciiFormat(bool b) { d->opt_ascii = b; } void GpgOp::setDisableAgent(bool b) { d->opt_noagent = b; } void GpgOp::setAlwaysTrust(bool b) { d->opt_alwaystrust = b; } void GpgOp::setKeyrings(const QString &pubfile, const QString &secfile) { d->opt_pubfile = pubfile; d->opt_secfile = secfile; } void GpgOp::doCheck() { d->make_act(Check); d->act->start(); } void GpgOp::doSecretKeyringFile() { d->make_act(SecretKeyringFile); d->act->start(); } void GpgOp::doPublicKeyringFile() { d->make_act(PublicKeyringFile); d->act->start(); } void GpgOp::doSecretKeys() { d->make_act(SecretKeys); d->act->start(); } void GpgOp::doPublicKeys() { d->make_act(PublicKeys); d->act->start(); } void GpgOp::doEncrypt(const QStringList &recip_ids) { #ifdef GPG_PROFILE d->timer.start(); printf("<< doEncrypt >>\n"); #endif d->make_act(Encrypt); d->act->input.recip_ids = recip_ids; d->act->start(); } void GpgOp::doDecrypt() { d->make_act(Decrypt); d->act->start(); } void GpgOp::doSign(const QString &signer_id) { d->make_act(Sign); d->act->input.signer_id = signer_id; d->act->start(); } void GpgOp::doSignAndEncrypt(const QString &signer_id, const QStringList &recip_ids) { d->make_act(SignAndEncrypt); d->act->input.signer_id = signer_id; d->act->input.recip_ids = recip_ids; d->act->start(); } void GpgOp::doSignClearsign(const QString &signer_id) { d->make_act(SignClearsign); d->act->input.signer_id = signer_id; d->act->start(); } void GpgOp::doSignDetached(const QString &signer_id) { d->make_act(SignDetached); d->act->input.signer_id = signer_id; d->act->start(); } void GpgOp::doVerify() { d->make_act(Verify); d->act->start(); } void GpgOp::doVerifyDetached(const QByteArray &sig) { d->make_act(VerifyDetached); d->act->input.sig = sig; d->act->start(); } void GpgOp::doImport(const QByteArray &in) { d->make_act(Import); d->act->input.inkey = in; d->act->start(); } void GpgOp::doExport(const QString &key_id) { d->make_act(Export); d->act->input.export_key_id = key_id; d->act->start(); } void GpgOp::doDeleteKey(const QString &key_fingerprint) { d->make_act(DeleteKey); d->act->input.delete_key_fingerprint = key_fingerprint; d->act->start(); } #ifdef QPIPE_SECURE void GpgOp::submitPassphrase(const QCA::SecureArray &a) #else void GpgOp::submitPassphrase(const QByteArray &a) #endif { d->act->submitPassphrase(a); } void GpgOp::cardOkay() { d->act->cardOkay(); } QByteArray GpgOp::read() { if(d->act) { return d->act->read(); } else { QByteArray a = d->result; d->result.clear(); return a; } } void GpgOp::write(const QByteArray &in) { d->act->write(in); } void GpgOp::endWrite() { d->act->endWrite(); } QString GpgOp::readDiagnosticText() { QString s = d->diagnosticText; d->diagnosticText = QString(); return s; } GpgOp::Event GpgOp::waitForEvent(int msecs) { if(!d->eventList.isEmpty()) return d->eventList.takeFirst(); if(!d->act) return GpgOp::Event(); d->waiting = true; d->sync.waitForCondition(msecs); d->waiting = false; return d->eventList.takeFirst(); } bool GpgOp::success() const { return d->output.success; } GpgOp::Error GpgOp::errorCode() const { return d->output.errorCode; } GpgOp::KeyList GpgOp::keys() const { return d->output.keys; } QString GpgOp::keyringFile() const { return d->output.keyringFile; } QString GpgOp::encryptedToId() const { return d->output.encryptedToId; } bool GpgOp::wasSigned() const { return d->output.wasSigned; } QString GpgOp::signerId() const { return d->output.signerId; } QDateTime GpgOp::timestamp() const { return d->output.timestamp; } GpgOp::VerifyResult GpgOp::verifyResult() const { return d->output.verifyResult; } } #include "gpgop.moc"