1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
8 import org.ibex.io.Fountain;
9 import org.ibex.util.*;
10 import org.ibex.mail.filter.*;
11 import org.ibex.mail.target.*;
16 // FIXME: check for binaries (razor, clamassassin, etc) and complain if not present
19 // - better matching syntax:
23 // - ==> {discard, refuse, bounce}
26 public class Script extends JS.Obj implements Target {
28 private static final JS.Method METHOD = new JS.Method();
30 private static Script root = null;
31 private static final String DEFAULT_CONF = Mailbox.STORAGE_ROOT + "conf" + File.separatorChar + "inbound.js";
32 public static Script root() {
34 if (root == null) root = new Script(System.getProperty("ibex.mail.conf", DEFAULT_CONF));
36 } catch (Exception e) {
37 Log.error(Script.class, e);
43 private Message m = null;
44 private String filePath = null;
45 public Script(String filePath) throws JSExn, IOException {
46 this.filePath = filePath;
47 js = JSU.cloneWithNewGlobalScope(JSU.fromReader(filePath, 1, new InputStreamReader(new FileInputStream(filePath))),
50 private class ScriptScope extends JS.Immutable {
51 ScriptEnv env = new ScriptEnv();
52 public JS get(JS name) throws JSExn {
55 case "ibex": return env;
62 public void accept(Message m) throws IOException, MailException {
64 new Script(filePath).reallyAccept(m);
67 throw new MailException(e.toString());
71 private synchronized void reallyAccept(Message m) throws IOException, MailException, JSExn {
74 Object ret = js.call(null, new JS[] { m });
75 Log.warn(this, "configuration script returned " + ret);
76 if (ret == null) throw new IOException("configuration script returned null");
77 while (ret instanceof JSReflection.Wrapper) ret = ((JSReflection.Wrapper)ret).unwrap();
78 if (ret instanceof Target) ((Target)ret).accept(m);
79 //else if (ret instanceof Filter) ((Filter)ret).process(m);
80 else throw new IOException("configuration script returned a " + ret.getClass().getName());
83 throw new IOException("configuration script threw an exception");
87 // FIXME: this should extend org.ibex.core.Ibex
88 public class ScriptEnv extends JS.Obj {
90 private PropertyFile prefs = null;
95 prefs = new PropertyFile(new File("/etc/org.ibex.mail.properties"));
96 } catch (IOException e) {
97 Log.error(ScriptEnv.class, e);
102 /** lets us put multi-level get/put/call keys all in the same method */
103 private class Sub extends JS.Immutable {
105 Sub(String key) { this.key = key; }
106 public void put(JS key, JS val) throws JSExn {
107 ScriptEnv.this.put(JSU.S(this.key + "." + JSU.toString(key)), val); }
108 public JS get(JS key) throws JSExn { return ScriptEnv.this.get(JSU.S(this.key + "." + JSU.toString(key))); }
109 public JS call(JS method, JS[] args) throws JSExn {
110 return ScriptEnv.this.call(JSU.S(this.key + "." + JSU.toString(method)), args);
113 private Sub getSub(String s) { return new Sub(s); }
115 public JS get(JS name) throws JSExn {
117 case "math": return ibexMath;
118 case "string": return ibexString;
119 case "date": return METHOD;
120 case "regexp": return METHOD;
121 case "log": return getSub("log");
122 case "log.debug": return METHOD;
123 case "log.info": return METHOD;
124 case "log.warn": return METHOD;
125 case "log.error": return METHOD;
126 case "list": return getSub("list");
127 case "url": return getSub("url");
128 case "url.encode": return METHOD;
129 case "mail": return getSub("mail");
130 case "mail.forward": return METHOD;
131 case "mail.forward2": return METHOD;
132 case "mail.send": return METHOD;
133 case "mail.attempt": return METHOD;
134 case "mail.later": return Later.instance;
135 case "mail.drop": return METHOD;
136 case "mail.razor": return getSub("mail.razor");
137 case "mail.razor.check": return METHOD;
138 case "mail.clamav": return getSub("mail.clamav");
139 case "mail.clamav.check": return METHOD;
140 case "mail.procmail": /* FEATURE */ return null;
141 case "mail.vacation": /* FEATURE */ return null;
142 case "mail.verp": return getSub("mail.verp");
143 case "mail.verp.check": return METHOD;
144 case "mail.dcc": return getSub("mail.dcc");
145 case "mail.dcc.check": return METHOD;
146 case "mail.bounce": return METHOD;
147 case "mail.reject": return METHOD;
148 case "mail.my": return getSub("mail.my");
149 case "mail.dir": return METHOD;
150 case "mail.shell": return METHOD;
151 case "mail.my.prefs": try {
152 return new org.ibex.js.Directory(new File("/etc/org.ibex.mail.prefs"));
153 } catch (IOException e) { throw new JSExn(e.toString()); }
154 case "mail.whitelist": return JSReflection.wrap(org.ibex.mail.SMTP.whitelist);
155 case "mail.my.mailbox":
156 MailTree root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, true);
157 return (JS)root.slash("user", true).slash("megacz", true);
158 case "mail.list": return METHOD;
160 return super.get(name);
163 public JS call(JS name0, JS[] args) throws JSExn {
164 final JS a = args.length >= 1 ? args[0] : null;
165 final JS b = args.length >= 2 ? args[1] : null;
166 final JS c = args.length >= 3 ? args[2] : null;
167 final int nargs = args.length;
168 String name = JSU.toString(name0);
170 if (name.equals("url.encode")) return JSU.S(java.net.URLEncoder.encode(JSU.toString(args[0])));
171 if (name.equals("mail.list")) return JSReflection.wrap(FileBasedMailbox.getFileBasedMailbox(JSU.toString(args[0]), false));
172 if (name.equals("mail.dir")) {
173 return new org.ibex.js.Directory(new File(JSU.toString(args[0])));
175 if (name.equals("mail.shell")) {
177 Log.warn("dbug", a.getClass().getName());
178 Log.warn("dbug", b.getClass().getName());
179 Message m = (Message)b;
180 final Process p = Runtime.getRuntime().exec(JSU.toString(a));
181 Main.threadPool.start(new Runnable() {
184 BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
186 while((s = br.readLine())!=null)
187 Log.warn("shell", s);
188 } catch (Exception e) { e.printStackTrace(); }
191 OutputStream os = p.getOutputStream();
192 Stream stream = new Stream(os);
194 // why do I need to go via an sb here?
195 StringBuffer sb = new StringBuffer();
196 m.getBody().getStream().transcribe(sb);
197 stream.println(sb.toString());
204 if (name.equals("date")) { return new JSDate(args); }
205 if (name.equals("mail.send") || name.equals("send") || name.equals("mail.attempt") || name.equals("attempt")) {
206 boolean attempt = name.equals("mail.attempt") || name.equals("attempt");
209 Address from = null, to = null, envelopeFrom = null, envelopeTo = null;
210 JS.Enumeration e = m.keys();
211 Headers headers = new Headers();
212 for(; e.hasNext();) {
213 JS key = (JS)e.next();
214 JS val = m.get(key) == null ? null : m.get(key);
215 if ("body".equalsIgnoreCase(JSU.toString(key))) body = JSU.toString(val);
216 else headers = new Headers(headers, new String[] { JSU.toString(key), JSU.toString(val) });
217 if ("from".equalsIgnoreCase(JSU.toString(key))) from = Address.parse(JSU.toString(val));
218 if ("to".equalsIgnoreCase(JSU.toString(key))) to = Address.parse(JSU.toString(val));
219 if ("envelopeFrom".equalsIgnoreCase(JSU.toString(key))) envelopeFrom = Address.parse(JSU.toString(val));
220 if ("envelopeTo".equalsIgnoreCase(JSU.toString(key))) envelopeTo = Address.parse(JSU.toString(val));
222 if (envelopeTo == null) envelopeTo = to;
223 if (envelopeFrom == null) envelopeFrom = from;
225 Message.newMessageFromHeadersAndBody(headers, Fountain.Util.create(body), envelopeFrom, envelopeTo);
230 org.ibex.mail.SMTP.Outgoing.attempt(message);
232 org.ibex.mail.SMTP.Outgoing.enqueue(message);
235 } catch (Exception ex) {
236 if (!attempt) Log.warn(this, ex);
238 if (!ok && !attempt) throw new JSExn("SMTP server rejected message");
241 if (name.equals("mail.razor.check")) {
242 Process p = Runtime.getRuntime().exec("razor-check");
243 ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
244 return JSU.N(p.waitFor());
246 if (name.equals("mail.clamav.check")) {
247 // FIXME: this is returning "is-virus-laden" when clamdscan is unhappy -- BAD!
248 // should use error code: 0=clean, 1=virus, 2=malfunction
249 Process p = Runtime.getRuntime().exec("clamdscan - --stdout --quiet");
250 ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
251 int result = p.waitFor();
252 if (result==0) return JSU.N(0);
253 StringBuffer ret = new StringBuffer();
254 new Stream(p.getInputStream()).transcribe(ret);
255 return JSU.S(ret.toString());
257 if (name.equals("mail.verp.check")) {
258 String ret = VERP.verpVerify(Address.parse(JSU.toString(a)), "SECRET".getBytes(), 0);
259 return ret==null ? null : JSU.S(ret);
261 if (name.equals("mail.dcc.check")) {
262 Process p = Runtime.getRuntime().exec(new String[] { "dccproc", "-H" });
263 ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
264 StringBuffer ret = new StringBuffer();
265 new Stream(p.getInputStream()).transcribe(ret);
267 String result = ret.toString();
268 Log.warn("dcc", ((Message)args[0]).summary() + ":\n " + result);
272 int i_body = result.indexOf("Body=");
273 int i_fuz1 = result.indexOf("Fuz1=");
274 int i_fuz2 = result.indexOf("Fuz2=");
275 if (i_body != -1) try {
276 String s = result.substring(i_body+5);
277 if (s.indexOf(' ') != -1) s = s.substring(0, s.indexOf(' '));
278 if (s.indexOf('\n') != -1) s = s.substring(0, s.indexOf('\n'));
279 body = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim());
280 } catch (Exception e) { Log.error("", e); }
281 if (i_fuz1 != -1) try {
282 String s = result.substring(i_fuz1+5);
283 if (s.indexOf(' ') != -1) s = s.substring(0, s.indexOf(' '));
284 if (s.indexOf('\n') != -1) s = s.substring(0, s.indexOf('\n'));
285 fuz1 = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim());
286 } catch (Exception e) { Log.error("", e); }
287 if (i_fuz2 != -1) try {
288 String s = result.substring(i_fuz2+5);
289 if (s.indexOf(' ') != -1) s = s.substring(0, s.indexOf(' '));
290 if (s.indexOf('\n') != -1) s = s.substring(0, s.indexOf('\n'));
291 fuz2 = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim());
292 } catch (Exception e) { Log.error("", e); }
293 JSArray jsa = new JSArray();
294 jsa.put(JSU.N(0), JSU.N(body));
295 jsa.put(JSU.N(1), JSU.N(fuz1));
296 jsa.put(JSU.N(2), JSU.N(fuz2));
299 if (name.equals("mail.drop")) {
300 return args.length==0 ? new Drop() : new Drop(JSU.toString(args[0]));
302 if (name.equals("mail.bounce")) {
303 return new JSTarget() {
304 public void accept(Message m) throws MailException {
306 Message m2 = m.bounce(JSU.toString(a));
307 org.ibex.mail.SMTP.Outgoing.enqueue(m2);
308 Log.error(this, "BOUNCING! " + m2.summary());
309 } catch (Exception e) {
314 if (name.equals("mail.forward2") || name.equals("forward2")) {
316 Message m2 = m.withEnvelope(m.envelopeFrom, new Address(JSU.toString(a)));
317 org.ibex.mail.SMTP.Outgoing.enqueue(m2);
318 } catch (Exception e) {
320 throw new JSExn(e.toString());
324 if (name.equals("mail.forward") || name.equals("forward")) {
325 Message m2 = Script.this.m.withEnvelope(Script.this.m.envelopeFrom, new Address(JSU.toString(a)));
326 org.ibex.mail.SMTP.Outgoing.attempt(m2, false);
327 return Drop.instance;
329 if (name.equals("mail.reject"))
330 return new Reject(JSU.toString(a));
331 if (name.equals("log.debug") || name.equals("debug")) { JSU.debug(a== null ? "**null**" : JSU.toString(a)); return null; }
332 if (name.equals("log.info") || name.equals("info")) { JSU.info(a== null ? "**null**" : JSU.toString(a)); return null; }
333 if (name.equals("log.warn") || name.equals("warn")) { JSU.warn(a== null ? "**null**" : JSU.toString(a)); return null; }
334 if (name.equals("log.error") || name.equals("error")) { JSU.error(a== null ? "**null**" : JSU.toString(a)); return null; }
337 if (name.equals("regexp")) {return new JSRegexp(a, null); }
340 if (name.equals("regexp")) {return new JSRegexp(a, b); }
342 } catch (MailException e) { throw e;
343 } catch (Exception e) {
344 Log.warn(this, "ibex."+name+"() threw: " + e);
346 if (e instanceof JSExn) throw ((JSExn)e);
347 throw new JSExn("invalid argument for ibex object method "+JSU.toString(name0)+"()");
349 throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+JSU.toString(name0)+"()");
352 public final JSMath ibexMath = new JSMath() {
353 public JS get(JS name) throws JSExn {
356 case "isNaN": return gs.get(name);
357 case "isFinite": return gs.get(name);
358 case "NaN": return gs.get(name);
359 case "Infinity": return gs.get(name);
365 public final JS ibexString = new JS.Immutable() {
366 public JS get(JS name) throws JSExn {
369 case "parseInt": return gs.get(JSU.S("parseInt"));
370 case "parseFloat": return gs.get(JSU.S("parseFloat"));
371 case "decodeURI": return gs.get(JSU.S("decodeURI"));
372 case "decodeURIComponent": return gs.get(JSU.S("decodeURIComponent"));
373 case "encodeURI": return gs.get(JSU.S("encodeURI"));
374 case "encodeURIComponent": return gs.get(JSU.S("encodeURIComponent"));
375 case "escape": return gs.get(JSU.S("escape"));
376 case "unescape": return gs.get(JSU.S("unescape"));
377 case "fromCharCode": return gs.get(JSU.S("stringFromCharCode"));
384 private static abstract class JSTarget extends JS.Obj implements Target { }
386 public static class Drop extends JS.Obj implements Target {
387 public static final Drop instance = new Drop();
388 public final String reason;
389 public Drop() { this(null); }
390 public Drop(String reason) { this.reason = reason; }
391 public void accept(Message m) throws IOException, MailException {
392 Log.warn(this, "dropping" +(reason==null?"":(" because "+reason))+ ": " + m.summary());
396 public static class Later extends JS.Obj implements Target {
397 public static final Later instance = new Later();
398 public static class LaterException extends RuntimeException { }
399 public void accept(Message m) throws IOException, MailException {
400 Log.warn(this, "delaying message " + m.summary());
401 throw new LaterException();
405 /** a fast-write, slow-read place to stash all messages we touch -- in case of a major f*ckup */
406 public static class Transcript implements Target {
408 public static final Transcript transcript = new Transcript(Mailbox.STORAGE_ROOT + File.separatorChar + "transcript");
411 public Transcript(String path) { new File(this.path = path).mkdirs(); }
412 private static String lastTime = null;
413 private static int lastCounter = 0;
415 public synchronized void accept(Message message) {
417 File today = new File(path + File.separatorChar + (new SimpleDateFormat("yy-MMM-dd").format(new Date())));
420 String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
421 synchronized (Transcript.class) {
422 if (lastTime != null && lastTime.equals(time)) {
423 time += "." + (++lastCounter);
430 File target = new File(today.getPath() + File.separatorChar + time + ".txt");
431 OutputStream os = new FileOutputStream(target);
433 message.getStream().transcribe(new Stream(os));
435 } finally { os.close(); }
436 } catch (IOException e) { throw new MailException.IOException(e); }
440 public static class Reject extends JS.Obj implements Target {
441 public final String reason;
442 public Reject(String reason) { this.reason = reason; }
443 public void accept(Message m) throws IOException, MailException {
444 throw new RejectException(m, reason);
446 public static class RejectException extends RuntimeException {
447 public final Message m;
448 public final String reason;
449 public RejectException(Message m, String reason) { this.m = m; this.reason = reason; }