summaryrefslogtreecommitdiff
path: root/kimap/fetchjob.cpp
blob: f820b7000c1dba97dd3f4bed18028e1cf6267164 (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
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
/*
    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 "fetchjob.h"

#include <QtCore/QTimer>
#include <KDE/KDebug>
#include <KDE/KLocale>

#include "job_p.h"
#include "message_p.h"
#include "session_p.h"

namespace KIMAP
{
  class FetchJobPrivate : public JobPrivate
  {
    public:
      FetchJobPrivate( FetchJob *job, Session *session, const QString& name ) : JobPrivate( session, name ), q(job), uidBased(false) { }
      ~FetchJobPrivate() { }

      void parseBodyStructure( const QByteArray &structure, int &pos, KMime::Content *content );
      void parsePart( const QByteArray &structure, int &pos, KMime::Content *content );
      QByteArray parseString( const QByteArray &structure, int &pos );
      QByteArray parseSentence( const QByteArray &structure, int &pos );
      void skipLeadingSpaces( const QByteArray &structure, int &pos );

      void emitPendings()
      {
        if ( pendingUids.isEmpty() ) {
          return;
        }

        if ( !pendingParts.isEmpty() ) {
          emit q->partsReceived( selectedMailBox,
                                 pendingUids, pendingParts );
        }
        if ( !pendingSizes.isEmpty() || !pendingFlags.isEmpty() ) {
          emit q->headersReceived( selectedMailBox,
                                   pendingUids, pendingSizes,
                                   pendingFlags, pendingMessages );
        }
        if ( !pendingMessages.isEmpty() ) {
          emit q->messagesReceived( selectedMailBox,
                                    pendingUids, pendingMessages );
        }

        pendingUids.clear();
        pendingMessages.clear();
        pendingParts.clear();
        pendingSizes.clear();
        pendingFlags.clear();
      }

      FetchJob * const q;

      ImapSet set;
      bool uidBased;
      FetchJob::FetchScope scope;
      QString selectedMailBox;

      QTimer emitPendingsTimer;
      QMap<qint64, MessagePtr> pendingMessages;
      QMap<qint64, MessageParts> pendingParts;
      QMap<qint64, MessageFlags> pendingFlags;
      QMap<qint64, qint64> pendingSizes;
      QMap<qint64, qint64> pendingUids;
  };
}

using namespace KIMAP;

FetchJob::FetchJob( Session *session )
  : Job( *new FetchJobPrivate(this, session, i18n("Fetch")) )
{
  Q_D(FetchJob);
  d->scope.mode = FetchScope::Content;
  connect( &d->emitPendingsTimer, SIGNAL(timeout()),
           this, SLOT(emitPendings()) );
}

FetchJob::~FetchJob()
{
}

void FetchJob::setSequenceSet( const ImapSet &set )
{
  Q_D(FetchJob);
  Q_ASSERT( !set.toImapSequenceSet().trimmed().isEmpty() );
  d->set = set;
}

ImapSet FetchJob::sequenceSet() const
{
  Q_D(const FetchJob);
  return d->set;
}

void FetchJob::setUidBased(bool uidBased)
{
  Q_D(FetchJob);
  d->uidBased = uidBased;
}

bool FetchJob::isUidBased() const
{
  Q_D(const FetchJob);
  return d->uidBased;
}

void FetchJob::setScope( const FetchScope &scope )
{
  Q_D(FetchJob);
  d->scope = scope;
}

FetchJob::FetchScope FetchJob::scope() const
{
  Q_D(const FetchJob);
  return d->scope;
}

QMap<qint64, MessagePtr> FetchJob::messages() const
{
  return QMap<qint64, MessagePtr>();
}

QMap<qint64, MessageParts> FetchJob::parts() const
{
  return QMap<qint64, MessageParts>();
}

QMap<qint64, MessageFlags> FetchJob::flags() const
{
  return QMap<qint64, MessageFlags>();
}

QMap<qint64, qint64> FetchJob::sizes() const
{
  return QMap<qint64, qint64>();
}

QMap<qint64, qint64> FetchJob::uids() const
{
  return QMap<qint64, qint64>();
}

void FetchJob::doStart()
{
  Q_D(FetchJob);

  QByteArray parameters = d->set.toImapSequenceSet()+' ';
  Q_ASSERT( !parameters.trimmed().isEmpty() );

  switch ( d->scope.mode ) {
  case FetchScope::Headers:
    if ( d->scope.parts.isEmpty() ) {
      parameters+="(RFC822.SIZE INTERNALDATE BODY.PEEK[HEADER.FIELDS (TO FROM MESSAGE-ID REFERENCES IN-REPLY-TO SUBJECT DATE)] FLAGS UID)";
    } else {
      parameters+='(';
      foreach ( const QByteArray &part, d->scope.parts ) {
        parameters+="BODY.PEEK["+part+".MIME] ";
      }
      parameters+="UID)";
    }
    break;
  case FetchScope::Flags:
    parameters+="(FLAGS UID)";
    break;
  case FetchScope::Structure:
    parameters+="(BODYSTRUCTURE UID)";
    break;
  case FetchScope::Content:
    if ( d->scope.parts.isEmpty() ) {
      parameters+="(BODY.PEEK[] UID)";
    } else {
      parameters+='(';
      foreach ( const QByteArray &part, d->scope.parts ) {
        parameters+="BODY.PEEK["+part+"] ";
      }
      parameters+="UID)";
    }
    break;
  case FetchScope::Full:
    parameters+="(RFC822.SIZE INTERNALDATE BODY.PEEK[] FLAGS UID)";
    break;
  case FetchScope::HeaderAndContent:
    if ( d->scope.parts.isEmpty() ) {
      parameters+="(BODY.PEEK[] FLAGS UID)";
    } else {
      parameters+="(BODY.PEEK[HEADER.FIELDS (TO FROM MESSAGE-ID REFERENCES IN-REPLY-TO SUBJECT DATE)]";
      foreach ( const QByteArray &part, d->scope.parts ) {
        parameters+=" BODY.PEEK["+part+".MIME] BODY.PEEK["+part+"]"; //krazy:exclude=doublequote_chars
      }
      parameters+=" FLAGS UID)";
    }
    break;
  }

  QByteArray command = "FETCH";
  if ( d->uidBased ) {
    command = "UID "+command;
  }

  d->emitPendingsTimer.start( 100 );
  d->selectedMailBox = d->m_session->selectedMailBox();
  d->tags << d->sessionInternal()->sendCommand( command, parameters );
}

void FetchJob::handleResponse( const Message &response )
{
  Q_D(FetchJob);

  // We can predict it'll be handled by handleErrorReplies() so stop
  // the timer now so that result() will really be the last emitted signal.
  if ( !response.content.isEmpty()
       && d->tags.size() == 1
       && d->tags.contains( response.content.first().toString() ) ) {
    d->emitPendingsTimer.stop();
    d->emitPendings();
  }

  if (handleErrorReplies(response) == NotHandled ) {
    if ( response.content.size() == 4
           && response.content[2].toString()=="FETCH"
           && response.content[3].type()==Message::Part::List ) {

      qint64 id = response.content[1].toString().toLongLong();
      QList<QByteArray> content = response.content[3].toList();

      MessagePtr message( new KMime::Message );
      bool shouldParseMessage = false;
      MessageParts parts;

      for ( QList<QByteArray>::ConstIterator it = content.constBegin();
            it!=content.constEnd(); ++it ) {
        QByteArray str = *it;
        ++it;

        if ( it==content.constEnd() ) { // Uh oh, message was truncated?
          kWarning() << "FETCH reply got truncated, skipping.";
          break;
        }

        if ( str=="UID" ) {
          d->pendingUids[id] = it->toLongLong();
        } else if ( str=="RFC822.SIZE" ) {
          d->pendingSizes[id] = it->toLongLong();
        } else if ( str=="INTERNALDATE" ) {
          message->date()->setDateTime( KDateTime::fromString( *it, KDateTime::RFCDate ) );
        } else if ( str=="FLAGS" ) {
          if ( (*it).startsWith('(') && (*it).endsWith(')') ) {
            QByteArray str = *it;
            str.chop(1);
            str.remove(0, 1);
            d->pendingFlags[id] = str.split(' ');
          } else {
            d->pendingFlags[id] << *it;
          }
        } else if ( str=="BODYSTRUCTURE" ) {
          int pos = 0;
          d->parseBodyStructure(*it, pos, message.get());
          message->assemble();
          d->pendingMessages[id] = message;
        } else if ( str.startsWith( "BODY[") ) { //krazy:exclude=strings
          if ( !str.endsWith(']') ) { // BODY[ ... ] might have been split, skip until we find the ]
            while ( !(*it).endsWith(']') ) ++it;
            ++it;
          }

          int index;
          if ( (index=str.indexOf("HEADER"))>0 || (index=str.indexOf("MIME"))>0 ) { // headers
            if ( str[index-1]=='.' ) {
              QByteArray partId = str.mid( 5, index-6 );
              if ( !parts.contains( partId ) ) {
                  parts[partId] = ContentPtr( new KMime::Content );
              }
              parts[partId]->setHead(*it);
              parts[partId]->parse();
              d->pendingParts[id] = parts;
            } else {
              message->setHead(*it);
              shouldParseMessage = true;
            }
          } else { // full payload
            if ( str=="BODY[]" ) {
              message->setContent( KMime::CRLFtoLF(*it) );
              shouldParseMessage = true;

              d->pendingMessages[id] = message;
            } else {
              QByteArray partId = str.mid( 5, str.size()-6 );
              if ( !parts.contains( partId ) ) {
                parts[partId] = ContentPtr( new KMime::Content );
              }
              parts[partId]->setBody(*it);
              parts[partId]->parse();

              d->pendingParts[id] = parts;
            }
          }
        }
      }

      if ( shouldParseMessage ) {
        message->parse();
      }

      // For the headers mode the message is built in several
      // steps, hence why we wait it to be done until putting it
      // in the pending queue.
      if ( d->scope.mode == FetchScope::Headers || d->scope.mode == FetchScope::HeaderAndContent ) {
        d->pendingMessages[id] = message;
      }
    }
  }
}

void FetchJobPrivate::parseBodyStructure(const QByteArray &structure, int &pos, KMime::Content *content)
{
  skipLeadingSpaces(structure, pos);

  if ( structure[pos]!='(' ) {
    return;
  }

  pos++;


  if ( structure[pos]!='(' ) { // simple part
    pos--;
    parsePart( structure, pos, content );
  } else { // multi part
    content->contentType()->setMimeType("MULTIPART/MIXED");
    while ( pos<structure.size() && structure[pos]=='(' ) {
      KMime::Content *child = new KMime::Content;
      content->addContent( child );
      parseBodyStructure( structure, pos, child );
      child->assemble();
    }

    QByteArray subType = parseString( structure, pos );
    content->contentType()->setMimeType( "MULTIPART/"+subType );

    QByteArray parameters = parseSentence( structure, pos ); // FIXME: Read the charset
    if (parameters.contains("BOUNDARY") ) {
      content->contentType()->setBoundary(parameters.remove(0, parameters.indexOf("BOUNDARY") + 11).split('\"')[0]);
    }

    QByteArray disposition = parseSentence( structure, pos );
    if ( disposition.contains("INLINE") ) {
      content->contentDisposition()->setDisposition( KMime::Headers::CDinline );
    } else if ( disposition.contains("ATTACHMENT") ) {
      content->contentDisposition()->setDisposition( KMime::Headers::CDattachment );
    }

    parseSentence( structure, pos ); // Ditch the body language
  }

  // Consume what's left
  while ( pos<structure.size() && structure[pos]!=')' ) {
    skipLeadingSpaces( structure, pos );
    parseSentence( structure, pos );
    skipLeadingSpaces( structure, pos );
  }

  pos++;
}

void FetchJobPrivate::parsePart( const QByteArray &structure, int &pos, KMime::Content *content )
{
  if ( structure[pos]!='(' ) {
    return;
  }

  pos++;

  QByteArray mainType = parseString( structure, pos );
  QByteArray subType = parseString( structure, pos );

  content->contentType()->setMimeType( mainType+'/'+subType );

  parseSentence( structure, pos ); // Ditch the parameters... FIXME: Read it to get charset and name
  parseString( structure, pos ); // ... and the id

  content->contentDescription()->from7BitString( parseString( structure, pos ) );

  parseString( structure, pos ); // Ditch the encoding too
  parseString( structure, pos ); // ... and the size
  parseString( structure, pos ); // ... and the line count

  QByteArray disposition = parseSentence( structure, pos );
  if ( disposition.contains("INLINE") ) {
    content->contentDisposition()->setDisposition( KMime::Headers::CDinline );
  } else if ( disposition.contains("ATTACHMENT") ) {
    content->contentDisposition()->setDisposition( KMime::Headers::CDattachment );
  }
  if ( (content->contentDisposition()->disposition() == KMime::Headers::CDattachment
        || content->contentDisposition()->disposition() == KMime::Headers::CDinline)
       && disposition.contains("FILENAME") ) {
    QByteArray filename = disposition.remove(0, disposition.indexOf("FILENAME") + 11).split('\"')[0];
    content->contentDisposition()->setFilename( filename );
  }

  // Consume what's left
  while ( pos<structure.size() && structure[pos]!=')' ) {
    skipLeadingSpaces( structure, pos );
    parseSentence( structure, pos );
    skipLeadingSpaces( structure, pos );
  }
}

QByteArray FetchJobPrivate::parseSentence( const QByteArray &structure, int &pos )
{
  QByteArray result;
  int stack = 0;

  skipLeadingSpaces( structure, pos );

  if ( structure[pos]!='(' ) {
    return parseString( structure, pos );
  }

  int start = pos;

  do {
    switch ( structure[pos] ) {
    case '(':
      pos++;
      stack++;
      break;
    case ')':
      pos++;
      stack--;
      break;
    case '[':
      pos++;
      stack++;
      break;
    case ']':
      pos++;
      stack--;
      break;
    default:
      skipLeadingSpaces(structure, pos);
      parseString(structure, pos);
      skipLeadingSpaces(structure, pos);
      break;
    }
  } while ( pos<structure.size() && stack!=0 );

  result = structure.mid( start, pos - start );

  return result;
}

QByteArray FetchJobPrivate::parseString( const QByteArray &structure, int &pos )
{
  QByteArray result;

  skipLeadingSpaces( structure, pos );

  int start = pos;
  bool foundSlash = false;

  // quoted string
  if ( structure[pos] == '"' ) {
    pos++;
    Q_FOREVER {
      if ( structure[pos] == '\\' ) {
        pos+= 2;
        foundSlash = true;
        continue;
      }
      if ( structure[pos] == '"' ) {
        result = structure.mid( start+1, pos - start - 1);
        pos++;
        break;
      }
      pos++;
    }
  } else { // unquoted string
    Q_FOREVER {
      if ( structure[pos] == ' ' || structure[pos] == '(' || structure[pos] == ')' || structure[pos] == '[' || structure[pos] == ']' || structure[pos] == '\n' || structure[pos] == '\r' || structure[pos] == '"') {
        break;
      }
      if (structure[pos] == '\\')
        foundSlash = true;
      pos++;
    }

    result = structure.mid( start, pos - start );

    // transform unquoted NIL
    if ( result == "NIL" )
      result.clear();
  }

  // simplify slashes
  if ( foundSlash ) {
    while ( result.contains( "\\\"" ) )
      result.replace( "\\\"", "\"" );
    while ( result.contains( "\\\\" ) )
      result.replace( "\\\\", "\\" );
  }

  return result;
}

void FetchJobPrivate::skipLeadingSpaces( const QByteArray &structure, int &pos )
{
  while ( structure[pos]==' ' && pos<structure.size() ) pos++;
}

#include "fetchjob.moc"