Refactor SSH key loading so we don't duplicate keys
[egit.git] / org.spearce.jgit / src / org / spearce / jgit / transport / DefaultSshSessionFactory.java
blob0484fc0113668970313a8e2f36be2d5223569a37
1 /*
2 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
3 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
5 * All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
9 * conditions are met:
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * - Neither the name of the Git Development Community nor the
20 * names of its contributors may be used to endorse or promote
21 * products derived from this software without specific prior
22 * written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
25 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
26 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 package org.spearce.jgit.transport;
41 import java.awt.Container;
42 import java.awt.GridBagConstraints;
43 import java.awt.GridBagLayout;
44 import java.awt.Insets;
45 import java.io.File;
46 import java.io.FileInputStream;
47 import java.io.FileNotFoundException;
48 import java.io.IOException;
49 import java.io.OutputStream;
50 import java.security.AccessController;
51 import java.security.PrivilegedAction;
53 import javax.swing.JLabel;
54 import javax.swing.JOptionPane;
55 import javax.swing.JPanel;
56 import javax.swing.JPasswordField;
57 import javax.swing.JTextField;
59 import org.spearce.jgit.util.FS;
61 import com.jcraft.jsch.JSch;
62 import com.jcraft.jsch.JSchException;
63 import com.jcraft.jsch.Session;
64 import com.jcraft.jsch.UIKeyboardInteractive;
65 import com.jcraft.jsch.UserInfo;
67 /**
68 * Loads known hosts and private keys from <code>$HOME/.ssh</code>.
69 * <p>
70 * This is the default implementation used by JGit and provides most of the
71 * compatibility necessary to match OpenSSH, a popular implementation of SSH
72 * used by C Git.
73 * <p>
74 * If user interactivity is required by SSH (e.g. to obtain a password) AWT is
75 * used to display a password input field to the end-user.
77 class DefaultSshSessionFactory extends SshSessionFactory {
78 /** IANA assigned port number for SSH. */
79 private static final int SSH_PORT = 22;
81 private Set<String> loadedIdentities;
83 private JSch userJSch;
85 @Override
86 public synchronized Session getSession(String user, String pass,
87 String host, int port) throws JSchException {
88 if (port <= 0)
89 port = SSH_PORT;
90 if (user == null)
91 user = userName();
93 final Session session = getUserJSch().getSession(user, host, port);
94 if (pass != null)
95 session.setPassword(pass);
96 else
97 session.setUserInfo(new AWT_UserInfo());
98 return session;
101 private static String userName() {
102 return AccessController.doPrivileged(new PrivilegedAction<String>() {
103 public String run() {
104 return System.getProperty("user.name");
109 private JSch getUserJSch() throws JSchException {
110 if (userJSch == null) {
111 loadedIdentities = new HashSet<String>();
112 userJSch = new JSch();
113 knownHosts(userJSch);
114 identities();
116 return userJSch;
119 private void knownHosts(final JSch sch) throws JSchException {
120 final File home = FS.userHome();
121 if (home == null)
122 return;
123 final File known_hosts = new File(new File(home, ".ssh"), "known_hosts");
124 try {
125 final FileInputStream in = new FileInputStream(known_hosts);
126 try {
127 sch.setKnownHosts(in);
128 } finally {
129 in.close();
131 } catch (FileNotFoundException none) {
132 // Oh well. They don't have a known hosts in home.
133 } catch (IOException err) {
134 // Oh well. They don't have a known hosts in home.
138 private void identities() throws JSchException {
139 final File home = FS.userHome();
140 if (home == null)
141 return;
142 final File sshdir = new File(home, ".ssh");
143 final File[] keys = sshdir.listFiles();
144 if (keys == null)
145 return;
146 for (int i = 0; i < keys.length; i++) {
147 final File pk = keys[i];
148 final String n = pk.getName();
149 if (!n.endsWith(".pub"))
150 continue;
151 final File k = new File(sshdir, n.substring(0, n.length() - 4));
152 if (!k.isFile())
153 continue;
154 addIdentity(k);
158 private void addIdentity(final File identityFile) throws JSchException {
159 final String path = identityFile.getAbsolutePath();
160 if (loadedIdentities.add(path))
161 userJSch.addIdentity(path);
164 private static class AWT_UserInfo implements UserInfo,
165 UIKeyboardInteractive {
166 private String passwd;
168 private String passphrase;
170 public void showMessage(final String msg) {
171 JOptionPane.showMessageDialog(null, msg);
174 public boolean promptYesNo(final String msg) {
175 return JOptionPane.showConfirmDialog(null, msg, "Warning",
176 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
179 public boolean promptPassword(final String msg) {
180 passwd = null;
181 final JPasswordField passwordField = new JPasswordField(20);
182 final int result = JOptionPane.showConfirmDialog(null,
183 new Object[] { passwordField }, msg,
184 JOptionPane.OK_CANCEL_OPTION);
185 if (result == JOptionPane.OK_OPTION) {
186 passwd = new String(passwordField.getPassword());
187 return true;
189 return false;
192 public boolean promptPassphrase(final String msg) {
193 passphrase = null;
194 final JPasswordField passwordField = new JPasswordField(20);
195 final int result = JOptionPane.showConfirmDialog(null,
196 new Object[] { passwordField }, msg,
197 JOptionPane.OK_CANCEL_OPTION);
198 if (result == JOptionPane.OK_OPTION) {
199 passphrase = new String(passwordField.getPassword());
200 return true;
202 return false;
205 public String getPassword() {
206 return passwd;
209 public String getPassphrase() {
210 return passphrase;
213 public String[] promptKeyboardInteractive(final String destination,
214 final String name, final String instruction,
215 final String[] prompt, final boolean[] echo) {
216 final GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1,
217 1, 1, GridBagConstraints.NORTHWEST,
218 GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
219 final Container panel = new JPanel();
220 panel.setLayout(new GridBagLayout());
222 gbc.weightx = 1.0;
223 gbc.gridwidth = GridBagConstraints.REMAINDER;
224 gbc.gridx = 0;
225 panel.add(new JLabel(instruction), gbc);
226 gbc.gridy++;
228 gbc.gridwidth = GridBagConstraints.RELATIVE;
230 final JTextField[] texts = new JTextField[prompt.length];
231 for (int i = 0; i < prompt.length; i++) {
232 gbc.fill = GridBagConstraints.NONE;
233 gbc.gridx = 0;
234 gbc.weightx = 1;
235 panel.add(new JLabel(prompt[i]), gbc);
237 gbc.gridx = 1;
238 gbc.fill = GridBagConstraints.HORIZONTAL;
239 gbc.weighty = 1;
240 if (echo[i]) {
241 texts[i] = new JTextField(20);
242 } else {
243 texts[i] = new JPasswordField(20);
245 panel.add(texts[i], gbc);
246 gbc.gridy++;
249 if (JOptionPane.showConfirmDialog(null, panel, destination + ": "
250 + name, JOptionPane.OK_CANCEL_OPTION,
251 JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
252 String[] response = new String[prompt.length];
253 for (int i = 0; i < prompt.length; i++) {
254 response[i] = texts[i].getText();
256 return response;
258 return null; // cancel
262 @Override
263 public OutputStream getErrorStream() {
264 return new OutputStream() {
265 private StringBuilder all = new StringBuilder();
267 private StringBuilder sb = new StringBuilder();
269 public String toString() {
270 String r = all.toString();
271 while (r.endsWith("\n"))
272 r = r.substring(0, r.length() - 1);
273 return r;
276 @Override
277 public void write(final int b) throws IOException {
278 if (b == '\r') {
279 System.err.print('\r');
280 return;
283 sb.append((char) b);
285 if (b == '\n') {
286 final String line = sb.toString();
287 System.err.print(line);
288 all.append(line);
289 sb = new StringBuilder();