1 /*
  2  * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 package org.openjdk.skara.test;
 24 
 25 import org.openjdk.skara.email.*;
 26 
 27 import java.io.*;
 28 import java.net.*;
 29 import java.time.*;
 30 import java.util.concurrent.ConcurrentLinkedDeque;
 31 import java.util.regex.Pattern;
 32 
 33 public class SMTPServer implements AutoCloseable {
 34     private final ServerSocket serverSocket;
 35     private final Thread acceptThread;
 36     private final ConcurrentLinkedDeque<Email> emails = new ConcurrentLinkedDeque<>();
 37 
 38     private static Pattern ehloPattern = Pattern.compile("^EHLO .*$");
 39     private static Pattern mailFromPattern = Pattern.compile("^MAIL FROM:.*$");
 40     private static Pattern rcptToPattern = Pattern.compile("^RCPT TO:<.*$");
 41     private static Pattern dataPattern = Pattern.compile("^DATA$");
 42     private static Pattern messageEndPattern = Pattern.compile("^\\.$");
 43     private static Pattern quitPattern = Pattern.compile("^QUIT$");
 44 
 45     private final static Pattern encodeQuotedPrintablePattern = Pattern.compile("([^\\x00-\\x7f]+)");
 46 
 47     private class AcceptThread implements Runnable {
 48         private void handleSession(SMTPSession session) throws IOException {
 49             session.sendCommand("220 localhost SMTP", ehloPattern);
 50             session.sendCommand("250 HELP", mailFromPattern);
 51             session.sendCommand("250 FROM OK", rcptToPattern);
 52             session.sendCommand("250 RCPT OK", dataPattern);
 53             session.sendCommand("354 Enter message now, end with .");
 54             var message = session.readLinesUntil(messageEndPattern);
 55             session.sendCommand("250 MESSAGE OK", quitPattern);
 56 
 57             // SMTP is only 7-bit safe, ensure that we break any high ascii passing through here
 58             var quoteMatcher = encodeQuotedPrintablePattern.matcher(String.join("\n", message));
 59             var ascii7message = quoteMatcher.replaceAll(mo -> "HIGH_ASCII");
 60 
 61             var email = Email.parse(ascii7message);
 62             emails.addLast(email);
 63         }
 64 
 65         @Override
 66         public void run() {
 67             while (!serverSocket.isClosed()) {
 68                 try {
 69                     try (var socket = serverSocket.accept();
 70                          var input = new InputStreamReader(socket.getInputStream());
 71                          var output = new OutputStreamWriter(socket.getOutputStream())) {
 72                         var session = new SMTPSession(input, output);
 73                         handleSession(session);
 74                     }
 75                 } catch (SocketException e) {
 76                     // Socket closed
 77                 } catch (IOException e) {
 78                     throw new UncheckedIOException(e);
 79                 }
 80             }
 81         }
 82     }
 83 
 84     public SMTPServer() throws IOException {
 85         serverSocket = new ServerSocket(0);
 86         acceptThread = new Thread(new AcceptThread());
 87         acceptThread.start();
 88     }
 89 
 90     public String address() {
 91         var host = serverSocket.getInetAddress();
 92         return InetAddress.getLoopbackAddress().getHostAddress() + ":" + serverSocket.getLocalPort();
 93     }
 94 
 95     public Email receive(Duration timeout) {
 96         var start = Instant.now();
 97         while (emails.isEmpty() && start.plus(timeout).isAfter(Instant.now())) {
 98             try {
 99                 Thread.sleep(10);
100             } catch (InterruptedException ignored) {
101             }
102         }
103 
104         if (emails.isEmpty()) {
105             throw new RuntimeException("No email received");
106         }
107         return emails.removeFirst();
108     }
109 
110     @Override
111     public void close() throws IOException {
112         serverSocket.close();
113     }
114 }