3a829c688b6221096435054bbd6443c2c17b2fee
[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.dcc": return getSub("mail.dcc");
143             case "mail.dcc.check": return METHOD;
144             case "mail.bounce": return METHOD;
145             case "mail.reject": return METHOD;
146             case "mail.my": return getSub("mail.my");
147             case "mail.dir": return METHOD;
148             case "mail.shell": return METHOD;
149             case "mail.my.prefs": try {
150                 return new org.ibex.js.Directory(new File("/etc/org.ibex.mail.prefs"));
151             } catch (IOException e) { throw new JSExn(e.toString()); }
152             case "mail.whitelist": return JSReflection.wrap(org.ibex.mail.SMTP.whitelist);
153             case "mail.my.mailbox":
154                 MailTree root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, true);
155                 return (JS)root.slash("user", true).slash("megacz", true);
156             case "mail.list": return METHOD;
157                 //#end
158                 return super.get(name);
159         }
160
161         public JS call(JS name0, JS[] args) throws JSExn {
162             final JS a = args.length >= 1 ? args[0] : null;
163             final JS b = args.length >= 2 ? args[1] : null;
164             final JS c = args.length >= 3 ? args[2] : null;
165             final int nargs = args.length;
166             String name = JSU.toString(name0);
167             try {
168                 if (name.equals("url.encode")) return JSU.S(java.net.URLEncoder.encode(JSU.toString(args[0])));
169                 if (name.equals("mail.list")) return JSReflection.wrap(FileBasedMailbox.getFileBasedMailbox(JSU.toString(args[0]), false));
170                 if (name.equals("mail.dir")) {
171                     return new org.ibex.js.Directory(new File(JSU.toString(args[0])));
172                 }
173                 if (name.equals("mail.shell")) {
174                     // FIXME: EEEEEVIL!
175                     Log.warn("dbug", a.getClass().getName());
176                     Log.warn("dbug", b.getClass().getName());
177                     Message m = (Message)b;
178                     final Process p = Runtime.getRuntime().exec(JSU.toString(a));
179                     Main.threadPool.start(new Runnable() {
180                         public void run() {
181                             try {
182                                 BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
183                                 String s = null;
184                                 while((s = br.readLine())!=null) 
185                                     Log.warn("shell", s);
186                             } catch (Exception e) { e.printStackTrace(); }
187                         }
188                     });
189                     OutputStream os = p.getOutputStream();
190                     Stream stream = new Stream(os);
191
192                     // why do I need to go via an sb here?
193                     StringBuffer sb = new StringBuffer();
194                     m.getBody().getStream().transcribe(sb);
195                     stream.println(sb.toString());
196
197                     stream.flush();
198                     stream.close();
199                     p.waitFor();
200                     return null;
201                 }
202                 if (name.equals("date")) { return new JSDate(args); }
203                 if (name.equals("mail.send") || name.equals("send") || name.equals("mail.attempt") || name.equals("attempt")) {
204                     boolean attempt = name.equals("mail.attempt") || name.equals("attempt");
205                     JS m = (JS)a;
206                     String body = "";
207                     Address from = null, to = null, envelopeFrom = null, envelopeTo = null;
208                     JS.Enumeration e = m.keys();
209                     Headers headers = new Headers();
210                     for(; e.hasNext();) {
211                         JS key = (JS)e.next();
212                         JS val = m.get(key) == null ? null : m.get(key);
213                         if ("body".equalsIgnoreCase(JSU.toString(key))) body = JSU.toString(val);
214                         else headers = new Headers(headers, new String[] { JSU.toString(key), JSU.toString(val) });
215                         if ("from".equalsIgnoreCase(JSU.toString(key))) from = Address.parse(JSU.toString(val));
216                         if ("to".equalsIgnoreCase(JSU.toString(key))) to = Address.parse(JSU.toString(val));
217                         if ("envelopeFrom".equalsIgnoreCase(JSU.toString(key))) envelopeFrom = Address.parse(JSU.toString(val));
218                         if ("envelopeTo".equalsIgnoreCase(JSU.toString(key))) envelopeTo = Address.parse(JSU.toString(val));
219                     }
220                     if (envelopeTo == null) envelopeTo = to;
221                     if (envelopeFrom == null) envelopeFrom = from;
222                     Message message =
223                         Message.newMessageFromHeadersAndBody(headers, Fountain.Util.create(body), envelopeFrom, envelopeTo);
224                     
225                     boolean ok = false;
226                     try {
227                         if (attempt) {
228                             org.ibex.mail.SMTP.Outgoing.attempt(message);
229                         } else {
230                             org.ibex.mail.SMTP.Outgoing.enqueue(message);
231                         }
232                         ok = true;
233                     } catch (Exception ex) {
234                         if (!attempt) Log.warn(this, ex);
235                     }
236                     if (!ok && !attempt) throw new JSExn("SMTP server rejected message");
237                     return JSU.B(ok);
238                 }
239                 if (name.equals("mail.razor.check")) {
240                     Process p = Runtime.getRuntime().exec("razor-check");
241                     ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
242                     return JSU.N(p.waitFor());
243                 }
244                 if (name.equals("mail.clamav.check")) {
245                     // FIXME: this is returning "is-virus-laden" when clamdscan is unhappy -- BAD!
246                     // should use error code: 0=clean, 1=virus, 2=malfunction
247                     Process p = Runtime.getRuntime().exec("clamdscan - --stdout --quiet");
248                     ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
249                     int result = p.waitFor();
250                     if (result==0) return JSU.N(0);
251                     StringBuffer ret = new StringBuffer();
252                     new Stream(p.getInputStream()).transcribe(ret);
253                     return JSU.S(ret.toString());
254                 }
255                 if (name.equals("mail.dcc.check")) {
256                     Process p = Runtime.getRuntime().exec(new String[] { "dccproc", "-H" });
257                     ((Message)args[0]).getStream().transcribe(new Stream(p.getOutputStream()), true);
258                     StringBuffer ret = new StringBuffer();
259                     new Stream(p.getInputStream()).transcribe(ret);
260                     p.waitFor();
261                     String result = ret.toString();
262                     Log.warn("dcc", ((Message)args[0]).summary() + ":\n  " + result);
263                     int body = 0;
264                     int fuz1 = 0;
265                     int fuz2 = 0;
266                     int i_body = result.indexOf("Body=");
267                     int i_fuz1 = result.indexOf("Fuz1=");
268                     int i_fuz2 = result.indexOf("Fuz2=");
269                     if (i_body != -1) try {
270                         String s = result.substring(i_body+5);
271                         if (s.indexOf(' ') != -1) s = s.substring(0, s.indexOf(' '));
272                         if (s.indexOf('\n') != -1) s = s.substring(0, s.indexOf('\n'));
273                         body = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim());
274                     } catch (Exception e) { Log.error("", e); }
275                     if (i_fuz1 != -1) try {
276                         String s = result.substring(i_fuz1+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                         fuz1 = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim());
280                     } catch (Exception e) { Log.error("", e); }
281                     if (i_fuz2 != -1) try {
282                         String s = result.substring(i_fuz2+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                         fuz2 = s.trim().equals("many") ? 999 : Integer.parseInt(s.trim());
286                     } catch (Exception e) { Log.error("", e); }
287                     JSArray jsa = new JSArray();
288                     jsa.put(JSU.N(0), JSU.N(body));
289                     jsa.put(JSU.N(1), JSU.N(fuz1));
290                     jsa.put(JSU.N(2), JSU.N(fuz2));
291                     return jsa;
292                 }
293                 if (name.equals("mail.drop")) {
294                     return args.length==0 ? new Drop() : new Drop(JSU.toString(args[0]));
295                 }
296                 if (name.equals("mail.bounce")) {
297                     return new JSTarget() {
298                             public void accept(Message m) throws MailException {
299                                 try {
300                                     Message m2 = m.bounce(JSU.toString(a));
301                                     org.ibex.mail.SMTP.Outgoing.enqueue(m2);
302                                     Log.error(this, "BOUNCING! " + m2.summary());
303                                 } catch (Exception e) {
304                                     Log.warn(this, e);
305                                 }
306                             } };
307                 }
308                 if (name.equals("mail.forward2") || name.equals("forward2")) {
309                     try {
310                         Message m2 = m.withEnvelope(m.envelopeFrom, new Address(JSU.toString(a)));
311                         org.ibex.mail.SMTP.Outgoing.enqueue(m2);
312                     } catch (Exception e) {
313                         Log.warn(this, e);
314                         throw new JSExn(e.toString());
315                     }
316                     return null;
317                 }
318                 if (name.equals("mail.forward") || name.equals("forward")) {
319                     Message m2 = Script.this.m.withEnvelope(Script.this.m.envelopeFrom, new Address(JSU.toString(a)));
320                     org.ibex.mail.SMTP.Outgoing.attempt(m2, false);
321                     return Drop.instance;
322                 }
323                 if (name.equals("mail.reject"))
324                     return new Reject(JSU.toString(a));
325                 if (name.equals("log.debug") || name.equals("debug")) {    JSU.debug(a== null ? "**null**" : JSU.toString(a)); return null; }
326                 if (name.equals("log.info") || name.equals("info")) {     JSU.info(a== null ? "**null**" : JSU.toString(a)); return null; }
327                 if (name.equals("log.warn") || name.equals("warn")) {     JSU.warn(a== null ? "**null**" : JSU.toString(a)); return null; }
328                 if (name.equals("log.error") || name.equals("error")) {    JSU.error(a== null ? "**null**" : JSU.toString(a)); return null; }
329                 switch (nargs) {
330                     case 1:
331                         if (name.equals("regexp")) {return new JSRegexp(a, null); }
332                         break;
333                     case 2:
334                         if (name.equals("regexp")) {return new JSRegexp(a, b); }
335                 }
336             } catch (MailException e) { throw e;
337             } catch (Exception e) {
338                 Log.warn(this, "ibex."+name+"() threw: " + e);
339                 Log.warn(this, e);
340                 if (e instanceof JSExn) throw ((JSExn)e);
341                 throw new JSExn("invalid argument for ibex object method "+JSU.toString(name0)+"()");
342             }
343             throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+JSU.toString(name0)+"()");
344         }
345
346         public final JSMath ibexMath = new JSMath() {
347                 public JS get(JS name) throws JSExn {
348                     // FIXME!!!
349                     /*
350                       case "isNaN": return gs.get(name);
351                       case "isFinite": return gs.get(name);
352                       case "NaN": return gs.get(name);
353                       case "Infinity": return gs.get(name);
354                     */
355                     return null;
356                 }
357             };
358         
359         public final JS ibexString = new JS.Immutable() {
360                 public JS get(JS name) throws JSExn {
361                     // FIXME!!!
362                     /*
363                       case "parseInt": return gs.get(JSU.S("parseInt"));
364                       case "parseFloat": return gs.get(JSU.S("parseFloat"));
365                       case "decodeURI": return gs.get(JSU.S("decodeURI"));
366                       case "decodeURIComponent": return gs.get(JSU.S("decodeURIComponent"));
367                       case "encodeURI": return gs.get(JSU.S("encodeURI"));
368                       case "encodeURIComponent": return gs.get(JSU.S("encodeURIComponent"));
369                       case "escape": return gs.get(JSU.S("escape"));
370                       case "unescape": return gs.get(JSU.S("unescape"));
371                       case "fromCharCode": return gs.get(JSU.S("stringFromCharCode"));
372                     */
373                     return null;
374                 }
375             };
376     }
377
378     private static abstract class JSTarget extends JS.Obj implements Target { }
379
380     public static class Drop extends JS.Obj implements Target {
381         public static final Drop instance = new Drop();
382         public final String reason;
383         public Drop() { this(null); }
384         public Drop(String reason) { this.reason = reason; }
385         public void accept(Message m) throws IOException, MailException {
386             Log.warn(this, "dropping" +(reason==null?"":(" because "+reason))+ ": " + m.summary());
387         }
388     }
389
390     public static class Later extends JS.Obj implements Target {
391         public static final Later instance = new Later();
392         public static class LaterException extends RuntimeException { }
393         public void accept(Message m) throws IOException, MailException {
394             Log.warn(this, "delaying message " + m.summary());
395             throw new LaterException();
396         }
397     }
398
399     /** a fast-write, slow-read place to stash all messages we touch -- in case of a major f*ckup */
400     public static class Transcript implements Target {
401
402         public static final Transcript transcript = new Transcript(Mailbox.STORAGE_ROOT + File.separatorChar + "transcript");
403
404         private String path;
405         public Transcript(String path) { new File(this.path = path).mkdirs(); }
406         private static String lastTime = null;
407         private static int lastCounter = 0;
408
409         public synchronized void accept(Message message) {
410             try {
411                 File today = new File(path + File.separatorChar + (new SimpleDateFormat("yy-MMM-dd").format(new Date())));
412                 today.mkdirs();
413                 
414                 String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
415                 synchronized (Transcript.class) {
416                     if (lastTime != null && lastTime.equals(time)) {
417                         time += "." + (++lastCounter);
418                     } else {
419                         lastTime = time;
420                         lastCounter = 0;
421                     }
422                 }
423                 
424                 File target = new File(today.getPath() + File.separatorChar + time + ".txt");
425                 OutputStream os = new FileOutputStream(target);
426                 try {
427                     message.getStream().transcribe(new Stream(os));
428                     os.flush();
429                 } finally { os.close(); }
430             } catch (IOException e) { throw new MailException.IOException(e); }
431         }
432     }
433
434     public static class Reject extends JS.Obj implements Target {
435         public final String reason;
436         public Reject(String reason) { this.reason = reason; }
437         public void accept(Message m) throws IOException, MailException {
438             throw new RejectException(m, reason);
439         }
440         public static class RejectException extends RuntimeException {
441             public final Message m;
442             public final String reason;
443             public RejectException(Message m, String reason) { this.m = m; this.reason = reason; }
444         }
445     }
446
447 }