1.新增注视 2.修改部分可能会抛异常的代码

master
星期八 5 years ago
parent 635ef92e8b
commit d669be0a8e
  1. 3
      proxy-protocol/src/main/java/org/fengfei/lanproxy/protocol/Constants.java
  2. 7
      proxy-server/src/main/java/org/fengfei/lanproxy/server/config/web/HttpRequestHandler.java
  3. 355
      proxy-server/src/main/java/org/fengfei/lanproxy/server/config/web/routes/RouteConfig.java

@ -3,6 +3,9 @@ package org.fengfei.lanproxy.protocol;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.util.AttributeKey; import io.netty.util.AttributeKey;
/**
* 常量类
*/
public interface Constants { public interface Constants {
AttributeKey<Channel> NEXT_CHANNEL = AttributeKey.newInstance("nxt_channel"); AttributeKey<Channel> NEXT_CHANNEL = AttributeKey.newInstance("nxt_channel");

@ -34,6 +34,11 @@ public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequ
private static final String SERVER_VS = "LPS-0.1"; private static final String SERVER_VS = "LPS-0.1";
/**
* http 斜杠
*/
private static final String HTTP_SYMBOL ="/";
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
@ -76,7 +81,7 @@ public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequ
HttpResponseStatus status = HttpResponseStatus.OK; HttpResponseStatus status = HttpResponseStatus.OK;
URI uri = new URI(request.getUri()); URI uri = new URI(request.getUri());
String uriPath = uri.getPath(); String uriPath = uri.getPath();
uriPath = uriPath.equals("/") ? "/index.html" : uriPath; uriPath = HTTP_SYMBOL.equals(uriPath)? "/index.html" : uriPath;
String path = PAGE_FOLDER + uriPath; String path = PAGE_FOLDER + uriPath;
File rfile = new File(path); File rfile = new File(path);
if (rfile.isDirectory()) { if (rfile.isDirectory()) {

@ -1,175 +1,180 @@
package org.fengfei.lanproxy.server.config.web.routes; package org.fengfei.lanproxy.server.config.web.routes;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.fengfei.lanproxy.common.JsonUtil; import org.fengfei.lanproxy.common.JsonUtil;
import org.fengfei.lanproxy.server.ProxyChannelManager; import org.fengfei.lanproxy.server.ProxyChannelManager;
import org.fengfei.lanproxy.server.config.ProxyConfig; import org.fengfei.lanproxy.server.config.ProxyConfig;
import org.fengfei.lanproxy.server.config.ProxyConfig.Client; import org.fengfei.lanproxy.server.config.ProxyConfig.Client;
import org.fengfei.lanproxy.server.config.web.ApiRoute; import org.fengfei.lanproxy.server.config.web.ApiRoute;
import org.fengfei.lanproxy.server.config.web.RequestHandler; import org.fengfei.lanproxy.server.config.web.RequestHandler;
import org.fengfei.lanproxy.server.config.web.RequestMiddleware; import org.fengfei.lanproxy.server.config.web.RequestMiddleware;
import org.fengfei.lanproxy.server.config.web.ResponseInfo; import org.fengfei.lanproxy.server.config.web.ResponseInfo;
import org.fengfei.lanproxy.server.config.web.exception.ContextException; import org.fengfei.lanproxy.server.config.web.exception.ContextException;
import org.fengfei.lanproxy.server.metrics.MetricsCollector; import org.fengfei.lanproxy.server.metrics.MetricsCollector;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
/** /**
* 接口实现 * 接口实现
* *
* @author fengfei * @author fengfei
* *
*/ */
public class RouteConfig { public class RouteConfig {
protected static final String AUTH_COOKIE_KEY = "token"; /**
* 登陆url
private static Logger logger = LoggerFactory.getLogger(RouteConfig.class); */
public static final String LOGIN_URL = "/login";
/** 管理员不能同时在多个地方登录 */
private static String token; protected static final String AUTH_COOKIE_KEY = "token";
public static void init() { private static Logger logger = LoggerFactory.getLogger(RouteConfig.class);
ApiRoute.addMiddleware(new RequestMiddleware() { /** 管理员不能同时在多个地方登录 */
private static String token;
@Override
public void preRequest(FullHttpRequest request) { public static void init() {
String cookieHeader = request.headers().get(HttpHeaders.Names.COOKIE);
boolean authenticated = false; ApiRoute.addMiddleware(new RequestMiddleware() {
if (cookieHeader != null) {
String[] cookies = cookieHeader.split(";"); @Override
for (String cookie : cookies) { public void preRequest(FullHttpRequest request) {
String[] cookieArr = cookie.split("="); String cookieHeader = request.headers().get(HttpHeaders.Names.COOKIE);
if (AUTH_COOKIE_KEY.equals(cookieArr[0].trim())) { boolean authenticated = false;
if (cookieArr.length == 2 && cookieArr[1].equals(token)) { if (cookieHeader != null) {
authenticated = true; String[] cookies = cookieHeader.split(";");
} for (String cookie : cookies) {
} String[] cookieArr = cookie.split("=");
} if (AUTH_COOKIE_KEY.equals(cookieArr[0].trim())) {
} if (cookieArr.length == 2 && cookieArr[1].equals(token)) {
authenticated = true;
String auth = request.headers().get(HttpHeaders.Names.AUTHORIZATION); }
if (!authenticated && auth != null) { }
String[] authArr = auth.split(" "); }
if (authArr.length == 2 && authArr[0].equals(ProxyConfig.getInstance().getConfigAdminUsername()) && authArr[1].equals(ProxyConfig.getInstance().getConfigAdminPassword())) { }
authenticated = true;
} String auth = request.headers().get(HttpHeaders.Names.AUTHORIZATION);
} if (!authenticated && auth != null) {
String[] authArr = auth.split(" ");
if (!request.getUri().equals("/login") && !authenticated) { if (authArr.length == 2 && authArr[0].equals(ProxyConfig.getInstance().getConfigAdminUsername()) && authArr[1].equals(ProxyConfig.getInstance().getConfigAdminPassword())) {
throw new ContextException(ResponseInfo.CODE_UNAUTHORIZED); authenticated = true;
} }
}
logger.info("handle request for api {}", request.getUri());
} if (!LOGIN_URL.equals(request.getUri()) && !authenticated) {
}); throw new ContextException(ResponseInfo.CODE_UNAUTHORIZED);
}
// 获取配置详细信息
ApiRoute.addRoute("/config/detail", new RequestHandler() { logger.info("handle request for api {}", request.getUri());
}
@Override });
public ResponseInfo request(FullHttpRequest request) {
List<Client> clients = ProxyConfig.getInstance().getClients(); // 获取配置详细信息
for (Client client : clients) { ApiRoute.addRoute("/config/detail", new RequestHandler() {
Channel channel = ProxyChannelManager.getCmdChannel(client.getClientKey());
if (channel != null) { @Override
client.setStatus(1);// online public ResponseInfo request(FullHttpRequest request) {
} else { List<Client> clients = ProxyConfig.getInstance().getClients();
client.setStatus(0);// offline for (Client client : clients) {
} Channel channel = ProxyChannelManager.getCmdChannel(client.getClientKey());
} if (channel != null) {
return ResponseInfo.build(ProxyConfig.getInstance().getClients()); client.setStatus(1);// online
} } else {
}); client.setStatus(0);// offline
}
// 更新配置 }
ApiRoute.addRoute("/config/update", new RequestHandler() { return ResponseInfo.build(ProxyConfig.getInstance().getClients());
}
@Override });
public ResponseInfo request(FullHttpRequest request) {
byte[] buf = new byte[request.content().readableBytes()]; // 更新配置
request.content().readBytes(buf); ApiRoute.addRoute("/config/update", new RequestHandler() {
String config = new String(buf, Charset.forName("UTF-8"));
List<Client> clients = JsonUtil.json2object(config, new TypeToken<List<Client>>() { @Override
}); public ResponseInfo request(FullHttpRequest request) {
if (clients == null) { byte[] buf = new byte[request.content().readableBytes()];
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error json config"); request.content().readBytes(buf);
} String config = new String(buf, Charset.forName("UTF-8"));
List<Client> clients = JsonUtil.json2object(config, new TypeToken<List<Client>>() {
try { });
ProxyConfig.getInstance().update(config); if (clients == null) {
} catch (Exception ex) { return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error json config");
logger.error("config update error", ex); }
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, ex.getMessage());
} try {
ProxyConfig.getInstance().update(config);
return ResponseInfo.build(ResponseInfo.CODE_OK, "success"); } catch (Exception ex) {
} logger.error("config update error", ex);
}); return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, ex.getMessage());
}
ApiRoute.addRoute("/login", new RequestHandler() {
return ResponseInfo.build(ResponseInfo.CODE_OK, "success");
@Override }
public ResponseInfo request(FullHttpRequest request) { });
byte[] buf = new byte[request.content().readableBytes()];
request.content().readBytes(buf); ApiRoute.addRoute("/login", new RequestHandler() {
String config = new String(buf);
Map<String, String> loginParams = JsonUtil.json2object(config, new TypeToken<Map<String, String>>() { @Override
}); public ResponseInfo request(FullHttpRequest request) {
if (loginParams == null) { byte[] buf = new byte[request.content().readableBytes()];
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error login info"); request.content().readBytes(buf);
} String config = new String(buf);
Map<String, String> loginParams = JsonUtil.json2object(config, new TypeToken<Map<String, String>>() {
String username = loginParams.get("username"); });
String password = loginParams.get("password"); if (loginParams == null) {
if (username == null || password == null) { return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error login info");
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error username or password"); }
}
String username = loginParams.get("username");
if (username.equals(ProxyConfig.getInstance().getConfigAdminUsername()) && password.equals(ProxyConfig.getInstance().getConfigAdminPassword())) { String password = loginParams.get("password");
token = UUID.randomUUID().toString().replace("-", ""); if (username == null || password == null) {
return ResponseInfo.build(token); return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error username or password");
} }
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error username or password"); if (username.equals(ProxyConfig.getInstance().getConfigAdminUsername()) && password.equals(ProxyConfig.getInstance().getConfigAdminPassword())) {
} token = UUID.randomUUID().toString().replace("-", "");
}); return ResponseInfo.build(token);
}
ApiRoute.addRoute("/logout", new RequestHandler() {
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error username or password");
@Override }
public ResponseInfo request(FullHttpRequest request) { });
token = null;
return ResponseInfo.build(ResponseInfo.CODE_OK, "success"); ApiRoute.addRoute("/logout", new RequestHandler() {
}
}); @Override
public ResponseInfo request(FullHttpRequest request) {
ApiRoute.addRoute("/metrics/get", new RequestHandler() { token = null;
return ResponseInfo.build(ResponseInfo.CODE_OK, "success");
@Override }
public ResponseInfo request(FullHttpRequest request) { });
return ResponseInfo.build(MetricsCollector.getAllMetrics());
} ApiRoute.addRoute("/metrics/get", new RequestHandler() {
});
@Override
ApiRoute.addRoute("/metrics/getandreset", new RequestHandler() { public ResponseInfo request(FullHttpRequest request) {
return ResponseInfo.build(MetricsCollector.getAllMetrics());
@Override }
public ResponseInfo request(FullHttpRequest request) { });
return ResponseInfo.build(MetricsCollector.getAndResetAllMetrics());
} ApiRoute.addRoute("/metrics/getandreset", new RequestHandler() {
});
} @Override
public ResponseInfo request(FullHttpRequest request) {
} return ResponseInfo.build(MetricsCollector.getAndResetAllMetrics());
}
});
}
}

Loading…
Cancel
Save