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