/
imap.cpp
1340 lines (1075 loc) · 37.4 KB
/
imap.cpp
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <QCryptographicHash>
#include <QStringList>
#include <QRegExp>
#ifndef QT_NO_OPENSSL
#include <QtNetwork/QSslSocket>
#else
#include <QtNetwork/QTcpSocket>
#endif
#include "imapmessage.h"
#include "imapmailbox.h"
#include "imap.h"
#ifdef IMAP_DEBUG
#include <QDebug>
#endif
#ifdef Q_WS_WIN
#define IMAP_MESSAGE_BODY_NEWLINE "\r\n"
#else
#define IMAP_MESSAGE_BODY_NEWLINE "\n"
#endif
//#define IMAP_TAG "THIMAP"
#define IMAP_TAG "IMAP4"
// ===========================================================================
// PRIVATE Functions
// ===========================================================================
static ImapMessage *_imapParseMessage (const QString& responseText) {
if (!responseText.startsWith('*'))
return(NULL);
QString response = responseText;
QRegExp regexId("\\* (\\d*)");
QRegExp regexMessageId("\"<([^>]+)>\"\\)\\)");
QRegExp regexFlags("\\(UID (\\d*) FLAGS \\(([^\\)]*)\\)");
QRegExp regexInternalDate("INTERNALDATE \"([^\"]+)\"");
QRegExp regexSentDate("ENVELOPE \(\"([^\"]+)\"");
QRegExp regexSize("RFC822.SIZE (\\d+)");
QRegExp regexEnvelope("ENVELOPE");
QRegExp regexUid("\\(UID (\\d*)\\");
ImapMessage *message = new ImapMessage;
if (regexId.indexIn(response) != -1)
message->setId(regexId.cap(1).toInt());
if (regexFlags.indexIn(response) != -1)
{
message->setFlags(regexFlags.cap(1));
message->setUid(regexFlags.cap(1));
//QString tmp = regexFlags.cap(1);
//QStringList list = tmp.split(" ");
}
if (regexInternalDate.indexIn(response) != -1)
message->setReceived(regexInternalDate.cap(1));
if (regexSize.indexIn(response) != -1)
message->setSize(regexSize.cap(1).toInt());
if (regexEnvelope.indexIn(response) != -1) {
int rmSize = regexEnvelope.pos() + regexEnvelope.matchedLength();
response = response.remove(0, rmSize);
}
if (regexUid.indexIn(response) != -1)
{
QString tmp = regexUid.cap(1);
QStringList list = tmp.split(" ");
message->setUid(list[1]);
}
QRegExp regexSent("\"([^\"]+)\"");
// QRegExp regexSent("\(\"(?:\\w{3}\\, )?([^\"]+)\"");
if (regexSent.indexIn(response) != -1) {
QRegExp subRegex("([\\-\\+]\\d{4}.*|NIL.*)");
subRegex.indexIn(regexSent.cap(1));
message->setSent(regexSent.cap(1).remove(subRegex.pos()));
message->setTimeZone(subRegex.cap(1));
response = response.remove(0, regexSent.pos() + regexSent.matchedLength());
}
QString token = "((";
int tokenOffset;
if (response.contains(token)) {
tokenOffset = 0;
} else {
token = "\" NIL";
tokenOffset = 2;
}
QRegExp regexSubject(" \"(.*)\"");
QString subject = response.mid(0, response.indexOf(token) + tokenOffset).trimmed();
if (subject == "NIL")
subject.clear();
else if (regexSubject.indexIn(subject) != -1)
subject = regexSubject.cap(1);
message->setSubject(Imap::decode(subject.toLatin1()));
if (response.contains("((")) {
response = response.remove(0, response.indexOf("(("));
} else {
if (message->subject().isEmpty())
message->setSubject(response);
}
if (regexMessageId.indexIn(response)) {
message->setMessageId(regexMessageId.cap(1));
response = response.remove(regexMessageId.pos()).trimmed();
}
if (response.endsWith("NIL")) {
response = response.remove(response.size() - 3);
} else {
QRegExp regexReference("\"<([^>]+)>\"");
if (regexReference.indexIn(response) != -1)
message->setReference(regexReference.cap(1));
}
message->setAddresses(response.trimmed());
return(message);
}
// ===========================================================================
// PRIVATE Class
// ===========================================================================
class ImapPrivate {
public:
QString responseErrorMsg;
QTcpSocket *socket;
public:
bool connectToHost (const QString& host, quint16 port, bool useSsl);
bool setFlag (int uid, const QString& flag, bool append);
public:
QByteArray readLine (bool *ok = NULL);
bool isMultiline (const QString& data) const;
bool isResponseOk (const QByteArray& response) const;
bool isResponseEnd (const QString& response) const;
bool sendDataLine (const QString& data);
bool sendCommand (const QString& command,
const QStringList& args = QStringList());
public:
QByteArray hmacMd5 (const QString& username,
const QString& password,
const QString& serverResponse);
ImapMailbox *parseMailbox (const QString& mailboxName);
ImapMailbox *parseMessages (ImapMailbox *mailbox);
ImapMailbox *parseMessageHeader (ImapMailbox *mailbox);
QByteArray parseBodyPart (ImapMessageBodyPart::Encoding encoding);
QList<ImapMessageBodyPart *> bodyPartSplit (const QByteArray& response);
QString rfcDate (const QDateTime& date) const;
int _imapParseMessageHeaders (const QString& responseText, ImapMessage *message, int lastField);
private:
QString buildId (void) const;
QStringList adressList[ADDRESS_TYPE_COUNT];
private:
QString m_lastId;
};
bool ImapPrivate::connectToHost (const QString& host, quint16 port, bool useSsl)
{
#ifndef QT_NO_OPENSSL
if (useSsl)
socket = new QSslSocket;
else
socket = new QTcpSocket;
#else
Q_UNUSED(useSsl)
socket = new QTcpSocket;
#endif
#ifndef QT_NO_OPENSSL
if (useSsl) {
QSslSocket *sslSocket = static_cast<QSslSocket *>(socket);
sslSocket->connectToHostEncrypted(host, port);
return(sslSocket->waitForEncrypted());
} else {
socket->connectToHost(host, port);
return(socket->waitForConnected());
}
#else
socket->connectToHost(host, port);
return(socket->waitForConnected());
#endif
}
bool ImapPrivate::setFlag (int uid, const QString& flag, bool append) {
QString method = (append ? "+flags" : "-flags");
QString command = "UID STORE %1 %2 (%3)";
if (!sendCommand(command.arg(uid).arg(method).arg(flag)))
return(false);
QByteArray response = readLine();
if (!response.startsWith('*'))
return(false);
bool ok = false;
readLine(&ok);
return(ok);
}
bool ImapPrivate::sendDataLine (const QString& data) {
qDebug() << "sendDataLine()" << data;
responseErrorMsg.clear();
socket->write(QString("%1\r\n").arg(data).toLatin1());
return(socket->waitForBytesWritten());
}
bool ImapPrivate::sendCommand (const QString& command, const QStringList& args)
{
m_lastId = IMAP_TAG;
QString fullCommand = QString("%1 %2").arg(m_lastId).arg(command);
foreach (QString arg, args)
fullCommand = fullCommand.arg(arg);
return(sendDataLine(fullCommand));
}
QByteArray ImapPrivate::readLine (bool *ok) {
quint8 attempts = 0;
while (!socket->canReadLine() && attempts < 2) {
if (!socket->waitForReadyRead())
attempts++;
}
if (attempts >= 2) {
if (ok != NULL) *ok = false;
return(QByteArray());
}
if (ok != NULL) *ok = true;
#ifdef IMAP_DEBUG
QByteArray response = socket->readLine();
qDebug() << "readLine()" << response;
return(response);
#else
return(socket->readLine());
#endif
}
bool ImapPrivate::isMultiline (const QString& data) const {
bool res = QRegExp("^.*\\{\\d+\\}$").exactMatch(data.trimmed());
return(res);
}
bool ImapPrivate::isResponseOk (const QByteArray& response) const {
if (response.startsWith("* OK"))
return(true);
if (response.startsWith(m_lastId.toLatin1() + " OK"))
return(true);
return(true);
}
bool ImapPrivate::isResponseEnd (const QString& response) const {
QString trimmed = response.trimmed().toUpper();
//QString fetchEnd;
// fetchEnd.arg(IMAP_TAG);
if (trimmed.contains(m_lastId + " OK"))
{
trimmed = trimmed.replace(".", "").replace("(", "").replace(")", "");
return(trimmed.endsWith("SUCCESS") || trimmed.endsWith("COMPLETED") || trimmed.endsWith("DONE"));
}
else if (trimmed.contains(m_lastId + " BAD")) {
return(true);
}
else if (trimmed.contains(m_lastId + " NO")) {
return(true);
}
else if (trimmed.contains(m_lastId + " OK")) {
return(true);
}
else if (trimmed.contains(m_lastId.toUpper() + " OK FETCH")) {
return(true);
}
return(false);
}
QString ImapPrivate::buildId (void) const {
QString id;
do {
//id = QString("%1%2").arg(IMAP_TAG).arg(qrand());
id = QString("%1").arg(IMAP_TAG);
} while (m_lastId == id);
return(id);
}
QByteArray ImapPrivate::hmacMd5 (const QString& username,
const QString& password,
const QString& serverResponse)
{
QByteArray passwordBytes = password.toLatin1();
QByteArray ipad(64, 0);
QByteArray opad(64, 0);
for (int i = 0; i < 64; ++i) {
if (i < passwordBytes.size()) {
ipad[i] = (quint8)(0x36 ^ passwordBytes[i]);
opad[i] = (quint8)(0x5c ^ passwordBytes[i]);
} else {
ipad[i] = 0x36;
opad[i] = 0x5c;
}
}
QByteArray serverResponseBytes = serverResponse.toLatin1();
while (serverResponseBytes[0] == '+' || serverResponseBytes[0] == ' ')
serverResponseBytes.remove(0, 1);
QCryptographicHash md5hash(QCryptographicHash::Md5);
md5hash.addData(ipad);
md5hash.addData(serverResponseBytes);
QByteArray resultIpad = md5hash.result();
md5hash.reset();
md5hash.addData(opad);
md5hash.addData(resultIpad);
QByteArray resultOpad = md5hash.result();
QByteArray response = username.toLatin1() + ' ' + resultOpad.toHex();
return(response.toBase64());
}
ImapMailbox *ImapPrivate::parseMailbox (const QString& mailboxName) {
ImapMailbox *mailbox = NULL;
QByteArray response = readLine();
//QByteArray response = socket->readAll().data();
if (response.startsWith(IMAP_TAG) || response.startsWith('*')) {
QRegExp regexUnseen("\\[UNSEEN (\\d+)\\]");
QRegExp regexExists("(\\d+) EXISTS");
QRegExp regexRecent("(\\d+) RECENT");
QRegExp regexFlags(" FLAGS \\((.*)\\)");
mailbox = new ImapMailbox(mailboxName);
do {
if (regexExists.indexIn(response) != -1) {
mailbox->setExists(regexExists.cap(1).toInt());
} else if (regexRecent.indexIn(response) != -1) {
mailbox->setRecent(regexRecent.cap(1).toInt());
} else if (regexFlags.indexIn(response) != -1) {
mailbox->setFlags(regexFlags.cap(1));
} else if (regexUnseen.indexIn(response) != -1) {
mailbox->setUnseen(regexUnseen.cap(1).toInt());
}
response = readLine();
} while (response.startsWith('*'));
response = response.toUpper();
if (isResponseOk(response) &&
(response.contains("READ/WRITE") || response.contains("READ-WRITE")))
{
mailbox->setReadWrite(true);
}
}
return(mailbox);
}
//----------------------------------------------
ImapMailbox *ImapPrivate::parseMessageHeader (ImapMailbox *mailbox)
{
QByteArray response;
QByteArray fullHeaders;
ImapMessage *message = new ImapMessage;
int criritVal = 400;
int controlCriticVal = 0;
int lastHeaderField = -1; // поле которое парсилось последним
while(true)
{
response.clear();
response.append(readLine()); // читаем строчку с сокета
// Break if End Response Found.
if (isResponseEnd(response) || controlCriticVal > criritVal)
break;
if (response.startsWith('*'))
continue;
fullHeaders.append(response);
// парсинг строчки
lastHeaderField = _imapParseMessageHeaders(response.trimmed(), message, lastHeaderField);
controlCriticVal++;
}
//qDebug() << fullHeaders ;
message->setFullHeaders(fullHeaders);
// proto здесь будет обработка адресов
for (int i =0; i < ADDRESS_TYPE_COUNT; i++)
{
message->setAddresses(adressList[i], i);
}
if (message != NULL) mailbox->addMessage(message);
return(mailbox);
}
//------------------------------------------
int ImapPrivate::_imapParseMessageHeaders (const QString& responseText, ImapMessage *message, int lastField)
{
QString response = responseText;
QString regStr = "([A-Za-z-]+):(.*)";
// парсим строчку и записываем в message найденные данные
QRegExp rx(regStr);
int pos = 0;
// если шаблон найден
if (rx.indexIn(responseText, pos) != -1)
{
QString field = rx.cap(1);
QString fieldContent = rx.cap(2);
if (field == "Subject" )
{
message->setSubject(fieldContent);
return SUBJECT;
}
if (field == "From")
{
//message->setAddresses(fieldContent, FROM);
adressList[FROM] << fieldContent;
return FROM;
}
if (field == "To")
{
adressList[TO] << fieldContent;
//message->setAddresses(fieldContent, TO);
return TO;
}
if (field == "Cc"){
//message->setAddresses(fieldContent, CC);
adressList[CC] << fieldContent;
return CC;
}
if (field == "Bcc"){
// message->setAddresses(fieldContent, BCC);
adressList[BCC] << fieldContent;
return BCC;
}
if (field == "Reply-To"){
// message->setAddresses(fieldContent, REPLY);
adressList[REPLY] << fieldContent;
return REPLY;
}
if (field == "ReSent-To"){
//message->setAddresses(fieldContent, RESENT_TO);
adressList[RESENT_TO] << fieldContent;
return RESENT_TO;
}
if (field == "ReSent-From"){
//message->setAddresses(fieldContent, RESENT_FROM);
adressList[RESENT_FROM] << fieldContent;
return RESENT_FROM;
}
}
// если шаблон не найден
else
{
// это строка не соответствует шаблону
// узнать какое поле было последним
switch(lastField)
{
case NO:return NO;break;
case TO: adressList[TO] << response;return TO;
case CC: adressList[CC] << response;return CC;
case BCC: adressList[BCC] << response;return BCC;
case REPLY: adressList[REPLY] << response;return REPLY;
case RESENT_TO: adressList[RESENT_TO] << response;return RESENT_TO;
case RESENT_FROM: adressList[ RESENT_FROM] << response;return RESENT_FROM;
default: return NO;
}
}
return NO;
}
ImapMailbox *ImapPrivate::parseMessages (ImapMailbox *mailbox) {
QByteArray response;
while (true) {
// Read Message
response.clear();
do {
if (response.size() > 0) {
response.remove(response.lastIndexOf('}'),
response.size() - response.lastIndexOf('{'));
}
response.append(readLine());
} while (isMultiline(response));
// Break if End Response Found.
if (isResponseEnd(response))
break;
// Parse and Add Message to Mailbox
ImapMessage *message = _imapParseMessage(response.trimmed());
if (message != NULL) mailbox->addMessage(message);
}
return(mailbox);
}
QList<ImapMessageBodyPart *> ImapPrivate::bodyPartSplit (const QByteArray& response) {
QList<ImapMessageBodyPart *> partList;
int count = 0;
int index = 1;
int i = 0;
do {
int next = index;
do {
if (response[next] == '(')
i++;
else if (response[next] == ')')
i--;
next++;
} while (i > 0 || response[next - 1] != ')');
if (i >= 0 && response[index] == '(') {
count++;
if (response.indexOf("((", index) == index) {
QByteArray part = response.mid(index, next);
QList<ImapMessageBodyPart *> tempParts = bodyPartSplit(part);
foreach (ImapMessageBodyPart *p, tempParts) {
p->setBodyPart(QString("%1.%2").arg(count).arg(p->bodyPart()));
partList.append(p);
}
} else {
QByteArray part = response.mid(index, next - index);
ImapMessageBodyPart *bodyPart = new ImapMessageBodyPart(part);
bodyPart->setBodyPart(QString::number(count));
partList.append(bodyPart);
}
} else if (partList.size() == 0) {
ImapMessageBodyPart *bodyPart = new ImapMessageBodyPart(response);
bodyPart->setBodyPart("1");
partList.append(bodyPart);
}
index = next;
} while (i >= 0);
return(partList);
}
QByteArray ImapPrivate::parseBodyPart (ImapMessageBodyPart::Encoding encoding) {
QByteArray response;
QByteArray data;
while (!isResponseEnd((response = readLine())))
{
response.remove(response.size() - 2, 2);
if (encoding == ImapMessageBodyPart::Base64Encoding)
{
data += response;
}
else if (encoding == ImapMessageBodyPart::QuotedPrintableEncoding)
{
if (response.endsWith('=') || response.endsWith(')'))
data += response.mid(0, response.size() - 1);
else
data += response + IMAP_MESSAGE_BODY_NEWLINE;
}
else
{
data += response + IMAP_MESSAGE_BODY_NEWLINE;
}
}
if (data.trimmed().endsWith(')'))
data = data.remove(data.lastIndexOf(')'), 1);
if (encoding != ImapMessageBodyPart::Base64Encoding)
return(Imap::decode(data));
return(data);
}
QString ImapPrivate::rfcDate (const QDateTime& date) const {
return(date.toString("dd-MMM-yyyy HH:mm:ss +0000"));
}
// ===========================================================================
// PUBLIC Constructors/Destructor
// ===========================================================================
Imap::Imap()
: d(new ImapPrivate)
{
}
Imap::~Imap() {
//disconnectFromHost();
delete d;
}
// ===========================================================================
// PUBLIC STATIC Methods (Decode)
// ===========================================================================
QString Imap::decode (const QString& text) {
return(decode(text.toLatin1()));
}
QByteArray Imap::decode (const QByteArray& text) {
QRegExp rx("=\\?([^\\?]+)\\?([^\\?]+)\\?([^\\?]+)\\?=");
QByteArray output;
int pos = 0;
while ((pos = rx.indexIn(text, pos)) != -1) {
QString method = rx.cap(2).toLower();
QString data = rx.cap(3);
if (method == "b") {
output += QByteArray::fromBase64(data.toLatin1());
} else if (!data.isEmpty()) {
bool ok;
for (int i = 0; i < data.size(); ++i) {
if (data[i] == '=') {
i++;
int chr = data.mid(i, 2).toInt(&ok, 16);
if (data.size() >= (i + 2) && ok) {
output += (char)chr;
i++;
}
} else if (data[i] == '_') {
output += ' ';
} else {
output += data[i].toLatin1();
}
}
}
pos += rx.matchedLength();
}
return(output.size() > 0 ? output : text);
}
// ===========================================================================
// PUBLIC Methods (Connect/Disconnect)
// ===========================================================================
/**
* Connect to IMAP Server, using SSL connection if useSsl flag is True.
*/
bool Imap::connectToHost (const QString& host, quint16 port, bool useSsl) {
if (!d->connectToHost(host, port, useSsl))
return(false);
QByteArray response = d->readLine();
if (!response.startsWith("* OK"))
return(false);
return(true);
}
#ifndef QT_NO_OPENSSL
/**
* Connect to IMAP Server using SSL connection.
*/
bool Imap::connectToSslHost (const QString& host, quint16 port) {
return(connectToHost(host, port, true));
}
#endif
/**
* Disconnect from IMAP Server.
*/
bool Imap::disconnectFromHost (void) {
if (d->socket == NULL)
return(true);
if (d->socket->state() == QAbstractSocket::UnconnectedState)
return(true);
d->socket->disconnectFromHost();
if (!d->socket->waitForDisconnected())
return(false);
delete d->socket;
d->socket = NULL;
return(true);
}
// ===========================================================================
// PUBLIC Methods (IMAP Login/Logout)
// ===========================================================================
/**
* Login to the IMAP Server, using the specified username/password.
* TODO: Need to check server capabilities before use specified login type.
*/
bool Imap::login (const QString& username,
const QString& password,
LoginType type)
{
// TODO: Check Capabilities before use specified Login Type.
//QString capabilities = capability();
switch (type) {
case LoginPlain:
if (!d->sendCommand("LOGIN %1 %2", QStringList() << username << password))
return(false);
break;
case LoginAuthenticate:
if (!d->sendCommand("AUTHENTICATE LOGIN"))
return(false);
// Send Username
d->readLine();
if (!d->sendDataLine(username.toLatin1().toBase64()))
return(false);
// Send Password
d->readLine();
if (!d->sendDataLine(password.toLatin1().toBase64()))
return(false);
break;
case LoginCramMd5:
if (!d->sendCommand("AUTHENTICATE CRAM-MD5"))
return(false);
QByteArray serverResponse = d->readLine();
QByteArray hmac = d->hmacMd5(username, password, serverResponse);
if (!d->sendDataLine(hmac))
return(false);
break;
}
QByteArray result = d->readLine();
if (!d->isResponseOk(result)) {
d->responseErrorMsg = result;
return(false);
}
return(true);
}
/**
* Shutdown connection to server.
*/
bool Imap::logout (void) {
if (!d->sendCommand("LOGOUT"))
return(false);
bool ok = false;
d->readLine(&ok);
return(ok);
}
// ===========================================================================
// PUBLIC Methods (IMAP Commands)
// ===========================================================================
/**
* Returns server capabilities.
*/
QString Imap::capability (void) {
if (!d->sendCommand("CAPABILITY"))
return(false);
QByteArray capability = d->readLine();
d->readLine();
return(capability.trimmed());
}
// ===========================================================================
// PUBLIC Methods (IMAP Mailbox Related)
// ===========================================================================
/**
* Permanently remove deleted items from selected mailbox.
*/
bool Imap::expunge (void) {
QRegExp regexExpunge("^"IMAP_TAG"\\d+\\WOK\\W(EXPUNGE\\W|)COMPLETE");
QByteArray response;
if (!d->sendCommand("EXPUNGE"))
return(false);
do {
response = d->readLine();
if (regexExpunge.exactMatch(response))
return(true);
} while (!d->isResponseEnd(response));
return(true);
}
/*
* Selects a mailbox to perform commands on.
* Returns a mailbox object containing the properties of the mailbox.
*/
ImapMailbox *Imap::select (const QString& mailbox) {
if (!d->sendCommand("SELECT %1", QStringList() << mailbox))
return(NULL);
return(d->parseMailbox(mailbox));
}
/*
* Examines a mailbox.
* Returns a mailbox object containing the properties of the mailbox.
*/
ImapMailbox *Imap::examine (const QString& mailbox) {
if (!d->sendCommand("EXAMINE %2", QStringList() << mailbox))
return(NULL);
return(d->parseMailbox(mailbox));
}
/**
* List mailbox names in directory matching pattern.
* Directory defaults to the top-level mail folder,
* and pattern defaults to match anything.
*/
QStringList Imap::list (const QString& directory, const QString& pattern) {
QByteArray response;
QStringList folders;
//directory = "imap.mail.ru";
if (!d->sendCommand("LIST %1 %2", QStringList() << directory << pattern))
return(folders);
QRegExp rx("\\((.*)\\)\\s+\"(.*)\"\\s+\"(.*)\"");
while (!d->isResponseEnd(response = d->readLine())) {
if (rx.indexIn(response) != -1)
folders.append(rx.cap(3));
}
return(folders);
}
/*
* Create Mailbox with specified name.
*/
bool Imap::createMailbox (const QString& mailbox) {
QByteArray response;
if (!d->sendCommand("CREATE %1", QStringList() << mailbox))
return(false);
do {
response = d->readLine();
} while (!d->isResponseEnd(response));
return(d->isResponseOk(response));
}
/**
* Create Mailbox with specified name 'folder.name'.
*/
bool Imap::createMailbox (const QString& folder, const QString& name) {
return(createMailbox(QString("%1%.%2").arg(folder).arg(name)));
}
/**
* Rename Mailbox (oldName) with the specified newName.
*/
bool Imap::renameMailbox (const QString& oldName, const QString& newName) {
QByteArray response;
if (!d->sendCommand("RENAME %1 %2", QStringList() << oldName << newName))
return(false);
do {
response = d->readLine();
} while (!d->isResponseEnd(response));
return(d->isResponseOk(response));
}
/**
* Delete Mailbox with specified name.
*/
bool Imap::deleteMailbox (const QString& mailbox) {
QByteArray response;
if (!d->sendCommand("DELETE %1", QStringList() << mailbox))
return(false);
do {
response = d->readLine();
} while (!d->isResponseEnd(response));
return(d->isResponseOk(response));
}
/**
* Delte Mailbox Named 'folder.name'.
*/
bool Imap::deleteMailbox (const QString& folder, const QString& name) {
return(deleteMailbox(QString("%1.%2").arg(folder).arg(name)));
}
/**
* Copy Messages onto end of new Mailbox.
*/
bool Imap::copyMailbox (const QString& mailbox, int begin, int end) {
QByteArray response;
QString command = "COPY %1:%2 \"%3\"";
if (!d->sendCommand(command.arg(begin).arg(end).arg(mailbox)))
return(false);
do {
response = d->readLine();
} while (!d->isResponseEnd(response));
return(true);
}
// ===========================================================================
// PUBLIC Methods (IMAP Message Related)
// ===========================================================================
/**
* Fetch UID of specified Message. (message->id())
*/
int Imap::fetchUid (int messageNumber) {
if (!d->sendCommand(QString("FETCH %1 UID").arg(messageNumber)))
return(-1);
QByteArray response = d->readLine();
if (!response.startsWith('*')) {
d->responseErrorMsg = response;
return(-1);
}
QRegExp regex("\\(UID (\\d+)\\)");
if (regex.indexIn(response) != -1) {
int uid = regex.cap(1).toInt();
d->readLine();
return(uid);
}