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