2006-12-12 18:57:24 -05:00
|
|
|
package davmail;
|
|
|
|
|
|
|
|
import java.net.ServerSocket;
|
|
|
|
import java.net.Socket;
|
|
|
|
import java.io.IOException;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generic abstract server common to SMTP and POP3 implementations
|
|
|
|
*/
|
|
|
|
public abstract class AbstractServer extends Thread {
|
|
|
|
protected int port;
|
|
|
|
protected ServerSocket serverSocket;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a ServerSocket to listen for connections.
|
|
|
|
* Start the thread.
|
|
|
|
*/
|
2006-12-14 10:14:18 -05:00
|
|
|
public AbstractServer(int port) {
|
2006-12-12 18:57:24 -05:00
|
|
|
this.port = port;
|
|
|
|
try {
|
2007-04-26 06:29:11 -04:00
|
|
|
//noinspection SocketOpenedButNotSafelyClosed
|
2006-12-12 18:57:24 -05:00
|
|
|
serverSocket = new ServerSocket(port);
|
|
|
|
} catch (IOException e) {
|
2006-12-14 10:14:18 -05:00
|
|
|
DavGatewayTray.error("Exception creating server socket", e);
|
2006-12-12 18:57:24 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The body of the server thread. Loop forever, listening for and
|
|
|
|
* accepting connections from clients. For each connection,
|
|
|
|
* create a Connection object to handle communication through the
|
|
|
|
* new Socket.
|
|
|
|
*/
|
|
|
|
public void run() {
|
2007-04-26 06:29:11 -04:00
|
|
|
Socket clientSocket = null;
|
2006-12-12 18:57:24 -05:00
|
|
|
try {
|
|
|
|
//noinspection InfiniteLoopStatement
|
|
|
|
while (true) {
|
2007-04-26 06:29:11 -04:00
|
|
|
clientSocket = serverSocket.accept();
|
2006-12-12 18:57:24 -05:00
|
|
|
DavGatewayTray.debug("Connection from " + clientSocket.getInetAddress() + " on port " + port);
|
|
|
|
// only accept localhost connections for security reasons
|
|
|
|
if (clientSocket.getInetAddress().toString().indexOf("127.0.0.1") > 0) {
|
2006-12-14 10:14:18 -05:00
|
|
|
createConnectionHandler(clientSocket);
|
2006-12-12 18:57:24 -05:00
|
|
|
} else {
|
|
|
|
clientSocket.close();
|
|
|
|
DavGatewayTray.warn("Connection from external client refused");
|
|
|
|
}
|
|
|
|
System.gc();
|
|
|
|
}
|
|
|
|
} catch (IOException e) {
|
2006-12-14 10:14:18 -05:00
|
|
|
DavGatewayTray.warn("Exception while listening for connections", e);
|
2007-04-26 06:29:11 -04:00
|
|
|
} finally {
|
|
|
|
try {
|
|
|
|
if (clientSocket != null) {
|
|
|
|
clientSocket.close();
|
|
|
|
}
|
|
|
|
} catch (IOException e) {
|
|
|
|
// ignore
|
|
|
|
}
|
2006-12-12 18:57:24 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2006-12-14 10:14:18 -05:00
|
|
|
public abstract void createConnectionHandler(Socket clientSocket);
|
|
|
|
|
|
|
|
public void close() {
|
|
|
|
try {
|
|
|
|
serverSocket.close();
|
|
|
|
} catch (IOException e) {
|
|
|
|
DavGatewayTray.warn("Exception closing server socket", e);
|
|
|
|
}
|
|
|
|
}
|
2006-12-12 18:57:24 -05:00
|
|
|
}
|
|
|
|
|