summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/test/fakeserver/Pop3d.jsm
blob: 33a2b06a9047a57b5b89f051dc26dfa91b736942 (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
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
/* -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/**
 * Contributors:
 *   Ben Bucksch <ben.bucksch beonex.com> <http://business.beonex.com> (RFC 5034 Authentication)
 */
/* This file implements test POP3 servers
 */

var EXPORTED_SYMBOLS = [
  "Pop3Daemon",
  "POP3_RFC1939_handler",
  "POP3_RFC2449_handler",
  "POP3_RFC5034_handler",
];

var { AuthPLAIN, AuthLOGIN, AuthCRAM } = ChromeUtils.import(
  "resource://testing-common/mailnews/Auth.jsm"
);
var { mailTestUtils } = ChromeUtils.import(
  "resource://testing-common/mailnews/MailTestUtils.jsm"
);

// Since we don't really need to worry about peristence, we can just
// use a UIDL counter.
var gUIDLCount = 1;

/**
 * Read the contents of a file to the string.
 *
 * @param fileName A path relative to the current working directory, or
 *                 a filename underneath the "data" directory relative to
 *                 the cwd.
 */
function readFile(fileName) {
  let cwd = Services.dirsvc.get("CurWorkD", Ci.nsIFile);

  // Try to find the file relative to either the data directory or to the
  // current working directory.
  let file = cwd.clone();
  if (fileName.includes("/")) {
    let parts = fileName.split("/");
    for (let part of parts) {
      if (part == "..") {
        file = file.parent;
      } else {
        file.append(part);
      }
    }
  } else {
    file.append("data");
    file.append(fileName);
  }

  if (!file.exists()) {
    throw new Error("Cannot find file named " + fileName);
  }

  return mailTestUtils.loadFileToString(file);
}

class Pop3Daemon {
  messages = [];
  _messages = [];
  _totalMessageSize = 0;

  /**
   * Set the messages that the POP3 daemon will provide to its clients.
   *
   * @param messages An array of either 1) strings that are filenames whose
   *     contents will be loaded from the files or 2) objects with a "fileData"
   *     attribute whose value is the content of the file.
   */
  setMessages(messages) {
    this._messages = [];
    this._totalMessageSize = 0;

    function addMessage(element) {
      // if it's a string, then it's a file-name.
      if (typeof element == "string") {
        this._messages.push({ fileData: readFile(element), size: -1 });
      } else {
        // Otherwise it's an object as dictionary already.
        this._messages.push(element);
      }
    }
    messages.forEach(addMessage, this);

    for (var i = 0; i < this._messages.length; ++i) {
      this._messages[i].size = this._messages[i].fileData.length;
      this._messages[i].uidl = "UIDL" + gUIDLCount++;
      this._totalMessageSize += this._messages[i].size;
    }
  }
  getTotalMessages() {
    return this._messages.length;
  }
  getTotalMessageSize() {
    return this._totalMessageSize;
  }
}

// POP3 TEST SERVERS
// -----------------

var kStateAuthNeeded = 1; // Not authenticated yet, need username and password
var kStateAuthPASS = 2; // got command USER, expecting command PASS
var kStateTransaction = 3; // Authenticated, can fetch and delete mail

/**
 * This handler implements the bare minimum required by RFC 1939.
 * If dropOnAuthFailure is set, the server will drop the connection
 * on authentication errors, to simulate servers that do the same.
 */
class POP3_RFC1939_handler {
  kUsername = "fred";
  kPassword = "wilma";

  constructor(daemon) {
    this._daemon = daemon;
    this.closing = false;
    this.dropOnAuthFailure = false;
    this._multiline = false;
    this.resetTest();
  }

  resetTest() {
    this._state = kStateAuthNeeded;
  }

  USER(args) {
    if (this._state != kStateAuthNeeded) {
      return "-ERR invalid state";
    }

    if (args == this.kUsername) {
      this._state = kStateAuthPASS;
      return "+OK user recognized";
    }

    return "-ERR sorry, no such mailbox";
  }
  PASS(args) {
    if (this._state != kStateAuthPASS) {
      return "-ERR invalid state";
    }

    if (args == this.kPassword) {
      this._state = kStateTransaction;
      return "+OK maildrop locked and ready";
    }

    this._state = kStateAuthNeeded;
    if (this.dropOnAuthFailure) {
      this.closing = true;
    }
    return "-ERR invalid password";
  }
  STAT(args) {
    if (this._state != kStateTransaction) {
      return "-ERR invalid state";
    }

    return (
      "+OK " +
      this._daemon.getTotalMessages() +
      " " +
      this._daemon.getTotalMessageSize()
    );
  }
  LIST(args) {
    if (this._state != kStateTransaction) {
      return "-ERR invalid state";
    }

    var result = "+OK " + this._daemon._messages.length + " messages\r\n";
    for (var i = 0; i < this._daemon._messages.length; ++i) {
      result += i + 1 + " " + this._daemon._messages[i].size + "\r\n";
    }

    result += ".";
    return result;
  }
  UIDL(args) {
    if (this._state != kStateTransaction) {
      return "-ERR invalid state";
    }
    let result = "+OK\r\n";
    for (let i = 0; i < this._daemon._messages.length; ++i) {
      result += i + 1 + " " + this._daemon._messages[i].uidl + "\r\n";
    }

    result += ".";
    return result;
  }
  TOP(args) {
    let [messageNumber, numberOfBodyLines] = args.split(" ");
    if (this._state != kStateTransaction) {
      return "-ERR invalid state";
    }
    let result = "+OK\r\n";
    let msg = this._daemon._messages[messageNumber - 1].fileData;
    let index = msg.indexOf("\r\n\r\n");
    result += msg.slice(0, index);
    if (numberOfBodyLines) {
      result += "\r\n\r\n";
      let bodyLines = msg.slice(index + 4).split("\r\n");
      result += bodyLines.slice(0, numberOfBodyLines).join("\r\n");
    }
    result += "\r\n.";
    return result;
  }
  RETR(args) {
    if (this._state != kStateTransaction) {
      return "-ERR invalid state";
    }

    var result = "+OK " + this._daemon._messages[args - 1].size + "\r\n";
    result += this._daemon._messages[args - 1].fileData;
    result += ".";
    return result;
  }
  DELE(args) {
    if (this._state != kStateTransaction) {
      return "-ERR invalid state";
    }
    return "+OK";
  }
  NOOP(args) {
    if (this._state != kStateTransaction) {
      return "-ERR invalid state";
    }
    return "+OK";
  }
  RSET(args) {
    if (this._state != kStateTransaction) {
      return "-ERR invalid state";
    }
    this._state = kStateAuthNeeded;
    return "+OK";
  }
  QUIT(args) {
    // Let the client close the socket
    // this.closing = true;
    return "+OK fakeserver signing off";
  }
  onStartup() {
    this.closing = false;
    this._state = kStateAuthNeeded;
    return "+OK Fake POP3 server ready";
  }
  onError(command, args) {
    return "-ERR command " + command + " not implemented";
  }
  onServerFault(e) {
    return "-ERR internal server error: " + e;
  }
  postCommand(reader) {
    reader.setMultiline(this._multiline);
    if (this.closing) {
      reader.closeSocket();
    }
  }
}

/**
 * This implements CAPA
 *
 * @see RFC 2449
 */
class POP3_RFC2449_handler extends POP3_RFC1939_handler {
  kCapabilities = ["UIDL", "TOP"]; // the test may adapt this as necessary

  CAPA(args) {
    var capa = "+OK List of our wanna-be capabilities follows:\r\n";
    for (var i = 0; i < this.kCapabilities.length; i++) {
      capa += this.kCapabilities[i] + "\r\n";
    }
    if (this.capaAdditions) {
      capa += this.capaAdditions();
    }
    capa += "IMPLEMENTATION fakeserver\r\n.";
    return capa;
  }
}

/**
 * This implements the AUTH command, i.e. authentication using CRAM-MD5 etc.
 *
 * @see RFC 5034
 * @author Ben Bucksch <ben.bucksch beonex.com> <http://business.beonex.com>
 */
class POP3_RFC5034_handler extends POP3_RFC2449_handler {
  kAuthSchemes = ["CRAM-MD5", "PLAIN", "LOGIN"]; // the test may adapt this as necessary
  _usedCRAMMD5Challenge = null; // not base64-encoded

  constructor(daemon) {
    super(daemon);

    this._kAuthSchemeStartFunction = {
      "CRAM-MD5": this.authCRAMStart,
      PLAIN: this.authPLAINStart,
      LOGIN: this.authLOGINStart,
    };
  }

  // called by this.CAPA()
  capaAdditions() {
    var capa = "";
    if (this.kAuthSchemes.length > 0) {
      capa += "SASL";
      for (var i = 0; i < this.kAuthSchemes.length; i++) {
        capa += " " + this.kAuthSchemes[i];
      }
      capa += "\r\n";
    }
    return capa;
  }
  AUTH(lineRest) {
    // |lineRest| is a string containing the rest of line after "AUTH "
    if (this._state != kStateAuthNeeded) {
      return "-ERR invalid state";
    }

    // AUTH without arguments returns a list of supported schemes
    if (!lineRest) {
      var capa = "+OK I like:\r\n";
      for (var i = 0; i < this.kAuthSchemes.length; i++) {
        capa += this.kAuthSchemes[i] + "\r\n";
      }
      capa += ".\r\n";
      return capa;
    }

    var args = lineRest.split(" ");
    var scheme = args[0].toUpperCase();
    // |scheme| contained in |kAuthSchemes|?
    if (
      !this.kAuthSchemes.some(function (s) {
        return s == scheme;
      })
    ) {
      return "-ERR AUTH " + scheme + " not supported";
    }

    var func = this._kAuthSchemeStartFunction[scheme];
    if (!func || typeof func != "function") {
      return (
        "-ERR I just pretended to implement AUTH " + scheme + ", but I don't"
      );
    }
    return func.call(this, "1" in args ? args[1] : undefined);
  }

  onMultiline(line) {
    if (this._nextAuthFunction) {
      var func = this._nextAuthFunction;
      this._multiline = false;
      this._nextAuthFunction = undefined;
      if (line == "*") {
        return "-ERR Okay, as you wish. Chicken";
      }
      if (!func || typeof func != "function") {
        return "-ERR I'm lost. Internal server error during auth";
      }
      try {
        return func.call(this, line);
      } catch (e) {
        return "-ERR " + e;
      }
    }

    if (super.onMultiline) {
      // Call parent.
      return super.onMultiline.call(this, line);
    }
    return undefined;
  }

  authPLAINStart(lineRest) {
    this._nextAuthFunction = this.authPLAINCred;
    this._multiline = true;

    return "+";
  }
  authPLAINCred(line) {
    var req = AuthPLAIN.decodeLine(line);
    if (req.username == this.kUsername && req.password == this.kPassword) {
      this._state = kStateTransaction;
      return "+OK Hello friend! Friends give friends good advice: Next time, use CRAM-MD5";
    }
    if (this.dropOnAuthFailure) {
      this.closing = true;
    }
    return "-ERR Wrong username or password, crook!";
  }

  authCRAMStart(lineRest) {
    this._nextAuthFunction = this.authCRAMDigest;
    this._multiline = true;

    this._usedCRAMMD5Challenge = AuthCRAM.createChallenge("localhost");
    return "+ " + this._usedCRAMMD5Challenge;
  }
  authCRAMDigest(line) {
    var req = AuthCRAM.decodeLine(line);
    var expectedDigest = AuthCRAM.encodeCRAMMD5(
      this._usedCRAMMD5Challenge,
      this.kPassword
    );
    if (req.username == this.kUsername && req.digest == expectedDigest) {
      this._state = kStateTransaction;
      return "+OK Hello friend!";
    }
    if (this.dropOnAuthFailure) {
      this.closing = true;
    }
    return "-ERR Wrong username or password, crook!";
  }

  authLOGINStart(lineRest) {
    this._nextAuthFunction = this.authLOGINUsername;
    this._multiline = true;

    return "+ " + btoa("Username:");
  }
  authLOGINUsername(line) {
    var req = AuthLOGIN.decodeLine(line);
    if (req == this.kUsername) {
      this._nextAuthFunction = this.authLOGINPassword;
    } else {
      // Don't return error yet, to not reveal valid usernames.
      this._nextAuthFunction = this.authLOGINBadUsername;
    }
    this._multiline = true;
    return "+ " + btoa("Password:");
  }
  authLOGINBadUsername(line) {
    if (this.dropOnAuthFailure) {
      this.closing = true;
    }
    return "-ERR Wrong username or password, crook!";
  }
  authLOGINPassword(line) {
    var req = AuthLOGIN.decodeLine(line);
    if (req == this.kPassword) {
      this._state = kStateTransaction;
      return "+OK Hello friend! Where did you pull out this old auth scheme?";
    }
    if (this.dropOnAuthFailure) {
      this.closing = true;
    }
    return "-ERR Wrong username or password, crook!";
  }
}