00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include <config.h>
00021 #include <qfileinfo.h>
00022 #include <qregexp.h>
00023
00024 #include "kmfoldermbox.h"
00025 #include "folderstorage.h"
00026 #include "kmfolder.h"
00027 #include "kmkernel.h"
00028 #include "kmmsgdict.h"
00029 #include "undostack.h"
00030 #include "kcursorsaver.h"
00031 #include "jobscheduler.h"
00032 #include "compactionjob.h"
00033 #include "util.h"
00034
00035 #include <kdebug.h>
00036 #include <klocale.h>
00037 #include <kmessagebox.h>
00038 #include <knotifyclient.h>
00039 #include <kprocess.h>
00040 #include <kconfig.h>
00041
00042 #include <ctype.h>
00043 #include <stdio.h>
00044 #include <errno.h>
00045 #include <assert.h>
00046 #include <ctype.h>
00047 #include <unistd.h>
00048
00049 #ifdef HAVE_FCNTL_H
00050 #include <fcntl.h>
00051 #endif
00052
00053 #include <stdlib.h>
00054 #include <sys/types.h>
00055 #include <sys/stat.h>
00056 #include <sys/file.h>
00057 #include "broadcaststatus.h"
00058 using KPIM::BroadcastStatus;
00059
00060 #ifndef MAX_LINE
00061 #define MAX_LINE 4096
00062 #endif
00063 #ifndef INIT_MSGS
00064 #define INIT_MSGS 8
00065 #endif
00066
00067
00068
00069 #define MSG_SEPERATOR_START "From "
00070 #define MSG_SEPERATOR_START_LEN (sizeof(MSG_SEPERATOR_START) - 1)
00071 #define MSG_SEPERATOR_REGEX "^From .*[0-9][0-9]:[0-9][0-9]"
00072
00073
00074
00075 KMFolderMbox::KMFolderMbox(KMFolder* folder, const char* name)
00076 : KMFolderIndex(folder, name)
00077 {
00078 mStream = 0;
00079 mFilesLocked = false;
00080 mReadOnly = false;
00081 mLockType = lock_none;
00082 }
00083
00084
00085
00086 KMFolderMbox::~KMFolderMbox()
00087 {
00088 if (mOpenCount>0)
00089 close("~kmfoldermbox", true);
00090 if (kmkernel->undoStack())
00091 kmkernel->undoStack()->folderDestroyed( folder() );
00092 }
00093
00094
00095 int KMFolderMbox::open(const char *owner)
00096 {
00097 Q_UNUSED( owner );
00098 int rc = 0;
00099
00100 mOpenCount++;
00101 kmkernel->jobScheduler()->notifyOpeningFolder( folder() );
00102
00103 if (mOpenCount > 1) return 0;
00104
00105 assert(!folder()->name().isEmpty());
00106
00107 mFilesLocked = false;
00108 mStream = fopen(QFile::encodeName(location()), "r+");
00109 if (!mStream)
00110 {
00111 KNotifyClient::event( 0, "warning",
00112 i18n("Cannot open file \"%1\":\n%2").arg(location()).arg(strerror(errno)));
00113 kdDebug(5006) << "Cannot open folder `" << location() << "': " << strerror(errno) << endl;
00114 mOpenCount = 0;
00115 return errno;
00116 }
00117
00118 lock();
00119
00120 if (!folder()->path().isEmpty())
00121 {
00122 KMFolderIndex::IndexStatus index_status = indexStatus();
00123
00124 if (KMFolderIndex::IndexOk != index_status)
00125 {
00126
00127
00128 if (KMFolderIndex::IndexTooOld == index_status) {
00129 QString msg = i18n("<qt><p>The index of folder '%2' seems "
00130 "to be out of date. To prevent message "
00131 "corruption the index will be "
00132 "regenerated. As a result deleted "
00133 "messages might reappear and status "
00134 "flags might be lost.</p>"
00135 "<p>Please read the corresponding entry "
00136 "in the <a href=\"%1\">FAQ section of the manual "
00137 "of KMail</a> for "
00138 "information about how to prevent this "
00139 "problem from happening again.</p></qt>")
00140 .arg("help:/kmail/faq.html#faq-index-regeneration")
00141 .arg(name());
00142
00143
00144
00145
00146 if (kmkernel->startingUp())
00147 {
00148 KConfigGroup configGroup( KMKernel::config(), "Notification Messages" );
00149 bool showMessage =
00150 configGroup.readBoolEntry( "showIndexRegenerationMessage", true );
00151 if (showMessage)
00152 KMessageBox::queuedMessageBox( 0, KMessageBox::Information,
00153 msg, i18n("Index Out of Date"),
00154 KMessageBox::AllowLink );
00155 }
00156 else
00157 {
00158 KCursorSaver idle(KBusyPtr::idle());
00159 KMessageBox::information( 0, msg, i18n("Index Out of Date"),
00160 "showIndexRegenerationMessage",
00161 KMessageBox::AllowLink );
00162 }
00163 }
00164 QString str;
00165 mIndexStream = 0;
00166 str = i18n("Folder `%1' changed. Recreating index.")
00167 .arg(name());
00168 emit statusMsg(str);
00169 } else {
00170 mIndexStream = fopen(QFile::encodeName(indexLocation()), "r+");
00171 if ( mIndexStream ) {
00172 fcntl(fileno(mIndexStream), F_SETFD, FD_CLOEXEC);
00173 updateIndexStreamPtr();
00174 }
00175 }
00176
00177 if (!mIndexStream)
00178 rc = createIndexFromContents();
00179 else
00180 if (!readIndex())
00181 rc = createIndexFromContents();
00182 }
00183 else
00184 {
00185 mAutoCreateIndex = false;
00186 rc = createIndexFromContents();
00187 }
00188
00189 mChanged = false;
00190
00191 fcntl(fileno(mStream), F_SETFD, FD_CLOEXEC);
00192 if (mIndexStream)
00193 fcntl(fileno(mIndexStream), F_SETFD, FD_CLOEXEC);
00194
00195 return rc;
00196 }
00197
00198
00199 int KMFolderMbox::canAccess()
00200 {
00201 assert(!folder()->name().isEmpty());
00202
00203 if (access(QFile::encodeName(location()), R_OK | W_OK) != 0) {
00204 kdDebug(5006) << "KMFolderMbox::access call to access function failed" << endl;
00205 return 1;
00206 }
00207 return 0;
00208 }
00209
00210
00211 int KMFolderMbox::create()
00212 {
00213 int rc;
00214 int old_umask;
00215
00216 assert(!folder()->name().isEmpty());
00217 assert(mOpenCount == 0);
00218
00219 kdDebug(5006) << "Creating folder " << name() << endl;
00220 if (access(QFile::encodeName(location()), F_OK) == 0) {
00221 kdDebug(5006) << "KMFolderMbox::create call to access function failed." << endl;
00222 kdDebug(5006) << "File:: " << endl;
00223 kdDebug(5006) << "Error " << endl;
00224 return EEXIST;
00225 }
00226
00227 old_umask = umask(077);
00228 mStream = fopen(QFile::encodeName(location()), "w+");
00229 umask(old_umask);
00230
00231 if (!mStream) return errno;
00232
00233 fcntl(fileno(mStream), F_SETFD, FD_CLOEXEC);
00234
00235 if (!folder()->path().isEmpty())
00236 {
00237 old_umask = umask(077);
00238 mIndexStream = fopen(QFile::encodeName(indexLocation()), "w+");
00239 updateIndexStreamPtr(true);
00240 umask(old_umask);
00241
00242 if (!mIndexStream) return errno;
00243 fcntl(fileno(mIndexStream), F_SETFD, FD_CLOEXEC);
00244 }
00245 else
00246 {
00247 mAutoCreateIndex = false;
00248 }
00249
00250 mOpenCount++;
00251 mChanged = false;
00252
00253 rc = writeIndex();
00254 if (!rc) lock();
00255 return rc;
00256 }
00257
00258
00259
00260 void KMFolderMbox::reallyDoClose(const char* owner)
00261 {
00262 Q_UNUSED( owner );
00263 if (mAutoCreateIndex)
00264 {
00265 if (KMFolderIndex::IndexOk != indexStatus()) {
00266 kdDebug(5006) << "Critical error: " << location() <<
00267 " has been modified by an external application while KMail was running." << endl;
00268
00269 }
00270
00271 updateIndex();
00272 writeConfig();
00273 }
00274
00275 if (!noContent()) {
00276 if (mStream) unlock();
00277 mMsgList.clear(true);
00278
00279 if (mStream) fclose(mStream);
00280 if (mIndexStream) {
00281 fclose(mIndexStream);
00282 updateIndexStreamPtr(true);
00283 }
00284 }
00285 mOpenCount = 0;
00286 mStream = 0;
00287 mIndexStream = 0;
00288 mFilesLocked = false;
00289 mUnreadMsgs = -1;
00290
00291 mMsgList.reset(INIT_MSGS);
00292 }
00293
00294
00295 void KMFolderMbox::sync()
00296 {
00297 if (mOpenCount > 0)
00298 if (!mStream || fsync(fileno(mStream)) ||
00299 !mIndexStream || fsync(fileno(mIndexStream))) {
00300 kmkernel->emergencyExit( i18n("Could not sync index file <b>%1</b>: %2").arg( indexLocation() ).arg(errno ? QString::fromLocal8Bit(strerror(errno)) : i18n("Internal error. Please copy down the details and report a bug.")));
00301 }
00302 }
00303
00304
00305 int KMFolderMbox::lock()
00306 {
00307 int rc;
00308 struct flock fl;
00309 fl.l_type=F_WRLCK;
00310 fl.l_whence=0;
00311 fl.l_start=0;
00312 fl.l_len=0;
00313 fl.l_pid=-1;
00314 QCString cmd_str;
00315 assert(mStream != 0);
00316 mFilesLocked = false;
00317 mReadOnly = false;
00318
00319 switch( mLockType )
00320 {
00321 case FCNTL:
00322 rc = fcntl(fileno(mStream), F_SETLKW, &fl);
00323
00324 if (rc < 0)
00325 {
00326 kdDebug(5006) << "Cannot lock folder `" << location() << "': "
00327 << strerror(errno) << " (" << errno << ")" << endl;
00328 mReadOnly = true;
00329 return errno;
00330 }
00331
00332 if (mIndexStream)
00333 {
00334 rc = fcntl(fileno(mIndexStream), F_SETLK, &fl);
00335
00336 if (rc < 0)
00337 {
00338 kdDebug(5006) << "Cannot lock index of folder `" << location() << "': "
00339 << strerror(errno) << " (" << errno << ")" << endl;
00340 rc = errno;
00341 fl.l_type = F_UNLCK;
00342 fcntl(fileno(mIndexStream), F_SETLK, &fl);
00343 mReadOnly = true;
00344 return rc;
00345 }
00346 }
00347 break;
00348
00349 case procmail_lockfile:
00350 cmd_str = "lockfile -l20 -r5 ";
00351 if (!mProcmailLockFileName.isEmpty())
00352 cmd_str += QFile::encodeName(KProcess::quote(mProcmailLockFileName));
00353 else
00354 cmd_str += QFile::encodeName(KProcess::quote(location() + ".lock"));
00355
00356 rc = system( cmd_str.data() );
00357 if( rc != 0 )
00358 {
00359 kdDebug(5006) << "Cannot lock folder `" << location() << "': "
00360 << strerror(rc) << " (" << rc << ")" << endl;
00361 mReadOnly = true;
00362 return rc;
00363 }
00364 if( mIndexStream )
00365 {
00366 cmd_str = "lockfile -l20 -r5 " + QFile::encodeName(KProcess::quote(indexLocation() + ".lock"));
00367 rc = system( cmd_str.data() );
00368 if( rc != 0 )
00369 {
00370 kdDebug(5006) << "Cannot lock index of folder `" << location() << "': "
00371 << strerror(rc) << " (" << rc << ")" << endl;
00372 mReadOnly = true;
00373 return rc;
00374 }
00375 }
00376 break;
00377
00378 case mutt_dotlock:
00379 cmd_str = "mutt_dotlock " + QFile::encodeName(KProcess::quote(location()));
00380 rc = system( cmd_str.data() );
00381 if( rc != 0 )
00382 {
00383 kdDebug(5006) << "Cannot lock folder `" << location() << "': "
00384 << strerror(rc) << " (" << rc << ")" << endl;
00385 mReadOnly = true;
00386 return rc;
00387 }
00388 if( mIndexStream )
00389 {
00390 cmd_str = "mutt_dotlock " + QFile::encodeName(KProcess::quote(indexLocation()));
00391 rc = system( cmd_str.data() );
00392 if( rc != 0 )
00393 {
00394 kdDebug(5006) << "Cannot lock index of folder `" << location() << "': "
00395 << strerror(rc) << " (" << rc << ")" << endl;
00396 mReadOnly = true;
00397 return rc;
00398 }
00399 }
00400 break;
00401
00402 case mutt_dotlock_privileged:
00403 cmd_str = "mutt_dotlock -p " + QFile::encodeName(KProcess::quote(location()));
00404 rc = system( cmd_str.data() );
00405 if( rc != 0 )
00406 {
00407 kdDebug(5006) << "Cannot lock folder `" << location() << "': "
00408 << strerror(rc) << " (" << rc << ")" << endl;
00409 mReadOnly = true;
00410 return rc;
00411 }
00412 if( mIndexStream )
00413 {
00414 cmd_str = "mutt_dotlock -p " + QFile::encodeName(KProcess::quote(indexLocation()));
00415 rc = system( cmd_str.data() );
00416 if( rc != 0 )
00417 {
00418 kdDebug(5006) << "Cannot lock index of folder `" << location() << "': "
00419 << strerror(rc) << " (" << rc << ")" << endl;
00420 mReadOnly = true;
00421 return rc;
00422 }
00423 }
00424 break;
00425
00426 case lock_none:
00427 default:
00428 break;
00429 }
00430
00431
00432 mFilesLocked = true;
00433 return 0;
00434 }
00435
00436
00437 FolderJob*
00438 KMFolderMbox::doCreateJob( KMMessage *msg, FolderJob::JobType jt,
00439 KMFolder *folder, QString, const AttachmentStrategy* ) const
00440 {
00441 MboxJob *job = new MboxJob( msg, jt, folder );
00442 job->setParent( this );
00443 return job;
00444 }
00445
00446
00447 FolderJob*
00448 KMFolderMbox::doCreateJob( QPtrList<KMMessage>& msgList, const QString& sets,
00449 FolderJob::JobType jt, KMFolder *folder ) const
00450 {
00451 MboxJob *job = new MboxJob( msgList, sets, jt, folder );
00452 job->setParent( this );
00453 return job;
00454 }
00455
00456
00457 int KMFolderMbox::unlock()
00458 {
00459 int rc;
00460 struct flock fl;
00461 fl.l_type=F_UNLCK;
00462 fl.l_whence=0;
00463 fl.l_start=0;
00464 fl.l_len=0;
00465 QCString cmd_str;
00466
00467 assert(mStream != 0);
00468 mFilesLocked = false;
00469
00470 switch( mLockType )
00471 {
00472 case FCNTL:
00473 if (mIndexStream) fcntl(fileno(mIndexStream), F_SETLK, &fl);
00474 fcntl(fileno(mStream), F_SETLK, &fl);
00475 rc = errno;
00476 break;
00477
00478 case procmail_lockfile:
00479 cmd_str = "rm -f ";
00480 if (!mProcmailLockFileName.isEmpty())
00481 cmd_str += QFile::encodeName(KProcess::quote(mProcmailLockFileName));
00482 else
00483 cmd_str += QFile::encodeName(KProcess::quote(location() + ".lock"));
00484
00485 rc = system( cmd_str.data() );
00486 if( mIndexStream )
00487 {
00488 cmd_str = "rm -f " + QFile::encodeName(KProcess::quote(indexLocation() + ".lock"));
00489 rc = system( cmd_str.data() );
00490 }
00491 break;
00492
00493 case mutt_dotlock:
00494 cmd_str = "mutt_dotlock -u " + QFile::encodeName(KProcess::quote(location()));
00495 rc = system( cmd_str.data() );
00496 if( mIndexStream )
00497 {
00498 cmd_str = "mutt_dotlock -u " + QFile::encodeName(KProcess::quote(indexLocation()));
00499 rc = system( cmd_str.data() );
00500 }
00501 break;
00502
00503 case mutt_dotlock_privileged:
00504 cmd_str = "mutt_dotlock -p -u " + QFile::encodeName(KProcess::quote(location()));
00505 rc = system( cmd_str.data() );
00506 if( mIndexStream )
00507 {
00508 cmd_str = "mutt_dotlock -p -u " + QFile::encodeName(KProcess::quote(indexLocation()));
00509 rc = system( cmd_str.data() );
00510 }
00511 break;
00512
00513 case lock_none:
00514 default:
00515 rc = 0;
00516 break;
00517 }
00518
00519 return rc;
00520 }
00521
00522
00523
00524 KMFolderIndex::IndexStatus KMFolderMbox::indexStatus()
00525 {
00526 QFileInfo contInfo(location());
00527 QFileInfo indInfo(indexLocation());
00528
00529 if (!contInfo.exists()) return KMFolderIndex::IndexOk;
00530 if (!indInfo.exists()) return KMFolderIndex::IndexMissing;
00531
00532
00533
00534
00535 return ( contInfo.lastModified() > indInfo.lastModified().addSecs(5) )
00536 ? KMFolderIndex::IndexTooOld
00537 : KMFolderIndex::IndexOk;
00538 }
00539
00540
00541
00542 int KMFolderMbox::createIndexFromContents()
00543 {
00544 char line[MAX_LINE];
00545 char status[8], xstatus[8];
00546 QCString subjStr, dateStr, fromStr, toStr, xmarkStr, *lastStr=0;
00547 QCString replyToIdStr, replyToAuxIdStr, referencesStr, msgIdStr;
00548 QCString sizeServerStr, uidStr;
00549 QCString contentTypeStr, charset;
00550 bool atEof = false;
00551 bool inHeader = true;
00552 KMMsgInfo* mi;
00553 QString msgStr;
00554 QRegExp regexp(MSG_SEPERATOR_REGEX);
00555 int i, num, numStatus;
00556 short needStatus;
00557
00558 assert(mStream != 0);
00559 rewind(mStream);
00560
00561 mMsgList.clear();
00562
00563 num = -1;
00564 numStatus= 11;
00565 off_t offs = 0;
00566 size_t size = 0;
00567 dateStr = "";
00568 fromStr = "";
00569 toStr = "";
00570 subjStr = "";
00571 *status = '\0';
00572 *xstatus = '\0';
00573 xmarkStr = "";
00574 replyToIdStr = "";
00575 replyToAuxIdStr = "";
00576 referencesStr = "";
00577 msgIdStr = "";
00578 needStatus = 3;
00579 size_t sizeServer = 0;
00580 ulong uid = 0;
00581
00582
00583 while (!atEof)
00584 {
00585 off_t pos = ftell(mStream);
00586 if (!fgets(line, MAX_LINE, mStream)) atEof = true;
00587
00588 if (atEof ||
00589 (memcmp(line, MSG_SEPERATOR_START, MSG_SEPERATOR_START_LEN)==0 &&
00590 regexp.search(line) >= 0))
00591 {
00592 size = pos - offs;
00593 pos = ftell(mStream);
00594
00595 if (num >= 0)
00596 {
00597 if (numStatus <= 0)
00598 {
00599 msgStr = i18n("Creating index file: one message done", "Creating index file: %n messages done", num);
00600 emit statusMsg(msgStr);
00601 numStatus = 10;
00602 }
00603
00604 if (size > 0)
00605 {
00606 msgIdStr = msgIdStr.stripWhiteSpace();
00607 if( !msgIdStr.isEmpty() ) {
00608 int rightAngle;
00609 rightAngle = msgIdStr.find( '>' );
00610 if( rightAngle != -1 )
00611 msgIdStr.truncate( rightAngle + 1 );
00612 }
00613
00614 replyToIdStr = replyToIdStr.stripWhiteSpace();
00615 if( !replyToIdStr.isEmpty() ) {
00616 int rightAngle;
00617 rightAngle = replyToIdStr.find( '>' );
00618 if( rightAngle != -1 )
00619 replyToIdStr.truncate( rightAngle + 1 );
00620 }
00621
00622 referencesStr = referencesStr.stripWhiteSpace();
00623 if( !referencesStr.isEmpty() ) {
00624 int leftAngle, rightAngle;
00625 leftAngle = referencesStr.findRev( '<' );
00626 if( ( leftAngle != -1 )
00627 && ( replyToIdStr.isEmpty() || ( replyToIdStr[0] != '<' ) ) ) {
00628
00629 replyToIdStr = referencesStr.mid( leftAngle );
00630 }
00631
00632
00633 leftAngle = referencesStr.findRev( '<', leftAngle - 1 );
00634 if( leftAngle != -1 )
00635 referencesStr = referencesStr.mid( leftAngle );
00636 rightAngle = referencesStr.findRev( '>' );
00637 if( rightAngle != -1 )
00638 referencesStr.truncate( rightAngle + 1 );
00639
00640
00641
00642
00643
00644 replyToAuxIdStr = referencesStr;
00645 rightAngle = referencesStr.find( '>' );
00646 if( rightAngle != -1 )
00647 replyToAuxIdStr.truncate( rightAngle + 1 );
00648 }
00649
00650 contentTypeStr = contentTypeStr.stripWhiteSpace();
00651 charset = "";
00652 if ( !contentTypeStr.isEmpty() )
00653 {
00654 int cidx = contentTypeStr.find( "charset=" );
00655 if ( cidx != -1 ) {
00656 charset = contentTypeStr.mid( cidx + 8 );
00657 if ( !charset.isEmpty() && ( charset[0] == '"' ) ) {
00658 charset = charset.mid( 1 );
00659 }
00660 cidx = 0;
00661 while ( (unsigned int) cidx < charset.length() ) {
00662 if ( charset[cidx] == '"' || ( !isalnum(charset[cidx]) &&
00663 charset[cidx] != '-' && charset[cidx] != '_' ) )
00664 break;
00665 ++cidx;
00666 }
00667 charset.truncate( cidx );
00668
00669
00670 }
00671 }
00672
00673 mi = new KMMsgInfo(folder());
00674 mi->init( subjStr.stripWhiteSpace(),
00675 fromStr.stripWhiteSpace(),
00676 toStr.stripWhiteSpace(),
00677 0, KMMsgStatusNew,
00678 xmarkStr.stripWhiteSpace(),
00679 replyToIdStr, replyToAuxIdStr, msgIdStr,
00680 KMMsgEncryptionStateUnknown, KMMsgSignatureStateUnknown,
00681 KMMsgMDNStateUnknown, charset, offs, size, sizeServer, uid );
00682 mi->setStatus(status, xstatus);
00683 mi->setDate( dateStr.stripWhiteSpace() );
00684 mi->setDirty(false);
00685 mMsgList.append(mi, mExportsSernums );
00686
00687 *status = '\0';
00688 *xstatus = '\0';
00689 needStatus = 3;
00690 xmarkStr = "";
00691 replyToIdStr = "";
00692 replyToAuxIdStr = "";
00693 referencesStr = "";
00694 msgIdStr = "";
00695 dateStr = "";
00696 fromStr = "";
00697 subjStr = "";
00698 sizeServer = 0;
00699 uid = 0;
00700 }
00701 else num--,numStatus++;
00702 }
00703
00704 offs = ftell(mStream);
00705 num++;
00706 numStatus--;
00707 inHeader = true;
00708 continue;
00709 }
00710
00711 if (inHeader && (line[0]=='\t' || line[0]==' '))
00712 {
00713 i = 0;
00714 while (line [i]=='\t' || line [i]==' ') i++;
00715 if (line [i] < ' ' && line [i]>0) inHeader = false;
00716 else if (lastStr) *lastStr += line + i;
00717 }
00718 else lastStr = 0;
00719
00720 if (inHeader && (line [0]=='\n' || line [0]=='\r'))
00721 inHeader = false;
00722 if (!inHeader) continue;
00723
00724
00725
00726
00727 if ((needStatus & 1) && strncasecmp(line, "Status:", 7) == 0)
00728 {
00729 for(i=0; i<4 && line[i+8] > ' '; i++)
00730 status[i] = line[i+8];
00731 status[i] = '\0';
00732 needStatus &= ~1;
00733 }
00734 else if ((needStatus & 2) && strncasecmp(line, "X-Status:", 9)==0)
00735 {
00736 for(i=0; i<4 && line[i+10] > ' '; i++)
00737 xstatus[i] = line[i+10];
00738 xstatus[i] = '\0';
00739 needStatus &= ~2;
00740 }
00741 else if (strncasecmp(line,"X-KMail-Mark:",13)==0)
00742 xmarkStr = QCString(line+13);
00743 else if (strncasecmp(line,"In-Reply-To:",12)==0) {
00744 replyToIdStr = QCString(line+12);
00745 lastStr = &replyToIdStr;
00746 }
00747 else if (strncasecmp(line,"References:",11)==0) {
00748 referencesStr = QCString(line+11);
00749 lastStr = &referencesStr;
00750 }
00751 else if (strncasecmp(line,"Message-Id:",11)==0) {
00752 msgIdStr = QCString(line+11);
00753 lastStr = &msgIdStr;
00754 }
00755 else if (strncasecmp(line,"Date:",5)==0)
00756 {
00757 dateStr = QCString(line+5);
00758 lastStr = &dateStr;
00759 }
00760 else if (strncasecmp(line,"From:", 5)==0)
00761 {
00762 fromStr = QCString(line+5);
00763 lastStr = &fromStr;
00764 }
00765 else if (strncasecmp(line,"To:", 3)==0)
00766 {
00767 toStr = QCString(line+3);
00768 lastStr = &toStr;
00769 }
00770 else if (strncasecmp(line,"Subject:",8)==0)
00771 {
00772 subjStr = QCString(line+8);
00773 lastStr = &subjStr;
00774 }
00775 else if (strncasecmp(line,"X-Length:",9)==0)
00776 {
00777 sizeServerStr = QCString(line+9);
00778 sizeServer = sizeServerStr.toULong();
00779 lastStr = &sizeServerStr;
00780 }
00781 else if (strncasecmp(line,"X-UID:",6)==0)
00782 {
00783 uidStr = QCString(line+6);
00784 uid = uidStr.toULong();
00785 lastStr = &uidStr;
00786 }
00787 else if (strncasecmp(line, "Content-Type:", 13) == 0)
00788 {
00789 contentTypeStr = QCString(line+13);
00790 lastStr = &contentTypeStr;
00791 }
00792 }
00793
00794 if (mAutoCreateIndex)
00795 {
00796 emit statusMsg(i18n("Writing index file"));
00797 writeIndex();
00798 }
00799 else mHeaderOffset = 0;
00800
00801 correctUnreadMsgsCount();
00802
00803 if (kmkernel->outboxFolder() == folder() && count() > 0)
00804 KMessageBox::queuedMessageBox(0, KMessageBox::Information,
00805 i18n("Your outbox contains messages which were "
00806 "most-likely not created by KMail;\nplease remove them from there if you "
00807 "do not want KMail to send them."));
00808
00809 invalidateFolder();
00810 return 0;
00811 }
00812
00813
00814
00815 KMMessage* KMFolderMbox::readMsg(int idx)
00816 {
00817 KMMsgInfo* mi = (KMMsgInfo*)mMsgList[idx];
00818
00819 assert(mi!=0 && !mi->isMessage());
00820 assert(mStream != 0);
00821
00822 KMMessage *msg = new KMMessage(*mi);
00823 msg->setMsgInfo( mi );
00824 mMsgList.set(idx,&msg->toMsgBase());
00825 msg->fromDwString(getDwString(idx));
00826 return msg;
00827 }
00828
00829
00830 #define STRDIM(x) (sizeof(x)/sizeof(*x)-1)
00831
00832 static size_t unescapeFrom( char* str, size_t strLen ) {
00833 if ( !str )
00834 return 0;
00835 if ( strLen <= STRDIM(">From ") )
00836 return strLen;
00837
00838
00839
00840
00841
00842 const char * s = str;
00843 char * d = str;
00844 const char * const e = str + strLen - STRDIM(">From ");
00845
00846 while ( s < e ) {
00847 if ( *s == '\n' && *(s+1) == '>' ) {
00848 *d++ = *s++;
00849 *d++ = *s++;
00850 while ( s < e && *s == '>' )
00851 *d++ = *s++;
00852 if ( qstrncmp( s, "From ", STRDIM("From ") ) == 0 )
00853 --d;
00854 }
00855 *d++ = *s++; // yes, s might be e here, but e is not the end :-)
00856 }
00857 // copy the rest:
00858 while ( s < str + strLen )
00859 *d++ = *s++;
00860 if ( d < s ) // only NUL-terminate if it's shorter
00861 *d = 0;
00862
00863 return d - str;
00864 }
00865
00866
00867 QByteArray KMFolderMbox::escapeFrom( const DwString & str ) {
00868 const unsigned int strLen = str.length();
00869 if ( strLen <= STRDIM("From ") )
00870 return KMail::Util::ByteArray( str );
00871
00872 QByteArray result( int( strLen + 5 ) / 6 * 7 + 1 );
00873
00874 const char * s = str.data();
00875 const char * const e = s + strLen - STRDIM("From ");
00876 char * d = result.data();
00877
00878 bool onlyAnglesAfterLF = false;
00879 while ( s < e ) {
00880 switch ( *s ) {
00881 case '\n':
00882 onlyAnglesAfterLF = true;
00883 break;
00884 case '>':
00885 break;
00886 case 'F':
00887 if ( onlyAnglesAfterLF && qstrncmp( s+1, "rom ", STRDIM("rom ") ) == 0 )
00888 *d++ = '>';
00889
00890 default:
00891 onlyAnglesAfterLF = false;
00892 break;
00893 }
00894 *d++ = *s++;
00895 }
00896 while ( s < str.data() + strLen )
00897 *d++ = *s++;
00898
00899 result.truncate( d - result.data() );
00900 return result;
00901 }
00902
00903 #undef STRDIM
00904
00905
00906 DwString KMFolderMbox::getDwString(int idx)
00907 {
00908 KMMsgInfo* mi = (KMMsgInfo*)mMsgList[idx];
00909
00910 assert(mi!=0);
00911 assert(mStream != 0);
00912
00913 size_t msgSize = mi->msgSize();
00914 char* msgText = new char[ msgSize + 1 ];
00915
00916 fseek(mStream, mi->folderOffset(), SEEK_SET);
00917 fread(msgText, msgSize, 1, mStream);
00918 msgText[msgSize] = '\0';
00919
00920 size_t newMsgSize = unescapeFrom( msgText, msgSize );
00921 newMsgSize = KMail::Util::crlf2lf( msgText, newMsgSize );
00922
00923 DwString msgStr;
00924
00925 msgStr.TakeBuffer( msgText, msgSize + 1, 0, newMsgSize );
00926 return msgStr;
00927 }
00928
00929
00930
00931 int KMFolderMbox::addMsg( KMMessage* aMsg, int* aIndex_ret )
00932 {
00933 if (!canAddMsgNow(aMsg, aIndex_ret)) return 0;
00934 QByteArray msgText;
00935 char endStr[3];
00936 int idx = -1, rc;
00937 KMFolder* msgParent;
00938 bool editing = false;
00939 int growth = 0;
00940
00941 KMFolderOpener openThis(folder(), "mboxaddMsg");
00942 rc = openThis.openResult();
00943 if (rc)
00944 {
00945 kdDebug(5006) << "KMFolderMbox::addMsg-open: " << rc << " of folder: " << label() << endl;
00946 return rc;
00947 }
00948
00949
00950 msgParent = aMsg->parent();
00951 if (msgParent)
00952 {
00953 if ( msgParent== folder() )
00954 {
00955 if (kmkernel->folderIsDraftOrOutbox( folder() ))
00956
00957 {
00958 kdDebug(5006) << "Editing message in outbox or drafts" << endl;
00959 editing = true;
00960 }
00961 else
00962 return 0;
00963 }
00964
00965 idx = msgParent->find(aMsg);
00966 msgParent->getMsg( idx );
00967 }
00968
00969 if (folderType() != KMFolderTypeImap)
00970 {
00971
00972
00973
00974
00975
00976
00977
00978
00979 aMsg->setStatusFields();
00980
00981
00982
00983
00984
00985
00986
00987
00988 if (aMsg->headerField("Content-Type").isEmpty())
00989 aMsg->removeHeaderField("Content-Type");
00990 }
00991 msgText = escapeFrom( aMsg->asDwString() );
00992 size_t len = msgText.size();
00993
00994 assert(mStream != 0);
00995 clearerr(mStream);
00996 if (len <= 0)
00997 {
00998 kdDebug(5006) << "Message added to folder `" << name() << "' contains no data. Ignoring it." << endl;
00999 return 0;
01000 }
01001
01002
01003
01004 fseek(mStream, 0, SEEK_END);
01005 off_t revert = ftell(mStream);
01006 if (ftell(mStream) >= 2) {
01007
01008 fseek(mStream, -2, SEEK_END);
01009 fread(endStr, 1, 2, mStream);
01010 if (ftell(mStream) > 0 && endStr[0]!='\n') {
01011 ++growth;
01012 if (endStr[1]!='\n') {
01013
01014 fwrite("\n\n", 1, 2, mStream);
01015 ++growth;
01016 }
01017 else fwrite("\n", 1, 1, mStream);
01018 }
01019 }
01020 fseek(mStream,0,SEEK_END);
01021 int error = ferror(mStream);
01022 if (error)
01023 return error;
01024
01025 QCString messageSeparator( aMsg->mboxMessageSeparator() );
01026 fwrite( messageSeparator.data(), messageSeparator.length(), 1, mStream );
01027 off_t offs = ftell(mStream);
01028 fwrite(msgText.data(), len, 1, mStream);
01029 if (msgText[(int)len-1]!='\n') fwrite("\n\n", 1, 2, mStream);
01030 fflush(mStream);
01031 size_t size = ftell(mStream) - offs;
01032
01033 error = ferror(mStream);
01034 if (error) {
01035 kdDebug(5006) << "Error: Could not add message to folder: " << strerror(errno) << endl;
01036 if (ftell(mStream) > revert) {
01037 kdDebug(5006) << "Undoing changes" << endl;
01038 truncate( QFile::encodeName(location()), revert );
01039 }
01040 kmkernel->emergencyExit( i18n("Could not add message to folder: ") + QString::fromLocal8Bit(strerror(errno)));
01041
01042
01043
01044
01045
01046
01047
01048
01049
01050
01051
01052 return error;
01053 }
01054
01055 if (msgParent) {
01056 if (idx >= 0) msgParent->take(idx);
01057 }
01058
01059
01060 if (aMsg->isUnread() || aMsg->isNew() ||
01061 (folder() == kmkernel->outboxFolder())) {
01062 if (mUnreadMsgs == -1) mUnreadMsgs = 1;
01063 else ++mUnreadMsgs;
01064 if ( !mQuiet )
01065 emit numUnreadMsgsChanged( folder() );
01066 }
01067 ++mTotalMsgs;
01068 mSize = -1;
01069
01070 if ( aMsg->attachmentState() == KMMsgAttachmentUnknown && aMsg->readyToShow() ) {
01071 aMsg->updateAttachmentState();
01072 }
01073 if ( aMsg->invitationState() == KMMsgInvitationUnknown && aMsg->readyToShow() ) {
01074 aMsg->updateInvitationState();
01075 }
01076
01077
01078 aMsg->setParent(folder());
01079 aMsg->setFolderOffset(offs);
01080 aMsg->setMsgSize(size);
01081 idx = mMsgList.append(&aMsg->toMsgBase(), mExportsSernums );
01082 if ( aMsg->getMsgSerNum() <= 0 )
01083 aMsg->setMsgSerNum();
01084 else
01085 replaceMsgSerNum( aMsg->getMsgSerNum(), &aMsg->toMsgBase(), idx );
01086
01087
01088 if ((idx > 0) && (growth > 0)) {
01089
01090 if ((ulong)revert == mMsgList[idx - 1]->folderOffset() + mMsgList[idx - 1]->msgSize() )
01091 mMsgList[idx - 1]->setMsgSize( mMsgList[idx - 1]->msgSize() + growth );
01092 }
01093
01094
01095 if (mAutoCreateIndex)
01096 {
01097 assert(mIndexStream != 0);
01098 clearerr(mIndexStream);
01099 fseek(mIndexStream, 0, SEEK_END);
01100 revert = ftell(mIndexStream);
01101
01102 KMMsgBase * mb = &aMsg->toMsgBase();
01103 int len;
01104 const uchar *buffer = mb->asIndexString(len);
01105 fwrite(&len,sizeof(len), 1, mIndexStream);
01106 mb->setIndexOffset( ftell(mIndexStream) );
01107 mb->setIndexLength( len );
01108 if(fwrite(buffer, len, 1, mIndexStream) != 1)
01109 kdDebug(5006) << "Whoa! " << __FILE__ << ":" << __LINE__ << endl;
01110
01111 fflush(mIndexStream);
01112 error = ferror(mIndexStream);
01113
01114 if ( mExportsSernums )
01115 error |= appendToFolderIdsFile( idx );
01116
01117 if (error) {
01118 kdWarning(5006) << "Error: Could not add message to folder (No space left on device?)" << endl;
01119 if (ftell(mIndexStream) > revert) {
01120 kdWarning(5006) << "Undoing changes" << endl;
01121 truncate( QFile::encodeName(indexLocation()), revert );
01122 }
01123 if ( errno )
01124 kmkernel->emergencyExit( i18n("Could not add message to folder:") + QString::fromLocal8Bit(strerror(errno)));
01125 else
01126 kmkernel->emergencyExit( i18n("Could not add message to folder (No space left on device?)") );
01127
01128
01129
01130
01131
01132
01133
01134
01135
01136
01137 return error;
01138 }
01139 }
01140
01141 if (aIndex_ret) *aIndex_ret = idx;
01142 emitMsgAddedSignals(idx);
01143
01144
01145
01146
01147 return 0;
01148 }
01149
01150 int KMFolderMbox::compact( unsigned int startIndex, int nbMessages, FILE* tmpfile, off_t& offs, bool& done )
01151 {
01152 int rc = 0;
01153 QCString mtext;
01154 unsigned int stopIndex = nbMessages == -1 ? mMsgList.count() :
01155 QMIN( mMsgList.count(), startIndex + nbMessages );
01156
01157 for(unsigned int idx = startIndex; idx < stopIndex; ++idx) {
01158 KMMsgInfo* mi = (KMMsgInfo*)mMsgList.at(idx);
01159 size_t msize = mi->msgSize();
01160 if (mtext.size() < msize + 2)
01161 mtext.resize(msize+2);
01162 off_t folder_offset = mi->folderOffset();
01163
01164
01165 for(off_t i = folder_offset-25; true; i -= 20) {
01166 off_t chunk_offset = i <= 0 ? 0 : i;
01167 if(fseek(mStream, chunk_offset, SEEK_SET) == -1) {
01168 rc = errno;
01169 break;
01170 }
01171 if (mtext.size() < 20)
01172 mtext.resize(20);
01173 fread(mtext.data(), 20, 1, mStream);
01174 if(i <= 0) {
01175 if ( mtext.contains( "from ", false ) ) {
01176 if (mtext.size() < (size_t)folder_offset)
01177 mtext.resize(folder_offset);
01178 if(fseek(mStream, chunk_offset, SEEK_SET) == -1 ||
01179 !fread(mtext.data(), folder_offset, 1, mStream) ||
01180 !fwrite(mtext.data(), folder_offset, 1, tmpfile)) {
01181 rc = errno;
01182 break;
01183 }
01184 offs += folder_offset;
01185 } else {
01186 rc = 666;
01187 }
01188 break;
01189 } else {
01190 int last_crlf = -1;
01191 for(int i2 = 0; i2 < 20; i2++) {
01192 if(*(mtext.data()+i2) == '\n')
01193 last_crlf = i2;
01194 }
01195 if(last_crlf != -1) {
01196 int size = folder_offset - (i + last_crlf+1);
01197 if ((int)mtext.size() < size)
01198 mtext.resize(size);
01199 if(fseek(mStream, i + last_crlf+1, SEEK_SET) == -1 ||
01200 !fread(mtext.data(), size, 1, mStream) ||
01201 !fwrite(mtext.data(), size, 1, tmpfile)) {
01202 rc = errno;
01203 break;
01204 }
01205 offs += size;
01206 break;
01207 }
01208 }
01209 }
01210 if (rc)
01211 break;
01212
01213
01214 if(fseek(mStream, folder_offset, SEEK_SET) == -1 ||
01215 !fread(mtext.data(), msize, 1, mStream) || !fwrite(mtext.data(), msize, 1, tmpfile)) {
01216 rc = errno;
01217 break;
01218 }
01219 mi->setFolderOffset(offs);
01220 offs += msize;
01221 }
01222 done = ( !rc && stopIndex == mMsgList.count() );
01223 return rc;
01224 }
01225
01226
01227 int KMFolderMbox::compact( bool silent )
01228 {
01229
01230
01231
01232 KMail::MboxCompactionJob* job = new KMail::MboxCompactionJob( folder(), true );
01233 int rc = job->executeNow( silent );
01234
01235
01236
01237
01238 QString statusMsg = BroadcastStatus::instance()->statusMsg();
01239 emit changed();
01240 BroadcastStatus::instance()->setStatusMsg( statusMsg );
01241 return rc;
01242 }
01243
01244
01245
01246 void KMFolderMbox::setLockType( LockType ltype )
01247 {
01248 mLockType = ltype;
01249 }
01250
01251
01252 void KMFolderMbox::setProcmailLockFileName( const QString &fname )
01253 {
01254 mProcmailLockFileName = fname;
01255 }
01256
01257
01258 int KMFolderMbox::removeContents()
01259 {
01260 int rc = 0;
01261 rc = unlink(QFile::encodeName(location()));
01262 return rc;
01263 }
01264
01265
01266 int KMFolderMbox::expungeContents()
01267 {
01268 int rc = 0;
01269 if (truncate(QFile::encodeName(location()), 0))
01270 rc = errno;
01271 return rc;
01272 }
01273
01274
01275
01276 Q_INT64 KMFolderMbox::doFolderSize() const
01277 {
01278 QFileInfo info( location() );
01279 return (Q_INT64)(info.size());
01280 }
01281
01282
01283 #include "kmfoldermbox.moc"