POP3.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.net.pop3;

  18. import java.io.BufferedReader;
  19. import java.io.BufferedWriter;
  20. import java.io.EOFException;
  21. import java.io.IOException;
  22. import java.io.InputStreamReader;
  23. import java.io.OutputStreamWriter;
  24. import java.nio.charset.Charset;
  25. import java.nio.charset.StandardCharsets;
  26. import java.util.ArrayList;
  27. import java.util.List;

  28. import org.apache.commons.net.MalformedServerReplyException;
  29. import org.apache.commons.net.ProtocolCommandSupport;
  30. import org.apache.commons.net.SocketClient;
  31. import org.apache.commons.net.io.CRLFLineReader;
  32. import org.apache.commons.net.util.NetConstants;

  33. /**
  34.  * The POP3 class is not meant to be used by itself and is provided only so that you may easily implement your own POP3 client if you so desire. If you have no
  35.  * need to perform your own implementation, you should use {@link org.apache.commons.net.pop3.POP3Client}.
  36.  * <p>
  37.  * Rather than list it separately for each method, we mention here that every method communicating with the server and throwing an IOException can also throw a
  38.  * {@link org.apache.commons.net.MalformedServerReplyException} , which is a subclass of IOException. A MalformedServerReplyException will be thrown when the
  39.  * reply received from the server deviates enough from the protocol specification that it cannot be interpreted in a useful manner despite attempts to be as
  40.  * lenient as possible.
  41.  *
  42.  *
  43.  * @see POP3Client
  44.  * @see org.apache.commons.net.MalformedServerReplyException
  45.  */

  46. public class POP3 extends SocketClient {
  47.     /** The default POP3 port. Set to 110 according to RFC 1288. */
  48.     public static final int DEFAULT_PORT = 110;
  49.     /**
  50.      * A constant representing the state where the client is not yet connected to a POP3 server.
  51.      */
  52.     public static final int DISCONNECTED_STATE = -1;
  53.     /** A constant representing the POP3 authorization state. */
  54.     public static final int AUTHORIZATION_STATE = 0;
  55.     /** A constant representing the POP3 transaction state. */
  56.     public static final int TRANSACTION_STATE = 1;
  57.     /** A constant representing the POP3 update state. */
  58.     public static final int UPDATE_STATE = 2;

  59.     static final String OK = "+OK";
  60.     // The reply indicating intermediate response to a command.
  61.     static final String OK_INT = "+ ";
  62.     static final String ERROR = "-ERR";

  63.     // We have to ensure that the protocol communication is in ASCII,
  64.     // but we use ISO-8859-1 just in case 8-bit characters cross
  65.     // the wire.
  66.     static final Charset DEFAULT_ENCODING = StandardCharsets.ISO_8859_1;

  67.     private int popState;
  68.     BufferedWriter writer;

  69.     BufferedReader reader;
  70.     int replyCode;
  71.     String lastReplyLine;
  72.     List<String> replyLines;

  73.     /**
  74.      * A ProtocolCommandSupport object used to manage the registering of ProtocolCommandListeners and the firing of ProtocolCommandEvents.
  75.      */
  76.     protected ProtocolCommandSupport _commandSupport_;

  77.     /**
  78.      * The default POP3Client constructor. Initializes the state to <code>DISCONNECTED_STATE</code>.
  79.      */
  80.     public POP3() {
  81.         setDefaultPort(DEFAULT_PORT);
  82.         popState = DISCONNECTED_STATE;
  83.         reader = null;
  84.         writer = null;
  85.         replyLines = new ArrayList<>();
  86.         _commandSupport_ = new ProtocolCommandSupport(this);
  87.     }

  88.     /**
  89.      * Performs connection initialization and sets state to <code>AUTHORIZATION_STATE</code>.
  90.      */
  91.     @Override
  92.     protected void _connectAction_() throws IOException {
  93.         super._connectAction_();
  94.         reader = new CRLFLineReader(new InputStreamReader(_input_, DEFAULT_ENCODING));
  95.         writer = new BufferedWriter(new OutputStreamWriter(_output_, DEFAULT_ENCODING));
  96.         getReply();
  97.         setState(AUTHORIZATION_STATE);
  98.     }

  99.     /**
  100.      * Disconnects the client from the server, and sets the state to <code>DISCONNECTED_STATE</code>. The reply text information from the last issued command
  101.      * is voided to allow garbage collection of the memory used to store that information.
  102.      *
  103.      * @throws IOException If there is an error in disconnecting.
  104.      */
  105.     @Override
  106.     public void disconnect() throws IOException {
  107.         super.disconnect();
  108.         reader = null;
  109.         writer = null;
  110.         lastReplyLine = null;
  111.         replyLines.clear();
  112.         setState(DISCONNECTED_STATE);
  113.     }

  114.     /**
  115.      * Retrieves the additional lines of a multi-line server reply.
  116.      *
  117.      * @throws IOException on error
  118.      */
  119.     public void getAdditionalReply() throws IOException {
  120.         String line;

  121.         line = reader.readLine();
  122.         while (line != null) {
  123.             replyLines.add(line);
  124.             if (line.equals(".")) {
  125.                 break;
  126.             }
  127.             line = reader.readLine();
  128.         }
  129.     }

  130.     /**
  131.      * Provide command support to super-class
  132.      */
  133.     @Override
  134.     protected ProtocolCommandSupport getCommandSupport() {
  135.         return _commandSupport_;
  136.     }

  137.     private void getReply() throws IOException {
  138.         final String line;

  139.         replyLines.clear();
  140.         line = reader.readLine();

  141.         if (line == null) {
  142.             throw new EOFException("Connection closed without indication.");
  143.         }

  144.         if (line.startsWith(OK)) {
  145.             replyCode = POP3Reply.OK;
  146.         } else if (line.startsWith(ERROR)) {
  147.             replyCode = POP3Reply.ERROR;
  148.         } else if (line.startsWith(OK_INT)) {
  149.             replyCode = POP3Reply.OK_INT;
  150.         } else {
  151.             throw new MalformedServerReplyException("Received invalid POP3 protocol response from server." + line);
  152.         }

  153.         replyLines.add(line);
  154.         lastReplyLine = line;

  155.         fireReplyReceived(replyCode, getReplyString());
  156.     }

  157.     /**
  158.      * Returns the reply to the last command sent to the server. The value is a single string containing all the reply lines including newlines. If the reply is
  159.      * a single line, but its format ndicates it should be a multiline reply, then you must call {@link #getAdditionalReply getAdditionalReply() } to fetch the
  160.      * rest of the reply, and then call <code>getReplyString</code> again. You only have to worry about this if you are implementing your own client using the
  161.      * {@link #sendCommand sendCommand } methods.
  162.      *
  163.      * @return The last server response.
  164.      */
  165.     public String getReplyString() {
  166.         final StringBuilder buffer = new StringBuilder(256);

  167.         for (final String entry : replyLines) {
  168.             buffer.append(entry);
  169.             buffer.append(SocketClient.NETASCII_EOL);
  170.         }

  171.         return buffer.toString();
  172.     }

  173.     /**
  174.      * Returns an array of lines received as a reply to the last command sent to the server. The lines have end of lines truncated. If the reply is a single
  175.      * line, but its format ndicates it should be a multiline reply, then you must call {@link #getAdditionalReply getAdditionalReply() } to fetch the rest of
  176.      * the reply, and then call <code>getReplyStrings</code> again. You only have to worry about this if you are implementing your own client using the
  177.      * {@link #sendCommand sendCommand } methods.
  178.      *
  179.      * @return The last server response.
  180.      */
  181.     public String[] getReplyStrings() {
  182.         return replyLines.toArray(NetConstants.EMPTY_STRING_ARRAY);
  183.     }

  184.     /**
  185.      * Returns the current POP3 client state.
  186.      *
  187.      * @return The current POP3 client state.
  188.      */
  189.     public int getState() {
  190.         return popState;
  191.     }

  192.     /**
  193.      * Removes a ProtocolCommandListener.
  194.      *
  195.      * Delegates this incorrectly named method - removeProtocolCommandistener (note the missing "L")- to the correct method
  196.      * {@link SocketClient#removeProtocolCommandListener}
  197.      *
  198.      * @param listener The ProtocolCommandListener to remove
  199.      */
  200.     public void removeProtocolCommandistener(final org.apache.commons.net.ProtocolCommandListener listener) {
  201.         removeProtocolCommandListener(listener);
  202.     }

  203.     /**
  204.      * Sends a command with no arguments to the server and returns the reply code.
  205.      *
  206.      * @param command The POP3 command to send (one of the POP3Command constants).
  207.      * @return The server reply code (either {@code POP3Reply.OK}, {@code POP3Reply.ERROR} or {@code POP3Reply.OK_INT}).
  208.      * @throws IOException on error
  209.      */
  210.     public int sendCommand(final int command) throws IOException {
  211.         return sendCommand(POP3Command.commands[command], null);
  212.     }

  213.     /**
  214.      * Sends a command an arguments to the server and returns the reply code.
  215.      *
  216.      * @param command The POP3 command to send (one of the POP3Command constants).
  217.      * @param args    The command arguments.
  218.      * @return The server reply code (either {@code POP3Reply.OK}, {@code POP3Reply.ERROR} or {@code POP3Reply.OK_INT}).
  219.      * @throws IOException on error
  220.      */
  221.     public int sendCommand(final int command, final String args) throws IOException {
  222.         return sendCommand(POP3Command.commands[command], args);
  223.     }

  224.     /**
  225.      * Sends a command with no arguments to the server and returns the reply code.
  226.      *
  227.      * @param command The POP3 command to send.
  228.      * @return The server reply code (either {@code POP3Reply.OK}, {@code POP3Reply.ERROR} or {@code POP3Reply.OK_INT}).
  229.      * @throws IOException on error
  230.      */
  231.     public int sendCommand(final String command) throws IOException {
  232.         return sendCommand(command, null);
  233.     }

  234.     /**
  235.      * Sends a command an arguments to the server and returns the reply code.
  236.      *
  237.      * @param command The POP3 command to send.
  238.      * @param args    The command arguments.
  239.      * @return The server reply code (either {@code POP3Reply.OK}, {@code POP3Reply.ERROR} or {@code POP3Reply.OK_INT}).
  240.      * @throws IOException on error
  241.      */
  242.     public int sendCommand(final String command, final String args) throws IOException {
  243.         if (writer == null) {
  244.             throw new IllegalStateException("Socket is not connected");
  245.         }
  246.         final StringBuilder __commandBuffer = new StringBuilder();
  247.         __commandBuffer.append(command);

  248.         if (args != null) {
  249.             __commandBuffer.append(' ');
  250.             __commandBuffer.append(args);
  251.         }
  252.         __commandBuffer.append(SocketClient.NETASCII_EOL);

  253.         final String message = __commandBuffer.toString();
  254.         writer.write(message);
  255.         writer.flush();

  256.         fireCommandSent(command, message);

  257.         getReply();
  258.         return replyCode;
  259.     }

  260.     /**
  261.      * Sets the internal POP3 state.
  262.      *
  263.      * @param state the new state. This must be one of the <code>_STATE</code> constants.
  264.      */
  265.     public void setState(final int state) {
  266.         popState = state;
  267.     }
  268. }