📄 servletsocks.java
字号:
/*This file is part of Socks via HTTP.This package is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2 of the License, or(at your option) any later version.Socks via HTTP is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with Socks via HTTP; if not, write to the Free SoftwareFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA*/// Title : ServletSocks.java// Version : 0.40// Copyright : Copyright (c) 2001// Author : Florent CUETO (fcueto@wanadoo.fr)// Description : Main Servlet (Server part of Socks via HTTP)package socks4;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.util.zip.*;public class ServletSocks extends HttpServlet{ private static final String PROPERTIES_FILE = "socks4.initsrv"; public static ConnectionTable table = null; public static UserList userlist = null; // init method public void init(ServletConfig config) throws ServletException { super.init(config); // Create the UserList userlist = new UserList(); // Fill it String sUsers = PropertiesFileReader.getPropertyStringValue(PROPERTIES_FILE, "socks.server.users"); String[] users = stringSplit(sUsers, ",", true); for (int i = 0; i < users.length; i++) { String userLogin = users[i]; String userPassword = PropertiesFileReader.getPropertyStringValue(PROPERTIES_FILE, "users.password." + userLogin); UserInfo userInfo = new UserInfo(userLogin, userPassword); userInfo.autorizedTime = PropertiesFileReader.getPropertyLongValue(PROPERTIES_FILE, "users.autorizedtime." + userLogin); String sIp = PropertiesFileReader.getPropertyStringValue(PROPERTIES_FILE, "users.ip." + userLogin); String[] ips = stringSplit(sIp, ",", true); for (int j = 0; j < ips.length; j++) { userInfo.addIp(ips[j]); } // Add the UserInfo to the list userlist.addUser(userInfo); } // Create the ConnectionTable table = new ConnectionTable(); // Start the ThreadPing new ThreadPing().start(); } // get method public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<p>This servlet cannot be invoked directly.</p>"); out.println("</body>"); out.println("</html>"); } // post method public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the remote IP String ip = request.getRemoteAddr(); // Set the headers response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); try { // Read the request GZIPInputStream zis = new GZIPInputStream(request.getInputStream()); ObjectInputStream ois = new ObjectInputStream(zis); DataPacket input = (DataPacket)ois.readObject(); ois.close(); int type = input.type; String id_conn = input.id; ExtendedConnection extConn = null; Connection conn = null; // Build the response DataPacket output = new DataPacket(); output.id = id_conn; switch(type) { case Const.CONNECTION_CREATE: // Create a connection String iprev = nslookup(ip); String err = null; String[] userpass = stringSplit(input.id, ":", false); String login = userpass[0]; String pass = userpass[1]; String sTimeout = userpass[2]; int timeout = Integer.parseInt(sTimeout); // Check the user UserInfo userInfo = userlist.getUser(login); if (userInfo == null) { // Unknown user Log.printLog("Refused connection to unknown user : " + login + "..."); err = "Refused connection to unknown user : " + login + "..."; } // Check the password else if (!userInfo.password.equals(pass)) { // Wrong password Log.printLog("Refused connection to user : " + login + " (bad password)..."); err = "Refused connection to user : " + login + " (bad password)..."; } // Check the IP else if (!userInfo.isAutorised(ip)) { // Bad IP Log.printLog("Refused connection to user : " + login + " (unauthorized ip : " + ip + ")..."); err = "Refused connection to user : " + login + " (unauthorized ip : " + ip + ")..."; } if (err != null) { output.type = Const.CONNECTION_CREATE_KO; output.tab = err.getBytes(); } else { // Create a connection ID id_conn = "" + (new java.util.Date()).getTime(); // Log Log.printLog("Connection create : " + id_conn); // Get the host and the port we have to connect to String url = new String(input.tab); String host = url.substring(0, url.indexOf(':')); int port = Integer.parseInt(url.substring(1 + url.indexOf(':'), url.length())); // Create the connection conn = new Connection(Connection.CONNECTION_CLIENT_TYPE); // Connect if (conn.connect(host, port) != 0) { // Log Log.printLog("Connection failed from " + iprev + "(" + ip + ") to " + host + ":" + port); output.type = Const.CONNECTION_CREATE_KO; err = "Server was unable to connect to " + host + ":" + port; output.tab = err.getBytes(); } else { // Log Log.printLog("Connection created from " + iprev + "(" + ip + ") to " + host + ":" + port); // Create the ExtendedConnection extConn = new ExtendedConnection(); extConn.conn = conn; extConn.ip = ip; extConn.iprev = iprev; extConn.destIP = host; extConn.destIPrev = nslookup(host); extConn.destPort = port; extConn.user = userInfo; extConn.serverTimeout = timeout; extConn.autorizedTime = userInfo.autorizedTime; // Add this to the ConnectionTable table.put(id_conn, extConn); // Build the response output.type = Const.CONNECTION_CREATE_OK; output.id = id_conn; //output.tab = conn.read(); //output.tab = Const.TAB_EMPTY; String resp = "" + conn.getSocket().getInetAddress().getHostAddress() + ":" + conn.getSocket().getPort(); output.tab = resp.getBytes(); } } break; case Const.CONNECTION_PING: // Send a PONG output.type = Const.CONNECTION_PONG; output.tab = input.tab; break; case Const.CONNECTION_PONG: // Reply to PONG // TO DO // Send a pong_received output.type = Const.CONNECTION_PONG_RECEIVED; output.tab = input.tab; break; case Const.CONNECTION_REQUEST: // Request // Get the connection extConn = table.get(id_conn); if (extConn == null) { Log.printLog("Connection not found : " + id_conn); // Connection not found output.type = Const.CONNECTION_NOT_FOUND; output.tab = Const.TAB_EMPTY; } else { long lastAccessDate = extConn.lastAccessDate; extConn.lastAccessDate = new java.util.Date().getTime(); conn = extConn.conn; // Add the sended bytes extConn.uploadedBytes += input.tab.length; // write the bytes conn.write(input.tab); // Update the upload speed long div = 1 + extConn.lastAccessDate - lastAccessDate; extConn.currentUploadSpeed = (double)input.tab.length / div; // Build the response output.type = Const.CONNECTION_RESPONSE; byte[] buf = conn.read(); if (buf == null) { output.tab = Const.TAB_EMPTY; output.isConnClosed = true; // Remove the connection from the ConnectionTable table.remove(id_conn); } else { // Add the received bytes extConn.downloadedBytes += buf.length; // Update the download speed div = 1 + extConn.lastAccessDate - lastAccessDate; extConn.currentDownloadSpeed = (double)buf.length / div; // Prepare the output output.tab = buf; } } break; case Const.CONNECTION_DESTROY: // Close the connection // Log Log.printLog("Connection destroy : " + id_conn); // Get the connection extConn = table.get(id_conn); extConn.lastAccessDate = new java.util.Date().getTime(); conn = extConn.conn; // Close it conn.disconnect(); // Remove it from the ConnectionTable table.remove(id_conn); // Build the response output.type = Const.CONNECTION_DESTROY_OK; break; } // Send the response GZIPOutputStream zos = new GZIPOutputStream(response.getOutputStream()); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(output); oos.close(); } catch(Throwable e) { Log.printLog("Exception : " + e); } } // destroy method public void destroy() { } // Nslookup (IP -> DNS Name) public String nslookup(String ip) { String hostname = "?"; java.net.InetAddress address = null; try { address = java.net.InetAddress.getByName(ip); hostname = address.getHostName(); } catch (Exception e){} return(hostname); } // Split a string public static String[] stringSplit(String string, String tokens, boolean trimStrings) { if (string == null) return(null); if (string.length() == 0) return(new String[0]); Vector res = new Vector(); StringTokenizer stk = new StringTokenizer(string, tokens, false); while (stk.hasMoreTokens()) res.addElement(stk.nextToken()); String[] res2 = new String[res.size()]; for (int i=0;i<res.size();i++) { res2[i]=(String)res.elementAt(i); if (trimStrings) res2[i] = res2[i].trim(); } return(res2); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -