Source code reformat

master
Yan 7 months ago
parent 5084c50f1c
commit a2200af1ce

@ -10,22 +10,22 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class Boot { public class Boot {
private static final Logger logger = LoggerFactory.getLogger(Boot.class); private static final Logger logger = LoggerFactory.getLogger(Boot.class);
@Autowired @Autowired
protected SshServer sshd; protected SshServer sshd;
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
String configDirectory = "conf"; String configDirectory = "conf";
if (args.length > 0) { if (args.length > 0) {
configDirectory = args[0]; configDirectory = args[0];
} }
logger.info("config directory: {}", configDirectory); logger.info("config directory: {}", configDirectory);
if (new java.io.File(configDirectory).exists() && new java.io.File(configDirectory).isDirectory()) { if (new java.io.File(configDirectory).exists() && new java.io.File(configDirectory).isDirectory()) {
System.setProperty("spring.config.location", configDirectory + "/springboot.yml"); System.setProperty("spring.config.location", configDirectory + "/springboot.yml");
System.setProperty("logging.config", configDirectory + "/log4j2.xml"); System.setProperty("logging.config", configDirectory + "/log4j2.xml");
}
SpringApplication.run(Boot.class, args);
} }
SpringApplication.run(Boot.class, args);
}
} }

@ -29,42 +29,42 @@ import com.github.benmanes.caffeine.cache.Caffeine;
@ImportResource("file:conf/scheduler.xml") @ImportResource("file:conf/scheduler.xml")
public class AppConfig { public class AppConfig {
@Value("${xmpp-component.config-json}") @Value("${xmpp-component.config-json}")
private String xmppComponentConfigJson; private String xmppComponentConfigJson;
@Bean @Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public XmppComponentConfig xmppComponentConfig() throws StreamReadException, DatabindException, IOException { public XmppComponentConfig xmppComponentConfig() throws StreamReadException, DatabindException, IOException {
return new ObjectMapper().readValue(new java.io.File(xmppComponentConfigJson), XmppComponentConfig.class); return new ObjectMapper().readValue(new java.io.File(xmppComponentConfigJson), XmppComponentConfig.class);
} }
@Bean("userAdminCache") @Bean("userAdminCache")
public Cache<String, Message> userAdminCache() { public Cache<String, Message> userAdminCache() {
return Caffeine.newBuilder().expireAfterWrite(Duration.ofMinutes(1)).build(); return Caffeine.newBuilder().expireAfterWrite(Duration.ofMinutes(1)).build();
} }
@Bean @Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public Map<String, Session> remoteSessionMapping() { public Map<String, Session> remoteSessionMapping() {
return new ConcurrentHashMap<>(); return new ConcurrentHashMap<>();
} }
@Bean @Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public Map<String, String> ipInfoMapping() { public Map<String, String> ipInfoMapping() {
return new ConcurrentHashMap<>(); return new ConcurrentHashMap<>();
} }
@Bean @Bean
public CloseableHttpAsyncClient asyncClient() { public CloseableHttpAsyncClient asyncClient() {
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().build(); final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).build(); final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).build();
client.start(); client.start();
return client; return client;
} }
@Bean @Bean
public CloseableHttpClient httpClient() { public CloseableHttpClient httpClient() {
return HttpClients.createDefault(); return HttpClients.createDefault();
} }
} }

@ -29,72 +29,72 @@ import com.example.sshd.core.OnetimeCommand;
@Configuration @Configuration
public class SshConfig { public class SshConfig {
private static final Logger loginLogger = LoggerFactory.getLogger("login"); private static final Logger loginLogger = LoggerFactory.getLogger("login");
@Value("${ssh-server.port}") @Value("${ssh-server.port}")
private int port; private int port;
@Value("${ssh-server.private-key.location}") @Value("${ssh-server.private-key.location}")
private String pkLocation; private String pkLocation;
@Value("${ssh-server.login.usernames:root}") @Value("${ssh-server.login.usernames:root}")
private String[] usernames; private String[] usernames;
@Value("${ssh-server.hash-replies.location}") @Value("${ssh-server.hash-replies.location}")
private String hashReplies; private String hashReplies;
@Value("${ssh-server.regex-mapping.location}") @Value("${ssh-server.regex-mapping.location}")
private String regexMapping; private String regexMapping;
@Autowired @Autowired
ApplicationContext applicationContext; ApplicationContext applicationContext;
@Bean @Bean
public SshServer sshd() throws IOException, NoSuchAlgorithmException { public SshServer sshd() throws IOException, NoSuchAlgorithmException {
SshServer sshd = SshServer.setUpDefaultServer(); SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(port); sshd.setPort(port);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File(pkLocation).getPath(), "RSA", 2048)); sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File(pkLocation).getPath(), "RSA", 2048));
sshd.setPasswordAuthenticator(new PasswordAuthenticator() { sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
@Override @Override
public boolean authenticate(final String username, final String password, final ServerSession session) { public boolean authenticate(final String username, final String password, final ServerSession session) {
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) { if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress(); InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
String remoteIpAddress = remoteAddress.getAddress().getHostAddress(); String remoteIpAddress = remoteAddress.getAddress().getHostAddress();
loginLogger.info("[{}] Login Attempt: username = {}, password = {}", remoteIpAddress, username, loginLogger.info("[{}] Login Attempt: username = {}, password = {}", remoteIpAddress, username,
password); password);
} else { } else {
loginLogger.info("[{}] Login Attempt: username = {}, password = {}", loginLogger.info("[{}] Login Attempt: username = {}, password = {}",
session.getIoSession().getRemoteAddress(), username, password); session.getIoSession().getRemoteAddress(), username, password);
} }
return Arrays.asList(usernames).contains(username); return Arrays.asList(usernames).contains(username);
} }
}); });
sshd.setShellFactory(applicationContext.getBean(EchoShellFactory.class)); sshd.setShellFactory(applicationContext.getBean(EchoShellFactory.class));
sshd.setCommandFactory(command -> applicationContext.getBean(OnetimeCommand.class, command)); sshd.setCommandFactory(command -> applicationContext.getBean(OnetimeCommand.class, command));
sshd.start(); sshd.start();
sshd.getSessionFactory().addListener(applicationContext.getBean(EchoSessionListener.class)); sshd.getSessionFactory().addListener(applicationContext.getBean(EchoSessionListener.class));
return sshd; return sshd;
} }
@Bean @Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public Properties hashReplies() throws IOException { public Properties hashReplies() throws IOException {
Properties prop = new Properties(); Properties prop = new Properties();
File configFile = new File(hashReplies); File configFile = new File(hashReplies);
FileInputStream stream = new FileInputStream(configFile); FileInputStream stream = new FileInputStream(configFile);
prop.load(stream); prop.load(stream);
return prop; return prop;
} }
@Bean @Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public Properties regexMapping() throws IOException { public Properties regexMapping() throws IOException {
Properties prop = new Properties(); Properties prop = new Properties();
File configFile = new File(regexMapping); File configFile = new File(regexMapping);
FileInputStream stream = new FileInputStream(configFile); FileInputStream stream = new FileInputStream(configFile);
prop.load(stream); prop.load(stream);
return prop; return prop;
} }
} }

@ -8,71 +8,71 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class XmppComponentConfig { public class XmppComponentConfig {
private static final Logger logger = LoggerFactory.getLogger(XmppComponentConfig.class); private static final Logger logger = LoggerFactory.getLogger(XmppComponentConfig.class);
private String subdomainPrefix; private String subdomainPrefix;
private String domain; private String domain;
private String host; private String host;
private int port; private int port;
private String secretKey; private String secretKey;
private boolean startEncrypted; private boolean startEncrypted;
public String getSubdomainPrefix() { public String getSubdomainPrefix() {
return subdomainPrefix; return subdomainPrefix;
} }
public void setSubdomainPrefix(String subdomainPrefix) { public void setSubdomainPrefix(String subdomainPrefix) {
this.subdomainPrefix = subdomainPrefix; this.subdomainPrefix = subdomainPrefix;
} }
public String getDomain() { public String getDomain() {
return domain; return domain;
} }
public void setDomain(String domain) { public void setDomain(String domain) {
this.domain = domain; this.domain = domain;
} }
public String getHost() { public String getHost() {
return host; return host;
} }
public void setHost(String host) { public void setHost(String host) {
this.host = host; this.host = host;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
} }
public String getSecretKey() { public String getSecretKey() {
return secretKey; return secretKey;
} }
public void setSecretKey(String secretKey) { public void setSecretKey(String secretKey) {
this.secretKey = secretKey; this.secretKey = secretKey;
} }
public boolean isStartEncrypted() { public boolean isStartEncrypted() {
return startEncrypted; return startEncrypted;
} }
public void setStartEncrypted(boolean startEncrypted) { public void setStartEncrypted(boolean startEncrypted) {
this.startEncrypted = startEncrypted; this.startEncrypted = startEncrypted;
} }
@Override @Override
@JsonIgnore @JsonIgnore
public String toString() { public String toString() {
try { try {
return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this); return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
logger.error("convert to json error!", e); logger.error("convert to json error!", e);
}
return "{}";
} }
return "{}";
}
} }

@ -17,66 +17,66 @@ import com.example.sshd.service.JdbcService;
@Component @Component
public class EchoSessionListener implements SessionListener { public class EchoSessionListener implements SessionListener {
private static final Logger logger = LoggerFactory.getLogger(EchoSessionListener.class); private static final Logger logger = LoggerFactory.getLogger(EchoSessionListener.class);
private static final Logger ipInfoLogger = LoggerFactory.getLogger("ip_info"); private static final Logger ipInfoLogger = LoggerFactory.getLogger("ip_info");
@Autowired @Autowired
Map<String, Session> remoteSessionMapping; Map<String, Session> remoteSessionMapping;
@Autowired @Autowired
Map<String, String> ipInfoMapping; Map<String, String> ipInfoMapping;
@Autowired @Autowired
GeoIpLocator geoIpLocator; GeoIpLocator geoIpLocator;
@Autowired @Autowired
JdbcService jdbcService; JdbcService jdbcService;
@Override @Override
public void sessionCreated(Session session) { public void sessionCreated(Session session) {
logger.info("sessionCreated: {}", session); logger.info("sessionCreated: {}", session);
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) { if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress(); InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
String remoteIpAddress = remoteAddress.getAddress().getHostAddress(); String remoteIpAddress = remoteAddress.getAddress().getHostAddress();
if (remoteSessionMapping.containsKey(remoteIpAddress)) { if (remoteSessionMapping.containsKey(remoteIpAddress)) {
logger.info("kill old session: {} -> {}", remoteIpAddress, remoteSessionMapping.get(remoteIpAddress)); logger.info("kill old session: {} -> {}", remoteIpAddress, remoteSessionMapping.get(remoteIpAddress));
remoteSessionMapping.get(remoteIpAddress).close(false); remoteSessionMapping.get(remoteIpAddress).close(false);
} }
logger.info("new session: {} -> {}", remoteIpAddress, session); logger.info("new session: {} -> {}", remoteIpAddress, session);
remoteSessionMapping.put(remoteIpAddress, session); remoteSessionMapping.put(remoteIpAddress, session);
if (!ipInfoMapping.containsKey(remoteIpAddress)) { if (!ipInfoMapping.containsKey(remoteIpAddress)) {
List<Map<String, Object>> ipInfoList = jdbcService.getAllRemoteIpInfo(remoteIpAddress); List<Map<String, Object>> ipInfoList = jdbcService.getAllRemoteIpInfo(remoteIpAddress);
if (!ipInfoList.isEmpty()) { if (!ipInfoList.isEmpty()) {
ipInfoMapping.put(remoteIpAddress, (String) ipInfoList.get(0).get("remote_ip_info")); ipInfoMapping.put(remoteIpAddress, (String) ipInfoList.get(0).get("remote_ip_info"));
}
}
} }
}
} }
}
@Override @Override
public void sessionEvent(Session session, Event event) { public void sessionEvent(Session session, Event event) {
logger.info("sessionEvent: {}, event: {}", session, event); logger.info("sessionEvent: {}, event: {}", session, event);
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress && event == Event.KexCompleted) { if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress && event == Event.KexCompleted) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress(); InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
String remoteIpAddress = remoteAddress.getAddress().getHostAddress(); String remoteIpAddress = remoteAddress.getAddress().getHostAddress();
if (!ipInfoMapping.containsKey(remoteIpAddress)) { if (!ipInfoMapping.containsKey(remoteIpAddress)) {
geoIpLocator.asyncUpdateIpLocationInfo(remoteIpAddress); geoIpLocator.asyncUpdateIpLocationInfo(remoteIpAddress);
} else { } else {
ipInfoLogger.debug("[{}] {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress)); ipInfoLogger.debug("[{}] {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress));
} }
}
} }
}
@Override @Override
public void sessionClosed(Session session) { public void sessionClosed(Session session) {
logger.info("sessionClosed: {}", session); logger.info("sessionClosed: {}", session);
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) { if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress(); InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
String remoteIpAddress = remoteAddress.getAddress().getHostAddress(); String remoteIpAddress = remoteAddress.getAddress().getHostAddress();
logger.info("removing session: {} -> {}", remoteIpAddress, remoteSessionMapping.get(remoteIpAddress)); logger.info("removing session: {} -> {}", remoteIpAddress, remoteSessionMapping.get(remoteIpAddress));
remoteSessionMapping.remove(remoteIpAddress); remoteSessionMapping.remove(remoteIpAddress);
ipInfoMapping.remove(remoteIpAddress); ipInfoMapping.remove(remoteIpAddress);
}
} }
}
} }

@ -28,119 +28,119 @@ import com.example.sshd.service.ReplyService;
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class EchoShell implements Command, Runnable, SessionAware { public class EchoShell implements Command, Runnable, SessionAware {
private static final Logger logger = LoggerFactory.getLogger(EchoShell.class); private static final Logger logger = LoggerFactory.getLogger(EchoShell.class);
@Autowired @Autowired
ReplyService replyUtil; ReplyService replyUtil;
@Autowired @Autowired
Properties hashReplies; Properties hashReplies;
protected InputStream in; protected InputStream in;
protected OutputStream out; protected OutputStream out;
protected OutputStream err; protected OutputStream err;
protected ExitCallback callback; protected ExitCallback callback;
protected Environment environment; protected Environment environment;
protected Thread thread; protected Thread thread;
protected ServerSession session; protected ServerSession session;
@Override @Override
public void setInputStream(InputStream in) { public void setInputStream(InputStream in) {
this.in = in; this.in = in;
} }
@Override @Override
public void setOutputStream(OutputStream out) { public void setOutputStream(OutputStream out) {
this.out = out; this.out = out;
} }
@Override @Override
public void setErrorStream(OutputStream err) { public void setErrorStream(OutputStream err) {
this.err = err; this.err = err;
} }
@Override @Override
public void setExitCallback(ExitCallback callback) { public void setExitCallback(ExitCallback callback) {
this.callback = callback; this.callback = callback;
} }
@Override @Override
public void start(Environment env) throws IOException { public void start(Environment env) throws IOException {
environment = env; environment = env;
thread = new Thread(this, remoteIpAddress()); thread = new Thread(this, remoteIpAddress());
logger.info("environment: {}, thread-name: {}", environment.getEnv(), thread.getName()); logger.info("environment: {}, thread-name: {}", environment.getEnv(), thread.getName());
thread.start(); thread.start();
}
protected String remoteIpAddress() {
String remoteIpAddress = "";
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
remoteIpAddress = remoteAddress.getAddress().getHostAddress();
} else {
remoteIpAddress = session.getIoSession().getRemoteAddress().toString();
} }
return remoteIpAddress;
}
@Override
public void destroy() {
thread.interrupt();
}
@Override
public void run() {
String prompt = hashReplies.getProperty("prompt", "$ ").replace("{user}", environment.getEnv().get("USER"));
try {
out.write(prompt.getBytes());
out.flush();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String command = "";
while (!Thread.currentThread().isInterrupted()) {
int s = r.read();
if (s == 13 || s == 10) {
boolean containsExit = Arrays.asList(StringUtils.split(command, ";|&")).stream().map(cmd -> {
boolean wantsExit = false;
try {
wantsExit = replyUtil.replyToCommand(cmd.trim(), out, prompt, session);
out.flush();
} catch (Exception e) {
logger.error("run error!", e);
}
return wantsExit;
}).reduce((a, b) -> a || b).get();
if (containsExit) { protected String remoteIpAddress() {
break; String remoteIpAddress = "";
}
command = ""; if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
remoteIpAddress = remoteAddress.getAddress().getHostAddress();
} else { } else {
logger.trace("input character: {}", s); remoteIpAddress = session.getIoSession().getRemoteAddress().toString();
if (s == 127) { }
if (command.length() > 0) { return remoteIpAddress;
command = command.substring(0, command.length() - 1); }
out.write(s);
@Override
public void destroy() {
thread.interrupt();
}
@Override
public void run() {
String prompt = hashReplies.getProperty("prompt", "$ ").replace("{user}", environment.getEnv().get("USER"));
try {
out.write(prompt.getBytes());
out.flush();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String command = "";
while (!Thread.currentThread().isInterrupted()) {
int s = r.read();
if (s == 13 || s == 10) {
boolean containsExit = Arrays.asList(StringUtils.split(command, ";|&")).stream().map(cmd -> {
boolean wantsExit = false;
try {
wantsExit = replyUtil.replyToCommand(cmd.trim(), out, prompt, session);
out.flush();
} catch (Exception e) {
logger.error("run error!", e);
}
return wantsExit;
}).reduce((a, b) -> a || b).get();
if (containsExit) {
break;
}
command = "";
} else {
logger.trace("input character: {}", s);
if (s == 127) {
if (command.length() > 0) {
command = command.substring(0, command.length() - 1);
out.write(s);
}
} else if (s >= 32 && s < 127) {
command += (char) s;
out.write(s);
}
}
out.flush();
} }
} else if (s >= 32 && s < 127) { } catch (Exception e) {
command += (char) s; logger.error("run error!", e);
out.write(s); } finally {
} callback.onExit(0);
} }
out.flush();
}
} catch (Exception e) {
logger.error("run error!", e);
} finally {
callback.onExit(0);
} }
}
@Override @Override
public void setSession(ServerSession session) { public void setSession(ServerSession session) {
this.session = session; this.session = session;
} }
} }

@ -9,12 +9,12 @@ import org.springframework.stereotype.Component;
@Component @Component
public class EchoShellFactory implements Factory<Command> { public class EchoShellFactory implements Factory<Command> {
@Autowired @Autowired
ApplicationContext applicationContext; ApplicationContext applicationContext;
@Override @Override
public Command create() { public Command create() {
return (Command) applicationContext.getBean("echoShell"); return (Command) applicationContext.getBean("echoShell");
} }
} }

@ -13,29 +13,29 @@ import org.springframework.stereotype.Component;
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class OnetimeCommand extends EchoShell { public class OnetimeCommand extends EchoShell {
private static final Logger logger = LoggerFactory.getLogger(OnetimeCommand.class); private static final Logger logger = LoggerFactory.getLogger(OnetimeCommand.class);
private String command; private String command;
public OnetimeCommand(String cmd) { public OnetimeCommand(String cmd) {
command = cmd; command = cmd;
} }
@Override @Override
public void run() { public void run() {
try {
Arrays.asList(StringUtils.split(command, ";|&")).stream().forEach(cmd -> {
try { try {
replyUtil.replyToCommand(cmd.trim(), out, "", session); Arrays.asList(StringUtils.split(command, ";|&")).stream().forEach(cmd -> {
out.flush(); try {
replyUtil.replyToCommand(cmd.trim(), out, "", session);
out.flush();
} catch (Exception e) {
logger.error("run error!", e);
}
});
} catch (Exception e) { } catch (Exception e) {
logger.error("run error!", e); logger.error("run error!", e);
} finally {
callback.onExit(0);
} }
});
} catch (Exception e) {
logger.error("run error!", e);
} finally {
callback.onExit(0);
} }
}
} }

@ -23,290 +23,290 @@ import jakarta.annotation.PostConstruct;
@Component @Component
public class EchoComponent extends AbstractComponent { public class EchoComponent extends AbstractComponent {
private static final Logger logger = LoggerFactory.getLogger(EchoComponent.class); private static final Logger logger = LoggerFactory.getLogger(EchoComponent.class);
public static final String CONST_OPERATION_ADD_USER = "adduser"; public static final String CONST_OPERATION_ADD_USER = "adduser";
public static final String CONST_OPERATION_CHANGE_USER_PASSWORD = "chgpasswd"; public static final String CONST_OPERATION_CHANGE_USER_PASSWORD = "chgpasswd";
public static final String CONST_OPERATION_DELETE_USER = "deluser"; public static final String CONST_OPERATION_DELETE_USER = "deluser";
public static final String CONST_OPERATION_JMX_CLIENT = "jmx_client"; public static final String CONST_OPERATION_JMX_CLIENT = "jmx_client";
@Autowired @Autowired
XmppComponentConfig xmppComponentConfig; XmppComponentConfig xmppComponentConfig;
@Autowired @Autowired
ReplyService replyService; ReplyService replyService;
@Autowired @Autowired
JmxClientService jmxClientService; JmxClientService jmxClientService;
@Autowired
@Qualifier("userAdminCache")
private volatile Cache<String, Message> userAdminCache;
ExternalComponentManager externalComponentManager = null; @Autowired
@Qualifier("userAdminCache")
private volatile Cache<String, Message> userAdminCache;
@PostConstruct ExternalComponentManager externalComponentManager = null;
public void init() throws ComponentException {
logger.info("Starting up {} ...", xmppComponentConfig);
externalComponentManager = new ExternalComponentManager(xmppComponentConfig.getHost(),
xmppComponentConfig.getPort(), xmppComponentConfig.isStartEncrypted());
externalComponentManager.setMultipleAllowed(xmppComponentConfig.getSubdomainPrefix(), false);
externalComponentManager.setServerName(xmppComponentConfig.getDomain());
externalComponentManager.setSecretKey(xmppComponentConfig.getSubdomainPrefix(),
xmppComponentConfig.getSecretKey());
externalComponentManager.addComponent(xmppComponentConfig.getSubdomainPrefix(), this,
xmppComponentConfig.getPort());
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
externalComponentManager.removeComponent(xmppComponentConfig.getSubdomainPrefix());
} catch (ComponentException e) {
e.printStackTrace();
}
}));
}
@Override @PostConstruct
public String getDescription() { public void init() throws ComponentException {
return "XMPP component for doing ECHO"; logger.info("Starting up {} ...", xmppComponentConfig);
} externalComponentManager = new ExternalComponentManager(xmppComponentConfig.getHost(),
xmppComponentConfig.getPort(), xmppComponentConfig.isStartEncrypted());
externalComponentManager.setMultipleAllowed(xmppComponentConfig.getSubdomainPrefix(), false);
externalComponentManager.setServerName(xmppComponentConfig.getDomain());
externalComponentManager.setSecretKey(xmppComponentConfig.getSubdomainPrefix(),
xmppComponentConfig.getSecretKey());
externalComponentManager.addComponent(xmppComponentConfig.getSubdomainPrefix(), this,
xmppComponentConfig.getPort());
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
externalComponentManager.removeComponent(xmppComponentConfig.getSubdomainPrefix());
} catch (ComponentException e) {
e.printStackTrace();
}
}));
}
@Override @Override
public String getName() { public String getDescription() {
return this.getClass().getName(); return "XMPP component for doing ECHO";
} }
public void sendMessage(String fromJID, String toJID, String message) { @Override
try { public String getName() {
Message outMsg = new Message(); return this.getClass().getName();
outMsg.setType(Message.Type.chat);
outMsg.setFrom(fromJID);
outMsg.setTo(toJID);
outMsg.setBody(replyService.executeShellCommand(message));
externalComponentManager.sendPacket(this, outMsg);
logger.info("[sendMessage] -- SENT -- {}", outMsg);
} catch (Exception err) {
logger.error("[sendMessage] ", err);
} }
}
public void sendMessage(String fromJID, String toJID, String message) {
private void doEcho(final Message inMsg, String body) { try {
try { Message outMsg = new Message();
Message outMsg = new Message(); outMsg.setType(Message.Type.chat);
outMsg.setType(inMsg.getType()); outMsg.setFrom(fromJID);
outMsg.setFrom(inMsg.getTo()); outMsg.setTo(toJID);
if (StringUtils.endsWith(inMsg.getSubject(), "@" + xmppComponentConfig.getDomain())) { outMsg.setBody(replyService.executeShellCommand(message));
outMsg.setTo(inMsg.getSubject()); externalComponentManager.sendPacket(this, outMsg);
} else { logger.info("[sendMessage] -- SENT -- {}", outMsg);
outMsg.setTo(inMsg.getFrom()); } catch (Exception err) {
} logger.error("[sendMessage] ", err);
outMsg.setSubject(inMsg.getSubject()); }
outMsg.setBody(body == null ? inMsg.getBody() : body);
externalComponentManager.sendPacket(this, outMsg);
logger.info("[doEcho] -- SENT -- {}", outMsg);
} catch (Exception err) {
logger.error("[doEcho] ", err);
} }
}
protected void handleMessage(final Message inMsg) { private void doEcho(final Message inMsg, String body) {
logger.info("[handleMessage] -- RECEIVED -- {}", inMsg); try {
try { Message outMsg = new Message();
if (StringUtils.isNotBlank(inMsg.getBody())) { outMsg.setType(inMsg.getType());
String[] commandParts = StringUtils.split(inMsg.getBody().trim(), ' '); outMsg.setFrom(inMsg.getTo());
switch (commandParts[0]) { if (StringUtils.endsWith(inMsg.getSubject(), "@" + xmppComponentConfig.getDomain())) {
case CONST_OPERATION_ADD_USER: outMsg.setTo(inMsg.getSubject());
if (commandParts.length == 3) } else {
requestAddUserForm(inMsg); outMsg.setTo(inMsg.getFrom());
else }
doEcho(inMsg, "adduser <username> <password>"); outMsg.setSubject(inMsg.getSubject());
break; outMsg.setBody(body == null ? inMsg.getBody() : body);
case CONST_OPERATION_DELETE_USER: externalComponentManager.sendPacket(this, outMsg);
if (commandParts.length == 2) logger.info("[doEcho] -- SENT -- {}", outMsg);
requestDeleteUserForm(inMsg); } catch (Exception err) {
else logger.error("[doEcho] ", err);
doEcho(inMsg, "deluser <username>");
break;
case CONST_OPERATION_CHANGE_USER_PASSWORD:
if (commandParts.length == 3)
requestChangeUserPassword(inMsg);
else
doEcho(inMsg, "chgpasswd <username> <new_password>");
break;
case CONST_OPERATION_JMX_CLIENT:
doEcho(inMsg, jmxClientService.process(commandParts));
break;
default:
doEcho(inMsg, replyService.executeShellCommand(inMsg.getBody().trim()));
break;
} }
}
} catch (Exception err) {
logger.error("[handleMessage] ", err);
} }
}
@Override protected void handleMessage(final Message inMsg) {
protected void handleIQResult(IQ iq) { logger.info("[handleMessage] -- RECEIVED -- {}", inMsg);
try { try {
logger.debug("[handleIQResult] {} has received iq-result: {}", getName(), iq); if (StringUtils.isNotBlank(inMsg.getBody())) {
if (iq.getChildElement() != null) { String[] commandParts = StringUtils.split(inMsg.getBody().trim(), ' ');
logger.debug("[{}] {}'s child-namespace: {}", iq.getID(), getName(), switch (commandParts[0]) {
iq.getChildElement().getNamespace()); case CONST_OPERATION_ADD_USER:
logger.debug("[{}] {}'s child-name: {}", iq.getID(), getName(), iq.getChildElement().getName()); if (commandParts.length == 3)
if (iq.getChildElement().getNamespace().equals(Namespace.get("http://jabber.org/protocol/commands")) requestAddUserForm(inMsg);
&& iq.getChildElement().getName().equals("command")) { else
Message inMsg = userAdminCache.getIfPresent(iq.getID()); doEcho(inMsg, "adduser <username> <password>");
handleCommands(iq.getID(), inMsg, iq.getChildElement()); break;
case CONST_OPERATION_DELETE_USER:
if (commandParts.length == 2)
requestDeleteUserForm(inMsg);
else
doEcho(inMsg, "deluser <username>");
break;
case CONST_OPERATION_CHANGE_USER_PASSWORD:
if (commandParts.length == 3)
requestChangeUserPassword(inMsg);
else
doEcho(inMsg, "chgpasswd <username> <new_password>");
break;
case CONST_OPERATION_JMX_CLIENT:
doEcho(inMsg, jmxClientService.process(commandParts));
break;
default:
doEcho(inMsg, replyService.executeShellCommand(inMsg.getBody().trim()));
break;
}
}
} catch (Exception err) {
logger.error("[handleMessage] ", err);
} }
}
} catch (Exception err) {
logger.error("[handleIQResult] ", err);
} }
}
protected void handleCommands(String id, Message inMsg, Element command) throws InterruptedException { @Override
String status = command.attributeValue("status"); protected void handleIQResult(IQ iq) {
String node = command.attributeValue("node"); try {
String sessionid = command.attributeValue("sessionid"); logger.debug("[handleIQResult] {} has received iq-result: {}", getName(), iq);
logger.debug("[{}] sessionid: {}, status: {}, node: {}", id, sessionid, status, node); if (iq.getChildElement() != null) {
if (status.equals("executing")) { logger.debug("[{}] {}'s child-namespace: {}", iq.getID(), getName(),
if (node.equals("http://jabber.org/protocol/admin#add-user")) { iq.getChildElement().getNamespace());
sendAddUserForm(sessionid, inMsg); logger.debug("[{}] {}'s child-name: {}", iq.getID(), getName(), iq.getChildElement().getName());
} else if (node.equals("http://jabber.org/protocol/admin#delete-user")) { if (iq.getChildElement().getNamespace().equals(Namespace.get("http://jabber.org/protocol/commands"))
sendDeleteUserForm(sessionid, inMsg); && iq.getChildElement().getName().equals("command")) {
} else if (node.equals("http://jabber.org/protocol/admin#change-user-password")) { Message inMsg = userAdminCache.getIfPresent(iq.getID());
sendChangeUserPasswordForm(sessionid, inMsg); handleCommands(iq.getID(), inMsg, iq.getChildElement());
} }
} else if (status.equals("completed")) { }
doEcho(inMsg, "OK"); } catch (Exception err) {
logger.error("[handleIQResult] ", err);
}
} }
}
public void requestAddUserForm(Message inMsg) { protected void handleCommands(String id, Message inMsg, Element command) throws InterruptedException {
try { String status = command.attributeValue("status");
IQ addUserIq = new IQ(Type.set); String node = command.attributeValue("node");
addUserIq.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain()); String sessionid = command.attributeValue("sessionid");
addUserIq.setTo(xmppComponentConfig.getDomain()); logger.debug("[{}] sessionid: {}, status: {}, node: {}", id, sessionid, status, node);
Element child = addUserIq.setChildElement("command", "http://jabber.org/protocol/commands"); if (status.equals("executing")) {
child.addAttribute("action", "execute"); if (node.equals("http://jabber.org/protocol/admin#add-user")) {
child.addAttribute("node", "http://jabber.org/protocol/admin#add-user"); sendAddUserForm(sessionid, inMsg);
userAdminCache.put(addUserIq.getID(), inMsg); } else if (node.equals("http://jabber.org/protocol/admin#delete-user")) {
externalComponentManager.sendPacket(this, addUserIq); sendDeleteUserForm(sessionid, inMsg);
logger.info("[requestAddUserForm] -- SENT -- {}", addUserIq); } else if (node.equals("http://jabber.org/protocol/admin#change-user-password")) {
} catch (Exception err) { sendChangeUserPasswordForm(sessionid, inMsg);
logger.error("[requestAddUserForm] ", err); }
} else if (status.equals("completed")) {
doEcho(inMsg, "OK");
}
} }
}
private void createFormTypeElement(Element x, String var, String type, String value) { public void requestAddUserForm(Message inMsg) {
Element formType = x.addElement("field"); try {
formType.addAttribute("var", var); IQ addUserIq = new IQ(Type.set);
if (type != null) { addUserIq.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain());
formType.addAttribute("type", type); addUserIq.setTo(xmppComponentConfig.getDomain());
Element child = addUserIq.setChildElement("command", "http://jabber.org/protocol/commands");
child.addAttribute("action", "execute");
child.addAttribute("node", "http://jabber.org/protocol/admin#add-user");
userAdminCache.put(addUserIq.getID(), inMsg);
externalComponentManager.sendPacket(this, addUserIq);
logger.info("[requestAddUserForm] -- SENT -- {}", addUserIq);
} catch (Exception err) {
logger.error("[requestAddUserForm] ", err);
}
} }
formType.addElement("value").setText(value);
}
public void sendAddUserForm(String sessionId, Message inMsg) { private void createFormTypeElement(Element x, String var, String type, String value) {
try { Element formType = x.addElement("field");
String[] commandParts = StringUtils.split(inMsg.getBody(), ' '); formType.addAttribute("var", var);
IQ addUserIq = new IQ(Type.set); if (type != null) {
addUserIq.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain()); formType.addAttribute("type", type);
addUserIq.setTo(xmppComponentConfig.getDomain()); }
Element child = addUserIq.setChildElement("command", "http://jabber.org/protocol/commands"); formType.addElement("value").setText(value);
child.addAttribute("node", "http://jabber.org/protocol/admin#add-user");
child.addAttribute("sessionid", sessionId);
Element x = child.addElement("x", "jabber:x:data");
x.addAttribute("type", "submit");
createFormTypeElement(x, "FORM_TYPE", "hidden", "http://jabber.org/protocol/admin");
createFormTypeElement(x, "accountjid", "jid-single",
commandParts[1] + "@" + xmppComponentConfig.getDomain());
createFormTypeElement(x, "password", "text-private", commandParts[2]);
createFormTypeElement(x, "password-verify", "text-private", commandParts[2]);
userAdminCache.put(addUserIq.getID(), inMsg);
externalComponentManager.sendPacket(this, addUserIq);
logger.info("[sendAddUserForm] -- SENT -- {}", addUserIq);
} catch (Exception err) {
logger.error("[sendAddUserForm] ", err);
} }
}
public void requestDeleteUserForm(Message inMsg) { public void sendAddUserForm(String sessionId, Message inMsg) {
try { try {
IQ deleteUserIq = new IQ(Type.set); String[] commandParts = StringUtils.split(inMsg.getBody(), ' ');
deleteUserIq.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain()); IQ addUserIq = new IQ(Type.set);
deleteUserIq.setTo(xmppComponentConfig.getDomain()); addUserIq.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain());
Element child = deleteUserIq.setChildElement("command", "http://jabber.org/protocol/commands"); addUserIq.setTo(xmppComponentConfig.getDomain());
child.addAttribute("action", "execute"); Element child = addUserIq.setChildElement("command", "http://jabber.org/protocol/commands");
child.addAttribute("node", "http://jabber.org/protocol/admin#delete-user"); child.addAttribute("node", "http://jabber.org/protocol/admin#add-user");
userAdminCache.put(deleteUserIq.getID(), inMsg); child.addAttribute("sessionid", sessionId);
externalComponentManager.sendPacket(this, deleteUserIq); Element x = child.addElement("x", "jabber:x:data");
logger.info("[requestDeleteUserForm] -- SENT -- {}", deleteUserIq); x.addAttribute("type", "submit");
} catch (Exception err) { createFormTypeElement(x, "FORM_TYPE", "hidden", "http://jabber.org/protocol/admin");
logger.error("[requestDeleteUserForm] ", err); createFormTypeElement(x, "accountjid", "jid-single",
commandParts[1] + "@" + xmppComponentConfig.getDomain());
createFormTypeElement(x, "password", "text-private", commandParts[2]);
createFormTypeElement(x, "password-verify", "text-private", commandParts[2]);
userAdminCache.put(addUserIq.getID(), inMsg);
externalComponentManager.sendPacket(this, addUserIq);
logger.info("[sendAddUserForm] -- SENT -- {}", addUserIq);
} catch (Exception err) {
logger.error("[sendAddUserForm] ", err);
}
} }
}
public void sendDeleteUserForm(String sessionId, Message inMsg) { public void requestDeleteUserForm(Message inMsg) {
try { try {
String[] commandParts = StringUtils.split(inMsg.getBody(), ' '); IQ deleteUserIq = new IQ(Type.set);
IQ deleteUserIq = new IQ(Type.set); deleteUserIq.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain());
deleteUserIq.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain()); deleteUserIq.setTo(xmppComponentConfig.getDomain());
deleteUserIq.setTo(xmppComponentConfig.getDomain()); Element child = deleteUserIq.setChildElement("command", "http://jabber.org/protocol/commands");
Element child = deleteUserIq.setChildElement("command", "http://jabber.org/protocol/commands"); child.addAttribute("action", "execute");
child.addAttribute("node", "http://jabber.org/protocol/admin#delete-user"); child.addAttribute("node", "http://jabber.org/protocol/admin#delete-user");
child.addAttribute("sessionid", sessionId); userAdminCache.put(deleteUserIq.getID(), inMsg);
Element x = child.addElement("x", "jabber:x:data"); externalComponentManager.sendPacket(this, deleteUserIq);
x.addAttribute("type", "submit"); logger.info("[requestDeleteUserForm] -- SENT -- {}", deleteUserIq);
createFormTypeElement(x, "FORM_TYPE", "hidden", "http://jabber.org/protocol/admin"); } catch (Exception err) {
createFormTypeElement(x, "accountjids", "jid-single", logger.error("[requestDeleteUserForm] ", err);
commandParts[1] + "@" + xmppComponentConfig.getDomain()); }
userAdminCache.put(deleteUserIq.getID(), inMsg);
externalComponentManager.sendPacket(this, deleteUserIq);
logger.info("[sendDeleteUserForm] -- SENT -- {}", deleteUserIq);
} catch (Exception err) {
logger.error("[sendDeleteUserForm] ", err);
} }
}
public void requestChangeUserPassword(Message inMsg) { public void sendDeleteUserForm(String sessionId, Message inMsg) {
try { try {
IQ changeUserPasswordIq = new IQ(Type.set); String[] commandParts = StringUtils.split(inMsg.getBody(), ' ');
changeUserPasswordIq IQ deleteUserIq = new IQ(Type.set);
.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain()); deleteUserIq.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain());
changeUserPasswordIq.setTo(xmppComponentConfig.getDomain()); deleteUserIq.setTo(xmppComponentConfig.getDomain());
Element child = changeUserPasswordIq.setChildElement("command", "http://jabber.org/protocol/commands"); Element child = deleteUserIq.setChildElement("command", "http://jabber.org/protocol/commands");
child.addAttribute("action", "execute"); child.addAttribute("node", "http://jabber.org/protocol/admin#delete-user");
child.addAttribute("node", "http://jabber.org/protocol/admin#change-user-password"); child.addAttribute("sessionid", sessionId);
userAdminCache.put(changeUserPasswordIq.getID(), inMsg); Element x = child.addElement("x", "jabber:x:data");
externalComponentManager.sendPacket(this, changeUserPasswordIq); x.addAttribute("type", "submit");
logger.info("[requestChangeUserPassword] -- SENT -- {}", changeUserPasswordIq); createFormTypeElement(x, "FORM_TYPE", "hidden", "http://jabber.org/protocol/admin");
} catch (Exception err) { createFormTypeElement(x, "accountjids", "jid-single",
logger.error("[requestChangeUserPassword] ", err); commandParts[1] + "@" + xmppComponentConfig.getDomain());
userAdminCache.put(deleteUserIq.getID(), inMsg);
externalComponentManager.sendPacket(this, deleteUserIq);
logger.info("[sendDeleteUserForm] -- SENT -- {}", deleteUserIq);
} catch (Exception err) {
logger.error("[sendDeleteUserForm] ", err);
}
} }
}
public void sendChangeUserPasswordForm(String sessionId, Message inMsg) { public void requestChangeUserPassword(Message inMsg) {
try { try {
String[] commandParts = StringUtils.split(inMsg.getBody(), ' '); IQ changeUserPasswordIq = new IQ(Type.set);
IQ changeUserPasswordIq = new IQ(Type.set); changeUserPasswordIq
changeUserPasswordIq .setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain());
.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain()); changeUserPasswordIq.setTo(xmppComponentConfig.getDomain());
changeUserPasswordIq.setTo(xmppComponentConfig.getDomain()); Element child = changeUserPasswordIq.setChildElement("command", "http://jabber.org/protocol/commands");
Element child = changeUserPasswordIq.setChildElement("command", "http://jabber.org/protocol/commands"); child.addAttribute("action", "execute");
child.addAttribute("node", "http://jabber.org/protocol/admin#change-user-password"); child.addAttribute("node", "http://jabber.org/protocol/admin#change-user-password");
child.addAttribute("sessionid", sessionId); userAdminCache.put(changeUserPasswordIq.getID(), inMsg);
Element x = child.addElement("x", "jabber:x:data"); externalComponentManager.sendPacket(this, changeUserPasswordIq);
x.addAttribute("type", "submit"); logger.info("[requestChangeUserPassword] -- SENT -- {}", changeUserPasswordIq);
createFormTypeElement(x, "FORM_TYPE", "hidden", "http://jabber.org/protocol/admin"); } catch (Exception err) {
createFormTypeElement(x, "accountjid", "jid-single", logger.error("[requestChangeUserPassword] ", err);
commandParts[1] + "@" + xmppComponentConfig.getDomain()); }
createFormTypeElement(x, "password", "text-private", commandParts[2]); }
userAdminCache.put(changeUserPasswordIq.getID(), inMsg);
externalComponentManager.sendPacket(this, changeUserPasswordIq); public void sendChangeUserPasswordForm(String sessionId, Message inMsg) {
logger.info("[sendChangeUserPasswordForm] -- SENT -- {}", changeUserPasswordIq); try {
} catch (Exception err) { String[] commandParts = StringUtils.split(inMsg.getBody(), ' ');
logger.error("[sendChangeUserPasswordForm] ", err); IQ changeUserPasswordIq = new IQ(Type.set);
changeUserPasswordIq
.setFrom(xmppComponentConfig.getSubdomainPrefix() + "." + xmppComponentConfig.getDomain());
changeUserPasswordIq.setTo(xmppComponentConfig.getDomain());
Element child = changeUserPasswordIq.setChildElement("command", "http://jabber.org/protocol/commands");
child.addAttribute("node", "http://jabber.org/protocol/admin#change-user-password");
child.addAttribute("sessionid", sessionId);
Element x = child.addElement("x", "jabber:x:data");
x.addAttribute("type", "submit");
createFormTypeElement(x, "FORM_TYPE", "hidden", "http://jabber.org/protocol/admin");
createFormTypeElement(x, "accountjid", "jid-single",
commandParts[1] + "@" + xmppComponentConfig.getDomain());
createFormTypeElement(x, "password", "text-private", commandParts[2]);
userAdminCache.put(changeUserPasswordIq.getID(), inMsg);
externalComponentManager.sendPacket(this, changeUserPasswordIq);
logger.info("[sendChangeUserPasswordForm] -- SENT -- {}", changeUserPasswordIq);
} catch (Exception err) {
logger.error("[sendChangeUserPasswordForm] ", err);
}
} }
}
} }

@ -22,74 +22,74 @@ import org.springframework.stereotype.Service;
@Service @Service
public class GeoIpLocator { public class GeoIpLocator {
private static final Logger logger = LoggerFactory.getLogger(GeoIpLocator.class); private static final Logger logger = LoggerFactory.getLogger(GeoIpLocator.class);
private static final Logger ipInfoLogger = LoggerFactory.getLogger("ip_info"); private static final Logger ipInfoLogger = LoggerFactory.getLogger("ip_info");
@Autowired @Autowired
Map<String, String> ipInfoMapping; Map<String, String> ipInfoMapping;
@Autowired @Autowired
JdbcService jdbcService; JdbcService jdbcService;
@Autowired @Autowired
CloseableHttpAsyncClient asyncClient; CloseableHttpAsyncClient asyncClient;
@Autowired @Autowired
CloseableHttpClient httpClient; CloseableHttpClient httpClient;
@Value("${ssh-server.ip-info-api.url:http://ip-api.com/json/%s}") @Value("${ssh-server.ip-info-api.url:http://ip-api.com/json/%s}")
private String ipInfoApiUrl; private String ipInfoApiUrl;
@Value("${ssh-server.ip-info-api.method:GET}") @Value("${ssh-server.ip-info-api.method:GET}")
private String ipInfoApiMethod; private String ipInfoApiMethod;
public String getIpLocationInfo(String remoteIpAddress) { public String getIpLocationInfo(String remoteIpAddress) {
HttpGet httpGet = new HttpGet(String.format(ipInfoApiUrl, remoteIpAddress)); HttpGet httpGet = new HttpGet(String.format(ipInfoApiUrl, remoteIpAddress));
try { try {
return httpClient.execute(httpGet, new HttpClientResponseHandler<String>() { return httpClient.execute(httpGet, new HttpClientResponseHandler<String>() {
@Override @Override
public String handleResponse(ClassicHttpResponse result) throws HttpException, IOException { public String handleResponse(ClassicHttpResponse result) throws HttpException, IOException {
String body = new String(result.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8); String body = new String(result.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8);
logger.info("[{}] httpClient.execute completed, response code: {}, body: {}", remoteIpAddress, logger.info("[{}] httpClient.execute completed, response code: {}, body: {}", remoteIpAddress,
result.getCode(), body); result.getCode(), body);
ipInfoMapping.put(remoteIpAddress, body); ipInfoMapping.put(remoteIpAddress, body);
int inserted = jdbcService.insertRemoteIpInfo(remoteIpAddress, body); int inserted = jdbcService.insertRemoteIpInfo(remoteIpAddress, body);
ipInfoLogger.info("[{}] {}, inserted = {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress), ipInfoLogger.info("[{}] {}, inserted = {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress),
inserted); inserted);
return body; return body;
}
});
} catch (IOException e) {
logger.error("[getIpLocationInfo] IO Exception has occurred!", e);
return null;
} }
}
}); public void asyncUpdateIpLocationInfo(String remoteIpAddress) {
} catch (IOException e) { asyncClient.execute(SimpleHttpRequest.create(ipInfoApiMethod, String.format(ipInfoApiUrl, remoteIpAddress)),
logger.error("[getIpLocationInfo] IO Exception has occurred!", e); new FutureCallback<SimpleHttpResponse>() {
return null;
@Override
public void completed(SimpleHttpResponse result) {
logger.info("[{}] asyncClient.execute completed, result: {}, content-type: {}, body: {}",
remoteIpAddress, result, result.getContentType(), result.getBodyText());
ipInfoMapping.put(remoteIpAddress, result.getBodyText());
int inserted = jdbcService.insertRemoteIpInfo(remoteIpAddress, result.getBodyText());
ipInfoLogger.info("[{}] {}, inserted = {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress),
inserted);
}
@Override
public void failed(Exception exception) {
logger.info("[{}] asyncClient.execute failed, exception: {}", remoteIpAddress, exception);
}
@Override
public void cancelled() {
logger.info("[{}] asyncClient.execute cancelled.", remoteIpAddress);
}
});
} }
}
public void asyncUpdateIpLocationInfo(String remoteIpAddress) {
asyncClient.execute(SimpleHttpRequest.create(ipInfoApiMethod, String.format(ipInfoApiUrl, remoteIpAddress)),
new FutureCallback<SimpleHttpResponse>() {
@Override
public void completed(SimpleHttpResponse result) {
logger.info("[{}] asyncClient.execute completed, result: {}, content-type: {}, body: {}",
remoteIpAddress, result, result.getContentType(), result.getBodyText());
ipInfoMapping.put(remoteIpAddress, result.getBodyText());
int inserted = jdbcService.insertRemoteIpInfo(remoteIpAddress, result.getBodyText());
ipInfoLogger.info("[{}] {}, inserted = {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress),
inserted);
}
@Override
public void failed(Exception exception) {
logger.info("[{}] asyncClient.execute failed, exception: {}", remoteIpAddress, exception);
}
@Override
public void cancelled() {
logger.info("[{}] asyncClient.execute cancelled.", remoteIpAddress);
}
});
}
} }

@ -16,59 +16,59 @@ import jakarta.annotation.PostConstruct;
@Service @Service
public class JdbcService { public class JdbcService {
private static final String createRemoteIpLookupTableSql = "CREATE TABLE IF NOT EXISTS public.remote_ip_lookup (id BIGINT not null, " private static final String createRemoteIpLookupTableSql = "CREATE TABLE IF NOT EXISTS public.remote_ip_lookup (id BIGINT not null, "
+ "remote_ip_address CHARACTER VARYING not null, remote_ip_info CHARACTER VARYING not null, PRIMARY KEY (id));"; + "remote_ip_address CHARACTER VARYING not null, remote_ip_info CHARACTER VARYING not null, PRIMARY KEY (id));";
private static final String createRemoteIpLookupIndexSql = "CREATE INDEX IF NOT EXISTS public.remote_ip_lookup_idx ON " private static final String createRemoteIpLookupIndexSql = "CREATE INDEX IF NOT EXISTS public.remote_ip_lookup_idx ON "
+ "public.remote_ip_lookup (remote_ip_address);"; + "public.remote_ip_lookup (remote_ip_address);";
@Autowired @Autowired
private JdbcTemplate jdbcTemplate; private JdbcTemplate jdbcTemplate;
@PostConstruct @PostConstruct
private void init() { private void init() {
jdbcTemplate.execute(createRemoteIpLookupTableSql); jdbcTemplate.execute(createRemoteIpLookupTableSql);
jdbcTemplate.execute(createRemoteIpLookupIndexSql); jdbcTemplate.execute(createRemoteIpLookupIndexSql);
} }
public String getRemoteIpInfo(String remoteIp) { public String getRemoteIpInfo(String remoteIp) {
var result = jdbcTemplate.query( var result = jdbcTemplate.query(
"SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup WHERE remote_ip_address = ? ", "SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup WHERE remote_ip_address = ? ",
new RowMapper<String>() { new RowMapper<String>() {
@Override @Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException { public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString(3); return rs.getString(3);
} }
}, remoteIp); }, remoteIp);
return result.isEmpty() ? null : result.get(0); return result.isEmpty() ? null : result.get(0);
} }
public List<Map<String, Object>> getAllRemoteIpInfo(String remoteIp) { public List<Map<String, Object>> getAllRemoteIpInfo(String remoteIp) {
return jdbcTemplate.query( return jdbcTemplate.query(
"SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup WHERE remote_ip_address = ? ", "SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup WHERE remote_ip_address = ? ",
new RowMapper<Map<String, Object>>() { new RowMapper<Map<String, Object>>() {
@Override @Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException { public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
return Map.of("insert_time", new Date(rs.getLong(1)), "remote_ip_address", rs.getString(2), return Map.of("insert_time", new Date(rs.getLong(1)), "remote_ip_address", rs.getString(2),
"remote_ip_info", rs.getString(3)); "remote_ip_info", rs.getString(3));
} }
}, remoteIp); }, remoteIp);
} }
public List<Map<String, Object>> getAllRemoteIpInfo() { public List<Map<String, Object>> getAllRemoteIpInfo() {
return jdbcTemplate.query( return jdbcTemplate.query(
"SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup order by id", "SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup order by id",
new RowMapper<Map<String, Object>>() { new RowMapper<Map<String, Object>>() {
@Override @Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException { public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
return Map.of("insert_time", new Date(rs.getLong(1)), "remote_ip_address", rs.getString(2), return Map.of("insert_time", new Date(rs.getLong(1)), "remote_ip_address", rs.getString(2),
"remote_ip_info", rs.getString(3)); "remote_ip_info", rs.getString(3));
} }
}); });
} }
public int insertRemoteIpInfo(String remoteIpAddress, String remoteIpInfo) { public int insertRemoteIpInfo(String remoteIpAddress, String remoteIpInfo) {
return jdbcTemplate.update( return jdbcTemplate.update(
"INSERT INTO public.remote_ip_lookup (id, remote_ip_address, remote_ip_info) VALUES (?, ?, ?)", "INSERT INTO public.remote_ip_lookup (id, remote_ip_address, remote_ip_info) VALUES (?, ?, ?)",
System.currentTimeMillis(), remoteIpAddress, remoteIpInfo); System.currentTimeMillis(), remoteIpAddress, remoteIpInfo);
} }
} }

@ -24,64 +24,64 @@ import org.springframework.stereotype.Service;
@Service @Service
public class JmxClientService { public class JmxClientService {
private static final Logger logger = LoggerFactory.getLogger(ReplyService.class); private static final Logger logger = LoggerFactory.getLogger(ReplyService.class);
public String process(String[] args) { public String process(String[] args) {
// Example // Example
// 1st parameter: service:jmx:rmi:///jndi/rmi://127.0.0.1:2020/jmxrmi // 1st parameter: service:jmx:rmi:///jndi/rmi://127.0.0.1:2020/jmxrmi
// 2nd parameter: java.lang:type=Memory // 2nd parameter: java.lang:type=Memory
StringBuilder output = new StringBuilder(); StringBuilder output = new StringBuilder();
try { try {
if (args.length > 2) { if (args.length > 2) {
Runtime.getRuntime().freeMemory(); Runtime.getRuntime().freeMemory();
JMXServiceURL url = new JMXServiceURL(args[1]); JMXServiceURL url = new JMXServiceURL(args[1]);
JMXConnector jmxc = JMXConnectorFactory.connect(url, null); JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
ObjectName mbeanName = new ObjectName(args[2]); ObjectName mbeanName = new ObjectName(args[2]);
MBeanInfo info = mbsc.getMBeanInfo(mbeanName); MBeanInfo info = mbsc.getMBeanInfo(mbeanName);
MBeanAttributeInfo[] attribute = info.getAttributes(); MBeanAttributeInfo[] attribute = info.getAttributes();
logger.info("[process] args.length: {}", args.length); logger.info("[process] args.length: {}", args.length);
if (args.length > 3) { if (args.length > 3) {
for (MBeanAttributeInfo attr : attribute) { for (MBeanAttributeInfo attr : attribute) {
List<Attribute> alist = mbsc.getAttributes(mbeanName, new String[] { attr.getName() }).asList(); List<Attribute> alist = mbsc.getAttributes(mbeanName, new String[] { attr.getName() }).asList();
if (args[3].equals(attr.getName())) { if (args[3].equals(attr.getName())) {
Optional<Map<String, Object>> opt = alist.stream().filter(a -> a.getName().equals(args[3])) Optional<Map<String, Object>> opt = alist.stream().filter(a -> a.getName().equals(args[3]))
.map(a -> toMap((CompositeData) a.getValue())).findFirst(); .map(a -> toMap((CompositeData) a.getValue())).findFirst();
if (opt.isPresent()) { if (opt.isPresent()) {
output.append(attr.getName() + ": " + opt.get() + "\r\n"); output.append(attr.getName() + ": " + opt.get() + "\r\n");
} }
}
}
} else {
for (MBeanAttributeInfo attr : attribute) {
List<Attribute> alist = mbsc.getAttributes(mbeanName, new String[] { attr.getName() }).asList();
output.append(attr.getName() + ": " + alist + "\r\n");
}
}
jmxc.close();
} else {
output.append(
"Example: jmx_client service:jmx:rmi:///jndi/rmi://127.0.0.1:2020/jmxrmi java.lang:type=Memory HeapMemoryUsage\r\n");
} }
} } catch (Exception e) {
} else { logger.error("process cmd failed: {}", Arrays.asList(args), e);
for (MBeanAttributeInfo attr : attribute) {
List<Attribute> alist = mbsc.getAttributes(mbeanName, new String[] { attr.getName() }).asList();
output.append(attr.getName() + ": " + alist + "\r\n");
}
} }
jmxc.close(); return output.toString();
} else {
output.append(
"Example: jmx_client service:jmx:rmi:///jndi/rmi://127.0.0.1:2020/jmxrmi java.lang:type=Memory HeapMemoryUsage\r\n");
}
} catch (Exception e) {
logger.error("process cmd failed: {}", Arrays.asList(args), e);
} }
return output.toString();
}
public static Map<String, Object> toMap(CompositeData cd) { public static Map<String, Object> toMap(CompositeData cd) {
if (cd == null) if (cd == null)
throw new IllegalArgumentException("composite data should not be null"); throw new IllegalArgumentException("composite data should not be null");
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
Set<String> itemNames = cd.getCompositeType().keySet(); Set<String> itemNames = cd.getCompositeType().keySet();
for (String itemName : itemNames) { for (String itemName : itemNames) {
Object item = cd.get(itemName); Object item = cd.get(itemName);
map.put(itemName, item); map.put(itemName, item);
}
return map;
} }
return map;
}
} }

@ -4,36 +4,36 @@ import org.springframework.beans.factory.annotation.Autowired;
public class MessageSender { public class MessageSender {
@Autowired @Autowired
EchoComponent echoComponent; EchoComponent echoComponent;
private String fromJID, toJID, message; private String fromJID, toJID, message;
public void sendMessage() { public void sendMessage() {
echoComponent.sendMessage(fromJID, toJID, message); echoComponent.sendMessage(fromJID, toJID, message);
} }
public String getFromJID() { public String getFromJID() {
return fromJID; return fromJID;
} }
public void setFromJID(String fromJID) { public void setFromJID(String fromJID) {
this.fromJID = fromJID; this.fromJID = fromJID;
} }
public String getToJID() { public String getToJID() {
return toJID; return toJID;
} }
public void setToJID(String toJID) { public void setToJID(String toJID) {
this.toJID = toJID; this.toJID = toJID;
} }
public String getMessage() { public String getMessage() {
return message; return message;
} }
public void setMessage(String message) { public void setMessage(String message) {
this.message = message; this.message = message;
} }
} }

@ -25,126 +25,126 @@ import org.springframework.stereotype.Service;
@Service @Service
public class ReplyService { public class ReplyService {
private static final Logger logger = LoggerFactory.getLogger(ReplyService.class); private static final Logger logger = LoggerFactory.getLogger(ReplyService.class);
private static final Logger notFoundLogger = LoggerFactory.getLogger("not_found"); private static final Logger notFoundLogger = LoggerFactory.getLogger("not_found");
@Autowired @Autowired
Properties hashReplies; Properties hashReplies;
@Autowired @Autowired
Properties regexMapping; Properties regexMapping;
@Autowired @Autowired
Map<String, String> ipInfoMapping; Map<String, String> ipInfoMapping;
@Autowired @Autowired
JdbcService jdbcService; JdbcService jdbcService;
@Autowired @Autowired
GeoIpLocator geoIpLocator; GeoIpLocator geoIpLocator;
@Autowired @Autowired
JmxClientService jmxClientService; JmxClientService jmxClientService;
public boolean replyToCommand(String command, OutputStream out, String prompt, ServerSession session) public boolean replyToCommand(String command, OutputStream out, String prompt, ServerSession session)
throws IOException { throws IOException {
String cmdHash = DigestUtils.md5Hex(command.trim()).toUpperCase(); String cmdHash = DigestUtils.md5Hex(command.trim()).toUpperCase();
if (StringUtils.equalsIgnoreCase(command.trim(), "my_geolocation")) { if (StringUtils.equalsIgnoreCase(command.trim(), "my_geolocation")) {
logger.info("[{}] my_geolocation command detected: {}", cmdHash, command.trim()); logger.info("[{}] my_geolocation command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", ipInfoMapping.get(Thread.currentThread().getName()), prompt) out.write(String.format("\r\n%s\r\n%s", ipInfoMapping.get(Thread.currentThread().getName()), prompt)
.getBytes()); .getBytes());
} else if (StringUtils.equalsIgnoreCase(command.trim(), "whoami")) { } else if (StringUtils.equalsIgnoreCase(command.trim(), "whoami")) {
logger.info("[{}] whoami command detected: {}", cmdHash, command.trim()); logger.info("[{}] whoami command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", session.getUsername(), prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", session.getUsername(), prompt).getBytes());
} else if (StringUtils.equalsIgnoreCase(command.trim(), "online_geolocations")) { } else if (StringUtils.equalsIgnoreCase(command.trim(), "online_geolocations")) {
logger.info("[{}] online_geolocations command detected: {}", cmdHash, command.trim()); logger.info("[{}] online_geolocations command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", ipInfoMapping.toString(), prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", ipInfoMapping.toString(), prompt).getBytes());
} else if (StringUtils.equalsIgnoreCase(StringUtils.split(command.trim(), " ")[0], "jmx_client")) { } else if (StringUtils.equalsIgnoreCase(StringUtils.split(command.trim(), " ")[0], "jmx_client")) {
String remoteJmxResponse = jmxClientService.process(StringUtils.split(command.trim(), " ")); String remoteJmxResponse = jmxClientService.process(StringUtils.split(command.trim(), " "));
logger.info("[{}] jmx_client command detected: {}", cmdHash, command.trim()); logger.info("[{}] jmx_client command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", remoteJmxResponse, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", remoteJmxResponse, prompt).getBytes());
} else if (StringUtils.split(command.trim(), " ").length == 2 } else if (StringUtils.split(command.trim(), " ").length == 2
&& StringUtils.equalsIgnoreCase(StringUtils.split(command.trim(), " ")[0], "get_geolocation")) { && StringUtils.equalsIgnoreCase(StringUtils.split(command.trim(), " ")[0], "get_geolocation")) {
String remoteIpInfo = StringUtils.getIfBlank( String remoteIpInfo = StringUtils.getIfBlank(
jdbcService.getRemoteIpInfo(StringUtils.split(command.trim(), " ")[1]), jdbcService.getRemoteIpInfo(StringUtils.split(command.trim(), " ")[1]),
() -> geoIpLocator.getIpLocationInfo(StringUtils.split(command.trim(), " ")[1])); () -> geoIpLocator.getIpLocationInfo(StringUtils.split(command.trim(), " ")[1]));
logger.info("[{}] get_geolocation command detected: {}", cmdHash, command.trim()); logger.info("[{}] get_geolocation command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", remoteIpInfo, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", remoteIpInfo, prompt).getBytes());
} else if (StringUtils.equalsIgnoreCase(command.trim(), "all_geolocations")) { } else if (StringUtils.equalsIgnoreCase(command.trim(), "all_geolocations")) {
logger.info("[{}] all_geolocations command detected: {}", cmdHash, command.trim()); logger.info("[{}] all_geolocations command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", jdbcService.getAllRemoteIpInfo(), prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", jdbcService.getAllRemoteIpInfo(), prompt).getBytes());
} else if (StringUtils.equalsIgnoreCase(command.trim(), "exit") } else if (StringUtils.equalsIgnoreCase(command.trim(), "exit")
|| StringUtils.equalsIgnoreCase(command.trim(), "quit")) { || StringUtils.equalsIgnoreCase(command.trim(), "quit")) {
logger.info("[{}] Exiting command detected: {}", cmdHash, command.trim()); logger.info("[{}] Exiting command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\nExiting...\r\n%s", prompt).getBytes()); out.write(String.format("\r\nExiting...\r\n%s", prompt).getBytes());
return true; return true;
} else if (hashReplies.containsKey(command.trim())) { } else if (hashReplies.containsKey(command.trim())) {
logger.info("[{}] Known command detected: {}", cmdHash, command.trim()); logger.info("[{}] Known command detected: {}", cmdHash, command.trim());
String reply = hashReplies.getProperty(command.trim()).replace("\\r", "\r").replace("\\n", "\n") String reply = hashReplies.getProperty(command.trim()).replace("\\r", "\r").replace("\\n", "\n")
.replace("\\t", "\t"); .replace("\\t", "\t");
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else if (hashReplies.containsKey(cmdHash)) { } else if (hashReplies.containsKey(cmdHash)) {
logger.info("[{}] Known command-hash detected: {}", cmdHash, command.trim()); logger.info("[{}] Known command-hash detected: {}", cmdHash, command.trim());
String reply = hashReplies.getProperty(cmdHash).replace("\\r", "\r").replace("\\n", "\n").replace("\\t", String reply = hashReplies.getProperty(cmdHash).replace("\\r", "\r").replace("\\n", "\n").replace("\\t",
"\t"); "\t");
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else if (hashReplies.containsKey(String.format("base64(%s)", cmdHash))) { } else if (hashReplies.containsKey(String.format("base64(%s)", cmdHash))) {
logger.info("[{}] Known base64-hash detected: {}", cmdHash, command.trim()); logger.info("[{}] Known base64-hash detected: {}", cmdHash, command.trim());
String reply = hashReplies.getProperty(String.format("base64(%s)", cmdHash)); String reply = hashReplies.getProperty(String.format("base64(%s)", cmdHash));
reply = new String(Base64.decodeBase64(reply)); reply = new String(Base64.decodeBase64(reply));
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else {
Optional<Pair<String, String>> o = regexMapping.entrySet().stream()
.filter(e -> command.trim().matches(((String) e.getKey())))
.map(e -> Pair.of((String) e.getKey(), (String) e.getValue())).findAny();
if (o.isPresent()) {
String reply = hashReplies.getProperty(o.get().getRight(), "").replace("\\r", "\r").replace("\\n", "\n")
.replace("\\t", "\t");
if (reply.isEmpty()) {
reply = executeShellCommand(command.trim());
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else { } else {
logger.info("[{}] Known pattern detected: {} ({})", cmdHash, command.trim(), o.get()); Optional<Pair<String, String>> o = regexMapping.entrySet().stream()
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes()); .filter(e -> command.trim().matches(((String) e.getKey())))
.map(e -> Pair.of((String) e.getKey(), (String) e.getValue())).findAny();
if (o.isPresent()) {
String reply = hashReplies.getProperty(o.get().getRight(), "").replace("\\r", "\r").replace("\\n", "\n")
.replace("\\t", "\t");
if (reply.isEmpty()) {
reply = executeShellCommand(command.trim());
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else {
logger.info("[{}] Known pattern detected: {} ({})", cmdHash, command.trim(), o.get());
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
}
} else {
logger.info("[{}] Command not found: {}", cmdHash, command.trim());
notFoundLogger.info("[{}] Command not found: {}", cmdHash, command.trim());
out.write(String.format("\r\nCommand '%s' not found. Try 'exit'.\r\n%s", command.trim(), prompt)
.getBytes());
}
} }
} else { return false;
logger.info("[{}] Command not found: {}", cmdHash, command.trim());
notFoundLogger.info("[{}] Command not found: {}", cmdHash, command.trim());
out.write(String.format("\r\nCommand '%s' not found. Try 'exit'.\r\n%s", command.trim(), prompt)
.getBytes());
}
} }
return false;
} public String executeShellCommand(String command) {
String cmdHash = DigestUtils.md5Hex(command.trim()).toUpperCase();
public String executeShellCommand(String command) { logger.info("[{}] Execute cmd for real: {}", cmdHash, command.trim());
String cmdHash = DigestUtils.md5Hex(command.trim()).toUpperCase(); ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
logger.info("[{}] Execute cmd for real: {}", cmdHash, command.trim()); try {
ByteArrayOutputStream tempOut = new ByteArrayOutputStream(); CommandLine cmdLine = CommandLine.parse(command.trim());
try { DefaultExecutor executor = DefaultExecutor.builder().get();
CommandLine cmdLine = CommandLine.parse(command.trim()); PumpStreamHandler streamHandler = new PumpStreamHandler(tempOut);
DefaultExecutor executor = DefaultExecutor.builder().get(); executor.setStreamHandler(streamHandler);
PumpStreamHandler streamHandler = new PumpStreamHandler(tempOut); int exitValue = executor.execute(cmdLine);
executor.setStreamHandler(streamHandler); logger.info("[{}] Result: {} ({})", cmdHash, command.trim(), exitValue);
int exitValue = executor.execute(cmdLine); return new String(tempOut.toByteArray()).replace("\n", "\r\n");
logger.info("[{}] Result: {} ({})", cmdHash, command.trim(), exitValue); } catch (ExecuteException e) {
return new String(tempOut.toByteArray()).replace("\n", "\r\n"); logger.info("[{}] Execute cmd failed: {}", cmdHash, command.trim(), e);
} catch (ExecuteException e) { } catch (IOException e) {
logger.info("[{}] Execute cmd failed: {}", cmdHash, command.trim(), e); logger.info("[{}] Execute cmd failed: {}", cmdHash, command.trim(), e);
} catch (IOException e) { }
logger.info("[{}] Execute cmd failed: {}", cmdHash, command.trim(), e); return null;
} }
return null;
}
} }

Loading…
Cancel
Save