This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrun_hoodiecrow.js
420 lines (381 loc) · 12.1 KB
/
run_hoodiecrow.js
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
#!/usr/bin/env node
// This file is invoked from XPCOM-land by fake-server-support.js. It passes us
// some JSON options via process.argv, and we're expected to contact the control
// server after we have spun up a set of hoodiecrow IMAP+SMTP servers.
var request = require('request');
var hoodiecrow = require('hoodiecrow');
var mimeparser = require('hoodiecrow/lib/mimeparser')
var simplesmtp = require('simplesmtp');
var http = require('http');
// Pull out the arguments as passed from fake-server-support, treating the last
// argument passed as a JSON string, e.g.:
//
// args = {
// serverId: (number),
// controlUrl: "http://...",
// credentials: creds,
// options: opts,
// deliveryMode: 'inbox' or 'blackhole'
// }
var args = JSON.parse(process.argv[process.argv.length - 1]);
console.log('Started hoodiecrow node process. Args:', JSON.stringify(args));
var imapServer = startImapServer();
var smtpServer = startSmtpServer();
var sendShouldFail = false;
/**
* The startup handshake for hoodiecrow looks like this:
*
* 1. The mail-fakeservers control server receives a "make_hoodiecrow" request.
* It spawns this file in Node, and holds onto the "make_hoodiecrow" request.
*
* 2. We ping the control server with a 'hoodiecrow_ready' message, with details
* about the IMAP/SMTP ports.
*
* 3. The mail-fakeservers control server then responds to the original
* "make_hoodiecrow" request, such that it appears synchronous from GELAM's
* point of view.
*/
function main() {
var backdoorServer = startBackdoorServer(handleRequest);
updateCredentials(args.credentials);
if (args.options.oauth) {
updateCredentials({
accessToken: args.options.oauth.initialTokens.accessToken
});
}
sendReadyMessageToControlServer(args.controlUrl, {
command: 'hoodiecrow_ready',
serverId: args.serverId,
controlUrl: 'http://localhost:' + backdoorServer.address().port,
imapHost: 'localhost',
imapPort: imapServer.server.address().port,
smtpHost: 'localhost',
smtpPort: smtpServer.server.SMTPServer._server.address().port,
oauthInfo: null
});
}
var currentDateMS = null;
function getCurrentDate() {
if (currentDateMS) {
var date = new Date(currentDateMS);
currentDateMS += 1000;
return date;
} else {
return new Date(Date.now());
}
}
// A plugin to force the server to not return UIDNEXT from SELECT.
function NOUIDNEXT(imapServer) {
imapServer.setCommandHandler(
'SELECT', require('./hoodiecrow-mods/select-nouidnext'));
}
// A plugin to remove the timezone part from INTERNALDATE representations.
function NO_INTERNALDATE_TZ(imapServer) {
imapServer.formatInternalDate = function(date) {
var day = date.getDate(),
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
][date.getMonth()],
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
tz = date.getTimezoneOffset(),
tzHours = Math.abs(Math.floor(tz / 60)),
tzMins = Math.abs(tz) - tzHours * 60;
return (day < 10 ? "0" : "") + day + "-" + month + "-" + year + " " +
(hour < 10 ? "0" : "") + hour + ":" + (minute < 10 ? "0" : "") +
minute + ":" + (second < 10 ? "0" : "") + second;
};
}
var currentCredentials = {};
function updateCredentials(obj) {
currentCredentials = {
username: obj.username || currentCredentials.username,
password: obj.password || currentCredentials.password,
accessToken: obj.accessToken || currentCredentials.accessToken,
outgoingPassword: (obj.outgoingPassword ||
currentCredentials.outgoingPassword ||
currentCredentials.password ||
obj.password)
};
console.log('Hoodiecrow credentials updated:',
JSON.stringify(currentCredentials));
imapServer.users = {};
imapServer.users[currentCredentials.username] = {
password: currentCredentials.password,
xoauth2: (currentCredentials.accessToken ? {
accessToken: currentCredentials.accessToken,
sessionTimeout: 3600 * 1000
} : null)
};
smtpServer.server.removeAllListeners('authorizeUser');
smtpServer.server.on('authorizeUser', function(conn, user, pass, cb) {
if (user === currentCredentials.username &&
(currentCredentials.accessToken
? pass === currentCredentials.accessToken
: pass === currentCredentials.outgoingPassword)) {
cb(null, true);
} else {
cb('wrong username/password', false);
}
});
}
/**
* Create the folder configuration. There are three modes:
*
* - "flat" / (default): The folders are not namespaced under the INBOX.
* - "underinbox": The folders are namespaced under the INBOX. This is
* historically done dynamically by issuing a
* "moveSystemFoldersUnderneathInbox" request.
* - "custom": Uses the "folderConfig" idiom created prior to adopting
* hoodiecrow. This is being left as-is structurally for consistency with
* the legacy imapd logic, but we should probably just change to directly
* propagating the structure directly to what hoodiecrow consumes once we
* need to make a significant change to this.
*
* NOTE: It turns out hoodiecrow has some (known, admitted) awkwardness with
* how it handles the INBOX folder and namespaces. This should all be
* overhauled in conjunction with improving upstream hoodiecrow.
*/
function makeFolderStorage(modeOrConfig) {
var mode, folderDefs;
if (!modeOrConfig) {
mode = 'flat';
} else if (typeof(modeOrConfig) === 'string') {
mode = modeOrConfig;
} else if (!modeOrConfig.folders) {
if (modeOrConfig.underInbox) {
mode = 'underinbox';
} else {
mode = 'flat';
}
} else {
mode = 'custom';
folderDefs = modeOrConfig.folders;
}
if (mode === 'flat') {
return {
'INBOX': {},
'': { // (implied personal namespace)
separator: '/',
folders: {
'Drafts': { 'special-use': '\\Drafts' },
'Sent': { 'special-use': '\\Sent' },
'Trash': { 'special-use': '\\Trash' },
'Custom': { }
}
}
};
} else if (mode === 'underinbox') {
return {
'INBOX': {
},
'INBOX/': { // documentme: why is the personal namespace still under ''?
type: 'personal',
separator: '/',
folders: {
'Drafts': { 'special-use': '\\Drafts' },
'Sent': { 'special-use': '\\Sent' },
'Trash': { 'special-use': '\\Trash' },
'Custom': { }
}
}
};
} else if (mode === 'custom') {
var foldersByPath = {};
folderDefs.forEach(function(folderDef) {
var meta = {};
if (folderDef['special-use']) {
meta['special-use'] = folderDef['special-use'];
}
foldersByPath[folderDef.name] = meta;
});
var storage = {
'INBOX': {}
};
if (modeOrConfig.underInbox) {
storage['INBOX/'] = {
type: 'personal',
separator: '/',
folders: foldersByPath
};
} else {
storage[''] = {
separator: '/',
folders: foldersByPath
};
}
return storage;
};
}
function handleRequest(msg) {
switch (msg.command) {
case 'getFolderByPath':
var folder = imapServer.getMailbox(msg.name);
if (folder) {
return folder.path;
} else {
return null;
}
break;
case 'setDate':
currentDateMS = msg.timestamp;
break;
case 'addFolder':
imapServer.createMailbox(msg.name);
return imapServer.getMailbox(msg.name).path;
case 'removeFolder':
imapServer.deleteMailbox(msg.name);
break;
case 'addMessagesToFolder':
msg.messages.forEach(function(message) {
imapServer.appendMessage(
msg.name,
message.flags,
new Date(message.date),
new Buffer(message.msgString));
});
break;
case 'modifyMessagesInFolder':
var name = msg.name;
var uids = msg.uids;
var addFlags = msg.addFlags;
var delFlags = msg.delFlags;
var mailbox = imapServer.getMailbox(name);
mailbox.messages.forEach(function(message) {
if (msg.uids.indexOf(message.uid) !== -1) {
addFlags && addFlags.forEach(function(flag) {
imapServer.ensureFlag(message.flags, flag);
});
delFlags && delFlags.forEach(function(flag) {
imapServer.removeFlag(message.flags, flag);
});
}
});
break;
case 'getMessagesInFolder':
var name = msg.name;
var mailbox = imapServer.getMailbox(name);
return mailbox.messages.map(function(message) {
var mimeMsg = mimeparser(message.raw);
return {
date: mimeMsg.internaldate,
subject: mimeMsg.parsedHeader['subject']
};
});
break;
case 'setValidOAuthAccessTokens':
// XXX: Only using one token for now.
updateCredentials({ accessToken: msg.accessTokens[0] });
break;
case 'changeCredentials':
updateCredentials(msg.credentials);
break;
case 'toggleSendFailure':
sendShouldFail = msg.shouldFail;
break;
case 'moveSystemFoldersUnderneathInbox':
imapServer.folderCache = {};
imapServer.storage = makeFolderStorage('underinbox');
// indexFolders is not intended to be used multiple times, irrevocably
// mutating referenceNamespace, so we need to reset it here.
imapServer.referenceNamespace = false;
imapServer.indexFolders();
break;
}
}
function withBufferAsString(req, fn) {
var body = '';
req.on('data', function(arr) {
body += arr.toString('utf-8');
});
req.on('end', function() {
fn(body);
});
}
function startBackdoorServer(handler) {
var server = http.createServer(function(req, res) {
withBufferAsString(req, function(body) {
try {
var responseBody = handler(JSON.parse(body), req, res);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(responseBody));
} catch(e) {
console.error('Internal hoodiecrow backdoor error:', e, e.stack);
res.writeHead(500);
res.end();
}
});
});
server.listen(0);
return server;
}
function startImapServer() {
var plugins = [
"ID", "STARTTLS", "SASL-IR",
"AUTH-PLAIN", "NAMESPACE", "IDLE", "ENABLE", "CONDSTORE",
"LITERALPLUS", "UNSELECT", "SPECIAL-USE",
"CREATE-SPECIAL-USE", "XOAUTH2"
];
if (args.options.imapExtensions &&
args.options.imapExtensions.indexOf('NOUIDNEXT') !== -1){
plugins.push(NOUIDNEXT);
}
if (args.options.imapExtensions &&
args.options.imapExtensions.indexOf('NO_INTERNALDATE_TZ') !== -1){
plugins.push(NO_INTERNALDATE_TZ);
}
var imapServer = hoodiecrow({
debug: true,
storage: makeFolderStorage(args.options.folderConfig),
plugins: plugins,
});
imapServer.listen(0);
return imapServer;
}
function startSmtpServer() {
// Spin up the SMTP server. This is mainly boilerplate derived from
// hoodiecrow/bin/hoodiecrow, which just wraps simplesmtp:
var smtpServer = simplesmtp.createSimpleServer({
SMTPBanner: "Hoodiecrow",
enableAuthentication: true,
debug: false,
disableDNSValidation: true,
authMethods: ['XOAUTH2', 'PLAIN', 'LOGIN']
}, function(req) {
if (sendShouldFail) {
req.reject();
} else {
withBufferAsString(req, function(body) {
if (args.deliveryMode !== 'blackhole') {
// XXX we need to switch to https://github.com/andris9/smtp-server
// which understands how to do dot removal
body = body.replace(/\n\./g, '\n');
imapServer.appendMessage(
'INBOX',
/* flags: */ [],
getCurrentDate(),
new Buffer(body));
}
req.accept();
});
}
});
smtpServer.listen(0);
return smtpServer;
}
function sendReadyMessageToControlServer(controlUrl, args) {
request({
url: controlUrl,
json: true,
body: args
}, function(error, response) {
if (error) {
console.error('Hoodiecrow process got error from control server:', error);
process.exit(1);
return;
}
});
}
main();