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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
|
/* $Id: mbox.C,v 1.10 2004/06/14 00:18:42 mrsam Exp $
**
** Copyright 2002-2004, Double Precision Inc.
**
** See COPYING for distribution information.
*/
#include "libmail_config.h"
#include "driver.H"
#include "file.H"
#include "misc.H"
#include "mbox.H"
#include "mboxopen.H"
#include "mboxread.H"
#include "mboxexpunge.H"
#include "mboxgetmessage.H"
#include "search.H"
#include "copymessage.H"
#include "mboxmultilock.H"
#include "liblock/config.h"
#include "liblock/mail.h"
#include "rfc822/rfc822.h"
#include "rfc2045/rfc2045.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <ctype.h>
using namespace std;
/////////////////////////////////////////////////////////////////////////////
LIBMAIL_START
static bool open_inbox(mail::account *&accountRet,
mail::account::openInfo &oi,
mail::callback &callback,
mail::callback::disconnect &disconnectCallback)
{
if (oi.url.substr(0, 6) != "inbox:")
return false;
accountRet=new mail::mbox(true, oi.url.substr(6),
callback,
disconnectCallback);
return true;
}
static bool open_mbox(mail::account *&accountRet,
mail::account::openInfo &oi,
mail::callback &callback,
mail::callback::disconnect &disconnectCallback)
{
if (oi.url.substr(0, 5) != "mbox:")
return false;
accountRet=new mail::mbox(false, oi.url.substr(5),
callback,
disconnectCallback);
return true;
}
static bool mbox_remote(string url, bool &flag)
{
if (url.substr(0, 6) == "inbox:" ||
url.substr(0, 5) == "mbox:")
{
flag=false;
return true;
}
return false;
}
driver inbox_driver= { &open_inbox, &mbox_remote };
driver mbox_driver= { &open_mbox, &mbox_remote };
LIBMAIL_END
/////////////////////////////////////////////////////////////////////////////
mail::mbox::task::task(mail::mbox &mboxArg)
: mboxAccount(mboxArg)
{
}
mail::mbox::task::~task()
{
}
void mail::mbox::task::done()
{
if (mboxAccount.tasks.front() != this)
LIBMAIL_THROW("Assertion failed: mail::mbox::task::done");
mboxAccount.tasks.pop();
delete this;
}
/////////////////////////////////////////////////////////////////////////////
mail::mbox::lock::lock()
: ll(NULL), fd(-1), readOnlyLock(false)
{
}
mail::mbox::lock::lock(string filename)
: ll(ll_mail_alloc(filename.c_str())), fd(-1), readOnlyLock(false)
{
if (!ll)
LIBMAIL_THROW("Out of memory.");
}
mail::mbox::lock *mail::mbox::lock::copy()
{
lock *c=new lock();
if (!c)
LIBMAIL_THROW(strerror(errno));
c->ll=ll;
c->fd=fd;
c->readOnlyLock=readOnlyLock;
ll=NULL;
fd=-1;
return c;
}
mail::mbox::lock::~lock()
{
if (fd >= 0)
close(fd);
if (ll)
ll_mail_free(ll);
}
bool mail::mbox::lock::operator()(bool readOnly)
{
if (fd >= 0)
return true;
if (!ll)
{
errno=ENOENT;
return false;
}
// Create a dot-lock file, first.
if (ll_mail_lock(ll) < 0 && !readOnly)
return false;
// Now, open the file.
fd=readOnly ? ll_mail_open_ro(ll):ll_mail_open(ll);
readOnlyLock=readOnly;
return fd >= 0;
}
/////////////////////////////////////////////////////////////////////////////
mail::mbox::TimedTask::TimedTask(mail::mbox &mboxArg,
mail::callback &callbackArg,
int timeoutArg)
: task(mboxArg), timeout(time(NULL) + timeoutArg), nextTry(0),
callback(callbackArg)
{
}
mail::mbox::TimedTask::~TimedTask()
{
}
void mail::mbox::TimedTask::doit(int &timeout)
{
time_t now=time(NULL);
if (nextTry && now < nextTry)
{
int nms=(nextTry - now) * 1000;
if (timeout > nms)
timeout=nms;
return;
}
timeout=0;
if (doit())
return;
nextTry = now + 5; // Try again in 5 seconds.
if (now >= timeout)
timedOut();
}
void mail::mbox::TimedTask::fail(string errmsg)
{
callback.fail(errmsg);
done();
}
void mail::mbox::TimedTask::timedOut()
{
callback.fail("Operation timed out - mail folder in use.");
done();
}
void mail::mbox::TimedTask::disconnected()
{
callback.fail("Operation cancelled.");
}
/////////////////////////////////////////////////////////////////////////////
void mail::mbox::resumed()
{
}
void mail::mbox::handler(vector<pollfd> &fds, int &timeout)
{
// Our job is to do the first task at hand, as simple as that.
if (!tasks.empty())
tasks.front()->doit(timeout);
}
void mail::mbox::installTask(task *t)
{
if (t == NULL)
LIBMAIL_THROW("Out of memory.");
try {
tasks.push(t);
} catch (...) {
delete t;
LIBMAIL_THROW();
}
}
mail::mbox::mbox(bool magicInboxArg,
string folderRoot, mail::callback &callback,
mail::callback::disconnect &disconnect_callback)
: mail::account(disconnect_callback),
calledDisconnected(false),
magicInbox(magicInboxArg),
inboxFolder("INBOX", *this),
hierarchyFolder("", *this),
currentFolderReadOnly(false),
folderSavedSize(0),
folderSavedTimestamp(0),
multiLockLock(NULL),
folderDirty(false),
newMessages(false),
cachedMessageRfcp(NULL),
cachedMessageFp(NULL),
currentFolderCallback(NULL)
{
sigset_t ss;
// Ignore SIGUSR2 from c-client
sigemptyset(&ss);
sigaddset(&ss, SIGUSR2);
sigprocmask(SIG_BLOCK, &ss, NULL);
const char *m=getenv("MAIL");
string h=mail::homedir();
struct passwd *pw=getpwuid(getuid());
if (!pw || h.size() == 0)
{
callback.fail("Cannot find my home directory!");
return;
}
inboxMailboxPath=h + "/Inbox";
// Figure out the mail spool directory.
if (m && *m)
inboxSpoolPath=m;
else
{
static const char *spools[]={"/var/spool/mail", "/var/mail",
"/usr/spool/mail", "/usr/mail",
0};
size_t i;
for (i=0; spools[i]; i++)
if (access(spools[i], X_OK) == 0)
{
inboxSpoolPath=string(spools[i]) + "/"
+ pw->pw_name;
break;
}
if (!spools[i])
{
callback.fail("Cannot determine your system mailbox location,");
return;
}
}
if (folderRoot.size() > 0 && folderRoot[0] != '/')
folderRoot=h + "/" + folderRoot;
rootPath=folderRoot;
// Initialize the top level folder.
hierarchyFolder.path=folderRoot;
hierarchyFolder.name=folder::defaultName(folderRoot);
// First time through, create the top level folder directory, if
// necessary.
if (magicInboxArg)
mkdir(folderRoot.c_str(), 0700);
struct stat stat_buf;
if (stat(folderRoot.c_str(), &stat_buf) == 0 &&
S_ISDIR(stat_buf.st_mode))
{
hierarchyFolder.hasMessages(false);
hierarchyFolder.hasSubFolders(true);
}
else
{
hierarchyFolder.hasMessages(true);
hierarchyFolder.hasSubFolders(false);
}
callback.success("Mail folder opened.");
}
mail::mbox::~mbox()
{
resetFolder();
while (!tasks.empty())
{
tasks.front()->disconnected();
tasks.front()->done();
}
if (!calledDisconnected)
{
calledDisconnected=true;
disconnect_callback.disconnected("");
}
}
//
// General cleanup when the current folder is closed.
//
void mail::mbox::resetFolder()
{
if (multiLockLock)
{
delete multiLockLock;
multiLockLock=NULL;
}
if (cachedMessageRfcp)
{
rfc2045_free(cachedMessageRfcp);
cachedMessageRfcp=NULL;
}
if (cachedMessageFp)
{
fclose(cachedMessageFp);
cachedMessageFp=NULL;
}
cachedMessageUid="";
folderMessageIndex.clear();
uidmap.clear();
folderDirty=false;
newMessages=false;
}
void mail::mbox::logout(mail::callback &callback)
{
if (!folderDirty)
{
callback.success("Mail folder closed.");
return;
}
// Something dirty needs to be saved.
installTask(new ExpungeTask(*this, callback, false, NULL));
}
void mail::mbox::checkNewMail(class mail::callback &callback)
{
if (currentFolder.size() == 0)
{
callback.success("OK"); // Nothing's opened.
return;
}
installTask(new CheckNewMailTask(*this, currentFolder,
callback, NULL));
}
void mail::mbox::checkNewMail()
{
// The real folder contents have been updated, now compare against
// the folder contents seen by the app, and create entries for
// new msgs
set<string> uidSet;
// Create an index of all existing msgs seen by the app.
{
vector<mail::messageInfo>::iterator b, e;
b=index.begin();
e=index.end();
while (b != e)
uidSet.insert( (*b++).uid );
}
// Step through the real folder index, see what's new.
{
vector<mboxMessageIndex>::iterator b, e;
b=folderMessageIndex.begin();
e=folderMessageIndex.end();
while (b != e)
{
mail::messageInfo i=(*b++).tag.getMessageInfo();
if (uidSet.count(i.uid))
continue;
index.push_back(i);
newMessages=true;
}
}
}
bool mail::mbox::hasCapability(string capability)
{
if (capability == LIBMAIL_SINGLEFOLDER)
return hierarchyFolder.hasMessages();
return false;
}
string mail::mbox::getCapability(string name)
{
mail::upper(name);
if (name == LIBMAIL_SERVERTYPE)
{
return "mbox";
}
if (name == LIBMAIL_SERVERDESCR)
{
return "Local mail folder";
}
if (name == LIBMAIL_SINGLEFOLDER)
return hierarchyFolder.hasMessages() ? "1":"";
return "";
}
mail::folder *mail::mbox::folderFromString(string s)
{
string name="";
string::iterator b=s.begin(), e=s.end();
while (b != e)
{
if (*b == '\\')
{
b++;
if (b == e)
break;
} else if (*b == ':')
{
b++;
break;
}
name += *b++;
}
// If the path component is relative, prepend home dir.
string path=string(b, e);
if (path.size() == 0)
path=rootPath;
else if (path[0] != '/' && path != "INBOX")
path=rootPath + "/" + path;
return new folder(path, *this);
}
void mail::mbox::readTopLevelFolders(mail::callback::folderList &callback1,
class mail::callback &callback2)
{
vector<const mail::folder *> folder_list;
if (magicInbox)
folder_list.push_back( &inboxFolder );
if (rootPath.size() > 0)
folder_list.push_back( &hierarchyFolder );
callback1.success(folder_list);
callback2.success("OK");
}
void mail::mbox::findFolder(string path,
mail::callback::folderList &callback1,
mail::callback &callback2)
{
if (path.size() == 0)
path=rootPath;
else if (path[0] != '/' && path != "INBOX")
path=rootPath + "/" + path;
folder *f=new folder(path, *this);
if (!f)
{
callback2.fail(path + ": " + strerror(errno));
return;
}
try {
vector<const mail::folder *> folder_list;
folder_list.push_back(f);
callback1.success(folder_list);
callback2.success("OK");
delete f;
} catch (...) {
delete f;
LIBMAIL_THROW();
}
}
void mail::mbox::readMessageAttributes(const vector<size_t> &messages,
MessageAttributes attributes,
mail::callback::message
&callback)
{
vector<size_t> messageCpy=messages;
// ARRIVALDATE can be handled here, for everything else use the
// generic methods.
if (attributes & mail::account::ARRIVALDATE)
{
attributes &= ~mail::account::ARRIVALDATE;
vector<size_t>::iterator b=messageCpy.begin(),
e=messageCpy.end();
MONITOR(mail::mbox);
while (b != e && !DESTROYED())
{
size_t n= *b++;
if (n >= index.size())
continue;
string uid=index[n].uid;
callback
.messageArrivalDateCallback(n,
uidmap.count(uid)
== 0 ? 0:
folderMessageIndex
[ uidmap.find(uid)
->second]
.internalDate);
}
if (DESTROYED() || attributes == 0)
{
callback.success("OK");
return;
}
}
MultiLockRelease *mlock=new MultiLockRelease(*this, callback);
if (!mlock)
{
callback.fail(strerror(errno));
return;
}
try {
MultiLockGenericAttributes *mr=
new MultiLockGenericAttributes(*this,
messageCpy,
attributes,
*mlock);
if (!mr)
LIBMAIL_THROW((strerror(errno)));
try {
installTask(new MultiLock( *this, *mr ));
} catch (...) {
delete mr;
}
} catch (...) {
delete mlock;
LIBMAIL_THROW();
}
}
void mail::mbox::readMessageContent(const vector<size_t> &messages,
bool peek,
enum mail::readMode readType,
mail::callback::message &callback)
{
MultiLockRelease *mlock=new MultiLockRelease(*this, callback);
if (!mlock)
{
callback.fail(strerror(errno));
return;
}
try {
MultiLockGenericMessageRead *mr=
new MultiLockGenericMessageRead(*this,
messages,
peek,
readType,
*mlock);
if (!mr)
LIBMAIL_THROW((strerror(errno)));
try {
installTask(new MultiLock( *this, *mr ));
} catch (...) {
delete mr;
}
} catch (...) {
delete mlock;
LIBMAIL_THROW();
}
}
void mail::mbox::readMessageContent(size_t messageNum,
bool peek,
const mail::mimestruct &msginfo,
enum mail::readMode readType,
mail::callback::message
&callback)
{
genericReadMessageContent(this, this, messageNum, peek,
msginfo, readType,
callback);
}
void mail::mbox::readMessageContentDecoded(size_t messageNum,
bool peek,
const mail::mimestruct &msginfo,
mail::callback::message
&callback)
{
genericReadMessageContentDecoded(this, this, messageNum, peek,
msginfo,
callback);
}
size_t mail::mbox::getFolderIndexSize()
{
return index.size();
}
mail::messageInfo mail::mbox::getFolderIndexInfo(size_t n)
{
return n < index.size() ? index[n]:mail::messageInfo();
}
void mail::mbox::saveFolderIndexInfo(size_t messageNum,
const mail::messageInfo &info,
mail::callback &callback)
{
MONITOR(mail::mbox);
if (messageNum < index.size())
{
folderDirty=true;
#define DOFLAG(dummy1, field, dummy2) \
(index[messageNum].field= info.field)
LIBMAIL_MSGFLAGS;
#undef DOFLAG
}
callback.success(currentFolderReadOnly ?
"Folder opened in read-only mode.":
"Message updated.");
if (! DESTROYED() && messageNum < index.size()
&& currentFolderCallback)
currentFolderCallback->messageChanged(messageNum);
}
void mail::mbox::updateFolderIndexFlags(const vector<size_t> &messages,
bool doFlip,
bool enableDisable,
const mail::messageInfo &flags,
mail::callback &callback)
{
vector<size_t>::const_iterator b, e;
b=messages.begin();
e=messages.end();
size_t n=index.size();
while (b != e)
{
size_t i= *b++;
if (i < n)
{
#define DOFLAG(dummy, field, dummy2) \
if (flags.field) \
{ \
index[i].field=\
doFlip ? !index[i].field\
: enableDisable; \
}
LIBMAIL_MSGFLAGS;
#undef DOFLAG
}
}
folderDirty=true;
b=messages.begin();
e=messages.end();
MONITOR(mail::mbox);
while (!DESTROYED() && b != e)
{
size_t i= *b++;
if (i < n && currentFolderCallback)
currentFolderCallback->messageChanged(i);
}
callback.success(!DESTROYED() && currentFolderReadOnly ?
"Folder opened in read-only mode.":
"Message updated.");
}
void mail::mbox::genericMarkRead(size_t messageNumber)
{
if (messageNumber < index.size() && index[messageNumber].unread)
{
index[messageNumber].unread=false;
folderDirty=true;
if (currentFolderCallback)
currentFolderCallback->messageChanged(messageNumber);
}
}
void mail::mbox::updateFolderIndexInfo(mail::callback &callback)
{
if (currentFolder.size() == 0)
{
callback.success("Mail folder updated");
return;
}
installTask(new ExpungeTask(*this, callback, true, NULL));
}
void mail::mbox::getFolderKeywordInfo(size_t messageNumber,
set<string> &keywords)
{
keywords.clear();
if (messageNumber < index.size())
{
map<string, size_t>::iterator p=
uidmap.find(index[messageNumber].uid);
if (p != uidmap.end())
{
folderMessageIndex[p->second].tag.getKeywords()
.getFlags(keywords);
}
}
}
void mail::mbox::updateKeywords(const std::vector<size_t> &messages,
const std::set<std::string> &keywords,
bool setOrChange,
// false: set, true: see changeTo
bool changeTo,
callback &cb)
{
genericUpdateKeywords(messages, keywords,
setOrChange, changeTo, currentFolderCallback,
this, cb);
}
bool mail::mbox::genericProcessKeyword(size_t messageNumber,
generic::updateKeywordHelper &helper)
{
if (messageNumber < index.size())
{
map<string, size_t>::iterator p=
uidmap.find(index[messageNumber].uid);
if (p != uidmap.end())
{
folderDirty=true;
return helper
.doUpdateKeyword(folderMessageIndex[p->second]
.tag.getKeywords(),
keywordHashtable);
}
}
return true;
}
void mail::mbox::removeMessages(const std::vector<size_t> &messages,
callback &cb)
{
installTask(new ExpungeTask(*this, cb, true, &messages));
}
void mail::mbox::copyMessagesTo(const vector<size_t> &messages,
mail::folder *copyTo,
mail::callback &callback)
{
mail::copyMessages::copy(this, messages, copyTo, callback);
}
void mail::mbox::searchMessages(const class mail::searchParams &searchInfo,
mail::searchCallback &callback)
{
mail::searchMessages::search(callback, searchInfo, this);
}
/////////////////////////////////////////////////////////////////////////////
//
// Generic message access implementation
void mail::mbox::genericMessageRead(string uid,
size_t messageNumber,
bool peek,
mail::readMode readType,
mail::callback::message &callback)
{
installTask(new GenericReadTask(*this, callback, uid, messageNumber,
peek, readType));
}
bool mail::mbox::verifyUid(string uid, size_t &messageNumber,
mail::callback &callback)
{
if (uidmap.count(uid) > 0)
{
if (messageNumber < index.size() &&
index[messageNumber].uid == uid)
return true;
size_t n=index.size();
while (n)
{
if (index[--n].uid == uid)
{
messageNumber=n;
return true;
}
}
}
callback.fail("Message no longer exists in the folder.");
return false;
}
void mail::mbox::genericMessageSize(string uid,
size_t messageNumber,
mail::callback::message &callback)
{
if (!verifyUid(uid, messageNumber, callback))
return;
size_t n=uidmap.find(uid)->second;
off_t s=folderMessageIndex[n].startingPos;
off_t e=n + 1 >= folderMessageIndex.size()
? folderSavedSize:folderMessageIndex[n+1].startingPos;
callback.messageSizeCallback( messageNumber, e > s ? e-s:0);
callback.success("OK");
}
void mail::mbox::genericGetMessageFd(string uid,
size_t messageNumber,
bool peek,
int &fdRet,
mail::callback &callback)
{
if (uid == cachedMessageUid && cachedMessageFp)
{
fdRet=fileno(cachedMessageFp);
callback.success("OK");
return;
}
installTask(new GenericGetMessageTask(*this, callback,
uid, messageNumber,
peek,
&fdRet, NULL));
}
void mail::mbox::genericGetMessageStruct(string uid,
size_t messageNumber,
struct rfc2045 *&structRet,
mail::callback &callback)
{
if (uid == cachedMessageUid && cachedMessageRfcp)
{
structRet=cachedMessageRfcp;
callback.success("OK");
return;
}
installTask(new GenericGetMessageTask(*this, callback,
uid, messageNumber,
true,
NULL, &structRet));
}
void mail::mbox::genericGetMessageFdStruct(string uid,
size_t messageNumber,
bool peek,
int &fdRet,
struct rfc2045 *&structret,
mail::callback &callback)
{
if (uid == cachedMessageUid && cachedMessageRfcp &&
cachedMessageFp)
{
structret=cachedMessageRfcp;
fdRet=fileno(cachedMessageFp);
callback.success("OK");
return;
}
installTask(new GenericGetMessageTask(*this, callback,
uid, messageNumber,
peek,
&fdRet, &structret));
}
bool mail::mbox::genericCachedUid(string uid)
{
return uid == cachedMessageUid && cachedMessageRfcp;
}
/*
** Hack away at ctime ("Wed Sep 01 13:58:06 2002")
** in the From_ header until we end up with a timestamp
*/
static time_t fromCtime(string hdr)
{
char mon[4];
int dom, h, m, s, y;
char tempbuf[100];
struct tm *tmptr;
time_t tv;
int mnum;
const char *p=hdr.c_str();
while (*p && !isspace((int)(unsigned char)*p))
p++;
p++;
while (*p && !isspace((int)(unsigned char)*p))
p++;
if (sscanf(p, "%*s %3s %d %d:%d:%d %d", mon, &dom,
&h, &m, &s, &y)!=6)
return 0;
/* Some hackery to get the month number */
sprintf(tempbuf, "15 %s %d 12:00:00", mon, y);
tv=rfc822_parsedt(tempbuf);
if (tv == 0)
return 0;
tmptr=localtime(&tv);
mnum=tmptr->tm_mon;
/* For real, this time */
sprintf(tempbuf, "%d %s %d 00:00:00", dom, mon, y);
tv=rfc822_parsedt(tempbuf);
if (tv == 0)
return 0;
tmptr=localtime(&tv);
while ((tmptr=localtime(&tv))->tm_year + 1900 < y ||
(tmptr->tm_year + 1900 == y && tmptr->tm_mon < mnum) ||
(tmptr->tm_year + 1900 == y && tmptr->tm_mon == mnum &&
tmptr->tm_mday < dom))
tv += 60 * 60;
while ((tmptr=localtime(&tv))->tm_year + 1900 > y ||
(tmptr->tm_year + 1900 == y && tmptr->tm_mon > mnum) ||
(tmptr->tm_year + 1900 == y && tmptr->tm_mon == mnum &&
tmptr->tm_mday > dom))
tv -= 60 * 60;
while ((tmptr=localtime(&tv))->tm_mday == dom &&
tmptr->tm_hour < h)
tv += 60 * 60;
while ((tmptr=localtime(&tv))->tm_mday == dom &&
tmptr->tm_hour > h)
tv -= 60 * 60;
tv += m * 60 + s;
return tv;
}
/////////////////////////////////////////////////////////////////////////////
//
// scan() is where all the exciting stuff happens. scan() reads a file with
// messages; potentially copies the messages to another file.
//
// scan() is invoked in the following situations, where it acts as follows:
//
// A. OPENING A NEW FOLDER
//
// saveFile=NULL, reopening=false, deleteMsgs=NULL, rewriting=false
//
// folderMessageIndex and uidmap are created based on the messages in
// the file. folderDirty is set to true if there are messages in the
// file without an existing UID (in which case each message is assigned
// a new UID).
//
// B. NEW MAIL CHECK FROM SYSTEM MAILBOX
//
// saveFile=not NULL, reopening=false, deleteMsgs=NULL, rewriting=false
//
// Previously, scan() was called in situation A, to open $HOME/Inbox.
// This time, saveFile is $HOME/Inbox, and scanFile is the existing file
// is the spoolfile (/var/spool/something, usually).
//
// If any messages are found in the spoolfile, they are copied to saveFile,
// and are added to folderMessageIndex and uidmap. Any existing UIDs in
// the new messages are ignored, each new message is assigned a new UID,
// and folderDirty is set to true.
//
// C. REOPENING A FOLDER
//
// saveFile=NULL, reopening=true, deleteMsgs=NULL, rewriting=false
//
// If we believe that the file has not been touched by another process
// (timestamp and size have not been changed), everything is left alone
// the way it is. Otherwise;
//
// folderMessageIndex and uidmap are created based on the messages in
// the file. folderDirty is set to true if there are messages in the
// file without an existing UID (in which case each message is assigned
// a new UID).
//
// D. EXPUNGING THE FOLDER
//
// saveFile=new file, reopening=true, deleteMsgs != NULL, rewriting=true
//
// Messages are copied to saveFile, except ones that are marked as
// deleted. folderMessageIndex and uidmap are updated accordingly.
//
// E. CLOSING THE FOLDER
//
// saveFile=new file, reopening=true, deleteMsgs=NULL, rewriting=true
//
// All messages are copied to saveFile, with any updated flags and uids.
//
bool mail::mbox::scan(mail::file &scanFile,
mail::file *saveFile,
bool reopening,
set<string> *deleteMsgs,
bool rewriting,
mail::callback *progress)
{
struct stat stat_buf;
set<string> deleted; // All deleted UIDs
map<string, mail::messageInfo *> updatedFlags;
// List of all updated flags
vector<mboxMessageIndex> newMessageIndex;
// All new UIDs that were created for messages without UIDs.
if (reopening)
{
// Initialize the list of all updated message flags,
// as well as the deleted messages that should not be copied
vector<mail::messageInfo>::iterator b=index.begin(),
e=index.end();
while (b != e)
{
mail::messageInfo &i=*b++;
if (deleteMsgs != NULL)
{
if (deleteMsgs->count(i.uid) > 0)
deleted.insert(i.uid);
}
updatedFlags.insert(make_pair(i.uid, &i));
}
}
// Read the folder file, line by line.
// Keep track of the starting points of each message.
bool skipping=false; // Not copying the current message
bool copying=false; // Message copy in progress
bool seenFrom=false; // Previous line was a From_ line.
string fromhdr;
stat_buf.st_size=0;
off_t nextUpdatePos=0;
off_t fromPos=0;
size_t rewriteIndex=0;
string fromLine;
scanFile.seeked();
while (!feof(scanFile))
{
off_t pos; // Current line starts here
if ((pos=scanFile.tell()) < 0)
{
return false;
}
// Every 10k bytes send an update.
if (progress && pos >= nextUpdatePos)
{
nextUpdatePos=pos + 10000;
progress->reportProgress(pos, stat_buf.st_size, 0, 1);
}
string line=scanFile.getline();
if (strncmp(line.c_str(), "From ", 5) == 0)
{
fromhdr=line;
// copying is false if this is the first message.
if (!copying &&
saveFile) // Copying messages.
{
// We're copying messages, and this is the
// first message. A couple of things must
// be done:
// Remember how big the saveFile was,
// originally.
if (fstat(fileno(static_cast<FILE *>
(*saveFile)),
// fileno may be a macro
&stat_buf) < 0)
{
return false;
}
// Make sure From of the first new
// message begins on a new line
if (stat_buf.st_size > 0)
{
if (fseek(*saveFile, -1L, SEEK_END)
< 0)
{
return false;
}
int c=getc(*saveFile);
if (fseek(*saveFile, 0L, SEEK_END) < 0)
{
return false;
}
if (c != '\n')
{
stat_buf.st_size++;
putc('\n', *saveFile);
}
}
}
if (!copying && // First message
!saveFile && reopening && !rewriting) // REOPENING
{
// Potential short cut.
if (fstat(fileno(static_cast<FILE *>(scanFile)),
&stat_buf) < 0)
{
return false;
}
if (stat_buf.st_size == folderSavedSize &&
stat_buf.st_mtime ==
folderSavedTimestamp)
{
return true;
}
}
if (!copying && // First message
!saveFile) // NOT READING NEW MAIL
resetFolder();
copying=true;
fromLine=line;
if (saveFile)
{
if ((pos=ftell(*saveFile)) < 0)
{
return false;
}
}
fromPos=pos;
seenFrom=true;
continue;
}
if (seenFrom) // Previous line was the From_ line.
{
seenFrom=false;
skipping=false;
// Does the first line of the message has our magic
// tag?
mail::mboxMagicTag tag(line, keywordHashtable);
if (tag.good()) // Yes.
{
string uid=tag.getMessageInfo().uid;
if (deleted.count(uid) > 0)
// This one's deleted.
{
skipping=true;
rewriteIndex++;
continue;
}
if (saveFile)
// Flags in the file might be stale,
// make sure the current flags are
// written out later.
{
if (updatedFlags.count(uid) > 0)
{
mail::messageInfo *i=
updatedFlags
.find(uid)->second;
map<string, size_t>
::iterator kw=
uidmap.find(uid);
tag=mail::mboxMagicTag(uid,
*i,
kw ==
uidmap.end() ?
tag.getKeywords():
folderMessageIndex[kw->second].tag.getKeywords());
}
else
// READING NEW MAIL -- ignore
// existing tags.
tag=mail::mboxMagicTag();
fprintf(*saveFile, "%s\n%s\n",
fromLine.c_str(),
tag.toString().c_str());
}
}
else if (rewriteIndex < folderMessageIndex.size() &&
deleted.count(folderMessageIndex[rewriteIndex]
.tag.getMessageInfo().uid) > 0)
{
// The folder was opened, this was a new
// message without a tag. Subsequently the
// message was marked deleted. We can assume
// that folderMessageIndex is valid at this
// point in time because the mailbox file is
// locked.
skipping=true;
rewriteIndex++;
continue;
}
else
{
folderDirty=true;
if (rewriting &&
rewriteIndex < folderMessageIndex.size())
{
// See the previous comment, except
// for the part where the message was
// marked as deleted.
tag=folderMessageIndex[rewriteIndex]
.tag;
string uid=tag.getMessageInfo().uid;
if (updatedFlags.count(uid) > 0)
{
mail::messageInfo *i=
updatedFlags
.find(uid)->second;
tag=mail::mboxMagicTag(uid,
*i,
tag.getKeywords());
}
}
else // Yes, it's really a new message.
tag=mail::mboxMagicTag();
if (saveFile)
{
fprintf(*saveFile, "%s\n%s\n%s\n",
fromLine.c_str(),
tag.toString().c_str(),
line.c_str());
}
}
rewriteIndex++;
mail::messageInfo info=tag.getMessageInfo();
mboxMessageIndex newIndex;
newIndex.startingPos=fromPos;
newIndex.tag=tag;
if ((newIndex.internalDate=fromCtime(fromhdr)) == 0)
newIndex.internalDate=time(NULL);
newMessageIndex.push_back(newIndex);
}
else // Message contents
{
if (!copying)
{
// If we get here, this is the first
// non-empty line in the file, and it is
// not a From_ line.
if (line.size() == 0)
continue;
errno=EINVAL;
return false;
}
if (line.size() == 0 && feof(scanFile))
break;
if (!skipping && saveFile)
fprintf(*saveFile, "%s\n", line.c_str());
}
}
// Ok, we've created newMessageIndex, and we have an existing index
// what now?
//
// Blow away the existing index if:
// 1. Rewriting or closing the folder
// 2. If we're opening or reopening the folder, an the file did
// not have any messages (resetFolder() was never called inside
// the loop - see above).
//
if ((!copying && !saveFile) || rewriting)
resetFolder();
// At this point now we'll append newMessageIndex to whatever's in
// folderMessageIndex, and update uidmap accordingly.
vector<mboxMessageIndex>::iterator b, e;
b=newMessageIndex.begin();
e=newMessageIndex.end();
size_t n=folderMessageIndex.size();
while (b != e)
{
mboxMessageIndex &i= *b++;
mail::messageInfo info=i.tag.getMessageInfo();
if (uidmap.count(info.uid) > 0) // SHOULD NOT HAPPEN
{
info.uid=mail::mboxMagicTag().getMessageInfo().uid;
i.tag=mail::mboxMagicTag(info.uid, info,
i.tag.getKeywords());
folderDirty=true;
}
folderMessageIndex.insert(folderMessageIndex.end(), i);
try {
uidmap.insert(make_pair(info.uid, n));
} catch (...) {
folderMessageIndex.erase(folderMessageIndex.begin()+n);
LIBMAIL_THROW();
}
n++;
}
// Cleanup
if (progress)
progress->reportProgress(stat_buf.st_size, stat_buf.st_size,
0, 1);
if (saveFile && (ferror(*saveFile) || fflush(*saveFile) < 0))
{
return false;
}
if (ferror(scanFile))
{
return false;
}
return true;
}
void mail::mbox::mkverbotten(vector<unicode_char> &verbotten)
{
verbotten.push_back('/');
verbotten.push_back('~');
verbotten.push_back(0);
}
string mail::mbox::translatePath(string path)
{
vector<unicode_char> verbotten;
mkverbotten(verbotten);
return translatePathCommon(path, verbotten, "/");
}
|