-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathSMTPRelayServer.java
More file actions
382 lines (348 loc) · 11.1 KB
/
Copy pathSMTPRelayServer.java
File metadata and controls
382 lines (348 loc) · 11.1 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
package javaforce.service;
import java.io.*;
import java.util.*;
import javaforce.*;
import javaforce.bus.*;
/** SMTP Relay Server.
*
* Logs into POP3 service periodically and re-sends all messages to another SMTP service.
*
* Typical usage:
* Install SMTP/POP3 service in insecure network configured in digest mode.
* Install SMTPRelay service in secure network and relay messages from insecure network to corporate SMTP service.
*
* @author pquiring
*/
public class SMTPRelayServer extends ConfigServlet {
private Server server;
private String pop3_host;
private int pop3_port;
private boolean pop3_secure;
private String pop3_user; //login name (required)
private String pop3_pass; //login pass (required)
private String smtp_host;
private int smtp_port;
private boolean smtp_secure;
private String smtp_user; //login name (optional)
private String smtp_pass; //login pass (optional)
private String smtp_from; //override 'from' email (optional)
private ArrayList<String> to_filters = new ArrayList<>();
private boolean keepalive = false; //keep POP3 connection active
private long interval = 15; //how often (minutes) to check for new messages
private POP3 pop3;
private static boolean debug = false;
public final static String serviceBus = "javaforce.jfsmtprelay";
public String getAppName() {return "SMTPRelay";}
public String getBusName() {return serviceBus;}
public String getHelpURL() {return "https://pquiring.github.io/javaforce//projects/jfsmtprelay/docs/help.html";}
public static String getConfigFile() {
return JF.getConfigPath() + "/jfsmtprelay.cfg";
}
public static String getLogFile() {
return JF.getLogPath() + "/jfsmtprelay.log";
}
private class Server extends Thread {
public boolean active;
public void run() {
JFLog.append(JF.getLogPath() + "/jfsmtprelay.log", true);
JFLog.setRetention(30);
JFLog.log("SMTPRelay : Starting service");
try {
loadConfig();
busServer = new JBusServer(serviceBus, new JBusMethods());
busServer.connect();
active = true;
while (active) {
relay();
for(int a=0;a<interval * 60;a++) {
if (!active) break;
JF.sleep(1000);
}
}
if (pop3 != null) {
pop3.disconnect();
pop3 = null;
}
} 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;
if (busServer != null) {
busServer.disconnect();
busServer = null;
}
server = null;
}
private void relay() {
if (!validConfig()) {
JFLog.log("Please configure!");
return;
}
SMTP smtp = null; //client
try {
if (debug) JFLog.log("Checking messages...");
if (pop3 == null) {
pop3 = new POP3(); //client
pop3.debug = debug;
if (debug) JFLog.log("POP3:connecting...");
if (pop3_secure)
pop3.connectSSL(pop3_host, pop3_port);
else
pop3.connect(pop3_host, pop3_port);
if (debug) JFLog.log("POP3:auth...");
if (!pop3.auth(pop3_user, pop3_pass, POP3.AUTH_APOP)) {
throw new Exception("POP3:auth failed!");
}
}
if (debug) JFLog.log("POP3 listing...");
POP3.Message[] list = pop3.list();
if (list == null || list.length == 0) {
if (!keepalive) {
pop3.disconnect();
pop3 = null;
}
if (debug) JFLog.log("No messages found");
return;
}
if (debug || list.length > 0) JFLog.log("Found " + list.length + " messages to relay");
for(POP3.Message em : list) {
if (debug) JFLog.log("Relay message:" + em.idx + ":size=" + em.size);
byte[] data = pop3.get(em.idx);
if (debug) JFLog.log("Message size=" + data.length);
//decode message and re-send
boolean relay = true;
String msg = new String(data);
String[] lns = msg.split("\r\n");
String em_from = null;
ArrayList<String> em_to = new ArrayList<>();
int idx = 0;
while (!lns[idx].equals("")) {
String ln = lns[idx++];
int sp = ln.indexOf(':');
if (sp == -1) continue;
String key = ln.substring(0, sp).toLowerCase();
switch (key) {
case "from":
em_from = getEmail(ln);
break;
case "to":
String to = getEmail(ln);
if (to_filters.size() > 0) {
boolean matches = false;
for(String to_filter : to_filters) {
if (to.toLowerCase().matches(to_filter)) {
matches = true;
break;
}
}
if (!matches) {
relay = false;
}
}
em_to.add(to);
break;
}
}
if (smtp_from != null) {
//override from email
em_from = smtp_from;
}
//send email
if (relay) {
smtp = new SMTP(); //client
smtp.debug = debug;
if (smtp_secure)
smtp.connectSSL(smtp_host, smtp_port);
else
smtp.connect(smtp_host, smtp_port);
smtp.login(); //HELO
if (smtp_user != null && smtp_pass != null) {
if (!smtp.auth(smtp_user, smtp_pass, SMTP.AUTH_LOGIN)) {
smtp.disconnect();
throw new Exception("SMTP auth failed!");
}
}
smtp.from(em_from);
for(String to : em_to) {
smtp.to(to);
}
smtp.data(msg);
smtp.disconnect();
smtp = null;
}
pop3.delete(em.idx);
}
if (!keepalive) {
pop3.disconnect();
pop3 = null;
}
} catch (Exception e) {
if (pop3 != null) {
try {
pop3.disconnect();
} catch (Exception e2) {}
pop3 = null;
}
if (smtp != null) {
try {
smtp.disconnect();
} catch (Exception e2) {}
smtp = null;
}
JFLog.log(e);
}
}
private String getEmail(String ln) {
int i1 = ln.indexOf('<');
int i2 = ln.indexOf('>');
if (i1 == -1 || i2 == -1) return ln;
return ln.substring(i1 + 1, i2);
}
enum Section {None, Global};
private final static String defaultConfig
= "[global]\n"
+ "#pop3_host=1.2.3.4\n"
+ "#pop3_port=995\n"
+ "#pop3_secure=true #(default = false)\n"
+ "#pop3_user=bob\n"
+ "#pop3_pass=secret\n"
+ "#smtp_host=5.6.7.8\n"
+ "#smtp_port=25\n"
+ "#smtp_secure=false #(default = false)\n"
+ "#[email protected] #optional\n"
+ "#smtp_pass=secret #optional\n"
+ "#[email protected] #override from email address (optional)\n"
+ "#to_filter=regexp #regular expression to email must match (multiple supported) (else msg is discarded)\n"
+ "keepalive=true #keep pop3 connection alive (default = false)\n"
+ "#interval=15 #how often to check for messages (minutes) (default=15)\n"
;
private void loadConfig() {
JFLog.log("loadConfig");
Section section = Section.None;
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();
if (ln.startsWith("#")) continue;
if (ln.length() == 0) continue;
if (ln.equals("[global]")) {
section = Section.Global;
continue;
}
int cmt = ln.indexOf('#');
if (cmt != -1) {
ln = ln.substring(0, cmt).trim();
}
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) {
//receive config
case "pop3_host": pop3_host = value; break;
case "pop3_port": pop3_port = Integer.valueOf(value); break;
case "pop3_secure": pop3_secure = value.equals("true"); break;
case "pop3_user": pop3_user = value; break;
case "pop3_pass": pop3_pass = value; break;
//send config
case "smtp_host": smtp_host = value; break;
case "smtp_port": smtp_port = Integer.valueOf(value); break;
case "smtp_secure": smtp_secure = value.equals("true"); break;
case "smtp_user": smtp_user = value; break;
case "smtp_pass": smtp_pass = value; break;
case "smtp_from": smtp_from = value; break;
//msg filtering
case "to_filter": to_filters.add(value.toLowerCase()); break;
//service config
case "keepalive": keepalive = value.equals("true"); break;
case "interval":
interval = Integer.valueOf(value);
if (interval < 1) interval = 1;
if (interval > 1440) interval = 1440; //one day
break;
case "debug": debug = value.equals("true"); 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 validConfig() {
if (pop3_host == null) return false;
if (pop3_user == null) return false;
if (pop3_pass == null) return false;
if (smtp_host == null) return false;
return true;
}
public static void serviceStart(String[] args) {
service = new SMTPRelayServer();
service.start();
}
public static void serviceStop() {
JFLog.log("SMTPRelay : Stopping service");
service.stop();
}
private static SMTPRelayServer service;
private JBusServer busServer;
private String config;
public static class JBusMethods {
public String getConfig() {
return service.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");
service.stop();
service = new SMTPRelayServer();
service.start();
return true;
}
public String getLogFile() {
return SMTPRelayServer.getLogFile();
}
}
}