summaryrefslogtreecommitdiff
path: root/kimap/sessionthread.cpp
blob: b7a1cb9bbee10bb20e78b402d56ca5cbd5705daf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*
    Copyright (c) 2009 Kevin Ottens <ervin@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "sessionthread_p.h"

#include <QtCore/QDebug>
#include <QtCore/QTimer>

#include <kdebug.h>

#include "imapstreamparser.h"
#include "message_p.h"
#include "session.h"

using namespace KIMAP;

Q_DECLARE_METATYPE(KTcpSocket::Error)
Q_DECLARE_METATYPE(KSslErrorUiData)
static const int _kimap_socketErrorTypeId = qRegisterMetaType<KTcpSocket::Error>();
static const int _kimap_sslErrorUiData = qRegisterMetaType<KSslErrorUiData>();

SessionThread::SessionThread( const QString &hostName, quint16 port, Session *parent )
  : QThread(), m_hostName(hostName), m_port(port),
    m_session(parent), m_socket(0), m_stream(0), m_encryptedMode(false)
{
  // Yeah, sounds weird, but QThread object is linked to the parent
  // thread not to itself, and I'm too lazy to introduce yet another
  // internal QObject
  moveToThread(this);
}

SessionThread::~SessionThread()
{
  // don't call quit() directly, this will deadlock in wait() if exec() hasn't run yet
  QMetaObject::invokeMethod( this, "quit" );
  if ( !wait( 10 * 1000 ) ) {
    kWarning() << "Session thread refuses to die, killing harder...";
    terminate();
    // Make sure to wait until it's done, otherwise it can crash when the pthread callback is called
    wait();
  }
}

void SessionThread::sendData( const QByteArray &payload )
{
  QMutexLocker locker(&m_mutex);

  m_dataQueue.enqueue( payload );
  QTimer::singleShot( 0, this, SLOT(writeDataQueue()) );
}

void SessionThread::writeDataQueue()
{
  QMutexLocker locker(&m_mutex);

  while ( !m_dataQueue.isEmpty() ) {
    m_socket->write( m_dataQueue.dequeue() );
  }
}

void SessionThread::readMessage()
{
  QMutexLocker locker(&m_mutex);

  if ( m_stream->availableDataSize()==0 ) {
    return;
  }

  Message message;
  QList<Message::Part> *payload = &message.content;

  try {
    while ( !m_stream->atCommandEnd() ) {
      if ( m_stream->hasString() ) {
        QByteArray string = m_stream->readString();
        if ( string == "NIL" ) {
          *payload << Message::Part( QList<QByteArray>() );
        } else {
          *payload << Message::Part(string);
        }
      } else if ( m_stream->hasList() ) {
        *payload << Message::Part(m_stream->readParenthesizedList());
      } else if ( m_stream->hasResponseCode() ) {
        payload = &message.responseCode;
      } else if ( m_stream->atResponseCodeEnd() ) {
        payload = &message.content;
      } else if ( m_stream->hasLiteral() ) {
        QByteArray literal;
        while ( !m_stream->atLiteralEnd() ) {
          literal+= m_stream->readLiteralPart();
        }
        *payload << Message::Part(literal);
      } else {
        // Oops! Something really bad happened
        throw ImapParserException( "Inconsistent state, probably due to some packet loss" );
      }
    }

    emit responseReceived(message);

  } catch (KIMAP::ImapParserException e) {
    qWarning() << "The stream parser raised an exception:" << e.what();
  }

  if ( m_stream->availableDataSize()>1 ) {
    QTimer::singleShot( 0, this, SLOT(readMessage()) );
  }

}

void SessionThread::closeSocket()
{
  QTimer::singleShot( 0, this, SLOT(doCloseSocket()) );
}

void SessionThread::doCloseSocket()
{
  m_encryptedMode = false;
  m_socket->close();
}

void SessionThread::reconnect()
{
  QMutexLocker locker(&m_mutex);

  if ( m_socket->state() != SessionSocket::ConnectedState &&
       m_socket->state() != SessionSocket::ConnectingState ) {
    if (m_encryptedMode) {
      m_socket->connectToHostEncrypted(m_hostName, m_port);
    } else {
      m_socket->connectToHost(m_hostName, m_port);
    }
  }
}

void SessionThread::run()
{
  m_socket = new SessionSocket;
  m_stream = new ImapStreamParser( m_socket );
  connect( m_socket, SIGNAL(readyRead()),
           this, SLOT(readMessage()), Qt::QueuedConnection );

  connect( m_socket, SIGNAL(disconnected()),
           m_session, SLOT(socketDisconnected()) );
  connect( m_socket, SIGNAL(connected()),
           m_session, SLOT(socketConnected()) );
  connect( m_socket, SIGNAL(error(KTcpSocket::Error)),
           m_session, SLOT(socketError()) );
  connect( m_socket, SIGNAL(bytesWritten(qint64)),
           m_session, SLOT(socketActivity()) );
  if ( m_socket->metaObject()->indexOfSignal("encryptedBytesWritten(qint64)" ) > -1 ) {
      connect( m_socket, SIGNAL(encryptedBytesWritten(qint64)), // needs kdelibs > 4.8
               m_session, SLOT(socketActivity()) );
  }
  connect( m_socket, SIGNAL(readyRead()),
           m_session, SLOT(socketActivity()) );

  connect( this, SIGNAL(responseReceived(KIMAP::Message)),
           m_session, SLOT(responseReceived(KIMAP::Message)) );

  QTimer::singleShot( 0, this, SLOT(reconnect()) );
  exec();

  delete m_stream;
  delete m_socket;
}

void SessionThread::startSsl(const KTcpSocket::SslVersion &version)
{
  QMutexLocker locker(&m_mutex);

  m_socket->setAdvertisedSslVersion(version);
  m_socket->ignoreSslErrors();
  connect(m_socket, SIGNAL(encrypted()), this, SLOT(sslConnected()));
  m_socket->startClientEncryption();
}

void SessionThread::sslConnected()
{
  QMutexLocker locker(&m_mutex);
  KSslCipher cipher = m_socket->sessionCipher();

  if ( m_socket->sslErrors().count() > 0 || m_socket->encryptionMode() != KTcpSocket::SslClientMode
      || cipher.isNull() || cipher.usedBits() == 0) {
      qDebug() << "Initial SSL handshake failed. cipher.isNull() is" << cipher.isNull()
                    << ", cipher.usedBits() is" << cipher.usedBits()
                    << ", the socket says:" <<  m_socket->errorString()
                    << "and the list of SSL errors contains"
                    << m_socket->sslErrors().count() << "items.";
     KSslErrorUiData errorData(m_socket);
     emit sslError(errorData);
  } else {
    qDebug() << "TLS negotiation done.";
    m_encryptedMode = true;
    emit encryptionNegotiationResult(true, m_socket->negotiatedSslVersion());
  }
}

void SessionThread::sslErrorHandlerResponse(bool response)
{
  QMutexLocker locker(&m_mutex);
  if (response) {
    m_encryptedMode = true;
    emit encryptionNegotiationResult(true, m_socket->negotiatedSslVersion());
  } else {
     m_encryptedMode = false;
     //reconnect in unencrypted mode, so new commands can be issued
     m_socket->disconnectFromHost();
     m_socket->waitForDisconnected();
     m_socket->connectToHost(m_hostName, m_port);
     emit encryptionNegotiationResult(false, KTcpSocket::UnknownSslVersion);
  }
}

#include "sessionthread_p.moc"