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 public class Script extends JS.Obj implements Target {
18 private static final JS.Method METHOD = new JS.Method();
20 private static Script root = null;
21 private static final String DEFAULT_CONF = Mailbox.STORAGE_ROOT + "conf" + File.separatorChar + "inbound.js";
22 public static Script root() {
24 if (root == null) root = new Script(System.getProperty("ibex.mail.conf", DEFAULT_CONF));
26 } catch (Exception e) {
27 Log.error(Script.class, e);
33 private Message m = null;
34 private String filePath = null;
35 public Script(String filePath) throws JSExn, IOException {
36 this.filePath = filePath;
37 js = JSU.cloneWithNewGlobalScope(JSU.fromReader(filePath, 1, new InputStreamReader(new FileInputStream(filePath))),
40 private class ScriptScope extends JS.Immutable {
41 ScriptEnv env = new ScriptEnv();
42 public JS get(JS name) throws JSExn {
45 case "ibex": return env;
52 public void accept(Message m) throws IOException, MailException {
54 new Script(filePath).reallyAccept(m);
57 throw new MailException(e.toString());
61 private synchronized void reallyAccept(Message m) throws IOException, MailException, JSExn {
64 Object ret = js.call(null, new JS[] { m });
65 Log.debug(this, "configuration script returned " + ret);
66 if (ret == null) throw new IOException("configuration script returned null");
67 while (ret instanceof JSReflection.Wrapper) ret = ((JSReflection.Wrapper)ret).unwrap();
68 if (ret instanceof Target) ((Target)ret).accept(m);
69 //else if (ret instanceof Filter) ((Filter)ret).process(m);
70 else throw new IOException("configuration script returned a " + ret.getClass().getName());
73 throw new IOException("configuration script threw an exception");
77 // FIXME: this should extend org.ibex.core.Ibex
78 public class ScriptEnv extends JS.Obj {
80 private PropertyFile prefs = null;
85 prefs = new PropertyFile(new File("/etc/org.ibex.mail.properties"));
86 } catch (IOException e) {
87 Log.error(ScriptEnv.class, e);
92 /** lets us put multi-level get/put/call keys all in the same method */
93 private class Sub extends JS.Immutable {
95 Sub(String key) { this.key = key; }
96 public void put(JS key, JS val) throws JSExn {
97 ScriptEnv.this.put(JSU.S(this.key + "." + JSU.toString(key)), val); }
98 public JS get(JS key) throws JSExn { return ScriptEnv.this.get(JSU.S(this.key + "." + JSU.toString(key))); }
99 public JS call(JS method, JS[] args) throws JSExn {
100 return ScriptEnv.this.call(JSU.S(this.key + "." + JSU.toString(method)), args);
103 private Sub getSub(String s) { return new Sub(s); }
105 public JS get(JS name) throws JSExn {
107 case "math": return ibexMath;
108 case "string": return ibexString;
109 case "date": return METHOD;
110 case "regexp": return METHOD;
111 case "log": return getSub("log");
112 case "log.debug": return METHOD;
113 case "log.info": return METHOD;
114 case "log.warn": return METHOD;
115 case "log.error": return METHOD;
116 case "list": return getSub("list");
117 case "url": return getSub("url");
118 case "url.encode": return METHOD;
119 case "mail": return getSub("mail");
120 case "mail.forward": return METHOD;
121 case "mail.forward2": return METHOD;
122 case "mail.send": return METHOD;
123 case "mail.attempt": return METHOD;
124 case "mail.later": return Later.instance;
125 case "mail.drop": return METHOD;
126 case "mail.razor": return getSub("mail.razor");
127 case "mail.razor.check": return METHOD;
128 case "mail.dcc": return getSub("mail.dcc");
129 case "mail.dcc.check": return METHOD;
130 case "mail.bounce": return METHOD;
131 case "mail.reject": return METHOD;
132 case "mail.my": return getSub("mail.my");
133 case "mail.dir": return METHOD;
134 case "mail.shell": return METHOD;
135 case "mail.my.prefs": try {
136 return new org.ibex.js.Directory(new File("/etc/org.ibex.mail.prefs"));
137 } catch (IOException e) { throw new JSExn(e.toString()); }
138 case "mail.whitelist": return JSReflection.wrap(org.ibex.mail.SMTP.whitelist);
139 case "mail.my.mailbox":
140 Mailbox root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, true);
141 return root.slash("user", true).slash("megacz", true);
142 case "mail.list": return METHOD;
144 return super.get(name);
147 public JS call(JS name0, JS[] args) throws JSExn {
148 final JS a = args.length >= 1 ? args[0] : null;
149 final JS b = args.length >= 2 ? args[1] : null;
150 final JS c = args.length >= 3 ? args[2] : null;
151 final int nargs = args.length;
152 String name = JSU.toString(name0);
154 if (name.equals("url.encode")) return JSU.S(java.net.URLEncoder.encode(JSU.toString(args[0])));
155 if (name.equals("mail.list")) return JSReflection.wrap(FileBasedMailbox.getFileBasedMailbox(JSU.toString(args[0]), false));
156 if (name.equals("mail.dir")) {
157 return new org.ibex.js.Directory(new File(JSU.toString(args[0])));
159 if (name.equals("mail.shell")) {
161 Log.warn("dbug", args[0].getClass().getName());
162 Log.warn("dbug", args[1].getClass().getName());
163 final Process p = Runtime.getRuntime().exec(JSU.toString(args[1]));
164 Message m = (Message)args[0];
168 BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
170 while((s = br.readLine())!=null)
171 Log.warn("shell", s);
172 } catch (Exception e) { e.printStackTrace(); }
175 OutputStream os = p.getOutputStream();
176 Stream stream = new Stream(os);
177 m.getStream().transcribe(stream);
182 if (name.equals("date")) { return new JSDate(args); }
183 if (name.equals("mail.send") || name.equals("send") || name.equals("mail.attempt") || name.equals("attempt")) {
184 boolean attempt = name.equals("mail.attempt") || name.equals("attempt");
186 StringBuffer headers = new StringBuffer();
188 Address from = null, to = null, envelopeFrom = null, envelopeTo = null;
189 JS.Enumeration e = m.keys();
190 for(; e.hasNext();) {
191 JS key = (JS)e.next();
192 JS val = m.get(key) == null ? null : m.get(key);
193 if ("body".equalsIgnoreCase(JSU.toString(key))) body = JSU.toString(val);
194 else headers.append(JSU.toString(key) + ": " + JSU.toString(val) + "\r\n");
195 if ("from".equalsIgnoreCase(JSU.toString(key))) from = Address.parse(JSU.toString(val));
196 if ("to".equalsIgnoreCase(JSU.toString(key))) to = Address.parse(JSU.toString(val));
197 if ("envelopeFrom".equalsIgnoreCase(JSU.toString(key))) envelopeFrom = Address.parse(JSU.toString(val));
198 if ("envelopeTo".equalsIgnoreCase(JSU.toString(key))) envelopeTo = Address.parse(JSU.toString(val));
200 if (envelopeTo == null) envelopeTo = to;
201 if (envelopeFrom == null) envelopeFrom = from;
203 Message.newMessage(Fountain.Util.concat(Fountain.Util.create(headers.toString()),
204 Fountain.Util.create("\r\n"),
205 Fountain.Util.create(body)),
213 org.ibex.mail.SMTP.Outgoing.attempt(message);
215 org.ibex.mail.SMTP.Outgoing.enqueue(message);
218 } catch (Exception ex) {
219 if (!attempt) Log.warn(this, ex);
221 if (!ok && !attempt) throw new JSExn("SMTP server rejected message");
224 if (name.equals("mail.razor.check")) {
225 Process p = Runtime.getRuntime().exec("razor-check");
226 ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
227 return JSU.N(p.waitFor());
229 if (name.equals("mail.dcc.check")) {
230 Process p = Runtime.getRuntime().exec(new String[] { "dccproc", "-H" });
231 ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
232 StringBuffer ret = new StringBuffer();
233 new Stream(p.getInputStream()).transcribe(ret);
235 return JSU.S(ret.toString());
237 if (name.equals("mail.drop")) {
238 return args.length==0 ? new Drop() : new Drop(JSU.toString(args[0]));
240 if (name.equals("mail.bounce")) {
241 return new JSTarget() {
242 public void accept(Message m) throws MailException {
244 Message m2 = m.bounce(JSU.toString(a));
245 org.ibex.mail.SMTP.Outgoing.enqueue(m2);
246 Log.error(this, "BOUNCING! " + m2.summary());
247 } catch (Exception e) {
252 if (name.equals("mail.forward2") || name.equals("forward2")) {
254 Message m2 = Message.newMessage(m,
256 new Address(JSU.toString(a)));
257 org.ibex.mail.SMTP.Outgoing.enqueue(m2);
258 } catch (Exception e) {
260 throw new JSExn(e.toString());
264 if (name.equals("mail.forward") || name.equals("forward")) {
265 Message m2 = Message.newMessage(Script.this.m, Script.this.m.envelopeFrom, new Address(JSU.toString(a)));
266 org.ibex.mail.SMTP.Outgoing.attempt(m2, false);
267 return Drop.instance;
269 if (name.equals("mail.reject"))
270 return new Reject(JSU.toString(a));
271 if (name.equals("log.debug") || name.equals("debug")) { JSU.debug(a== null ? "**null**" : JSU.toString(a)); return null; }
272 if (name.equals("log.info") || name.equals("info")) { JSU.info(a== null ? "**null**" : JSU.toString(a)); return null; }
273 if (name.equals("log.warn") || name.equals("warn")) { JSU.warn(a== null ? "**null**" : JSU.toString(a)); return null; }
274 if (name.equals("log.error") || name.equals("error")) { JSU.error(a== null ? "**null**" : JSU.toString(a)); return null; }
277 if (name.equals("regexp")) {return new JSRegexp(a, null); }
280 if (name.equals("regexp")) {return new JSRegexp(a, b); }
282 } catch (MailException e) { throw e;
283 } catch (Exception e) {
284 Log.warn(this, "ibex."+name+"() threw: " + e);
286 if (e instanceof JSExn) throw ((JSExn)e);
287 throw new JSExn("invalid argument for ibex object method "+JSU.toString(name0)+"()");
289 throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+JSU.toString(name0)+"()");
292 public final JSMath ibexMath = new JSMath() {
293 public JS get(JS name) throws JSExn {
296 case "isNaN": return gs.get(name);
297 case "isFinite": return gs.get(name);
298 case "NaN": return gs.get(name);
299 case "Infinity": return gs.get(name);
305 public final JS ibexString = new JS.Immutable() {
306 public JS get(JS name) throws JSExn {
309 case "parseInt": return gs.get(JSU.S("parseInt"));
310 case "parseFloat": return gs.get(JSU.S("parseFloat"));
311 case "decodeURI": return gs.get(JSU.S("decodeURI"));
312 case "decodeURIComponent": return gs.get(JSU.S("decodeURIComponent"));
313 case "encodeURI": return gs.get(JSU.S("encodeURI"));
314 case "encodeURIComponent": return gs.get(JSU.S("encodeURIComponent"));
315 case "escape": return gs.get(JSU.S("escape"));
316 case "unescape": return gs.get(JSU.S("unescape"));
317 case "fromCharCode": return gs.get(JSU.S("stringFromCharCode"));
324 private static abstract class JSTarget extends JS.Obj implements Target { }
326 public static class Drop extends JS.Obj implements Target {
327 public static final Drop instance = new Drop();
328 public final String reason;
329 public Drop() { this(null); }
330 public Drop(String reason) { this.reason = reason; }
331 public void accept(Message m) throws IOException, MailException {
332 Log.warn(this, "dropping" +(reason==null?"":(" because "+reason))+ ": " + m.summary());
336 public static class Later extends JS.Obj implements Target {
337 public static final Later instance = new Later();
338 public static class LaterException extends RuntimeException { }
339 public void accept(Message m) throws IOException, MailException {
340 Log.warn(this, "delaying message " + m.summary());
341 throw new LaterException();
345 /** a fast-write, slow-read place to stash all messages we touch -- in case of a major f*ckup */
346 public static class Transcript implements Target {
348 public static final Transcript transcript = new Transcript(Mailbox.STORAGE_ROOT + File.separatorChar + "transcript");
351 public Transcript(String path) { new File(this.path = path).mkdirs(); }
352 private static String lastTime = null;
353 private static int lastCounter = 0;
355 public synchronized void accept(Message message) {
357 File today = new File(path + File.separatorChar + (new SimpleDateFormat("yy-MMM-dd").format(new Date())));
360 String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
361 synchronized (Transcript.class) {
362 if (lastTime != null && lastTime.equals(time)) {
363 time += "." + (++lastCounter);
370 File target = new File(today.getPath() + File.separatorChar + time + ".txt");
371 OutputStream os = new FileOutputStream(target);
373 message.getStream().transcribe(new Stream(os));
375 } finally { os.close(); }
376 } catch (IOException e) { throw new MailException.IOException(e); }
380 public static class Reject extends JS.Obj implements Target {
381 public final String reason;
382 public Reject(String reason) { this.reason = reason; }
383 public void accept(Message m) throws IOException, MailException {
384 throw new RejectException(m, reason);
386 public static class RejectException extends RuntimeException {
387 public final Message m;
388 public final String reason;
389 public RejectException(Message m, String reason) { this.m = m; this.reason = reason; }