added preliminary mailing list support
[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             if (ret instanceof Target)      ((Target)ret).accept(m);
66             //else if (ret instanceof Filter) ((Filter)ret).process(m);
67             else throw new IOException("configuration script returned a " + ret.getClass().getName());
68         } catch (JSExn e) {
69             Log.warn(this, e);
70             throw new IOException("configuration script threw an exception");
71         }
72     }
73
74     // FIXME: this should extend org.ibex.core.Ibex
75     public class ScriptEnv extends JS.Obj {
76
77         private PropertyFile prefs = null;
78             /*
79         static {
80             try {
81                 // FIXME
82                 prefs = new PropertyFile(new File("/etc/org.ibex.mail.properties"));
83             } catch (IOException e) {
84                 Log.error(ScriptEnv.class, e);
85             }
86         }
87             */
88
89         /** lets us put multi-level get/put/call keys all in the same method */
90         private class Sub extends JS.Immutable {
91             String key;
92             Sub(String key) { this.key = key; }
93             public void put(JS key, JS val) throws JSExn {
94                 ScriptEnv.this.put(JSU.S(this.key + "." + JSU.toString(key)), val); }
95             public JS get(JS key) throws JSExn { return ScriptEnv.this.get(JSU.S(this.key + "." + JSU.toString(key))); }
96             public JS call(JS method, JS[] args) throws JSExn {
97                 return ScriptEnv.this.call(JSU.S(this.key + "." + JSU.toString(method)), args);
98             }
99         }
100         private Sub getSub(String s) { return new Sub(s); }
101
102         public JS get(JS name) throws JSExn {
103             //#jsswitch(name)
104             case "math": return ibexMath;
105             case "string": return ibexString;
106             case "date": return METHOD;
107             case "regexp": return METHOD;
108             case "log": return getSub("log");
109             case "log.debug": return METHOD;
110             case "log.info": return METHOD;
111             case "log.warn": return METHOD;
112             case "log.error": return METHOD;
113             case "list": return getSub("list");
114             case "mail": return getSub("mail");
115             case "mail.forward": return METHOD;
116             case "mail.forward2": return METHOD;
117             case "mail.send": return METHOD;
118             case "mail.attempt": return METHOD;
119             case "mail.later": return Later.instance;
120             case "mail.drop": return Drop.instance;
121             case "mail.bounce": return METHOD;
122             case "mail.my": return getSub("mail.my");
123             case "mail.my.prefs": try {
124                     return new org.ibex.js.Directory(new File("/etc/org.ibex.mail.prefs"));
125             } catch (IOException e) { throw new JSExn(e.toString()); }
126             case "mail.my.mailbox":
127                 FileBasedMailbox root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, true);
128                 return root.slash("user", true).slash("megacz", true).slash("newmail", true);
129             case "mail.list": return METHOD;
130             //#end
131             return super.get(name);
132         }
133
134         public JS call(JS name0, JS[] args) throws JSExn {
135             final JS a = args.length >= 1 ? args[0] : null;
136             final JS b = args.length >= 2 ? args[1] : null;
137             final JS c = args.length >= 3 ? args[2] : null;
138             final int nargs = args.length;
139             String name = JSU.toString(name0);
140             try {
141                 if (name.equals("mail.list")) return MailingList.getMailingList(JS.toString(args[0])).acceptor;
142                 if (name.equals("date")) { return new JSDate(args); }
143                 if (name.equals("mail.send") || name.equals("send") || name.equals("mail.attempt") || name.equals("attempt")) {
144                     boolean attempt = name.equals("mail.attempt") || name.equals("attempt");
145                     JS m = (JS)a;
146                     StringBuffer headers = new StringBuffer();
147                     String body = "";
148                     Address from = null, to = null, envelopeFrom = null, envelopeTo = null;
149                     JS.Enumeration e = m.keys();
150                     for(; e.hasNext();) {
151                         JS key = (JS)e.next();
152                         JS val = m.get(key) == null ? null : m.get(key);
153                         if ("body".equalsIgnoreCase(JSU.toString(key))) body = JSU.toString(val);
154                         else headers.append(JSU.toString(key) + ": " + JSU.toString(val) + "\r\n");
155                         if ("from".equalsIgnoreCase(JSU.toString(key))) from = Address.parse(JSU.toString(val));
156                         if ("to".equalsIgnoreCase(JSU.toString(key))) to = Address.parse(JSU.toString(val));
157                         if ("envelopeFrom".equalsIgnoreCase(JSU.toString(key))) envelopeFrom = Address.parse(JSU.toString(val));
158                         if ("envelopeTo".equalsIgnoreCase(JSU.toString(key))) envelopeTo = Address.parse(JSU.toString(val));
159                     }
160                     if (envelopeTo == null) envelopeTo = to;
161                     if (envelopeFrom == null) envelopeFrom = from;
162                     Message message =
163                         Message.newMessage(new org.ibex.io.Fountain.StringFountain(headers.toString() + "\r\n" + body),
164                                            envelopeFrom,
165                                            envelopeTo
166                                            );
167                     
168                     boolean ok = false;
169                     try {
170                         if (attempt) {
171                             org.ibex.mail.protocol.SMTP.Outgoing.attempt(message);
172                         } else {
173                             org.ibex.mail.protocol.SMTP.Outgoing.accept(message);
174                         }
175                         ok = true;
176                     } catch (Exception ex) {
177                         if (!attempt) Log.warn(this, ex);
178                     }
179                     if (!ok && !attempt) throw new JSExn("SMTP server rejected message");
180                     return JSU.B(ok);
181                 }
182                 if (name.equals("mail.bounce")) {
183                     return new JSTarget() {
184                             public void accept(Message m) throws MailException {
185                                 try {
186                                     Message m2 = m.bounce(JSU.toString(a));
187                                     org.ibex.mail.protocol.SMTP.Outgoing.accept(m2);
188                                     Log.error(this, "BOUNCING! " + m2.summary());
189                                 } catch (Exception e) {
190                                     Log.warn(this, e);
191                                 }
192                             } };
193                 }
194                 if (name.equals("mail.forward2") || name.equals("forward2")) {
195                     try {
196                         Message m2 = Message.newMessage(new org.ibex.io.Fountain.StringFountain(m.toString()),
197                                                         m.envelopeFrom,
198                                                         new Address(JSU.toString(a)));
199                         org.ibex.mail.protocol.SMTP.Outgoing.accept(m2);
200                     } catch (Exception e) {
201                         Log.warn(this, e);
202                         throw new JSExn(e.toString());
203                     }
204                     return null;
205                 }
206                 if (name.equals("mail.forward") || name.equals("forward")) {
207                     Message m2 = Message.newMessage(Script.this.m, Script.this.m.envelopeFrom, new Address(JSU.toString(a)));
208                     org.ibex.mail.protocol.SMTP.Outgoing.attempt(m2);
209                     return Drop.instance;
210                 }
211                 if (name.equals("log.debug") || name.equals("debug")) {    JSU.debug(a== null ? "**null**" : JSU.toString(a)); return null; }
212                 if (name.equals("log.info") || name.equals("info")) {     JSU.info(a== null ? "**null**" : JSU.toString(a)); return null; }
213                 if (name.equals("log.warn") || name.equals("warn")) {     JSU.warn(a== null ? "**null**" : JSU.toString(a)); return null; }
214                 if (name.equals("log.error") || name.equals("error")) {    JSU.error(a== null ? "**null**" : JSU.toString(a)); return null; }
215                 switch (nargs) {
216                 case 1:
217                     if (name.equals("regexp")) {return new JSRegexp(a, null); }
218                     break;
219                 case 2:
220                     if (name.equals("regexp")) {return new JSRegexp(a, b); }
221                 }
222             } catch (Exception e) {
223                 Log.warn(this, "ibex."+name+"() threw: " + e);
224                 Log.warn(this, e);
225                 if (e instanceof JSExn) throw ((JSExn)e);
226                 throw new JSExn("invalid argument for ibex object method "+JSU.toString(name0)+"()");
227             }
228             throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+JSU.toString(name0)+"()");
229         }
230
231         public final JSMath ibexMath = new JSMath() {
232                 public JS get(JS name) throws JSExn {
233                     // FIXME!!!
234                     /*
235                     case "isNaN": return gs.get(name);
236                     case "isFinite": return gs.get(name);
237                     case "NaN": return gs.get(name);
238                     case "Infinity": return gs.get(name);
239                     */
240                     return null;
241                 }
242             };
243         
244         public final JS ibexString = new JS.Immutable() {
245                 public JS get(JS name) throws JSExn {
246                     // FIXME!!!
247                     /*
248                     case "parseInt": return gs.get(JSU.S("parseInt"));
249                     case "parseFloat": return gs.get(JSU.S("parseFloat"));
250                     case "decodeURI": return gs.get(JSU.S("decodeURI"));
251                     case "decodeURIComponent": return gs.get(JSU.S("decodeURIComponent"));
252                     case "encodeURI": return gs.get(JSU.S("encodeURI"));
253                     case "encodeURIComponent": return gs.get(JSU.S("encodeURIComponent"));
254                     case "escape": return gs.get(JSU.S("escape"));
255                     case "unescape": return gs.get(JSU.S("unescape"));
256                     case "fromCharCode": return gs.get(JSU.S("stringFromCharCode"));
257                     */
258                     return null;
259                 }
260             };
261     }
262
263     private static abstract class JSTarget extends JS.Obj implements Target { }
264 }