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 private final static Pattern headerPattern = Pattern.compile("[^A-Za-z0-9-]+: .+"); 47 48 private class AcceptThread implements Runnable { 49 private void handleSession(SMTPSession session) throws IOException { 50 session.sendCommand("220 localhost SMTP", ehloPattern); 51 session.sendCommand("250 HELP", mailFromPattern); 52 session.sendCommand("250 FROM OK", rcptToPattern); 53 session.sendCommand("250 RCPT OK", dataPattern); 54 session.sendCommand("354 Enter message now, end with ."); 55 var message = session.readLinesUntil(messageEndPattern); 56 session.sendCommand("250 MESSAGE OK", quitPattern); 57 58 // Email headers are only 7-bit safe, ensure that we break any high ascii passing through 59 var inHeader = true; 60 var mailBody = new StringBuilder(); 61 for (var line : message) { 62 if (inHeader) { 63 var headerMatcher = headerPattern.matcher(line); 64 if (headerMatcher.matches()) { 65 var quoteMatcher = encodeQuotedPrintablePattern.matcher(String.join("\n", message)); 66 var ascii7line = quoteMatcher.replaceAll(mo -> "HIGH_ASCII"); 67 mailBody.append(ascii7line); 68 mailBody.append("\n"); 69 continue; 70 } else { 71 inHeader = false; 72 } 73 } 74 if (line.startsWith(".")) { 75 line = line.substring(1); 76 } 77 mailBody.append(line); 78 mailBody.append("\n"); 79 } 80 81 var email = Email.parse(mailBody.toString()); 82 emails.addLast(email); 83 } 84 85 @Override 86 public void run() { 87 while (!serverSocket.isClosed()) { 88 try { 89 try (var socket = serverSocket.accept(); 90 var input = new InputStreamReader(socket.getInputStream()); 91 var output = new OutputStreamWriter(socket.getOutputStream())) { 92 var session = new SMTPSession(input, output, Duration.ofMinutes(10)); 93 handleSession(session); 94 } 95 } catch (SocketException e) { 96 // Socket closed 97 } catch (IOException e) { 98 throw new UncheckedIOException(e); 99 } 100 } 101 } 102 } 103 104 public SMTPServer() throws IOException { 105 serverSocket = new ServerSocket(0); 106 acceptThread = new Thread(new AcceptThread()); 107 acceptThread.start(); 108 } 109 110 public String address() { 111 var host = serverSocket.getInetAddress(); 112 return InetAddress.getLoopbackAddress().getHostAddress() + ":" + serverSocket.getLocalPort(); 113 } 114 115 public Email receive(Duration timeout) { 116 var start = Instant.now(); 117 while (emails.isEmpty() && start.plus(timeout).isAfter(Instant.now())) { 118 try { 119 Thread.sleep(10); 120 } catch (InterruptedException ignored) { 121 } 122 } 123 124 if (emails.isEmpty()) { 125 throw new RuntimeException("No email received"); 126 } 127 return emails.removeFirst(); 128 } 129 130 @Override 131 public void close() throws IOException { 132 serverSocket.close(); 133 } 134 }