latest version

This commit is contained in:
Peter Hormanns 2011-05-16 13:46:34 +00:00
parent b7df964612
commit 2efa12790b

View File

@ -19,50 +19,51 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
/// command line client for hsadmin /**
public class HSadmin * command line client for hsadmin.
{ */
static String version = "1.0.8 (2009/June/05 17:25 MEST)"; public class HSadmin {
static String loginURL = "https://agnes.ostwall195.de:8443/cas/v1/tickets"; private static String version = "CLI Client 2.0.0 (2011/May/21 09:00 MEST)";
static String servletURL = "https://agnes.ostwall195.de:8443/hsar/hsadmin/cli-interface/";
static String backendURL = "https://agnes.ostwall195.de:8443/hsar/backend";
// static String loginURL = "https://login.hostsharing.net:443/cas/v1/tickets"; private static String loginURL = "https://login.hostsharing.net/cas/v1/tickets";
// static String servletURL = "https://hsh93-test.hostsharing.net:443/hsar/hsadmin/cli-interface/"; private static String servletURL = "https://admin.hostsharing.net/hsar/hsadmin/cli-interface/";
// static String backendURL = "https://hsh93-test.hostsharing.net:443/hsar/backend"; private static String backendURL = "https://admin.hostsharing.net:443/hsar/backend";
static Properties config; private static Properties config;
static String userName; private static String authenticatedUserName;
static String passWord; private static String passWord;
static int verbosity = 0; private static String runAsUserName;
private static int verbosity = 0;
private static class PasswordMaskingThread extends Thread private static class PasswordMaskingThread extends Thread {
{
private boolean stop = false;
public void interrupt() private boolean stop = false;
{
stop = true;
super.interrupt();
}
public void run() { public void interrupt() {
while(!stop) { stop = true;
try { super.interrupt();
Thread.sleep(50); // rate at which attempts to mask }
} catch (InterruptedException ie) {}
// in case I was sleeping while stop was changed, don't print public void run() {
// I might be on the next line because of enter key being while (!stop) {
// pressed try {
if (!stop) System.out.print("\rPassword: " + "\rPassword: " ); Thread.sleep(50); // rate at which attempts to mask
System.out.flush(); } catch (InterruptedException ie) {
} }
} // in case I was sleeping while stop was changed, don't print
// I might be on the next line because of enter key being
// pressed
if (!stop) {
System.out.print("\rPassword: "
+ "\rPassword: ");
}
System.out.flush();
}
}
} }
static class HttpRequest private static class HttpRequest {
{
private URL url; private URL url;
private Map<String, List<String>> responseHeaders; private Map<String, List<String>> responseHeaders;
private StringBuilder requestData; private StringBuilder requestData;
@ -71,397 +72,385 @@ public class HSadmin
private String username; private String username;
private String responseMessage; private String responseMessage;
public HttpRequest(String url) public HttpRequest(String url) throws MalformedURLException {
throws MalformedURLException this.url = new URL(url);
{
this.url = new URL( url );
} }
public int post() throws IOException public int post() throws IOException {
{
return doRequest("POST"); return doRequest("POST");
} }
public int put() throws IOException public int put() throws IOException {
{
return doRequest("PUT"); return doRequest("PUT");
} }
public int doRequest(String method) throws IOException public int doRequest(String method) throws IOException {
{ echoVerbose(method + ": " + url.toString());
echoVerbose(method + ": " + url.toString() ); HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-type",
"application/x-www-form-urlencoded; charset=" + "UTF-8");
if (username != null)
conn.setRequestProperty("Authorization",
createAuthorizationHeader(username, password));
conn.setRequestMethod(method);
OutputStreamWriter wr = new OutputStreamWriter(conn
.getOutputStream(), "UTF-8");
if (requestData == null) {
if (username != null)
addParam("username", username);
if (password != null)
addParam("password", password);
}
if (requestData != null)
wr.write(requestData.toString());
wr.flush();
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); responseHeaders = conn.getHeaderFields();
conn.setDoOutput(true); if (verbosity > 1)
conn.setDoInput(true); echoResponseHeaders(conn);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=" + "UTF-8");
if ( username != null )
conn.setRequestProperty("Authorization", createAuthorizationHeader(username, password) );
conn.setRequestMethod(method);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
if ( requestData == null )
{
if ( username != null )
addParam("username", username);
if ( password != null )
addParam("password", password);
}
if ( requestData != null )
wr.write(requestData.toString());
wr.flush();
responseHeaders = conn.getHeaderFields(); responseData = new StringBuilder();
if (verbosity > 1) try {
echoResponseHeaders(conn); BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "ISO-8859-1"));
responseData = new StringBuilder(); String line;
try while ((line = rd.readLine()) != null) {
{ responseData.append(line + "\n");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-1")); }
String line; rd.close();
while ((line = rd.readLine()) != null) { } catch (IOException exc) {
responseData.append(line + "\n"); }
} wr.close();
rd.close(); responseMessage = conn.getResponseMessage();
} return conn.getResponseCode();
catch ( IOException exc )
{
}
wr.close();
responseMessage = conn.getResponseMessage();
return conn.getResponseCode();
} }
private String createAuthorizationHeader(String username, String password) throws IOException private String createAuthorizationHeader(String username,
{ String password) throws IOException {
if ( password == null ) if (password == null)
password = getPassWord(); password = getPassWord();
String authValue = username + ":" + password; String authValue = username + ":" + password;
String encodedAuth = Base64.byteArrayToBase64(authValue.getBytes()); String encodedAuth = Base64.byteArrayToBase64(authValue.getBytes());
return "Basic " + encodedAuth; return "Basic " + encodedAuth;
} }
/// printing the response header (TODO: just for debugging - remove) /**
private void echoResponseHeaders(HttpURLConnection conn) throws IOException * printing the response header.
{ */
System.out.println("ResponseCode: " + conn.getResponseCode()); private void echoResponseHeaders(HttpURLConnection conn)
System.out.println("ResponseMessage: " + conn.getResponseMessage()); throws IOException {
for ( String key: responseHeaders.keySet() ) // TODO: just for debugging - remove
{ System.out.println("ResponseCode: " + conn.getResponseCode());
System.out.println( key + ": " + responseHeaders.get(key) ); System.out.println("ResponseMessage: " + conn.getResponseMessage());
} for (String key : responseHeaders.keySet()) {
System.out.println(key + ": " + responseHeaders.get(key));
}
} }
public void addParam(String name, String value) throws UnsupportedEncodingException public void addParam(String name, String value)
{ throws UnsupportedEncodingException {
if ( requestData == null ) if (requestData == null) {
requestData = new StringBuilder(); requestData = new StringBuilder();
else } else {
requestData.append("&"); requestData.append("&");
requestData.append( }
URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8") ); requestData.append(URLEncoder.encode(name, "UTF-8") + "="
+ URLEncoder.encode(value, "UTF-8"));
} }
public String getResponseData() public String getResponseData() {
{ return responseData.toString();
return responseData.toString();
} }
public void setUsername(String username) public void setUsername(String username) {
{
this.username = username; this.username = username;
} }
public void setPassword(String password) public void setPassword(String password) {
{
this.password = password; this.password = password;
} }
public List<String> getResponseHeader(String key) public List<String> getResponseHeader(String key) {
{
return responseHeaders.get(key); return responseHeaders.get(key);
} }
public void setRequestData(String data) public void setRequestData(String data) {
{
requestData = new StringBuilder(data); requestData = new StringBuilder(data);
} }
public String getResponseMessage() public String getResponseMessage() {
{
return responseMessage; return responseMessage;
} }
} }
/// returns the TGT, either from a special user config file or from stdin /**
private static String getTGT() throws IOException * returns the TGT, either from a special user config file or from stdin
{ */
HttpRequest postReq = new HttpRequest( loginURL ); private static String getTGT() throws IOException {
echoVerbose("using userName=" + userName + " for login"); HttpRequest postReq = new HttpRequest(loginURL);
echoVerbose("using userName=" + authenticatedUserName + " for login");
postReq.setUsername(userName); postReq.setUsername(authenticatedUserName);
String pw = getPassWord(); String pw = getPassWord();
postReq.setPassword(pw); postReq.setPassword(pw);
if ( 201 == postReq.post() ) if (201 == postReq.post()) {
{ String tgt = postReq.getResponseHeader("Location").get(0);
String tgt = postReq.getResponseHeader("Location").get(0); echoVerbose("TGT: " + tgt);
echoVerbose("TGT: " + tgt); return tgt;
return tgt; } else {
} return null;
else
return null;
}
/// retrieves a new session ticket using the given ticket granting ticket
private static String getST(String tgt)
{
String st = null;
try
{
HttpRequest httpReq = new HttpRequest( tgt );
httpReq.setRequestData( "service=" + backendURL );
if ( 200 == httpReq.post() )
st = httpReq.getResponseData();
} }
catch ( Exception exc )
{ /* ignore */ }
echoVerbose("ST: " + st);
return st;
} }
/// returns the password, either from parameter, user config file or from stdin /**
private static String getPassWord() throws IOException * retrieves a new session ticket using the given ticket granting ticket
{ */
if ( passWord == null ) private static String getST(String tgt) {
passWord = config.getProperty( "passWord." + userName, config.getProperty("passWord") ); String st = null;
try {
if ( passWord == null ) HttpRequest httpReq = new HttpRequest(tgt);
{ httpReq.setRequestData("service=" + backendURL);
Console console = System.console(); if (200 == httpReq.post()) {
if ( console != null ) st = httpReq.getResponseData();
{
char [] input = console.readPassword("Password: ");
passWord = new String(input);
} }
else } catch (Exception exc) { /* ignore */
{ }
echoVerbose("ST: " + st);
return st;
}
/**
* returns the password, either from parameter, user config file or from
* stdin.
*/
private static String getPassWord() throws IOException {
if (passWord == null)
passWord = config.getProperty("passWord." + authenticatedUserName,
config.getProperty("passWord"));
if (passWord == null) {
Console console = System.console();
if (console != null) {
char[] input = console.readPassword("Password: ");
passWord = new String(input);
} else {
System.out.print("Password: "); System.out.print("Password: ");
System.out.flush(); System.out.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
PasswordMaskingThread thread = new PasswordMaskingThread(); PasswordMaskingThread thread = new PasswordMaskingThread();
thread.start(); thread.start();
passWord = reader.readLine(); passWord = reader.readLine();
thread.interrupt(); thread.interrupt();
} }
} }
return passWord; return passWord;
} }
/// calls the remote service using the given service ticket 'st' /**
private static String exec(String st, String[] args) throws IOException * calls the remote service using the given service ticket 'st'.
{ */
HttpRequest httpReq = new HttpRequest( servletURL ); private static String exec(String st, String[] args) throws IOException {
echoVerbose("using userName=" + userName + " for exec"); HttpRequest httpReq = new HttpRequest(servletURL);
httpReq.setUsername(userName); if (runAsUserName == null) {
httpReq.setPassword(st); runAsUserName = authenticatedUserName;
StringBuilder argsAsString = new StringBuilder(); }
for ( String arg: args ) echoVerbose("using userName=" + runAsUserName + " for exec");
argsAsString.append(arg + "\n"); httpReq.setUsername(runAsUserName);
echoVerbose("--- remote args: ---\n" + argsAsString.toString() + "\n--- end of args. ---"); httpReq.setPassword(st);
httpReq.setRequestData(argsAsString.toString()); StringBuilder argsAsString = new StringBuilder();
for (String arg : args) {
int code = httpReq.put(); argsAsString.append(arg + "\n");
List<String> hsadminErrors = httpReq.getResponseHeader("X-hsadmin-error"); }
if ( hsadminErrors != null && hsadminErrors.size() > 0 && hsadminErrors.get(0) != null ) echoVerbose("--- remote args: ---\n" + argsAsString.toString()
throw new RuntimeException( hsadminErrors.get(0) ); + "\n--- end of args. ---");
else if ( 200 == code ) httpReq.setRequestData(argsAsString.toString());
return httpReq.getResponseData(); int code = httpReq.put();
throw new RuntimeException( "HTTP error #" + code + ": " + httpReq.getResponseMessage() ); List<String> hsadminErrors = httpReq
.getResponseHeader("X-hsadmin-error");
if (hsadminErrors != null && hsadminErrors.size() > 0
&& hsadminErrors.get(0) != null) {
throw new RuntimeException(hsadminErrors.get(0));
}
else {
if (200 == code) return httpReq.getResponseData();
}
throw new RuntimeException("HTTP error #" + code + ": "
+ httpReq.getResponseMessage());
} }
/// reads session information (in users home dir) /**
private static String loadTGT(String user, String fileName) throws IOException * reads session information (in users home dir).
{ */
private static String loadTGT(String user, String fileName)
throws IOException {
Properties properties = new Properties(); Properties properties = new Properties();
try try {
{ properties.load(new FileInputStream(new File(System
properties.load( new FileInputStream( new File( System.getProperty("user.home"), fileName)) ); .getProperty("user.home"), fileName)));
return properties.getProperty(user); return properties.getProperty(user);
} } catch (FileNotFoundException exc) {
catch ( FileNotFoundException exc )
{
return null; return null;
} }
} }
/// stores session information (in users home dir) /**
private static void storeTGT(String fileName, String user, String tgt) throws IOException * stores session information (in users home dir).
{ */
private static void storeTGT(String fileName, String user, String tgt)
throws IOException {
Properties properties = new Properties(); Properties properties = new Properties();
try try {
{ properties.load(new FileInputStream(new File(System
properties.load( new FileInputStream( new File( System.getProperty("user.home"), fileName)) ); .getProperty("user.home"), fileName)));
} catch (Exception exc) { /* ignore */
} }
catch ( Exception exc )
{ /* ignore */ }
properties.setProperty(user, tgt); properties.setProperty(user, tgt);
properties.store( new FileOutputStream( new File( System.getProperty("user.home"), fileName)), "" ); properties.store(new FileOutputStream(new File(System
.getProperty("user.home"), fileName)), "");
} }
/// reads the settings from the given config file (looked up in users home dir) /**
private static void readUserConfig(String string) throws IOException * reads the settings from the given config file (looked up in users home
{ * dir).
*/
private static void readUserConfig(String string) throws IOException {
// Read properties file. // Read properties file.
config = new Properties(); config = new Properties();
try { try {
config.load(new FileInputStream( new File(System.getProperty("user.home"), ".hsadmin.conf"))); config.load(
} catch (FileNotFoundException e) { new FileInputStream(
} new File(System.getProperty("user.home"), ".hsadmin.conf")));
} catch (FileNotFoundException e) {
userName = config.getProperty("userName", System.getenv("USER")); }
authenticatedUserName = config.getProperty("userName", System.getenv("USER"));
loginURL = config.getProperty("loginURL", loginURL); loginURL = config.getProperty("loginURL", loginURL);
servletURL = config.getProperty("servletURL", servletURL); servletURL = config.getProperty("servletURL", servletURL);
backendURL = config.getProperty("backendURL", backendURL); backendURL = config.getProperty("backendURL", backendURL);
verbosity = Integer.parseInt( config.getProperty("verbosity", "0") ); verbosity = Integer.parseInt(config.getProperty("verbosity", "0"));
} }
/// echoes the string to stdout depending on verbosity level /**
private static void echoVerbose(String string) * echoes the string to stdout depending on verbosity level.
{ */
if (verbosity > 0) private static void echoVerbose(String string) {
if (verbosity > 0) {
System.out.println("]" + string); System.out.println("]" + string);
}
} }
private static void printHelp() private static void printHelp() {
{ System.out.println("syntax: hsadmin [-h|--help] [-V (0|1|2)|--verbosity=(0|1|2)] [-v|--version]\n"
System.out.println("syntax: hsadmin [-h|--help] [-V (0|1|2)|--verbosity=(0|1|2)] [-v|--version]\n" + + " [-u USER|--user=USER] [-|REMOTE-ARGUMENTS]");
" [-u USER|--user=USER] [-|REMOTE-ARGUMENTS]");
System.out.println("sample: hsadmin -V 0 -u xyz00 -c user.search"); System.out.println("sample: hsadmin -V 0 -u xyz00 -c user.search");
System.out.println("version: " + version); System.out.println("version: " + version);
System.out.println(""); System.out.println("");
System.out.println("REMOTE-ARGUMENTS ('-' on command line => read from stdin):"); System.out.println("REMOTE-ARGUMENTS ('-' on command line => read from stdin):");
} }
/// reads remote arguments from stdin into 'remoteArgs' /**
private static void readArgsFromStdIn(ArrayList<String> remoteArgs) throws IOException * reads remote arguments from stdin into 'remoteArgs'.
{ */
private static void readArgsFromStdIn(ArrayList<String> remoteArgs)
throws IOException {
echoVerbose("READING ARGS FROM STDIN"); echoVerbose("READING ARGS FROM STDIN");
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
String line; String line;
while ((line = rd.readLine()) != null) { while ((line = rd.readLine()) != null) {
echoVerbose("ADDING REMOTE ARG:" + line); echoVerbose("ADDING REMOTE ARG:" + line);
remoteArgs.add(line); remoteArgs.add(line);
} }
rd.close(); rd.close();
} }
private static String createSessionTicket() throws IOException private static String createSessionTicket() throws IOException {
{ String tgt = loadTGT(authenticatedUserName, ".hsadmin.tgt");
String tgt = loadTGT(userName, ".hsadmin.tgt"); String st = getST(tgt);
String st = getST(tgt); if (st == null) {
if ( st == null) tgt = getTGT();
{ if (tgt == null) {
tgt = getTGT(); System.err
if ( tgt == null ) .println("ERROR: login failure - cannot get ticket granting ticket");
{ System.exit(1);
System.err.println("ERROR: login failure - cannot get ticket granting ticket"); }
System.exit(1); storeTGT(".hsadmin.tgt", authenticatedUserName, tgt);
} st = getST(tgt);
storeTGT(".hsadmin.tgt", userName, tgt ); }
st = getST(tgt);
}
return st; return st;
} }
private static ArrayList<String> createRemoteArgs(String[] args) throws IOException private static ArrayList<String> createRemoteArgs(String[] args)
{ throws IOException {
ArrayList<String> remoteArgs = new ArrayList<String>(); ArrayList<String> remoteArgs = new ArrayList<String>();
for ( int n = 0; n < args.length; ++n ) for (int n = 0; n < args.length; ++n) {
{
String arg = args[n]; String arg = args[n];
if ( arg.equals("-u") ) if (arg.equals("-u")) {
{
// TODO: out of bounds error // TODO: out of bounds error
userName = args[++n]; authenticatedUserName = args[++n];
} } else if (arg.startsWith("--user=") || arg.startsWith("--user:")) {
else if ( arg.startsWith("--user=") || arg.startsWith("--user:") ) authenticatedUserName = args[n].substring(7);
{ } else if (arg.equals("-r")) {
userName = args[n].substring(7); // TODO: out of bounds error
} runAsUserName = args[++n];
else if ( arg.equals("-V") ) } else if (arg.toLowerCase().startsWith("--runas=") || arg.toLowerCase().startsWith("--runas:")) {
{ runAsUserName = args[n].substring(8);
} else if (arg.equals("-V")) {
// TODO: out of bounds error // TODO: out of bounds error
verbosity = Integer.parseInt(args[++n]); verbosity = Integer.parseInt(args[++n]);
} } else if (arg.startsWith("--verbosity:")
else if ( arg.startsWith("--verbosity:") || arg.startsWith("--verbosity=") ) || arg.startsWith("--verbosity=")) {
{
verbosity = Integer.parseInt(args[n].substring(12)); verbosity = Integer.parseInt(args[n].substring(12));
} } else if (arg.equals("-v")) {
else if ( arg.equals("-v") )
{
System.out.println(version); System.out.println(version);
remoteArgs = new ArrayList<String>(); remoteArgs = new ArrayList<String>();
break; break;
} } else if (arg.startsWith("--version")) {
else if ( arg.startsWith("--version") )
{
System.out.println(version); System.out.println(version);
remoteArgs = new ArrayList<String>(); remoteArgs = new ArrayList<String>();
break; break;
} } else if (arg.equals("-h")) {
else if ( arg.equals("-h") )
{
// TODO: out of bounds error // TODO: out of bounds error
printHelp(); printHelp();
remoteArgs = new ArrayList<String>(); remoteArgs = new ArrayList<String>();
remoteArgs.add("-h"); remoteArgs.add("-h");
break; break;
} } else if (arg.startsWith("--help")) {
else if ( arg.startsWith("--help") )
{
printHelp(); printHelp();
remoteArgs = new ArrayList<String>(); remoteArgs = new ArrayList<String>();
remoteArgs.add("-h"); remoteArgs.add("-h");
break; break;
} } else if (arg.equals("-"))
else if ( arg.equals("-") )
readArgsFromStdIn(remoteArgs); readArgsFromStdIn(remoteArgs);
else else {
{
echoVerbose("ADDING REMOTE ARG:" + args[n]); echoVerbose("ADDING REMOTE ARG:" + args[n]);
remoteArgs.add(args[n]); remoteArgs.add(args[n]);
} }
} }
return remoteArgs; return remoteArgs;
} }
/// main program /**
public static void main(String[] args) throws IOException * main program.
{ */
public static void main(String[] args) throws IOException {
readUserConfig(".hsadmin.conf"); readUserConfig(".hsadmin.conf");
ArrayList<String> remoteArgs = createRemoteArgs(args); ArrayList<String> remoteArgs = createRemoteArgs(args);
if (remoteArgs.size() > 0) {
try {
String st = createSessionTicket();
if ( remoteArgs.size() > 0 ) String response = exec(st, remoteArgs
{ .toArray(new String[remoteArgs.size()]));
try { if (response != null)
String st = createSessionTicket(); System.out.print(response);
} catch (Exception exc) {
String response = exec(st, remoteArgs.toArray(new String[remoteArgs.size()])); System.err.println(exc.getMessage());
if ( response != null ) System.exit(1); // TODO: be more specific,
System.out.print(response); // like: 1=unknown, 2=remoting, 3=functional
} }
catch ( Exception exc )
{
System.err.println(exc.getMessage());
System.exit(1); // TODO: be more specific, like: 1=unknown, 2=remoting, 3=functional
}
} }
} }