author | zecke <zecke> | 2004-02-21 13:09:17 (UTC) |
---|---|---|
committer | zecke <zecke> | 2004-02-21 13:09:17 (UTC) |
commit | 4024cfd1e32a43d82361d6ba9977fe64db88e3ce (patch) (side-by-side diff) | |
tree | 1d2e0592a3df330a17d9a07cd2f29615ce5be595 | |
parent | aa11789fc4d735a04fac09063851753d8a57027b (diff) | |
download | opie-4024cfd1e32a43d82361d6ba9977fe64db88e3ce.zip opie-4024cfd1e32a43d82361d6ba9977fe64db88e3ce.tar.gz opie-4024cfd1e32a43d82361d6ba9977fe64db88e3ce.tar.bz2 |
Fix up syncing mode
InetlliSync,Opie1.0,QtopiaNEW
-rw-r--r-- | core/launcher/qcopbridge.cpp | 2 | ||||
-rw-r--r-- | core/launcher/qcopbridge.h | 3 | ||||
-rw-r--r-- | core/launcher/transferserver.cpp | 36 |
3 files changed, 30 insertions, 11 deletions
diff --git a/core/launcher/qcopbridge.cpp b/core/launcher/qcopbridge.cpp index b45f0cc..9bca360 100644 --- a/core/launcher/qcopbridge.cpp +++ b/core/launcher/qcopbridge.cpp @@ -1,498 +1,498 @@ /********************************************************************** ** 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 "qcopbridge.h" #include "transferserver.h" #include <opie2/oglobal.h> #ifdef Q_WS_QWS #include <qtopia/qcopenvelope_qws.h> #endif #include <qtopia/qpeapplication.h> #include <qtopia/version.h> #include <qtopia/config.h> #include <qdir.h> #include <qfile.h> #include <qtextstream.h> #include <qdatastream.h> #include <qcstring.h> #include <qstringlist.h> #include <qfileinfo.h> #include <qregexp.h> #include <qtimer.h> #ifdef Q_WS_QWS #include <qcopchannel_qws.h> #endif #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE #endif #ifndef Q_OS_WIN32 #include <pwd.h> #include <unistd.h> #include <sys/types.h> #endif #if defined(_OS_LINUX_) #include <shadow.h> #endif //#define INSECURE const int block_size = 51200; QCopBridge::QCopBridge( Q_UINT16 port, QObject *parent, const char* name ) : QServerSocket( port, 1, parent, name ), desktopChannel( 0 ), cardChannel( 0 ) { if ( !ok() ) qWarning( "Failed to bind to port %d", port ); else { #ifndef QT_NO_COP desktopChannel = new QCopChannel( "QPE/Desktop", this ); connect( desktopChannel, SIGNAL(received(const QCString &, const QByteArray &)), this, SLOT(desktopMessage( const QCString &, const QByteArray &)) ); cardChannel = new QCopChannel( "QPE/Card", this ); connect( cardChannel, SIGNAL(received(const QCString &, const QByteArray &)), this, SLOT(desktopMessage( const QCString &, const QByteArray &)) ); #endif } sendSync = FALSE; openConnections.setAutoDelete( TRUE ); authorizeConnections(); } QCopBridge::~QCopBridge() { #ifndef QT_NO_COP delete desktopChannel; #endif } void QCopBridge::authorizeConnections() { Config cfg("Security"); cfg.setGroup("SyncMode"); m_mode = Mode(cfg.readNumEntry("Mode", Sharp )); QListIterator<QCopBridgePI> it(openConnections); while ( it.current() ) { if ( !it.current()->verifyAuthorised() ) { disconnect ( it.current(), SIGNAL( connectionClosed( QCopBridgePI *) ), this, SLOT( closed( QCopBridgePI *) ) ); openConnections.removeRef( it.current() ); } else ++it; } } void QCopBridge::newConnection( int socket ) { QCopBridgePI *pi = new QCopBridgePI( socket, this ); openConnections.append( pi ); connect ( pi, SIGNAL( connectionClosed( QCopBridgePI *) ), this, SLOT( closed( QCopBridgePI *) ) ); /* ### libqtopia merge FIXME */ #if 0 QPEApplication::setTempScreenSaverMode( QPEApplication::DisableSuspend ); #endif #ifndef QT_NO_COP QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::DisableSuspend; #endif if ( sendSync ) { pi ->startSync(); sendSync = FALSE; } } void QCopBridge::closed( QCopBridgePI *pi ) { emit connectionClosed( pi->peerAddress() ); openConnections.removeRef( pi ); if ( openConnections.count() == 0 ) { /* ### FIXME libqtopia merge */ #if 0 QPEApplication::setTempScreenSaverMode( QPEApplication::Enable ); #endif #ifndef QT_NO_COP QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; #endif } } void QCopBridge::closeOpenConnections() { QCopBridgePI *pi; for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) pi->close(); } void QCopBridge::desktopMessage( const QCString &command, const QByteArray &data ) { if ( command == "startSync()" ) { // we need to buffer it a bit sendSync = TRUE; startTimer( 20000 ); } if ( m_mode & Qtopia1_7 ) { // send the command to all open connections QCopBridgePI *pi; for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) { pi->sendDesktopMessage( command, data ); } } - if ( m_mode & Sharp ) + if ( ( m_mode & Sharp ) || (m_mode & IntelliSync) ) sendDesktopMessageOld( command, data ); } #ifndef OPIE_NO_OLD_SYNC_CODE /* * Old compat mode */ void QCopBridge::sendDesktopMessageOld( const QCString& command, const QByteArray& args) { command.stripWhiteSpace(); int paren = command.find( "(" ); if ( paren <= 0 ) { qDebug("DesktopMessage: bad qcop syntax"); return; } QString params = command.mid( paren + 1 ); if ( params[params.length()-1] != ')' ) { qDebug("DesktopMessage: bad qcop syntax"); return; } params.truncate( params.length()-1 ); QStringList paramList = QStringList::split( ",", params ); QString data; if ( paramList.count() ) { QDataStream stream( args, IO_ReadOnly ); for ( QStringList::Iterator it = paramList.begin(); it != paramList.end(); ++it ) { QString str; if ( *it == "QString" ) { stream >> str; } else if ( *it == "QCString" ) { QCString cstr; stream >> cstr; str = QString::fromLocal8Bit( cstr ); } else if ( *it == "int" ) { int i; stream >> i; str = QString::number( i ); } else if ( *it == "bool" ) { int i; stream >> i; str = QString::number( i ); } else { qDebug(" cannot route the argument type %s throught the qcop bridge", (*it).latin1() ); return; } QString estr; for (int i=0; i<(int)str.length(); i++) { QChar ch = str[i]; if ( ch.row() ) goto quick; switch (ch.cell()) { case '&': estr.append( "&" ); break; case ' ': estr.append( "&0x20;" ); break; case '\n': estr.append( "&0x0d;" ); break; case '\r': estr.append( "&0x0a;" ); break; default: quick: estr.append(ch); } } data += " " + estr; } } QString sendCommand = QString(command.data()) + data; // send the command to all open connections QCopBridgePI *pi; for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) pi->sendDesktopMessage( sendCommand ); } #endif void QCopBridge::timerEvent( QTimerEvent * ) { sendSync = FALSE; killTimers(); } QCopBridgePI::QCopBridgePI( int socket, QObject *parent, const char* name ) : QSocket( parent, name ) { setSocket( socket ); peerport = peerPort(); peeraddress = peerAddress(); #ifndef INSECURE if ( !SyncAuthentication::isAuthorized(peeraddress) ) { state = Forbidden; close(); } else #endif { state = Connected; connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); QString intro="220 Qtopia "; intro += QPE_VERSION; intro += ";"; intro += "challenge="; intro += SyncAuthentication::serverId(); intro += ";"; // No tr intro += "loginname="; intro += SyncAuthentication::loginName(); intro += ";"; intro += "displayname="; intro += SyncAuthentication::ownerName(); intro += ";"; send( intro ); state = Wait_USER; } sendSync = FALSE; connect( this, SIGNAL( connectionClosed() ), SLOT( myConnectionClosed() ) ); // idle timer to close connections when not used anymore timer = new QTimer(this); connect( timer, SIGNAL(timeout()), this, SLOT(myConnectionClosed()) ); timer->start( 300000, TRUE ); } QCopBridgePI::~QCopBridgePI() { } bool QCopBridgePI::verifyAuthorised() { if ( !SyncAuthentication::isAuthorized(peerAddress()) ) { state = Forbidden; return FALSE; } return TRUE; } void QCopBridgePI::myConnectionClosed() { emit connectionClosed( this ); } void QCopBridgePI::sendDesktopMessage( const QString &msg ) { QString str = "CALL QPE/Desktop " + msg; // No tr send ( str ); } void QCopBridgePI::sendDesktopMessage( const QCString &msg, const QByteArray& data ) { if ( !isOpen() ) // eg. Forbidden return; const char hdr[]="CALLB QPE/Desktop "; writeBlock(hdr,sizeof(hdr)-1); writeBlock(msg,msg.length()); writeBlock(" ",1); QByteArray b64 = OGlobal::encodeBase64(data); writeBlock(b64.data(),b64.size()); writeBlock("\r\n",2); } void QCopBridgePI::send( const QString& msg ) { if ( !isOpen() ) // eg. Forbidden return; QTextStream os( this ); os << msg << endl; //qDebug( "sending qcop message: %s", msg.latin1() ); } void QCopBridgePI::read() { while ( canReadLine() ) { timer->start( 300000, TRUE ); process( readLine().stripWhiteSpace() ); } } void QCopBridgePI::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]; // we always respond to QUIT, regardless of state if ( cmd == "QUIT" ) { send( "211 Have a nice day!" ); // No tr close(); 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" ); // No tr return; } send( "331 User name ok, need password" ); // No tr 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" ); // No tr return; } send( "230 User logged in, proceed" ); // No tr state = Ready; if ( sendSync ) { sendDesktopMessage( "startSync()" ); sendSync = FALSE; } return; } // noop (NOOP) else if ( cmd == "NOOP" ) { send( "200 Command okay" ); // No tr } // call (CALL) else if ( cmd == "CALL" ) { // example: call QPE/System execute(QString) addressbook if ( msg.count() < 3 ) { send( "500 Syntax error, command unrecognized" ); // No tr } else { QString channel = msg[1]; QString command = msg[2]; command.stripWhiteSpace(); int paren = command.find( "(" ); if ( paren <= 0 ) { send( "500 Syntax error, command unrecognized" ); // No tr return; } QString params = command.mid( paren + 1 ); if ( params[(int)params.length()-1] != ')' ) { send( "500 Syntax error, command unrecognized" ); // No tr return; } params.truncate( params.length()-1 ); QByteArray buffer; QDataStream ds( buffer, IO_WriteOnly ); int msgId = 3; QStringList paramList = QStringList::split( ",", params ); if ( paramList.count() > msg.count() - 3 ) { send( "500 Syntax error, command unrecognized" ); // No tr return; } for ( QStringList::Iterator it = paramList.begin(); it != paramList.end(); ++it ) { QString arg = msg[msgId]; arg.replace( QRegExp("&0x20;"), " " ); arg.replace( QRegExp("&"), "&" ); arg.replace( QRegExp("&0x0d;"), "\n" ); arg.replace( QRegExp("&0x0a;"), "\r" ); if ( *it == "QString" ) ds << arg; else if ( *it == "QCString" ) ds << arg.local8Bit(); else if ( *it == "int" ) ds << arg.toInt(); else if ( *it == "bool" ) ds << arg.toInt(); else { send( "500 Syntax error, command unrecognized" ); // No tr return; } msgId++; } #ifndef QT_NO_COP if ( !QCopChannel::isRegistered( channel.latin1() ) ) { // send message back about it QString answer = "599 ChannelNotRegistered " + channel; send( answer ); return; } #endif #ifndef QT_NO_COP if ( paramList.count() ) QCopChannel::send( channel.latin1(), command.latin1(), buffer ); else QCopChannel::send( channel.latin1(), command.latin1() ); send( "200 Command okay" ); // No tr #endif } } // not implemented else send( "502 Command not implemented" ); // No tr } diff --git a/core/launcher/qcopbridge.h b/core/launcher/qcopbridge.h index 9483d9d..d5988cd 100644 --- a/core/launcher/qcopbridge.h +++ b/core/launcher/qcopbridge.h @@ -1,100 +1,101 @@ /********************************************************************** ** 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. ** **********************************************************************/ #ifndef __qcopbridge_h__ #define __qcopbridge_h__ #include <qtopia/global.h> #include <qserversocket.h> #include <qsocket.h> #include <qdir.h> #include <qfile.h> #include <qbuffer.h> class QFileInfo; class QCopBridgePI; class QCopChannel; class QTimer; class QCopBridge : public QServerSocket { Q_OBJECT public: - enum Mode { Qtopia1_7= 0x01, Sharp = 0x02, Both = Qtopia1_7 | Sharp }; + /* can not or anymore :) */ + enum Mode { Qtopia1_7= 0x01, Sharp = 0x02, IntelliSync = 0x04 }; QCopBridge( Q_UINT16 port, QObject *parent = 0, const char* name = 0 ); virtual ~QCopBridge(); void newConnection( int socket ); void closeOpenConnections(); void authorizeConnections(); public slots: void closed( QCopBridgePI *pi ); void desktopMessage( const QCString &call, const QByteArray & ); signals: void connectionClosed( const QHostAddress & ); protected: void timerEvent( QTimerEvent * ); void sendDesktopMessageOld( const QCString&, const QByteArray& ); private: QCopChannel *desktopChannel; QCopChannel *cardChannel; QList<QCopBridgePI> openConnections; bool sendSync; Mode m_mode; }; class QCopBridgePI : public QSocket { Q_OBJECT enum State { Connected, Wait_USER, Wait_PASS, Ready, Forbidden }; public: QCopBridgePI( int socket, QObject *parent = 0, const char* name = 0 ); virtual ~QCopBridgePI(); void sendDesktopMessage( const QString &msg ); void sendDesktopMessage( const QCString &msg, const QByteArray& ); void startSync() { sendSync = TRUE; } bool verifyAuthorised(); signals: void connectionClosed( QCopBridgePI *); protected slots: void read(); void send( const QString& msg ); void process( const QString& command ); void myConnectionClosed(); private: State state; Q_UINT16 peerport; QHostAddress peeraddress; bool sendSync; QTimer *timer; }; #endif diff --git a/core/launcher/transferserver.cpp b/core/launcher/transferserver.cpp index 9cb9d7a..8367a62 100644 --- a/core/launcher/transferserver.cpp +++ b/core/launcher/transferserver.cpp @@ -1,973 +1,991 @@ /********************************************************************** ** 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 <opie2/oglobal.h> #include <qtopia/qpeapplication.h> #ifndef Q_OS_WIN32 #include <pwd.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #ifndef Q_OS_MACX #include <shadow.h> #include <crypt.h> #endif /* Q_OS_MACX */ #else #include <stdlib.h> #include <time.h> #endif #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 <qtopia/qcopchannel_qws.h> #include <qtopia/process.h> #include <qtopia/global.h> #include <qtopia/config.h> #include <qtopia/private/contact.h> #include <qtopia/quuid.h> #include <qtopia/version.h> #ifdef Q_WS_QWS #include <qtopia/qcopenvelope_qws.h> #endif #include "transferserver.h" #include <qtopia/qprocess.h> const int block_size = 51200; TransferServer::TransferServer( Q_UINT16 port, QObject *parent, const char* name) : QServerSocket( port, 1, parent, name ) { connections.setAutoDelete( TRUE ); if ( !ok() ) qWarning( "Failed to bind to port %d", port ); } void TransferServer::authorizeConnections() { QListIterator<ServerPI> it(connections); while ( it.current() ) { if ( !it.current()->verifyAuthorised() ) { disconnect( it.current(), SIGNAL(connectionClosed(ServerPI *)), this, SLOT( closed(ServerPI *)) ); connections.removeRef( it.current() ); } else ++it; } } void TransferServer::closed(ServerPI *item) { connections.removeRef(item); } TransferServer::~TransferServer() { } void TransferServer::newConnection( int socket ) { ServerPI *ptr = new ServerPI( socket, this ); connect( ptr, SIGNAL(connectionClosed(ServerPI *)), this, SLOT( closed(ServerPI *)) ); connections.append( ptr ); } QString SyncAuthentication::serverId() { Config cfg("Security"); cfg.setGroup("Sync"); QString r = cfg.readEntry("serverid"); if ( r.isEmpty() ) { r = OGlobal::generateUuid(); 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::null; } QString SyncAuthentication::loginName() { struct passwd *pw = 0L; #ifndef Q_OS_WIN32 pw = getpwuid( geteuid() ); return QString::fromLocal8Bit( pw->pw_name ); #else //### revise return QString(); #endif } 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; } bool SyncAuthentication::checkUser( const QString& user ) { 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... struct passwd *pw = 0; struct spwd *spw = 0; 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 ); // 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); Config cfg("Security"); - cfg.setGroup("Sync"); - QString syncapp = cfg.readEntry("syncapp","Qtopia"); - - //No password needed if the user really wants it - if (syncapp == "IntelliSync") { - return TRUE; - } - - // Detect old Qtopia Desktop (no password) + cfg.setGroup("SyncMode"); + int mode = cfg.readNumEntry("Mode", 0x02 ); + + //No pass word needed if the user really needs it + if (mode & 0x04) { + QMessageBox unauth( + tr("Sync Connection"), + tr("<qt><p>An unauthorized system is requesting access to this device." + "<p>You chose IntelliSync so you may I allow or deny this connection.</qt>" ), + QMessageBox::Warning, + QMessageBox::Ok, QMessageBox::Cancel|QMessageBox::Default, QMessageBox::NoButton, + 0, QString::null, TRUE, WStyle_StaysOnTop); + unauth.setButtonText(QMessageBox::Ok, tr("Allow" ) ); + unauth.setButtonText(QMessageBox::Cancel, tr("Deny")); + switch( unauth.exec() ) { + case QMessageBox::Ok: + return TRUE; + break; + case QMessageBox::Cancel: + default: + denials++; + lastdenial=now; + return FALSE; + } + } + + // Detect old Qtopia Desktop (no password) and fail if ( password.isEmpty() ) { if ( denials < 3 || now > lastdenial+600 ) { QMessageBox unauth( 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 or change the security setting to use IntelliSync." ), QMessageBox::Warning, QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton, 0, QString::null, TRUE, WStyle_StaysOnTop); unauth.setButtonText(QMessageBox::Cancel, tr("Deny")); unauth.exec(); denials++; lastdenial=now; } return FALSE; } // Second, check sync password... static int lock=0; if ( lock ) return FALSE; ++lock; /* * we need to support old Sync software and QtopiaDesktop */ if ( password.left(6) == "Qtopia" || password.left(6) == "rootme" ) { Config cfg( "Security" ); cfg.setGroup("Sync"); QStringList pwds = cfg.readListEntry("Passwords",' '); for (QStringList::ConstIterator it=pwds.begin(); it!=pwds.end(); ++it) { #ifndef Q_OS_WIN32 QString cpassword = QString::fromLocal8Bit( crypt( password.mid(8).local8Bit(), (*it).left(2).latin1() ) ); #else // ### revise QString cpassword(""); #endif if ( *it == cpassword ) { lock--; return TRUE; } } // Unrecognized system. Be careful... QMessageBox unrecbox( 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."), QMessageBox::Warning, QMessageBox::Cancel, QMessageBox::Yes, QMessageBox::NoButton, 0, QString::null, TRUE, WStyle_StaysOnTop); unrecbox.setButtonText(QMessageBox::Cancel, tr("Deny")); unrecbox.setButtonText(QMessageBox::Yes, tr("Allow")); if ( (denials > 2 && now < lastdenial+600) || unrecbox.exec() != QMessageBox::Yes) { denials++; lastdenial=now; lock--; return FALSE; } else { const char salty[]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/."; char salt[2]; salt[0]= salty[rand() % (sizeof(salty)-1)]; salt[1]= salty[rand() % (sizeof(salty)-1)]; #ifndef Q_OS_WIN32 QString cpassword = QString::fromLocal8Bit( crypt( password.mid(8).local8Bit(), salt ) ); #else //### revise QString cpassword(""); #endif denials=0; pwds.prepend(cpassword); cfg.writeEntry("Passwords",pwds,' '); lock--; return TRUE; } } lock--; return FALSE; } ServerPI::ServerPI( int socket, QObject *parent, const char* name ) : QSocket( parent, name ) , dtp( 0 ), serversocket( 0 ), waitsocket( 0 ), storFileSize(-1) { state = Connected; setSocket( socket ); peerport = peerPort(); peeraddress = peerAddress(); #ifndef INSECURE if ( !SyncAuthentication::isAuthorized(peeraddress) ) { state = Forbidden; startTimer( 0 ); } else #endif { connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); passiv = FALSE; for( int i = 0; i < 4; i++ ) wait[i] = FALSE; send( "220 Qtopia " QPE_VERSION " FTP Server" ); // No tr 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 ) ) ); directory = QDir::currentDirPath(); static int p = 1024; while ( !serversocket || !serversocket->ok() ) { delete serversocket; serversocket = new ServerSocket( ++p, this ); } connect( serversocket, SIGNAL( newIncomming( int ) ), SLOT( newConnection( int ) ) ); } } ServerPI::~ServerPI() { close(); if ( dtp ) dtp->close(); delete dtp; delete serversocket; } bool ServerPI::verifyAuthorised() { if ( !SyncAuthentication::isAuthorized(peerAddress()) ) { state = Forbidden; return FALSE; } return TRUE; } void ServerPI::connectionClosed() { // qDebug( "Debug: Connection closed" ); emit connectionClosed(this); } void ServerPI::send( const QString& msg ) { QTextStream os( this ); os << msg << endl; //qDebug( "Reply: %s", msg.latin1() ); } void ServerPI::read() { while ( canReadLine() ) process( readLine().stripWhiteSpace() ); } bool ServerPI::checkReadFile( const QString& file ) { QString filename; if ( file[0] != "/" ) filename = directory.path() + "/" + file; else filename = file; QFileInfo fi( filename ); return ( fi.exists() && fi.isReadable() ); } bool ServerPI::checkWriteFile( const QString& file ) { QString filename; if ( file[0] != "/" ) filename = directory.path() + "/" + file; else filename = file; QFileInfo fi( filename ); 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!" ); // No tr close(); 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" ); // No tr return; } send( "331 User name ok, need password" ); // No tr 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" ); // No tr return; } send( "230 User logged in, proceed" ); // No tr state = Ready; return; } // ACCESS CONTROL COMMANDS // Only an ALLO sent immediately before STOR is valid. if ( cmd != "STOR" ) storFileSize = -1; // account (ACCT) if ( cmd == "ACCT" ) { // even wu-ftp does not support it send( "502 Command not implemented" ); // No tr } // change working directory (CWD) else if ( cmd == "CWD" ) { if ( !args.isEmpty() ) { if ( directory.cd( args, TRUE ) ) send( "250 Requested file action okay, completed" ); // No tr else send( "550 Requested action not taken" ); // No tr } else send( "500 Syntax error, command unrecognized" ); // No tr } // change to parent directory (CDUP) else if ( cmd == "CDUP" ) { if ( directory.cdUp() ) send( "250 Requested file action okay, completed" ); // No tr else send( "550 Requested action not taken" ); // No tr } // structure mount (SMNT) else if ( cmd == "SMNT" ) { // even wu-ftp does not support it send( "502 Command not implemented" ); // No tr } // reinitialize (REIN) else if ( cmd == "REIN" ) { // even wu-ftp does not support it send( "502 Command not implemented" ); // No tr } // TRANSFER PARAMETER COMMANDS // data port (PORT) else if ( cmd == "PORT" ) { if ( parsePort( arg ) ) send( "200 Command okay" ); // No tr else send( "500 Syntax error, command unrecognized" ); // No tr } // passive (PASV) else if ( cmd == "PASV" ) { passiv = TRUE; send( "227 Entering Passive Mode (" // No tr + 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" ); // No tr else send( "504 Command not implemented for that parameter" ); // No tr } // file structure (STRU) else if ( cmd == "STRU" ) { if ( arg.upper() == "F" ) send( "200 Command okay" ); // No tr else send( "504 Command not implemented for that parameter" ); // No tr } // transfer mode (MODE) else if ( cmd == "MODE" ) { if ( arg.upper() == "S" ) send( "200 Command okay" ); // No tr else send( "504 Command not implemented for that parameter" ); // No tr } // FTP SERVICE COMMANDS // retrieve (RETR) else if ( cmd == "RETR" ) if ( !args.isEmpty() && checkReadFile( absFilePath( args ) ) || backupRestoreGzip( absFilePath( args ) ) ) { send( "150 File status okay" ); // No tr sendFile( absFilePath( args ) ); } else { qDebug("550 Requested action not taken"); send( "550 Requested action not taken" ); // No tr } // store (STOR) else if ( cmd == "STOR" ) if ( !args.isEmpty() && checkWriteFile( absFilePath( args ) ) ) { send( "150 File status okay" ); // No tr retrieveFile( absFilePath( args ) ); } else send( "550 Requested action not taken" ); // No tr // store unique (STOU) else if ( cmd == "STOU" ) { send( "502 Command not implemented" ); // No tr } // append (APPE) else if ( cmd == "APPE" ) { send( "502 Command not implemented" ); // No tr } // allocate (ALLO) else if ( cmd == "ALLO" ) { storFileSize = args.toInt(); send( "200 Command okay" ); // No tr } // restart (REST) else if ( cmd == "REST" ) { send( "502 Command not implemented" ); // No tr } // rename from (RNFR) else if ( cmd == "RNFR" ) { renameFrom = QString::null; if ( args.isEmpty() ) send( "500 Syntax error, command unrecognized" ); // No tr else { QFile file( absFilePath( args ) ); if ( file.exists() ) { send( "350 File exists, ready for destination name" ); // No tr renameFrom = absFilePath( args ); } else send( "550 Requested action not taken" ); // No tr } } // rename to (RNTO) else if ( cmd == "RNTO" ) { if ( lastCommand != "RNFR" ) send( "503 Bad sequence of commands" ); // No tr else if ( args.isEmpty() ) send( "500 Syntax error, command unrecognized" ); // No tr else { QDir dir( absFilePath( args ) ); if ( dir.rename( renameFrom, absFilePath( args ), TRUE ) ) send( "250 Requested file action okay, completed." ); // No tr else send( "550 Requested action not taken" ); // No tr } } // abort (ABOR) else if ( cmd.contains( "ABOR" ) ) { dtp->close(); if ( dtp->dtpMode() != ServerDTP::Idle ) send( "426 Connection closed; transfer aborted" ); // No tr else send( "226 Closing data connection" ); // No tr } // delete (DELE) else if ( cmd == "DELE" ) { if ( args.isEmpty() ) send( "500 Syntax error, command unrecognized" ); // No tr else { QFile file( absFilePath( args ) ) ; if ( file.remove() ) { send( "250 Requested file action okay, completed" ); // No tr QCopEnvelope e("QPE/System", "linkChanged(QString)" ); e << file.name(); } else { send( "550 Requested action not taken" ); // No tr } } } // remove directory (RMD) else if ( cmd == "RMD" ) { if ( args.isEmpty() ) send( "500 Syntax error, command unrecognized" ); // No tr else { QDir dir; if ( dir.rmdir( absFilePath( args ), TRUE ) ) send( "250 Requested file action okay, completed" ); // No tr else send( "550 Requested action not taken" ); // No tr } } // make directory (MKD) else if ( cmd == "MKD" ) { if ( args.isEmpty() ) { qDebug(" Error: no arg"); send( "500 Syntax error, command unrecognized" ); // No tr } else { QDir dir; if ( dir.mkdir( absFilePath( args ), TRUE ) ) send( "250 Requested file action okay, completed." ); // No tr else send( "550 Requested action not taken" ); // No tr } } // 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" ); // No tr else send( "500 Syntax error, command unrecognized" ); // No tr } // 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" ); // No tr 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") ) // No tr 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" ); // No tr } // site parameters (SITE) else if ( cmd == "SITE" ) { send( "502 Command not implemented" ); // No tr } // system (SYST) else if ( cmd == "SYST" ) { send( "215 UNIX Type: L8" ); // No tr } // status (STAT) else if ( cmd == "STAT" ) { send( "502 Command not implemented" ); // No tr } // help (HELP ) else if ( cmd == "HELP" ) { send( "502 Command not implemented" ); // No tr } // noop (NOOP) else if ( cmd == "NOOP" ) { send( "200 Command okay" ); // No tr } // not implemented else send( "502 Command not implemented" ); // No tr lastCommand = cmd; } bool ServerPI::backupRestoreGzip( const QString &file ) { return (file.find( "backup" ) != -1 && // No tr file.findRev( ".tgz" ) == (int)file.length()-4 ); } bool ServerPI::backupRestoreGzip( const QString &file, QStringList &targets ) { if ( file.find( "backup" ) != -1 && // No tr 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 ); } } 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, storFileSize ); } } 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; } void ServerPI::dtpCompleted() { send( "226 Closing data connection, file transfer successful" ); // No tr 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(); storFileSize = -1; } void ServerPI::dtpFailed() { dtp->close(); waitsocket = 0; send( "451 Requested action aborted: local error in processing" ); // No tr storFileSize = -1; } void ServerPI::dtpError( int ) { dtp->close(); waitsocket = 0; send( "451 Requested action aborted: local error in processing" ); // No tr storFileSize = -1; } 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; // No tr 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; // type char if ( info->isDir() ) s += "d"; else if ( info->isSymLink() ) s += "l"; else s += "-"; // permisson string s += permissionString( info ) + " "; // 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(); s += QString::number( subdirs ).rightJustify( 3, ' ', TRUE ) + " "; // owner QString o = info->owner(); if ( o.isEmpty() ) o = QString::number(info->ownerId()); s += o.leftJustify( 8, ' ', TRUE ) + " "; // group QString g = info->group(); if ( g.isEmpty() ) g = QString::number(info->groupId()); s += g.leftJustify( 8, ' ', TRUE ) + " "; // file size in bytes s += QString::number( info->size() ).rightJustify( 9, ' ', TRUE ) + " "; // last modified date QDate date = info->lastModified().date(); |