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