added support for DCC, VipulRazor
[org.ibex.mail.git] / src / org / ibex / mail / target / 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.target;
6 import org.ibex.js.*;
7 import org.ibex.io.*;
8 import org.ibex.util.*;
9 import org.ibex.mail.*;
10 import org.ibex.mail.filter.*;
11 import org.ibex.mail.target.*;
12 import java.io.*;
13 import java.util.*;
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 = File.separatorChar + "etc" + File.separatorChar + "org.ibex.mail.conf";
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.my.prefs": try {
133                     return new org.ibex.js.Directory(new File("/etc/org.ibex.mail.prefs"));
134             } catch (IOException e) { throw new JSExn(e.toString()); }
135             case "mail.my.mailbox":
136                 FileBasedMailbox root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, true);
137                 return root.slash("user", true).slash("megacz", true).slash("newmail", true);
138             case "mail.list": return METHOD;
139             //#end
140             return super.get(name);
141         }
142
143         public JS call(JS name0, JS[] args) throws JSExn {
144             final JS a = args.length >= 1 ? args[0] : null;
145             final JS b = args.length >= 2 ? args[1] : null;
146             final JS c = args.length >= 3 ? args[2] : null;
147             final int nargs = args.length;
148             String name = JSU.toString(name0);
149             try {
150                 if (name.equals("url.encode")) return JSU.S(java.net.URLEncoder.encode(JSU.toString(args[0])));
151                 if (name.equals("mail.list")) return JSReflection.wrap(MailingList.getMailingList(JSU.toString(args[0])));
152                 if (name.equals("date")) { return new JSDate(args); }
153                 if (name.equals("mail.send") || name.equals("send") || name.equals("mail.attempt") || name.equals("attempt")) {
154                     boolean attempt = name.equals("mail.attempt") || name.equals("attempt");
155                     JS m = (JS)a;
156                     StringBuffer headers = new StringBuffer();
157                     String body = "";
158                     Address from = null, to = null, envelopeFrom = null, envelopeTo = null;
159                     JS.Enumeration e = m.keys();
160                     for(; e.hasNext();) {
161                         JS key = (JS)e.next();
162                         JS val = m.get(key) == null ? null : m.get(key);
163                         if ("body".equalsIgnoreCase(JSU.toString(key))) body = JSU.toString(val);
164                         else headers.append(JSU.toString(key) + ": " + JSU.toString(val) + "\r\n");
165                         if ("from".equalsIgnoreCase(JSU.toString(key))) from = Address.parse(JSU.toString(val));
166                         if ("to".equalsIgnoreCase(JSU.toString(key))) to = Address.parse(JSU.toString(val));
167                         if ("envelopeFrom".equalsIgnoreCase(JSU.toString(key))) envelopeFrom = Address.parse(JSU.toString(val));
168                         if ("envelopeTo".equalsIgnoreCase(JSU.toString(key))) envelopeTo = Address.parse(JSU.toString(val));
169                     }
170                     if (envelopeTo == null) envelopeTo = to;
171                     if (envelopeFrom == null) envelopeFrom = from;
172                     Message message =
173                         Message.newMessage(new org.ibex.io.Fountain.StringFountain(headers.toString() + "\r\n" + body),
174                                            envelopeFrom,
175                                            envelopeTo
176                                            );
177                     
178                     boolean ok = false;
179                     try {
180                         if (attempt) {
181                             org.ibex.mail.protocol.SMTP.Outgoing.attempt(message);
182                         } else {
183                             org.ibex.mail.protocol.SMTP.Outgoing.accept(message);
184                         }
185                         ok = true;
186                     } catch (Exception ex) {
187                         if (!attempt) Log.warn(this, ex);
188                     }
189                     if (!ok && !attempt) throw new JSExn("SMTP server rejected message");
190                     return JSU.B(ok);
191                 }
192                 if (name.equals("mail.razor.check")) {
193                     Process p = Runtime.getRuntime().exec("razor-check");
194                     ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
195                     return JSU.N(p.waitFor());
196                 }
197                 if (name.equals("mail.dcc.check")) {
198                     Process p = Runtime.getRuntime().exec(new String[] { "dccproc", "-H" });
199                     ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
200                     StringBuffer ret = new StringBuffer();
201                     new Stream(p.getInputStream()).transcribe(ret);
202                     p.waitFor();
203                     return JSU.S(ret.toString());
204                 }
205                 if (name.equals("mail.drop")) {
206                     return args.length==0 ? new Drop() : new Drop(JSU.toString(args[0]));
207                 }
208                 if (name.equals("mail.bounce")) {
209                     return new JSTarget() {
210                             public void accept(Message m) throws MailException {
211                                 try {
212                                     Message m2 = m.bounce(JSU.toString(a));
213                                     org.ibex.mail.protocol.SMTP.Outgoing.accept(m2);
214                                     Log.error(this, "BOUNCING! " + m2.summary());
215                                 } catch (Exception e) {
216                                     Log.warn(this, e);
217                                 }
218                             } };
219                 }
220                 if (name.equals("mail.forward2") || name.equals("forward2")) {
221                     try {
222                         Message m2 = Message.newMessage(new org.ibex.io.Fountain.StringFountain(m.toString()),
223                                                         m.envelopeFrom,
224                                                         new Address(JSU.toString(a)));
225                         org.ibex.mail.protocol.SMTP.Outgoing.accept(m2);
226                     } catch (Exception e) {
227                         Log.warn(this, e);
228                         throw new JSExn(e.toString());
229                     }
230                     return null;
231                 }
232                 if (name.equals("mail.forward") || name.equals("forward")) {
233                     Message m2 = Message.newMessage(Script.this.m, Script.this.m.envelopeFrom, new Address(JSU.toString(a)));
234                     org.ibex.mail.protocol.SMTP.Outgoing.attempt(m2, false);
235                     return Drop.instance;
236                 }
237                 if (name.equals("mail.reject"))
238                     return new Reject(JSU.toString(a));
239                 if (name.equals("log.debug") || name.equals("debug")) {    JSU.debug(a== null ? "**null**" : JSU.toString(a)); return null; }
240                 if (name.equals("log.info") || name.equals("info")) {     JSU.info(a== null ? "**null**" : JSU.toString(a)); return null; }
241                 if (name.equals("log.warn") || name.equals("warn")) {     JSU.warn(a== null ? "**null**" : JSU.toString(a)); return null; }
242                 if (name.equals("log.error") || name.equals("error")) {    JSU.error(a== null ? "**null**" : JSU.toString(a)); return null; }
243                 switch (nargs) {
244                 case 1:
245                     if (name.equals("regexp")) {return new JSRegexp(a, null); }
246                     break;
247                 case 2:
248                     if (name.equals("regexp")) {return new JSRegexp(a, b); }
249                 }
250             } catch (MailException e) { throw e;
251             } catch (Exception e) {
252                 Log.warn(this, "ibex."+name+"() threw: " + e);
253                 Log.warn(this, e);
254                 if (e instanceof JSExn) throw ((JSExn)e);
255                 throw new JSExn("invalid argument for ibex object method "+JSU.toString(name0)+"()");
256             }
257             throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+JSU.toString(name0)+"()");
258         }
259
260         public final JSMath ibexMath = new JSMath() {
261                 public JS get(JS name) throws JSExn {
262                     // FIXME!!!
263                     /*
264                     case "isNaN": return gs.get(name);
265                     case "isFinite": return gs.get(name);
266                     case "NaN": return gs.get(name);
267                     case "Infinity": return gs.get(name);
268                     */
269                     return null;
270                 }
271             };
272         
273         public final JS ibexString = new JS.Immutable() {
274                 public JS get(JS name) throws JSExn {
275                     // FIXME!!!
276                     /*
277                     case "parseInt": return gs.get(JSU.S("parseInt"));
278                     case "parseFloat": return gs.get(JSU.S("parseFloat"));
279                     case "decodeURI": return gs.get(JSU.S("decodeURI"));
280                     case "decodeURIComponent": return gs.get(JSU.S("decodeURIComponent"));
281                     case "encodeURI": return gs.get(JSU.S("encodeURI"));
282                     case "encodeURIComponent": return gs.get(JSU.S("encodeURIComponent"));
283                     case "escape": return gs.get(JSU.S("escape"));
284                     case "unescape": return gs.get(JSU.S("unescape"));
285                     case "fromCharCode": return gs.get(JSU.S("stringFromCharCode"));
286                     */
287                     return null;
288                 }
289             };
290     }
291
292     private static abstract class JSTarget extends JS.Obj implements Target { }
293 }