📄 httpserver.java
字号:
/*
* SSL-Explorer
*
* Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package com.sslexplorer.vpn.client;
import java.io.*;
import java.util.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import com.maverick.http.URLDecoder;
/* DEBUG */import org.apache.commons.logging.*;
public class HTTPServer
implements Runnable {
private ServerSocket server = null;
private int port;
Vector listeners = new Vector();
/* DEBUG */static Log log = LogFactory.getLog(HTTPServer.class);
public HTTPServer(int port) throws IOException {
this.port = port;
server = new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
newListener();
}
/**
* Add a request listener
* @param listener
*/
public void addListener(HTTPRequestListener listener) {
/* DEBUG */log.info("Adding request listener");
if (listener != null) {
listeners.addElement(listener);
}
}
public void run() {
Socket socket;
/* DEBUG */log.info("Waiting for a client connection on port " + port);
try {
socket = server.accept();
/* DEBUG */log.info("Got connection from " + socket.getInetAddress().getHostAddress() + ":" + socket.getPort());
}
catch (IOException e) {
/* DEBUG */log.info("Failed to accept a client connection", e);
return;
}
// create a new thread to accept the next connection
newListener();
try {
DataOutputStream out =
new DataOutputStream(socket.getOutputStream());
try {
// get path to class file from header
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
processRequest(in, out);
}
catch (Throwable ex) {
/* DEBUG */log.info("Request failed", ex);
out.writeBytes("HTTP/1.0 400 " + ex.getMessage() + "\r\n");
out.writeBytes("Connection: close\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.flush();
}
}
catch (IOException ex) {
/* DEBUG */log.info("Request failed", ex);
}
finally {
try {
socket.close();
}
catch (IOException e) {
}
}
}
/**
* Create a new thread to listen.
*/
private void newListener() {
Thread t = new Thread(this, "HTTP Server");
t.start();
}
/**
* Returns the path to the class file obtained from
* parsing the HTML header.
*/
private void processRequest(BufferedReader in, DataOutputStream out) throws
IOException {
HTTPRequest request = new HTTPRequest();
String line = in.readLine();
String raw;
String version;
String path = "";
String query = null;
Hashtable parameters = new Hashtable();
Hashtable headers = new Hashtable();
if (line.startsWith("GET /")
|| line.startsWith("POST /")) {
/* DEBUG */log.info("Processing request " + line);
int x = line.indexOf(' ') + 1;
int v = line.indexOf(' ', x);
raw = line.substring(x, v).trim();
version = line.substring(v + 1);
int index = raw.indexOf("?");
if (index != -1) {
path = raw.substring(0, index);
query = raw.substring(index + 1);
}
else {
path = raw;
}
if (query != null) {
StringTokenizer tokens = new StringTokenizer(query, "&");
while (tokens.hasMoreElements()) {
String parameter = (String) tokens.nextElement();
int idx = parameter.indexOf('=');
if (idx > -1) {
request.addParameter(URLDecoder.decode(parameter.substring(0, idx)),
URLDecoder.decode(parameter.substring(idx + 1)));
}
else {
request.addParameter(URLDecoder.decode(parameter), "");
}
}
}
}
else {
throw new IOException("Unsupported request " + line);
}
// Record the header - you never know this might come in handy one day
do {
line = in.readLine();
int idx = line.indexOf(':');
if (idx > -1) {
request.setHeader(line.substring(0, idx), line.substring(idx + 1));
/* DEBUG */log.info("HTTP Header: "
/* DEBUG */+ line.substring(0, idx)
/* DEBUG */+ ": "
/* DEBUG */+ line.substring(idx + 1));
}
}
while ( (line.length() != 0)
&& (line.charAt(0) != '\r')
&& (line.charAt(0) != '\n'));
if (request.containsHeader("Content-Type") &&
request.containsHeader("Content-Length")) {
String contentType = request.getHeader("Content-Type");
/* DEBUG */log.info("Request contains some content of type "
/* DEBUG */ + contentType);
if (contentType.equalsIgnoreCase("application/x-www-form-urlencoded")) {
int length = Integer.parseInt(request.getHeader("Content-Length"));
/* DEBUG */log.info("Reading " + length + " bytes of form data");
ByteArrayOutputStream input = new ByteArrayOutputStream();
char[] buf = new char[length];
int i;
while (length > 0) {
i = in.read(buf, buf.length - length, length);
if (i == -1) {
break;
}
length -= i;
}
String urlencoded = new String(buf, 0, buf.length);
/* DEBUG */ log.info("Extracting parameters from form data " + urlencoded);
StringTokenizer tokens = new StringTokenizer(urlencoded, "&");
while (tokens.hasMoreElements()) {
String param = (String) tokens.nextElement();
int idx = param.indexOf('=');
String name = param.substring(0, idx);
String value = param.substring(idx + 1);
if (idx > -1) {
/* DEBUG */log.info("HTTP Encoded Parameter: " + name + "=" + value);
/* DEBUG */log.info("HTTP Parameter: " + URLDecoder.decode(name) + "=" + URLDecoder.decode(value));
request.addParameter(URLDecoder.decode(name),
URLDecoder.decode(value));
}
else {
request.addParameter(URLDecoder.decode(param), "");
/* DEBUG */log.info("HTTP Encoded Parameter: " + name);
/* DEBUG */log.info("HTTP Parameter: " + URLDecoder.decode(name));
}
}
}
}
Enumeration e = listeners.elements();
HTTPRequestListener listener;
try {
byte[] response = null;
while (e.hasMoreElements()) {
listener = (HTTPRequestListener) e.nextElement();
response = listener.processHTTPRequest(path,
request);
if (response != null) {
break;
}
}
// Retrieve response
if (response == null) {
throw new IOException("Unhandled request for " + path);
}
// Send response (assumes HTTP/1.0 or later)
out.writeBytes("HTTP/1.0 200 OK\r\n");
out.writeBytes("Content-Length: " + response.length + "\r\n");
out.writeBytes("Connection: close\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.write(response);
out.flush();
}
catch (RedirectException ex) {
/* DEBUG */log.info("Redirecting browser to " + ex.getLocation());
byte[] html = ("<HTML><HEAD><TITLE>SSL-Explorer Agent Redirect</TITLE></HEAD><BODY>The SSL-Explorer Agent requested that your browser redirect to the following link:<BR><BR><A HREF=\"" + ex.getLocation() + "\">" + ex.getLocation() + "</A>This should have been completed automatically but if you are reading this the redirect has failed. Click on the link to access the redirected page.</BODY></HTML>").getBytes();
out.writeBytes("HTTP/1.0 302 Redirecting\r\n");
out.writeBytes("Location: " + ex.getLocation() + "\r\n");
out.writeBytes("Content-Length: " + html.length + "\r\n");
out.writeBytes("Content-Type: text/html\r\n");
out.writeBytes("Cache-Control: no-cache\r\n");
out.writeBytes("Connection: close\r\n");
out.writeBytes("Pragma: no-cache\r\n");
out.writeBytes("Expires: 0\r\n\r\n");
out.write(html);
out.flush();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -