rename MailboxTree -> MailTree
[org.ibex.mail.git] / src / org / ibex / mail / Script.java
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.
4
5 package org.ibex.mail;
6 import org.ibex.js.*;
7 import org.ibex.io.*;
8 import org.ibex.io.Fountain;
9 import org.ibex.util.*;
10 import org.ibex.mail.filter.*;
11 import org.ibex.mail.target.*;
12 import java.io.*;
13 import java.util.*;
14 import java.text.*;
15
16 //
17 //  - better matching syntax:
18 //  - src-ip
19 //  - from *@foo.com
20 //  - list-id
21 //      - ==> {discard, refuse, bounce}
22 //
23
24 public class Script extends JS.Obj implements Target {
25
26     private static final JS.Method METHOD = new JS.Method();
27
28     private static Script root = null;
29     private static final String DEFAULT_CONF = Mailbox.STORAGE_ROOT + "conf" + File.separatorChar + "inbound.js";
30     public static Script root() {
31         try {
32             if (root == null) root = new Script(System.getProperty("ibex.mail.conf", DEFAULT_CONF));
33             return root;
34         } catch (Exception e) {
35             Log.error(Script.class, e);
36             return null;
37         }
38     }
39
40     final JS js;
41     private Message m = null;
42     private String filePath = null;
43     public Script(String filePath) throws JSExn, IOException {
44         this.filePath = filePath;
45         js = JSU.cloneWithNewGlobalScope(JSU.fromReader(filePath, 1, new InputStreamReader(new FileInputStream(filePath))),
46                                          new ScriptScope()); }
47
48     private class ScriptScope extends JS.Immutable {
49         ScriptEnv env = new ScriptEnv();
50         public JS get(JS name) throws JSExn {
51             //#jsswitch(name)
52             case "m": return m;
53             case "ibex": return env;
54             default: return null;
55                 //#end
56                 return null;
57         }
58     }
59
60     public void accept(Message m) throws IOException, MailException {
61         try {
62             new Script(filePath).reallyAccept(m);
63         } catch (JSExn e) {
64             Log.error(this, e);
65             throw new MailException(e.toString());
66         }
67     }
68
69     private synchronized void reallyAccept(Message m) throws IOException, MailException, JSExn {
70         this.m = m;
71         try {
72             Object ret = js.call(null, new JS[] { m });
73             Log.warn(this, "configuration script returned " + ret);
74             if (ret == null) throw new IOException("configuration script returned null");
75             while (ret instanceof JSReflection.Wrapper) ret = ((JSReflection.Wrapper)ret).unwrap();
76             if (ret instanceof Target)      ((Target)ret).accept(m);
77             //else if (ret instanceof Filter) ((Filter)ret).process(m);
78             else throw new IOException("configuration script returned a " + ret.getClass().getName());
79         } catch (JSExn e) {
80             Log.warn(this, e);
81             throw new IOException("configuration script threw an exception");
82         }
83     }
84
85     // FIXME: this should extend org.ibex.core.Ibex
86     public class ScriptEnv extends JS.Obj {
87
88         private PropertyFile prefs = null;
89         /*
90           static {
91           try {
92           // FIXME
93           prefs = new PropertyFile(new File("/etc/org.ibex.mail.properties"));
94           } catch (IOException e) {
95           Log.error(ScriptEnv.class, e);
96           }
97           }
98         */
99
100         /** lets us put multi-level get/put/call keys all in the same method */
101         private class Sub extends JS.Immutable {
102             String key;
103             Sub(String key) { this.key = key; }
104             public void put(JS key, JS val) throws JSExn {
105                 ScriptEnv.this.put(JSU.S(this.key + "." + JSU.toString(key)), val); }
106             public JS get(JS key) throws JSExn { return ScriptEnv.this.get(JSU.S(this.key + "." + JSU.toString(key))); }
107             public JS call(JS method, JS[] args) throws JSExn {
108                 return ScriptEnv.this.call(JSU.S(this.key + "." + JSU.toString(method)), args);
109             }
110         }
111         private Sub getSub(String s) { return new Sub(s); }
112
113         public JS get(JS name) throws JSExn {
114             //#jsswitch(name)
115             case "math": return ibexMath;
116             case "string": return ibexString;
117             case "date": return METHOD;
118             case "regexp": return METHOD;
119             case "log": return getSub("log");
120             case "log.debug": return METHOD;
121             case "log.info": return METHOD;
122             case "log.warn": return METHOD;
123             case "log.error": return METHOD;
124             case "list": return getSub("list");
125             case "url": return getSub("url");
126             case "url.encode": return METHOD;
127             case "mail": return getSub("mail");
128             case "mail.forward": return METHOD;
129             case "mail.forward2": return METHOD;
130             case "mail.send": return METHOD;
131             case "mail.attempt": return METHOD;
132             case "mail.later": return Later.instance;
133             case "mail.drop": return METHOD;
134             case "mail.razor": return getSub("mail.razor");
135             case "mail.razor.check": return METHOD;
136             case "mail.procmail": /* FEATURE */ return null;
137             case "mail.vacation": /* FEATURE */ return null;
138             case "mail.dcc": return getSub("mail.dcc");
139             case "mail.dcc.check": return METHOD;
140             case "mail.bounce": return METHOD;
141             case "mail.reject": return METHOD;
142             case "mail.my": return getSub("mail.my");
143             case "mail.dir": return METHOD;
144             case "mail.shell": return METHOD;
145             case "mail.my.prefs": try {
146                 return new org.ibex.js.Directory(new File("/etc/org.ibex.mail.prefs"));
147             } catch (IOException e) { throw new JSExn(e.toString()); }
148             case "mail.whitelist": return JSReflection.wrap(org.ibex.mail.SMTP.whitelist);
149             case "mail.my.mailbox":
150                 MailTree root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, true);
151                 return (JS)root.slash("user", true).slash("megacz", true);
152             case "mail.list": return METHOD;
153                 //#end
154                 return super.get(name);
155         }
156
157         public JS call(JS name0, JS[] args) throws JSExn {
158             final JS a = args.length >= 1 ? args[0] : null;
159             final JS b = args.length >= 2 ? args[1] : null;
160             final JS c = args.length >= 3 ? args[2] : null;
161             final int nargs = args.length;
162             String name = JSU.toString(name0);
163             try {
164                 if (name.equals("url.encode")) return JSU.S(java.net.URLEncoder.encode(JSU.toString(args[0])));
165                 if (name.equals("mail.list")) return JSReflection.wrap(FileBasedMailbox.getFileBasedMailbox(JSU.toString(args[0]), false));
166                 if (name.equals("mail.dir")) {
167                     return new org.ibex.js.Directory(new File(JSU.toString(args[0])));
168                 }
169                 if (name.equals("mail.shell")) {
170                     // FIXME: EEEEEVIL!
171                     Log.warn("dbug", a.getClass().getName());
172                     Log.warn("dbug", b.getClass().getName());
173                     Message m = (Message)b;
174                     final Process p = Runtime.getRuntime().exec(JSU.toString(a));
175                     Main.threadPool.start(new Runnable() {
176                         public void run() {
177                             try {
178                                 BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
179                                 String s = null;
180                                 while((s = br.readLine())!=null) 
181                                     Log.warn("shell", s);
182                             } catch (Exception e) { e.printStackTrace(); }
183                         }
184                     });
185                     OutputStream os = p.getOutputStream();
186                     Stream stream = new Stream(os);
187
188                     // why do I need to go via an sb here?
189                     StringBuffer sb = new StringBuffer();
190                     m.getBody().getStream().transcribe(sb);
191                     stream.println(sb.toString());
192
193                     stream.flush();
194                     stream.close();
195                     p.waitFor();
196                     return null;
197                 }
198                 if (name.equals("date")) { return new JSDate(args); }
199                 if (name.equals("mail.send") || name.equals("send") || name.equals("mail.attempt") || name.equals("attempt")) {
200                     boolean attempt = name.equals("mail.attempt") || name.equals("attempt");
201                     JS m = (JS)a;
202                     String body = "";
203                     Address from = null, to = null, envelopeFrom = null, envelopeTo = null;
204                     JS.Enumeration e = m.keys();
205                     Headers headers = new Headers();
206                     for(; e.hasNext();) {
207                         JS key = (JS)e.next();
208                         JS val = m.get(key) == null ? null : m.get(key);
209                         if ("body".equalsIgnoreCase(JSU.toString(key))) body = JSU.toString(val);
210                         else headers = new Headers(headers, new String[] { JSU.toString(key), JSU.toString(val) });
211                         if ("from".equalsIgnoreCase(JSU.toString(key))) from = Address.parse(JSU.toString(val));
212                         if ("to".equalsIgnoreCase(JSU.toString(key))) to = Address.parse(JSU.toString(val));
213                         if ("envelopeFrom".equalsIgnoreCase(JSU.toString(key))) envelopeFrom = Address.parse(JSU.toString(val));
214                         if ("envelopeTo".equalsIgnoreCase(JSU.toString(key))) envelopeTo = Address.parse(JSU.toString(val));
215                     }
216                     if (envelopeTo == null) envelopeTo = to;
217                     if (envelopeFrom == null) envelopeFrom = from;
218                     Message message =
219                         Message.newMessageFromHeadersAndBody(headers, Fountain.Util.create(body), envelopeFrom, envelopeTo);
220                     
221                     boolean ok = false;
222                     try {
223                         if (attempt) {
224                             org.ibex.mail.SMTP.Outgoing.attempt(message);
225                         } else {
226                             org.ibex.mail.SMTP.Outgoing.enqueue(message);
227                         }
228                         ok = true;
229                     } catch (Exception ex) {
230                         if (!attempt) Log.warn(this, ex);
231                     }
232                     if (!ok && !attempt) throw new JSExn("SMTP server rejected message");
233                     return JSU.B(ok);
234                 }
235                 if (name.equals("mail.razor.check")) {
236                     Process p = Runtime.getRuntime().exec("razor-check");
237                     ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
238                     return JSU.N(p.waitFor());
239                 }
240                 if (name.equals("mail.dcc.check")) {
241                     Process p = Runtime.getRuntime().exec(new String[] { "dccproc", "-H" });
242                     ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
243                     StringBuffer ret = new StringBuffer();
244                     new Stream(p.getInputStream()).transcribe(ret);
245                     p.waitFor();
246                     return JSU.S(ret.toString());
247                 }
248                 if (name.equals("mail.drop")) {
249                     return args.length==0 ? new Drop() : new Drop(JSU.toString(args[0]));
250                 }
251                 if (name.equals("mail.bounce")) {
252                     return new JSTarget() {
253                             public void accept(Message m) throws MailException {
254                                 try {
255                                     Message m2 = m.bounce(JSU.toString(a));
256                                     org.ibex.mail.SMTP.Outgoing.enqueue(m2);
257                                     Log.error(this, "BOUNCING! " + m2.summary());
258                                 } catch (Exception e) {
259                                     Log.warn(this, e);
260                                 }
261                             } };
262                 }
263                 if (name.equals("mail.forward2") || name.equals("forward2")) {
264                     try {
265                         Message m2 = m.withEnvelope(m.envelopeFrom, new Address(JSU.toString(a)));
266                         org.ibex.mail.SMTP.Outgoing.enqueue(m2);
267                     } catch (Exception e) {
268                         Log.warn(this, e);
269                         throw new JSExn(e.toString());
270                     }
271                     return null;
272                 }
273                 if (name.equals("mail.forward") || name.equals("forward")) {
274                     Message m2 = Script.this.m.withEnvelope(Script.this.m.envelopeFrom, new Address(JSU.toString(a)));
275                     org.ibex.mail.SMTP.Outgoing.attempt(m2, false);
276                     return Drop.instance;
277                 }
278                 if (name.equals("mail.reject"))
279                     return new Reject(JSU.toString(a));
280                 if (name.equals("log.debug") || name.equals("debug")) {    JSU.debug(a== null ? "**null**" : JSU.toString(a)); return null; }
281                 if (name.equals("log.info") || name.equals("info")) {     JSU.info(a== null ? "**null**" : JSU.toString(a)); return null; }
282                 if (name.equals("log.warn") || name.equals("warn")) {     JSU.warn(a== null ? "**null**" : JSU.toString(a)); return null; }
283                 if (name.equals("log.error") || name.equals("error")) {    JSU.error(a== null ? "**null**" : JSU.toString(a)); return null; }
284                 switch (nargs) {
285                     case 1:
286                         if (name.equals("regexp")) {return new JSRegexp(a, null); }
287                         break;
288                     case 2:
289                         if (name.equals("regexp")) {return new JSRegexp(a, b); }
290                 }
291             } catch (MailException e) { throw e;
292             } catch (Exception e) {
293                 Log.warn(this, "ibex."+name+"() threw: " + e);
294                 Log.warn(this, e);
295                 if (e instanceof JSExn) throw ((JSExn)e);
296                 throw new JSExn("invalid argument for ibex object method "+JSU.toString(name0)+"()");
297             }
298             throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+JSU.toString(name0)+"()");
299         }
300
301         public final JSMath ibexMath = new JSMath() {
302                 public JS get(JS name) throws JSExn {
303                     // FIXME!!!
304                     /*
305                       case "isNaN": return gs.get(name);
306                       case "isFinite": return gs.get(name);
307                       case "NaN": return gs.get(name);
308                       case "Infinity": return gs.get(name);
309                     */
310                     return null;
311                 }
312             };
313         
314         public final JS ibexString = new JS.Immutable() {
315                 public JS get(JS name) throws JSExn {
316                     // FIXME!!!
317                     /*
318                       case "parseInt": return gs.get(JSU.S("parseInt"));
319                       case "parseFloat": return gs.get(JSU.S("parseFloat"));
320                       case "decodeURI": return gs.get(JSU.S("decodeURI"));
321                       case "decodeURIComponent": return gs.get(JSU.S("decodeURIComponent"));
322                       case "encodeURI": return gs.get(JSU.S("encodeURI"));
323                       case "encodeURIComponent": return gs.get(JSU.S("encodeURIComponent"));
324                       case "escape": return gs.get(JSU.S("escape"));
325                       case "unescape": return gs.get(JSU.S("unescape"));
326                       case "fromCharCode": return gs.get(JSU.S("stringFromCharCode"));
327                     */
328                     return null;
329                 }
330             };
331     }
332
333     private static abstract class JSTarget extends JS.Obj implements Target { }
334
335     public static class Drop extends JS.Obj implements Target {
336         public static final Drop instance = new Drop();
337         public final String reason;
338         public Drop() { this(null); }
339         public Drop(String reason) { this.reason = reason; }
340         public void accept(Message m) throws IOException, MailException {
341             Log.warn(this, "dropping" +(reason==null?"":(" because "+reason))+ ": " + m.summary());
342         }
343     }
344
345     public static class Later extends JS.Obj implements Target {
346         public static final Later instance = new Later();
347         public static class LaterException extends RuntimeException { }
348         public void accept(Message m) throws IOException, MailException {
349             Log.warn(this, "delaying message " + m.summary());
350             throw new LaterException();
351         }
352     }
353
354     /** a fast-write, slow-read place to stash all messages we touch -- in case of a major f*ckup */
355     public static class Transcript implements Target {
356
357         public static final Transcript transcript = new Transcript(Mailbox.STORAGE_ROOT + File.separatorChar + "transcript");
358
359         private String path;
360         public Transcript(String path) { new File(this.path = path).mkdirs(); }
361         private static String lastTime = null;
362         private static int lastCounter = 0;
363
364         public synchronized void accept(Message message) {
365             try {
366                 File today = new File(path + File.separatorChar + (new SimpleDateFormat("yy-MMM-dd").format(new Date())));
367                 today.mkdirs();
368                 
369                 String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
370                 synchronized (Transcript.class) {
371                     if (lastTime != null && lastTime.equals(time)) {
372                         time += "." + (++lastCounter);
373                     } else {
374                         lastTime = time;
375                         lastCounter = 0;
376                     }
377                 }
378                 
379                 File target = new File(today.getPath() + File.separatorChar + time + ".txt");
380                 OutputStream os = new FileOutputStream(target);
381                 try {
382                     message.getStream().transcribe(new Stream(os));
383                     os.flush();
384                 } finally { os.close(); }
385             } catch (IOException e) { throw new MailException.IOException(e); }
386         }
387     }
388
389     public static class Reject extends JS.Obj implements Target {
390         public final String reason;
391         public Reject(String reason) { this.reason = reason; }
392         public void accept(Message m) throws IOException, MailException {
393             throw new RejectException(m, reason);
394         }
395         public static class RejectException extends RuntimeException {
396             public final Message m;
397             public final String reason;
398             public RejectException(Message m, String reason) { this.m = m; this.reason = reason; }
399         }
400     }
401
402 }