]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/testUtils/TestEmailReceiver.java
upd: rename sendmail to sendMail
[gigi.git] / tests / org / cacert / gigi / testUtils / TestEmailReceiver.java
1 package org.cacert.gigi.testUtils;
2
3 import java.io.DataInputStream;
4 import java.io.DataOutputStream;
5 import java.io.IOException;
6 import java.net.Socket;
7 import java.net.SocketAddress;
8 import java.net.URL;
9 import java.net.URLConnection;
10 import java.util.concurrent.LinkedBlockingQueue;
11 import java.util.concurrent.TimeUnit;
12 import java.util.regex.Matcher;
13 import java.util.regex.Pattern;
14
15 import org.cacert.gigi.email.EmailProvider;
16 import org.cacert.gigi.email.TestEmailProvider;
17
18 /**
19  * This class reveives emails from the current system under test. It is the
20  * counterpart to the {@link TestEmailProvider} who is loaded into the system to
21  * intercept the emails. This class resides in the VM that executes the
22  * testcases and supplies the intercepted emails to the current test case.
23  */
24 public final class TestEmailReceiver extends EmailProvider implements Runnable, MailReceiver {
25
26     /**
27      * An email that has been intercepted.
28      */
29     public static class TestMail {
30
31         String to;
32
33         String subject;
34
35         String message;
36
37         String from;
38
39         String replyto;
40
41         public TestMail(String to, String subject, String message, String from, String replyto) {
42             this.to = to;
43             this.subject = subject;
44             this.message = message;
45             this.from = from;
46             this.replyto = replyto;
47         }
48
49         public String getTo() {
50             return to;
51         }
52
53         public String getSubject() {
54             return subject;
55         }
56
57         public String getMessage() {
58             return message;
59         }
60
61         public String getFrom() {
62             return from;
63         }
64
65         public String getReplyto() {
66             return replyto;
67         }
68
69         public String extractLink() {
70             Pattern link = Pattern.compile("https?://[^\\s]+(?=\\s)");
71             Matcher m = link.matcher(getMessage());
72             m.find();
73             return m.group(0);
74         }
75
76         public void verify() throws IOException {
77             String link = extractLink();
78             String[] parts = link.split("\\?");
79             URL u = new URL("https://" + ManagedTest.getServerName() + "/verify?" + parts[1]);
80
81             URLConnection csrfConn = u.openConnection();
82             String csrf = ManagedTest.getCSRF(csrfConn, 0);
83
84             u = new URL("https://" + ManagedTest.getServerName() + "/verify");
85             URLConnection uc = u.openConnection();
86             ManagedTest.cookie(uc, ManagedTest.stripCookie(csrfConn.getHeaderField("Set-Cookie")));
87             uc.setDoOutput(true);
88             uc.getOutputStream().write((parts[1] + "&csrf=" + csrf).getBytes("UTF-8"));
89             uc.connect();
90             uc.getInputStream().close();
91         }
92
93     }
94
95     private Socket s;
96
97     private DataInputStream dis;
98
99     private DataOutputStream dos;
100
101     /**
102      * Creates a new TestEmailReceiver based on the address where the
103      * {@link TestEmailProvider} is listening. This class is only ready after
104      * {@link #start()} has been called.
105      * 
106      * @param target
107      *            the address where the {@link TestEmailProvider} is listening.
108      * @throws IOException
109      *             if the connection cannot be opened
110      */
111     public TestEmailReceiver(SocketAddress target) throws IOException {
112         s = new Socket();
113         s.connect(target);
114         s.setKeepAlive(true);
115         s.setSoTimeout(1000 * 60 * 60);
116         dis = new DataInputStream(s.getInputStream());
117         dos = new DataOutputStream(s.getOutputStream());
118         setInstance(this);
119     }
120
121     /**
122      * Spawns a new {@link Thread} that reads incoming {@link TestMail}s.
123      * 
124      * @see #destroy()
125      */
126     public void start() {
127         new Thread(this, "Mail receiver").start();
128     }
129
130     private LinkedBlockingQueue<TestMail> mails = new LinkedBlockingQueue<TestEmailReceiver.TestMail>();
131
132     /**
133      * Retrieves an outgoing mail from the system. The method will return a
134      * {@link TestMail} or fail.
135      * 
136      * @return The intercepted {@link TestMail}
137      * @see #poll()
138      */
139     @Override
140     public TestMail receive() {
141         TestMail poll;
142
143         try {
144             poll = mails.poll(60, TimeUnit.SECONDS);
145
146         } catch (InterruptedException e) {
147             throw new AssertionError("Interrupted while receiving mails");
148         }
149         if (poll == null) {
150             throw new AssertionError("Mail receiving timed out");
151         }
152
153         return poll;
154     }
155
156     /**
157      * Retrieves an outgoing mail from the system or returns <code>null</code>
158      * if there was no mail sent in 30 seconds.
159      * 
160      * @return The intercepted {@link TestMail} or <code>null</code> if no mail
161      *         has been sent.
162      * @see #receive()
163      */
164     public TestMail poll() {
165         return mails.poll();
166     }
167
168     @Override
169     public void run() {
170         try {
171             while (true) {
172                 String type = dis.readUTF();
173                 if (type.equals("mail")) {
174                     String to = dis.readUTF();
175                     String subject = dis.readUTF();
176                     String message = dis.readUTF();
177                     String from = dis.readUTF();
178                     String replyto = dis.readUTF();
179                     mails.add(new TestMail(to, subject, message, from, replyto));
180                 } else if (type.equals("challengeAddrBox")) {
181                     String email = dis.readUTF();
182                     dos.writeUTF(quickEmailCheck(email));
183                     dos.flush();
184                 } else if (type.equals("ping")) {
185                 } else {
186                     System.err.println("Unknown type: " + type);
187                 }
188             }
189         } catch (IOException e) {
190             if ( !closed) {
191                 e.printStackTrace();
192             }
193         }
194
195     }
196
197     private String quickEmailCheck(String email) throws IOException {
198         if (approveRegex.matcher(email).matches()) {
199             return "OK";
200         } else {
201             return error;
202         }
203     }
204
205     String error = "FAIL";
206
207     /**
208      * Sets the error that will be sent back to incoming "fast mail checks" that
209      * only check for the availability of a mailbox.
210      * 
211      * @param error
212      *            the error Massage to return in
213      *            {@link EmailProvider#checkEmailServer(int, String)}
214      */
215     public void setEmailCheckError(String error) {
216         this.error = error;
217     }
218
219     private Pattern approveRegex = Pattern.compile(".*");
220
221     /**
222      * Specifies a pattern that will be used for incoming
223      * {@link EmailProvider#checkEmailServer(int, String)} calls to determine
224      * whether the mailbox should exist.
225      * 
226      * @param approveRegex
227      *            the regex that will perform the check
228      */
229     public void setApproveRegex(Pattern approveRegex) {
230         this.approveRegex = approveRegex;
231     }
232
233     /**
234      * Removes all queued mails.
235      */
236     @Override
237     public void clearMails() {
238         mails.clear();
239     }
240
241     /**
242      * Resets this class to its initial state
243      * 
244      * @see #clearMails()
245      * @see #setApproveRegex(Pattern)
246      * @see #setEmailCheckError(String)
247      */
248     public void reset() {
249         clearMails();
250         error = "FAIL";
251         approveRegex = Pattern.compile(".*");
252     }
253
254     private boolean closed = false;
255
256     /**
257      * stops reading for incoming messages
258      * 
259      * @see #start()
260      */
261     public void destroy() {
262         try {
263             closed = true;
264             s.close();
265         } catch (IOException e) {
266             e.printStackTrace();
267         }
268     }
269
270     @Override
271     public String checkEmailServer(int forUid, String address) throws IOException {
272         return quickEmailCheck(address);
273     }
274
275     @Override
276     public void sendMail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
277         mails.add(new TestMail(to, subject, message, from, replyto));
278     }
279
280 }