1/*
2 * Copyright 2007 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.mockftpserver.core.server;
17
18import org.apache.log4j.Logger;
19import org.mockftpserver.core.MockFtpServerException;
20import org.mockftpserver.core.command.Command;
21import org.mockftpserver.core.command.CommandHandler;
22import org.mockftpserver.core.session.DefaultSession;
23import org.mockftpserver.core.session.Session;
24import org.mockftpserver.core.socket.DefaultServerSocketFactory;
25import org.mockftpserver.core.socket.ServerSocketFactory;
26import org.mockftpserver.core.util.Assert;
27
28import java.io.IOException;
29import java.net.ServerSocket;
30import java.net.Socket;
31import java.net.SocketTimeoutException;
32import java.util.HashMap;
33import java.util.Iterator;
34import java.util.Map;
35import java.util.ResourceBundle;
36
37/**
38 * This is the abstract superclass for "mock" implementations of an FTP Server,
39 * suitable for testing FTP client code or standing in for a live FTP server. It supports
40 * the main FTP commands by defining handlers for each of the corresponding low-level FTP
41 * server commands (e.g. RETR, DELE, LIST). These handlers implement the {@link org.mockftpserver.core.command.CommandHandler}
42 * interface.
43 * <p/>
44 * By default, mock FTP Servers bind to the server control port of 21. You can use a different server
45 * control port by setting the the <code>serverControlPort</code> property. This is usually necessary
46 * when running on Unix or some other system where that port number is already in use or cannot be bound
47 * from a user process.
48 * <p/>
49 * <h4>Command Handlers</h4>
50 * You can set the existing {@link CommandHandler} defined for an FTP server command
51 * by calling the {@link #setCommandHandler(String, CommandHandler)} method, passing
52 * in the FTP server command name and {@link CommandHandler} instance.
53 * You can also replace multiple command handlers at once by using the {@link #setCommandHandlers(Map)}
54 * method. That is especially useful when configuring the server through the <b>Spring Framework</b>.
55 * <p/>
56 * You can retrieve the existing {@link CommandHandler} defined for an FTP server command by
57 * calling the {@link #getCommandHandler(String)} method, passing in the FTP server command name.
58 * <p/>
59 * <h4>FTP Command Reply Text ResourceBundle</h4>
60 * The default text asociated with each FTP command reply code is contained within the
61 * "ReplyText.properties" ResourceBundle file. You can customize these messages by providing a
62 * locale-specific ResourceBundle file on the CLASSPATH, according to the normal lookup rules of
63 * the ResourceBundle class (e.g., "ReplyText_de.properties"). Alternatively, you can
64 * completely replace the ResourceBundle file by calling the calling the
65 * {@link #setReplyTextBaseName(String)} method.
66 *
67 * @author Chris Mair
68 * @version $Revision$ - $Date$
69 * @see org.mockftpserver.fake.FakeFtpServer
70 * @see org.mockftpserver.stub.StubFtpServer
71 */
72public abstract class AbstractFtpServer implements Runnable {
73
74    /**
75     * Default basename for reply text ResourceBundle
76     */
77    public static final String REPLY_TEXT_BASENAME = "ReplyText";
78    private static final int DEFAULT_SERVER_CONTROL_PORT = 21;
79
80    protected Logger LOG = Logger.getLogger(getClass());
81
82    // Simple value object that holds the socket and thread for a single session
83    private static class SessionInfo {
84        Socket socket;
85        Thread thread;
86    }
87
88    protected ServerSocketFactory serverSocketFactory = new DefaultServerSocketFactory();
89    private ServerSocket serverSocket = null;
90    private ResourceBundle replyTextBundle;
91    private volatile boolean terminate = false;
92    private Map commandHandlers;
93    private Thread serverThread;
94    private int serverControlPort = DEFAULT_SERVER_CONTROL_PORT;
95    private final Object startLock = new Object();
96
97    // Map of Session -> SessionInfo
98    private Map sessions = new HashMap();
99
100    /**
101     * Create a new instance. Initialize the default command handlers and
102     * reply text ResourceBundle.
103     */
104    public AbstractFtpServer() {
105        replyTextBundle = ResourceBundle.getBundle(REPLY_TEXT_BASENAME);
106        commandHandlers = new HashMap();
107    }
108
109    /**
110     * Start a new Thread for this server instance
111     */
112    public void start() {
113        serverThread = new Thread(this);
114
115        synchronized (startLock) {
116            try {
117                // Start here in case server thread runs faster than main thread.
118                // See https://sourceforge.net/tracker/?func=detail&atid=1006533&aid=1925590&group_id=208647
119                serverThread.start();
120
121                // Wait until the server thread is initialized
122                startLock.wait();
123            }
124            catch (InterruptedException e) {
125                e.printStackTrace();
126                throw new MockFtpServerException(e);
127            }
128        }
129    }
130
131    /**
132     * The logic for the server thread
133     *
134     * @see Runnable#run()
135     */
136    public void run() {
137        try {
138            LOG.info("Starting the server on port " + serverControlPort);
139            serverSocket = serverSocketFactory.createServerSocket(serverControlPort);
140
141            // Notify to allow the start() method to finish and return
142            synchronized (startLock) {
143                startLock.notify();
144            }
145
146            serverSocket.setSoTimeout(500);
147            while (!terminate) {
148                try {
149                    Socket clientSocket = serverSocket.accept();
150                    LOG.info("Connection accepted from host " + clientSocket.getInetAddress());
151
152                    Session session = createSession(clientSocket);
153                    Thread sessionThread = new Thread(session);
154                    sessionThread.start();
155
156                    SessionInfo sessionInfo = new SessionInfo();
157                    sessionInfo.socket = clientSocket;
158                    sessionInfo.thread = sessionThread;
159                    sessions.put(session, sessionInfo);
160                }
161                catch (SocketTimeoutException socketTimeoutException) {
162                    LOG.trace("Socket accept() timeout");
163                }
164            }
165        }
166        catch (IOException e) {
167            LOG.error("Error", e);
168        }
169        finally {
170
171            LOG.debug("Cleaning up server...");
172
173            try {
174                if (serverSocket != null) {
175                    serverSocket.close();
176                }
177
178                for (Iterator iter = sessions.keySet().iterator(); iter.hasNext();) {
179                    Session session = (Session) iter.next();
180                    SessionInfo sessionInfo = (SessionInfo) sessions.get(session);
181                    session.close();
182                    sessionInfo.thread.join(500L);
183                    Socket sessionSocket = sessionInfo.socket;
184                    if (sessionSocket != null) {
185                        sessionSocket.close();
186                    }
187                }
188            }
189            catch (IOException e) {
190                LOG.error("Error cleaning up server", e);
191            }
192            catch (InterruptedException e) {
193                LOG.error("Error cleaning up server", e);
194            }
195            LOG.info("Server stopped.");
196        }
197    }
198
199    /**
200     * Stop this server instance and wait for it to terminate.
201     */
202    public void stop() {
203
204        LOG.trace("Stopping the server...");
205        terminate = true;
206
207        try {
208            if (serverThread != null) {
209                serverThread.join();
210            }
211        }
212        catch (InterruptedException e) {
213            e.printStackTrace();
214            throw new MockFtpServerException(e);
215        }
216    }
217
218    /**
219     * Return the CommandHandler defined for the specified command name
220     *
221     * @param name - the command name
222     * @return the CommandHandler defined for name
223     */
224    public CommandHandler getCommandHandler(String name) {
225        return (CommandHandler) commandHandlers.get(Command.normalizeName(name));
226    }
227
228    /**
229     * Override the default CommandHandlers with those in the specified Map of
230     * commandName>>CommandHandler. This will only override the default CommandHandlers
231     * for the keys in <code>commandHandlerMapping</code>. All other default CommandHandler
232     * mappings remain unchanged.
233     *
234     * @param commandHandlerMapping - the Map of commandName->CommandHandler; these override the defaults
235     * @throws org.mockftpserver.core.util.AssertFailedException
236     *          - if the commandHandlerMapping is null
237     */
238    public void setCommandHandlers(Map commandHandlerMapping) {
239        Assert.notNull(commandHandlerMapping, "commandHandlers");
240        for (Iterator iter = commandHandlerMapping.keySet().iterator(); iter.hasNext();) {
241            String commandName = (String) iter.next();
242            setCommandHandler(commandName, (CommandHandler) commandHandlerMapping.get(commandName));
243        }
244    }
245
246    /**
247     * Set the CommandHandler for the specified command name. If the CommandHandler implements
248     * the {@link org.mockftpserver.core.command.ReplyTextBundleAware} interface and its <code>replyTextBundle</code> attribute
249     * is null, then set its <code>replyTextBundle</code> to the <code>replyTextBundle</code> of
250     * this StubFtpServer.
251     *
252     * @param commandName    - the command name to which the CommandHandler will be associated
253     * @param commandHandler - the CommandHandler
254     * @throws org.mockftpserver.core.util.AssertFailedException
255     *          - if the commandName or commandHandler is null
256     */
257    public void setCommandHandler(String commandName, CommandHandler commandHandler) {
258        Assert.notNull(commandName, "commandName");
259        Assert.notNull(commandHandler, "commandHandler");
260        commandHandlers.put(Command.normalizeName(commandName), commandHandler);
261        initializeCommandHandler(commandHandler);
262    }
263
264    /**
265     * Set the reply text ResourceBundle to a new ResourceBundle with the specified base name,
266     * accessible on the CLASSPATH. See {@link java.util.ResourceBundle#getBundle(String)}.
267     *
268     * @param baseName - the base name of the resource bundle, a fully qualified class name
269     */
270    public void setReplyTextBaseName(String baseName) {
271        replyTextBundle = ResourceBundle.getBundle(baseName);
272    }
273
274    /**
275     * Return the ReplyText ResourceBundle. Set the bundle through the  {@link #setReplyTextBaseName(String)}  method.
276     *
277     * @return the reply text ResourceBundle
278     */
279    public ResourceBundle getReplyTextBundle() {
280        return replyTextBundle;
281    }
282
283    /**
284     * Set the port number to which the server control connection socket will bind. The default value is 21.
285     *
286     * @param serverControlPort - the port number for the server control connection ServerSocket
287     */
288    public void setServerControlPort(int serverControlPort) {
289        this.serverControlPort = serverControlPort;
290    }
291
292    //-------------------------------------------------------------------------
293    // Internal Helper Methods
294    //-------------------------------------------------------------------------
295
296    /**
297     * Return true if this server is fully shutdown -- i.e., there is no active (alive) threads and
298     * all sockets are closed. This method is intended for testing only.
299     *
300     * @return true if this server is fully shutdown
301     */
302    public boolean isShutdown() {
303        boolean shutdown = !serverThread.isAlive() && serverSocket.isClosed();
304
305        for (Iterator iter = sessions.values().iterator(); iter.hasNext();) {
306            SessionInfo sessionInfo = (SessionInfo) iter.next();
307            shutdown = shutdown && sessionInfo.socket.isClosed() && !sessionInfo.thread.isAlive();
308        }
309        return shutdown;
310    }
311
312    /**
313     * Return true if this server has started -- i.e., there is an active (alive) server threads
314     * and non-null server socket. This method is intended for testing only.
315     *
316     * @return true if this server has started
317     */
318    public boolean isStarted() {
319        return serverThread != null && serverThread.isAlive() && serverSocket != null;
320    }
321
322    /**
323     * Create a new Session instance for the specified client Socket
324     *
325     * @param clientSocket - the Socket associated with the client
326     * @return a Session
327     */
328    protected Session createSession(Socket clientSocket) {
329        return new DefaultSession(clientSocket, commandHandlers);
330    }
331
332    //------------------------------------------------------------------------------------
333    // Abstract method declarations
334    //------------------------------------------------------------------------------------
335
336    /**
337     * Initialize a CommandHandler that has been registered to this server. What "initialization"
338     * means is dependent on the subclass implementation.
339     *
340     * @param commandHandler - the CommandHandler to initialize
341     */
342    protected abstract void initializeCommandHandler(CommandHandler commandHandler);
343
344}