author | sandman <sandman> | 2002-12-17 19:16:18 (UTC) |
---|---|---|
committer | sandman <sandman> | 2002-12-17 19:16:18 (UTC) |
commit | f36c70938c8c2907a1b61637af3bd589262b4b5e (patch) (side-by-side diff) | |
tree | 7ed7429477ad0b17ea131fddcc5cab9fff088b26 | |
parent | b6a03145553d7f536b04fc3355718cfdd72c590d (diff) | |
download | opie-f36c70938c8c2907a1b61637af3bd589262b4b5e.zip opie-f36c70938c8c2907a1b61637af3bd589262b4b5e.tar.gz opie-f36c70938c8c2907a1b61637af3bd589262b4b5e.tar.bz2 |
replaced the private QProcess copy for the FTP server with the already
available libopie/OProcess
-rw-r--r-- | core/launcher/launcher.pro | 2 | ||||
-rw-r--r-- | core/launcher/qprocess.cpp | 654 | ||||
-rw-r--r-- | core/launcher/qprocess.h | 174 | ||||
-rw-r--r-- | core/launcher/qprocess_unix.cpp | 1158 | ||||
-rw-r--r-- | core/launcher/transferserver.cpp | 2145 | ||||
-rw-r--r-- | core/launcher/transferserver.h | 14 |
6 files changed, 1097 insertions, 3050 deletions
diff --git a/core/launcher/launcher.pro b/core/launcher/launcher.pro index 3391378..21f8374 100644 --- a/core/launcher/launcher.pro +++ b/core/launcher/launcher.pro @@ -1,114 +1,112 @@ TEMPLATE = app CONFIG = qt warn_on release DESTDIR = ../../bin HEADERS = background.h \ desktop.h \ screensaver.h \ - qprocess.h \ mediummountgui.h \ info.h \ appicons.h \ taskbar.h \ sidething.h \ runningappbar.h \ stabmon.h \ inputmethods.h \ systray.h \ wait.h \ shutdownimpl.h \ launcher.h \ launcherview.h \ ../../core/apps/calibrate/calibrate.h \ startmenu.h \ transferserver.h \ qcopbridge.h \ packageslave.h \ irserver.h \ ../../rsync/buf.h \ ../../rsync/checksum.h \ ../../rsync/command.h \ ../../rsync/emit.h \ ../../rsync/job.h \ ../../rsync/netint.h \ ../../rsync/protocol.h \ ../../rsync/prototab.h \ ../../rsync/rsync.h \ ../../rsync/search.h \ ../../rsync/stream.h \ ../../rsync/sumset.h \ ../../rsync/trace.h \ ../../rsync/types.h \ ../../rsync/util.h \ ../../rsync/whole.h \ ../../rsync/config_rsync.h \ ../../rsync/qrsync.h \ quicklauncher.h SOURCES = background.cpp \ desktop.cpp \ screensaver.cpp \ mediummountgui.cpp \ - qprocess.cpp qprocess_unix.cpp \ info.cpp \ appicons.cpp \ taskbar.cpp \ sidething.cpp \ runningappbar.cpp \ stabmon.cpp \ inputmethods.cpp \ systray.cpp \ wait.cpp \ shutdownimpl.cpp \ launcher.cpp \ launcherview.cpp \ ../../core/apps/calibrate/calibrate.cpp \ transferserver.cpp \ packageslave.cpp \ irserver.cpp \ qcopbridge.cpp \ startmenu.cpp \ main.cpp \ ../../rsync/base64.c \ ../../rsync/buf.c \ ../../rsync/checksum.c \ ../../rsync/command.c \ ../../rsync/delta.c \ ../../rsync/emit.c \ ../../rsync/hex.c \ ../../rsync/job.c \ ../../rsync/mdfour.c \ ../../rsync/mksum.c \ ../../rsync/msg.c \ ../../rsync/netint.c \ ../../rsync/patch.c \ ../../rsync/prototab.c \ ../../rsync/readsums.c \ ../../rsync/scoop.c \ ../../rsync/search.c \ ../../rsync/stats.c \ ../../rsync/stream.c \ ../../rsync/sumset.c \ ../../rsync/trace.c \ ../../rsync/tube.c \ ../../rsync/util.c \ ../../rsync/version.c \ ../../rsync/whole.c \ ../../rsync/qrsync.cpp INTERFACES = syncdialog.ui INCLUDEPATH += ../../include DEPENDPATH += ../../include . INCLUDEPATH += ../../core/apps/calibrate DEPENDPATH += ../../core/apps/calibrate INCLUDEPATH += ../../rsync DEPENDPATH += ../../rsync TARGET = qpe LIBS += -lqpe -lcrypt -lopie TRANSLATIONS = ../../i18n/de/qpe.ts \ ../../i18n/xx/qpe.ts \ ../../i18n/en/qpe.ts \ ../../i18n/es/qpe.ts \ ../../i18n/fr/qpe.ts \ ../../i18n/hu/qpe.ts \ ../../i18n/ja/qpe.ts \ ../../i18n/ko/qpe.ts \ ../../i18n/no/qpe.ts \ diff --git a/core/launcher/qprocess.cpp b/core/launcher/qprocess.cpp deleted file mode 100644 index 618c0e0..0000000 --- a/core/launcher/qprocess.cpp +++ b/dev/null @@ -1,654 +0,0 @@ -/**************************************************************************** -** $Id$ -** -** Implementation of QProcess class -** -** Created : 20000905 -** -** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. -** -** This file is part of the kernel module of the Qt GUI Toolkit. -** -** This file may be distributed under the terms of the Q Public License -** as defined by Trolltech AS of Norway and appearing in the file -** LICENSE.QPL included in the packaging of this file. -** -** This file may be distributed and/or modified under the terms of the -** GNU General Public License version 2 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. -** -** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition -** licenses may use this file in accordance with the Qt Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for -** information about Qt Commercial License Agreements. -** See http://www.trolltech.com/qpl/ for QPL licensing information. -** See http://www.trolltech.com/gpl/ for GPL licensing information. -** -** Contact info@trolltech.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#include <stdio.h> -#include <stdlib.h> - -#include "qprocess.h" - -#ifndef QT_NO_PROCESS - -#include "qapplication.h" - - -//#define QT_QPROCESS_DEBUG - - -/*! - \class QProcess qprocess.h - - \brief The QProcess class is used to start external programs and to - communicate with them. - - This is a temporary class. This will be replaced by Qt 3's QProcess class. -*/ - -/*! - \enum QProcess::Communication - - This enum type defines the communication channels connected to the - process. - - \value Stdin Data can be written to the process's standard input. - - \value Stdout Data can be read from the process's standard output. - - \value Stderr Data can be read from the process's standard error. - - \value DupStderr Duplicates standard error to standard output for new - processes; i.e. everything that the process writes to standard error, is - reported by QProcess on standard output instead. This is especially useful if - your application requires that the output on standard output and standard - error is read in the same order as the process output it. Please note that - this is a binary flag, so if you want to activate this together with standard - input, output and error redirection (the default), you have to specify - \c{Stdin|Stdout|Stderr|DupStderr} for the setCommunication() call. - - \sa setCommunication() communication() -*/ - -/*! - Constructs a QProcess object. The \a parent and \a name parameters are passed - to the QObject constructor. - - \sa setArguments() addArgument() start() -*/ -QProcess::QProcess( QObject *parent, const char *name ) - : QObject( parent, name ), ioRedirection( FALSE ), notifyOnExit( FALSE ), - wroteToStdinConnected( FALSE ), - readStdoutCalled( FALSE ), readStderrCalled( FALSE ), - comms( Stdin|Stdout|Stderr ) -{ - init(); -} - -/*! - Constructs a QProcess with \a arg0 as the command to be executed. The - \a parent and \a name parameters are passed to the QObject constructor. - - The process is not started. You must call start() or launch() - to start the process. - - \sa setArguments() addArgument() start() -*/ -QProcess::QProcess( const QString& arg0, QObject *parent, const char *name ) - : QObject( parent, name ), ioRedirection( FALSE ), notifyOnExit( FALSE ), - wroteToStdinConnected( FALSE ), - readStdoutCalled( FALSE ), readStderrCalled( FALSE ), - comms( Stdin|Stdout|Stderr ) -{ - init(); - addArgument( arg0 ); -} - -/*! - Constructs a QProcess with \a args as the arguments of the process. The first - element in the list is the command to be executed. The other elements in the - list are the arguments to this command. The \a parent and \a name - parameters are passed to the QObject constructor. - - The process is not started. You must call start() or launch() - to start the process. - - \sa setArguments() addArgument() start() -*/ -QProcess::QProcess( const QStringList& args, QObject *parent, const char *name ) - : QObject( parent, name ), ioRedirection( FALSE ), notifyOnExit( FALSE ), - wroteToStdinConnected( FALSE ), - readStdoutCalled( FALSE ), readStderrCalled( FALSE ), - comms( Stdin|Stdout|Stderr ) -{ - init(); - setArguments( args ); -} - - -/*! - Returns the list of arguments that are set for the process. Arguments can be - specified with the constructor or with the functions setArguments() and - addArgument(). - - \sa setArguments() addArgument() -*/ -QStringList QProcess::arguments() const -{ - return _arguments; -} - -/*! - Clears the list of arguments that are set for the process. - - \sa setArguments() addArgument() -*/ -void QProcess::clearArguments() -{ - _arguments.clear(); -} - -/*! - Sets \a args as the arguments for the process. The first element in the list - is the command to be executed. The other elements in the list are the - arguments to the command. Any previous arguments are deleted. - - \sa arguments() addArgument() -*/ -void QProcess::setArguments( const QStringList& args ) -{ - _arguments = args; -} - -/*! - Adds \a arg to the end of the list of arguments. - - The first element in the list of arguments is the command to be - executed; the following elements are the arguments to the command. - - \sa arguments() setArguments() -*/ -void QProcess::addArgument( const QString& arg ) -{ - _arguments.append( arg ); -} - -#ifndef QT_NO_DIR -/*! - Returns the working directory that was set with - setWorkingDirectory(), or the current directory if none has been - set. - - \sa setWorkingDirectory() QDir::current() -*/ -QDir QProcess::workingDirectory() const -{ - return workingDir; -} - -/*! - Sets \a dir as the working directory for a process. This does not affect - running processes; only processes that are started afterwards are affected. - - Setting the working directory is especially useful for processes that try to - access files with relative filenames. - - \sa workingDirectory() start() -*/ -void QProcess::setWorkingDirectory( const QDir& dir ) -{ - workingDir = dir; -} -#endif //QT_NO_DIR - -/*! - Returns the communication required with the process. - - \sa setCommunication() -*/ -int QProcess::communication() const -{ - return comms; -} - -/*! - Sets \a commFlags as the communication required with the process. - - \a commFlags is a bitwise OR between the flags defined in \c Communication. - - The default is \c{Stdin|Stdout|Stderr}. - - \sa communication() -*/ -void QProcess::setCommunication( int commFlags ) -{ - comms = commFlags; -} - -/*! - Returns TRUE if the process has exited normally; otherwise returns - FALSE. This implies that this function returns FALSE if the process - is still running. - - \sa isRunning() exitStatus() processExited() -*/ -bool QProcess::normalExit() const -{ - // isRunning() has the side effect that it determines the exit status! - if ( isRunning() ) - return FALSE; - else - return exitNormal; -} - -/*! - Returns the exit status of the process or 0 if the process is still - running. This function returns immediately and does not wait until - the process is finished. - - If normalExit() is FALSE (e.g. if the program was killed or - crashed), this function returns 0, so you should check the return - value of normalExit() before relying on this value. - - \sa normalExit() processExited() -*/ -int QProcess::exitStatus() const -{ - // isRunning() has the side effect that it determines the exit status! - if ( isRunning() ) - return 0; - else - return exitStat; -} - - -/*! - Reads the data that the process has written to standard output. When - new data is written to standard output, the class emits the signal - readyReadStdout(). - - If there is no data to read, this function returns a QByteArray of - size 0: it does not wait until there is something to read. - - \sa readyReadStdout() readLineStdout() readStderr() writeToStdin() -*/ -QByteArray QProcess::readStdout() -{ - if ( readStdoutCalled ) { - return QByteArray(); - } - readStdoutCalled = TRUE; - - QByteArray buf = bufStdout()->copy(); - consumeBufStdout( -1 ); // consume everything - - readStdoutCalled = FALSE; - return buf; -} - -/*! - Reads the data that the process has written to standard error. When - new data is written to standard error, the class emits the signal - readyReadStderr(). - - If there is no data to read, this function returns a QByteArray of - size 0: it does not wait until there is something to read. - - \sa readyReadStderr() readLineStderr() readStdout() writeToStdin() -*/ -QByteArray QProcess::readStderr() -{ - if ( readStderrCalled ) { - return QByteArray(); - } - readStderrCalled = TRUE; - - QByteArray buf = bufStderr()->copy(); - consumeBufStderr( -1 ); // consume everything - - readStderrCalled = FALSE; - return buf; -} - -/*! - Returns TRUE if it's possible to read an entire line of text from - standard output at this time; otherwise returns FALSE. - - \sa readLineStdout() canReadLineStderr() -*/ -bool QProcess::canReadLineStdout() const -{ - QProcess *that = (QProcess*)this; - return that->scanNewline( TRUE, 0 ); -} - -/*! - Returns TRUE if it's possible to read an entire line of text from - standard error at this time; otherwise returns FALSE. - - \sa readLineStderr() canReadLineStdout() -*/ -bool QProcess::canReadLineStderr() const -{ - QProcess *that = (QProcess*)this; - return that->scanNewline( FALSE, 0 ); -} - -/*! - Reads a line of text from standard output, excluding any trailing newline or - carriage return characters, and returns it. Returns QString::null if - canReadLineStdout() returns FALSE. - - \sa canReadLineStdout() readyReadStdout() readStdout() readLineStderr() -*/ -QString QProcess::readLineStdout() -{ - QByteArray a; - QString s; - if ( scanNewline( TRUE, &a ) ) { - if ( a.isEmpty() ) - s = ""; - else - s = QString( a ); - } - return s; -} - -/*! - Reads a line of text from standard error, excluding any trailing newline or - carriage return characters and returns it. Returns QString::null if - canReadLineStderr() returns FALSE. - - \sa canReadLineStderr() readyReadStderr() readStderr() readLineStdout() -*/ -QString QProcess::readLineStderr() -{ - QByteArray a; - QString s; - if ( scanNewline( FALSE, &a ) ) { - if ( a.isEmpty() ) - s = ""; - else - s = QString( a ); - } - return s; -} - -/*! - This private function scans for any occurrence of \n or \r\n in the - buffer \e buf. It stores the text in the byte array \a store if it is - non-null. -*/ -bool QProcess::scanNewline( bool stdOut, QByteArray *store ) -{ - QByteArray *buf; - if ( stdOut ) - buf = bufStdout(); - else - buf = bufStderr(); - uint n = buf->size(); - uint i; - for ( i=0; i<n; i++ ) { - if ( buf->at(i) == '\n' ) { - break; - } - } - if ( i >= n ) - return FALSE; - - if ( store ) { - uint lineLength = i; - if ( lineLength>0 && buf->at(lineLength-1) == '\r' ) - lineLength--; // (if there are two \r, let one stay) - store->resize( lineLength ); - memcpy( store->data(), buf->data(), lineLength ); - if ( stdOut ) - consumeBufStdout( i+1 ); - else - consumeBufStderr( i+1 ); - } - return TRUE; -} - -/*! - \fn void QProcess::launchFinished() - - This signal is emitted when the process was started with launch(). - If the start was successful, this signal is emitted after all the - data has been written to standard input. If the start failed, then - this signal is emitted immediately. - - \sa launch() QObject::deleteLater() -*/ - -/*! - Runs the process and writes the data \a buf to the process's standard input. - If all the data is written to standard input, standard input is - closed. The command is searched for in the path for executable programs; - you can also use an absolute path in the command itself. - - If \a env is null, then the process is started with the same environment as - the starting process. If \a env is non-null, then the values in the - stringlist are interpreted as environment setttings of the form \c - {key=value} and the process is started with these environment settings. For - convenience, there is a small exception to this rule under Unix: if \a env - does not contain any settings for the environment variable \c - LD_LIBRARY_PATH, then this variable is inherited from the starting process. - - Returns TRUE if the process could be started; otherwise returns FALSE. - - Note that you should not use the slots writeToStdin() and closeStdin() on - processes started with launch(), since the result is not well-defined. If you - need these slots, use start() instead. - - The process may or may not read the \a buf data sent to its standard - input. - - You can call this function even when a process that was started with - this instance is still running. Be aware that if you do this the - standard input of the process that was launched first will be - closed, with any pending data being deleted, and the process will be - left to run out of your control. Similarly, if the process could not - be started the standard input will be closed and the pending data - deleted. (On operating systems that have zombie processes, Qt will - also wait() on the old process.) - - The object emits the signal launchFinished() when this function - call is finished. If the start was successful, this signal is - emitted after all the data has been written to standard input. If - the start failed, then this signal is emitted immediately. - - \sa start() launchFinished(); -*/ -bool QProcess::launch( const QByteArray& buf, QStringList *env ) -{ - if ( start( env ) ) { - if ( !buf.isEmpty() ) { - connect( this, SIGNAL(wroteToStdin()), - this, SLOT(closeStdinLaunch()) ); - writeToStdin( buf ); - } else { - closeStdin(); - emit launchFinished(); - } - return TRUE; - } else { - emit launchFinished(); - return FALSE; - } -} - -/*! \overload - - The data \a buf is written to standard input with writeToStdin() - using the QString::local8Bit() representation of the strings. -*/ -bool QProcess::launch( const QString& buf, QStringList *env ) -{ - if ( start( env ) ) { - if ( !buf.isEmpty() ) { - connect( this, SIGNAL(wroteToStdin()), - this, SLOT(closeStdinLaunch()) ); - writeToStdin( buf ); - } else { - closeStdin(); - emit launchFinished(); - } - return TRUE; - } else { - emit launchFinished(); - return FALSE; - } -} - -/*! - This private slot is used by the launch() functions to close standard input. -*/ -void QProcess::closeStdinLaunch() -{ - disconnect( this, SIGNAL(wroteToStdin()), - this, SLOT(closeStdinLaunch()) ); - closeStdin(); - emit launchFinished(); -} - - -/*! - \fn void QProcess::readyReadStdout() - - This signal is emitted when the process has written data to standard output. - You can read the data with readStdout(). - - Note that this signal is only emitted when there is new data and not - when there is old, but unread data. In the slot connected to this signal, you - should always read everything that is available at that moment to make sure - that you don't lose any data. - - \sa readStdout() readLineStdout() readyReadStderr() -*/ -/*! - \fn void QProcess::readyReadStderr() - - This signal is emitted when the process has written data to standard error. - You can read the data with readStderr(). - - Note that this signal is only emitted when there is new data and not - when there is old, but unread data. In the slot connected to this signal, you - should always read everything that is available at that moment to make sure - that you don't lose any data. - - \sa readStderr() readLineStderr() readyReadStdout() -*/ -/*! - \fn void QProcess::processExited() - - This signal is emitted when the process has exited. - - \sa isRunning() normalExit() exitStatus() start() launch() -*/ -/*! - \fn void QProcess::wroteToStdin() - - This signal is emitted if the data sent to standard input (via - writeToStdin()) was actually written to the process. This does not - imply that the process really read the data, since this class only detects - when it was able to write the data to the operating system. But it is now - safe to close standard input without losing pending data. - - \sa writeToStdin() closeStdin() -*/ - - -/*! \overload - - The string \a buf is handled as text using - the QString::local8Bit() representation. -*/ -void QProcess::writeToStdin( const QString& buf ) -{ - QByteArray tmp = buf.local8Bit(); - tmp.resize( buf.length() ); - writeToStdin( tmp ); -} - - -/* - * Under Windows the implementation is not so nice: it is not that easy to - * detect when one of the signals should be emitted; therefore there are some - * timers that query the information. - * To keep it a little efficient, use the timers only when they are needed. - * They are needed, if you are interested in the signals. So use - * connectNotify() and disconnectNotify() to keep track of your interest. - */ -/*! \reimp -*/ -void QProcess::connectNotify( const char * signal ) -{ -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::connectNotify(): signal %s has been connected", signal ); -#endif - if ( !ioRedirection ) - if ( qstrcmp( signal, SIGNAL(readyReadStdout()) )==0 || - qstrcmp( signal, SIGNAL(readyReadStderr()) )==0 - ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::connectNotify(): set ioRedirection to TRUE" ); -#endif - setIoRedirection( TRUE ); - return; - } - if ( !notifyOnExit && qstrcmp( signal, SIGNAL(processExited()) )==0 ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::connectNotify(): set notifyOnExit to TRUE" ); -#endif - setNotifyOnExit( TRUE ); - return; - } - if ( !wroteToStdinConnected && qstrcmp( signal, SIGNAL(wroteToStdin()) )==0 ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::connectNotify(): set wroteToStdinConnected to TRUE" ); -#endif - setWroteStdinConnected( TRUE ); - return; - } -} - -/*! \reimp -*/ -void QProcess::disconnectNotify( const char * ) -{ - if ( ioRedirection && - receivers( SIGNAL(readyReadStdout()) ) ==0 && - receivers( SIGNAL(readyReadStderr()) ) ==0 - ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::disconnectNotify(): set ioRedirection to FALSE" ); -#endif - setIoRedirection( FALSE ); - } - if ( notifyOnExit && receivers( SIGNAL(processExited()) ) == 0 ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::disconnectNotify(): set notifyOnExit to FALSE" ); -#endif - setNotifyOnExit( FALSE ); - } - if ( wroteToStdinConnected && receivers( SIGNAL(wroteToStdin()) ) == 0 ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::disconnectNotify(): set wroteToStdinConnected to FALSE" ); -#endif - setWroteStdinConnected( FALSE ); - } -} - -#endif // QT_NO_PROCESS diff --git a/core/launcher/qprocess.h b/core/launcher/qprocess.h deleted file mode 100644 index 306e659..0000000 --- a/core/launcher/qprocess.h +++ b/dev/null @@ -1,174 +0,0 @@ -/**************************************************************************** -** $Id$ -** -** Implementation of QProcess class -** -** Created : 20000905 -** -** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. -** -** This file is part of the kernel module of the Qt GUI Toolkit. -** -** This file may be distributed under the terms of the Q Public License -** as defined by Trolltech AS of Norway and appearing in the file -** LICENSE.QPL included in the packaging of this file. -** -** This file may be distributed and/or modified under the terms of the -** GNU General Public License version 2 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. -** -** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition -** licenses may use this file in accordance with the Qt Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for -** information about Qt Commercial License Agreements. -** See http://www.trolltech.com/qpl/ for QPL licensing information. -** See http://www.trolltech.com/gpl/ for GPL licensing information. -** -** Contact info@trolltech.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#ifndef QPROCESS_H -#define QPROCESS_H - -#ifndef QT_H -#include "qobject.h" -#include "qstringlist.h" -#include "qdir.h" -#endif // QT_H - -#ifndef QT_NO_PROCESS - -class QProcessPrivate; - - -class Q_EXPORT QProcess : public QObject -{ - Q_OBJECT -public: - QProcess( QObject *parent=0, const char *name=0 ); - QProcess( const QString& arg0, QObject *parent=0, const char *name=0 ); - QProcess( const QStringList& args, QObject *parent=0, const char *name=0 ); - ~QProcess(); - - // set and get the arguments and working directory - QStringList arguments() const; - void clearArguments(); - virtual void setArguments( const QStringList& args ); - virtual void addArgument( const QString& arg ); -#ifndef QT_NO_DIR - QDir workingDirectory() const; - virtual void setWorkingDirectory( const QDir& dir ); -#endif - - // set and get the comms wanted - enum Communication { Stdin=0x01, Stdout=0x02, Stderr=0x04, DupStderr=0x08 }; - void setCommunication( int c ); - int communication() const; - - // start the execution - virtual bool start( QStringList *env=0 ); - virtual bool launch( const QString& buf, QStringList *env=0 ); - virtual bool launch( const QByteArray& buf, QStringList *env=0 ); - - // inquire the status - bool isRunning() const; - bool normalExit() const; - int exitStatus() const; - - // reading - virtual QByteArray readStdout(); - virtual QByteArray readStderr(); - bool canReadLineStdout() const; - bool canReadLineStderr() const; - virtual QString readLineStdout(); - virtual QString readLineStderr(); - - // get platform dependent process information -#if defined(Q_OS_WIN32) - typedef void* PID; -#else - typedef long Q_LONG; - typedef Q_LONG PID; -#endif - PID processIdentifier(); - - void flushStdin(); - -signals: - void readyReadStdout(); - void readyReadStderr(); - void processExited(); - void wroteToStdin(); - void launchFinished(); - -public slots: - // end the execution - void tryTerminate() const; - void kill() const; - - // input - virtual void writeToStdin( const QByteArray& buf ); - virtual void writeToStdin( const QString& buf ); - virtual void closeStdin(); - -protected: // ### or private? - void connectNotify( const char * signal ); - void disconnectNotify( const char * signal ); -private: - void setIoRedirection( bool value ); - void setNotifyOnExit( bool value ); - void setWroteStdinConnected( bool value ); - - void init(); - void reset(); -#if defined(Q_OS_WIN32) - uint readStddev( HANDLE dev, char *buf, uint bytes ); -#endif - bool scanNewline( bool stdOut, QByteArray *store ); - - QByteArray* bufStdout(); - QByteArray* bufStderr(); - void consumeBufStdout( int consume ); - void consumeBufStderr( int consume ); - -private slots: - void socketRead( int fd ); - void socketWrite( int fd ); - void timeout(); - void closeStdinLaunch(); - -private: - QProcessPrivate *d; -#ifndef QT_NO_DIR - QDir workingDir; -#endif - QStringList _arguments; - - int exitStat; // exit status - bool exitNormal; // normal exit? - bool ioRedirection; // automatically set be (dis)connectNotify - bool notifyOnExit; // automatically set be (dis)connectNotify - bool wroteToStdinConnected; // automatically set be (dis)connectNotify - - bool readStdoutCalled; - bool readStderrCalled; - int comms; - - friend class QProcessPrivate; -#if defined(Q_OS_UNIX) || defined(_OS_UNIX) || defined(UNIX) - friend class QProcessManager; - friend class QProc; -#endif -}; - -#endif // QT_NO_PROCESS - -#endif // QPROCESS_H diff --git a/core/launcher/qprocess_unix.cpp b/core/launcher/qprocess_unix.cpp deleted file mode 100644 index 75f0f0c..0000000 --- a/core/launcher/qprocess_unix.cpp +++ b/dev/null @@ -1,1158 +0,0 @@ -/**************************************************************************** -** $Id$ -** -** Implementation of QProcess class for Unix -** -** Created : 20000905 -** -** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. -** -** This file is part of the kernel module of the Qt GUI Toolkit. -** -** This file may be distributed under the terms of the Q Public License -** as defined by Trolltech AS of Norway and appearing in the file -** LICENSE.QPL included in the packaging of this file. -** -** This file may be distributed and/or modified under the terms of the -** GNU General Public License version 2 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. -** -** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition -** licenses may use this file in accordance with the Qt Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for -** information about Qt Commercial License Agreements. -** See http://www.trolltech.com/qpl/ for QPL licensing information. -** See http://www.trolltech.com/gpl/ for GPL licensing information. -** -** Contact info@trolltech.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -//#include "qplatformdefs.h" - -// Solaris redefines connect -> __xnet_connect with _XOPEN_SOURCE_EXTENDED. -#if defined(connect) -#undef connect -#endif - -#include "qprocess.h" - -#ifndef QT_NO_PROCESS - -#include "qapplication.h" -#include "qqueue.h" -#include "qlist.h" -#include "qsocketnotifier.h" -#include "qtimer.h" -#include "qregexp.h" - -#include "qcleanuphandler_p.h" - -#include <stdlib.h> - -// ### FOR Qt 2.3 compat -#include <unistd.h> -#include <signal.h> -#include <sys/socket.h> -#include <sys/ioctl.h> -#include <sys/wait.h> -#include <sys/fcntl.h> - -#include <errno.h> - -#ifdef __MIPSEL__ -# ifndef SOCK_DGRAM -# define SOCK_DGRAM 1 -# endif -# ifndef SOCK_STREAM -# define SOCK_STREAM 2 -# endif -#endif - -//#define QT_QPROCESS_DEBUG - - -#ifdef Q_C_CALLBACKS -extern "C" { -#endif // Q_C_CALLBACKS - -#define QT_SIGNAL_RETTYPE void -#define QT_SIGNAL_ARGS int -#define QT_SIGNAL_IGNORE SIG_IGN - - QT_SIGNAL_RETTYPE qt_C_sigchldHnd(QT_SIGNAL_ARGS); - -#ifdef Q_C_CALLBACKS -} -#endif // Q_C_CALLBACKS - - -class QProc; -class QProcessManager; -class QProcessPrivate -{ -public: - QProcessPrivate(); - ~QProcessPrivate(); - - void closeOpenSocketsForChild(); - void newProc( pid_t pid, QProcess *process ); - - QByteArray bufStdout; - QByteArray bufStderr; - - QQueue<QByteArray> stdinBuf; - - QSocketNotifier *notifierStdin; - QSocketNotifier *notifierStdout; - QSocketNotifier *notifierStderr; - - ssize_t stdinBufRead; - QProc *proc; - - bool exitValuesCalculated; - bool socketReadCalled; - - static QProcessManager *procManager; -}; - - -/*********************************************************************** - * - * QProc - * - **********************************************************************/ -/* - The class QProcess does not necessarily map exactly to the running - child processes: if the process is finished, the QProcess class may still be - there; furthermore a user can use QProcess to start more than one process. - - The helper-class QProc has the semantics that one instance of this class maps - directly to a running child process. -*/ -class QProc -{ -public: - QProc( pid_t p, QProcess *proc=0 ) : pid(p), process(proc) - { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProc: Constructor for pid %d and QProcess %p", pid, process ); -#endif - socketStdin = 0; - socketStdout = 0; - socketStderr = 0; - } - ~QProc() - { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProc: Destructor for pid %d and QProcess %p", pid, process ); -#endif - if ( process != 0 ) { - if ( process->d->notifierStdin ) - process->d->notifierStdin->setEnabled( FALSE ); - if ( process->d->notifierStdout ) - process->d->notifierStdout->setEnabled( FALSE ); - if ( process->d->notifierStderr ) - process->d->notifierStderr->setEnabled( FALSE ); - process->d->proc = 0; - } - if( socketStdin != 0 ) - ::close( socketStdin ); - // ### close these sockets even on parent exit or is it better only on - // sigchld (but what do I have to do with them on exit then)? - if( socketStdout != 0 ) - ::close( socketStdout ); - if( socketStderr != 0 ) - ::close( socketStderr ); - } - - pid_t pid; - int socketStdin; - int socketStdout; - int socketStderr; - QProcess *process; -}; - -/*********************************************************************** - * - * QProcessManager - * - **********************************************************************/ -class QProcessManager : public QObject -{ - Q_OBJECT - -public: - QProcessManager(); - ~QProcessManager(); - - void append( QProc *p ); - void remove( QProc *p ); - - void cleanup(); - -public slots: - void removeMe(); - void sigchldHnd( int ); - -public: - struct sigaction oldactChld; - struct sigaction oldactPipe; - QList<QProc> *procList; - int sigchldFd[2]; -}; - -QCleanupHandler<QProcessManager> qprocess_cleanup_procmanager; - -QProcessManager::QProcessManager() -{ - procList = new QList<QProc>; - procList->setAutoDelete( TRUE ); - - // The SIGCHLD handler writes to a socket to tell the manager that - // something happened. This is done to get the processing in sync with the - // event reporting. - if ( ::socketpair( AF_UNIX, SOCK_STREAM, 0, sigchldFd ) ) { - sigchldFd[0] = 0; - sigchldFd[1] = 0; - } else { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager: install socket notifier (%d)", sigchldFd[1] ); -#endif - QSocketNotifier *sn = new QSocketNotifier( sigchldFd[1], - QSocketNotifier::Read, this ); - connect( sn, SIGNAL(activated(int)), - this, SLOT(sigchldHnd(int)) ); - sn->setEnabled( TRUE ); - } - - // install a SIGCHLD handler and ignore SIGPIPE - struct sigaction act; - -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager: install a SIGCHLD handler" ); -#endif - act.sa_handler = qt_C_sigchldHnd; - sigemptyset( &(act.sa_mask) ); - sigaddset( &(act.sa_mask), SIGCHLD ); - act.sa_flags = SA_NOCLDSTOP; -#if defined(SA_RESTART) - act.sa_flags |= SA_RESTART; -#endif - if ( sigaction( SIGCHLD, &act, &oldactChld ) != 0 ) - qWarning( "Error installing SIGCHLD handler" ); - -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager: install a SIGPIPE handler (SIG_IGN)" ); -#endif - act.sa_handler = QT_SIGNAL_IGNORE; - sigemptyset( &(act.sa_mask) ); - sigaddset( &(act.sa_mask), SIGPIPE ); - act.sa_flags = 0; - if ( sigaction( SIGPIPE, &act, &oldactPipe ) != 0 ) - qWarning( "Error installing SIGPIPE handler" ); -} - -QProcessManager::~QProcessManager() -{ - delete procList; - - if ( sigchldFd[0] != 0 ) - ::close( sigchldFd[0] ); - if ( sigchldFd[1] != 0 ) - ::close( sigchldFd[1] ); - - // restore SIGCHLD handler -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager: restore old sigchild handler" ); -#endif - if ( sigaction( SIGCHLD, &oldactChld, 0 ) != 0 ) - qWarning( "Error restoring SIGCHLD handler" ); - -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager: restore old sigpipe handler" ); -#endif - if ( sigaction( SIGPIPE, &oldactPipe, 0 ) != 0 ) - qWarning( "Error restoring SIGPIPE handler" ); -} - -void QProcessManager::append( QProc *p ) -{ - procList->append( p ); -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager: append process (procList.count(): %d)", procList->count() ); -#endif -} - -void QProcessManager::remove( QProc *p ) -{ - procList->remove( p ); -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager: remove process (procList.count(): %d)", procList->count() ); -#endif - cleanup(); -} - -void QProcessManager::cleanup() -{ - if ( procList->count() == 0 ) { - QTimer::singleShot( 0, this, SLOT(removeMe()) ); - } -} - -void QProcessManager::removeMe() -{ - if ( procList->count() == 0 ) { - qprocess_cleanup_procmanager.remove( &QProcessPrivate::procManager ); - QProcessPrivate::procManager = 0; - delete this; - } -} - -void QProcessManager::sigchldHnd( int fd ) -{ - char tmp; - ::read( fd, &tmp, sizeof(tmp) ); -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager::sigchldHnd()" ); -#endif - QProc *proc; - QProcess *process; - bool removeProc; - proc = procList->first(); - while ( proc != 0 ) { - removeProc = FALSE; - process = proc->process; - if ( process != 0 ) { - if ( !process->isRunning() ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager::sigchldHnd() (PID: %d): process exited (QProcess available)", proc->pid ); -#endif - // read pending data - int nbytes = 0; - if ( ::ioctl(proc->socketStdout, FIONREAD, (char*)&nbytes)==0 && nbytes>0 ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager::sigchldHnd() (PID: %d): reading %d bytes of pending data on stdout", proc->pid, nbytes ); -#endif - process->socketRead( proc->socketStdout ); - } - nbytes = 0; - if ( ::ioctl(proc->socketStderr, FIONREAD, (char*)&nbytes)==0 && nbytes>0 ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager::sigchldHnd() (PID: %d): reading %d bytes of pending data on stderr", proc->pid, nbytes ); -#endif - process->socketRead( proc->socketStderr ); - } - - if ( process->notifyOnExit ) - emit process->processExited(); - - removeProc = TRUE; - } - } else { - int status; - if ( ::waitpid( proc->pid, &status, WNOHANG ) == proc->pid ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessManager::sigchldHnd() (PID: %d): process exited (QProcess not available)", proc->pid ); -#endif - removeProc = TRUE; - } - } - if ( removeProc ) { - QProc *oldproc = proc; - proc = procList->next(); - remove( oldproc ); - } else { - proc = procList->next(); - } - } -} - -#include "qprocess_unix.moc" - - -/*********************************************************************** - * - * QProcessPrivate - * - **********************************************************************/ -QProcessManager *QProcessPrivate::procManager = 0; - -QProcessPrivate::QProcessPrivate() -{ -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessPrivate: Constructor" ); -#endif - stdinBufRead = 0; - - notifierStdin = 0; - notifierStdout = 0; - notifierStderr = 0; - - exitValuesCalculated = FALSE; - socketReadCalled = FALSE; - - proc = 0; -} - -QProcessPrivate::~QProcessPrivate() -{ -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcessPrivate: Destructor" ); -#endif - - if ( proc != 0 ) { - if ( proc->socketStdin != 0 ) { - ::close( proc->socketStdin ); - proc->socketStdin = 0; - } - proc->process = 0; - } - - while ( !stdinBuf.isEmpty() ) { - delete stdinBuf.dequeue(); - } - delete notifierStdin; - delete notifierStdout; - delete notifierStderr; -} - -/* - Closes all open sockets in the child process that are not needed by the child - process. Otherwise one child may have an open socket on standard input, etc. - of another child. -*/ -void QProcessPrivate::closeOpenSocketsForChild() -{ - if ( procManager != 0 ) { - if ( procManager->sigchldFd[0] != 0 ) - ::close( procManager->sigchldFd[0] ); - if ( procManager->sigchldFd[1] != 0 ) - ::close( procManager->sigchldFd[1] ); - - // close also the sockets from other QProcess instances - QProc *proc; - for ( proc=procManager->procList->first(); proc!=0; proc=procManager->procList->next() ) { - ::close( proc->socketStdin ); - ::close( proc->socketStdout ); - ::close( proc->socketStderr ); - } - } -} - -void QProcessPrivate::newProc( pid_t pid, QProcess *process ) -{ - proc = new QProc( pid, process ); - if ( procManager == 0 ) { - procManager = new QProcessManager; - qprocess_cleanup_procmanager.add( &procManager ); - } - // the QProcessManager takes care of deleting the QProc instances - procManager->append( proc ); -} - -/*********************************************************************** - * - * sigchld handler callback - * - **********************************************************************/ -QT_SIGNAL_RETTYPE qt_C_sigchldHnd( QT_SIGNAL_ARGS ) -{ - if ( QProcessPrivate::procManager == 0 ) - return; - if ( QProcessPrivate::procManager->sigchldFd[0] == 0 ) - return; - - char a = 1; - ::write( QProcessPrivate::procManager->sigchldFd[0], &a, sizeof(a) ); -} - - -/*********************************************************************** - * - * QProcess - * - **********************************************************************/ -/*! - This private class does basic initialization. -*/ -void QProcess::init() -{ - d = new QProcessPrivate(); - exitStat = 0; - exitNormal = FALSE; -} - -/*! - This private class resets the process variables, etc. so that it can be used - for another process to start. -*/ -void QProcess::reset() -{ - delete d; - d = new QProcessPrivate(); - exitStat = 0; - exitNormal = FALSE; - d->bufStdout.resize( 0 ); - d->bufStderr.resize( 0 ); -} - -QByteArray* QProcess::bufStdout() -{ - if ( d->proc && d->proc->socketStdout ) { - // ### can this cause a blocking behaviour (maybe do a ioctl() to see - // if data is available)? - socketRead( d->proc->socketStdout ); - } - return &d->bufStdout; -} - -QByteArray* QProcess::bufStderr() -{ - if ( d->proc && d->proc->socketStderr ) { - // ### can this cause a blocking behaviour (maybe do a ioctl() to see - // if data is available)? - socketRead( d->proc->socketStderr ); - } - return &d->bufStderr; -} - -void QProcess::consumeBufStdout( int consume ) -{ - uint n = d->bufStdout.size(); - if ( consume==-1 || (uint)consume >= n ) { - d->bufStdout.resize( 0 ); - } else { - QByteArray tmp( n - consume ); - memcpy( tmp.data(), d->bufStdout.data()+consume, n-consume ); - d->bufStdout = tmp; - } -} - -void QProcess::consumeBufStderr( int consume ) -{ - uint n = d->bufStderr.size(); - if ( consume==-1 || (uint)consume >= n ) { - d->bufStderr.resize( 0 ); - } else { - QByteArray tmp( n - consume ); - memcpy( tmp.data(), d->bufStderr.data()+consume, n-consume ); - d->bufStderr = tmp; - } -} - -/*! - Destroys the class. - - If the process is running, it is NOT terminated! Standard input, standard - output and standard error of the process are closed. - - You can connect the destroyed() signal to the kill() slot, if you want the - process to be terminated automatically when the class is destroyed. - - \sa tryTerminate() kill() -*/ -QProcess::~QProcess() -{ - delete d; -} - -/*! - Tries to run a process for the command and arguments that were specified with - setArguments(), addArgument() or that were specified in the constructor. The - command is searched in the path for executable programs; you can also use an - absolute path to the command. - - If \a env is null, then the process is started with the same environment as - the starting process. If \a env is non-null, then the values in the - stringlist are interpreted as environment setttings of the form \c - {key=value} and the process is started in these environment settings. For - convenience, there is a small exception to this rule: under Unix, if \a env - does not contain any settings for the environment variable \c - LD_LIBRARY_PATH, then this variable is inherited from the starting process; - under Windows the same applies for the enverionment varialbe \c PATH. - - Returns TRUE if the process could be started, otherwise FALSE. - - You can write data to standard input of the process with - writeToStdin(), you can close standard input with closeStdin() and you can - terminate the process tryTerminate() resp. kill(). - - You can call this function even when there already is a running - process in this object. In this case, QProcess closes standard input - of the old process and deletes pending data, i.e., you loose all - control over that process, but the process is not terminated. This applies - also if the process could not be started. (On operating systems that have - zombie processes, Qt will also wait() on the old process.) - - \sa launch() closeStdin() -*/ -bool QProcess::start( QStringList *env ) -{ -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::start()" ); -#endif - reset(); - - int sStdin[2]; - int sStdout[2]; - int sStderr[2]; - - // open sockets for piping - if ( (comms & Stdin) && ::socketpair( AF_UNIX, SOCK_STREAM, 0, sStdin ) == -1 ) { - return FALSE; - } - if ( (comms & Stderr) && ::socketpair( AF_UNIX, SOCK_STREAM, 0, sStderr ) == -1 ) { - return FALSE; - } - if ( (comms & Stdout) && ::socketpair( AF_UNIX, SOCK_STREAM, 0, sStdout ) == -1 ) { - return FALSE; - } - - // the following pipe is only used to determine if the process could be - // started - int fd[2]; - if ( pipe( fd ) < 0 ) { - // non critical error, go on - fd[0] = 0; - fd[1] = 0; - } - - // construct the arguments for exec - QCString *arglistQ = new QCString[ _arguments.count() + 1 ]; - const char** arglist = new const char*[ _arguments.count() + 1 ]; - int i = 0; - for ( QStringList::Iterator it = _arguments.begin(); it != _arguments.end(); ++it ) { - arglistQ[i] = (*it).local8Bit(); - arglist[i] = arglistQ[i]; -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::start(): arg %d = %s", i, arglist[i] ); -#endif - i++; - } - arglist[i] = 0; - - // Must make sure signal handlers are installed before exec'ing - // in case the process exits quickly. - if ( d->procManager == 0 ) { - d->procManager = new QProcessManager; - qprocess_cleanup_procmanager.add( &d->procManager ); - } - - // fork and exec - QApplication::flushX(); - pid_t pid = fork(); - if ( pid == 0 ) { - // child - d->closeOpenSocketsForChild(); - if ( comms & Stdin ) { - ::close( sStdin[1] ); - ::dup2( sStdin[0], STDIN_FILENO ); - } - if ( comms & Stdout ) { - ::close( sStdout[0] ); - ::dup2( sStdout[1], STDOUT_FILENO ); - } - if ( comms & Stderr ) { - ::close( sStderr[0] ); - ::dup2( sStderr[1], STDERR_FILENO ); - } - if ( comms & DupStderr ) { - ::dup2( STDOUT_FILENO, STDERR_FILENO ); - } -#ifndef QT_NO_DIR - ::chdir( workingDir.absPath().latin1() ); -#endif - if ( fd[0] ) - ::close( fd[0] ); - if ( fd[1] ) - ::fcntl( fd[1], F_SETFD, FD_CLOEXEC ); // close on exec shows sucess - - if ( env == 0 ) { // inherit environment and start process - ::execvp( arglist[0], (char*const*)arglist ); // ### cast not nice - } else { // start process with environment settins as specified in env - // construct the environment for exec - int numEntries = env->count(); - bool setLibraryPath = - env->grep( QRegExp( "^LD_LIBRARY_PATH=" ) ).isEmpty() && - getenv( "LD_LIBRARY_PATH" ) != 0; - if ( setLibraryPath ) - numEntries++; - QCString *envlistQ = new QCString[ numEntries + 1 ]; - const char** envlist = new const char*[ numEntries + 1 ]; - int i = 0; - if ( setLibraryPath ) { - envlistQ[i] = QString( "LD_LIBRARY_PATH=%1" ).arg( getenv( "LD_LIBRARY_PATH" ) ).local8Bit(); - envlist[i] = envlistQ[i]; - i++; - } - for ( QStringList::Iterator it = env->begin(); it != env->end(); ++it ) { - envlistQ[i] = (*it).local8Bit(); - envlist[i] = envlistQ[i]; - i++; - } - envlist[i] = 0; - - // look for the executable in the search path - if ( _arguments.count()>0 && getenv("PATH")!=0 ) { - QString command = _arguments[0]; - if ( !command.contains( '/' ) ) { - QStringList pathList = QStringList::split( ':', getenv( "PATH" ) ); - for (QStringList::Iterator it = pathList.begin(); it != pathList.end(); ++it ) { - QString dir = *it; -#ifdef Q_OS_MACX - if(QFile::exists(dir + "/" + command + ".app")) //look in a bundle - dir += "/" + command + ".app/Contents/MacOS"; -#endif -#ifndef QT_NO_DIR - QFileInfo fileInfo( dir, command ); -#else - QFileInfo fileInfo( dir + "/" + command ); -#endif - if ( fileInfo.isExecutable() ) { - arglistQ[0] = fileInfo.filePath().local8Bit(); - arglist[0] = arglistQ[0]; - break; - } - } - } - } - ::execve( arglist[0], (char*const*)arglist, (char*const*)envlist ); // ### casts not nice - } - if ( fd[1] ) { - char buf = 0; - ::write( fd[1], &buf, 1 ); - ::close( fd[1] ); - } - ::exit( -1 ); - } else if ( pid == -1 ) { - // error forking - goto error; - } - - // test if exec was successful - if ( fd[1] ) - ::close( fd[1] ); - if ( fd[0] ) { - char buf; - for ( ;; ) { - int n = ::read( fd[0], &buf, 1 ); - if ( n==1 ) { - // socket was not closed => error - d->proc = 0; - goto error; - } else if ( n==-1 ) { - if ( errno==EAGAIN || errno==EINTR ) - // try it again - continue; - } - break; - } - ::close( fd[0] ); - } - - d->newProc( pid, this ); - - if ( comms & Stdin ) { - ::close( sStdin[0] ); - d->proc->socketStdin = sStdin[1]; - d->notifierStdin = new QSocketNotifier( sStdin[1], QSocketNotifier::Write ); - connect( d->notifierStdin, SIGNAL(activated(int)), - this, SLOT(socketWrite(int)) ); - // setup notifiers for the sockets - if ( !d->stdinBuf.isEmpty() ) { - d->notifierStdin->setEnabled( TRUE ); - } - } - if ( comms & Stdout ) { - ::close( sStdout[1] ); - d->proc->socketStdout = sStdout[0]; - d->notifierStdout = new QSocketNotifier( sStdout[0], QSocketNotifier::Read ); - connect( d->notifierStdout, SIGNAL(activated(int)), - this, SLOT(socketRead(int)) ); - if ( ioRedirection ) - d->notifierStdout->setEnabled( TRUE ); - } - if ( comms & Stderr ) { - ::close( sStderr[1] ); - d->proc->socketStderr = sStderr[0]; - d->notifierStderr = new QSocketNotifier( sStderr[0], QSocketNotifier::Read ); - connect( d->notifierStderr, SIGNAL(activated(int)), - this, SLOT(socketRead(int)) ); - if ( ioRedirection ) - d->notifierStderr->setEnabled( TRUE ); - } - - // cleanup and return - delete[] arglistQ; - delete[] arglist; - return TRUE; - -error: -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::start(): error starting process" ); -#endif - if ( d->procManager ) - d->procManager->cleanup(); - if ( comms & Stdin ) { - ::close( sStdin[1] ); - ::close( sStdin[0] ); - } - if ( comms & Stdout ) { - ::close( sStdout[0] ); - ::close( sStdout[1] ); - } - if ( comms & Stderr ) { - ::close( sStderr[0] ); - ::close( sStderr[1] ); - } - ::close( fd[0] ); - ::close( fd[1] ); - delete[] arglistQ; - delete[] arglist; - return FALSE; -} - - -/*! - Asks the process to terminate. Processes can ignore this wish. If you want to - be sure that the process really terminates, you must use kill() instead. - - The slot returns immediately: it does not wait until the process has - finished. When the process really exited, the signal processExited() is - emitted. - - \sa kill() processExited() -*/ -void QProcess::tryTerminate() const -{ - if ( d->proc != 0 ) - ::kill( d->proc->pid, SIGTERM ); -} - -/*! - Terminates the process. This is not a safe way to end a process since the - process will not be able to do cleanup. tryTerminate() is a safer way to do - it, but processes might ignore a tryTerminate(). - - The nice way to end a process and to be sure that it is finished, is doing - something like this: - \code - process->tryTerminate(); - QTimer::singleShot( 5000, process, SLOT( kill() ) ); - \endcode - - This tries to terminate the process the nice way. If the process is still - running after 5 seconds, it terminates the process the hard way. The timeout - should be chosen depending on the time the process needs to do all the - cleanup: use a higher value if the process is likely to do heavy computation - on cleanup. - - The slot returns immediately: it does not wait until the process has - finished. When the process really exited, the signal processExited() is - emitted. - - \sa tryTerminate() processExited() -*/ -void QProcess::kill() const -{ - if ( d->proc != 0 ) - ::kill( d->proc->pid, SIGKILL ); -} - -/*! - Returns TRUE if the process is running, otherwise FALSE. - - \sa normalExit() exitStatus() processExited() -*/ -bool QProcess::isRunning() const -{ - if ( d->exitValuesCalculated ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::isRunning(): FALSE (already computed)" ); -#endif - return FALSE; - } - if ( d->proc == 0 ) - return FALSE; - int status; - if ( ::waitpid( d->proc->pid, &status, WNOHANG ) == d->proc->pid ) - { - // compute the exit values - QProcess *that = (QProcess*)this; // mutable - that->exitNormal = WIFEXITED( status ) != 0; - if ( exitNormal ) { - that->exitStat = (char)WEXITSTATUS( status ); - } - d->exitValuesCalculated = TRUE; -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::isRunning() (PID: %d): FALSE", d->proc->pid ); -#endif - return FALSE; - } -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::isRunning() (PID: %d): TRUE", d->proc->pid ); -#endif - return TRUE; -} - -/*! - Writes the data \a buf to the standard input of the process. The process may - or may not read this data. - - This function returns immediately; the QProcess class might write the data at - a later point (you have to enter the event loop for that). When all the data - is written to the process, the signal wroteToStdin() is emitted. This does - not mean that the process really read the data, since this class only detects - when it was able to write the data to the operating system. - - \sa wroteToStdin() closeStdin() readStdout() readStderr() -*/ -void QProcess::writeToStdin( const QByteArray& buf ) -{ -#if defined(QT_QPROCESS_DEBUG) -// qDebug( "QProcess::writeToStdin(): write to stdin (%d)", d->socketStdin ); -#endif - d->stdinBuf.enqueue( new QByteArray(buf) ); - if ( d->notifierStdin != 0 ) - d->notifierStdin->setEnabled( TRUE ); -} - - -/*! - Closes standard input of the process. - - This function also deletes pending data that is not written to standard input - yet. - - \sa wroteToStdin() -*/ -void QProcess::closeStdin() -{ - if ( d->proc == 0 ) - return; - if ( d->proc->socketStdin !=0 ) { - while ( !d->stdinBuf.isEmpty() ) { - delete d->stdinBuf.dequeue(); - } - delete d->notifierStdin; - d->notifierStdin = 0; - if ( ::close( d->proc->socketStdin ) != 0 ) { - qWarning( "Could not close stdin of child process" ); - } -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::closeStdin(): stdin (%d) closed", d->proc->socketStdin ); -#endif - d->proc->socketStdin = 0; - } -} - - -/* - This private slot is called when the process has outputted data to either - standard output or standard error. -*/ -void QProcess::socketRead( int fd ) -{ - if ( d->socketReadCalled ) { - // the slots that are connected to the readyRead...() signals might - // trigger a recursive call of socketRead(). Avoid this since you get a - // blocking read otherwise. - return; - } -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::socketRead(): %d", fd ); -#endif - if ( fd == 0 ) - return; - const int bufsize = 4096; - QByteArray *buffer = 0; - uint oldSize; - int n; - if ( fd == d->proc->socketStdout ) { - buffer = &d->bufStdout; - } else if ( fd == d->proc->socketStderr ) { - buffer = &d->bufStderr; - } else { - // this case should never happen, but just to be safe - return; - } - - // read data - oldSize = buffer->size(); - buffer->resize( oldSize + bufsize ); - n = ::read( fd, buffer->data()+oldSize, bufsize ); - if ( n > 0 ) - buffer->resize( oldSize + n ); - else - buffer->resize( oldSize ); - // eof or error? - if ( n == 0 || n == -1 ) { - if ( fd == d->proc->socketStdout ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::socketRead(): stdout (%d) closed", fd ); -#endif - d->notifierStdout->setEnabled( FALSE ); - delete d->notifierStdout; - d->notifierStdout = 0; - ::close( d->proc->socketStdout ); - d->proc->socketStdout = 0; - return; - } else if ( fd == d->proc->socketStderr ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::socketRead(): stderr (%d) closed", fd ); -#endif - d->notifierStderr->setEnabled( FALSE ); - delete d->notifierStderr; - d->notifierStderr = 0; - ::close( d->proc->socketStderr ); - d->proc->socketStderr = 0; - return; - } - } - // read all data that is available - while ( n == bufsize ) { - oldSize = buffer->size(); - buffer->resize( oldSize + bufsize ); - n = ::read( fd, buffer->data()+oldSize, bufsize ); - if ( n > 0 ) - buffer->resize( oldSize + n ); - else - buffer->resize( oldSize ); - } - - d->socketReadCalled = TRUE; - if ( fd == d->proc->socketStdout ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::socketRead(): %d bytes read from stdout (%d)", - buffer->size()-oldSize, fd ); -#endif - emit readyReadStdout(); - } else if ( fd == d->proc->socketStderr ) { -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::socketRead(): %d bytes read from stderr (%d)", - buffer->size()-oldSize, fd ); -#endif - emit readyReadStderr(); - } - d->socketReadCalled = FALSE; -} - - -/* - This private slot is called when the process tries to read data from standard - input. -*/ -void QProcess::socketWrite( int fd ) -{ - if ( fd != d->proc->socketStdin || d->proc->socketStdin == 0 ) - return; - if ( d->stdinBuf.isEmpty() ) { - d->notifierStdin->setEnabled( FALSE ); - return; - } -#if defined(QT_QPROCESS_DEBUG) - qDebug( "QProcess::socketWrite(): write to stdin (%d)", fd ); -#endif - ssize_t ret = ::write( fd, - d->stdinBuf.head()->data() + d->stdinBufRead, - d->stdinBuf.head()->size() - d->stdinBufRead ); - if ( ret > 0 ) - d->stdinBufRead += ret; - if ( d->stdinBufRead == (ssize_t)d->stdinBuf.head()->size() ) { - d->stdinBufRead = 0; - delete d->stdinBuf.dequeue(); - if ( wroteToStdinConnected && d->stdinBuf.isEmpty() ) - emit wroteToStdin(); - socketWrite( fd ); - } -} - -/*! - \internal - Flushes standard input. This is useful if you want to use QProcess in a - synchronous manner. - - This function should probably go into the public API. -*/ -void QProcess::flushStdin() -{ - socketWrite( d->proc->socketStdin ); -} - -/* - This private slot is only used under Windows (but moc does not know about #if - defined()). -*/ -void QProcess::timeout() -{ -} - - -/* - This private function is used by connectNotify() and disconnectNotify() to - change the value of ioRedirection (and related behaviour) -*/ -void QProcess::setIoRedirection( bool value ) -{ - ioRedirection = value; - if ( ioRedirection ) { - if ( d->notifierStdout ) - d->notifierStdout->setEnabled( TRUE ); - if ( d->notifierStderr ) - d->notifierStderr->setEnabled( TRUE ); - } else { - if ( d->notifierStdout ) - d->notifierStdout->setEnabled( FALSE ); - if ( d->notifierStderr ) - d->notifierStderr->setEnabled( FALSE ); - } -} - -/* - This private function is used by connectNotify() and - disconnectNotify() to change the value of notifyOnExit (and related - behaviour) -*/ -void QProcess::setNotifyOnExit( bool value ) -{ - notifyOnExit = value; -} - -/* - This private function is used by connectNotify() and disconnectNotify() to - change the value of wroteToStdinConnected (and related behaviour) -*/ -void QProcess::setWroteStdinConnected( bool value ) -{ - wroteToStdinConnected = value; -} - -/*! \enum QProcess::PID - \internal -*/ -/*! - Returns platform dependent information about the process. This can be used - together with platform specific system calls. - - Under Unix the return value is the PID of the process, or -1 if no process is - belonging to this object. - - Under Windows it is a pointer to the \c PROCESS_INFORMATION struct, or 0 if - no process is belonging to this object. -*/ -QProcess::PID QProcess::processIdentifier() -{ - if ( d->proc == 0 ) - return -1; - return d->proc->pid; -} - -#endif // QT_NO_PROCESS diff --git a/core/launcher/transferserver.cpp b/core/launcher/transferserver.cpp index cbda247..0337a94 100644 --- a/core/launcher/transferserver.cpp +++ b/core/launcher/transferserver.cpp @@ -1,1389 +1,1424 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #define _XOPEN_SOURCE #include <pwd.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <shadow.h> /* we need the _OS_LINUX stuff first ! */ #include <qglobal.h> #ifndef _OS_LINUX_ -extern "C" { +extern "C" +{ #include <uuid/uuid.h> #define UUID_H_INCLUDED } #endif // not defined linux #if defined(_OS_LINUX_) #include <shadow.h> #endif #include <qdir.h> #include <qfile.h> #include <qtextstream.h> #include <qdatastream.h> #include <qmessagebox.h> #include <qstringlist.h> #include <qfileinfo.h> -#include <qregexp.h> +#include <qregexp.h> //#include <qpe/qcopchannel_qws.h> #include <qpe/process.h> #include <qpe/global.h> #include <qpe/config.h> #include <qpe/contact.h> #include <qpe/quuid.h> #include <qpe/version.h> #include <qpe/qcopenvelope_qws.h> #include "transferserver.h" -#include "qprocess.h" +#include <opie/oprocess.h> const int block_size = 51200; TransferServer::TransferServer( Q_UINT16 port, QObject *parent , - const char* name ) - : QServerSocket( port, 1, parent, name ) + const char* name ) + : QServerSocket( port, 1, parent, name ) { - if ( !ok() ) - qWarning( "Failed to bind to port %d", port ); + if ( !ok() ) + qWarning( "Failed to bind to port %d", port ); } TransferServer::~TransferServer() { - } void TransferServer::newConnection( int socket ) { - (void) new ServerPI( socket, this ); + (void) new ServerPI( socket, this ); } /* * small class in anonymous namespace * to generate a QUUid for us */ -namespace { - struct UidGen { - QString uuid(); - }; +namespace +{ +struct UidGen +{ + QString uuid(); +}; #if !defined(_OS_LINUX_) - QString UidGen::uuid() { - uuid_t uuid; - uuid_generate( uuid ); - return QUUid( uuid ).toString(); - } + +QString UidGen::uuid() +{ + uuid_t uuid; + uuid_generate( uuid ); + return QUUid( uuid ).toString(); +} #else - /* - * linux got a /proc/sys/kernel/random/uuid file - * it'll generate the uuids for us - */ - QString UidGen::uuid() { - QFile file( "/proc/sys/kernel/random/uuid" ); - if (!file.open(IO_ReadOnly ) ) - return QString::null; - - QTextStream stream(&file); - - return "{" + stream.read().stripWhiteSpace() + "}"; - } +/* +* linux got a /proc/sys/kernel/random/uuid file +* it'll generate the uuids for us +*/ +QString UidGen::uuid() +{ + QFile file( "/proc/sys/kernel/random/uuid" ); + if (!file.open(IO_ReadOnly ) ) + return QString::null; + + QTextStream stream(&file); + + return "{" + stream.read().stripWhiteSpace() + "}"; +} #endif } QString SyncAuthentication::serverId() { - Config cfg("Security"); - cfg.setGroup("Sync"); - QString r=cfg.readEntry("serverid"); - if ( r.isEmpty() ) { - UidGen gen; - r = gen.uuid(); - cfg.writeEntry("serverid", r ); - } - return r; + Config cfg("Security"); + cfg.setGroup("Sync"); + QString r = cfg.readEntry("serverid"); + if ( r.isEmpty() ) { + UidGen gen; + r = gen.uuid(); + cfg.writeEntry("serverid", r ); + } + return r; } QString SyncAuthentication::ownerName() { - QString vfilename = Global::applicationFileName("addressbook", - "businesscard.vcf"); - if (QFile::exists(vfilename)) { - Contact c; - c = Contact::readVCard( vfilename )[0]; - return c.fullName(); - } - - return ""; + QString vfilename = Global::applicationFileName("addressbook", + "businesscard.vcf"); + if (QFile::exists(vfilename)) { + Contact c; + c = Contact::readVCard( vfilename )[0]; + return c.fullName(); + } + + return ""; } QString SyncAuthentication::loginName() { - struct passwd *pw; - pw = getpwuid( geteuid() ); - return QString::fromLocal8Bit( pw->pw_name ); + struct passwd *pw; + pw = getpwuid( geteuid() ); + return QString::fromLocal8Bit( pw->pw_name ); } int SyncAuthentication::isAuthorized(QHostAddress peeraddress) { - Config cfg("Security"); - cfg.setGroup("Sync"); -// QString allowedstr = cfg.readEntry("auth_peer","192.168.1.0"); - uint auth_peer = cfg.readNumEntry("auth_peer",0xc0a80100); - -// QHostAddress allowed; -// allowed.setAddress(allowedstr); -// uint auth_peer = allowed.ip4Addr(); - uint auth_peer_bits = cfg.readNumEntry("auth_peer_bits",24); - uint mask = auth_peer_bits >= 32 // shifting by 32 is not defined - ? 0xffffffff : (((1<<auth_peer_bits)-1)<<(32-auth_peer_bits)); - return (peeraddress.ip4Addr() & mask) == auth_peer; + Config cfg("Security"); + cfg.setGroup("Sync"); + // QString allowedstr = cfg.readEntry("auth_peer","192.168.1.0"); + uint auth_peer = cfg.readNumEntry("auth_peer", 0xc0a80100); + + // QHostAddress allowed; + // allowed.setAddress(allowedstr); + // uint auth_peer = allowed.ip4Addr(); + uint auth_peer_bits = cfg.readNumEntry("auth_peer_bits", 24); + uint mask = auth_peer_bits >= 32 // shifting by 32 is not defined + ? 0xffffffff : (((1 << auth_peer_bits) - 1) << (32 - auth_peer_bits)); + return (peeraddress.ip4Addr() & mask) == auth_peer; } bool SyncAuthentication::checkUser( const QString& user ) { - if ( user.isEmpty() ) return FALSE; - QString euser = loginName(); - return user == euser; + if ( user.isEmpty() ) + return FALSE; + QString euser = loginName(); + return user == euser; } bool SyncAuthentication::checkPassword( const QString& password ) { #ifdef ALLOW_UNIX_USER_FTP - // First, check system password... + // First, check system password... - struct passwd *pw = 0; - struct spwd *spw = 0; + struct passwd *pw = 0; + struct spwd *spw = 0; - pw = getpwuid( geteuid() ); - spw = getspnam( pw->pw_name ); + pw = getpwuid( geteuid() ); + spw = getspnam( pw->pw_name ); - QString cpwd = QString::fromLocal8Bit( pw->pw_passwd ); - if ( cpwd == "x" && spw ) - cpwd = QString::fromLocal8Bit( spw->sp_pwdp ); + QString cpwd = QString::fromLocal8Bit( pw->pw_passwd ); + if ( cpwd == "x" && spw ) + cpwd = QString::fromLocal8Bit( spw->sp_pwdp ); - // Note: some systems use more than crypt for passwords. - QString cpassword = QString::fromLocal8Bit( crypt( password.local8Bit(), cpwd.local8Bit() ) ); - if ( cpwd == cpassword ) - return TRUE; + // Note: some systems use more than crypt for passwords. + QString cpassword = QString::fromLocal8Bit( crypt( password.local8Bit(), cpwd.local8Bit() ) ); + if ( cpwd == cpassword ) + return TRUE; #endif - static int lastdenial=0; - static int denials=0; - int now = time(0); - - // Detect old Qtopia Desktop (no password) - if ( password.isEmpty() ) { - if ( denials < 1 || now > lastdenial+600 ) { - QMessageBox::warning( 0,tr("Sync Connection"), - tr("<p>An unauthorized system is requesting access to this device." - "<p>If you are using a version of Qtopia Desktop older than 1.5.1, " - "please upgrade."), - tr("Deny") ); - denials++; - lastdenial=now; - } - return FALSE; - } - - // Second, check sync password... - QString pass = password.left(6); - /* old QtopiaDesktops are sending - * rootme newer versions got a Qtopia - * prefixed. Qtopia prefix will suceed - * until the sync software syncs up - * FIXME - */ - if ( pass == "rootme" || pass == "Qtopia") { - - QString cpassword = QString::fromLocal8Bit( crypt( password.mid(8).local8Bit(), "qp" ) ); - Config cfg("Security"); - cfg.setGroup("Sync"); - QString pwds = cfg.readEntry("Passwords"); - if ( QStringList::split(QChar(' '),pwds).contains(cpassword) ) - return TRUE; - - // Unrecognized system. Be careful... - - if ( (denials > 2 && now < lastdenial+600) - || QMessageBox::warning(0,tr("Sync Connection"), - tr("<p>An unrecognized system is requesting access to this device." - "<p>If you have just initiated a Sync for the first time, this is normal."), - tr("Allow"),tr("Deny"), 0, 1, 1 ) ==1 ) - { - denials++; - lastdenial=now; - return FALSE; - } else { - denials=0; - cfg.writeEntry("Passwords",pwds+" "+cpassword); - return TRUE; - } - } - - return FALSE; + static int lastdenial = 0; + static int denials = 0; + int now = time(0); + + // Detect old Qtopia Desktop (no password) + if ( password.isEmpty() ) { + if ( denials < 1 || now > lastdenial + 600 ) { + QMessageBox::warning( 0, tr("Sync Connection"), + tr("<p>An unauthorized system is requesting access to this device." + "<p>If you are using a version of Qtopia Desktop older than 1.5.1, " + "please upgrade."), + tr("Deny") ); + denials++; + lastdenial = now; + } + return FALSE; + } + + // Second, check sync password... + QString pass = password.left(6); + /* old QtopiaDesktops are sending + * rootme newer versions got a Qtopia + * prefixed. Qtopia prefix will suceed + * until the sync software syncs up + * FIXME + */ + if ( pass == "rootme" || pass == "Qtopia") { + + QString cpassword = QString::fromLocal8Bit( crypt( password.mid(8).local8Bit(), "qp" ) ); + Config cfg("Security"); + cfg.setGroup("Sync"); + QString pwds = cfg.readEntry("Passwords"); + if ( QStringList::split(QChar(' '), pwds).contains(cpassword) ) + return TRUE; + + // Unrecognized system. Be careful... + + if ( (denials > 2 && now < lastdenial + 600) + || QMessageBox::warning(0, tr("Sync Connection"), + tr("<p>An unrecognized system is requesting access to this device." + "<p>If you have just initiated a Sync for the first time, this is normal."), + tr("Allow"), tr("Deny"), 0, 1, 1 ) == 1 ) { + denials++; + lastdenial = now; + return FALSE; + } + else { + denials = 0; + cfg.writeEntry("Passwords", pwds + " " + cpassword); + return TRUE; + } + } + + return FALSE; } -ServerPI::ServerPI( int socket, QObject *parent , const char* name ) - : QSocket( parent, name ) , dtp( 0 ), serversocket( 0 ), waitsocket( 0 ) +ServerPI::ServerPI( int socket, QObject *parent , const char* name ) + : QSocket( parent, name ) , dtp( 0 ), serversocket( 0 ), waitsocket( 0 ) { - state = Connected; + state = Connected; - setSocket( socket ); + setSocket( socket ); - peerport = peerPort(); - peeraddress = peerAddress(); + peerport = peerPort(); + peeraddress = peerAddress(); #ifndef INSECURE - if ( !SyncAuthentication::isAuthorized(peeraddress) ) { - state = Forbidden; - startTimer( 0 ); - } else + + if ( !SyncAuthentication::isAuthorized(peeraddress) ) { + state = Forbidden; + startTimer( 0 ); + } + else #endif - { - connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); - connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); + { + connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); + connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); - passiv = FALSE; - for( int i = 0; i < 4; i++ ) - wait[i] = FALSE; + passiv = FALSE; + for ( int i = 0; i < 4; i++ ) + wait[i] = FALSE; - send( "220 Qtopia " QPE_VERSION " FTP Server" ); - state = Wait_USER; + send( "220 Qtopia " QPE_VERSION " FTP Server" ); + state = Wait_USER; - dtp = new ServerDTP( this ); - connect( dtp, SIGNAL( completed() ), SLOT( dtpCompleted() ) ); - connect( dtp, SIGNAL( failed() ), SLOT( dtpFailed() ) ); - connect( dtp, SIGNAL( error( int ) ), SLOT( dtpError( int ) ) ); + dtp = new ServerDTP( this ); + connect( dtp, SIGNAL( completed() ), SLOT( dtpCompleted() ) ); + connect( dtp, SIGNAL( failed() ), SLOT( dtpFailed() ) ); + connect( dtp, SIGNAL( error( int ) ), SLOT( dtpError( int ) ) ); - directory = QDir::currentDirPath(); + directory = QDir::currentDirPath(); - static int p = 1024; + static int p = 1024; - while ( !serversocket || !serversocket->ok() ) { - delete serversocket; - serversocket = new ServerSocket( ++p, this ); - } - connect( serversocket, SIGNAL( newIncomming( int ) ), - SLOT( newConnection( int ) ) ); - } + while ( !serversocket || !serversocket->ok() ) { + delete serversocket; + serversocket = new ServerSocket( ++p, this ); + } + connect( serversocket, SIGNAL( newIncomming( int ) ), + SLOT( newConnection( int ) ) ); + } } ServerPI::~ServerPI() { - } void ServerPI::connectionClosed() { - // qDebug( "Debug: Connection closed" ); - delete this; + // qDebug( "Debug: Connection closed" ); + delete this; } void ServerPI::send( const QString& msg ) { - QTextStream os( this ); - os << msg << endl; - //qDebug( "Reply: %s", msg.latin1() ); + QTextStream os( this ); + os << msg << endl; + //qDebug( "Reply: %s", msg.latin1() ); } void ServerPI::read() { - while ( canReadLine() ) - process( readLine().stripWhiteSpace() ); + while ( canReadLine() ) + process( readLine().stripWhiteSpace() ); } bool ServerPI::checkReadFile( const QString& file ) { - QString filename; + QString filename; - if ( file[0] != "/" ) - filename = directory.path() + "/" + file; - else - filename = file; + if ( file[0] != "/" ) + filename = directory.path() + "/" + file; + else + filename = file; - QFileInfo fi( filename ); - return ( fi.exists() && fi.isReadable() ); + QFileInfo fi( filename ); + return ( fi.exists() && fi.isReadable() ); } bool ServerPI::checkWriteFile( const QString& file ) { - QString filename; + QString filename; - if ( file[0] != "/" ) - filename = directory.path() + "/" + file; - else - filename = file; + if ( file[0] != "/" ) + filename = directory.path() + "/" + file; + else + filename = file; - QFileInfo fi( filename ); + QFileInfo fi( filename ); - if ( fi.exists() ) - if ( !QFile( filename ).remove() ) - return FALSE; - return TRUE; + if ( fi.exists() ) + if ( !QFile( filename ).remove() ) + return FALSE; + return TRUE; } void ServerPI::process( const QString& message ) { - //qDebug( "Command: %s", message.latin1() ); - - // split message using "," as separator - QStringList msg = QStringList::split( " ", message ); - if ( msg.isEmpty() ) return; - - // command token - QString cmd = msg[0].upper(); - - // argument token - QString arg; - if ( msg.count() >= 2 ) - arg = msg[1]; - - // full argument string - QString args; - if ( msg.count() >= 2 ) { - QStringList copy( msg ); - // FIXME: for Qt3 - // copy.pop_front() - copy.remove( copy.begin() ); - args = copy.join( " " ); - } - - //qDebug( "args: %s", args.latin1() ); - - // we always respond to QUIT, regardless of state - if ( cmd == "QUIT" ) { - send( "211 Good bye!" ); - delete this; - return; - } - - // connected to client - if ( Connected == state ) - return; - - // waiting for user name - if ( Wait_USER == state ) { - - if ( cmd != "USER" || msg.count() < 2 || !SyncAuthentication::checkUser( arg ) ) { - send( "530 Please login with USER and PASS" ); - return; - } - send( "331 User name ok, need password" ); - state = Wait_PASS; - return; - } - - // waiting for password - if ( Wait_PASS == state ) { - - if ( cmd != "PASS" || !SyncAuthentication::checkPassword( arg ) ) { - send( "530 Please login with USER and PASS" ); - return; - } - send( "230 User logged in, proceed" ); - state = Ready; - return; - } - - // ACCESS CONTROL COMMANDS - - - // account (ACCT) - if ( cmd == "ACCT" ) { - // even wu-ftp does not support it - send( "502 Command not implemented" ); - } - - // change working directory (CWD) - else if ( cmd == "CWD" ) { - - if ( !args.isEmpty() ) { - if ( directory.cd( args, TRUE ) ) - send( "250 Requested file action okay, completed" ); - else - send( "550 Requested action not taken" ); - } - else - send( "500 Syntax error, command unrecognized" ); - } - - // change to parent directory (CDUP) - else if ( cmd == "CDUP" ) { - if ( directory.cdUp() ) - send( "250 Requested file action okay, completed" ); - else - send( "550 Requested action not taken" ); - } - - // structure mount (SMNT) - else if ( cmd == "SMNT" ) { - // even wu-ftp does not support it - send( "502 Command not implemented" ); - } - - // reinitialize (REIN) - else if ( cmd == "REIN" ) { - // even wu-ftp does not support it - send( "502 Command not implemented" ); - } - - - // TRANSFER PARAMETER COMMANDS - - - // data port (PORT) - else if ( cmd == "PORT" ) { - if ( parsePort( arg ) ) - send( "200 Command okay" ); - else - send( "500 Syntax error, command unrecognized" ); - } - - // passive (PASV) - else if ( cmd == "PASV" ) { - passiv = TRUE; - send( "227 Entering Passive Mode (" - + address().toString().replace( QRegExp( "\\." ), "," ) + "," - + QString::number( ( serversocket->port() ) >> 8 ) + "," - + QString::number( ( serversocket->port() ) & 0xFF ) +")" ); - } - - // representation type (TYPE) - else if ( cmd == "TYPE" ) { - if ( arg.upper() == "A" || arg.upper() == "I" ) - send( "200 Command okay" ); - else - send( "504 Command not implemented for that parameter" ); - } - - // file structure (STRU) - else if ( cmd == "STRU" ) { - if ( arg.upper() == "F" ) - send( "200 Command okay" ); - else - send( "504 Command not implemented for that parameter" ); - } - - // transfer mode (MODE) - else if ( cmd == "MODE" ) { - if ( arg.upper() == "S" ) - send( "200 Command okay" ); - else - send( "504 Command not implemented for that parameter" ); - } - - - // FTP SERVICE COMMANDS - - - // retrieve (RETR) - else if ( cmd == "RETR" ) - if ( !args.isEmpty() && checkReadFile( absFilePath( args ) ) - || backupRestoreGzip( absFilePath( args ) ) ) { - send( "150 File status okay" ); - sendFile( absFilePath( args ) ); - } - else { - qDebug("550 Requested action not taken"); - send( "550 Requested action not taken" ); - } - - // store (STOR) - else if ( cmd == "STOR" ) - if ( !args.isEmpty() && checkWriteFile( absFilePath( args ) ) ) { - send( "150 File status okay" ); - retrieveFile( absFilePath( args ) ); - } - else - send( "550 Requested action not taken" ); - - // store unique (STOU) - else if ( cmd == "STOU" ) { - send( "502 Command not implemented" ); - } - - // append (APPE) - else if ( cmd == "APPE" ) { - send( "502 Command not implemented" ); - } - - // allocate (ALLO) - else if ( cmd == "ALLO" ) { - send( "200 Command okay" ); - } - - // restart (REST) - else if ( cmd == "REST" ) { - send( "502 Command not implemented" ); - } - - // rename from (RNFR) - else if ( cmd == "RNFR" ) { - renameFrom = QString::null; - if ( args.isEmpty() ) - send( "500 Syntax error, command unrecognized" ); - else { - QFile file( absFilePath( args ) ); - if ( file.exists() ) { - send( "350 File exists, ready for destination name" ); - renameFrom = absFilePath( args ); - } - else - send( "550 Requested action not taken" ); - } - } - - // rename to (RNTO) - else if ( cmd == "RNTO" ) { - if ( lastCommand != "RNFR" ) - send( "503 Bad sequence of commands" ); - else if ( args.isEmpty() ) - send( "500 Syntax error, command unrecognized" ); - else { - QDir dir( absFilePath( args ) ); - if ( dir.rename( renameFrom, absFilePath( args ), TRUE ) ) - send( "250 Requested file action okay, completed." ); - else - send( "550 Requested action not taken" ); - } - } - - // abort (ABOR) - else if ( cmd.contains( "ABOR" ) ) { - dtp->close(); - if ( dtp->dtpMode() != ServerDTP::Idle ) - send( "426 Connection closed; transfer aborted" ); - else - send( "226 Closing data connection" ); - } - - // delete (DELE) - else if ( cmd == "DELE" ) { - if ( args.isEmpty() ) - send( "500 Syntax error, command unrecognized" ); - else { - QFile file( absFilePath( args ) ) ; - if ( file.remove() ) { - send( "250 Requested file action okay, completed" ); - QCopEnvelope e("QPE/System", "linkChanged(QString)" ); - e << file.name(); - } else { - send( "550 Requested action not taken" ); - } - } - } - - // remove directory (RMD) - else if ( cmd == "RMD" ) { - if ( args.isEmpty() ) - send( "500 Syntax error, command unrecognized" ); - else { - QDir dir; - if ( dir.rmdir( absFilePath( args ), TRUE ) ) - send( "250 Requested file action okay, completed" ); - else - send( "550 Requested action not taken" ); - } - } - - // make directory (MKD) - else if ( cmd == "MKD" ) { - if ( args.isEmpty() ) { - qDebug(" Error: no arg"); - send( "500 Syntax error, command unrecognized" ); - } - else { - QDir dir; - if ( dir.mkdir( absFilePath( args ), TRUE ) ) - send( "250 Requested file action okay, completed." ); - else - send( "550 Requested action not taken" ); - } - } - - // print working directory (PWD) - else if ( cmd == "PWD" ) { - send( "257 \"" + directory.path() +"\"" ); - } - - // list (LIST) - else if ( cmd == "LIST" ) { - if ( sendList( absFilePath( args ) ) ) - send( "150 File status okay" ); - else - send( "500 Syntax error, command unrecognized" ); - } - - // size (SIZE) - else if ( cmd == "SIZE" ) { - QString filePath = absFilePath( args ); - QFileInfo fi( filePath ); - bool gzipfile = backupRestoreGzip( filePath ); - if ( !fi.exists() && !gzipfile ) - send( "500 Syntax error, command unrecognized" ); - else { - if ( !gzipfile ) - send( "213 " + QString::number( fi.size() ) ); - else { - Process duproc( QString("du") ); - duproc.addArgument("-s"); - QString in, out; - if ( !duproc.exec(in, out) ) { - qDebug("du process failed; just sending back 1K"); - send( "213 1024"); - } - else { - QString size = out.left( out.find("\t") ); - int guess = size.toInt()/5; - if ( filePath.contains("doc") ) - guess *= 1000; - qDebug("sending back gzip guess of %d", guess); - send( "213 " + QString::number(guess) ); - } - } - } - } - // name list (NLST) - else if ( cmd == "NLST" ) { - send( "502 Command not implemented" ); - } - - // site parameters (SITE) - else if ( cmd == "SITE" ) { - send( "502 Command not implemented" ); - } - - // system (SYST) - else if ( cmd == "SYST" ) { - send( "215 UNIX Type: L8" ); - } - - // status (STAT) - else if ( cmd == "STAT" ) { - send( "502 Command not implemented" ); - } - - // help (HELP ) - else if ( cmd == "HELP" ) { - send( "502 Command not implemented" ); - } - - // noop (NOOP) - else if ( cmd == "NOOP" ) { - send( "200 Command okay" ); - } - - // not implemented - else - send( "502 Command not implemented" ); - - lastCommand = cmd; + //qDebug( "Command: %s", message.latin1() ); + + // split message using "," as separator + QStringList msg = QStringList::split( " ", message ); + if ( msg.isEmpty() ) + return ; + + // command token + QString cmd = msg[0].upper(); + + // argument token + QString arg; + if ( msg.count() >= 2 ) + arg = msg[1]; + + // full argument string + QString args; + if ( msg.count() >= 2 ) { + QStringList copy( msg ); + // FIXME: for Qt3 + // copy.pop_front() + copy.remove( copy.begin() ); + args = copy.join( " " ); + } + + //qDebug( "args: %s", args.latin1() ); + + // we always respond to QUIT, regardless of state + if ( cmd == "QUIT" ) { + send( "211 Good bye!" ); + delete this; + return ; + } + + // connected to client + if ( Connected == state ) + return ; + + // waiting for user name + if ( Wait_USER == state ) { + + if ( cmd != "USER" || msg.count() < 2 || !SyncAuthentication::checkUser( arg ) ) { + send( "530 Please login with USER and PASS" ); + return ; + } + send( "331 User name ok, need password" ); + state = Wait_PASS; + return ; + } + + // waiting for password + if ( Wait_PASS == state ) { + + if ( cmd != "PASS" || !SyncAuthentication::checkPassword( arg ) ) { + send( "530 Please login with USER and PASS" ); + return ; + } + send( "230 User logged in, proceed" ); + state = Ready; + return ; + } + + // ACCESS CONTROL COMMANDS + + + // account (ACCT) + if ( cmd == "ACCT" ) { + // even wu-ftp does not support it + send( "502 Command not implemented" ); + } + + // change working directory (CWD) + else if ( cmd == "CWD" ) { + + if ( !args.isEmpty() ) { + if ( directory.cd( args, TRUE ) ) + send( "250 Requested file action okay, completed" ); + else + send( "550 Requested action not taken" ); + } + else + send( "500 Syntax error, command unrecognized" ); + } + + // change to parent directory (CDUP) + else if ( cmd == "CDUP" ) { + if ( directory.cdUp() ) + send( "250 Requested file action okay, completed" ); + else + send( "550 Requested action not taken" ); + } + + // structure mount (SMNT) + else if ( cmd == "SMNT" ) { + // even wu-ftp does not support it + send( "502 Command not implemented" ); + } + + // reinitialize (REIN) + else if ( cmd == "REIN" ) { + // even wu-ftp does not support it + send( "502 Command not implemented" ); + } + + + // TRANSFER PARAMETER COMMANDS + + + // data port (PORT) + else if ( cmd == "PORT" ) { + if ( parsePort( arg ) ) + send( "200 Command okay" ); + else + send( "500 Syntax error, command unrecognized" ); + } + + // passive (PASV) + else if ( cmd == "PASV" ) { + passiv = TRUE; + send( "227 Entering Passive Mode (" + + address().toString().replace( QRegExp( "\\." ), "," ) + "," + + QString::number( ( serversocket->port() ) >> 8 ) + "," + + QString::number( ( serversocket->port() ) & 0xFF ) + ")" ); + } + + // representation type (TYPE) + else if ( cmd == "TYPE" ) { + if ( arg.upper() == "A" || arg.upper() == "I" ) + send( "200 Command okay" ); + else + send( "504 Command not implemented for that parameter" ); + } + + // file structure (STRU) + else if ( cmd == "STRU" ) { + if ( arg.upper() == "F" ) + send( "200 Command okay" ); + else + send( "504 Command not implemented for that parameter" ); + } + + // transfer mode (MODE) + else if ( cmd == "MODE" ) { + if ( arg.upper() == "S" ) + send( "200 Command okay" ); + else + send( "504 Command not implemented for that parameter" ); + } + + + // FTP SERVICE COMMANDS + + + // retrieve (RETR) + else if ( cmd == "RETR" ) + if ( !args.isEmpty() && checkReadFile( absFilePath( args ) ) + || backupRestoreGzip( absFilePath( args ) ) ) { + send( "150 File status okay" ); + sendFile( absFilePath( args ) ); + } + else { + qDebug("550 Requested action not taken"); + send( "550 Requested action not taken" ); + } + + // store (STOR) + else if ( cmd == "STOR" ) + if ( !args.isEmpty() && checkWriteFile( absFilePath( args ) ) ) { + send( "150 File status okay" ); + retrieveFile( absFilePath( args ) ); + } + else + send( "550 Requested action not taken" ); + + // store unique (STOU) + else if ( cmd == "STOU" ) { + send( "502 Command not implemented" ); + } + + // append (APPE) + else if ( cmd == "APPE" ) { + send( "502 Command not implemented" ); + } + + // allocate (ALLO) + else if ( cmd == "ALLO" ) { + send( "200 Command okay" ); + } + + // restart (REST) + else if ( cmd == "REST" ) { + send( "502 Command not implemented" ); + } + + // rename from (RNFR) + else if ( cmd == "RNFR" ) { + renameFrom = QString::null; + if ( args.isEmpty() ) + send( "500 Syntax error, command unrecognized" ); + else { + QFile file( absFilePath( args ) ); + if ( file.exists() ) { + send( "350 File exists, ready for destination name" ); + renameFrom = absFilePath( args ); + } + else + send( "550 Requested action not taken" ); + } + } + + // rename to (RNTO) + else if ( cmd == "RNTO" ) { + if ( lastCommand != "RNFR" ) + send( "503 Bad sequence of commands" ); + else if ( args.isEmpty() ) + send( "500 Syntax error, command unrecognized" ); + else { + QDir dir( absFilePath( args ) ); + if ( dir.rename( renameFrom, absFilePath( args ), TRUE ) ) + send( "250 Requested file action okay, completed." ); + else + send( "550 Requested action not taken" ); + } + } + + // abort (ABOR) + else if ( cmd.contains( "ABOR" ) ) { + dtp->close(); + if ( dtp->dtpMode() != ServerDTP::Idle ) + send( "426 Connection closed; transfer aborted" ); + else + send( "226 Closing data connection" ); + } + + // delete (DELE) + else if ( cmd == "DELE" ) { + if ( args.isEmpty() ) + send( "500 Syntax error, command unrecognized" ); + else { + QFile file( absFilePath( args ) ) ; + if ( file.remove() ) { + send( "250 Requested file action okay, completed" ); + QCopEnvelope e("QPE/System", "linkChanged(QString)" ); + e << file.name(); + } + else { + send( "550 Requested action not taken" ); + } + } + } + + // remove directory (RMD) + else if ( cmd == "RMD" ) { + if ( args.isEmpty() ) + send( "500 Syntax error, command unrecognized" ); + else { + QDir dir; + if ( dir.rmdir( absFilePath( args ), TRUE ) ) + send( "250 Requested file action okay, completed" ); + else + send( "550 Requested action not taken" ); + } + } + + // make directory (MKD) + else if ( cmd == "MKD" ) { + if ( args.isEmpty() ) { + qDebug(" Error: no arg"); + send( "500 Syntax error, command unrecognized" ); + } + else { + QDir dir; + if ( dir.mkdir( absFilePath( args ), TRUE ) ) + send( "250 Requested file action okay, completed." ); + else + send( "550 Requested action not taken" ); + } + } + + // print working directory (PWD) + else if ( cmd == "PWD" ) { + send( "257 \"" + directory.path() + "\"" ); + } + + // list (LIST) + else if ( cmd == "LIST" ) { + if ( sendList( absFilePath( args ) ) ) + send( "150 File status okay" ); + else + send( "500 Syntax error, command unrecognized" ); + } + + // size (SIZE) + else if ( cmd == "SIZE" ) { + QString filePath = absFilePath( args ); + QFileInfo fi( filePath ); + bool gzipfile = backupRestoreGzip( filePath ); + if ( !fi.exists() && !gzipfile ) + send( "500 Syntax error, command unrecognized" ); + else { + if ( !gzipfile ) + send( "213 " + QString::number( fi.size() ) ); + else { + Process duproc( QString("du") ); + duproc.addArgument("-s"); + QString in, out; + if ( !duproc.exec(in, out) ) { + qDebug("du process failed; just sending back 1K"); + send( "213 1024"); + } + else { + QString size = out.left( out.find("\t") ); + int guess = size.toInt() / 5; + if ( filePath.contains("doc") ) + guess *= 1000; + qDebug("sending back gzip guess of %d", guess); + send( "213 " + QString::number(guess) ); + } + } + } + } + // name list (NLST) + else if ( cmd == "NLST" ) { + send( "502 Command not implemented" ); + } + + // site parameters (SITE) + else if ( cmd == "SITE" ) { + send( "502 Command not implemented" ); + } + + // system (SYST) + else if ( cmd == "SYST" ) { + send( "215 UNIX Type: L8" ); + } + + // status (STAT) + else if ( cmd == "STAT" ) { + send( "502 Command not implemented" ); + } + + // help (HELP ) + else if ( cmd == "HELP" ) { + send( "502 Command not implemented" ); + } + + // noop (NOOP) + else if ( cmd == "NOOP" ) { + send( "200 Command okay" ); + } + + // not implemented + else + send( "502 Command not implemented" ); + + lastCommand = cmd; } bool ServerPI::backupRestoreGzip( const QString &file ) { - return (file.find( "backup" ) != -1 && - file.findRev( ".tgz" ) == (int)file.length()-4 ); + return (file.find( "backup" ) != -1 && + file.findRev( ".tgz" ) == (int)file.length() - 4 ); } bool ServerPI::backupRestoreGzip( const QString &file, QStringList &targets ) { - if ( file.find( "backup" ) != -1 && - file.findRev( ".tgz" ) == (int)file.length()-4 ) { - QFileInfo info( file ); - targets = info.dirPath( TRUE ); - qDebug("ServerPI::backupRestoreGzip for %s = %s", file.latin1(), - targets.join(" ").latin1() ); - return true; - } - return false; + if ( file.find( "backup" ) != -1 && + file.findRev( ".tgz" ) == (int)file.length() - 4 ) { + QFileInfo info( file ); + targets = info.dirPath( TRUE ); + qDebug("ServerPI::backupRestoreGzip for %s = %s", file.latin1(), + targets.join(" ").latin1() ); + return true; + } + return false; } void ServerPI::sendFile( const QString& file ) { - if ( passiv ) { - wait[SendFile] = TRUE; - waitfile = file; - if ( waitsocket ) - newConnection( waitsocket ); - } - else { - QStringList targets; - if ( backupRestoreGzip( file, targets ) ) - dtp->sendGzipFile( file, targets, peeraddress, peerport ); - else dtp->sendFile( file, peeraddress, peerport ); - } + if ( passiv ) { + wait[SendFile] = TRUE; + waitfile = file; + if ( waitsocket ) + newConnection( waitsocket ); + } + else { + QStringList targets; + if ( backupRestoreGzip( file, targets ) ) + dtp->sendGzipFile( file, targets, peeraddress, peerport ); + else + dtp->sendFile( file, peeraddress, peerport ); + } } void ServerPI::retrieveFile( const QString& file ) { - if ( passiv ) { - wait[RetrieveFile] = TRUE; - waitfile = file; - if ( waitsocket ) - newConnection( waitsocket ); - } - else { - QStringList targets; - if ( backupRestoreGzip( file, targets ) ) - dtp->retrieveGzipFile( file, peeraddress, peerport ); - else - dtp->retrieveFile( file, peeraddress, peerport ); - } + if ( passiv ) { + wait[RetrieveFile] = TRUE; + waitfile = file; + if ( waitsocket ) + newConnection( waitsocket ); + } + else { + QStringList targets; + if ( backupRestoreGzip( file, targets ) ) + dtp->retrieveGzipFile( file, peeraddress, peerport ); + else + dtp->retrieveFile( file, peeraddress, peerport ); + } } bool ServerPI::parsePort( const QString& pp ) { - QStringList p = QStringList::split( ",", pp ); - if ( p.count() != 6 ) return FALSE; - - // h1,h2,h3,h4,p1,p2 - peeraddress = QHostAddress( ( p[0].toInt() << 24 ) + ( p[1].toInt() << 16 ) + - ( p[2].toInt() << 8 ) + p[3].toInt() ); - peerport = ( p[4].toInt() << 8 ) + p[5].toInt(); - return TRUE; + QStringList p = QStringList::split( ",", pp ); + if ( p.count() != 6 ) + return FALSE; + + // h1,h2,h3,h4,p1,p2 + peeraddress = QHostAddress( ( p[0].toInt() << 24 ) + ( p[1].toInt() << 16 ) + + ( p[2].toInt() << 8 ) + p[3].toInt() ); + peerport = ( p[4].toInt() << 8 ) + p[5].toInt(); + return TRUE; } void ServerPI::dtpCompleted() { - send( "226 Closing data connection, file transfer successful" ); - if ( dtp->dtpMode() == ServerDTP::RetrieveFile ) { - QString fn = dtp->fileName(); - if ( fn.right(8)==".desktop" && fn.find("/Documents/")>=0 ) { - QCopEnvelope e("QPE/System", "linkChanged(QString)" ); - e << fn; - } - } - waitsocket = 0; - dtp->close(); + send( "226 Closing data connection, file transfer successful" ); + if ( dtp->dtpMode() == ServerDTP::RetrieveFile ) { + QString fn = dtp->fileName(); + if ( fn.right(8) == ".desktop" && fn.find("/Documents/") >= 0 ) { + QCopEnvelope e("QPE/System", "linkChanged(QString)" ); + e << fn; + } + } + waitsocket = 0; + dtp->close(); } void ServerPI::dtpFailed() { - dtp->close(); - waitsocket = 0; - send( "451 Requested action aborted: local error in processing" ); + dtp->close(); + waitsocket = 0; + send( "451 Requested action aborted: local error in processing" ); } void ServerPI::dtpError( int ) { - dtp->close(); - waitsocket = 0; - send( "451 Requested action aborted: local error in processing" ); + dtp->close(); + waitsocket = 0; + send( "451 Requested action aborted: local error in processing" ); } bool ServerPI::sendList( const QString& arg ) { - QByteArray listing; - QBuffer buffer( listing ); - - if ( !buffer.open( IO_WriteOnly ) ) - return FALSE; - - QTextStream ts( &buffer ); - QString fn = arg; - - if ( fn.isEmpty() ) - fn = directory.path(); - - QFileInfo fi( fn ); - if ( !fi.exists() ) return FALSE; - - // return file listing - if ( fi.isFile() ) { - ts << fileListing( &fi ) << endl; - } - - // return directory listing - else if ( fi.isDir() ) { - QDir dir( fn ); - const QFileInfoList *list = dir.entryInfoList( QDir::All | QDir::Hidden ); - - QFileInfoListIterator it( *list ); - QFileInfo *info; - - unsigned long total = 0; - while ( ( info = it.current() ) ) { - if ( info->fileName() != "." && info->fileName() != ".." ) - total += info->size(); - ++it; - } - - ts << "total " << QString::number( total / 1024 ) << endl; - - it.toFirst(); - while ( ( info = it.current() ) ) { - if ( info->fileName() == "." || info->fileName() == ".." ) { - ++it; - continue; - } - ts << fileListing( info ) << endl; - ++it; - } - } - - if ( passiv ) { - waitarray = buffer.buffer(); - wait[SendByteArray] = TRUE; - if ( waitsocket ) - newConnection( waitsocket ); - } - else - dtp->sendByteArray( buffer.buffer(), peeraddress, peerport ); - return TRUE; + QByteArray listing; + QBuffer buffer( listing ); + + if ( !buffer.open( IO_WriteOnly ) ) + return FALSE; + + QTextStream ts( &buffer ); + QString fn = arg; + + if ( fn.isEmpty() ) + fn = directory.path(); + + QFileInfo fi( fn ); + if ( !fi.exists() ) + return FALSE; + + // return file listing + if ( fi.isFile() ) { + ts << fileListing( &fi ) << endl; + } + + // return directory listing + else if ( fi.isDir() ) { + QDir dir( fn ); + const QFileInfoList *list = dir.entryInfoList( QDir::All | QDir::Hidden ); + + QFileInfoListIterator it( *list ); + QFileInfo *info; + + unsigned long total = 0; + while ( ( info = it.current() ) ) { + if ( info->fileName() != "." && info->fileName() != ".." ) + total += info->size(); + ++it; + } + + ts << "total " << QString::number( total / 1024 ) << endl; + + it.toFirst(); + while ( ( info = it.current() ) ) { + if ( info->fileName() == "." || info->fileName() == ".." ) { + ++it; + continue; + } + ts << fileListing( info ) << endl; + ++it; + } + } + + if ( passiv ) { + waitarray = buffer.buffer(); + wait[SendByteArray] = TRUE; + if ( waitsocket ) + newConnection( waitsocket ); + } + else + dtp->sendByteArray( buffer.buffer(), peeraddress, peerport ); + return TRUE; } QString ServerPI::fileListing( QFileInfo *info ) { - if ( !info ) return QString::null; - QString s; + if ( !info ) + return QString::null; + QString s; - // type char - if ( info->isDir() ) - s += "d"; - else if ( info->isSymLink() ) - s += "l"; - else - s += "-"; + // type char + if ( info->isDir() ) + s += "d"; + else if ( info->isSymLink() ) + s += "l"; + else + s += "-"; - // permisson string - s += permissionString( info ) + " "; + // permisson string + s += permissionString( info ) + " "; - // number of hardlinks - int subdirs = 1; + // number of hardlinks + int subdirs = 1; - if ( info->isDir() ) - subdirs = 2; - // FIXME : this is to slow - //if ( info->isDir() ) - //subdirs = QDir( info->absFilePath() ).entryList( QDir::Dirs ).count(); + if ( info->isDir() ) + subdirs = 2; + // FIXME : this is to slow + //if ( info->isDir() ) + //subdirs = QDir( info->absFilePath() ).entryList( QDir::Dirs ).count(); - s += QString::number( subdirs ).rightJustify( 3, ' ', TRUE ) + " "; + s += QString::number( subdirs ).rightJustify( 3, ' ', TRUE ) + " "; - // owner - s += info->owner().leftJustify( 8, ' ', TRUE ) + " "; + // owner + s += info->owner().leftJustify( 8, ' ', TRUE ) + " "; - // group - s += info->group().leftJustify( 8, ' ', TRUE ) + " "; + // group + s += info->group().leftJustify( 8, ' ', TRUE ) + " "; - // file size in bytes - s += QString::number( info->size() ).rightJustify( 9, ' ', TRUE ) + " "; + // file size in bytes + s += QString::number( info->size() ).rightJustify( 9, ' ', TRUE ) + " "; - // last modified date - QDate date = info->lastModified().date(); - QTime time = info->lastModified().time(); - s += date.monthName( date.month() ) + " " - + QString::number( date.day() ).rightJustify( 2, ' ', TRUE ) + " " - + QString::number( time.hour() ).rightJustify( 2, '0', TRUE ) + ":" - + QString::number( time.minute() ).rightJustify( 2,'0', TRUE ) + " "; + // last modified date + QDate date = info->lastModified().date(); + QTime time = info->lastModified().time(); + s += date.monthName( date.month() ) + " " + + QString::number( date.day() ).rightJustify( 2, ' ', TRUE ) + " " + + QString::number( time.hour() ).rightJustify( 2, '0', TRUE ) + ":" + + QString::number( time.minute() ).rightJustify( 2, '0', TRUE ) + " "; - // file name - s += info->fileName(); + // file name + s += info->fileName(); - return s; + return s; } QString ServerPI::permissionString( QFileInfo *info ) { - if ( !info ) return QString( "---------" ); - QString s; - - // user - if ( info->permission( QFileInfo::ReadUser ) ) s += "r"; - else s += "-"; - if ( info->permission( QFileInfo::WriteUser ) ) s += "w"; - else s += "-"; - if ( info->permission( QFileInfo::ExeUser ) ) s += "x"; - else s += "-"; - - // group - if ( info->permission( QFileInfo::ReadGroup ) ) s += "r"; - else s += "-"; - if ( info->permission( QFileInfo::WriteGroup ) )s += "w"; - else s += "-"; - if ( info->permission( QFileInfo::ExeGroup ) ) s += "x"; - else s += "-"; - - // exec - if ( info->permission( QFileInfo::ReadOther ) ) s += "r"; - else s += "-"; - if ( info->permission( QFileInfo::WriteOther ) ) s += "w"; - else s += "-"; - if ( info->permission( QFileInfo::ExeOther ) ) s += "x"; - else s += "-"; - - return s; + if ( !info ) + return QString( "---------" ); + QString s; + + // user + if ( info->permission( QFileInfo::ReadUser ) ) + s += "r"; + else + s += "-"; + if ( info->permission( QFileInfo::WriteUser ) ) + s += "w"; + else + s += "-"; + if ( info->permission( QFileInfo::ExeUser ) ) + s += "x"; + else + s += "-"; + + // group + if ( info->permission( QFileInfo::ReadGroup ) ) + s += "r"; + else + s += "-"; + if ( info->permission( QFileInfo::WriteGroup ) ) + s += "w"; + else + s += "-"; + if ( info->permission( QFileInfo::ExeGroup ) ) + s += "x"; + else + s += "-"; + + // exec + if ( info->permission( QFileInfo::ReadOther ) ) + s += "r"; + else + s += "-"; + if ( info->permission( QFileInfo::WriteOther ) ) + s += "w"; + else + s += "-"; + if ( info->permission( QFileInfo::ExeOther ) ) + s += "x"; + else + s += "-"; + + return s; } void ServerPI::newConnection( int socket ) { - //qDebug( "New incomming connection" ); - - if ( !passiv ) return; - - if ( wait[SendFile] ) { - QStringList targets; - if ( backupRestoreGzip( waitfile, targets ) ) - dtp->sendGzipFile( waitfile, targets ); - else - dtp->sendFile( waitfile ); - dtp->setSocket( socket ); - } - else if ( wait[RetrieveFile] ) { - qDebug("check retrieve file"); - if ( backupRestoreGzip( waitfile ) ) - dtp->retrieveGzipFile( waitfile ); - else - dtp->retrieveFile( waitfile ); - dtp->setSocket( socket ); - } - else if ( wait[SendByteArray] ) { - dtp->sendByteArray( waitarray ); - dtp->setSocket( socket ); - } - else if ( wait[RetrieveByteArray] ) { - qDebug("retrieve byte array"); - dtp->retrieveByteArray(); - dtp->setSocket( socket ); - } - else - waitsocket = socket; - - for( int i = 0; i < 4; i++ ) - wait[i] = FALSE; + //qDebug( "New incomming connection" ); + + if ( !passiv ) + return ; + + if ( wait[SendFile] ) { + QStringList targets; + if ( backupRestoreGzip( waitfile, targets ) ) + dtp->sendGzipFile( waitfile, targets ); + else + dtp->sendFile( waitfile ); + dtp->setSocket( socket ); + } + else if ( wait[RetrieveFile] ) { + qDebug("check retrieve file"); + if ( backupRestoreGzip( waitfile ) ) + dtp->retrieveGzipFile( waitfile ); + else + dtp->retrieveFile( waitfile ); + dtp->setSocket( socket ); + } + else if ( wait[SendByteArray] ) { + dtp->sendByteArray( waitarray ); + dtp->setSocket( socket ); + } + else if ( wait[RetrieveByteArray] ) { + qDebug("retrieve byte array"); + dtp->retrieveByteArray(); + dtp->setSocket( socket ); + } + else + waitsocket = socket; + + for ( int i = 0; i < 4; i++ ) + wait[i] = FALSE; } QString ServerPI::absFilePath( const QString& file ) { - if ( file.isEmpty() ) return file; + if ( file.isEmpty() ) + return file; - QString filepath( file ); - if ( file[0] != "/" ) - filepath = directory.path() + "/" + file; + QString filepath( file ); + if ( file[0] != "/" ) + filepath = directory.path() + "/" + file; - return filepath; + return filepath; } void ServerPI::timerEvent( QTimerEvent * ) { - connectionClosed(); + connectionClosed(); } ServerDTP::ServerDTP( QObject *parent, const char* name) - : QSocket( parent, name ), mode( Idle ), createTargzProc( 0 ), -retrieveTargzProc( 0 ), gzipProc( 0 ) + : QSocket( parent, name ), mode( Idle ), createTargzProc( 0 ), + retrieveTargzProc( 0 ), gzipProc( 0 ) { - connect( this, SIGNAL( connected() ), SLOT( connected() ) ); - connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); - connect( this, SIGNAL( bytesWritten( int ) ), SLOT( bytesWritten( int ) ) ); - connect( this, SIGNAL( readyRead() ), SLOT( readyRead() ) ); - - gzipProc = new QProcess( this, "gzipProc" ); - gzipProc->setCommunication( QProcess::Stdin | QProcess::Stdout ); - - createTargzProc = new QProcess( QString("tar"), this, "createTargzProc"); - createTargzProc->setCommunication( QProcess::Stdout ); - createTargzProc->setWorkingDirectory( QDir::rootDirPath() ); - connect( createTargzProc, SIGNAL( processExited() ), SLOT( targzDone() ) ); - - QStringList args = "tar"; - args += "-xv"; - retrieveTargzProc = new QProcess( args, this, "retrieveTargzProc" ); - retrieveTargzProc->setCommunication( QProcess::Stdin ); - retrieveTargzProc->setWorkingDirectory( QDir::rootDirPath() ); - connect( retrieveTargzProc, SIGNAL( processExited() ), - SIGNAL( completed() ) ); - connect( retrieveTargzProc, SIGNAL( processExited() ), - SLOT( extractTarDone() ) ); + connect( this, SIGNAL( connected() ), SLOT( connected() ) ); + connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); + connect( this, SIGNAL( bytesWritten( int ) ), SLOT( bytesWritten( int ) ) ); + connect( this, SIGNAL( readyRead() ), SLOT( readyRead() ) ); + + gzipProc = new OProcess( this, "gzipProc" ); + + createTargzProc = new OProcess( QString("tar"), this, "createTargzProc"); + createTargzProc->setWorkingDirectory( QDir::rootDirPath() ); + connect( createTargzProc, SIGNAL( processExited(OProcess *) ), SLOT( targzDone() ) ); + + QStringList args = "tar"; + args += "-xv"; + retrieveTargzProc = new OProcess( args, this, "retrieveTargzProc" ); + retrieveTargzProc->setWorkingDirectory( QDir::rootDirPath() ); + connect( retrieveTargzProc, SIGNAL( processExited(OProcess *) ), + SIGNAL( completed() ) ); + connect( retrieveTargzProc, SIGNAL( processExited(OProcess *) ), + SLOT( extractTarDone() ) ); } ServerDTP::~ServerDTP() { - buf.close(); - file.close(); - createTargzProc->kill(); + buf.close(); + file.close(); + createTargzProc->kill(); } void ServerDTP::extractTarDone() { - qDebug("extract done"); + qDebug("extract done"); #ifndef QT_NO_COP - QCopEnvelope e( "QPE/Desktop", "restoreDone(QString)" ); - e << file.name(); + + QCopEnvelope e( "QPE/Desktop", "restoreDone(QString)" ); + e << file.name(); #endif } void ServerDTP::connected() { - // send file mode - switch ( mode ) { - case SendFile : - if ( !file.exists() || !file.open( IO_ReadOnly) ) { - emit failed(); - mode = Idle; - return; - } - - //qDebug( "Debug: Sending file '%s'", file.name().latin1() ); - - bytes_written = 0; - if ( file.size() == 0 ) { - //make sure it doesn't hang on empty files - file.close(); - emit completed(); - mode = Idle; - } else { - - if( !file.atEnd() ) { - QCString s; - s.resize( block_size ); - int bytes = file.readBlock( s.data(), block_size ); - writeBlock( s.data(), bytes ); - } - } - break; - case SendGzipFile: - if ( createTargzProc->isRunning() ) { - // SHOULDN'T GET HERE, BUT DOING A SAFETY CHECK ANYWAY - qWarning("Previous tar --gzip process is still running; killing it..."); - createTargzProc->kill(); - } - - bytes_written = 0; - qDebug("==>start send tar process"); - if ( !createTargzProc->start() ) - qWarning("Error starting %s or %s", - createTargzProc->arguments().join(" ").latin1(), - gzipProc->arguments().join(" ").latin1() ); - break; - case SendBuffer: - if ( !buf.open( IO_ReadOnly) ) { - emit failed(); - mode = Idle; - return; - } - - // qDebug( "Debug: Sending byte array" ); - bytes_written = 0; - while( !buf.atEnd() ) - putch( buf.getch() ); - buf.close(); - break; - case RetrieveFile: - // retrieve file mode - if ( file.exists() && !file.remove() ) { - emit failed(); - mode = Idle; - return; - } - - if ( !file.open( IO_WriteOnly) ) { - emit failed(); - mode = Idle; - return; - } - // qDebug( "Debug: Retrieving file %s", file.name().latin1() ); - break; - case RetrieveGzipFile: - qDebug("=-> starting tar process to receive .tgz file"); - break; - case RetrieveBuffer: - // retrieve buffer mode - if ( !buf.open( IO_WriteOnly) ) { - emit failed(); - mode = Idle; - return; - } - // qDebug( "Debug: Retrieving byte array" ); - break; - case Idle: - qDebug("connection established but mode set to Idle; BUG!"); - break; - } + // send file mode + switch ( mode ) { + case SendFile : + if ( !file.exists() || !file.open( IO_ReadOnly) ) { + emit failed(); + mode = Idle; + return ; + } + + //qDebug( "Debug: Sending file '%s'", file.name().latin1() ); + + bytes_written = 0; + if ( file.size() == 0 ) { + //make sure it doesn't hang on empty files + file.close(); + emit completed(); + mode = Idle; + } + else { + + if ( !file.atEnd() ) { + QCString s; + s.resize( block_size ); + int bytes = file.readBlock( s.data(), block_size ); + writeBlock( s.data(), bytes ); + } + } + break; + case SendGzipFile: + if ( createTargzProc->isRunning() ) { + // SHOULDN'T GET HERE, BUT DOING A SAFETY CHECK ANYWAY + qWarning("Previous tar --gzip process is still running; killing it..."); + createTargzProc->kill(); + } + + bytes_written = 0; + qDebug("==>start send tar process"); + if ( !createTargzProc->start(OProcess::NotifyOnExit, OProcess::Stdout) ) + qWarning("Error starting %s or %s", + createTargzProc->args()[0].data(), + gzipProc->args()[0].data()); + break; + case SendBuffer: + if ( !buf.open( IO_ReadOnly) ) { + emit failed(); + mode = Idle; + return ; + } + + // qDebug( "Debug: Sending byte array" ); + bytes_written = 0; + while ( !buf.atEnd() ) + putch( buf.getch() ); + buf.close(); + break; + case RetrieveFile: + // retrieve file mode + if ( file.exists() && !file.remove() ) { + emit failed(); + mode = Idle; + return ; + } + + if ( !file.open( IO_WriteOnly) ) { + emit failed(); + mode = Idle; + return ; + } + // qDebug( "Debug: Retrieving file %s", file.name().latin1() ); + break; + case RetrieveGzipFile: + qDebug("=-> starting tar process to receive .tgz file"); + break; + case RetrieveBuffer: + // retrieve buffer mode + if ( !buf.open( IO_WriteOnly) ) { + emit failed(); + mode = Idle; + return ; + } + // qDebug( "Debug: Retrieving byte array" ); + break; + case Idle: + qDebug("connection established but mode set to Idle; BUG!"); + break; + } } void ServerDTP::connectionClosed() { - //qDebug( "Debug: Data connection closed %ld bytes written", bytes_written ); - - // send file mode - if ( SendFile == mode ) { - if ( bytes_written == file.size() ) - emit completed(); - else - emit failed(); - } - - // send buffer mode - else if ( SendBuffer == mode ) { - if ( bytes_written == buf.size() ) - emit completed(); - else - emit failed(); - } - - // retrieve file mode - else if ( RetrieveFile == mode ) { - file.close(); - emit completed(); - } - - else if ( RetrieveGzipFile == mode ) { - qDebug("Done writing ungzip file; closing input"); - gzipProc->flushStdin(); - gzipProc->closeStdin(); - } - - // retrieve buffer mode - else if ( RetrieveBuffer == mode ) { - buf.close(); - emit completed(); - } - - mode = Idle; + //qDebug( "Debug: Data connection closed %ld bytes written", bytes_written ); + + // send file mode + if ( SendFile == mode ) { + if ( bytes_written == file.size() ) + emit completed(); + else + emit failed(); + } + + // send buffer mode + else if ( SendBuffer == mode ) { + if ( bytes_written == buf.size() ) + emit completed(); + else + emit failed(); + } + + // retrieve file mode + else if ( RetrieveFile == mode ) { + file.close(); + emit completed(); + } + + else if ( RetrieveGzipFile == mode ) { + qDebug("Done writing ungzip file; closing input"); + gzipProc->flushStdin(); + gzipProc->closeStdin(); + } + + // retrieve buffer mode + else if ( RetrieveBuffer == mode ) { + buf.close(); + emit completed(); + } + + mode = Idle; } void ServerDTP::bytesWritten( int bytes ) { - bytes_written += bytes; - - // send file mode - if ( SendFile == mode ) { - - if ( bytes_written == file.size() ) { - // qDebug( "Debug: Sending complete: %d bytes", file.size() ); - file.close(); - emit completed(); - mode = Idle; - } - else if( !file.atEnd() ) { - QCString s; - s.resize( block_size ); - int bytes = file.readBlock( s.data(), block_size ); - writeBlock( s.data(), bytes ); - } - } - - // send buffer mode - if ( SendBuffer == mode ) { - - if ( bytes_written == buf.size() ) { - // qDebug( "Debug: Sending complete: %d bytes", buf.size() ); - emit completed(); - mode = Idle; - } - } + bytes_written += bytes; + + // send file mode + if ( SendFile == mode ) { + + if ( bytes_written == file.size() ) { + // qDebug( "Debug: Sending complete: %d bytes", file.size() ); + file.close(); + emit completed(); + mode = Idle; + } + else if ( !file.atEnd() ) { + QCString s; + s.resize( block_size ); + int bytes = file.readBlock( s.data(), block_size ); + writeBlock( s.data(), bytes ); + } + } + + // send buffer mode + if ( SendBuffer == mode ) { + + if ( bytes_written == buf.size() ) { + // qDebug( "Debug: Sending complete: %d bytes", buf.size() ); + emit completed(); + mode = Idle; + } + } } void ServerDTP::readyRead() { - // retrieve file mode - if ( RetrieveFile == mode ) { - QCString s; - s.resize( bytesAvailable() ); - readBlock( s.data(), bytesAvailable() ); - file.writeBlock( s.data(), s.size() ); - } - else if ( RetrieveGzipFile == mode ) { - if ( !gzipProc->isRunning() ) - gzipProc->start(); - - QByteArray s; - s.resize( bytesAvailable() ); - readBlock( s.data(), bytesAvailable() ); - gzipProc->writeToStdin( s ); - qDebug("wrote %d bytes to ungzip ", s.size() ); - } - // retrieve buffer mode - else if ( RetrieveBuffer == mode ) { - QCString s; - s.resize( bytesAvailable() ); - readBlock( s.data(), bytesAvailable() ); - buf.writeBlock( s.data(), s.size() ); - } + // retrieve file mode + if ( RetrieveFile == mode ) { + QCString s; + s.resize( bytesAvailable() ); + readBlock( s.data(), bytesAvailable() ); + file.writeBlock( s.data(), s.size() ); + } + else if ( RetrieveGzipFile == mode ) { + if ( !gzipProc->isRunning() ) + gzipProc->start(OProcess::NotifyOnExit, (OProcess::Communication) ( OProcess::Stdin | OProcess::Stdout )); + + QByteArray s; + s.resize( bytesAvailable() ); + readBlock( s.data(), bytesAvailable() ); + gzipProc->writeStdin( s.data(), s.size() ); + qDebug("wrote %d bytes to ungzip ", s.size() ); + } + // retrieve buffer mode + else if ( RetrieveBuffer == mode ) { + QCString s; + s.resize( bytesAvailable() ); + readBlock( s.data(), bytesAvailable() ); + buf.writeBlock( s.data(), s.size() ); + } } -void ServerDTP::writeTargzBlock() +void ServerDTP::writeTargzBlock(OProcess *, char *buffer, int buflen) { - QByteArray block = gzipProc->readStdout(); - writeBlock( block.data(), block.size() ); - qDebug("writeTargzBlock %d", block.size()); - if ( !createTargzProc->isRunning() ) { - qDebug("tar and gzip done"); - emit completed(); - mode = Idle; - disconnect( gzipProc, SIGNAL( readyReadStdout() ), - this, SLOT( writeTargzBlock() ) ); - } + writeBlock( buffer, buflen ); + qDebug("writeTargzBlock %d", buflen); + if ( !createTargzProc->isRunning() ) { + qDebug("tar and gzip done"); + emit completed(); + mode = Idle; + disconnect( gzipProc, SIGNAL( receivedStdout(OProcess *, char *, int ) ), + this, SLOT( writeTargzBlock(OProcess *, char *, int) ) ); + } } void ServerDTP::targzDone() { - //qDebug("targz done"); - disconnect( createTargzProc, SIGNAL( readyReadStdout() ), - this, SLOT( gzipTarBlock() ) ); - gzipProc->closeStdin(); + //qDebug("targz done"); + disconnect( createTargzProc, SIGNAL( receivedStdout(OProcess *, char *, int) ), + this, SLOT( gzipTarBlock(OProcess *, char *, int) ) ); + gzipProc->closeStdin(); } -void ServerDTP::gzipTarBlock() +void ServerDTP::gzipTarBlock(OProcess *, char *buffer, int buflen) { - //qDebug("gzipTarBlock"); - if ( !gzipProc->isRunning() ) { - //qDebug("auto start gzip proc"); - gzipProc->start(); - } - gzipProc->writeToStdin( createTargzProc->readStdout() ); + //qDebug("gzipTarBlock"); + if ( !gzipProc->isRunning() ) { + //qDebug("auto start gzip proc"); + gzipProc->start(OProcess::NotifyOnExit, (OProcess::Communication) ( OProcess::Stdin | OProcess::Stdout )); + } + gzipProc->writeStdin( buffer, buflen ); } void ServerDTP::sendFile( const QString fn, const QHostAddress& host, Q_UINT16 port ) { - file.setName( fn ); - mode = SendFile; - connectToHost( host.toString(), port ); + file.setName( fn ); + mode = SendFile; + connectToHost( host.toString(), port ); } void ServerDTP::sendFile( const QString fn ) { - file.setName( fn ); - mode = SendFile; + file.setName( fn ); + mode = SendFile; } void ServerDTP::sendGzipFile( const QString &fn, - const QStringList &archiveTargets, - const QHostAddress& host, Q_UINT16 port ) + const QStringList &archiveTargets, + const QHostAddress& host, Q_UINT16 port ) { - sendGzipFile( fn, archiveTargets ); - connectToHost( host.toString(), port ); + sendGzipFile( fn, archiveTargets ); + connectToHost( host.toString(), port ); } void ServerDTP::sendGzipFile( const QString &fn, - const QStringList &archiveTargets ) + const QStringList &archiveTargets ) { - mode = SendGzipFile; - file.setName( fn ); - - QStringList args = "tar"; - args += "-cv"; - args += archiveTargets; - qDebug("sendGzipFile %s", args.join(" ").latin1() ); - createTargzProc->setArguments( args ); - connect( createTargzProc, - SIGNAL( readyReadStdout() ), SLOT( gzipTarBlock() ) ); - - gzipProc->setArguments( "gzip" ); - connect( gzipProc, SIGNAL( readyReadStdout() ), - SLOT( writeTargzBlock() ) ); + mode = SendGzipFile; + file.setName( fn ); + + QStringList args = "tar"; + args += "-cv"; + args += archiveTargets; + qDebug("sendGzipFile %s", args.join(" ").latin1() ); + createTargzProc->clearArguments( ); + *createTargzProc << args; + connect( createTargzProc, + SIGNAL( receivedStdout(OProcess *, char *, int) ), SLOT( gzipTarBlock(OProcess *, char *, int) ) ); + + gzipProc->clearArguments( ); + *gzipProc << "gzip"; + connect( gzipProc, SIGNAL( receivedStdout(OProcess *, char *, int) ), + SLOT( writeTargzBlock(OProcess *, char *, int) ) ); } void ServerDTP::gunzipDone() { - qDebug("gunzipDone"); - disconnect( gzipProc, SIGNAL( processExited() ), - this, SLOT( gunzipDone() ) ); - retrieveTargzProc->closeStdin(); - disconnect( gzipProc, SIGNAL( readyReadStdout() ), - this, SLOT( tarExtractBlock() ) ); + qDebug("gunzipDone"); + disconnect( gzipProc, SIGNAL( processExited() ), + this, SLOT( gunzipDone() ) ); + retrieveTargzProc->closeStdin(); + disconnect( gzipProc, SIGNAL( receivedStdout(OProcess *, char *, int) ), + this, SLOT( tarExtractBlock(OProcess *, char *, int) ) ); } -void ServerDTP::tarExtractBlock() +void ServerDTP::tarExtractBlock(OProcess *, char *buffer, int buflen) { - qDebug("ungzipTarBlock"); - if ( !retrieveTargzProc->isRunning() ) { - qDebug("auto start ungzip proc"); - if ( !retrieveTargzProc->start() ) - qWarning(" failed to start tar -x process"); - } - retrieveTargzProc->writeToStdin( gzipProc->readStdout() ); + qDebug("tarExtractBlock"); + if ( !retrieveTargzProc->isRunning() ) { + qDebug("auto start ungzip proc"); + if ( !retrieveTargzProc->start(OProcess::NotifyOnExit, OProcess::Stdin) ) + qWarning(" failed to start tar -x process"); + } + retrieveTargzProc->writeStdin( buffer, buflen ); } void ServerDTP::retrieveFile( const QString fn, const QHostAddress& host, Q_UINT16 port ) { - file.setName( fn ); - mode = RetrieveFile; - connectToHost( host.toString(), port ); + file.setName( fn ); + mode = RetrieveFile; + connectToHost( host.toString(), port ); } void ServerDTP::retrieveFile( const QString fn ) { - file.setName( fn ); - mode = RetrieveFile; + file.setName( fn ); + mode = RetrieveFile; } void ServerDTP::retrieveGzipFile( const QString &fn ) { - qDebug("retrieveGzipFile %s", fn.latin1()); - file.setName( fn ); - mode = RetrieveGzipFile; - - gzipProc->setArguments( "gunzip" ); - connect( gzipProc, SIGNAL( readyReadStdout() ), - SLOT( tarExtractBlock() ) ); - connect( gzipProc, SIGNAL( processExited() ), - SLOT( gunzipDone() ) ); + qDebug("retrieveGzipFile %s", fn.latin1()); + file.setName( fn ); + mode = RetrieveGzipFile; + + gzipProc->clearArguments(); + *gzipProc << "gunzip"; + connect( gzipProc, SIGNAL( readyReadStdout() ), + SLOT( tarExtractBlock() ) ); + connect( gzipProc, SIGNAL( processExited() ), + SLOT( gunzipDone() ) ); } void ServerDTP::retrieveGzipFile( const QString &fn, const QHostAddress& host, Q_UINT16 port ) { - retrieveGzipFile( fn ); - connectToHost( host.toString(), port ); + retrieveGzipFile( fn ); + connectToHost( host.toString(), port ); } void ServerDTP::sendByteArray( const QByteArray& array, const QHostAddress& host, Q_UINT16 port ) { - buf.setBuffer( array ); - mode = SendBuffer; - connectToHost( host.toString(), port ); + buf.setBuffer( array ); + mode = SendBuffer; + connectToHost( host.toString(), port ); } void ServerDTP::sendByteArray( const QByteArray& array ) { - buf.setBuffer( array ); - mode = SendBuffer; + buf.setBuffer( array ); + mode = SendBuffer; } void ServerDTP::retrieveByteArray( const QHostAddress& host, Q_UINT16 port ) { - buf.setBuffer( QByteArray() ); - mode = RetrieveBuffer; - connectToHost( host.toString(), port ); + buf.setBuffer( QByteArray() ); + mode = RetrieveBuffer; + connectToHost( host.toString(), port ); } void ServerDTP::retrieveByteArray() { - buf.setBuffer( QByteArray() ); - mode = RetrieveBuffer; + buf.setBuffer( QByteArray() ); + mode = RetrieveBuffer; } void ServerDTP::setSocket( int socket ) { - QSocket::setSocket( socket ); - connected(); + QSocket::setSocket( socket ); + connected(); } diff --git a/core/launcher/transferserver.h b/core/launcher/transferserver.h index a3bb060..1c5ab4b 100644 --- a/core/launcher/transferserver.h +++ b/core/launcher/transferserver.h @@ -1,175 +1,175 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include <qserversocket.h> #include <qsocket.h> #include <qdir.h> #include <qfile.h> #include <qbuffer.h> class QFileInfo; -class QProcess; +class OProcess; class TransferServer : public QServerSocket { Q_OBJECT public: TransferServer( Q_UINT16 port, QObject *parent = 0, const char* name = 0 ); virtual ~TransferServer(); void newConnection( int socket ); }; class SyncAuthentication : QObject { Q_OBJECT public: static int isAuthorized(QHostAddress peeraddress); static bool checkPassword(const QString& pw); static bool checkUser(const QString& user); static QString serverId(); static QString loginName(); static QString ownerName(); }; class ServerDTP : public QSocket { Q_OBJECT public: ServerDTP( QObject *parent = 0, const char* name = 0 ); ~ServerDTP(); enum Mode{ Idle = 0, SendFile, SendGzipFile, SendBuffer, RetrieveFile, RetrieveGzipFile, RetrieveBuffer }; void sendFile( const QString fn ); void sendFile( const QString fn, const QHostAddress& host, Q_UINT16 port ); void sendGzipFile( const QString &fn, const QStringList &archiveTargets ); void sendGzipFile( const QString &fn, const QStringList &archiveTargets, const QHostAddress& host, Q_UINT16 port ); void sendByteArray( const QByteArray& array ); void sendByteArray( const QByteArray& array, const QHostAddress& host, Q_UINT16 port ); void retrieveFile( const QString fn ); void retrieveFile( const QString fn, const QHostAddress& host, Q_UINT16 port ); void retrieveGzipFile( const QString &fn ); void retrieveGzipFile( const QString &fn, const QHostAddress& host, Q_UINT16 port ); void retrieveByteArray(); void retrieveByteArray( const QHostAddress& host, Q_UINT16 port ); Mode dtpMode() { return mode; } QByteArray buffer() { return buf.buffer(); } QString fileName() const { return file.name(); } void setSocket( int socket ); signals: void completed(); void failed(); private slots: void connectionClosed(); void connected(); void bytesWritten( int bytes ); void readyRead(); - void writeTargzBlock(); + void writeTargzBlock(OProcess *, char *, int); void targzDone(); - void gzipTarBlock(); - void tarExtractBlock(); + void gzipTarBlock(OProcess *, char *, int); + void tarExtractBlock(OProcess *, char *, int); void gunzipDone(); void extractTarDone(); private: unsigned long bytes_written; Mode mode; QFile file; QBuffer buf; - QProcess *createTargzProc; - QProcess *retrieveTargzProc; - QProcess *gzipProc; + OProcess *createTargzProc; + OProcess *retrieveTargzProc; + OProcess *gzipProc; }; class ServerSocket : public QServerSocket { Q_OBJECT public: ServerSocket( Q_UINT16 port, QObject *parent = 0, const char* name = 0 ) : QServerSocket( port, 1, parent, name ) {} void newConnection( int socket ) { emit newIncomming( socket ); } signals: void newIncomming( int socket ); }; class ServerPI : public QSocket { Q_OBJECT enum State { Connected, Wait_USER, Wait_PASS, Ready, Forbidden }; enum Transfer { SendFile = 0, RetrieveFile = 1, SendByteArray = 2, RetrieveByteArray = 3 }; public: ServerPI( int socket, QObject *parent = 0, const char* name = 0 ); virtual ~ServerPI(); protected slots: void read(); void send( const QString& msg ); void process( const QString& command ); void connectionClosed(); void dtpCompleted(); void dtpFailed(); void dtpError( int ); void newConnection( int socket ); protected: bool checkReadFile( const QString& file ); bool checkWriteFile( const QString& file ); bool parsePort( const QString& pw ); bool backupRestoreGzip( const QString &file, QStringList &targets ); bool backupRestoreGzip( const QString &file ); bool sendList( const QString& arg ); void sendFile( const QString& file ); void retrieveFile( const QString& file ); QString permissionString( QFileInfo *info ); QString fileListing( QFileInfo *info ); QString absFilePath( const QString& file ); void timerEvent( QTimerEvent *e ); private: State state; Q_UINT16 peerport; QHostAddress peeraddress; bool passiv; bool wait[4]; ServerDTP *dtp; ServerSocket *serversocket; QString waitfile; QDir directory; QByteArray waitarray; |