summaryrefslogtreecommitdiffstats
path: root/kmail/compactionjob.cpp
blob: 90d0e9f4b5972a79aa58708940237fe80c43c7a8 (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
/**
 * Copyright (c) 2004 David Faure <faure@kde.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *  In addition, as a special exception, the copyright holders give
 *  permission to link the code of this program with any edition of
 *  the TQt library by Trolltech AS, Norway (or with modified versions
 *  of TQt that use the same license as TQt), and distribute linked
 *  combinations including the two.  You must obey the GNU General
 *  Public License in all respects for all of the code used other than
 *  TQt.  If you modify this file, you may extend this exception to
 *  your version of the file, but you are not obligated to do so.  If
 *  you do not wish to do so, delete this exception statement from
 *  your version.
 */
#include "compactionjob.h"
#include "kmfolder.h"
#include "broadcaststatus.h"
using KPIM::BroadcastStatus;
#include "kmfoldermbox.h"
#include "kmfoldermaildir.h"

#include <kdebug.h>
#include <tdelocale.h>

#include <tqfile.h>
#include <tqfileinfo.h>
#include <tqdir.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

using namespace KMail;

// Look at this number of messages in each slotDoWork call
#define COMPACTIONJOB_NRMESSAGES 100
// And wait this number of milliseconds before calling it again
#define COMPACTIONJOB_TIMERINTERVAL 100

MboxCompactionJob::MboxCompactionJob( KMFolder* folder, bool immediate )
 : ScheduledJob( folder, immediate ), mTimer( this, "mTimer" ), mTmpFile( 0 ),
   mCurrentIndex( 0 ), mFolderOpen( false ), mSilent( false )
{
}

MboxCompactionJob::~MboxCompactionJob()
{
}

void MboxCompactionJob::kill()
{
  Q_ASSERT( mCancellable );
  // We must close the folder if we opened it and got interrupted
  if ( mFolderOpen && mSrcFolder && mSrcFolder->storage() )
    mSrcFolder->storage()->close("mboxcompact");

  if ( mTmpFile )
    fclose( mTmpFile );
  mTmpFile = 0;
  if ( !mTempName.isEmpty() )
    TQFile::remove( mTempName );
  FolderJob::kill();
}

TQString MboxCompactionJob::realLocation() const
{
  TQString location = mSrcFolder->location();
  TQFileInfo inf( location );
  if (inf.isSymLink()) {
    KURL u; u.setPath( location );
    // follow (and resolve) symlinks so that the final ::rename() always works
    // KURL gives us support for absolute and relative links transparently.
    return KURL( u, inf.readLink() ).path();
  }
  return location;
}

int MboxCompactionJob::executeNow( bool silent )
{
  mSilent = silent;
  FolderStorage* storage = mSrcFolder->storage();
  KMFolderMbox* mbox = static_cast<KMFolderMbox *>( storage );
  if (!storage->compactable()) {
    kdDebug(5006) << storage->location() << " compaction skipped." << endl;
    if ( !mSilent ) {
      TQString str = i18n( "For safety reasons, compaction has been disabled for %1" ).arg( mbox->label() );
      BroadcastStatus::instance()->setStatusMsg( str );
    }
    return 0;
  }
  kdDebug(5006) << "Compacting " << mSrcFolder->idString() << endl;

  if (KMFolderIndex::IndexOk != mbox->indexStatus()) {
      kdDebug(5006) << "Critical error: " << storage->location() <<
          " has been modified by an external application while KMail was running." << endl;
      //      exit(1); backed out due to broken nfs
  }

  const TQFileInfo pathInfo( realLocation() );
  // Use /dir/.mailboxname.compacted so that it's hidden, and doesn't show up after restarting kmail
  // (e.g. due to an unfortunate crash while compaction is happening)
  mTempName = pathInfo.dirPath() + "/." + pathInfo.fileName() + ".compacted";

  mode_t old_umask = umask(077);
  mTmpFile = fopen(TQFile::encodeName(mTempName), "w");
  umask(old_umask);
  if (!mTmpFile) {
    kdWarning(5006) << "Couldn't start compacting " << mSrcFolder->label()
                    << " : " << strerror( errno )
                    << " while creating " << mTempName << endl;
    return errno;
  }
  mOpeningFolder = true; // Ignore open-notifications while opening the folder
  storage->open("mboxcompact");
  mOpeningFolder = false;
  mFolderOpen = true;
  mOffset = 0;
  mCurrentIndex = 0;

  kdDebug(5006) << "MboxCompactionJob: starting to compact folder " << mSrcFolder->location() << " into " << mTempName << endl;
  connect( &mTimer, TQ_SIGNAL( timeout() ), TQ_SLOT( slotDoWork() ) );
  if ( !mImmediate )
    mTimer.start( COMPACTIONJOB_TIMERINTERVAL );
  slotDoWork();
  return mErrorCode;
}

void MboxCompactionJob::slotDoWork()
{
  // No need to worry about mSrcFolder==0 here. The FolderStorage deletes the jobs on destruction.
  KMFolderMbox* mbox = static_cast<KMFolderMbox *>( mSrcFolder->storage() );
  bool bDone = false;
  int nbMessages = mImmediate ? -1 /*all*/ : COMPACTIONJOB_NRMESSAGES;
  int rc = mbox->compact( mCurrentIndex, nbMessages,
                          mTmpFile, mOffset /*in-out*/, bDone /*out*/ );
  if ( !mImmediate )
    mCurrentIndex += COMPACTIONJOB_NRMESSAGES;
  if ( rc || bDone ) // error, or finished
    done( rc );
}

void MboxCompactionJob::done( int rc )
{
  mTimer.stop();
  mCancellable = false;
  KMFolderMbox* mbox = static_cast<KMFolderMbox *>( mSrcFolder->storage() );
  if (!rc)
      rc = fflush(mTmpFile);
  if (!rc)
      rc = fsync(fileno(mTmpFile));
  rc |= fclose(mTmpFile);
  TQString str;
  if (!rc) {
    bool autoCreate = mbox->autoCreateIndex();
    TQString box( realLocation() );
    ::rename(TQFile::encodeName(mTempName), TQFile::encodeName(box));
    mbox->writeIndex();
    mbox->writeConfig();
    mbox->setAutoCreateIndex( false );
    mbox->close("mboxcompact", true);
    mbox->setAutoCreateIndex( autoCreate );
    mbox->setNeedsCompacting( false );            // We are clean now
    str = i18n( "Folder \"%1\" successfully compacted" ).arg( mSrcFolder->label() );
    kdDebug(5006) << str << endl;
  } else {
    mbox->close("mboxcompact");
    str = i18n( "Error occurred while compacting \"%1\". Compaction aborted." ).arg( mSrcFolder->label() );
    kdDebug(5006) << "Error occurred while compacting " << mbox->location() << endl;
    kdDebug(5006) << "Compaction aborted." << endl;
    TQFile::remove( mTempName );
  }
  mErrorCode = rc;

  if ( !mSilent )
    BroadcastStatus::instance()->setStatusMsg( str );

  mFolderOpen = false;
  deleteLater(); // later, because of the "return mErrorCode"
}

////

MaildirCompactionJob::MaildirCompactionJob( KMFolder* folder, bool immediate )
 : ScheduledJob( folder, immediate ), mTimer( this, "mTimer" ),
   mCurrentIndex( 0 ), mFolderOpen( false ), mSilent( false )
{
}

MaildirCompactionJob::~MaildirCompactionJob()
{
}

void MaildirCompactionJob::kill()
{
  Q_ASSERT( mCancellable );
  // We must close the folder if we opened it and got interrupted
  if ( mFolderOpen && mSrcFolder && mSrcFolder->storage() )
    mSrcFolder->storage()->close("maildircompact");

  FolderJob::kill();
}

int MaildirCompactionJob::executeNow( bool silent )
{
  mSilent = silent;
  KMFolderMaildir* storage = static_cast<KMFolderMaildir *>( mSrcFolder->storage() );
  kdDebug(5006) << "Compacting " << mSrcFolder->idString() << endl;

  mOpeningFolder = true; // Ignore open-notifications while opening the folder
  storage->open("maildircompact");
  mOpeningFolder = false;
  mFolderOpen = true;
  TQString subdirNew(storage->location() + "/new/");
  TQDir d(subdirNew);
  mEntryList = d.entryList();
  mCurrentIndex = 0;

  kdDebug(5006) << "MaildirCompactionJob: starting to compact in folder " << mSrcFolder->location() << endl;
  connect( &mTimer, TQ_SIGNAL( timeout() ), TQ_SLOT( slotDoWork() ) );
  if ( !mImmediate )
    mTimer.start( COMPACTIONJOB_TIMERINTERVAL );
  slotDoWork();
  return mErrorCode;
}

void MaildirCompactionJob::slotDoWork()
{
  // No need to worry about mSrcFolder==0 here. The FolderStorage deletes the jobs on destruction.
  KMFolderMaildir* storage = static_cast<KMFolderMaildir *>( mSrcFolder->storage() );
  bool bDone = false;
  int nbMessages = mImmediate ? -1 /*all*/ : COMPACTIONJOB_NRMESSAGES;
  int rc = storage->compact( mCurrentIndex, nbMessages, mEntryList, bDone /*out*/ );
  if ( !mImmediate )
    mCurrentIndex += COMPACTIONJOB_NRMESSAGES;
  if ( rc || bDone ) // error, or finished
    done( rc );
}

void MaildirCompactionJob::done( int rc )
{
  KMFolderMaildir* storage = static_cast<KMFolderMaildir *>( mSrcFolder->storage() );
  mTimer.stop();
  mCancellable = false;
  TQString str;
  if ( !rc ) {
    str = i18n( "Folder \"%1\" successfully compacted" ).arg( mSrcFolder->label() );
  } else {
    str = i18n( "Error occurred while compacting \"%1\". Compaction aborted." ).arg( mSrcFolder->label() );
  }
  mErrorCode = rc;
  storage->setNeedsCompacting( false );
  storage->close("maildircompact");
  if ( storage->isOpened() )
    storage->updateIndex();
  if ( !mSilent )
    BroadcastStatus::instance()->setStatusMsg( str );

  mFolderOpen = false;
  deleteLater(); // later, because of the "return mErrorCode"
}

////

ScheduledJob* ScheduledCompactionTask::run()
{
  if ( !folder() || !folder()->needsCompacting() )
    return 0;
  switch( folder()->storage()->folderType() ) {
  case KMFolderTypeMbox:
    return new MboxCompactionJob( folder(), isImmediate() );
  case KMFolderTypeCachedImap:
  case KMFolderTypeMaildir:
    return new MaildirCompactionJob( folder(), isImmediate() );
  default: // imap, search, unknown...
    return 0;
  }
}

#include "compactionjob.moc"