summaryrefslogtreecommitdiff
path: root/src/operator-fetch.cc
blob: 7de2fbb7eb7aebf22b214107b0f26efaae7e5ea9 (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
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
/**
 * @file   operator-fetch.cc
 * @brief  Implementation of the FETCH command
 * @author Andreas Aardal Hanssen
 * @date   2002-2005
 */

#include "convert.h"
#include "depot.h"
#include "imapparser.h"
#include "iodevice.h"
#include "iofactory.h"
#include "mailbox.h"
#include "operators.h"
#include "pendingupdates.h"
#include "recursivedescent.h"
#include "session.h"

#include <string>

using namespace Binc;
using std::string;
using std::vector;

constexpr auto ACCEPT = Parser::ParseResult::ACCEPT;
constexpr auto ERROR = Parser::ParseResult::ERROR;
constexpr auto REJECT = Parser::ParseResult::REJECT;

namespace {
  void outputFlags(const Message &message)
  {
    bincClient << "FLAGS ";

    bincClient << "(";
    int flags = message.getStdFlags();
    vector<string> flagv;
    if (flags & Message::F_SEEN) flagv.push_back("\\Seen");
    if (flags & Message::F_ANSWERED) flagv.push_back("\\Answered");
    if (flags & Message::F_DELETED) flagv.push_back("\\Deleted");
    if (flags & Message::F_DRAFT) flagv.push_back("\\Draft");
    if (flags & Message::F_RECENT) flagv.push_back("\\Recent");
    if (flags & Message::F_FLAGGED) flagv.push_back("\\Flagged");

    for (auto k = flagv.begin(); k != flagv.end(); ++k) {
      if (k != flagv.begin()) bincClient << " ";
      bincClient << *k;
    }

    vector<string> customFlags = message.getCustomFlags();
    for (auto it = customFlags.begin(); it != customFlags.end(); ++it) {
      if (flagv.size() > 0 || it != customFlags.begin()) bincClient << " ";
      bincClient << *it;
    }

    bincClient << ")";
  }

}

FetchOperator::FetchOperator() {}

FetchOperator::~FetchOperator() {}

const string FetchOperator::getName() const
{
  return "FETCH";
}

Session::State FetchOperator::getState() const
{
  return Session::SELECTED;
}

Operator::ProcessResult FetchOperator::process(Depot &depot, Request &request)
{
  Session &session = Session::getInstance();

  bool updateFlags = false;
  Request req = request;

  Mailbox *mailbox = depot.getSelected();

  // If this is a UID FETCH, check if the UID attribute is fetched. If
  // it is not, then add it to the list of fetch attributes.
  vector<BincImapParserFetchAtt>::const_iterator f_i;
  bool uidfetched = false;
  if (request.getUidMode()) {
    f_i = request.fatt.begin();
    while (f_i != request.fatt.end()) {
      if ((*f_i).type == "UID") {
        uidfetched = true;
        break;
      }
      f_i++;
    }

    if (!uidfetched) {
      BincImapParserFetchAtt b;
      b.type = "UID";
      req.fatt.push_back(b);
    }
  }

  // Convert macros ALL, FULL and FAST
  f_i = request.fatt.begin();
  while (f_i != request.fatt.end()) {
    const string &type = (*f_i).type;
    if (type == "ALL") {
      req.fatt.push_back(BincImapParserFetchAtt("FLAGS"));
      req.fatt.push_back(BincImapParserFetchAtt("INTERNALDATE"));
      req.fatt.push_back(BincImapParserFetchAtt("RFC822.SIZE"));
      req.fatt.push_back(BincImapParserFetchAtt("ENVELOPE"));
    } else if (type == "FULL") {
      req.fatt.push_back(BincImapParserFetchAtt("FLAGS"));
      req.fatt.push_back(BincImapParserFetchAtt("INTERNALDATE"));
      req.fatt.push_back(BincImapParserFetchAtt("RFC822.SIZE"));
      req.fatt.push_back(BincImapParserFetchAtt("ENVELOPE"));
      req.fatt.push_back(BincImapParserFetchAtt("BODY"));
    } else if (type == "FAST") {
      req.fatt.push_back(BincImapParserFetchAtt("FLAGS"));
      req.fatt.push_back(BincImapParserFetchAtt("INTERNALDATE"));
      req.fatt.push_back(BincImapParserFetchAtt("RFC822.SIZE"));
    }

    ++f_i;
  }

  int mode;
  if (req.getUidMode())
    mode = Mailbox::UID_MODE;
  else
    mode = Mailbox::SQNR_MODE;

  for (Mailbox::iterator i = mailbox->begin(req.bset, Mailbox::SKIP_EXPUNGED | mode);
       i != mailbox->end();
       ++i)
  {
    Message &message = *i;

    bincClient << "* " << i.getSqnr() << " FETCH (";
    bool hasprinted = false;
    f_i = req.fatt.begin();
    while (f_i != req.fatt.end()) {
      BincImapParserFetchAtt fatt = *f_i;

      string prefix = "";
      if (hasprinted) prefix = " ";

      if (fatt.type == "FLAGS") {
        // FLAGS
        hasprinted = true;
        bincClient << prefix;

        outputFlags(message);
      } else if (fatt.type == "UID") {
        // UID
        hasprinted = true;
        bincClient << prefix << "UID " << message.getUID();
      } else if (fatt.type == "RFC822.SIZE") {
        // RFC822.SIZE
        hasprinted = true;
        bincClient << prefix << "RFC822.SIZE " << message.getSize(true);
      } else if (fatt.type == "ENVELOPE") {
        // ENVELOPE
        hasprinted = true;
        bincClient << prefix << "ENVELOPE ";
        message.printEnvelope();
      } else if (fatt.type == "BODYSTRUCTURE") {
        // BODYSTRUCTURE
        hasprinted = true;
        bincClient << prefix << "BODYSTRUCTURE ";
        message.printBodyStructure(true);
      } else if (fatt.type == "BODY" && !fatt.hassection) {
        // BODY with no section
        hasprinted = true;
        session.addBody();
        bincClient << prefix << "BODY ";
        message.printBodyStructure(false);
      } else if (fatt.type == "INTERNALDATE") {
        // INTERNALDATE
        hasprinted = true;
        bincClient << prefix << "INTERNALDATE ";

        time_t iDate = message.getInternalDate();
        struct tm *_tm = gmtime(&iDate);
        char internal[64];
        string iDateStr;
        if (strftime(internal, sizeof(internal), "%d-%b-%Y %H:%M:%S %z", _tm) != 0) {
          if (internal[0] == '0') internal[0] = ' ';
          iDateStr = internal;
        } else {
          iDateStr = "NIL";
        }

        bincClient << toImapString(iDateStr);
      } else if (fatt.type == "BODY" || fatt.type == "BODY.PEEK") {
        // BODY & BODY.PEEK
        hasprinted = true;
        session.addBody();

        bincClient << prefix;
        bool peek = (fatt.type == "BODY.PEEK");
        bincClient << fatt.toString();

        bool includeheaders = true;
        bool fullheader = false;
        bool bodyfetch = false;

        if (fatt.section != "" || fatt.sectiontext == "" || fatt.sectiontext == "TEXT") {
          bodyfetch = true;
          fullheader = true;
        }

        if (fatt.sectiontext == "HEADER.FIELDS.NOT") includeheaders = false;

        if (fatt.sectiontext == "HEADER" || fatt.sectiontext == "HEADER.FIELDS"
            || fatt.sectiontext == "HEADER.FIELDS.NOT" || fatt.sectiontext == "MIME")
        {
          vector<string> v;

          if (fatt.sectiontext == "MIME") {
            v.push_back("content-type");
            v.push_back("content-transfer-encoding");
            v.push_back("content-disposition");
            v.push_back("content-description");
          } else {
            v = fatt.headerlist;
          }

          string dummy;
          unsigned int size = fullheader ? message.getHeaderSize(fatt.section,
                                                                 v,
                                                                 true,
                                                                 fatt.offsetstart,
                                                                 fatt.offsetlength,
                                                                 fatt.sectiontext == "MIME")
                                         : message.getHeaderSize(fatt.section,
                                                                 fatt.headerlist,
                                                                 includeheaders,
                                                                 fatt.offsetstart,
                                                                 fatt.offsetlength,
                                                                 fatt.sectiontext == "MIME");

          bincClient << "{" << size << "}\r\n";

          if (fullheader) {
            message.printHeader(fatt.section,
                                v,
                                true,
                                fatt.offsetstart,
                                fatt.offsetlength,
                                fatt.sectiontext == "MIME");
          } else {
            message.printHeader(fatt.section,
                                fatt.headerlist,
                                includeheaders,
                                fatt.offsetstart,
                                fatt.offsetlength,
                                fatt.sectiontext == "MIME");
          }
        } else {
          unsigned int size;
          if ((fatt.sectiontext == "" || fatt.sectiontext == "TEXT") && fatt.section == "")
            size = message.getDocSize(fatt.offsetstart,
                                      fatt.offsetlength,
                                      fatt.sectiontext == "TEXT");
          else
            size = message.getBodySize(fatt.section, fatt.offsetstart, fatt.offsetlength);

          bincClient << "{" << size << "}\r\n";

          if ((fatt.sectiontext == "" || fatt.sectiontext == "TEXT") && fatt.section == "")
            message.printDoc(fatt.offsetstart, fatt.offsetlength, fatt.sectiontext == "TEXT");
          else
            message.printBody(fatt.section, fatt.offsetstart, fatt.offsetlength);
        }

        // set the \Seen flag if .PEEK is not used.
        if (!peek) {
          if ((message.getStdFlags() & Message::F_SEEN) == 0)
            message.setStdFlag(Message::F_SEEN);
        }
      } else if (fatt.type == "RFC822") {
        bincClient << prefix;
        hasprinted = true;
        session.addBody();
        bincClient << fatt.toString();
        unsigned int size = message.getDocSize(fatt.offsetstart, fatt.offsetlength);
        bincClient << " {" << size << "}\r\n";
        message.printDoc(fatt.offsetstart, fatt.offsetlength);

        // set the \Seen flag
        if ((message.getStdFlags() & Message::F_SEEN) == 0)
          message.setStdFlag(Message::F_SEEN);

      } else if (fatt.type == "RFC822.HEADER") {
        bincClient << prefix;
        hasprinted = true;
        bincClient << fatt.toString();
        vector<string> v;
        string dummy;
        unsigned int size = message.getHeaderSize("",
                                                  v,
                                                  true,
                                                  fatt.offsetstart,
                                                  fatt.offsetlength);
        bincClient << " {" << size << "}\r\n";
        message.printHeader("", v, true, fatt.offsetstart, fatt.offsetlength);
      } else if (fatt.type == "RFC822.TEXT") {
        // RFC822.TEXT
        bincClient << prefix;
        hasprinted = true;
        session.addBody();

        bincClient << fatt.toString();

        bool bodyfetch = false;
        bodyfetch = true;

        unsigned int size;
        if (fatt.sectiontext == "" && fatt.section == "")
          size = message.getDocSize(fatt.offsetstart, fatt.offsetlength, true);
        else
          size = message.getBodySize(fatt.section, fatt.offsetstart, fatt.offsetlength);

        bincClient << " {" << size << "}\r\n";

        if (fatt.sectiontext == "" && fatt.section == "")
          message.printDoc(fatt.offsetstart, fatt.offsetlength, true);
        else
          message.printBody(fatt.section, fatt.offsetstart, fatt.offsetlength);

        // set the \Seen flag
        if ((message.getStdFlags() & Message::F_SEEN) == 0)
          message.setStdFlag(Message::F_SEEN);

      } else {
        // Unrecognized fetch_att, this is stopped by the parser
        // so we never get here.
      }

      f_i++;
    }

    // FIXME: how are parse error passed back?

    bincClient << ")" << std::endl;

    if (message.hasFlagsChanged()) {
      updateFlags = true;
      bincClient << "* " << i.getSqnr() << " FETCH (";
      outputFlags(message);
      bincClient << ")" << std::endl;
      message.setFlagsUnchanged();
    }
  }

  if (updateFlags) mailbox->updateFlags();

  pendingUpdates(mailbox,
                 PendingUpdates::FLAGS | PendingUpdates::EXISTS | PendingUpdates::EXPUNGE
                     | PendingUpdates::RECENT,
                 true);

  return Operator::ProcessResult::OK;
}

Parser::ParseResult FetchOperator::parse(Request &c_in)
{
  Session &session = Session::getInstance();

  Parser::ParseResult res;
  if ((res = expectSPACE()) != ACCEPT) {
    session.setLastError("Expected SPACE after FETCH");
    return res;
  }

  if ((res = expectSet(c_in.getSet())) != ACCEPT) {
    session.setLastError("Expected sequence set after FETCH SPACE");
    return res;
  }

  if ((res = expectSPACE()) != ACCEPT) {
    session.setLastError("Expected SPACE after FETCH SPACE set");
    return res;
  }

  BincImapParserFetchAtt f;

  if ((res = expectThisString("ALL")) == ACCEPT) {
    f.type = "ALL";
    c_in.fatt.push_back(f);
  } else if ((res = expectThisString("FULL")) == ACCEPT) {
    f.type = "FULL";
    c_in.fatt.push_back(f);
  } else if ((res = expectThisString("FAST")) == ACCEPT) {
    f.type = "FAST";
    c_in.fatt.push_back(f);
  } else if ((res = expectFetchAtt(f)) == ACCEPT) {
    c_in.fatt.push_back(f);
  } else if ((res = expectThisString("(")) == ACCEPT) {
    while (1) {
      BincImapParserFetchAtt ftmp;
      if ((res = expectFetchAtt(ftmp)) != ACCEPT) {
        session.setLastError("Expected fetch_att");
        return res;
      }

      c_in.fatt.push_back(ftmp);

      if ((res = expectSPACE()) == REJECT)
        break;
      else if (res == ERROR)
        return ERROR;
    }

    if ((res = expectThisString(")")) != ACCEPT) {
      session.setLastError("Expected )");
      return res;
    }
  } else {
    session.setLastError("Expected ALL, FULL, FAST, fetch_att or (");
    return res;
  }

  if ((res = expectCRLF()) != ACCEPT) {
    session.setLastError("Expected CRLF");
    return res;
  }

  c_in.setName("FETCH");
  return ACCEPT;
}

Parser::ParseResult FetchOperator::expectSectionText(BincImapParserFetchAtt &f_in) const
{
  Session &session = Session::getInstance();

  Parser::ParseResult res;
  if ((res = expectThisString("HEADER")) == ACCEPT) {
    f_in.sectiontext = "HEADER";

    if ((res = expectThisString(".FIELDS")) == ACCEPT) {
      f_in.sectiontext += ".FIELDS";

      if ((res = expectThisString(".NOT")) == ACCEPT) f_in.sectiontext += ".NOT";

      if ((res = expectSPACE()) != ACCEPT) {
        session.setLastError("expected SPACE");
        return res;
      }

      if ((res = expectHeaderList(f_in)) != ACCEPT) {
        session.setLastError("Expected header_list");
        return res;
      }
    }
  } else if ((res = expectThisString("TEXT")) == ACCEPT) {
    f_in.sectiontext = "TEXT";
  } else {
    return Parser::ParseResult::REJECT;
  }

  return ACCEPT;
}

Parser::ParseResult FetchOperator::expectSection(BincImapParserFetchAtt &f_in) const
{
  Session &session = Session::getInstance();

  Parser::ParseResult res;
  if ((res = expectThisString("[")) != ACCEPT) return REJECT;

  if ((res = expectSectionText(f_in)) != ACCEPT) {
    unsigned int n;
    if ((res = expectNZNumber(n)) == ACCEPT) {
      BincStream nstr;
      nstr << n;
      f_in.section = nstr.str();

      bool gotadotalready = false;
      while (1) {
        if ((res = expectThisString(".")) != ACCEPT) break;

        if ((res = expectNZNumber(n)) != ACCEPT) {
          gotadotalready = true;
          break;
        }

        f_in.section += ".";
        BincStream nstr;
        nstr << n;
        f_in.section += nstr.str();
      }

      if (gotadotalready || (res = expectThisString(".")) == ACCEPT) {
        if ((res = expectThisString("MIME")) == ACCEPT) {
          f_in.sectiontext = "MIME";
        } else if ((res = expectSectionText(f_in)) != ACCEPT) {
          session.setLastError("Expected MIME or section_text");
          return res;
        }
      }
    }
  }

  if ((res = expectThisString("]")) != ACCEPT) {
    session.setLastError("Expected ]");
    return res;
  }

  return ACCEPT;
}

Parser::ParseResult FetchOperator::expectHeaderList(BincImapParserFetchAtt &f_in) const
{
  Session &session = Session::getInstance();

  Parser::ParseResult res;
  if ((res = expectThisString("(")) != ACCEPT) return REJECT;

  string header_fld_name;
  while (1) {
    if ((res = expectAstring(header_fld_name)) != ACCEPT) {
      session.setLastError("Expected header_fld_name");
      return res;
    }

    f_in.headerlist.push_back(header_fld_name);

    if ((res = expectSPACE()) == ACCEPT)
      continue;
    else
      break;
  }

  if ((res = expectThisString(")")) != ACCEPT) {
    session.setLastError("Expected )");
    return res;
  }

  return ACCEPT;
}

Parser::ParseResult FetchOperator::expectOffset(BincImapParserFetchAtt &f_in) const
{
  Session &session = Session::getInstance();
  Parser::ParseResult res;

  if ((res = expectThisString("<")) != ACCEPT) return REJECT;

  unsigned int i;
  if ((res = expectNumber(i)) != ACCEPT) {
    session.setLastError("Expected number");
    return res;
  }

  if ((res = expectThisString(".")) != ACCEPT) {
    session.setLastError("Expected .");
    return res;
  }

  unsigned int j;
  if ((res = expectNZNumber(j)) != ACCEPT) {
    session.setLastError("expected nz_number");
    return res;
  }

  if ((res = expectThisString(">")) != ACCEPT) {
    session.setLastError("Expected >");
    return res;
  }

  f_in.offsetstart = i;
  f_in.offsetlength = j;
  return ACCEPT;
}

Parser::ParseResult FetchOperator::expectFetchAtt(BincImapParserFetchAtt &f_in) const
{
  Parser::ParseResult res;

  Session &session = Session::getInstance();

  if ((res = expectThisString("ENVELOPE")) == ACCEPT) {
    f_in.type = "ENVELOPE";
  } else if ((res = expectThisString("FLAGS")) == ACCEPT) {
    f_in.type = "FLAGS";
  } else if ((res = expectThisString("INTERNALDATE")) == ACCEPT) {
    f_in.type = "INTERNALDATE";
  } else if ((res = expectThisString("UID")) == ACCEPT) {
    f_in.type = "UID";
  } else if ((res = expectThisString("RFC822")) == ACCEPT) {
    f_in.type = "RFC822";
    if ((res = expectThisString(".HEADER")) == ACCEPT) {
      f_in.type += ".HEADER";
    } else if ((res = expectThisString(".SIZE")) == ACCEPT) {
      f_in.type += ".SIZE";
    } else if ((res = expectThisString(".TEXT")) == ACCEPT) {
      f_in.type += ".TEXT";
    } else if ((res = expectThisString(".")) == ACCEPT) {
      session.setLastError("Expected RFC822, RFC822.HEADER,"
                           " RFC822.SIZE or RFC822.TEXT");
      return ERROR;
    }

  } else if ((res = expectThisString("BODY")) == ACCEPT) {
    f_in.type = "BODY";

    if ((res = expectThisString("STRUCTURE")) == ACCEPT)
      f_in.type += "STRUCTURE";
    else if ((res = expectThisString(".PEEK")) == ACCEPT)
      f_in.type += ".PEEK";

    if ((res = expectSection(f_in)) != ACCEPT) {
      f_in.hassection = false;
    } else {
      f_in.hassection = true;
      if ((res = expectOffset(f_in)) == ERROR) return ERROR;
    }
  } else {
    return REJECT;
  }

  return ACCEPT;
}