• Skip to content
  • Skip to link menu
KDE 4.5 API Reference
  • KDE API Reference
  • KDE-PIM Libraries
  • Sitemap
  • Contact Us
 

akonadi

session.cpp

00001 /*
00002     Copyright (c) 2007 Volker Krause <vkrause@kde.org>
00003 
00004     This library is free software; you can redistribute it and/or modify it
00005     under the terms of the GNU Library General Public License as published by
00006     the Free Software Foundation; either version 2 of the License, or (at your
00007     option) any later version.
00008 
00009     This library is distributed in the hope that it will be useful, but WITHOUT
00010     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00011     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
00012     License for more details.
00013 
00014     You should have received a copy of the GNU Library General Public License
00015     along with this library; see the file COPYING.LIB.  If not, write to the
00016     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
00017     02110-1301, USA.
00018 */
00019 
00020 #include "session.h"
00021 #include "session_p.h"
00022 
00023 #include "imapparser_p.h"
00024 #include "job.h"
00025 #include "job_p.h"
00026 #include "servermanager.h"
00027 #include "servermanager_p.h"
00028 #include "xdgbasedirs_p.h"
00029 
00030 #include <kdebug.h>
00031 #include <klocale.h>
00032 
00033 #include <QCoreApplication>
00034 #include <QtCore/QDir>
00035 #include <QtCore/QQueue>
00036 #include <QtCore/QThreadStorage>
00037 #include <QtCore/QTimer>
00038 #include <QSettings>
00039 
00040 #include <QtNetwork/QLocalSocket>
00041 #include <QtNetwork/QTcpSocket>
00042 
00043 // ### FIXME pipelining got broken by switching result emission in JobPrivate::handleResponse to delayed emission
00044 // in order to work around exec() deadlocks. As a result of that Session knows to late about a finished job and still
00045 // sends responses for the next one to the already finished one
00046 #define PIPELINE_LENGTH 0
00047 //#define PIPELINE_LENGTH 2
00048 
00049 using namespace Akonadi;
00050 
00051 
00052 //@cond PRIVATE
00053 
00054 void SessionPrivate::startNext()
00055 {
00056   QTimer::singleShot( 0, mParent, SLOT( doStartNext() ) );
00057 }
00058 
00059 void SessionPrivate::reconnect()
00060 {
00061   QLocalSocket *localSocket = qobject_cast<QLocalSocket*>( socket );
00062   if ( localSocket && (localSocket->state() == QLocalSocket::ConnectedState
00063                        || localSocket->state() == QLocalSocket::ConnectingState ) ) {
00064     // nothing to do, we are still/already connected
00065     return;
00066   }
00067 
00068   QTcpSocket *tcpSocket = qobject_cast<QTcpSocket*>( socket );
00069   if ( tcpSocket && (tcpSocket->state() == QTcpSocket::ConnectedState
00070                      || tcpSocket->state() == QTcpSocket::ConnectingState ) ) {
00071     // same here, but for TCP
00072     return;
00073   }
00074 
00075   // try to figure out where to connect to
00076   QString serverAddress;
00077   quint16 port = 0;
00078   bool useTcp = false;
00079 
00080   // env var has precedence
00081   const QByteArray serverAddressEnvVar = qgetenv( "AKONADI_SERVER_ADDRESS" );
00082   if ( !serverAddressEnvVar.isEmpty() ) {
00083     const int pos = serverAddressEnvVar.indexOf( ':' );
00084     const QByteArray protocol = serverAddressEnvVar.left( pos  );
00085     QMap<QString, QString> options;
00086     foreach ( const QString &entry, QString::fromLatin1( serverAddressEnvVar.mid( pos + 1 ) ).split( QLatin1Char(',') ) ) {
00087       const QStringList pair = entry.split( QLatin1Char('=') );
00088       if ( pair.size() != 2 )
00089         continue;
00090       options.insert( pair.first(), pair.last() );
00091     }
00092     kDebug() << protocol << options;
00093 
00094     if ( protocol == "tcp" ) {
00095       serverAddress = options.value( QLatin1String( "host" ) );
00096       port = options.value( QLatin1String( "port" ) ).toUInt();
00097       useTcp = true;
00098     } else if ( protocol == "unix" ) {
00099       serverAddress = options.value( QLatin1String( "path" ) );
00100     } else if ( protocol == "pipe" ) {
00101       serverAddress = options.value( QLatin1String( "name" ) );
00102     }
00103   }
00104 
00105   // try config file next, fall back to defaults if that fails as well
00106   if ( serverAddress.isEmpty() ) {
00107     const QString connectionConfigFile = XdgBaseDirs::akonadiConnectionConfigFile();
00108     const QFileInfo fileInfo( connectionConfigFile );
00109     if ( !fileInfo.exists() ) {
00110       kDebug() << "Akonadi Client Session: connection config file '"
00111                   "akonadi/akonadiconnectionrc' can not be found in"
00112                << XdgBaseDirs::homePath( "config" ) << "nor in any of"
00113                << XdgBaseDirs::systemPathList( "config" );
00114     }
00115     const QSettings connectionSettings( connectionConfigFile, QSettings::IniFormat );
00116 
00117 #ifdef Q_OS_WIN  //krazy:exclude=cpp
00118     serverAddress = connectionSettings.value( QLatin1String( "Data/NamedPipe" ), QLatin1String( "Akonadi" ) ).toString();
00119 #else
00120     const QString defaultSocketDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi" ) );
00121     serverAddress = connectionSettings.value( QLatin1String( "Data/UnixPath" ), defaultSocketDir + QLatin1String( "/akonadiserver.socket" ) ).toString();
00122 #endif
00123   }
00124 
00125   // create sockets if not yet done, note that this does not yet allow changing socket types on the fly
00126   // but that's probably not something we need to support anyway
00127   if ( !socket ) {
00128     if ( !useTcp ) {
00129       socket = localSocket = new QLocalSocket( mParent );
00130       mParent->connect( localSocket, SIGNAL( error( QLocalSocket::LocalSocketError ) ), SLOT( socketError( QLocalSocket::LocalSocketError ) ) );
00131     } else {
00132       socket = tcpSocket = new QTcpSocket( mParent );
00133       mParent->connect( tcpSocket, SIGNAL( error( QAbstractSocket::SocketError ) ), SLOT( socketError( QAbstractSocket::SocketError ) ) );
00134     }
00135     mParent->connect( socket, SIGNAL( disconnected() ), SLOT( socketDisconnected() ) );
00136     mParent->connect( socket, SIGNAL( readyRead() ), SLOT( dataReceived() ) );
00137   }
00138 
00139   // actually do connect
00140   kDebug() << "connectToServer" << serverAddress;
00141   if ( !useTcp ) {
00142     localSocket->connectToServer( serverAddress );
00143   } else {
00144     tcpSocket->connectToHost( serverAddress, port );
00145   }
00146 }
00147 
00148 void SessionPrivate::socketError( QLocalSocket::LocalSocketError )
00149 {
00150   Q_ASSERT( mParent->sender() == socket );
00151   kWarning() << "Socket error occurred:" << qobject_cast<QLocalSocket*>( socket )->errorString();
00152   socketDisconnected();
00153 }
00154 
00155 void SessionPrivate::socketError( QAbstractSocket::SocketError )
00156 {
00157   Q_ASSERT( mParent->sender() == socket );
00158   kWarning() << "Socket error occurred:" << qobject_cast<QTcpSocket*>( socket )->errorString();
00159   socketDisconnected();
00160 }
00161 
00162 void SessionPrivate::socketDisconnected()
00163 {
00164   if ( currentJob )
00165     currentJob->d_ptr->lostConnection();
00166   connected = false;
00167 }
00168 
00169 void SessionPrivate::dataReceived()
00170 {
00171   while ( socket->bytesAvailable() > 0 ) {
00172     if ( parser->continuationSize() > 1 ) {
00173       const QByteArray data = socket->read( qMin( socket->bytesAvailable(), parser->continuationSize() - 1 ) );
00174       parser->parseBlock( data );
00175     } else if ( socket->canReadLine() ) {
00176       if ( !parser->parseNextLine( socket->readLine() ) )
00177         continue; // response not yet completed
00178 
00179       // handle login response
00180       if ( parser->tag() == QByteArray( "0" ) ) {
00181         if ( parser->data().startsWith( "OK" ) ) { //krazy:exclude=strings
00182           connected = true;
00183           startNext();
00184         } else {
00185           kWarning() << "Unable to login to Akonadi server:" << parser->data();
00186           socket->close();
00187           QTimer::singleShot( 1000, mParent, SLOT( reconnect() ) );
00188         }
00189       }
00190 
00191       // send login command
00192       if ( parser->tag() == "*" && parser->data().startsWith( "OK Akonadi" ) ) {
00193         const int pos = parser->data().indexOf( "[PROTOCOL" );
00194         if ( pos > 0 ) {
00195           qint64 tmp = 0;
00196           ImapParser::parseNumber( parser->data(), tmp, 0, pos + 9 );
00197           protocolVersion = tmp;
00198           Internal::setServerProtocolVersion( tmp );
00199         }
00200         kDebug() << "Server protocol version is:" << protocolVersion;
00201 
00202         writeData( "0 LOGIN " + ImapParser::quote( sessionId ) + '\n' );
00203 
00204       // work for the current job
00205       } else {
00206         if ( currentJob )
00207           currentJob->d_ptr->handleResponse( parser->tag(), parser->data() );
00208       }
00209 
00210       // reset parser stuff
00211       parser->reset();
00212     } else {
00213       break; // nothing we can do for now
00214     }
00215   }
00216 }
00217 
00218 bool SessionPrivate::canPipelineNext()
00219 {
00220   if ( queue.isEmpty() || pipeline.count() >= PIPELINE_LENGTH )
00221     return false;
00222   if ( pipeline.isEmpty() && currentJob )
00223     return currentJob->d_ptr->mWriteFinished;
00224   if ( !pipeline.isEmpty() )
00225     return pipeline.last()->d_ptr->mWriteFinished;
00226   return false;
00227 }
00228 
00229 void SessionPrivate::doStartNext()
00230 {
00231   if ( !connected || (queue.isEmpty() && pipeline.isEmpty()) )
00232     return;
00233   if ( canPipelineNext() ) {
00234     Akonadi::Job *nextJob = queue.dequeue();
00235     pipeline.enqueue( nextJob );
00236     startJob( nextJob );
00237   }
00238   if ( jobRunning )
00239     return;
00240   jobRunning = true;
00241   if ( !pipeline.isEmpty() ) {
00242     currentJob = pipeline.dequeue();
00243   } else {
00244     currentJob = queue.dequeue();
00245     startJob( currentJob );
00246   }
00247 }
00248 
00249 void SessionPrivate::startJob( Job *job )
00250 {
00251   if ( protocolVersion < minimumProtocolVersion() ) {
00252     job->setError( Job::ProtocolVersionMismatch );
00253     job->setErrorText( i18n( "Protocol version %1 found, expected at least %2", protocolVersion, minimumProtocolVersion() ) );
00254     job->emitResult();
00255   } else {
00256     job->d_ptr->startQueued();
00257   }
00258 }
00259 
00260 void SessionPrivate::endJob( Job *job )
00261 {
00262   job->emitResult();
00263 }
00264 
00265 void SessionPrivate::jobDone(KJob * job)
00266 {
00267   // ### careful, this method can be called from the QObject dtor of job (see jobDestroyed() below)
00268   // so don't call any methods on job itself
00269   if ( job == currentJob ) {
00270     if ( pipeline.isEmpty() ) {
00271       jobRunning = false;
00272       currentJob = 0;
00273     } else {
00274       currentJob = pipeline.dequeue();
00275     }
00276     startNext();
00277   } else {
00278     // non-current job finished, likely canceled while still in the queue
00279     queue.removeAll( static_cast<Akonadi::Job*>( job ) );
00280     // ### likely not enough to really cancel already running jobs
00281     pipeline.removeAll( static_cast<Akonadi::Job*>( job ) );
00282   }
00283 }
00284 
00285 void SessionPrivate::jobWriteFinished( Akonadi::Job* job )
00286 {
00287   Q_ASSERT( (job == currentJob && pipeline.isEmpty()) || (job = pipeline.last()) );
00288   Q_UNUSED( job );
00289 
00290   startNext();
00291 }
00292 
00293 void SessionPrivate::jobDestroyed(QObject * job)
00294 {
00295   // careful, accessing non-QObject methods of job will fail here already
00296   jobDone( static_cast<KJob*>( job ) );
00297 }
00298 
00299 void SessionPrivate::addJob(Job * job)
00300 {
00301   queue.append( job );
00302   QObject::connect( job, SIGNAL( result( KJob* ) ), mParent, SLOT( jobDone( KJob* ) ) );
00303   QObject::connect( job, SIGNAL( writeFinished( Akonadi::Job* ) ), mParent, SLOT( jobWriteFinished( Akonadi::Job* ) ) );
00304   QObject::connect( job, SIGNAL( destroyed( QObject* ) ), mParent, SLOT( jobDestroyed( QObject* ) ) );
00305   startNext();
00306 }
00307 
00308 int SessionPrivate::nextTag()
00309 {
00310   return theNextTag++;
00311 }
00312 
00313 void SessionPrivate::writeData(const QByteArray & data)
00314 {
00315   if ( socket )
00316     socket->write( data );
00317   else
00318     kWarning() << "Trying to write while session is disconnected!" << kBacktrace();
00319 }
00320 
00321 void SessionPrivate::serverStateChanged( ServerManager::State state )
00322 {
00323   if ( state == ServerManager::Running && !connected )
00324     reconnect();
00325 }
00326 
00327 //@endcond
00328 
00329 
00330 SessionPrivate::SessionPrivate( Session *parent )
00331     : mParent( parent ), socket( 0 ), protocolVersion( 0 ), currentJob( 0 ), parser( 0 )
00332 {
00333 }
00334 
00335 void SessionPrivate::init( const QByteArray &id )
00336 {
00337   kDebug() << id;
00338   parser = new ImapParser();
00339 
00340   if ( !id.isEmpty() ) {
00341     sessionId = id;
00342   } else {
00343     sessionId = QCoreApplication::instance()->applicationName().toUtf8()
00344         + '-' + QByteArray::number( qrand() );
00345   }
00346 
00347   connected = false;
00348   theNextTag = 1;
00349   jobRunning = false;
00350 
00351   if ( ServerManager::state() == ServerManager::NotRunning )
00352     ServerManager::start();
00353   mParent->connect( ServerManager::self(), SIGNAL( stateChanged( Akonadi::ServerManager::State ) ),
00354                     SLOT( serverStateChanged( Akonadi::ServerManager::State ) ) );
00355 
00356   reconnect();
00357 }
00358 
00359 Session::Session(const QByteArray & sessionId, QObject * parent) :
00360     QObject( parent ),
00361     d( new SessionPrivate( this ) )
00362 {
00363   d->init( sessionId );
00364 }
00365 
00366 Session::Session( SessionPrivate *dd, const QByteArray & sessionId, QObject * parent)
00367     : QObject( parent ),
00368     d( dd )
00369 {
00370   d->init( sessionId );
00371 }
00372 
00373 Session::~Session()
00374 {
00375   clear();
00376   delete d;
00377 }
00378 
00379 QByteArray Session::sessionId() const
00380 {
00381   return d->sessionId;
00382 }
00383 
00384 QThreadStorage<Session*> instances;
00385 
00386 void SessionPrivate::createDefaultSession( const QByteArray &sessionId )
00387 {
00388   Q_ASSERT_X( !sessionId.isEmpty(), "SessionPrivate::createDefaultSession",
00389               "You tried to create a default session with empty session id!" );
00390   Q_ASSERT_X( !instances.hasLocalData(), "SessionPrivate::createDefaultSession",
00391               "You tried to create a default session twice!" );
00392 
00393   instances.setLocalData( new Session( sessionId ) );
00394 }
00395 
00396 Session* Session::defaultSession()
00397 {
00398   if ( !instances.hasLocalData() )
00399     instances.setLocalData( new Session() );
00400   return instances.localData();
00401 }
00402 
00403 void Session::clear()
00404 {
00405   foreach ( Job* job, d->queue )
00406     job->kill( KJob::EmitResult );
00407   d->queue.clear();
00408   foreach ( Job* job, d->pipeline )
00409     job->kill( KJob::EmitResult );
00410   d->pipeline.clear();
00411   if ( d->currentJob )
00412     d->currentJob->kill( KJob::EmitResult );
00413   d->jobRunning = false;
00414   d->connected = false;
00415   if ( d->socket )
00416     d->socket->disconnect( this ); // prevent signal emitted from close() causing mayhem - we might be called from ~QThreadStorage!
00417   delete d->socket;
00418   d->socket = 0;
00419   QMetaObject::invokeMethod( this, "reconnect", Qt::QueuedConnection ); // avoids reconnecting in the dtor
00420 }
00421 
00422 #include "session.moc"

akonadi

Skip menu "akonadi"
  • Main Page
  • Modules
  • Namespace List
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Namespace Members
  • Class Members
  • Related Pages

KDE-PIM Libraries

Skip menu "KDE-PIM Libraries"
  • akonadi
  •   contact
  •   kmime
  • kabc
  • kblog
  • kcal
  • kholidays
  • kimap
  • kioslave
  •   imap4
  •   mbox
  •   nntp
  • kldap
  • kmime
  • kontactinterface
  • kpimidentities
  • kpimtextedit
  •   richtextbuilders
  • kpimutils
  • kresources
  • ktnef
  • kxmlrpcclient
  • mailtransport
  • microblog
  • qgpgme
  • syndication
  •   atom
  •   rdf
  •   rss2
Generated for KDE-PIM Libraries by doxygen 1.7.1
This website is maintained by Adriaan de Groot and Allen Winter.
KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal