62d1d6a8b59418a222c625774b7b82a1858330fb
[org.ibex.mail.git] / src / org / ibex / mail / protocol / GMail.java
1 package org.ibex.mail.protocol;
2 import org.ibex.io.*;
3 import org.ibex.crypto.*;
4 import org.ibex.mail.protocol.*;
5 import org.ibex.jinetd.Listener;
6 import org.ibex.jinetd.Worker;
7 import org.ibex.mail.*;
8 import org.ibex.util.*;
9 import org.ibex.net.*;
10 import org.ibex.js.*;
11 import org.ibex.mail.target.*;
12 import java.util.*;
13 import java.net.*;
14 import java.text.*;
15 import java.io.*;
16
17 public class GMail extends Account {
18
19     private      GMailIMAP imap = new GMailIMAP();
20     private HTTP.Cookie.Jar jar = new HTTP.Cookie.Jar();
21     private      String captcha = null;
22     private       String ctoken = null;
23     private        String email = null;
24     private     String password = null;
25     private     boolean invalid = false;
26     private     String[] labels = new String[0];
27     private    String[] queries = new String[0];
28     private Summary[] summaries = new Summary[0];
29
30     // Constructor, Pooling  ///////////////////////////////////////////////////////////////////////////
31
32     public GMail(String email, String pass) throws IOException {
33         super(email.substring(0, email.indexOf('@')), Address.parse(email));
34         this.email = email; this.password = pass;
35         Log.warn(GMail.class, "logging in " + email);
36         getCookies();
37     }
38
39     public void close() { cache.remove(email, password); invalid = true; }
40
41     private static Hash cache = new Hash();
42     static { HTTP.userAgent = "Mozilla/5.0 (compatible;)"; }
43     public static GMail getGMail(String email, String pass) {
44         try {
45             GMail g = (GMail)cache.get(email, pass);
46             if (g == null) cache.put(email, pass, g = new GMail(email, pass));
47             return g;
48         } catch (Exception e) {
49             Log.error(GMail.class, e);
50             return null;
51         }
52     }
53
54     // IMAP Interface //////////////////////////////////////////////////////////////////////////////
55
56     public IMAP.Server getIMAP() { return imap; }
57     private class GMailIMAP implements IMAP.Server {
58
59         private String query = "?search=inbox&start=0&view=tl";
60         private int validity = new Random().nextInt();
61
62         private IMAP.Client client;
63         public void setClient(IMAP.Client client) { this.client = client; }
64
65         public String[]  capability() { return new String[] { }; }
66         public Hashtable id(Hashtable clientId) { return null; }
67         public void      logout() { GMail.this.close(); }
68         public void      subscribe(String mailbox) { }
69         public void      unsubscribe(String mailbox) { }
70
71         public void      unselect() { summaries = new Summary[0]; }
72         public void      close() { summaries = new Summary[0]; }
73
74         public void      noop() { check(); }
75         public void      expunge() { }
76
77         public void      setFlags(Query q, int flags, boolean uid, boolean silent) { }
78         public void      removeFlags(Query q, int flags, boolean uid, boolean silent) { }
79         public void      addFlags(Query q, int flags, boolean uid, boolean silent) { }
80
81         public void      rename(String from, String to) { }
82         public void      delete(String m) { }
83         public void      create(String m) {
84             String[] newqueries = new String[queries.length+1];
85             System.arraycopy(queries, 0, newqueries, 0, queries.length);
86             newqueries[queries.length] = m;
87             queries = newqueries;
88         }
89
90         public void      append(String m, int flags, Date arrival, String body) { }
91         public void      copy(Query q, String to) { }
92
93         public void      check() { query(query); }
94         public void      select(String mailbox, boolean examineOnly) {
95             String oldquery = query;
96             if (mailbox.equalsIgnoreCase("inbox")) {
97                 query = "?search=inbox&start=0&view=tl";
98                 if (!query.equals(oldquery)) check();
99                 return;
100             }
101             for(int i=0; i<labels.length; i++) {
102                 if (labels[i].equals(mailbox)) {
103                     query = "?search=cat&cat="+mailbox+"&inbox&start=0&view=tl";
104                     if (!query.equals(oldquery)) check();
105                     return;
106                 }
107             }
108             query = "?search=query&q="+URLEncoder.encode(mailbox)+"&start=0&view=tl";
109             if (!query.equals(oldquery)) check();
110         }
111
112         public void      lsub(String start, String ref) { list(true); }
113         public void      list(String start, String ref) { list(false); }
114         private void list(boolean lsub) {
115             client.list('/', "inbox", lsub, false);
116             for(int i=0; i<labels.length; i++) client.list('/', labels[i], lsub, false);
117             for(int i=0; i<queries.length; i++) client.list('/', queries[i], lsub, false);
118         }
119
120         public int[]     search(Query q, boolean uid) { return null; }
121         public void      fetch(Query q, int spec, String[] headers, int start, int end, boolean uid) {
122             if (captchaMessage != null) { client.fetch(1, 0, 100, captchaMessage, 100); return; }
123             for(int i=0; i<summaries.length; i++) try {
124                 final Message m = summaries[i].getMessage();
125                 final int num = i;
126                 if (q.match(new Mailbox.Iterator() {
127                         public Message cur() { return m; }
128                         public MIME.Headers head() { return m.headers; }
129                         public boolean next() { return false; }
130                         public int     uid() { return num; }
131                         public int     num() { return num; }
132                         public void    delete() { }
133                         public void    set(String key, String val) { }
134                         public String  get(String key) { return null; }
135                         public boolean seen() { return false; }
136                         public boolean deleted() { return false; }
137                         public boolean flagged() { return false; }
138                         public boolean draft() { return false;}
139                         public boolean answered() { return false; }
140                         public boolean recent() { return true; }
141                         public void    seen(boolean on) { }
142                         public void    deleted(boolean on) { }
143                         public void    flagged(boolean on) { }
144                         public void    draft(boolean on) { }
145                         public void    answered(boolean on) { }
146                         public void    recent(boolean on) { }
147                         public int     flags() { return 0; }
148                         public void    addFlags(int flags) { }
149                         public void    removeFlags(int flags) { }
150                         public void    setFlags(int flags) { }
151                     })) {
152                     Log.info(GMail.class, "fetch " + summaries[i].subject);
153                     client.fetch(i+1, 0, m.size(), m,/* summaries[i].getIntId()*/ i);
154                 }
155             } catch (Exception e) { Log.warn(this, e); }
156         }
157
158         public int       unseen(String mailbox)      { return summaries.length; }
159         public int       recent(String mailbox)      { return summaries.length; }
160         public int       count(String mailbox)       { return summaries.length; }
161         public int       uidNext(String mailbox)     { return summaries.length+1; }
162         public int       uidValidity(String mailbox) { return validity; }
163     }
164
165     public void getCookies() throws IOException {
166         jar = new HTTP.Cookie.Jar();
167         String params =
168             "continue="     + URLEncoder.encode(gmail) +
169             "&service=mail" +
170             "&Email="       + URLEncoder.encode(user) +
171             "&Passwd="      + password + 
172             "&null=Sign+in" +
173             (captcha != null ? "&captcha="+URLEncoder.encode(captcha) : "") +
174             (captcha != null ? "&ctoken="+URLEncoder.encode(ctoken) : "");
175         Log.info("[request]", params);
176         HTTP http = captcha==null ? new HTTP(login+"?"+params) : new HTTP(login);
177         InputStream reply = captcha==null ?
178             http.GET(null, jar) :
179             http.POST("application/x-www-form-urlencoded", params, null, jar);
180         String result = new String(InputStreamToByteArray.convert(reply));
181         System.err.println(result);
182         captcha = null;
183         
184         if (result.indexOf("top.location") == -1) { doCaptcha(result); return; }
185         result = result.substring(result.indexOf("top.location"));
186         result = result.substring(result.indexOf("CheckCookie?continue=") + "CheckCookie?continue=".length());
187         result = result.substring(0, result.indexOf('\"'));
188         result = URLDecoder.decode(result);
189         Log.warn("[]", "getting " + result);
190
191         // just need the cookie off of this page
192         InputStreamToByteArray.convert(new HTTP(result).GET(null, jar));
193         imap.check();
194         Log.warn("[]", "done");
195     }
196
197     Message captchaMessage = null;
198     public void doCaptcha(String result) throws IOException {
199         Log.warn(GMail.class,"no relocator found; checking for captcha");
200         ctoken = result.substring(result.indexOf("id=\"ctoken\" value=\"") + "id=\"ctoken\" value=\"".length());
201         ctoken = ctoken.substring(0, ctoken.indexOf("\""));
202         String image = result.substring(result.indexOf("Captcha?"));
203         image = image.substring(0, image.indexOf("\""));
204         String str =                                            
205             "From: google@google.com\r\n" +
206             "To: you@yourself.com\r\n" +
207             "Subject: Captcha\r\n" +
208             "Date: Mon Aug 30 19:05:40 PDT 2004\r\n" +
209             "Content-Type: text/html\r\n" +
210             "\r\n" +
211             "<html><body>\r\n" +
212             "Hi there.  Google is lame; please type in the word you see below and " +
213             "click submit.  You might have to click 'get mail' again after that.<br>  " +
214             "<img src=\"https://www.google.com/accounts/"+image+"\">\r\n" +
215             "<form method=get action=http://gmail.megacz.com:8099/Captcha>\r\n"+
216             "  <input type=text name=captcha>\r\n"+
217             "  <input type=hidden name=email value=\""+email+"\">\r\n"+
218             "  <input type=hidden name=pass value="+password+">\r\n"+
219             "  <input type=hidden name=ctoken value=\""+ctoken+"\">\r\n"+
220             "  <input type=submit>\r\n"+
221             "</form>\r\n"+
222             "</body></html>\r\n";
223         try {
224             captchaMessage = Message.newMessage(new Stream(str));
225         } catch (Message.Malformed e) {
226             Log.warn(this, e);
227             throw new IOException(e.toString());
228         }
229     }
230
231     public synchronized Summary[] query(String query) { 
232         if (captcha != null) return new Summary[0];
233         try {
234             Log.info(GMail.class, "query: " + query);
235             JSArray ret = http(gmail + query, jar);
236             Hashtable h = new Hashtable();
237             for(int i=0; i<ret.length(); i++) {
238                 JSArray j = (JSArray)ret.get(i);
239                 if (j.elementAt(0).equals("t")) {
240                     for(int k=1; k<j.length(); k++) getSummary((String)((JSArray)j.get(k)).get(0), h);
241                 } else if (j.elementAt(0).equals("ct") && labels.length == 0) {
242                     Vec v = new Vec();
243                     j = (JSArray)j.elementAt(1);
244                     for(int k=0; k<j.length(); k++) v.addElement(((JSArray)j.elementAt(k)).elementAt(0));
245                     v.copyInto(labels = new String[v.size()]);
246                 }
247             }
248             Enumeration e = h.keys();
249             Vec v = new Vec();
250             while(e.hasMoreElements()) v.addElement(h.get(e.nextElement()));
251             return summaries = (Summary[])v.copyInto(new Summary[v.size()]);
252         } catch (Exception e) {
253             Log.warn(this, e);
254             return new Summary[0];
255         }
256     }
257
258     public void getSummary(String id, Hashtable ret) {
259         try {
260             JSArray js2 = http(gmail + "?search=query&start=0&view=cv&q=in:anywhere&th=" + URLEncoder.encode(id), jar);
261             for(int i2=0; i2<js2.length(); i2++) {
262                 JSArray args = (JSArray)js2.elementAt(i2);
263                 if (!args.elementAt(0).equals("mi")) continue;
264                 Summary sum = new Summary(args);
265                 Log.info(GMail.class, "summary: " + sum.subject);
266                 ret.put(sum.id, sum);
267             }
268         } catch (Exception e) {
269             e.printStackTrace();
270         }
271     }
272
273     private class Summary {
274         public Address from;
275         public Address to;
276         public String  subject;
277         public Date    date;
278         public String  id;
279         public Message message = null;
280         
281         public int getIntId() { return Math.abs(Integer.parseInt(id.toLowerCase().substring(id.length()-7), 16)); }
282
283         public Message getMessage() throws Message.Malformed, IOException {
284             if (message != null) return message;
285             Stream thestream =
286                 new Stream(new HTTP(gmail+"?search=query&start=0&view=om&th=" + URLEncoder.encode(id)).GET(null, jar));
287             thestream.readln();
288             return message = Message.newMessage(thestream);
289         }
290         
291         public Summary(JSArray m) {
292             try { this.date = new Date(m.elementAt(9).toString()); } catch (Exception e) { this.date = null; }
293             this.id = m.elementAt(3).toString();
294             this.to = Address.parse(m.elementAt(8).toString() + " <" + m.elementAt(10).toString() + ">");
295             this.from = Address.parse(m.elementAt(6).toString()+"<"+m.elementAt(7).toString()+">");
296             this.subject = m.elementAt(15).toString();
297         }
298     }
299
300     public JSArray http(String url, HTTP.Cookie.Jar jar) throws JSExn, IOException  {
301         Stream stream = new Stream(new HTTP(url).GET(null, jar));                    
302         boolean inscript = false;
303         StringBuffer buf = new StringBuffer("var ret = []; var D = function(x){ret.push(x);};");
304         String s = null;
305         while((s = stream.readln()) != null) {
306             if (s.indexOf("<script>") != -1)  { inscript = true; continue; }
307             if (s.indexOf("</script>") != -1) { inscript = false; continue; }
308             if (inscript) buf.append(s);
309         }
310         buf.append("return ret;");
311         synchronized(GMail.class) {
312             JS js = JS.fromReader("google", 0, new StringReader(buf.toString()));
313             return (JSArray)js.call(null, null, null, null, 0);
314         }
315     }
316
317
318     // HTTP Listener for Captcha requests //////////////////////////////////////////////////////////////////////////////
319     
320     public static void handleRequest(Connection conn) {
321         String top = null;
322         for(String s = conn.readln(); s != null && s.length() > 0; s = conn.readln()) {
323             if (top == null) top = s;
324             Log.warn(GMail.class, s);
325         }
326         if (top.startsWith("GET /Captcha")) {
327             top = top.substring(top.indexOf('?')+1);
328             top = top.substring(0, top.indexOf(' '));
329             StringTokenizer st = new StringTokenizer(top, "&");
330             Hash h = new Hash();
331             while(st.hasMoreTokens()) {
332                 String tok = st.nextToken();
333                 h.put(URLDecoder.decode(tok.substring(0, tok.indexOf('='))),
334                       URLDecoder.decode(tok.substring(tok.indexOf('=')+1)));
335             }
336             ((GMail)cache.get((String)h.get("email"), (String)h.get("pass"))).setCaptcha(h);
337             conn.println("HTTP/1.0 200 OK\r\n");
338             conn.println("Content-Type: text/plain\r\n");
339             conn.println("\r\n");
340             conn.println("<html><body><script>window.close()</script></body></html>\r\n");
341         } else {
342             conn.println("HTTP/1.0 500 Error\r\n\r\n");
343         }
344         conn.flush();
345         conn.close();
346     }
347
348     public void setCaptcha(Hash h) {
349         captcha = (String)h.get("captcha");
350         ctoken = (String)h.get("ctoken");
351         Log.warn(GMail.class, "captcha = " + captcha);
352         Log.warn(GMail.class, "ctoken = " + ctoken);
353         Log.warn(GMail.class, "initting..." + ctoken);
354         try {
355             getCookies();
356             Log.warn(GMail.class, "  done..." + ctoken);
357         } catch (Exception e) {
358             Log.error(this, e);
359         }
360     }
361
362     // Constants //////////////////////////////////////////////////////////////////////////////
363
364     public static final String login = "https://www.google.com/accounts/ServiceLoginBoxAuth";
365     public static final String gmail = "https://gmail.google.com/gmail";
366 }