requestlistener.java
来自「轻量级Http代理服务器」· Java 代码 · 共 395 行
JAVA
395 行
/*
* jRevProxy, an opensource Java reverse proxy server
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
* $Id: RequestListener.java,v 2.12 2003/04/22 13:52:40 fnoe Exp $
*/
package cx.noe.jrevproxy;
import cx.noe.jrevproxy.PoolManager;
import cx.noe.jrevproxy.RequestHandler;
import cx.noe.jrevproxy.logging.ILog;
import cx.noe.jrevproxy.RulesetParser;
import cx.noe.jrevproxy.IHandlerInfo;
import cx.noe.jrevproxy.ConnectionInfo;
import java.net.ServerSocket;
import java.net.InetSocketAddress;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Properties;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.HandshakeCompletedListener;
import javax.security.cert.X509Certificate;
import javax.security.cert.CertificateExpiredException;
import javax.security.cert.CertificateNotYetValidException;
/**
* RequestListener
*
* Starts listening for HTTP/HTTPS requests
* @author <a href="mailto:frederik@noe.cx">Frederik Noe</a>
* @version <tt>$Revision: 2.12 $</tt>
*/
public class RequestListener extends Thread implements ILog{
public final int HTTP = 1;
public final int HTTPS = 2;
private final int HTTPPORT = 80;
private final int HTTPSPORT = 443;
private PoolManager manager = null;
private ILog logger = null;
private Ruleset ruleset = null;
private int port = 0;
private int protocol = 0;
private boolean isRunning = true;
private Properties properties = null;
private boolean clientauth = false;
private RulesetRefresher refresher = null;
/** Creates a new instance of RequestListener */
public RequestListener(PoolManager poolmanager, Properties properties) {
manager = poolmanager;
logger = poolmanager.getLogger();
this.properties = properties;
refresher = new RulesetRefresher(logger,properties);
}
public void init() throws Exception {
log(METHOD,"--init--");
parseXMLConfig();
refresher.start();
}
public void destroy() {
log(METHOD,"--destroy--");
isRunning = false;
try {
refresher.join();
}
catch(InterruptedException e) {}
}
public void run(){
log(METHOD,"--run--");
try{
//
ConnectionInfo connectioninfo = null;
// Get Socket factory
SocketFactory factory = new SocketFactory(properties,logger);
//************ HTTPS ******************//
if(protocol == HTTPS) {
SSLServerSocket serverSocket = null;
// create a SSL serversocket using the keystore provided
try {
serverSocket = factory.getSSLServerSocket(port,clientauth);
}
catch(Exception e) {
log(e);
System.out.println("was not able to connect on port " + port);
System.out.println("jRevProxy stopped");
System.exit(0);
return;
}
log(INFO,"created SSL serversocket");
CustomHandshakeCompletedListener hcl = null;
// start accepting requests and spawning handlers taking care of these requests
while(isRunning) {
log(INFO,"accept on port " + port);
SSLSocket s = (SSLSocket)serverSocket.accept();
log(INFO,"will handle request from "+ s.getRemoteSocketAddress().toString());
// we create a new object that will hold all info about the connection and the acquired authentication(s)
connectioninfo = new ConnectionInfo(logger, (InetSocketAddress) s.getRemoteSocketAddress());
if(clientauth) {
hcl = new CustomHandshakeCompletedListener(logger,connectioninfo);
s.addHandshakeCompletedListener(hcl);
}
// create a RequestHandler and provide the Socket
RequestHandler handler = new RequestHandler(manager,properties,connectioninfo);
handler.setRuleset(ruleset);
try {
handler.handle(s);
}
catch(Exception e) {
// we do not have a handler to do the job
log(INFO, "was not able to handle the request due to unavaible requesthandlers");
s.close();
}
//
}
}
//************ HTTP ******************//
else {
ServerSocket serverSocket = null;
// create a normal serversocket
try {
serverSocket = factory.getServerSocket(port);
}
catch(Exception e) {
log(e);
System.out.println("was not able to connect on port " + port);
System.out.println("jRevProxy stopped");
System.exit(0);
return;
}
log(INFO,"created serversocket");
// start accepting requests and spawning handlers taking care of these requests
while(isRunning) {
log(INFO,"accept on port " + port);
Socket s = serverSocket.accept();
log(INFO,"will handle request from "+ s.getRemoteSocketAddress().toString());
// we create a new object that will hold all info about the connection and the acquired authentication(s)
connectioninfo = new ConnectionInfo(logger, (InetSocketAddress) s.getRemoteSocketAddress());
// create a RequestHandler and provide the Socket
RequestHandler handler = new RequestHandler(manager,properties,connectioninfo);
handler.setRuleset(ruleset);
try {
handler.handle(s);
}
catch(Exception e) {
// we do not have a handler to do the job
s.close();
log(INFO, "was not able to handle the request due to unavaible requesthandlers");
}
//
}
}
} catch(IOException e) {
log(e);
System.out.println("was not able to handle incoming requests on port "+ port);
}
}
public int getPort(){
log(METHOD,"--getPort--");
return port;
}
/**
* Sets also the port number on which the socket has to listen
* @param port the port number
*/
public void setPort(int port) {
log(METHOD,"--setPort--");
this.port = port;
}
public void setClientAuthentication(boolean clientauth) {
log(METHOD,"--setClientAuthentication--");
this.clientauth = clientauth;
}
public int getProtocol() {
return protocol;
}
/**
* Sets the communication protocol used for the incoming requests
*/
public void setProtocol(int protocol) throws IllegalArgumentException{
log(METHOD,"--setProtocol--");
switch(protocol){
case HTTP:
this.protocol = protocol;
setPort(HTTPPORT);
break;
case HTTPS:
this.protocol = protocol;
setPort(HTTPSPORT);
break;
default:
throw new IllegalArgumentException();
}
}
public void log(Throwable e) {
if(logger != null)
logger.log(e);
}
public void log(int level, String str) {
if(logger != null)
logger.log(level,"[RequestListener] " + str);
}
// Inner class
/**
* CustomHandshakeCompletedListener
* retrieves the client certificate information and checks if it is valid
*/
class CustomHandshakeCompletedListener implements HandshakeCompletedListener, ILog {
private ILog logger = null;
private X509Certificate certificate = null;
private ConnectionInfo info = null;
CustomHandshakeCompletedListener(ILog logger, ConnectionInfo info ) {
this.logger = logger;
this.info = info;
}
public X509Certificate getX509Certificate() {
return certificate;
}
public String getSubjectName() {
log(METHOD," --getSubjectName-- ");
if(certificate != null)
return certificate.getSubjectDN().getName();
else
return "not specified";
}
public void handshakeCompleted(javax.net.ssl.HandshakeCompletedEvent event) {
log(METHOD," --handshakeCompleted-- ");
try {
X509Certificate certificate = event.getPeerCertificateChain()[0];
log(INFO,"SubjectDN: " + certificate.getSubjectDN().getName());
log(INFO,"IssuerDN: " + certificate.getIssuerDN().getName());
try {
certificate.checkValidity();
}
catch(CertificateExpiredException ce){
log(INFO,"Certificate has expired");
}
catch(CertificateNotYetValidException cnv){
log(INFO,"Certificate is not valid yet");
}
log(INFO,"Valid from " + certificate.getNotBefore().toString() + " to " + certificate.getNotAfter().toString());
this.certificate = certificate;
}
catch(javax.net.ssl.SSLPeerUnverifiedException e) {
log(INFO,"Peer unverified");
}
info.setCertificate(certificate);
}
public void log(int level, String str) {
if(logger != null)
logger.log(level,"[CustomHandshakeCompletedListener] " + str);
}
public void log(Throwable e) {
if(logger != null)
logger.log(e);
}
}
/**
* parse XML configuration file and create a set of rules out of it
*/
private void parseXMLConfig() throws Exception {
log(METHOD,"--parseXMLConfig--");
String xmlfilename = properties.getProperty("XMLCONFIGFILE");
log(DEBUG,"XMLConfigFile: " + xmlfilename);
// create the ruleset parser and let him parse the XML file
RulesetParser parser = new RulesetParser(xmlfilename);
try {
parser.parse();
}
catch(Exception e) {
log(e);
throw new Exception("Error parsing " + xmlfilename);
}
ruleset = parser.getRuleset();
log(INFO,"Ruleset read and parsed successfully ");
log(DEBUG, ruleset.toString());
}
// Inner class
/**
* Checks the xml configuration on a regular basis
*/
class RulesetRefresher extends Thread implements ILog {
private boolean isRunning = true;
private ILog logger = null;
private int sleepTime = 120;
public RulesetRefresher(ILog logger, Properties properties) {
this.logger = logger;
String strSleeptime = null;
if((strSleeptime = properties.getProperty("REFRESHINTERVAL")) != null)
try {
sleepTime = Integer.parseInt(strSleeptime);
}
catch(Exception e) {}
}
public void destroy() {
isRunning = false;
}
public void run() {
log(METHOD,"--run--");
while(isRunning) {
try {
sleep(sleepTime * 1000);
log(INFO,"will refresh ruleset");
parseXMLConfig();
}
catch(Exception e) {}
}
log(DEBUG,"refresher thread stopped");
}
public void log(int level, String str) {
if(logger != null)
logger.log(level,"[RulesetRefresher] " + str);
}
public void log(Throwable e) {
if(logger != null)
logger.log(e);
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?