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