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 // Ensure that the start() method is not still blocked 174 synchronized (startLock) { 175 startLock.notifyAll(); 176 } 177 178 try { 179 if (serverSocket != null) { 180 serverSocket.close(); 181 } 182 closeSessions(); 183 } 184 catch (IOException e) { 185 LOG.error("Error cleaning up server", e); 186 } 187 catch (InterruptedException e) { 188 LOG.error("Error cleaning up server", e); 189 } 190 LOG.info("Server stopped."); 191 terminate = false; 192 } 193 } 194 195 /** 196 * Stop this server instance and wait for it to terminate. 197 */ 198 public void stop() { 199 200 LOG.trace("Stopping the server..."); 201 terminate = true; 202 203 try { 204 if (serverThread != null) { 205 serverThread.join(); 206 } 207 } 208 catch (InterruptedException e) { 209 e.printStackTrace(); 210 throw new MockFtpServerException(e); 211 } 212 } 213 214 /** 215 * Return the CommandHandler defined for the specified command name 216 * 217 * @param name - the command name 218 * @return the CommandHandler defined for name 219 */ 220 public CommandHandler getCommandHandler(String name) { 221 return (CommandHandler) commandHandlers.get(Command.normalizeName(name)); 222 } 223 224 /** 225 * Override the default CommandHandlers with those in the specified Map of 226 * commandName>>CommandHandler. This will only override the default CommandHandlers 227 * for the keys in <code>commandHandlerMapping</code>. All other default CommandHandler 228 * mappings remain unchanged. 229 * 230 * @param commandHandlerMapping - the Map of commandName->CommandHandler; these override the defaults 231 * @throws org.mockftpserver.core.util.AssertFailedException 232 * - if the commandHandlerMapping is null 233 */ 234 public void setCommandHandlers(Map commandHandlerMapping) { 235 Assert.notNull(commandHandlerMapping, "commandHandlers"); 236 for (Iterator iter = commandHandlerMapping.keySet().iterator(); iter.hasNext();) { 237 String commandName = (String) iter.next(); 238 setCommandHandler(commandName, (CommandHandler) commandHandlerMapping.get(commandName)); 239 } 240 } 241 242 /** 243 * Set the CommandHandler for the specified command name. If the CommandHandler implements 244 * the {@link org.mockftpserver.core.command.ReplyTextBundleAware} interface and its <code>replyTextBundle</code> attribute 245 * is null, then set its <code>replyTextBundle</code> to the <code>replyTextBundle</code> of 246 * this StubFtpServer. 247 * 248 * @param commandName - the command name to which the CommandHandler will be associated 249 * @param commandHandler - the CommandHandler 250 * @throws org.mockftpserver.core.util.AssertFailedException 251 * - if the commandName or commandHandler is null 252 */ 253 public void setCommandHandler(String commandName, CommandHandler commandHandler) { 254 Assert.notNull(commandName, "commandName"); 255 Assert.notNull(commandHandler, "commandHandler"); 256 commandHandlers.put(Command.normalizeName(commandName), commandHandler); 257 initializeCommandHandler(commandHandler); 258 } 259 260 /** 261 * Set the reply text ResourceBundle to a new ResourceBundle with the specified base name, 262 * accessible on the CLASSPATH. See {@link java.util.ResourceBundle#getBundle(String)}. 263 * 264 * @param baseName - the base name of the resource bundle, a fully qualified class name 265 */ 266 public void setReplyTextBaseName(String baseName) { 267 replyTextBundle = ResourceBundle.getBundle(baseName); 268 } 269 270 /** 271 * Return the ReplyText ResourceBundle. Set the bundle through the {@link #setReplyTextBaseName(String)} method. 272 * 273 * @return the reply text ResourceBundle 274 */ 275 public ResourceBundle getReplyTextBundle() { 276 return replyTextBundle; 277 } 278 279 /** 280 * Set the port number to which the server control connection socket will bind. The default value is 21. 281 * 282 * @param serverControlPort - the port number for the server control connection ServerSocket 283 */ 284 public void setServerControlPort(int serverControlPort) { 285 this.serverControlPort = serverControlPort; 286 } 287 288 /** 289 * Return the port number to which the server control connection socket will bind. The default value is 21. 290 * 291 * @return the port number for the server control connection ServerSocket 292 */ 293 public int getServerControlPort() { 294 return serverControlPort; 295 } 296 297 /** 298 * Return true if this server is fully shutdown -- i.e., there is no active (alive) threads and 299 * all sockets are closed. This method is intended for testing only. 300 * 301 * @return true if this server is fully shutdown 302 */ 303 public boolean isShutdown() { 304 boolean shutdown = !serverThread.isAlive() && serverSocket.isClosed(); 305 306 for (Iterator iter = sessions.values().iterator(); iter.hasNext();) { 307 SessionInfo sessionInfo = (SessionInfo) iter.next(); 308 shutdown = shutdown && sessionInfo.socket.isClosed() && !sessionInfo.thread.isAlive(); 309 } 310 return shutdown; 311 } 312 313 /** 314 * Return true if this server has started -- i.e., there is an active (alive) server threads 315 * and non-null server socket. This method is intended for testing only. 316 * 317 * @return true if this server has started 318 */ 319 public boolean isStarted() { 320 return serverThread != null && serverThread.isAlive() && serverSocket != null; 321 } 322 323 //------------------------------------------------------------------------- 324 // Internal Helper Methods 325 //------------------------------------------------------------------------- 326 327 /** 328 * Create a new Session instance for the specified client Socket 329 * 330 * @param clientSocket - the Socket associated with the client 331 * @return a Session 332 */ 333 protected Session createSession(Socket clientSocket) { 334 return new DefaultSession(clientSocket, commandHandlers); 335 } 336 337 private void closeSessions() throws InterruptedException, IOException { 338 for (Iterator iter = sessions.entrySet().iterator(); iter.hasNext();) { 339 Map.Entry entry = (Map.Entry) iter.next(); 340 Session session = (Session) entry.getKey(); 341 SessionInfo sessionInfo = (SessionInfo) entry.getValue(); 342 session.close(); 343 sessionInfo.thread.join(500L); 344 Socket sessionSocket = sessionInfo.socket; 345 if (sessionSocket != null) { 346 sessionSocket.close(); 347 } 348 } 349 } 350 351 //------------------------------------------------------------------------------------ 352 // Abstract method declarations 353 //------------------------------------------------------------------------------------ 354 355 /** 356 * Initialize a CommandHandler that has been registered to this server. What "initialization" 357 * means is dependent on the subclass implementation. 358 * 359 * @param commandHandler - the CommandHandler to initialize 360 */ 361 protected abstract void initializeCommandHandler(CommandHandler commandHandler); 362 363}