• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdepimlibs-4.10.1 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  // Delay the call to socketDisconnected so that it finishes disconnecting before we call reconnect()
165  connect( m_socket, SIGNAL(disconnected()),
166  this, SLOT(socketDisconnected()), Qt::QueuedConnection );
167  connect( m_socket, SIGNAL(connected()),
168  m_session, SLOT(socketConnected()) );
169  connect( m_socket, SIGNAL(error(KTcpSocket::Error)),
170  this, SLOT(socketError()) );
171  connect( m_socket, SIGNAL(bytesWritten(qint64)),
172  m_session, SLOT(socketActivity()) );
173  if ( m_socket->metaObject()->indexOfSignal( "encryptedBytesWritten(qint64)" ) > -1 ) {
174  connect( m_socket, SIGNAL(encryptedBytesWritten(qint64)), // needs kdelibs > 4.8
175  m_session, SLOT(socketActivity()) );
176  }
177  connect( m_socket, SIGNAL(readyRead()),
178  m_session, SLOT(socketActivity()) );
179 
180  connect( this, SIGNAL(responseReceived(KIMAP::Message)),
181  m_session, SLOT(responseReceived(KIMAP::Message)) );
182 
183  QTimer::singleShot( 0, this, SLOT(reconnect()) );
184  exec();
185 
186  delete m_stream;
187  delete m_socket;
188 }
189 
190 void SessionThread::startSsl(const KTcpSocket::SslVersion &version)
191 {
192  QMutexLocker locker( &m_mutex );
193 
194  if ( version == KTcpSocket::AnySslVersion ) {
195  doSslFallback = true;
196  if ( m_socket->advertisedSslVersion() == KTcpSocket::UnknownSslVersion ) {
197  m_socket->setAdvertisedSslVersion( KTcpSocket::AnySslVersion );
198  } else if ( !( triedSslVersions & KTcpSocket::TlsV1 ) ) {
199  triedSslVersions |= KTcpSocket::TlsV1;
200  m_socket->setAdvertisedSslVersion( KTcpSocket::TlsV1 );
201  } else if ( !( triedSslVersions & KTcpSocket::SslV3 ) ) {
202  triedSslVersions |= KTcpSocket::SslV3;
203  m_socket->setAdvertisedSslVersion( KTcpSocket::SslV3 );
204  } else if ( !( triedSslVersions & KTcpSocket::SslV2 ) ) {
205  triedSslVersions |= KTcpSocket::SslV2;
206  m_socket->setAdvertisedSslVersion( KTcpSocket::SslV2 );
207  doSslFallback = false;
208  }
209  } else {
210  m_socket->setAdvertisedSslVersion( version );
211  }
212 
213  m_socket->ignoreSslErrors();
214  connect( m_socket, SIGNAL(encrypted()), this, SLOT(sslConnected()) );
215  m_socket->startClientEncryption();
216 }
217 
218 void SessionThread::socketDisconnected()
219 {
220  if ( doSslFallback ) {
221  reconnect();
222  } else {
223  QMetaObject::invokeMethod( m_session, "socketDisconnected" );
224  }
225 }
226 
227 void SessionThread::socketError()
228 {
229  QMutexLocker locker( &m_mutex );
230  if ( doSslFallback ) {
231  locker.unlock(); // disconnectFromHost() ends up calling reconnect()
232  m_socket->disconnectFromHost();
233  } else {
234  QMetaObject::invokeMethod( m_session, "socketError" );
235  }
236 }
237 
238 void SessionThread::sslConnected()
239 {
240  QMutexLocker locker( &m_mutex );
241  KSslCipher cipher = m_socket->sessionCipher();
242 
243  if ( m_socket->sslErrors().count() > 0 ||
244  m_socket->encryptionMode() != KTcpSocket::SslClientMode ||
245  cipher.isNull() || cipher.usedBits() == 0 ) {
246  kDebug() << "Initial SSL handshake failed. cipher.isNull() is" << cipher.isNull()
247  << ", cipher.usedBits() is" << cipher.usedBits()
248  << ", the socket says:" << m_socket->errorString()
249  << "and the list of SSL errors contains"
250  << m_socket->sslErrors().count() << "items.";
251  KSslErrorUiData errorData( m_socket );
252  emit sslError( errorData );
253  } else {
254  doSslFallback = false;
255  kDebug() << "TLS negotiation done.";
256  m_encryptedMode = true;
257  emit encryptionNegotiationResult( true, m_socket->negotiatedSslVersion() );
258  }
259 }
260 
261 void SessionThread::sslErrorHandlerResponse(bool response)
262 {
263  QMutexLocker locker( &m_mutex );
264  if ( response ) {
265  m_encryptedMode = true;
266  emit encryptionNegotiationResult( true, m_socket->negotiatedSslVersion() );
267  } else {
268  m_encryptedMode = false;
269  //reconnect in unencrypted mode, so new commands can be issued
270  m_socket->disconnectFromHost();
271  m_socket->waitForDisconnected();
272  m_socket->connectToHost( m_hostName, m_port );
273  emit encryptionNegotiationResult( false, KTcpSocket::UnknownSslVersion );
274  }
275 }
276 
277 #include "moc_sessionthread_p.cpp"
278 
This file is part of the KDE documentation.
Documentation copyright © 1996-2013 The KDE developers.
Generated on Wed Mar 27 2013 08:52:59 by doxygen 1.8.3 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.1 API Reference

Skip menu "kdepimlibs-4.10.1 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