// Copyright 2000-2005 the Contributors, as shown in the revision logs. // Licensed under the Apache Public Source License 2.0 ("the License"). // You may not use this file except in compliance with the License. package org.ibex.mail; import org.ibex.js.*; import org.ibex.io.*; import org.ibex.io.Fountain; import org.ibex.util.*; import org.ibex.mail.filter.*; import org.ibex.mail.target.*; import java.io.*; import java.util.*; import java.text.*; // FIXME: check for binaries (razor, clamassassin, etc) and complain if not present // // - better matching syntax: // - src-ip // - from *@foo.com // - list-id // - ==> {discard, refuse, bounce} // public class Script extends JS.Obj implements Target { private static final JS.Method METHOD = new JS.Method(); private static Script root = null; private static final String DEFAULT_CONF = Mailbox.STORAGE_ROOT + "conf" + File.separatorChar + "inbound.js"; public static Script root() { try { if (root == null) root = new Script(System.getProperty("ibex.mail.conf", DEFAULT_CONF)); return root; } catch (Exception e) { Log.error(Script.class, e); return null; } } final JS js; private Message m = null; private String filePath = null; public Script(String filePath) throws JSExn, IOException { this.filePath = filePath; js = JSU.cloneWithNewGlobalScope(JSU.fromReader(filePath, 1, new InputStreamReader(new FileInputStream(filePath))), new ScriptScope()); } private class ScriptScope extends JS.Immutable { ScriptEnv env = new ScriptEnv(); public JS get(JS name) throws JSExn { //#jsswitch(name) case "m": return m; case "ibex": return env; default: return null; //#end return null; } } public void accept(Message m) throws IOException, MailException { try { new Script(filePath).reallyAccept(m); } catch (JSExn e) { Log.error(this, e); throw new MailException(e.toString()); } } private synchronized void reallyAccept(Message m) throws IOException, MailException, JSExn { this.m = m; try { Object ret = js.call(null, new JS[] { m }); Log.warn(this, "configuration script returned " + ret); if (ret == null) throw new IOException("configuration script returned null"); while (ret instanceof JSReflection.Wrapper) ret = ((JSReflection.Wrapper)ret).unwrap(); if (ret instanceof Target) ((Target)ret).accept(m); //else if (ret instanceof Filter) ((Filter)ret).process(m); else throw new IOException("configuration script returned a " + ret.getClass().getName()); } catch (JSExn e) { Log.warn(this, e); throw new IOException("configuration script threw an exception"); } } // FIXME: this should extend org.ibex.core.Ibex public class ScriptEnv extends JS.Obj { private PropertyFile prefs = null; /* static { try { // FIXME prefs = new PropertyFile(new File("/etc/org.ibex.mail.properties")); } catch (IOException e) { Log.error(ScriptEnv.class, e); } } */ /** lets us put multi-level get/put/call keys all in the same method */ private class Sub extends JS.Immutable { String key; Sub(String key) { this.key = key; } public void put(JS key, JS val) throws JSExn { ScriptEnv.this.put(JSU.S(this.key + "." + JSU.toString(key)), val); } public JS get(JS key) throws JSExn { return ScriptEnv.this.get(JSU.S(this.key + "." + JSU.toString(key))); } public JS call(JS method, JS[] args) throws JSExn { return ScriptEnv.this.call(JSU.S(this.key + "." + JSU.toString(method)), args); } } private Sub getSub(String s) { return new Sub(s); } public JS get(JS name) throws JSExn { //#jsswitch(name) case "math": return ibexMath; case "string": return ibexString; case "date": return METHOD; case "regexp": return METHOD; case "log": return getSub("log"); case "log.debug": return METHOD; case "log.info": return METHOD; case "log.warn": return METHOD; case "log.error": return METHOD; case "list": return getSub("list"); case "url": return getSub("url"); case "url.encode": return METHOD; case "mail": return getSub("mail"); case "mail.forward": return METHOD; case "mail.forward2": return METHOD; case "mail.send": return METHOD; case "mail.attempt": return METHOD; case "mail.later": return Later.instance; case "mail.drop": return METHOD; case "mail.razor": return getSub("mail.razor"); case "mail.razor.check": return METHOD; case "mail.clamav": return getSub("mail.clamav"); case "mail.clamav.check": return METHOD; case "mail.procmail": /* FEATURE */ return null; case "mail.vacation": /* FEATURE */ return null; case "mail.verp": return getSub("mail.verp"); case "mail.verp.check": return METHOD; case "mail.dcc": return getSub("mail.dcc"); case "mail.dcc.check": return METHOD; case "mail.bounce": return METHOD; case "mail.reject": return METHOD; case "mail.my": return getSub("mail.my"); case "mail.dir": return METHOD; case "mail.shell": return METHOD; case "mail.my.prefs": try { return new org.ibex.js.Directory(new File("/etc/org.ibex.mail.prefs")); } catch (IOException e) { throw new JSExn(e.toString()); } case "mail.whitelist": return JSReflection.wrap(org.ibex.mail.SMTP.whitelist); case "mail.my.mailbox": MailTree root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, true); return (JS)root.slash("user", true).slash("megacz", true); case "mail.list": return METHOD; //#end return super.get(name); } public JS call(JS name0, JS[] args) throws JSExn { final JS a = args.length >= 1 ? args[0] : null; final JS b = args.length >= 2 ? args[1] : null; final JS c = args.length >= 3 ? args[2] : null; final int nargs = args.length; String name = JSU.toString(name0); try { if (name.equals("url.encode")) return JSU.S(java.net.URLEncoder.encode(JSU.toString(args[0]))); if (name.equals("mail.list")) return JSReflection.wrap(FileBasedMailbox.getFileBasedMailbox(JSU.toString(args[0]), false)); if (name.equals("mail.dir")) { return new org.ibex.js.Directory(new File(JSU.toString(args[0]))); } if (name.equals("mail.shell")) { // FIXME: EEEEEVIL! Log.warn("dbug", a.getClass().getName()); Log.warn("dbug", b.getClass().getName()); Message m = (Message)b; final Process p = Runtime.getRuntime().exec(JSU.toString(a)); Main.threadPool.start(new Runnable() { public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream())); String s = null; while((s = br.readLine())!=null) Log.warn("shell", s); } catch (Exception e) { e.printStackTrace(); } } }); OutputStream os = p.getOutputStream(); Stream stream = new Stream(os); // why do I need to go via an sb here? StringBuffer sb = new StringBuffer(); m.getBody().getStream().transcribe(sb); stream.println(sb.toString()); stream.flush(); stream.close(); p.waitFor(); return null; } if (name.equals("date")) { return new JSDate(args); } if (name.equals("mail.send") || name.equals("send") || name.equals("mail.attempt") || name.equals("attempt")) { boolean attempt = name.equals("mail.attempt") || name.equals("attempt"); JS m = (JS)a; String body = ""; Address from = null, to = null, envelopeFrom = null, envelopeTo = null; JS.Enumeration e = m.keys(); Headers headers = new Headers(); for(; e.hasNext();) { JS key = (JS)e.next(); JS val = m.get(key) == null ? null : m.get(key); if ("body".equalsIgnoreCase(JSU.toString(key))) body = JSU.toString(val); else headers = new Headers(headers, new String[] { JSU.toString(key), JSU.toString(val) }); if ("from".equalsIgnoreCase(JSU.toString(key))) from = Address.parse(JSU.toString(val)); if ("to".equalsIgnoreCase(JSU.toString(key))) to = Address.parse(JSU.toString(val)); if ("envelopeFrom".equalsIgnoreCase(JSU.toString(key))) envelopeFrom = Address.parse(JSU.toString(val)); if ("envelopeTo".equalsIgnoreCase(JSU.toString(key))) envelopeTo = Address.parse(JSU.toString(val)); } if (envelopeTo == null) envelopeTo = to; if (envelopeFrom == null) envelopeFrom = from; Message message = Message.newMessageFromHeadersAndBody(headers, Fountain.Util.create(body), envelopeFrom, envelopeTo); boolean ok = false; try { if (attempt) { org.ibex.mail.SMTP.Outgoing.attempt(message); } else { org.ibex.mail.SMTP.Outgoing.enqueue(message); } ok = true; } catch (Exception ex) { if (!attempt) Log.warn(this, ex); } if (!ok && !attempt) throw new JSExn("SMTP server rejected message"); return JSU.B(ok); } if (name.equals("mail.razor.check")) { Process p = Runtime.getRuntime().exec("razor-check"); ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true); return JSU.N(p.waitFor()); } if (name.equals("mail.clamav.check")) { // FIXME: this is returning "is-virus-laden" when clamdscan is unhappy -- BAD! // should use error code: 0=clean, 1=virus, 2=malfunction Process p = Runtime.getRuntime().exec("clamdscan - --stdout --quiet"); ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true); int result = p.waitFor(); if (result==0) return JSU.N(0); StringBuffer ret = new StringBuffer(); new Stream(p.getInputStream()).transcribe(ret); return JSU.S(ret.toString()); } if (name.equals("mail.verp.check")) { String ret = VERP.verpVerify(Address.parse(JSU.toString(a)), "SECRET".getBytes(), 0); return ret==null ? null : JSU.S(ret); } if (name.equals("mail.dcc.check")) { Process p = Runtime.getRuntime().exec(new String[] { "dccproc", "-H" }); ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true); StringBuffer ret = new StringBuffer(); new Stream(p.getInputStream()).transcribe(ret); p.waitFor(); String result = ret.toString(); Log.warn("dcc", ((Message)args[0]).summary() + ":\n " + result); int body = 0; int fuz1 = 0; int fuz2 = 0; int i_body = result.indexOf("Body="); int i_fuz1 = result.indexOf("Fuz1="); int i_fuz2 = result.indexOf("Fuz2="); if (i_body != -1) try { String s = result.substring(i_body+5); if (s.indexOf(' ') != -1) s = s.substring(0, s.indexOf(' ')); if (s.indexOf('\n') != -1) s = s.substring(0, s.indexOf('\n')); body = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim()); } catch (Exception e) { Log.error("", e); } if (i_fuz1 != -1) try { String s = result.substring(i_fuz1+5); if (s.indexOf(' ') != -1) s = s.substring(0, s.indexOf(' ')); if (s.indexOf('\n') != -1) s = s.substring(0, s.indexOf('\n')); fuz1 = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim()); } catch (Exception e) { Log.error("", e); } if (i_fuz2 != -1) try { String s = result.substring(i_fuz2+5); if (s.indexOf(' ') != -1) s = s.substring(0, s.indexOf(' ')); if (s.indexOf('\n') != -1) s = s.substring(0, s.indexOf('\n')); fuz2 = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim()); } catch (Exception e) { Log.error("", e); } JSArray jsa = new JSArray(); jsa.put(JSU.N(0), JSU.N(body)); jsa.put(JSU.N(1), JSU.N(fuz1)); jsa.put(JSU.N(2), JSU.N(fuz2)); return jsa; } if (name.equals("mail.drop")) { return args.length==0 ? new Drop() : new Drop(JSU.toString(args[0])); } if (name.equals("mail.bounce")) { return new JSTarget() { public void accept(Message m) throws MailException { try { Message m2 = m.bounce(JSU.toString(a)); org.ibex.mail.SMTP.Outgoing.enqueue(m2); Log.error(this, "BOUNCING! " + m2.summary()); } catch (Exception e) { Log.warn(this, e); } } }; } if (name.equals("mail.forward2") || name.equals("forward2")) { try { Message m2 = m.withEnvelope(m.envelopeFrom, new Address(JSU.toString(a))); org.ibex.mail.SMTP.Outgoing.enqueue(m2); } catch (Exception e) { Log.warn(this, e); throw new JSExn(e.toString()); } return null; } if (name.equals("mail.forward") || name.equals("forward")) { Message m2 = Script.this.m.withEnvelope(Script.this.m.envelopeFrom, new Address(JSU.toString(a))); org.ibex.mail.SMTP.Outgoing.attempt(m2, false); return Drop.instance; } if (name.equals("mail.reject")) return new Reject(JSU.toString(a)); if (name.equals("log.debug") || name.equals("debug")) { JSU.debug(a== null ? "**null**" : JSU.toString(a)); return null; } if (name.equals("log.info") || name.equals("info")) { JSU.info(a== null ? "**null**" : JSU.toString(a)); return null; } if (name.equals("log.warn") || name.equals("warn")) { JSU.warn(a== null ? "**null**" : JSU.toString(a)); return null; } if (name.equals("log.error") || name.equals("error")) { JSU.error(a== null ? "**null**" : JSU.toString(a)); return null; } switch (nargs) { case 1: if (name.equals("regexp")) {return new JSRegexp(a, null); } break; case 2: if (name.equals("regexp")) {return new JSRegexp(a, b); } } } catch (MailException e) { throw e; } catch (Exception e) { Log.warn(this, "ibex."+name+"() threw: " + e); Log.warn(this, e); if (e instanceof JSExn) throw ((JSExn)e); throw new JSExn("invalid argument for ibex object method "+JSU.toString(name0)+"()"); } throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+JSU.toString(name0)+"()"); } public final JSMath ibexMath = new JSMath() { public JS get(JS name) throws JSExn { // FIXME!!! /* case "isNaN": return gs.get(name); case "isFinite": return gs.get(name); case "NaN": return gs.get(name); case "Infinity": return gs.get(name); */ return null; } }; public final JS ibexString = new JS.Immutable() { public JS get(JS name) throws JSExn { // FIXME!!! /* case "parseInt": return gs.get(JSU.S("parseInt")); case "parseFloat": return gs.get(JSU.S("parseFloat")); case "decodeURI": return gs.get(JSU.S("decodeURI")); case "decodeURIComponent": return gs.get(JSU.S("decodeURIComponent")); case "encodeURI": return gs.get(JSU.S("encodeURI")); case "encodeURIComponent": return gs.get(JSU.S("encodeURIComponent")); case "escape": return gs.get(JSU.S("escape")); case "unescape": return gs.get(JSU.S("unescape")); case "fromCharCode": return gs.get(JSU.S("stringFromCharCode")); */ return null; } }; } private static abstract class JSTarget extends JS.Obj implements Target { } public static class Drop extends JS.Obj implements Target { public static final Drop instance = new Drop(); public final String reason; public Drop() { this(null); } public Drop(String reason) { this.reason = reason; } public void accept(Message m) throws IOException, MailException { Log.warn(this, "dropping" +(reason==null?"":(" because "+reason))+ ": " + m.summary()); } } public static class Later extends JS.Obj implements Target { public static final Later instance = new Later(); public static class LaterException extends RuntimeException { } public void accept(Message m) throws IOException, MailException { Log.warn(this, "delaying message " + m.summary()); throw new LaterException(); } } /** a fast-write, slow-read place to stash all messages we touch -- in case of a major f*ckup */ public static class Transcript implements Target { public static final Transcript transcript = new Transcript(Mailbox.STORAGE_ROOT + File.separatorChar + "transcript"); private String path; public Transcript(String path) { new File(this.path = path).mkdirs(); } private static String lastTime = null; private static int lastCounter = 0; public synchronized void accept(Message message) { try { File today = new File(path + File.separatorChar + (new SimpleDateFormat("yy-MMM-dd").format(new Date()))); today.mkdirs(); String time = new SimpleDateFormat("HH:mm:ss").format(new Date()); synchronized (Transcript.class) { if (lastTime != null && lastTime.equals(time)) { time += "." + (++lastCounter); } else { lastTime = time; lastCounter = 0; } } File target = new File(today.getPath() + File.separatorChar + time + ".txt"); OutputStream os = new FileOutputStream(target); try { message.getStream().transcribe(new Stream(os)); os.flush(); } finally { os.close(); } } catch (IOException e) { throw new MailException.IOException(e); } } } public static class Reject extends JS.Obj implements Target { public final String reason; public Reject(String reason) { this.reason = reason; } public void accept(Message m) throws IOException, MailException { throw new RejectException(m, reason); } public static class RejectException extends RuntimeException { public final Message m; public final String reason; public RejectException(Message m, String reason) { this.m = m; this.reason = reason; } } } }