• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdepimlibs-4.10.0 API Reference
  • KDE Home
  • Contact Us
 

KIMAP Library

  • kimap
sessionthread.cpp
1 /*
2  Copyright (c) 2009 Kevin Ottens <ervin@kde.org>
3 
4  This library is free software; you can redistribute it and/or modify it
5  under the terms of the GNU Library General Public License as published by
6  the Free Software Foundation; either version 2 of the License, or (at your
7  option) any later version.
8 
9  This library is distributed in the hope that it will be useful, but WITHOUT
10  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
12  License for more details.
13 
14  You should have received a copy of the GNU Library General Public License
15  along with this library; see the file COPYING.LIB. If not, write to the
16  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  02110-1301, USA.
18 */
19 
20 #include "sessionthread_p.h"
21 
22 #include <QtCore/QDebug>
23 #include <QtCore/QTimer>
24 
25 #include <KDE/KDebug>
26 
27 #include "imapstreamparser.h"
28 #include "message_p.h"
29 #include "session.h"
30 
31 using namespace KIMAP;
32 
33 Q_DECLARE_METATYPE( KTcpSocket::Error )
34 Q_DECLARE_METATYPE( KSslErrorUiData )
35 static const int _kimap_socketErrorTypeId = qRegisterMetaType<KTcpSocket::Error>();
36 static const int _kimap_sslErrorUiData = qRegisterMetaType<KSslErrorUiData>();
37 
38 SessionThread::SessionThread( const QString &hostName, quint16 port, Session *parent )
39  : QThread(), m_hostName( hostName ), m_port( port ),
40  m_session( parent ), m_socket( 0 ), m_stream( 0 ), m_mutex( QMutex::Recursive ),
41  m_encryptedMode( false ),
42  triedSslVersions( 0 ), doSslFallback( false )
43 {
44  // Yeah, sounds weird, but QThread object is linked to the parent
45  // thread not to itself, and I'm too lazy to introduce yet another
46  // internal QObject
47  moveToThread( this );
48 }
49 
50 SessionThread::~SessionThread()
51 {
52  // don't call quit() directly, this will deadlock in wait() if exec() hasn't run yet
53  QMetaObject::invokeMethod( this, "quit" );
54  if ( !wait( 10 * 1000 ) ) {
55  kWarning() << "Session thread refuses to die, killing harder...";
56  terminate();
57  // Make sure to wait until it's done, otherwise it can crash when the pthread callback is called
58  wait();
59  }
60 }
61 
62 void SessionThread::sendData( const QByteArray &payload )
63 {
64  QMutexLocker locker( &m_mutex );
65 
66  m_dataQueue.enqueue( payload );
67  QTimer::singleShot( 0, this, SLOT(writeDataQueue()) );
68 }
69 
70 void SessionThread::writeDataQueue()
71 {
72  QMutexLocker locker( &m_mutex );
73 
74  while ( !m_dataQueue.isEmpty() ) {
75  m_socket->write( m_dataQueue.dequeue() );
76  }
77 }
78 
79 void SessionThread::readMessage()
80 {
81  QMutexLocker locker( &m_mutex );
82 
83  if ( m_stream->availableDataSize() == 0 ) {
84  return;
85  }
86 
87  Message message;
88  QList<Message::Part> *payload = &message.content;
89 
90  try {
91  while ( !m_stream->atCommandEnd() ) {
92  if ( m_stream->hasString() ) {
93  QByteArray string = m_stream->readString();
94  if ( string == "NIL" ) {
95  *payload << Message::Part( QList<QByteArray>() );
96  } else {
97  *payload << Message::Part( string );
98  }
99  } else if ( m_stream->hasList() ) {
100  *payload << Message::Part( m_stream->readParenthesizedList() );
101  } else if ( m_stream->hasResponseCode() ) {
102  payload = &message.responseCode;
103  } else if ( m_stream->atResponseCodeEnd() ) {
104  payload = &message.content;
105  } else if ( m_stream->hasLiteral() ) {
106  QByteArray literal;
107  while ( !m_stream->atLiteralEnd() ) {
108  literal += m_stream->readLiteralPart();
109  }
110  *payload << Message::Part( literal );
111  } else {
112  // Oops! Something really bad happened, we won't be able to recover
113  // so close the socket immediately
114  qWarning( "Inconsistent state, probably due to some packet loss" );
115  doCloseSocket();
116  return;
117  }
118  }
119 
120  emit responseReceived( message );
121 
122  } catch ( KIMAP::ImapParserException e ) {
123  qWarning() << "The stream parser raised an exception:" << e.what();
124  }
125 
126  if ( m_stream->availableDataSize() > 1 ) {
127  QTimer::singleShot( 0, this, SLOT(readMessage()) );
128  }
129 
130 }
131 
132 void SessionThread::closeSocket()
133 {
134  QTimer::singleShot( 0, this, SLOT(doCloseSocket()) );
135 }
136 
137 void SessionThread::doCloseSocket()
138 {
139  m_encryptedMode = false;
140  m_socket->close();
141 }
142 
143 void SessionThread::reconnect()
144 {
145  QMutexLocker locker( &m_mutex );
146 
147  if ( m_socket->state() != SessionSocket::ConnectedState &&
148  m_socket->state() != SessionSocket::ConnectingState ) {
149  if ( m_encryptedMode ) {
150  m_socket->connectToHostEncrypted( m_hostName, m_port );
151  } else {
152  m_socket->connectToHost( m_hostName, m_port );
153  }
154  }
155 }
156 
157 void SessionThread::run()
158 {
159  m_socket = new SessionSocket;
160  m_stream = new ImapStreamParser( m_socket );
161  connect( m_socket, SIGNAL(readyRead()),
162  this, SLOT(readMessage()), Qt::QueuedConnection );
163 
164  connect( m_socket, SIGNAL(disconnected()),
165  this, SLOT(socketDisconnected()) );
166  connect( m_socket, SIGNAL(connected()),
167  m_session, SLOT(socketConnected()) );
168  connect( m_socket, SIGNAL(error(KTcpSocket::Error)),
169  this, SLOT(socketError()) );
170  connect( m_socket, SIGNAL(bytesWritten(qint64)),
171  m_session, SLOT(socketActivity()) );
172  if ( m_socket->metaObject()->indexOfSignal( "encryptedBytesWritten(qint64)" ) > -1 ) {
173  connect( m_socket, SIGNAL(encryptedBytesWritten(qint64)), // needs kdelibs > 4.8
174  m_session, SLOT(socketActivity()) );
175  }
176  connect( m_socket, SIGNAL(readyRead()),
177  m_session, SLOT(socketActivity()) );
178 
179  connect( this, SIGNAL(responseReceived(KIMAP::Message)),
180  m_session, SLOT(responseReceived(KIMAP::Message)) );
181 
182  QTimer::singleShot( 0, this, SLOT(reconnect()) );
183  exec();
184 
185  delete m_stream;
186  delete m_socket;
187 }
188 
189 void SessionThread::startSsl(const KTcpSocket::SslVersion &version)
190 {
191  QMutexLocker locker( &m_mutex );
192 
193  if ( version == KTcpSocket::AnySslVersion ) {
194  doSslFallback = true;
195  if ( m_socket->advertisedSslVersion() == KTcpSocket::UnknownSslVersion ) {
196  m_socket->setAdvertisedSslVersion( KTcpSocket::AnySslVersion );
197  } else if ( !( triedSslVersions & KTcpSocket::TlsV1 ) ) {
198  triedSslVersions |= KTcpSocket::TlsV1;
199  m_socket->setAdvertisedSslVersion( KTcpSocket::TlsV1 );
200  } else if ( !( triedSslVersions & KTcpSocket::SslV3 ) ) {
201  triedSslVersions |= KTcpSocket::SslV3;
202  m_socket->setAdvertisedSslVersion( KTcpSocket::SslV3 );
203  } else if ( !( triedSslVersions & KTcpSocket::SslV2 ) ) {
204  triedSslVersions |= KTcpSocket::SslV2;
205  m_socket->setAdvertisedSslVersion( KTcpSocket::SslV2 );
206  doSslFallback = false;
207  }
208  } else {
209  m_socket->setAdvertisedSslVersion( version );
210  }
211 
212  m_socket->ignoreSslErrors();
213  connect( m_socket, SIGNAL(encrypted()), this, SLOT(sslConnected()) );
214  m_socket->startClientEncryption();
215 }
216 
217 void SessionThread::socketDisconnected()
218 {
219  if ( doSslFallback ) {
220  reconnect();
221  } else {
222  QMetaObject::invokeMethod( m_session, "socketDisconnected" );
223  }
224 }
225 
226 void SessionThread::socketError()
227 {
228  QMutexLocker locker( &m_mutex );
229  if ( doSslFallback ) {
230  locker.unlock(); // disconnectFromHost() ends up calling reconnect()
231  m_socket->disconnectFromHost();
232  } else {
233  QMetaObject::invokeMethod( m_session, "socketError" );
234  }
235 }
236 
237 void SessionThread::sslConnected()
238 {
239  QMutexLocker locker( &m_mutex );
240  KSslCipher cipher = m_socket->sessionCipher();
241 
242  if ( m_socket->sslErrors().count() > 0 ||
243  m_socket->encryptionMode() != KTcpSocket::SslClientMode ||
244  cipher.isNull() || cipher.usedBits() == 0 ) {
245  kDebug() << "Initial SSL handshake failed. cipher.isNull() is" << cipher.isNull()
246  << ", cipher.usedBits() is" << cipher.usedBits()
247  << ", the socket says:" << m_socket->errorString()
248  << "and the list of SSL errors contains"
249  << m_socket->sslErrors().count() << "items.";
250  KSslErrorUiData errorData( m_socket );
251  emit sslError( errorData );
252  } else {
253  doSslFallback = false;
254  kDebug() << "TLS negotiation done.";
255  m_encryptedMode = true;
256  emit encryptionNegotiationResult( true, m_socket->negotiatedSslVersion() );
257  }
258 }
259 
260 void SessionThread::sslErrorHandlerResponse(bool response)
261 {
262  QMutexLocker locker( &m_mutex );
263  if ( response ) {
264  m_encryptedMode = true;
265  emit encryptionNegotiationResult( true, m_socket->negotiatedSslVersion() );
266  } else {
267  m_encryptedMode = false;
268  //reconnect in unencrypted mode, so new commands can be issued
269  m_socket->disconnectFromHost();
270  m_socket->waitForDisconnected();
271  m_socket->connectToHost( m_hostName, m_port );
272  emit encryptionNegotiationResult( false, KTcpSocket::UnknownSslVersion );
273  }
274 }
275 
276 #include "moc_sessionthread_p.cpp"
277 
This file is part of the KDE documentation.
Documentation copyright © 1996-2013 The KDE developers.
Generated on Fri Mar 8 2013 21:48:24 by doxygen 1.8.3.1 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.

KIMAP Library

Skip menu "KIMAP Library"
  • Main Page
  • Namespace List
  • Namespace Members
  • Alphabetical List
  • Class List
  • Class Hierarchy
  • Class Members
  • File List
  • Related Pages

kdepimlibs-4.10.0 API Reference

Skip menu "kdepimlibs-4.10.0 API Reference"
  • akonadi
  •   contact
  •   kmime
  •   socialutils
  • kabc
  • kalarmcal
  • kblog
  • kcal
  • kcalcore
  • kcalutils
  • kholidays
  • kimap
  • kioslave
  •   imap4
  •   mbox
  •   nntp
  • kldap
  • kmbox
  • kmime
  • kontactinterface
  • kpimidentities
  • kpimtextedit
  • kpimutils
  • kresources
  • ktnef
  • kxmlrpcclient
  • mailtransport
  • microblog
  • qgpgme
  • syndication
  •   atom
  •   rdf
  •   rss2
Report problems with this website to our bug tracking system.
Contact the specific authors with questions and comments about the page contents.

KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal