summaryrefslogtreecommitdiff
path: root/src/depot.cc
blob: c31c04b6705936306567bb3522934dc4f4d53cba (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
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
/**  --------------------------------------------------------------------
 *  @file depot.cc
 *  @brief Implementation of the Depot class.
 *  @author Andreas Aardal Hanssen
 *  @date 2002-2005
 *  ------------------------------------------------------------------ **/
#include "depot.h"

#include "convert.h"
#include "iodevice.h"
#include "iofactory.h"
#include "mailbox.h"
#include "status.h"

#include <map>
#include <string>

#include <errno.h>

#include <unistd.h>

using namespace ::std;
using namespace Binc;

//--------------------------------------------------------------------
DepotFactory::DepotFactory(void) {}

//--------------------------------------------------------------------
DepotFactory::~DepotFactory(void)
{
  for (vector<Depot *>::iterator i = depots.begin(); i != depots.end(); ++i)
    delete *i;
}

//--------------------------------------------------------------------
Depot *DepotFactory::get(const string &name) const
{
  for (vector<Depot *>::const_iterator i = depots.begin(); i != depots.end(); ++i)
    if ((*i)->getName() == name) return *i;

  return 0;
}

//--------------------------------------------------------------------
void DepotFactory::assign(Depot *depot)
{
  depots.push_back(depot);
}

//--------------------------------------------------------------------
DepotFactory &DepotFactory::getInstance(void)
{
  static DepotFactory depotfactory;
  return depotfactory;
}

//--------------------------------------------------------------------
Depot::Depot(void) : enditerator(0, 0)
{
  defaultmailbox = 0;
  selectedmailbox = 0;

  delimiter = '/';
}

//--------------------------------------------------------------------
Depot::Depot(const string &name) : enditerator(0, 0)
{
  defaultmailbox = 0;
  selectedmailbox = 0;

  delimiter = '/';

  this->name = name;
}

//--------------------------------------------------------------------
Depot::~Depot(void) {}

//--------------------------------------------------------------------
const string &Depot::getLastError(void) const
{
  return lastError;
}

//--------------------------------------------------------------------
void Depot::setLastError(const string &error) const
{
  lastError = error;
}

//--------------------------------------------------------------------
void Depot::assign(Mailbox *m)
{
  for (vector<Mailbox *>::const_iterator i = backends.begin(); i != backends.end(); ++i)
    if (*i == m) break;

  backends.push_back(m);
}

//--------------------------------------------------------------------
Mailbox *Depot::get(const string &s_in) const
{
  for (vector<Mailbox *>::const_iterator i = backends.begin(); i != backends.end(); ++i)
    if ((*i)->isMailbox(mailboxToFilename(s_in))) return *i;

  setLastError("No such mailbox " + toImapString(s_in));
  return 0;
}

//--------------------------------------------------------------------
bool Depot::setSelected(Mailbox *m)
{
  for (vector<Mailbox *>::const_iterator i = backends.begin(); i != backends.end(); ++i)
    if (*i == m) {
      selectedmailbox = m;
      return true;
    }

  setLastError("Attempted to select unregistered Mailbox type in Depot");
  return false;
}

//--------------------------------------------------------------------
const string &Depot::getName(void) const
{
  return name;
}

//--------------------------------------------------------------------
const string &Depot::getPersonalNamespace(void) const
{
  return personalNamespace;
}

//--------------------------------------------------------------------
const string &Depot::getOthersNamespace(void) const
{
  return othersNamespace;
}

//--------------------------------------------------------------------
const string &Depot::getSharedNamespace(void) const
{
  return sharedNamespace;
}

//--------------------------------------------------------------------
void Depot::setDelimiter(char c)
{
  delimiter = c;
}

//--------------------------------------------------------------------
const char Depot::getDelimiter(void) const
{
  return delimiter;
}

//--------------------------------------------------------------------
bool Depot::setDefaultType(const string &name)
{
  for (vector<Mailbox *>::const_iterator i = backends.begin(); i != backends.end(); ++i)
    if ((*i)->getTypeName() == name) {
      defaultmailbox = *i;
      return true;
    }

  setLastError("attempt to default to unregistered Mailbox type " + name);
  return false;
}

//--------------------------------------------------------------------
Mailbox *Depot::getSelected(void) const
{
  return selectedmailbox;
}

//--------------------------------------------------------------------
void Depot::resetSelected(void)
{
  selectedmailbox = 0;
}

//--------------------------------------------------------------------
Mailbox *Depot::getDefault(void) const
{
  return defaultmailbox;
}

//--------------------------------------------------------------------
bool Depot::createMailbox(const string &s_in) const
{
  const string &mailboxname = mailboxToFilename(toCanonMailbox(s_in));
  if (mailboxname == "") {
    setLastError("invalid mailbox name");
    return false;
  }

  Mailbox *mailbox = getDefault();
  if (mailbox == 0) {
    setLastError("no default mailbox defined");
    return false;
  }

  bool result = mailbox->createMailbox(mailboxname, 0777);
  if (result)
    return true;
  else {
    setLastError(mailbox->getLastError());
    return false;
  }
}

//--------------------------------------------------------------------
bool Depot::deleteMailbox(const string &s_in) const
{
  const string &mailboxname = mailboxToFilename(toCanonMailbox(s_in));

  Mailbox *mailbox = get(s_in);
  if (mailbox == 0) {
    setLastError(s_in + ": no such mailbox");
    return false;
  }

  bool result = mailbox->deleteMailbox(mailboxname);
  if (result)
    return true;
  else {
    setLastError(mailbox->getLastError());
    return false;
  }
}

//--------------------------------------------------------------------
bool Depot::renameMailbox(const string &s_in, const string &t_in) const
{
  const string &source = mailboxToFilename(s_in).c_str();
  const string &dest = mailboxToFilename(t_in).c_str();

  int nrenamed = 0;
  const iterator e = end();
  for (iterator i = begin("."); i != e; ++i) {
    string entry = *i;

    if (entry.substr(0, source.length()) == source) {
      string sourcename, destname;

      if (entry.length() == source.length()) {
        sourcename = source;
        destname = dest;

      } else if (entry.length() > source.length() && entry[source.length()] == '.') {
        sourcename = entry;
        destname = dest + entry.substr(source.length());
      } else
        continue;

      if (rename(sourcename.c_str(), destname.c_str()) != 0) {
        bincWarning << "error renaming " << sourcename << " to " << destname << ": " << strerror(errno)
                    << endl;
      } else
        nrenamed++;

      Mailbox *mailbox;
      if ((mailbox = get(filenameToMailbox(sourcename))) != 0)
        mailbox->bumpUidValidity(filenameToMailbox(sourcename));
      if ((mailbox = get(filenameToMailbox(destname))) != 0)
        mailbox->bumpUidValidity(filenameToMailbox(destname));
    }
  }

  if (nrenamed == 0) {
    setLastError("An error occurred when renaming " + toImapString(s_in) + " to " + toImapString(t_in)
                 + ". Try creating a new mailbox,"
                   " then copy over all messages."
                   " Finally, delete the original mailbox");
    return false;
  } else
    return true;
}

//--------------------------------------------------------------------
bool Depot::getStatus(const std::string &s_in, Status &dest) const
{
  const string mailbox = toCanonMailbox(s_in);
  Mailbox *m = get(mailbox);
  if (m == 0) {
    setLastError("Unrecognized mailbox: " + toImapString(s_in));
    return false;
  }

  int statusid = m->getStatusID(mailboxToFilename(mailbox));
  if (mailboxstatuses.find(mailbox) != mailboxstatuses.end()) {
    dest = mailboxstatuses[mailbox];
    if (dest.getStatusID() == statusid) return true;
  }

  if (!m->getStatus(mailboxToFilename(mailbox), dest)) {
    setLastError(m->getLastError());
    return false;
  }

  dest.setStatusID(statusid);
  mailboxstatuses[mailbox] = dest;
  return true;
}

//----------------------------------------------------------------------
vector<string> Depot::getSubscriptions(void) const
{
  return subscribed;
}

//----------------------------------------------------------------------
void Depot::subscribeTo(const std::string mailbox)
{
  for (vector<string>::iterator i = subscribed.begin(); i != subscribed.end(); ++i) {
    if (*i == mailbox) return;
  }

  subscribed.push_back(mailbox);
}

//----------------------------------------------------------------------
bool Depot::unsubscribeTo(const std::string mailbox)
{
  for (vector<string>::iterator i = subscribed.begin(); i != subscribed.end(); ++i) {
    if (*i == mailbox) {
      subscribed.erase(i);
      return true;
    }
  }

  return false;
}

//----------------------------------------------------------------------
void Depot::loadSubscribes(void)
{
  // drop all existing subscribed folders.
  subscribed.clear();

  // try loading the .subscribed file
  bool ok = false;
  FILE *fp = fopen(".subscribed", "r");
  map<string, bool> addedEntries;
  if (fp) {
    int c;
    string current;
    while ((c = fgetc(fp)) != EOF) {
      if (c == '\n') {
        if (current != "") {
          if (current == "INBOX") current = ".";

          if (current.substr(0, 5) == "INBOX") current = current.substr(5);

          if (addedEntries.find(current) == addedEntries.end()) {
            subscribed.push_back(filenameToMailbox(current));
            addedEntries[current] = true;
          }
          current = "";
        }
      } else
        current += c;
    }

    fclose(fp);
    ok = true;
  }

  if (!ok) {
    subscribed.push_back("INBOX");
    saveSubscribes();
  }
}

//----------------------------------------------------------------------
bool Depot::saveSubscribes(void) const
{
  // create a safe file name
  string tpl = ".subscribed-tmp-XXXXXX";
  char *ftemplate = new char[tpl.length() + 1];

  strcpy(ftemplate, tpl.c_str());
  int fd = mkstemp(ftemplate);
  if (fd == -1) {
    bincWarning << "unable to create temporary file \"" << tpl << "\"" << endl;
    delete[] ftemplate;
    return false;
  }

  map<string, bool> addedEntries;
  for (vector<string>::const_iterator i = subscribed.begin(); i != subscribed.end(); ++i) {
    if (addedEntries.find(*i) == addedEntries.end()) {
      addedEntries[*i] = true;
      string w = mailboxToFilename(*i) + "\n";
      if (write(fd, w.c_str(), w.length()) != (ssize_t)w.length()) {
        bincWarning << "failed to write to " << tpl << ": " << strerror(errno) << endl;
        break;
      }
    }
  }

  if ((fsync(fd) && (errno != EROFS || errno != EINVAL)) || close(fd)) {
    bincWarning << "failed to close " << ftemplate << ": " << strerror(errno) << endl;
    delete[] ftemplate;
    return false;
  }

  if (rename(ftemplate, ".subscribed") != 0) {
    bincWarning << "failed to rename " << ftemplate << " to .subscribed: " << strerror(errno) << endl;
    delete[] ftemplate;
    return false;
  }

  delete[] ftemplate;
  return true;
}

//--------------------------------------------------------------------
Depot::iterator::iterator(void)
{
  dirp = 0;
  ref = new int;
  *ref = 1;
}

//--------------------------------------------------------------------
Depot::iterator::iterator(DIR *dp, struct dirent *sp)
{
  dirp = dp;
  direntp = sp;

  ref = new int;
  *ref = 1;
}

//--------------------------------------------------------------------
Depot::iterator::iterator(const iterator &copy)
{
  if (*copy.ref != 0) ++(*copy.ref);

  ref = copy.ref;
  dirp = copy.dirp;
  direntp = copy.direntp;
}

//--------------------------------------------------------------------
Depot::iterator::~iterator(void)
{
  deref();
}

//--------------------------------------------------------------------
Depot::iterator &Depot::iterator::operator=(const iterator &copy)
{
  if (*copy.ref != 0) ++(*copy.ref);

  deref();

  ref = copy.ref;
  dirp = copy.dirp;
  direntp = copy.direntp;

  return *this;
}

//--------------------------------------------------------------------
void Depot::iterator::deref(void)
{
  // decrease existing copy ref if there is one
  if (*ref != 0 && --(*ref) == 0) {
    if (dirp) {
      closedir(dirp);
      dirp = 0;
    }

    delete ref;
    ref = 0;
  }
}

//--------------------------------------------------------------------
string Depot::iterator::operator*(void) const
{
  if (direntp == 0) return "";

  return direntp->d_name;
}

//--------------------------------------------------------------------
void Depot::iterator::operator++(void)
{
  direntp = readdir(dirp);
}

//--------------------------------------------------------------------
bool Depot::iterator::operator==(Depot::iterator i) const
{
  return direntp == i.direntp;
}

//--------------------------------------------------------------------
bool Depot::iterator::operator!=(Depot::iterator i) const
{
  return direntp != i.direntp;
}

//--------------------------------------------------------------------
Depot::iterator Depot::begin(const string &path) const
{
  Depot::iterator i;

  if ((i.dirp = opendir(path.c_str())) == 0) {
    bincWarning << "opendir on " << path << " failed" << endl;
    setLastError("opendir on " + path + " failed");
    return end();
  }

  ++i;
  return i;
}

//--------------------------------------------------------------------
const Depot::iterator &Depot::end(void) const
{
  return enditerator;
}

//--------------------------------------------------------------------
MaildirPPDepot::MaildirPPDepot(void) : Depot("Maildir++")
{
  privateNamespace = "INBOX";
  privateNamespace += getDelimiter();
}

//--------------------------------------------------------------------
MaildirPPDepot::~MaildirPPDepot(void) {}

//--------------------------------------------------------------------
const string &MaildirPPDepot::getPersonalNamespace(void) const
{
  return privateNamespace;
}

//--------------------------------------------------------------------
string MaildirPPDepot::mailboxToFilename(const string &m) const
{
  string prefix = "INBOX";
  prefix += delimiter;

  string mm = m;
  trim(mm, string(&delimiter, 1));
  string tmp = mm;
  uppercase(tmp);
  if (tmp != "INBOX" && tmp.substr(0, 6) != prefix) {
    setLastError("With a Maildir++ depot, you must create all"
                 " mailboxes under INBOX. Try creating"
                 " "
                 + prefix + mm + " .");
    return "";
  }

  string twodelim;
  twodelim += delimiter;
  twodelim += delimiter;

  if (mm == "INBOX")
    return ".";
  else if (mm.length() <= 6) {
    setLastError("With a Maildir++ depot, you must create all"
                 " mailboxes under INBOX.");
    return "";
  } else if (mm.substr(0, 6) != prefix) {
    setLastError("With a Maildir++ depot, you must create all"
                 " mailboxes under INBOX.");
    return "";
  } else if (mm.find(twodelim) != string::npos) {
    setLastError("Invalid character combination " + twodelim + " in mailbox name");
    return "";
  } else if (mm != "" && delimiter != '.' && mm.substr(1).find('.') != string::npos) {
    setLastError("Invalid character '.' in mailbox name");
    return "";
  } else {
    string tmp = mm.substr(6);
    for (string::iterator i = tmp.begin(); i != tmp.end(); ++i)
      if (*i == delimiter) *i = '.';

    return "." + tmp;
  }
}

//--------------------------------------------------------------------
string MaildirPPDepot::filenameToMailbox(const string &m) const
{
  if (m == ".")
    return "INBOX";
  else if (delimiter != '.' && m.find(delimiter) != string::npos)
    return "";
  else if (m != "" && m[0] == '.') {
    string tmp = m;
    for (string::iterator i = tmp.begin(); i != tmp.end(); ++i)
      if (*i == '.') *i = delimiter;

    return "INBOX" + tmp;
  } else
    return "";
}

//--------------------------------------------------------------------
IMAPdirDepot::IMAPdirDepot(void) : Depot("IMAPdir") {}

//--------------------------------------------------------------------
IMAPdirDepot::~IMAPdirDepot(void) {}

//--------------------------------------------------------------------
string IMAPdirDepot::mailboxToFilename(const string &m) const
{
  string tmp;
  string mm = m;
  trim(mm, string(&delimiter, 1));

  string twodelim;
  twodelim += delimiter;
  twodelim += delimiter;

  if (mm.find(twodelim) != string::npos) {
    setLastError("Invalid character combination " + twodelim + " in mailbox name");
    return "";
  }

  string::const_iterator i = mm.begin();
  while (i != mm.end()) {
    if (*i == delimiter) {
      tmp += '.';
    } else if (*i == '\\') {
      tmp += "\\\\";
    } else if (*i == '.') {
      if (i == mm.begin())
        tmp += ".";
      else
        tmp += "\\.";
    } else {
      tmp += *i;
    }

    ++i;
  }

  return tmp;
}

//--------------------------------------------------------------------
string IMAPdirDepot::filenameToMailbox(const string &m) const
{
  string tmp;
  bool escape = false;

  // hide the magic "." mailbox.
  if (m == "." || m == "..") return "";

  string::const_iterator i = m.begin();
  while (i != m.end()) {
    if (*i == '.') {
      if (i != m.begin() && !escape)
        tmp += delimiter;
      else if (i == m.begin() || escape)
        tmp += '.';
      escape = false;
    } else if (*i == '\\') {
      if (!escape)
        escape = true;
      else {
        tmp += '\\';
        escape = false;
      }
    } else if (*i == delimiter) {
      return "";
    } else {
      if (escape)
        return "";
      else {
        tmp += *i;
        escape = false;
      }
    }

    ++i;
  }

  return tmp;
}