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.dcc": return getSub("mail.dcc");
143 case "mail.dcc.check": return METHOD;
144 case "mail.bounce": return METHOD;
145 case "mail.reject": return METHOD;
146 case "mail.my": return getSub("mail.my");
147 case "mail.dir": return METHOD;
148 case "mail.shell": return METHOD;
149 case "mail.my.prefs": try {
150 return new org.ibex.js.Directory(new File("/etc/org.ibex.mail.prefs"));
151 } catch (IOException e) { throw new JSExn(e.toString()); }
152 case "mail.whitelist": return JSReflection.wrap(org.ibex.mail.SMTP.whitelist);
153 case "mail.my.mailbox":
154 MailTree root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, true);
155 return (JS)root.slash("user", true).slash("megacz", true);
156 case "mail.list": return METHOD;
158 return super.get(name);
161 public JS call(JS name0, JS[] args) throws JSExn {
162 final JS a = args.length >= 1 ? args[0] : null;
163 final JS b = args.length >= 2 ? args[1] : null;
164 final JS c = args.length >= 3 ? args[2] : null;
165 final int nargs = args.length;
166 String name = JSU.toString(name0);
168 if (name.equals("url.encode")) return JSU.S(java.net.URLEncoder.encode(JSU.toString(args[0])));
169 if (name.equals("mail.list")) return JSReflection.wrap(FileBasedMailbox.getFileBasedMailbox(JSU.toString(args[0]), false));
170 if (name.equals("mail.dir")) {
171 return new org.ibex.js.Directory(new File(JSU.toString(args[0])));
173 if (name.equals("mail.shell")) {
175 Log.warn("dbug", a.getClass().getName());
176 Log.warn("dbug", b.getClass().getName());
177 Message m = (Message)b;
178 final Process p = Runtime.getRuntime().exec(JSU.toString(a));
179 Main.threadPool.start(new Runnable() {
182 BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
184 while((s = br.readLine())!=null)
185 Log.warn("shell", s);
186 } catch (Exception e) { e.printStackTrace(); }
189 OutputStream os = p.getOutputStream();
190 Stream stream = new Stream(os);
192 // why do I need to go via an sb here?
193 StringBuffer sb = new StringBuffer();
194 m.getBody().getStream().transcribe(sb);
195 stream.println(sb.toString());
202 if (name.equals("date")) { return new JSDate(args); }
203 if (name.equals("mail.send") || name.equals("send") || name.equals("mail.attempt") || name.equals("attempt")) {
204 boolean attempt = name.equals("mail.attempt") || name.equals("attempt");
207 Address from = null, to = null, envelopeFrom = null, envelopeTo = null;
208 JS.Enumeration e = m.keys();
209 Headers headers = new Headers();
210 for(; e.hasNext();) {
211 JS key = (JS)e.next();
212 JS val = m.get(key) == null ? null : m.get(key);
213 if ("body".equalsIgnoreCase(JSU.toString(key))) body = JSU.toString(val);
214 else headers = new Headers(headers, new String[] { JSU.toString(key), JSU.toString(val) });
215 if ("from".equalsIgnoreCase(JSU.toString(key))) from = Address.parse(JSU.toString(val));
216 if ("to".equalsIgnoreCase(JSU.toString(key))) to = Address.parse(JSU.toString(val));
217 if ("envelopeFrom".equalsIgnoreCase(JSU.toString(key))) envelopeFrom = Address.parse(JSU.toString(val));
218 if ("envelopeTo".equalsIgnoreCase(JSU.toString(key))) envelopeTo = Address.parse(JSU.toString(val));
220 if (envelopeTo == null) envelopeTo = to;
221 if (envelopeFrom == null) envelopeFrom = from;
223 Message.newMessageFromHeadersAndBody(headers, Fountain.Util.create(body), envelopeFrom, envelopeTo);
228 org.ibex.mail.SMTP.Outgoing.attempt(message);
230 org.ibex.mail.SMTP.Outgoing.enqueue(message);
233 } catch (Exception ex) {
234 if (!attempt) Log.warn(this, ex);
236 if (!ok && !attempt) throw new JSExn("SMTP server rejected message");
239 if (name.equals("mail.razor.check")) {
240 Process p = Runtime.getRuntime().exec("razor-check");
241 ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
242 return JSU.N(p.waitFor());
244 if (name.equals("mail.clamav.check")) {
245 // FIXME: this is returning "is-virus-laden" when clamdscan is unhappy -- BAD!
246 // should use error code: 0=clean, 1=virus, 2=malfunction
247 Process p = Runtime.getRuntime().exec("clamdscan - --stdout --quiet");
248 ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
249 int result = p.waitFor();
250 if (result==0) return JSU.N(0);
251 StringBuffer ret = new StringBuffer();
252 new Stream(p.getInputStream()).transcribe(ret);
253 return JSU.S(ret.toString());
255 if (name.equals("mail.dcc.check")) {
256 Process p = Runtime.getRuntime().exec(new String[] { "dccproc", "-H" });
257 ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
258 StringBuffer ret = new StringBuffer();
259 new Stream(p.getInputStream()).transcribe(ret);
261 String result = ret.toString();
262 Log.warn("dcc", ((Message)args[0]).summary() + ":\n " + result);
266 int i_body = result.indexOf("Body=");
267 int i_fuz1 = result.indexOf("Fuz1=");
268 int i_fuz2 = result.indexOf("Fuz2=");
269 if (i_body != -1) try {
270 String s = result.substring(i_body+5);
271 if (s.indexOf(' ') != -1) s = s.substring(0, s.indexOf(' '));
272 if (s.indexOf('\n') != -1) s = s.substring(0, s.indexOf('\n'));
273 body = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim());
274 } catch (Exception e) { Log.error("", e); }
275 if (i_fuz1 != -1) try {
276 String s = result.substring(i_fuz1+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 fuz1 = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim());
280 } catch (Exception e) { Log.error("", e); }
281 if (i_fuz2 != -1) try {
282 String s = result.substring(i_fuz2+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 fuz2 = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim());
286 } catch (Exception e) { Log.error("", e); }
287 JSArray jsa = new JSArray();
288 jsa.put(JSU.N(0), JSU.N(body));
289 jsa.put(JSU.N(1), JSU.N(fuz1));
290 jsa.put(JSU.N(2), JSU.N(fuz2));
293 if (name.equals("mail.drop")) {
294 return args.length==0 ? new Drop() : new Drop(JSU.toString(args[0]));
296 if (name.equals("mail.bounce")) {
297 return new JSTarget() {
298 public void accept(Message m) throws MailException {
300 Message m2 = m.bounce(JSU.toString(a));
301 org.ibex.mail.SMTP.Outgoing.enqueue(m2);
302 Log.error(this, "BOUNCING! " + m2.summary());
303 } catch (Exception e) {
308 if (name.equals("mail.forward2") || name.equals("forward2")) {
310 Message m2 = m.withEnvelope(m.envelopeFrom, new Address(JSU.toString(a)));
311 org.ibex.mail.SMTP.Outgoing.enqueue(m2);
312 } catch (Exception e) {
314 throw new JSExn(e.toString());
318 if (name.equals("mail.forward") || name.equals("forward")) {
319 Message m2 = Script.this.m.withEnvelope(Script.this.m.envelopeFrom, new Address(JSU.toString(a)));
320 org.ibex.mail.SMTP.Outgoing.attempt(m2, false);
321 return Drop.instance;
323 if (name.equals("mail.reject"))
324 return new Reject(JSU.toString(a));
325 if (name.equals("log.debug") || name.equals("debug")) { JSU.debug(a== null ? "**null**" : JSU.toString(a)); return null; }
326 if (name.equals("log.info") || name.equals("info")) { JSU.info(a== null ? "**null**" : JSU.toString(a)); return null; }
327 if (name.equals("log.warn") || name.equals("warn")) { JSU.warn(a== null ? "**null**" : JSU.toString(a)); return null; }
328 if (name.equals("log.error") || name.equals("error")) { JSU.error(a== null ? "**null**" : JSU.toString(a)); return null; }
331 if (name.equals("regexp")) {return new JSRegexp(a, null); }
334 if (name.equals("regexp")) {return new JSRegexp(a, b); }
336 } catch (MailException e) { throw e;
337 } catch (Exception e) {
338 Log.warn(this, "ibex."+name+"() threw: " + e);
340 if (e instanceof JSExn) throw ((JSExn)e);
341 throw new JSExn("invalid argument for ibex object method "+JSU.toString(name0)+"()");
343 throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+JSU.toString(name0)+"()");
346 public final JSMath ibexMath = new JSMath() {
347 public JS get(JS name) throws JSExn {
350 case "isNaN": return gs.get(name);
351 case "isFinite": return gs.get(name);
352 case "NaN": return gs.get(name);
353 case "Infinity": return gs.get(name);
359 public final JS ibexString = new JS.Immutable() {
360 public JS get(JS name) throws JSExn {
363 case "parseInt": return gs.get(JSU.S("parseInt"));
364 case "parseFloat": return gs.get(JSU.S("parseFloat"));
365 case "decodeURI": return gs.get(JSU.S("decodeURI"));
366 case "decodeURIComponent": return gs.get(JSU.S("decodeURIComponent"));
367 case "encodeURI": return gs.get(JSU.S("encodeURI"));
368 case "encodeURIComponent": return gs.get(JSU.S("encodeURIComponent"));
369 case "escape": return gs.get(JSU.S("escape"));
370 case "unescape": return gs.get(JSU.S("unescape"));
371 case "fromCharCode": return gs.get(JSU.S("stringFromCharCode"));
378 private static abstract class JSTarget extends JS.Obj implements Target { }
380 public static class Drop extends JS.Obj implements Target {
381 public static final Drop instance = new Drop();
382 public final String reason;
383 public Drop() { this(null); }
384 public Drop(String reason) { this.reason = reason; }
385 public void accept(Message m) throws IOException, MailException {
386 Log.warn(this, "dropping" +(reason==null?"":(" because "+reason))+ ": " + m.summary());
390 public static class Later extends JS.Obj implements Target {
391 public static final Later instance = new Later();
392 public static class LaterException extends RuntimeException { }
393 public void accept(Message m) throws IOException, MailException {
394 Log.warn(this, "delaying message " + m.summary());
395 throw new LaterException();
399 /** a fast-write, slow-read place to stash all messages we touch -- in case of a major f*ckup */
400 public static class Transcript implements Target {
402 public static final Transcript transcript = new Transcript(Mailbox.STORAGE_ROOT + File.separatorChar + "transcript");
405 public Transcript(String path) { new File(this.path = path).mkdirs(); }
406 private static String lastTime = null;
407 private static int lastCounter = 0;
409 public synchronized void accept(Message message) {
411 File today = new File(path + File.separatorChar + (new SimpleDateFormat("yy-MMM-dd").format(new Date())));
414 String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
415 synchronized (Transcript.class) {
416 if (lastTime != null && lastTime.equals(time)) {
417 time += "." + (++lastCounter);
424 File target = new File(today.getPath() + File.separatorChar + time + ".txt");
425 OutputStream os = new FileOutputStream(target);
427 message.getStream().transcribe(new Stream(os));
429 } finally { os.close(); }
430 } catch (IOException e) { throw new MailException.IOException(e); }
434 public static class Reject extends JS.Obj implements Target {
435 public final String reason;
436 public Reject(String reason) { this.reason = reason; }
437 public void accept(Message m) throws IOException, MailException {
438 throw new RejectException(m, reason);
440 public static class RejectException extends RuntimeException {
441 public final Message m;
442 public final String reason;
443 public RejectException(Message m, String reason) { this.m = m; this.reason = reason; }