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