Honor ~/.ssh/config whenever possible during SSH based transport
[egit.git] / org.spearce.egit.ui / src / org / spearce / egit / ui / EclipseSshSessionFactory.java
blob640a165f7a4a7172d73816257e188f2c13e1a1b2
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. This program and the accompanying materials
6 * are made available under the terms of the Eclipse Public License v1.0
7 * See LICENSE for the full license text, also available.
8 *******************************************************************************/
9 package org.spearce.egit.ui;
11 import java.io.File;
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.util.HashSet;
15 import java.util.Set;
17 import org.eclipse.jsch.core.IJSchService;
18 import org.eclipse.jsch.ui.UserInfoPrompter;
19 import org.spearce.jgit.transport.OpenSshConfig;
20 import org.spearce.jgit.transport.SshSessionFactory;
22 import com.jcraft.jsch.JSchException;
23 import com.jcraft.jsch.Session;
25 class EclipseSshSessionFactory extends SshSessionFactory {
26 private final IJSchService provider;
28 private final Set<String> loadedIdentities = new HashSet<String>();
30 private OpenSshConfig config;
32 EclipseSshSessionFactory(final IJSchService p) {
33 provider = p;
36 @Override
37 public Session getSession(String user, String pass, String host, int port)
38 throws JSchException {
39 final OpenSshConfig.Host hc = getConfig().lookup(host);
40 host = hc.getHostName();
41 if (port <= 0)
42 port = hc.getPort();
43 if (user == null)
44 user = hc.getUser();
46 final Session session = provider.createSession(host, port, user);
47 if (hc.getIdentityFile() != null)
48 addIdentity(hc.getIdentityFile());
49 if (pass != null)
50 session.setPassword(pass);
51 else
52 new UserInfoPrompter(session);
53 return session;
56 private synchronized OpenSshConfig getConfig() {
57 if (config == null)
58 config = OpenSshConfig.get();
59 return config;
62 private void addIdentity(final File identityFile)
63 throws JSchException {
64 final String path = identityFile.getAbsolutePath();
65 if (loadedIdentities.add(path))
66 provider.getJSch().addIdentity(path);
69 @Override
70 public OutputStream getErrorStream() {
71 return new OutputStream() {
73 StringBuilder all = new StringBuilder();
75 StringBuilder sb = new StringBuilder();
77 public String toString() {
78 String r = all.toString();
79 while (r.endsWith("\n"))
80 r = r.substring(0, r.length() - 1);
81 return r;
84 @Override
85 public void write(int b) throws IOException {
86 if (b == '\r')
87 return;
88 sb.append((char) b);
89 if (b == '\n') {
90 String s = sb.toString();
91 all.append(s);
92 sb = new StringBuilder();
93 Activator.logError(s, new Throwable());