From dfc4ece4083bbbb98f55291d05e7d2b1513464b7 Mon Sep 17 00:00:00 2001
From: Thomas Pummer <dev@nullpointer.at>
Date: Fri, 22 Feb 2013 11:10:11 -0500
Subject: [PATCH] the display-name in web.xml now shows the actual version of Gitblit

---
 src/com/gitblit/authority/GitblitAuthority.java |  542 +++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 458 insertions(+), 84 deletions(-)

diff --git a/src/com/gitblit/authority/GitblitAuthority.java b/src/com/gitblit/authority/GitblitAuthority.java
index 8416200..c3d8184 100644
--- a/src/com/gitblit/authority/GitblitAuthority.java
+++ b/src/com/gitblit/authority/GitblitAuthority.java
@@ -17,9 +17,11 @@
 
 import java.awt.BorderLayout;
 import java.awt.Container;
+import java.awt.Desktop;
 import java.awt.Dimension;
 import java.awt.EventQueue;
 import java.awt.FlowLayout;
+import java.awt.GridLayout;
 import java.awt.Insets;
 import java.awt.Point;
 import java.awt.event.ActionEvent;
@@ -29,10 +31,14 @@
 import java.awt.event.WindowAdapter;
 import java.awt.event.WindowEvent;
 import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.FileWriter;
 import java.io.FilenameFilter;
 import java.io.IOException;
+import java.net.URI;
+import java.security.PrivateKey;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.text.MessageFormat;
@@ -51,15 +57,22 @@
 import javax.mail.internet.MimeBodyPart;
 import javax.mail.internet.MimeMultipart;
 import javax.swing.ImageIcon;
+import javax.swing.InputVerifier;
+import javax.swing.JButton;
+import javax.swing.JComponent;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JOptionPane;
 import javax.swing.JPanel;
+import javax.swing.JPasswordField;
 import javax.swing.JScrollPane;
 import javax.swing.JSplitPane;
 import javax.swing.JTable;
+import javax.swing.JTextArea;
 import javax.swing.JTextField;
+import javax.swing.JToolBar;
 import javax.swing.RowFilter;
+import javax.swing.SwingConstants;
 import javax.swing.UIManager;
 import javax.swing.event.ListSelectionEvent;
 import javax.swing.event.ListSelectionListener;
@@ -69,6 +82,7 @@
 import org.eclipse.jgit.lib.StoredConfig;
 import org.eclipse.jgit.storage.file.FileBasedConfig;
 import org.eclipse.jgit.util.FS;
+import org.slf4j.LoggerFactory;
 
 import com.gitblit.ConfigUserService;
 import com.gitblit.Constants;
@@ -80,9 +94,13 @@
 import com.gitblit.client.HeaderPanel;
 import com.gitblit.client.Translation;
 import com.gitblit.models.UserModel;
+import com.gitblit.utils.ArrayUtils;
+import com.gitblit.utils.FileUtils;
 import com.gitblit.utils.StringUtils;
+import com.gitblit.utils.TimeUtils;
 import com.gitblit.utils.X509Utils;
 import com.gitblit.utils.X509Utils.RevocationReason;
+import com.gitblit.utils.X509Utils.X509Log;
 import com.gitblit.utils.X509Utils.X509Metadata;
 
 /**
@@ -91,7 +109,7 @@
  * @author James Moger
  *
  */
-public class GitblitAuthority extends JFrame {
+public class GitblitAuthority extends JFrame implements X509Log {
 
 	private static final long serialVersionUID = 1L;
 	
@@ -105,15 +123,36 @@
 	
 	private IUserService userService;
 	
-	private String caKeystorePassword = null;
+	private String caKeystorePassword;
 
 	private JTable table;
 	
 	private int defaultDuration;
 	
 	private TableRowSorter<UserCertificateTableModel> defaultSorter;
+	
+	private MailExecutor mail;
+
+	private JButton certificateDefaultsButton;
+
+	private JButton newSSLCertificate;
 
 	public static void main(String... args) {
+		// filter out the baseFolder parameter
+		String folder = "data";
+		for (int i = 0; i< args.length; i++) {
+			String arg = args[i];
+			if (arg.equals("--baseFolder")) {
+				if (i + 1 == args.length) {
+					System.out.println("Invalid --baseFolder parameter!");
+					System.exit(-1);
+				} else if (args[i + 1] != ".") {
+					folder = args[i+1];
+				}
+				break;
+			}
+		}
+		final String baseFolder = folder;
 		EventQueue.invokeLater(new Runnable() {
 			public void run() {
 				try {
@@ -121,7 +160,7 @@
 				} catch (Exception e) {
 				}
 				GitblitAuthority authority = new GitblitAuthority();
-				authority.initialize();
+				authority.initialize(baseFolder);
 				authority.setLocationRelativeTo(null);
 				authority.setVisible(true);
 			}
@@ -134,7 +173,7 @@
 		defaultSorter = new TableRowSorter<UserCertificateTableModel>(tableModel);
 	}
 	
-	public void initialize() {
+	public void initialize(String baseFolder) {
 		setIconImage(new ImageIcon(getClass().getResource("/gitblt-favicon.png")).getImage());
 		setTitle("Gitblit Certificate Authority v" + Constants.VERSION + " (" + Constants.VERSION_DATE + ")");
 		setContentPane(getUI());
@@ -150,10 +189,10 @@
 			}
 		});		
 
-		setSizeAndPosition();
-		
-		File folder = new File(System.getProperty("user.dir"));
+		File folder = new File(baseFolder).getAbsoluteFile();
 		load(folder);
+		
+		setSizeAndPosition();
 	}
 	
 	private void setSizeAndPosition() {
@@ -170,7 +209,7 @@
 
 		// try to restore saved window size
 		if (StringUtils.isEmpty(sz)) {
-			setSize(850, 500);
+			setSize(900, 600);
 		} else {
 			String[] chunks = sz.split("x");
 			int width = Integer.parseInt(chunks[0]);
@@ -206,7 +245,7 @@
 	}
 	
 	private StoredConfig getConfig() throws IOException, ConfigInvalidException {
-		File configFile  = new File(System.getProperty("user.dir"), X509Utils.CA_CONFIG);
+		File configFile  = new File(folder, X509Utils.CA_CONFIG);
 		FileBasedConfig config = new FileBasedConfig(configFile, FS.detect());
 		config.load();
 		return config;
@@ -218,32 +257,35 @@
 			return null;
 		}
 		gitblitSettings = new FileSettings(file.getAbsolutePath());
-		caKeystorePassword = gitblitSettings.getString(Keys.server.storePassword, null);
-		String us = gitblitSettings.getString(Keys.realm.userService, "users.conf");
+		mail = new MailExecutor(gitblitSettings);
+		String us = gitblitSettings.getString(Keys.realm.userService, "${baseFolder}/users.conf");
 		String ext = us.substring(us.lastIndexOf(".") + 1).toLowerCase();
 		IUserService service = null;
 		if (!ext.equals("conf") && !ext.equals("properties")) {
 			if (us.equals("com.gitblit.LdapUserService")) {
-				us = gitblitSettings.getString(Keys.realm.ldap.backingUserService, "users.conf");		
+				us = gitblitSettings.getString(Keys.realm.ldap.backingUserService, "${baseFolder}/users.conf");		
 			} else if (us.equals("com.gitblit.LdapUserService")) {
-				us = gitblitSettings.getString(Keys.realm.redmine.backingUserService, "users.conf");
+				us = gitblitSettings.getString(Keys.realm.redmine.backingUserService, "${baseFolder}/users.conf");
 			}
 		}
 
 		if (us.endsWith(".conf")) {
-			service = new ConfigUserService(new File(us));
+			service = new ConfigUserService(FileUtils.resolveParameter(Constants.baseFolder$, folder, us));
 		} else {
 			throw new RuntimeException("Unsupported user service: " + us);
 		}
 		
-		service = new ConfigUserService(new File(us));
+		service = new ConfigUserService(FileUtils.resolveParameter(Constants.baseFolder$, folder, us));
 		return service;
 	}
 	
 	private void load(File folder) {
 		this.folder = folder;
 		this.userService = loadUsers(folder);
-		if (userService != null) {
+		System.out.println(Constants.baseFolder$ + " set to " + folder);
+		if (userService == null) {
+			JOptionPane.showMessageDialog(this, MessageFormat.format("Sorry, {0} doesn't look like a Gitblit GO installation.", folder));
+		} else {
 			// build empty certificate model for all users
 			Map<String, UserCertificateModel> map = new HashMap<String, UserCertificateModel>();
 			for (String user : userService.getAllUsernames()) {
@@ -272,7 +314,58 @@
 			tableModel.list = new ArrayList<UserCertificateModel>(map.values());
 			Collections.sort(tableModel.list);
 			tableModel.fireTableDataChanged();
+			Utils.packColumns(table, Utils.MARGIN);
+			
+			File caKeystore = new File(folder, X509Utils.CA_KEY_STORE);
+			if (!caKeystore.exists()) {
+				
+				if (!X509Utils.unlimitedStrength) {
+					// prompt to confirm user understands JCE Standard Strength encryption
+					int res = JOptionPane.showConfirmDialog(GitblitAuthority.this, Translation.get("gb.jceWarning"),
+							Translation.get("gb.warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
+					if (res != JOptionPane.YES_OPTION) {
+						if (Desktop.isDesktopSupported()) {
+							if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
+								try {
+									Desktop.getDesktop().browse(URI.create("http://www.oracle.com/technetwork/java/javase/downloads/index.html"));
+								} catch (IOException e) {
+								}
+							}
+						}
+						System.exit(1);
+					}
+				}
+				
+				// show certificate defaults dialog 
+				certificateDefaultsButton.doClick();
+				
+				// create "localhost" ssl certificate
+				prepareX509Infrastructure();
+			}
 		}
+	}
+	
+	private boolean prepareX509Infrastructure() {
+		if (caKeystorePassword == null) {
+			JPasswordField pass = new JPasswordField(10);
+			pass.setText(caKeystorePassword);
+			pass.addAncestorListener(new RequestFocusListener());
+			JPanel panel = new JPanel(new BorderLayout());
+			panel.add(new JLabel(Translation.get("gb.enterKeystorePassword")), BorderLayout.NORTH);
+			panel.add(pass, BorderLayout.CENTER);
+			int result = JOptionPane.showConfirmDialog(GitblitAuthority.this, panel, Translation.get("gb.password"), JOptionPane.OK_CANCEL_OPTION);
+			if (result == JOptionPane.OK_OPTION) {
+				caKeystorePassword = new String(pass.getPassword());
+			} else {
+				return false;
+			}
+		}
+
+		X509Metadata metadata = new X509Metadata("localhost", caKeystorePassword);
+		setMetadataDefaults(metadata);
+		metadata.notAfter = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR);
+		X509Utils.prepareX509Infrastructure(metadata, folder, this);
+		return true;
 	}
 	
 	private List<X509Certificate> findCerts(File folder, String username) {
@@ -309,6 +402,11 @@
 			public Insets getInsets() {
 				return Utils.INSETS;
 			}
+			
+			@Override
+			public boolean isAllowEmail() {
+				return mail.isReady();
+			}
 
 			@Override
 			public Date getDefaultExpiration() {
@@ -322,33 +420,22 @@
 			}
 			
 			@Override
-			public void saveUser(String username, UserCertificateModel ucm) {
-				userService.updateUserModel(username, ucm.user);
+			public boolean saveUser(String username, UserCertificateModel ucm) {
+				return userService.updateUserModel(username, ucm.user);
 			}
 			
 			@Override
-			public void newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
-				Date notAfter = metadata.notAfter;
-				metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, "localhost");
-				UserModel user = ucm.user;				
-				
-				// set default values from config file
-				File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
-				FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
-				if (certificatesConfigFile.exists()) {
-					try {
-						config.load();
-					} catch (Exception e) {
-						Utils.showException(GitblitAuthority.this, e);
-					}
-					NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
-					certificateConfig.update(metadata);
+			public boolean newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
+				if (!prepareX509Infrastructure()) {
+					return false;
 				}
-				
-				// restore expiration date
+
+				Date notAfter = metadata.notAfter;
+				setMetadataDefaults(metadata);
 				metadata.notAfter = notAfter;
 				
 				// set user's specified OID values
+				UserModel user = ucm.user;				
 				if (!StringUtils.isEmpty(user.organizationalUnit)) {
 					metadata.oids.put("OU", user.organizationalUnit);
 				}
@@ -366,18 +453,14 @@
 				}
 
 				File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
-				File zip = X509Utils.newClientBundle(metadata, caKeystoreFile, caKeystorePassword);
-				
+				File zip = X509Utils.newClientBundle(metadata, caKeystoreFile, caKeystorePassword, GitblitAuthority.this);
+
 				// save latest expiration date
-				if (ucm.expires == null || metadata.notAfter.after(ucm.expires)) {
+				if (ucm.expires == null || metadata.notAfter.before(ucm.expires)) {
 					ucm.expires = metadata.notAfter;
 				}
-				ucm.update(config);
-				try {
-					config.save();
-				} catch (Exception e) {
-					Utils.showException(GitblitAuthority.this, e);
-				}
+				
+				updateAuthorityConfig(ucm);
 				
 				// refresh user
 				ucm.certs = null;
@@ -386,47 +469,20 @@
 				table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
 				
 				if (sendEmail) {
-					// send email
-					try {
-						MailExecutor mail = new MailExecutor(gitblitSettings);
-						if (mail.isReady()) {
-							Message message = mail.createMessage(user.emailAddress);
-							message.setSubject("Your Gitblit client certificate for " + metadata.serverHostname);
-
-							// body of email
-							String body = X509Utils.processTemplate(new File(caKeystoreFile.getParentFile(), "mail.tmpl"), metadata);
-							if (StringUtils.isEmpty(body)) {
-								body = MessageFormat.format("Hi {0}\n\nHere is your client certificate bundle.\nInside the zip file are installation instructions.", user.getDisplayName());
-							}
-							Multipart mp = new MimeMultipart();
-							MimeBodyPart messagePart = new MimeBodyPart();
-							messagePart.setText(body);
-							mp.addBodyPart(messagePart);
-
-							// attach zip
-							MimeBodyPart filePart = new MimeBodyPart();
-							FileDataSource fds = new FileDataSource(zip);
-							filePart.setDataHandler(new DataHandler(fds));
-							filePart.setFileName(fds.getName());
-							mp.addBodyPart(filePart);
-
-							message.setContent(mp);
-
-							mail.sendNow(message);
-						} else {
-							JOptionPane.showMessageDialog(GitblitAuthority.this, "Sorry, the mail server settings are not configured properly.\nCan not send email.", Translation.get("gb.error"), JOptionPane.ERROR_MESSAGE);
-						}
-					} catch (Exception e) {
-						Utils.showException(GitblitAuthority.this, e);
-					}
+					sendEmail(user, metadata, zip);
 				}
+				return true;
 			}
 			
 			@Override
-			public void revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
+			public boolean revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
+				if (!prepareX509Infrastructure()) {
+					return false;
+				}
+
 				File caRevocationList = new File(folder, X509Utils.CA_REVOCATION_LIST);
 				File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
-				if (X509Utils.revoke(cert, reason, caRevocationList, caKeystoreFile, caKeystorePassword)) {
+				if (X509Utils.revoke(cert, reason, caRevocationList, caKeystoreFile, caKeystorePassword, GitblitAuthority.this)) {
 					File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
 					FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
 					if (certificatesConfigFile.exists()) {
@@ -450,7 +506,11 @@
 					int modelIndex = table.convertRowIndexToModel(table.getSelectedRow());
 					tableModel.fireTableDataChanged();
 					table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
+					
+					return true;
 				}
+				
+				return false;
 			}
 		};
 		
@@ -490,7 +550,206 @@
 		usersPanel.add(new JScrollPane(table), BorderLayout.CENTER);
 		usersPanel.setMinimumSize(new Dimension(400, 10));
 		
-		final JTextField filterTextfield = new JTextField(20);
+		certificateDefaultsButton = new JButton(new ImageIcon(getClass().getResource("/settings_16x16.png")));
+		certificateDefaultsButton.setFocusable(false);
+		certificateDefaultsButton.setToolTipText(Translation.get("gb.newCertificateDefaults"));		
+		certificateDefaultsButton.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				X509Metadata metadata = new X509Metadata("whocares", "whocares");
+				File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
+				FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
+				NewCertificateConfig certificateConfig = null;
+				if (certificatesConfigFile.exists()) {
+					try {
+						config.load();
+					} catch (Exception x) {
+						Utils.showException(GitblitAuthority.this, x);
+					}
+					certificateConfig = NewCertificateConfig.KEY.parse(config);
+					certificateConfig.update(metadata);
+				}
+				InputVerifier verifier = new InputVerifier() {
+					public boolean verify(JComponent comp) {
+						boolean returnValue;
+						JTextField textField = (JTextField) comp;
+						try {
+							Integer.parseInt(textField.getText());
+							returnValue = true;
+						} catch (NumberFormatException e) {
+							returnValue = false;
+						}
+						return returnValue;
+					}
+				};
+
+				JTextField siteNameTF = new JTextField(20);
+				siteNameTF.setText(gitblitSettings.getString(Keys.web.siteName, "Gitblit"));
+				JPanel siteNamePanel = Utils.newFieldPanel(Translation.get("gb.siteName"),
+						siteNameTF, Translation.get("gb.siteNameDescription"));
+
+				JTextField validityTF = new JTextField(4);
+				validityTF.setInputVerifier(verifier);
+				validityTF.setVerifyInputWhenFocusTarget(true);
+				validityTF.setText("" + certificateConfig.duration);
+				JPanel validityPanel = Utils.newFieldPanel(Translation.get("gb.validity"),
+						validityTF, Translation.get("gb.duration.days").replace("{0}",  "").trim());
+				
+				JPanel p1 = new JPanel(new GridLayout(0, 1, 5, 2));
+				p1.add(siteNamePanel);
+				p1.add(validityPanel);
+				
+				DefaultOidsPanel oids = new DefaultOidsPanel(metadata);
+
+				JPanel panel = new JPanel(new BorderLayout());
+				panel.add(p1, BorderLayout.NORTH);
+				panel.add(oids, BorderLayout.CENTER);
+
+				int result = JOptionPane.showConfirmDialog(GitblitAuthority.this, 
+						panel, Translation.get("gb.newCertificateDefaults"), JOptionPane.OK_CANCEL_OPTION,
+						JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/settings_32x32.png")));
+				if (result == JOptionPane.OK_OPTION) {
+					try {
+						oids.update(metadata);
+						certificateConfig.duration = Integer.parseInt(validityTF.getText());
+						certificateConfig.store(config, metadata);
+						config.save();
+						
+						Map<String, String> updates = new HashMap<String, String>();
+						updates.put(Keys.web.siteName, siteNameTF.getText());
+						gitblitSettings.saveSettings(updates);
+					} catch (Exception e1) {
+						Utils.showException(GitblitAuthority.this, e1);
+					}
+				}
+			}
+		});
+		
+		newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
+		newSSLCertificate.setFocusable(false);
+		newSSLCertificate.setToolTipText(Translation.get("gb.newSSLCertificate"));		
+		newSSLCertificate.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				Date defaultExpiration = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR);
+				NewSSLCertificateDialog dialog = new NewSSLCertificateDialog(GitblitAuthority.this, defaultExpiration);
+				dialog.setModal(true);
+				dialog.setVisible(true);
+				if (dialog.isCanceled()) {
+					return;
+				}
+				final Date expires = dialog.getExpiration();
+				final String hostname = dialog.getHostname();
+				final boolean serveCertificate = dialog.isServeCertificate();
+				
+				AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
+
+					@Override
+					protected Boolean doRequest() throws IOException {
+						if (!prepareX509Infrastructure()) {
+							return false;
+						}
+						
+						// read CA private key and certificate
+						File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
+						PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
+						X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
+						
+						// generate new SSL certificate
+						X509Metadata metadata = new X509Metadata(hostname, caKeystorePassword);
+						setMetadataDefaults(metadata);
+						metadata.notAfter = expires;
+						File serverKeystoreFile = new File(folder, X509Utils.SERVER_KEY_STORE);
+						X509Certificate cert = X509Utils.newSSLCertificate(metadata, caPrivateKey, caCert, serverKeystoreFile, GitblitAuthority.this);
+						boolean hasCert = cert != null;
+						if (hasCert && serveCertificate) {
+							// update Gitblit https connector alias
+							Map<String, String> updates = new HashMap<String, String>();
+							updates.put(Keys.server.certificateAlias, metadata.commonName);
+							gitblitSettings.saveSettings(updates);
+						}
+						return hasCert;
+					}
+
+					@Override
+					protected void onSuccess() {
+						if (serveCertificate) {
+							JOptionPane.showMessageDialog(GitblitAuthority.this, 
+									MessageFormat.format(Translation.get("gb.sslCertificateGeneratedRestart"), hostname),
+									Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
+						} else {
+							JOptionPane.showMessageDialog(GitblitAuthority.this, 
+								MessageFormat.format(Translation.get("gb.sslCertificateGenerated"), hostname),
+								Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
+						}
+					}
+				};
+				
+				worker.execute();
+			}
+		});
+		
+		JButton emailBundle = new JButton(new ImageIcon(getClass().getResource("/mail_16x16.png")));
+		emailBundle.setFocusable(false);
+		emailBundle.setToolTipText(Translation.get("gb.emailCertificateBundle"));		
+		emailBundle.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				int row = table.getSelectedRow();
+				if (row < 0) {
+					return;
+				}
+				int modelIndex = table.convertRowIndexToModel(row);
+				final UserCertificateModel ucm = tableModel.get(modelIndex);
+				if (ArrayUtils.isEmpty(ucm.certs)) {
+					JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.pleaseGenerateClientCertificate"), ucm.user.getDisplayName()));
+				}
+				final File zip = new File(folder, X509Utils.CERTS + File.separator + ucm.user.username + File.separator + ucm.user.username + ".zip");
+				if (!zip.exists()) {
+					return;
+				}
+				
+				AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
+					@Override
+					protected Boolean doRequest() throws IOException {
+						X509Metadata metadata = new X509Metadata(ucm.user.username, "whocares");
+						metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
+						if (StringUtils.isEmpty(metadata.serverHostname)) {
+							metadata.serverHostname = Constants.NAME;
+						}
+						metadata.userDisplayname = ucm.user.getDisplayName();
+						return sendEmail(ucm.user, metadata, zip);
+					}
+
+					@Override
+					protected void onSuccess() {
+						JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.clientCertificateBundleSent"),
+								ucm.user.getDisplayName()));
+					}
+					
+				};
+				worker.execute();				
+			}
+		});
+		
+		JButton logButton = new JButton(new ImageIcon(getClass().getResource("/script_16x16.png")));
+		logButton.setFocusable(false);
+		logButton.setToolTipText(Translation.get("gb.log"));		
+		logButton.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				File log = new File(folder, X509Utils.CERTS + File.separator + "log.txt");
+				if (log.exists()) {
+					String content = FileUtils.readContent(log,  "\n");
+					JTextArea textarea = new JTextArea(content);
+					JScrollPane scrollPane = new JScrollPane(textarea);
+					scrollPane.setPreferredSize(new Dimension(700, 400));
+					JOptionPane.showMessageDialog(GitblitAuthority.this, scrollPane, log.getAbsolutePath(), JOptionPane.INFORMATION_MESSAGE);
+				}
+			}
+		});
+		
+		final JTextField filterTextfield = new JTextField(15);
 		filterTextfield.addActionListener(new ActionListener() {
 			public void actionPerformed(ActionEvent e) {
 				filterUsers(filterTextfield.getText());
@@ -501,16 +760,35 @@
 				filterUsers(filterTextfield.getText());
 			}
 		});
+		
+		JToolBar buttonControls = new JToolBar(JToolBar.HORIZONTAL);
+		buttonControls.setFloatable(false);
+		buttonControls.add(certificateDefaultsButton);
+		buttonControls.add(newSSLCertificate);
+		buttonControls.add(emailBundle);
+		buttonControls.add(logButton);
 
-		JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
+		JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, Utils.MARGIN, Utils.MARGIN));
 		userControls.add(new JLabel(Translation.get("gb.filter")));
 		userControls.add(filterTextfield);
 		
+		JPanel topPanel = new JPanel(new BorderLayout(0, 0));
+		topPanel.add(buttonControls, BorderLayout.WEST);
+		topPanel.add(userControls, BorderLayout.EAST);
+		
 		JPanel leftPanel = new JPanel(new BorderLayout());
-		leftPanel.add(userControls, BorderLayout.NORTH);
+		leftPanel.add(topPanel, BorderLayout.NORTH);
 		leftPanel.add(usersPanel, BorderLayout.CENTER);
 		
 		userCertificatePanel.setMinimumSize(new Dimension(375, 10));
+		
+		JLabel statusLabel = new JLabel();
+		statusLabel.setHorizontalAlignment(SwingConstants.RIGHT);
+		if (X509Utils.unlimitedStrength) {
+			statusLabel.setText("JCE Unlimited Strength Jurisdiction Policy");
+		} else {
+			statusLabel.setText("JCE Standard Encryption Policy");
+		}
 		
 		JPanel root = new JPanel(new BorderLayout()) {
 			private static final long serialVersionUID = 1L;
@@ -520,7 +798,8 @@
 		};
 		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, userCertificatePanel);
 		splitPane.setDividerLocation(1d);
-		root.add(splitPane);
+		root.add(splitPane, BorderLayout.CENTER);
+		root.add(statusLabel, BorderLayout.SOUTH);
 		return root;
 	}
 	
@@ -544,4 +823,99 @@
 		sorter.setRowFilter(containsFilter);
 		table.setRowSorter(sorter);
 	}
+	
+	@Override
+	public void log(String message) {
+		BufferedWriter writer = null;
+		try {
+			writer = new BufferedWriter(new FileWriter(new File(folder, X509Utils.CERTS + File.separator + "log.txt"), true));
+			writer.write(MessageFormat.format("{0,date,yyyy-MM-dd HH:mm}: {1}", new Date(), message));
+			writer.newLine();
+			writer.flush();
+		} catch (Exception e) {
+			LoggerFactory.getLogger(GitblitAuthority.class).error("Failed to append log entry!", e);
+		} finally {
+			if (writer != null) {
+				try {
+					writer.close();
+				} catch (IOException e) {
+				}
+			}
+		}
+	}
+	
+	private boolean sendEmail(UserModel user, X509Metadata metadata, File zip) {
+		// send email
+		try {
+			if (mail.isReady()) {
+				Message message = mail.createMessage(user.emailAddress);
+				message.setSubject("Your Gitblit client certificate for " + metadata.serverHostname);
+
+				// body of email
+				String body = X509Utils.processTemplate(new File(folder, X509Utils.CERTS + File.separator + "mail.tmpl"), metadata);
+				if (StringUtils.isEmpty(body)) {
+					body = MessageFormat.format("Hi {0}\n\nHere is your client certificate bundle.\nInside the zip file are installation instructions.", user.getDisplayName());
+				}
+				Multipart mp = new MimeMultipart();
+				MimeBodyPart messagePart = new MimeBodyPart();
+				messagePart.setText(body);
+				mp.addBodyPart(messagePart);
+
+				// attach zip
+				MimeBodyPart filePart = new MimeBodyPart();
+				FileDataSource fds = new FileDataSource(zip);
+				filePart.setDataHandler(new DataHandler(fds));
+				filePart.setFileName(fds.getName());
+				mp.addBodyPart(filePart);
+
+				message.setContent(mp);
+
+				mail.sendNow(message);
+				return true;
+			} else {
+				JOptionPane.showMessageDialog(GitblitAuthority.this, "Sorry, the mail server settings are not configured properly.\nCan not send email.", Translation.get("gb.error"), JOptionPane.ERROR_MESSAGE);
+			}
+		} catch (Exception e) {
+			Utils.showException(GitblitAuthority.this, e);
+		}
+		return false;
+	}
+	
+	private void setMetadataDefaults(X509Metadata metadata) {
+		metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
+		if (StringUtils.isEmpty(metadata.serverHostname)) {
+			metadata.serverHostname = Constants.NAME;
+		}
+		
+		// set default values from config file
+		File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
+		FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
+		if (certificatesConfigFile.exists()) {
+			try {
+				config.load();
+			} catch (Exception e) {
+				Utils.showException(GitblitAuthority.this, e);
+			}
+			NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
+			certificateConfig.update(metadata);
+		}
+	}
+	
+	private void updateAuthorityConfig(UserCertificateModel ucm) {
+		File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
+		FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
+		if (certificatesConfigFile.exists()) {
+			try {
+				config.load();
+			} catch (Exception e) {
+				Utils.showException(GitblitAuthority.this, e);
+			}
+		}
+		ucm.update(config);
+		try {
+			config.save();
+		} catch (Exception e) {
+			Utils.showException(GitblitAuthority.this, e);
+		}
+	}
 }

--
Gitblit v1.9.1