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 mailBody.append(line); 75 mailBody.append("\n"); 76 } 77 78 var email = Email.parse(mailBody.toString()); 79 emails.addLast(email); 80 } 81 82 @Override 83 public void run() { 84 while (!serverSocket.isClosed()) { 85 try { 86 try (var socket = serverSocket.accept(); 87 var input = new InputStreamReader(socket.getInputStream()); 88 var output = new OutputStreamWriter(socket.getOutputStream())) { 89 var session = new SMTPSession(input, output, Duration.ofMinutes(10)); 90 handleSession(session); 91 } 92 } catch (SocketException e) { 93 // Socket closed 94 } catch (IOException e) { 95 throw new UncheckedIOException(e); 96 } 97 } 98 } 99 } 100 101 public SMTPServer() throws IOException { 102 serverSocket = new ServerSocket(0); 103 acceptThread = new Thread(new AcceptThread()); 104 acceptThread.start(); 105 } 106 107 public String address() { 108 var host = serverSocket.getInetAddress(); 109 return InetAddress.getLoopbackAddress().getHostAddress() + ":" + serverSocket.getLocalPort(); 110 } 111 112 public Email receive(Duration timeout) { 113 var start = Instant.now(); 114 while (emails.isEmpty() && start.plus(timeout).isAfter(Instant.now())) { 115 try { 116 Thread.sleep(10); 117 } catch (InterruptedException ignored) { 118 } 119 } 120 121 if (emails.isEmpty()) { 122 throw new RuntimeException("No email received"); 123 } 124 return emails.removeFirst(); 125 } 126 127 @Override 128 public void close() throws IOException { 129 serverSocket.close(); 130 } 131 }