-
-
Notifications
You must be signed in to change notification settings - Fork 277
Expand file tree
/
Copy pathon-copy.js
More file actions
387 lines (333 loc) · 13.6 KB
/
on-copy.js
File metadata and controls
387 lines (333 loc) · 13.6 KB
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
'use strict';
const ObjectId = require('mongodb').ObjectId;
const db = require('../db');
const tools = require('../tools');
const consts = require('../consts');
async function copyHandler(server, messageHandler, connection, mailbox, update, session) {
const socket = (session.socket && session.socket._parent) || session.socket;
server.logger.debug(
{
tnx: 'copy',
cid: session.id
},
'[%s] Copying messages from "%s" to "%s"',
session.id,
mailbox,
update.destination
);
tools.checkSocket(socket);
let userData = await db.users.collection('users').findOne(
{
_id: session.user.id
},
{
maxTimeMS: consts.DB_MAX_TIME_USERS
}
);
if (!userData) {
throw new Error('User not found');
}
if (userData.quota && userData.storageUsed > userData.quota) {
return 'OVERQUOTA';
}
let mailboxData = await db.database.collection('mailboxes').findOne(
{
_id: mailbox
},
{
maxTimeMS: consts.DB_MAX_TIME_MAILBOXES
}
);
if (!mailboxData) {
return 'NONEXISTENT';
}
let targetData = await db.database.collection('mailboxes').findOne(
{
user: session.user.id,
path: update.destination
},
{
maxTimeMS: consts.DB_MAX_TIME_MAILBOXES
}
);
if (!targetData) {
return 'TRYCREATE';
}
let cursor = await db.database
.collection('messages')
.find({
mailbox: mailboxData._id,
uid: tools.checkRangeQuery(update.messages)
}) // no projection as we need to copy the entire message
.sort({ uid: 1 })
.maxTimeMS(consts.DB_MAX_TIME_MESSAGES);
let copiedMessages = 0;
let copiedStorage = 0;
let updateQuota = async () => {
if (!copiedMessages) {
return;
}
try {
let r = await db.users.collection('users').findOneAndUpdate(
{
_id: mailboxData.user
},
{
$inc: {
storageUsed: copiedStorage
}
},
{
returnDocument: 'after',
projection: {
storageUsed: true
},
maxTimeMS: consts.DB_MAX_TIME_USERS
}
);
if (r && r.value) {
server.loggelf({
short_message: '[QUOTA] +',
_mail_action: 'quota',
_user: mailboxData.user,
_inc: copiedStorage,
_copied_messages: copiedMessages,
_storage_used: r.value.storageUsed,
_mailbox: targetData._id,
_sess: session && session.id
});
}
} catch (err) {
// ignore
}
};
let sourceUid = [];
let destinationUid = [];
let messageData;
// COPY might take a long time to finish, so send unsolicited responses
let notifyTimeout;
let notifyLongRunning = () => {
clearTimeout(notifyTimeout);
notifyTimeout = setTimeout(() => {
connection.send('* OK Still processing...');
notifyLongRunning();
}, consts.LONG_COMMAND_NOTIFY_TTL);
};
notifyLongRunning();
let targetMailboxEncrypted = false;
if (targetData.encryptMessages) {
targetMailboxEncrypted = true;
}
try {
while ((messageData = await cursor.next())) {
tools.checkSocket(socket); // do we even have to copy anything?
// this query points to current message
let existingQuery = {
mailbox: messageData.mailbox,
uid: messageData.uid,
_id: messageData._id
};
const parsedHeader = (messageData.mimeTree && messageData.mimeTree.parsedHeader) || {};
const parsedContentType = parsedHeader['content-type'];
const isMessageEncrypted = parsedContentType ? parsedContentType.subtype === 'encrypted' : false;
// Copying is not done in bulk to minimize risk of going out of sync with incremental UIDs
sourceUid.unshift(messageData.uid);
let item = await db.database.collection('mailboxes').findOneAndUpdate(
{
_id: targetData._id
},
{
$inc: {
uidNext: 1
}
},
{
projection: {
uidNext: true,
modifyIndex: true
},
returnDocument: 'before',
maxTimeMS: consts.DB_MAX_TIME_MAILBOXES
}
);
if (!item || !item.value) {
// mailbox not found
return 'TRYCREATE';
}
let uidNext = item.value.uidNext;
let modifyIndex = item.value.modifyIndex;
destinationUid.unshift(uidNext);
messageData._id = new ObjectId();
messageData.mailbox = targetData._id;
messageData.uid = uidNext;
// retention settings
messageData.exp = !!targetData.retention;
messageData.rdate = Date.now() + (targetData.retention || 0);
messageData.modseq = modifyIndex; // reset message modseq to whatever it is for the mailbox right now
if (!messageData.flags.includes('\\Deleted')) {
messageData.searchable = true;
} else {
delete messageData.searchable;
}
let junk = false;
if (targetData.specialUse === '\\Junk' && !messageData.junk) {
messageData.junk = true;
junk = 1;
} else if (targetData.specialUse !== '\\Trash' && messageData.junk) {
delete messageData.junk;
junk = -1;
}
if (!messageData.meta) {
messageData.meta = {};
}
if (!messageData.meta.events) {
messageData.meta.events = [];
}
messageData.meta.events.push({
action: 'IMAPCOPY',
time: new Date()
});
await db.database.collection('messages').updateOne(
existingQuery,
{
$set: {
// indicate that we do not need to archive this message when deleted
copied: true
}
},
{ writeConcern: 'majority' }
);
const newPrepared = await new Promise((resolve, reject) => {
if (targetMailboxEncrypted && !isMessageEncrypted && userData.pubKey) {
// encrypt message
// get raw from existing mimetree
let outputStream = messageHandler.indexer.rebuild(messageData.mimeTree); // get raw rebuilder response obj (.value is the stream)
if (!outputStream || outputStream.type !== 'stream' || !outputStream.value) {
return reject(new Error('Cannot fetch message'));
}
outputStream = outputStream.value; // set stream to actual stream object (.value)
let chunks = [];
let chunklen = 0;
outputStream
.on('readable', () => {
let chunk;
while ((chunk = outputStream.read()) !== null) {
chunks.push(chunk);
chunklen += chunk.length;
}
})
.on('end', () => {
const raw = Buffer.concat(chunks, chunklen);
messageHandler.encryptMessages(userData.pubKey, raw, (err, res) => {
if (err) {
return reject(err);
}
// encrypted rebuilt raw
if (res) {
messageHandler.prepareMessage({ raw: res }, (err, prepared) => {
if (err) {
return reject(err);
}
// prepared new message structure from encrypted raw
const maildata = messageHandler.indexer.getMaildata(prepared.mimeTree);
// add attachments of encrypted messages
if (maildata.attachments && maildata.attachments.length) {
messageData.attachments = maildata.attachments;
messageData.ha = maildata.attachments.some(a => !a.related);
} else {
messageData.ha = false;
}
// remove fields that may leak data in FE or DB
delete messageData.text;
delete messageData.html;
messageData.intro = '';
messageHandler.indexer.storeNodeBodies(maildata, prepared.mimeTree, err => {
// store new attachments
let cleanup = () => {
let attachmentIds = Object.keys(prepared.mimeTree.attachmentMap || {}).map(
key => prepared.mimeTree.attachmentMap[key]
);
messageHandler.attachmentStorage
.deleteManyAsync(attachmentIds, maildata.magic)
.then(() => {
if (err) {
return reject(err);
}
})
.catch(error => reject(error));
};
if (err) {
return cleanup();
}
return resolve(prepared);
});
});
}
});
});
} else {
resolve(false);
}
});
// replace fields
if (newPrepared) {
messageData.mimeTree = newPrepared.mimeTree;
messageData.size = newPrepared.size;
messageData.bodystructure = newPrepared.bodystructure;
messageData.envelope = newPrepared.envelope;
messageData.headers = newPrepared.headers;
}
let r = await db.database.collection('messages').insertOne(messageData, { writeConcern: 'majority' });
if (!r || !r.acknowledged) {
continue;
}
copiedMessages++;
copiedStorage += Number(messageData.size) || 0;
let attachmentIds = Object.keys(messageData.mimeTree.attachmentMap || {}).map(key => messageData.mimeTree.attachmentMap[key]);
if (attachmentIds.length) {
try {
await messageHandler.attachmentStorage.updateMany(attachmentIds, 1, messageData.magic);
} catch (err) {
// should we care about this error?
}
}
let entry = {
command: 'EXISTS',
uid: messageData.uid,
message: messageData._id,
unseen: messageData.unseen,
flagged: messageData.flagged,
keywords: tools.extractKeywords(messageData.flags),
idate: messageData.idate,
thread: messageData.thread
};
if (junk) {
entry.junk = junk;
}
await new Promise(resolve => server.notifier.addEntries(targetData, entry, resolve));
}
} finally {
clearTimeout(notifyTimeout);
try {
await cursor.close();
} catch (err) {
//ignore, might be already closed
}
await updateQuota();
}
server.notifier.fire(session.user.id, targetData.path);
return [
true,
{
uidValidity: targetData.uidValidity,
sourceUid,
destinationUid
}
];
}
// COPY / UID COPY sequence mailbox
module.exports = (server, messageHandler) => (connection, mailbox, update, session, callback) => {
copyHandler(server, messageHandler, connection, mailbox, update, session)
.then(args => callback(null, ...[].concat(args || [])))
.catch(err => callback(err));
};