-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathSMTPServer.java
More file actions
702 lines (657 loc) · 20.3 KB
/
Copy pathSMTPServer.java
File metadata and controls
702 lines (657 loc) · 20.3 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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
package javaforce.service;
import java.io.*;
import java.net.*;
import java.util.*;
import javaforce.*;
import javaforce.net.*;
import javaforce.bus.*;
/** SMTP Server.
*
* Simple non-relaying mail server.
*
* Supports 25, 465(ssl), 587(tls)
*
* See SMTPEvents
*
* @author pquiring
*/
public class SMTPServer extends ConfigServlet {
public final static String serviceBus = "javaforce.jfsmtp";
public static boolean debug = false;
public interface Events {
public void message(SMTPServer server, String msgfile);
}
public String getAppName() {return "SMTP";}
public String getBusName() {return serviceBus;}
public String getHelpURL() {return "https://pquiring.github.io/javaforce//projects/jfsmtp/docs/help.html";}
public static String getConfigFile() {
return JF.getConfigPath() + "/jfsmtp.cfg";
}
public static String getLogFile() {
return JF.getLogPath() + "/jfsmtp.log";
}
public static String getMailboxFolder(String user) {
StringBuilder path = new StringBuilder();
if (JF.isWindows()) {
path.append(System.getenv("ProgramData").replaceAll("\\\\", "/"));
path.append("/jfsmtp/mail");
} else {
path.append("/var/jfsmtp/mail");
}
if (user != null) {
path.append("/");
path.append(user);
}
String mail = path.toString();
new File(mail).mkdirs();
return mail;
}
private static SMTPServer smtp;
private Server server;
private Events events;
private ArrayList<ServerWorker> servers = new ArrayList<ServerWorker>();
private ArrayList<ClientWorker> clients = new ArrayList<ClientWorker>();
private String domain;
private String ldap_domain;
private String ldap_server;
private ArrayList<EMail> users;
private Object lock = new Object();
private IP4Port bind = new IP4Port();
private ArrayList<Subnet4> subnet_src_list;
private ArrayList<Integer> ports = new ArrayList<>();
private ArrayList<Integer> ssl_ports = new ArrayList<>();
private boolean digest = false; //any message is accepted ignoring all recipents (use POP3 admin account to retrieve)
public SMTPServer() {
}
public void setEvents(Events events) {
this.events = events;
}
private void addSession(ClientWorker sess) {
synchronized(lock) {
clients.add(sess);
}
}
private void removeSession(ClientWorker sess) {
synchronized(lock) {
clients.remove(sess);
}
}
private static String getKeyFile() {
return JF.getConfigPath() + "/jfsmtp.key";
}
private class Server extends Thread {
public boolean active;
public void run() {
JFLog.append(JF.getLogPath() + "/jfsmtp.log", true);
JFLog.setRetention(30);
JFLog.log("SMTP : Starting service");
active = true;
try {
loadConfig();
busServer = new JBusServer(serviceBus, new JBusMethods());
busServer.connect();
for(int p : ports) {
ServerWorker worker = new ServerWorker(p, false);
worker.start();
servers.add(worker);
}
for(int p : ssl_ports) {
ServerWorker worker = new ServerWorker(p, true);
worker.start();
servers.add(worker);
}
while (active) {
synchronized (this) {
wait();
}
}
} catch (Exception e) {
JFLog.log(e);
}
}
}
public void start() {
stop();
server = new Server();
server.start();
}
public void stop() {
if (server == null) return;
server.active = false;
synchronized (server) {
server.notify();
}
synchronized(lock) {
ServerWorker[] sa = servers.toArray(new ServerWorker[0]);
for(ServerWorker s : sa) {
s.close();
}
servers.clear();
ClientWorker[] ca = clients.toArray(new ClientWorker[0]);
for(ClientWorker s : ca) {
s.close();
}
clients.clear();
}
if (busServer != null) {
busServer.disconnect();
busServer = null;
}
server = null;
}
enum Section {None, Global};
private final static String defaultConfig
= "[global]\n"
+ "port=25\n" //default port (supports SSL)
+ "#port=587\n" //explicit SSL port
+ "#secure=465\n" //implicit SSL port
+ "#bind=192.168.100.2\n"
+ "#domain=example.com\n"
+ "#ldap_domain=example.org\n"
+ "#ldap_server=192.168.200.2\n"
+ "#account=user:pass\n"
+ "#digest=true\n" //digest mode (see POP3/SMTPRelay services)
+ "#src.ipnet=192.168.2.0/255.255.255.0\n"
+ "#src.ip=192.168.3.2\n"
;
private void loadConfig() {
JFLog.log("loadConfig");
users = new ArrayList<EMail>();
Section section = Section.None;
bind.setIP("0.0.0.0"); //bind to all interfaces
bind.port = 25;
subnet_src_list = new ArrayList<Subnet4>();
try {
BufferedReader br = new BufferedReader(new FileReader(getConfigFile()));
StringBuilder cfg = new StringBuilder();
while (true) {
String ln = br.readLine();
if (ln == null) break;
cfg.append(ln);
cfg.append("\n");
ln = ln.trim();
int cmt = ln.indexOf('#');
if (cmt != -1) ln = ln.substring(0, cmt).trim();
if (ln.length() == 0) continue;
if (ln.equals("[global]")) {
section = Section.Global;
continue;
}
int idx = ln.indexOf("=");
if (idx == -1) continue;
String key = ln.substring(0, idx);
String value = ln.substring(idx + 1);
switch (section) {
case None:
case Global:
switch (key) {
case "port":
ports.add(Integer.valueOf(ln.substring(5)));
break;
case "secure":
ssl_ports.add(Integer.valueOf(ln.substring(7)));
break;
case "bind":
if (!bind.setIP(value)) {
JFLog.log("SMTP:bind:Invalid IP:" + value);
break;
}
break;
case "account": {
EMail user = new EMail();
int cln = value.indexOf(':');
if (cln == -1) {
JFLog.log("Invalid user:" + value);
continue;
}
user.user = value.substring(0, cln);
user.pass = value.substring(cln + 1);
users.add(user);
break;
}
case "domain":
domain = value;
break;
case "ldap_domain":
ldap_domain = value;
break;
case "ldap_server":
ldap_server = value;
break;
case "digest":
digest = value.equals("true");
break;
case "debug":
debug = value.equals("true");
break;
case "src.ipnet": {
Subnet4 subnet = new Subnet4();
idx = value.indexOf('/');
if (idx == -1) {
JFLog.log("SMTP:Invalid IP Subnet:" + value);
break;
}
String ip = value.substring(0, idx);
String mask = value.substring(idx + 1);
if (!subnet.setIP(ip)) {
JFLog.log("SMTP:Invalid IP:" + ip);
break;
}
if (!subnet.setMask(mask)) {
JFLog.log("SMTP:Invalid netmask:" + mask);
break;
}
JFLog.log("Source Allow IP Network=" + subnet.toString());
subnet_src_list.add(subnet);
break;
}
case "src.ip": {
Subnet4 subnet = new Subnet4();
if (!subnet.setIP(value)) {
JFLog.log("SMTP:Invalid IP:" + value);
break;
}
subnet.setMask("255.255.255.255");
JFLog.log("Source Allow IP Address=" + subnet.toString());
subnet_src_list.add(subnet);
break;
}
}
break;
}
}
br.close();
config = cfg.toString();
} catch (FileNotFoundException e) {
//create default config
JFLog.log("config not found, creating defaults.");
try {
FileOutputStream fos = new FileOutputStream(getConfigFile());
fos.write(defaultConfig.getBytes());
fos.close();
config = defaultConfig;
} catch (Exception e2) {
JFLog.log(e2);
}
} catch (Exception e) {
JFLog.log(e);
}
}
public boolean login(String user, String pass) {
for(EMail acct : users) {
if (acct.user.equals(user)) {
return acct.pass.equals(pass);
}
}
if (ldap_server != null && ldap_domain != null) {
LDAP ldap = new LDAP();
return ldap.login(ldap_server, ldap_domain, user, pass);
}
return false;
}
public class ServerWorker extends Thread {
private ServerSocket ss;
private int port;
private boolean secure;
private boolean worker_active;
public ServerWorker(int port, boolean secure) {
this.port = port;
this.secure = secure;
}
public void run() {
try {
if (secure) {
JFLog.log("CreateServerSocketSSL");
KeyMgmt keys = new KeyMgmt();
if (new File(getKeyFile()).exists()) {
FileInputStream fis = new FileInputStream(getKeyFile());
keys.open(fis, "password");
fis.close();
} else {
JFLog.log("Warning:Server SSL Keys not generated!");
}
ss = JF.createServerSocketSSL(keys);
} else {
ss = new ServerSocket();
}
synchronized(bind) {
bind.port = port;
ss.bind(bind.toInetSocketAddress());
}
worker_active = true;
while (worker_active) {
Socket s = ss.accept();
InetSocketAddress sa = (InetSocketAddress)s.getRemoteSocketAddress();
String src_ip = sa.getAddress().getHostAddress();
if (src_ip.equals("0:0:0:0:0:0:0:1")) {
//IP6 localhost
src_ip = "127.0.0.1";
}
if (!ip_src_allowed(src_ip)) {
JFLog.log("SMTP:Source IP blocked:" + src_ip);
s.close();
continue;
}
ClientWorker sess = new ClientWorker(s, secure);
addSession(sess);
sess.start();
}
} catch (Exception e) {
JFLog.log(e);
}
}
public void close() {
try { ss.close(); } catch (Exception e) {}
ss = null;
}
}
private boolean ip_src_allowed(String ip4) {
if (subnet_src_list.size() == 0) return true;
IP4 target = new IP4();
if (!target.setIP(ip4)) return false;
for(Subnet4 net : subnet_src_list) {
if (net.isWithin(target)) {
return true;
}
}
return false;
}
private boolean userExists(EMail email) {
for(EMail acct : users) {
if (acct.user.equals(email.user)) {
return true;
}
}
//TODO : ldap users? (don't have password)
return false;
}
public class ClientWorker extends Thread {
private Socket c;
private boolean secure;
private InputStream cis = null;
private OutputStream cos = null;
private byte[] req = new byte[1500];
private int reqSize = 0;
private byte[] buffer = new byte[1500];
private int bufferSize = 0;
private EMail from;
private ArrayList<EMail> to = new ArrayList<>();
public ClientWorker(Socket s, boolean secure) {
c = s;
this.secure = secure;
}
public void close() {
if (c != null) {
try { c.close(); } catch (Exception e) {}
c = null;
}
}
public String readln() {
if (bufferSize > 0) {
System.arraycopy(buffer, 0, req, 0, bufferSize);
reqSize = bufferSize;
bufferSize = 0;
} else {
reqSize = 0;
}
try {
while (c != null && c.isConnected()) {
//check for EOL
if (reqSize >= 2) {
for(int idx=2;idx<=reqSize;idx++) {
if (req[idx - 2] == '\r' && req[idx - 1] == '\n') {
int left = reqSize - idx;
if (left > 0) {
//save extra data for next time
System.arraycopy(req, idx, buffer, 0, left);
bufferSize = left;
}
return new String(req, 0, idx - 2).trim();
}
}
}
//expand buffer if needed
if (reqSize == req.length) {
//req buffer full - expand it
if (req.length >= 8 * 1500) {
throw new Exception("data too large");
}
int newSize = req.length << 1;
byte[] new_req = new byte[newSize];
buffer = new byte[newSize];
System.arraycopy(req, 0, new_req, 0, req.length);
req = new_req;
}
//read more data
int read = cis.read(req, reqSize, req.length - reqSize);
if (read < 0) break;
reqSize += read;
}
} catch (Exception e) {
JFLog.log(e);
}
return null;
}
public void run() {
try {
JFLog.log("Session start");
cis = c.getInputStream();
cos = c.getOutputStream();
cos.write(("220 jfSMTP Server/" + JF.getVersion() + "\r\n").getBytes());
while (c != null && c.isConnected()) {
String cmd = readln();
if (cmd == null) break;
if (cmd.equalsIgnoreCase("QUIT")) {
cos.write("221 Goodbye\r\n".getBytes());
break;
}
doCommand(cmd);
}
} catch (Exception e) {
if (!(e instanceof SocketException)) JFLog.log(e);
}
close();
removeSession(this);
}
private void doCommand(String cmd) throws Exception {
if (debug) {
JFLog.log("Request=" + cmd);
}
String[] p = cmd.split(" ", 2);
switch (p[0].toUpperCase()) {
case "HELO":
case "EHLO":
cos.write(("250 jfSMTP Server/" + JF.getVersion() + "\r\n").getBytes());
break;
case "AUTH":
String type = p[1];
switch (type.toUpperCase()) {
case "LOGIN": { //plain text
cos.write("334 Send username\r\n".getBytes());
String user_base64 = readln();
if (user_base64 == null) {close(); return;}
String user = new String(javaforce.Base64.decode(user_base64.getBytes()));
cos.write("334 Send password\r\n".getBytes());
String pass_base64 = readln();
if (pass_base64 == null) {close(); return;}
String pass = new String(javaforce.Base64.decode(pass_base64.getBytes()));
if (login(user, pass)) {
cos.write("235 Login successful\r\n".getBytes());
} else {
JF.sleep(1000);
cos.write("501 Login failed\r\n".getBytes());
close();
return;
}
break;
}
default: {
cos.write("504 Unknown AUTH type\r\n".getBytes());
break;
}
}
break;
case "STARTTLS":
if (secure) {
cos.write("550 Already secure\r\n".getBytes());
break;
}
cos.write("220 Ok\r\n".getBytes());
//upgrade connection to SSL
c = JF.connectSSL(c, KeyMgmt.getDefaultClient());
cis = c.getInputStream();
cos = c.getOutputStream();
secure = true;
break;
case "DATA":
if (from == null) {
cos.write("550 No from address\r\n".getBytes());
break;
}
if (to.size() == 0) {
cos.write("550 No recipients\r\n".getBytes());
break;
}
cos.write("354 Send Data\r\n".getBytes());
String filename;
synchronized(lock) {
filename = Long.toString(System.currentTimeMillis());
JF.sleep(10);
}
String basefile = getMailboxFolder(null) + "/" + filename;
String quefile = basefile + ".que";
String msgfile = basefile + ".msg";
OutputStream questream = new FileOutputStream(quefile);
while (c != null && c.isConnected()) {
String ln = readln();
if (ln == null) {close(); return;}
if (ln.equals(".")) {
break;
}
questream.write(ln.getBytes());
questream.write("\r\n".getBytes());
}
questream.close();
new File(quefile).renameTo(new File(msgfile));
if (!digest) {
//link message to each recipient
StringBuilder to_list = new StringBuilder();
for(EMail acct : to) {
to_list.append("to:");
to_list.append(acct.user);
to_list.append("\r\n");
}
byte[] to_data = to_list.toString().getBytes();
for(EMail acct : to) {
String userbox = getMailboxFolder(acct.user);
String userbasefile = userbox + "/" + filename;
String userquefile = userbasefile + ".que";
String usermsgfile = userbasefile + ".msg";
FileOutputStream fos = new FileOutputStream(userquefile);
fos.write(to_data);
fos.close();
new File(userquefile).renameTo(new File(usermsgfile));
}
}
if (events != null) {
events.message(smtp, msgfile);
}
cos.write("250 Ok\r\n".getBytes());
reset();
break;
case "MAIL":
if (from != null) {
cos.write("550 Already have from email\r\n".getBytes());
break;
}
from = new EMail();
from = null;
cos.write("550 Invalid from address\r\n".getBytes());
break;
}
cos.write("250 Ok\r\n".getBytes());
break;
case "RCPT":
EMail email = new EMail();
if (!email.set(cmd)) {
cos.write("550 Invalid to address\r\n".getBytes());
break;
}
if (!digest) {
if (domain != null && !email.domain.equals(domain)) {
cos.write("550 Server will not relay messages\r\n".getBytes());
break;
}
if (!userExists(email)) {
cos.write("550 User not found\r\n".getBytes());
break;
}
}
to.add(email);
cos.write("250 Ok\r\n".getBytes());
break;
default:
cos.write("500 Unknown command\r\n".getBytes());
break;
}
}
private void reset() {
from = null;
to.clear();
}
}
public static void serviceStart(String[] args) {
smtp = new SMTPServer();
smtp.start();
}
public static void serviceStop() {
JFLog.log("SMTP : Stopping service");
smtp.stop();
}
private JBusServer busServer;
private String config;
public static boolean createKeys() {
return KeyMgmt.keytool(new String[] {
"-genkey", "-debug", "-alias", "jfsmtp", "-keypass", "password", "-storepass", "password",
"-keystore", getKeyFile(), "-validity", "3650", "-dname", "CN=jfsmtp.sourceforge.net, OU=user, O=server, C=CA",
"-keyalg" , "RSA", "-keysize", "2048"
});
}
public static class JBusMethods {
public String getConfig() {
return smtp.config;
}
public boolean setConfig(String cfg) {
//write new file
JFLog.log("setConfig");
try {
FileOutputStream fos = new FileOutputStream(getConfigFile());
fos.write(cfg.getBytes());
fos.close();
return true;
} catch (Exception e) {
JFLog.log(e);
return false;
}
}
public boolean restart() {
JFLog.log("restart");
smtp.stop();
smtp = new SMTPServer();
smtp.start();
return true;
}
public boolean genKeys() {
if (createKeys()) {
JFLog.log("Generated Keys");
return true;
} else {
return false;
}
}
public String getLogFile() {
return SMTPServer.getLogFile();
}
}
}