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.
5 package org.ibex.mail.protocol;
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.*;
15 import org.ibex.mail.target.*;
21 public class GMail extends Account {
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];
34 // Constructor, Pooling ///////////////////////////////////////////////////////////////////////////
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);
43 public void close() { cache.remove(email, password); invalid = true; }
45 private static Hash cache = new Hash();
46 static { HTTP.userAgent = "Mozilla/5.0 (compatible;)"; }
47 public static GMail getGMail(String email, String pass) {
49 GMail g = (GMail)cache.get(email, pass);
50 if (g == null) cache.put(email, pass, g = new GMail(email, pass));
52 } catch (Exception e) {
53 Log.error(GMail.class, e);
58 // IMAP Interface //////////////////////////////////////////////////////////////////////////////
60 public IMAP.Server getIMAP() { return imap; }
61 private class GMailIMAP implements IMAP.Server {
63 private String query = "?search=inbox&start=0&view=tl";
64 private int validity = new Random().nextInt();
66 private IMAP.Client client;
67 public void setClient(IMAP.Client client) { this.client = client; }
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) { }
75 public void unselect() { summaries = new Summary[0]; }
76 public void close() { summaries = new Summary[0]; }
78 public void noop() { check(); }
79 public void expunge() { }
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) { }
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;
94 public void append(String m, int flags, Date arrival, String body) { }
95 public void copy(Query q, String to) { }
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();
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();
112 query = "?search=query&q="+URLEncoder.encode(mailbox)+"&start=0&view=tl";
113 if (!query.equals(oldquery)) check();
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);
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();
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) { }
156 Log.info(GMail.class, "fetch " + summaries[i].subject);
157 client.fetch(i+1, 0, m.size(), m,/* summaries[i].getIntId()*/ i);
159 } catch (Exception e) { Log.warn(this, e); }
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 count() { return summaries.length; }
166 public int maxuid() { return summaries.length; }
167 public int uidNext(String mailbox) { return summaries.length+1; }
168 public int uidValidity(String mailbox) { return validity; }
171 public void getCookies() throws IOException {
172 jar = new HTTP.Cookie.Jar();
174 "continue=" + URLEncoder.encode(gmail) +
176 "&Email=" + URLEncoder.encode(user) +
177 "&Passwd=" + password +
179 (captcha != null ? "&captcha="+URLEncoder.encode(captcha) : "") +
180 (captcha != null ? "&ctoken="+URLEncoder.encode(ctoken) : "");
181 Log.info("[request]", params);
182 HTTP http = captcha==null ? new HTTP(login+"?"+params) : new HTTP(login);
183 InputStream reply = captcha==null ?
184 http.GET(null, jar) :
185 http.POST("application/x-www-form-urlencoded", params, null, jar);
186 String result = new String(InputStreamToByteArray.convert(reply));
187 System.err.println(result);
190 if (result.indexOf("top.location") == -1) { doCaptcha(result); return; }
191 result = result.substring(result.indexOf("top.location"));
192 result = result.substring(result.indexOf("CheckCookie?continue=") + "CheckCookie?continue=".length());
193 result = result.substring(0, result.indexOf('\"'));
194 result = URLDecoder.decode(result);
195 Log.warn("[]", "getting " + result);
197 // just need the cookie off of this page
198 InputStreamToByteArray.convert(new HTTP(result).GET(null, jar));
200 Log.warn("[]", "done");
203 Message captchaMessage = null;
204 public void doCaptcha(String result) throws IOException {
205 Log.warn(GMail.class,"no relocator found; checking for captcha");
206 ctoken = result.substring(result.indexOf("id=\"ctoken\" value=\"") + "id=\"ctoken\" value=\"".length());
207 ctoken = ctoken.substring(0, ctoken.indexOf("\""));
208 String image = result.substring(result.indexOf("Captcha?"));
209 image = image.substring(0, image.indexOf("\""));
211 "From: google@google.com\r\n" +
212 "To: you@yourself.com\r\n" +
213 "Subject: Captcha\r\n" +
214 "Date: Mon Aug 30 19:05:40 PDT 2004\r\n" +
215 "Content-Type: text/html\r\n" +
218 "Hi there. Google is lame; please type in the word you see below and " +
219 "click submit. You might have to click 'get mail' again after that.<br> " +
220 "<img src=\"https://www.google.com/accounts/"+image+"\">\r\n" +
221 "<form method=get action=http://gmail.megacz.com:8099/Captcha>\r\n"+
222 " <input type=text name=captcha>\r\n"+
223 " <input type=hidden name=email value=\""+email+"\">\r\n"+
224 " <input type=hidden name=pass value="+password+">\r\n"+
225 " <input type=hidden name=ctoken value=\""+ctoken+"\">\r\n"+
226 " <input type=submit>\r\n"+
228 "</body></html>\r\n";
230 captchaMessage = Message.newMessage(new Stream(str));
231 } catch (Message.Malformed e) {
233 throw new IOException(e.toString());
237 public synchronized Summary[] query(String query) {
238 if (captcha != null) return new Summary[0];
240 Log.info(GMail.class, "query: " + query);
241 JSArray ret = http(gmail + query, jar);
242 Hashtable h = new Hashtable();
243 for(int i=0; i<ret.size(); i++) {
244 JSArray j = (JSArray)ret.get(i);
245 if (j.get(0).equals("t")) {
246 for(int k=1; k<j.size(); k++) getSummary((String)((JSArray)j.get(k)).get(0), h);
247 } else if (j.get(0).equals("ct") && labels.length == 0) {
249 j = (JSArray)j.get(1);
250 for(int k=0; k<j.size(); k++) v.addElement(((JSArray)j.get(k)).get(0));
251 v.copyInto(labels = new String[v.size()]);
254 Enumeration e = h.keys();
256 while(e.hasMoreElements()) v.addElement(h.get(e.nextElement()));
257 return summaries = (Summary[])v.copyInto(new Summary[v.size()]);
258 } catch (Exception e) {
260 return new Summary[0];
264 public void getSummary(String id, Hashtable ret) {
266 JSArray js2 = http(gmail + "?search=query&start=0&view=cv&q=in:anywhere&th=" + URLEncoder.encode(id), jar);
267 for(int i2=0; i2<js2.size(); i2++) {
268 JSArray args = (JSArray)js2.get(i2);
269 if (!args.get(0).equals("mi")) continue;
270 Summary sum = new Summary(args);
271 Log.info(GMail.class, "summary: " + sum.subject);
272 ret.put(sum.id, sum);
274 } catch (Exception e) {
279 private class Summary {
282 public String subject;
285 public Message message = null;
287 public int getIntId() { return Math.abs(Integer.parseInt(id.toLowerCase().substring(id.length()-7), 16)); }
289 public Message getMessage() throws Message.Malformed, IOException {
290 if (message != null) return message;
292 new Stream(new HTTP(gmail+"?search=query&start=0&view=om&th=" + URLEncoder.encode(id)).GET(null, jar));
294 return message = Message.newMessage(thestream);
297 public Summary(JSArray m) {
298 try { this.date = new Date(m.get(9).toString()); } catch (Exception e) { this.date = null; }
299 this.id = m.get(3).toString();
300 this.to = Address.parse(m.get(8).toString() + " <" + m.get(10).toString() + ">");
301 this.from = Address.parse(m.get(6).toString()+"<"+m.get(7).toString()+">");
302 this.subject = m.get(15).toString();
306 public JSArray http(String url, HTTP.Cookie.Jar jar) throws JSExn, IOException {
307 Stream stream = new Stream(new HTTP(url).GET(null, jar));
308 boolean inscript = false;
309 StringBuffer buf = new StringBuffer("var ret = []; var D = function(x){ret.push(x);};");
311 while((s = stream.readln()) != null) {
312 if (s.indexOf("<script>") != -1) { inscript = true; continue; }
313 if (s.indexOf("</script>") != -1) { inscript = false; continue; }
314 if (inscript) buf.append(s);
316 buf.append("return ret;");
317 synchronized(GMail.class) {
318 JS js = JSU.fromReader("google", 0, new StringReader(buf.toString()));
319 return (JSArray)js.call(null, JSU.emptyArgs);
324 // HTTP Listener for Captcha requests //////////////////////////////////////////////////////////////////////////////
326 public static void handleRequest(Connection conn) {
328 for(String s = conn.readln(); s != null && s.length() > 0; s = conn.readln()) {
329 if (top == null) top = s;
330 Log.warn(GMail.class, s);
332 if (top.startsWith("GET /Captcha")) {
333 top = top.substring(top.indexOf('?')+1);
334 top = top.substring(0, top.indexOf(' '));
335 StringTokenizer st = new StringTokenizer(top, "&");
337 while(st.hasMoreTokens()) {
338 String tok = st.nextToken();
339 h.put(URLDecoder.decode(tok.substring(0, tok.indexOf('='))),
340 URLDecoder.decode(tok.substring(tok.indexOf('=')+1)));
342 ((GMail)cache.get((String)h.get("email"), (String)h.get("pass"))).setCaptcha(h);
343 conn.println("HTTP/1.0 200 OK\r\n");
344 conn.println("Content-Type: text/plain\r\n");
345 conn.println("\r\n");
346 conn.println("<html><body><script>window.close()</script></body></html>\r\n");
348 conn.println("HTTP/1.0 500 Error\r\n\r\n");
354 public void setCaptcha(Hash h) {
355 captcha = (String)h.get("captcha");
356 ctoken = (String)h.get("ctoken");
357 Log.warn(GMail.class, "captcha = " + captcha);
358 Log.warn(GMail.class, "ctoken = " + ctoken);
359 Log.warn(GMail.class, "initting..." + ctoken);
362 Log.warn(GMail.class, " done..." + ctoken);
363 } catch (Exception e) {
368 // Constants //////////////////////////////////////////////////////////////////////////////
370 public static final String login = "https://www.google.com/accounts/ServiceLoginBoxAuth";
371 public static final String gmail = "https://gmail.google.com/gmail";