update Script.java
[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 public class Script extends JS.Obj implements Target {
17
18     private static final JS.Method METHOD = new JS.Method();
19
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() {
23         try {
24             if (root == null) root = new Script(System.getProperty("ibex.mail.conf", DEFAULT_CONF));
25             return root;
26         } catch (Exception e) {
27             Log.error(Script.class, e);
28             return null;
29         }
30     }
31
32     final JS js;
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))),
38                                          new ScriptScope()); }
39
40     private class ScriptScope extends JS.Immutable {
41         ScriptEnv env = new ScriptEnv();
42         public JS get(JS name) throws JSExn {
43             //#jsswitch(name)
44             case "m": return m;
45             case "ibex": return env;
46             default: return null;
47                 //#end
48                 return null;
49         }
50     }
51
52     public void accept(Message m) throws IOException, MailException {
53         try {
54             new Script(filePath).reallyAccept(m);
55         } catch (JSExn e) {
56             Log.error(this, e);
57             throw new MailException(e.toString());
58         }
59     }
60
61     private synchronized void reallyAccept(Message m) throws IOException, MailException, JSExn {
62         this.m = m;
63         try {
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());
71         } catch (JSExn e) {
72             Log.warn(this, e);
73             throw new IOException("configuration script threw an exception");
74         }
75     }
76
77     // FIXME: this should extend org.ibex.core.Ibex
78     public class ScriptEnv extends JS.Obj {
79
80         private PropertyFile prefs = null;
81         /*
82           static {
83           try {
84           // FIXME
85           prefs = new PropertyFile(new File("/etc/org.ibex.mail.properties"));
86           } catch (IOException e) {
87           Log.error(ScriptEnv.class, e);
88           }
89           }
90         */
91
92         /** lets us put multi-level get/put/call keys all in the same method */
93         private class Sub extends JS.Immutable {
94             String key;
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);
101             }
102         }
103         private Sub getSub(String s) { return new Sub(s); }
104
105         public JS get(JS name) throws JSExn {
106             //#jsswitch(name)
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;
143                 //#end
144                 return super.get(name);
145         }
146
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);
153             try {
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])));
158                 }
159                 if (name.equals("mail.shell")) {
160                     // FIXME: EEEEEVIL!
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];
165                     new Thread() {
166                         public void run() {
167                             try {
168                                 BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
169                                 String s = null;
170                                 while((s = br.readLine())!=null) 
171                                     Log.warn("shell", s);
172                             } catch (Exception e) { e.printStackTrace(); }
173                         }
174                     }.start();
175                     OutputStream os = p.getOutputStream();
176                     Stream stream = new Stream(os);
177                     m.getStream().transcribe(stream);
178                     stream.close();
179                     p.waitFor();
180                     return null;
181                 }
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");
185                     JS m = (JS)a;
186                     StringBuffer headers = new StringBuffer();
187                     String body = "";
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));
199                     }
200                     if (envelopeTo == null) envelopeTo = to;
201                     if (envelopeFrom == null) envelopeFrom = from;
202                     Message message =
203                         Message.newMessage(Fountain.Util.concat(Fountain.Util.create(headers.toString()),
204                                                                 Fountain.Util.create("\r\n"),
205                                                                 Fountain.Util.create(body)),
206                                            envelopeFrom,
207                                            envelopeTo
208                                            );
209                     
210                     boolean ok = false;
211                     try {
212                         if (attempt) {
213                             org.ibex.mail.SMTP.Outgoing.attempt(message);
214                         } else {
215                             org.ibex.mail.SMTP.Outgoing.enqueue(message);
216                         }
217                         ok = true;
218                     } catch (Exception ex) {
219                         if (!attempt) Log.warn(this, ex);
220                     }
221                     if (!ok && !attempt) throw new JSExn("SMTP server rejected message");
222                     return JSU.B(ok);
223                 }
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());
228                 }
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);
234                     p.waitFor();
235                     return JSU.S(ret.toString());
236                 }
237                 if (name.equals("mail.drop")) {
238                     return args.length==0 ? new Drop() : new Drop(JSU.toString(args[0]));
239                 }
240                 if (name.equals("mail.bounce")) {
241                     return new JSTarget() {
242                             public void accept(Message m) throws MailException {
243                                 try {
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) {
248                                     Log.warn(this, e);
249                                 }
250                             } };
251                 }
252                 if (name.equals("mail.forward2") || name.equals("forward2")) {
253                     try {
254                         Message m2 = Message.newMessage(m,
255                                                         m.envelopeFrom,
256                                                         new Address(JSU.toString(a)));
257                         org.ibex.mail.SMTP.Outgoing.enqueue(m2);
258                     } catch (Exception e) {
259                         Log.warn(this, e);
260                         throw new JSExn(e.toString());
261                     }
262                     return null;
263                 }
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;
268                 }
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; }
275                 switch (nargs) {
276                     case 1:
277                         if (name.equals("regexp")) {return new JSRegexp(a, null); }
278                         break;
279                     case 2:
280                         if (name.equals("regexp")) {return new JSRegexp(a, b); }
281                 }
282             } catch (MailException e) { throw e;
283             } catch (Exception e) {
284                 Log.warn(this, "ibex."+name+"() threw: " + e);
285                 Log.warn(this, e);
286                 if (e instanceof JSExn) throw ((JSExn)e);
287                 throw new JSExn("invalid argument for ibex object method "+JSU.toString(name0)+"()");
288             }
289             throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+JSU.toString(name0)+"()");
290         }
291
292         public final JSMath ibexMath = new JSMath() {
293                 public JS get(JS name) throws JSExn {
294                     // FIXME!!!
295                     /*
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);
300                     */
301                     return null;
302                 }
303             };
304         
305         public final JS ibexString = new JS.Immutable() {
306                 public JS get(JS name) throws JSExn {
307                     // FIXME!!!
308                     /*
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"));
318                     */
319                     return null;
320                 }
321             };
322     }
323
324     private static abstract class JSTarget extends JS.Obj implements Target { }
325
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());
333         }
334     }
335
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();
342         }
343     }
344
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 {
347
348         public static final Transcript transcript = new Transcript(Mailbox.STORAGE_ROOT + File.separatorChar + "transcript");
349
350         private String path;
351         public Transcript(String path) { new File(this.path = path).mkdirs(); }
352         private static String lastTime = null;
353         private static int lastCounter = 0;
354
355         public synchronized void accept(Message message) {
356             try {
357                 File today = new File(path + File.separatorChar + (new SimpleDateFormat("yy-MMM-dd").format(new Date())));
358                 today.mkdirs();
359                 
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);
364                     } else {
365                         lastTime = time;
366                         lastCounter = 0;
367                     }
368                 }
369                 
370                 File target = new File(today.getPath() + File.separatorChar + time + ".txt");
371                 OutputStream os = new FileOutputStream(target);
372                 try {
373                     message.getStream().transcribe(new Stream(os));
374                     os.flush();
375                 } finally { os.close(); }
376             } catch (IOException e) { throw new MailException.IOException(e); }
377         }
378     }
379
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);
385         }
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; }
390         }
391     }
392
393
394 }