org.eclipse.jgit.errors.TransportException Java Examples

The following examples show how to use org.eclipse.jgit.errors.TransportException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransportCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected Transport openTransport (boolean openPush) throws URISyntaxException, NotSupportedException, TransportException {
    URIish uri = getUriWithUsername(openPush);
    // WA for #200693, jgit fails to initialize ftp protocol
    for (TransportProtocol proto : Transport.getTransportProtocols()) {
        if (proto.getSchemes().contains("ftp")) { //NOI18N
            Transport.unregister(proto);
        }
    }
    try {
        Transport transport = Transport.open(getRepository(), uri);
        RemoteConfig config = getRemoteConfig();
        if (config != null) {
            transport.applyConfig(config);
        }
        if (transport.getTimeout() <= 0) {
            transport.setTimeout(45);
        }
        transport.setCredentialsProvider(getCredentialsProvider());
        return transport;
    } catch (IllegalArgumentException ex) {
        throw new TransportException(ex.getLocalizedMessage(), ex);
    }
}
 
Example #2
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Java 11 spotbugs error")
private Set<String> listRemoteBranches(String remote) throws NotSupportedException, TransportException, URISyntaxException {
    Set<String> branches = new HashSet<>();
    try (final Repository repo = getRepository()) {
        StoredConfig config = repo.getConfig();
        try (final Transport tn = Transport.open(repo, new URIish(config.getString("remote",remote,"url")))) {
            tn.setCredentialsProvider(getProvider());
            try (final FetchConnection c = tn.openFetch()) {
                for (final Ref r : c.getRefs()) {
                    if (r.getName().startsWith(R_HEADS))
                        branches.add("refs/remotes/"+remote+"/"+r.getName().substring(R_HEADS.length()));
                }
            }
        }
    }
    return branches;
}
 
Example #3
Source File: JGitSshSessionFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized RemoteSession getSession (URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
    boolean agentUsed = false;
    String host = uri.getHost();
    CredentialItem.StringType identityFile = null;
    if (credentialsProvider != null) {
        identityFile = new JGitCredentialsProvider.IdentityFileItem("Identity file for " + host, false);
        if (credentialsProvider.isInteractive() && credentialsProvider.get(uri, identityFile) && identityFile.getValue() != null) {
            LOG.log(Level.FINE, "Identity file for {0}: {1}", new Object[] { host, identityFile.getValue() }); //NOI18N
            agentUsed = setupJSch(fs, host, identityFile, uri, true);
            LOG.log(Level.FINE, "Setting cert auth for {0}, agent={1}", new Object[] { host, agentUsed }); //NOI18N
        }
    }
    try {
        LOG.log(Level.FINE, "Trying to connect to {0}, agent={1}", new Object[] { host, agentUsed }); //NOI18N
        return super.getSession(uri, credentialsProvider, fs, tms);
    } catch (Exception ex) {
        // catch rather all exceptions. In case jsch-agent-proxy is broken again we should
        // at least fall back on key/pasphrase
        if (agentUsed) {
            LOG.log(ex instanceof TransportException ? Level.FINE : Level.INFO, null, ex);
            setupJSch(fs, host, identityFile, uri, false);
            LOG.log(Level.FINE, "Trying to connect to {0}, agent={1}", new Object[] { host, false }); //NOI18N
            return super.getSession(uri, credentialsProvider, fs, tms);
        } else {
            LOG.log(Level.FINE, "Connection failed: {0}", host); //NOI18N
            throw ex;
        }
    }
}
 
Example #4
Source File: TrileadSessionFactory.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
    try {
        int p = uri.getPort();
        if (p<0)    p = 22;
        Connection con = new Connection(uri.getHost(), p);
        con.setTCPNoDelay(true);
        con.connect();  // TODO: host key check

        boolean authenticated;
        if (credentialsProvider instanceof SmartCredentialsProvider) {
            final SmartCredentialsProvider smart = (SmartCredentialsProvider) credentialsProvider;
            StandardUsernameCredentialsCredentialItem
                    item = new StandardUsernameCredentialsCredentialItem("Credentials for " + uri, false);
            authenticated = smart.supports(item)
                    && smart.get(uri, item)
                    && SSHAuthenticator.newInstance(con, item.getValue(), uri.getUser())
                    .authenticate(smart.listener);
        } else if (credentialsProvider instanceof CredentialsProviderImpl) {
            CredentialsProviderImpl sshcp = (CredentialsProviderImpl) credentialsProvider;

            authenticated = SSHAuthenticator.newInstance(con, sshcp.cred).authenticate(sshcp.listener);
        } else {
            authenticated = false;
        }
        if (!authenticated && con.isAuthenticationComplete())
            throw new TransportException("Authentication failure");

        return wrap(con);
    } catch (UnsupportedCredentialItem | IOException | InterruptedException e) {
        throw new TransportException(uri,"Failed to connect",e);
    }
}
 
Example #5
Source File: CheckoutRequestHandlerTest.java    From gocd-git-path-material-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleApiRequestAndRenderErrorApiResponse() {
    RequestHandler checkoutRequestHandler = new CheckoutRequestHandler();
    ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
    TransportException cause = new TransportException("[email protected]:lifealike/gocd-config.git: UnknownHostKey: github.com. RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48");
    RuntimeException runtimeException = new RuntimeException("clone failed", cause);
    doThrow(runtimeException).when(jGitHelperMock).cloneOrFetch();
    when(JsonUtils.renderErrorApiResponse(eq(pluginApiRequestMock), errorCaptor.capture())).thenReturn(mock(GoPluginApiResponse.class));

    checkoutRequestHandler.handle(pluginApiRequestMock);
    assertThat(errorCaptor.getValue(), is(runtimeException));
}
 
Example #6
Source File: GetLatestRevisionRequestHandlerTest.java    From gocd-git-path-material-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleApiRequestAndRenderErrorApiResponseWhenCloneFailed() {
    RequestHandler checkoutRequestHandler = new GetLatestRevisionRequestHandler();
    ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
    TransportException cause = new TransportException("[email protected]:lifealike/gocd-config.git: UnknownHostKey: github.com. RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48");
    RuntimeException runtimeException = new RuntimeException("clone failed", cause);

    when(JsonUtils.renderErrorApiResponse(eq(pluginApiRequestMock), errorCaptor.capture())).thenReturn(mock(GoPluginApiResponse.class));
    when(gitConfigMock.getUrl()).thenReturn("https://github.com/TWChennai/gocd-git-path-material-plugin.git");
    doThrow(runtimeException).when(jGitHelperMock).cloneOrFetch();

    checkoutRequestHandler.handle(pluginApiRequestMock);

    assertThat(errorCaptor.getValue(), is(runtimeException));
}
 
Example #7
Source File: SecureShellAuthentication.java    From github-bucket with ISC License 5 votes vote down vote up
public SecureShellAuthentication(Bucket bucket, AmazonS3 client) {
    factory = new JschConfigSessionFactory() {

        @Override
        public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
            // Do not check for default ssh user config
            fs.setUserHome(null);
            return super.getSession(uri, credentialsProvider, fs, tms);
        }

        @Override
        protected void configure(OpenSshConfig.Host host, Session session) {
            session.setConfig("HashKnownHosts", "no");
            if ("localhost".equalsIgnoreCase(host.getHostName())) {
                session.setConfig("StrictHostKeyChecking", "no");
            }
        }

        @Override
        protected void configureJSch(JSch jsch) {
            S3Object file;
            file = client.getObject(bucket.getName(), ".ssh/known_hosts");
            try (InputStream is = file.getObjectContent()) {
                jsch.setKnownHosts(is);
            } catch (IOException | JSchException e) {
                throw new IllegalArgumentException("Missing known hosts file on s3: .ssh/known_hosts", e);
            }
            file = client.getObject(bucket.getName(), ".ssh/id_rsa");
            try (InputStream is = file.getObjectContent()) {
                jsch.addIdentity("git", IOUtils.toByteArray(is), null, new byte[0]);
            } catch (IOException | JSchException e) {
                throw new IllegalArgumentException("Missing key file on s3: .ssh/id_rsa", e);
            }
        }
    };
}
 
Example #8
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 5 votes vote down vote up
private void readLooseRefs(final TreeMap<String, Ref> avail) throws TransportException {
    try {
        // S3 limits the size of the response to 1000 entries. Batch the requests.
        String prefix = resolveKey(ROOT_DIR + "refs");
        List<S3ObjectSummary> refs = getS3ObjectSummaries(prefix);
        for (final S3ObjectSummary ref : refs) {
            readRef(avail, "refs/" + ref.getKey().substring(prefix.length() + 1));
        }
    }
    catch (IOException e) {
        throw new TransportException(getURI(), JGitText.get().cannotListRefs, e);
    }
}
 
Example #9
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 5 votes vote down vote up
Map<String, Ref> readAdvertisedRefs() throws TransportException {
    final TreeMap<String, Ref> avail = new TreeMap<>();
    readPackedRefs(avail);
    readLooseRefs(avail);
    readRef(avail, Constants.HEAD);
    return avail;
}
 
Example #10
Source File: SecureShellAuthentication.java    From github-bucket with ISC License 5 votes vote down vote up
public SecureShellAuthentication(Bucket bucket, AmazonS3 client) {
    factory = new JschConfigSessionFactory() {

        @Override
        public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
            // Do not check for default ssh user config
            fs.setUserHome(null);
            return super.getSession(uri, credentialsProvider, fs, tms);
        }

        @Override
        protected void configure(OpenSshConfig.Host host, Session session) {
            session.setConfig("HashKnownHosts", "no");
            if ("localhost".equalsIgnoreCase(host.getHostName())) {
                session.setConfig("StrictHostKeyChecking", "no");
            }
        }

        @Override
        protected void configureJSch(JSch jsch) {
            S3Object file;
            file = client.getObject(bucket.getName(), ".ssh/known_hosts");
            try (InputStream is = file.getObjectContent()) {
                jsch.setKnownHosts(is);
            } catch (IOException | JSchException e) {
                throw new IllegalArgumentException("Missing known hosts file on s3: .ssh/known_hosts", e);
            }
            file = client.getObject(bucket.getName(), ".ssh/id_rsa");
            try (InputStream is = file.getObjectContent()) {
                jsch.addIdentity("git", IOUtils.toByteArray(is), null, new byte[0]);
            } catch (IOException | JSchException e) {
                throw new IllegalArgumentException("Missing key file on s3: .ssh/id_rsa", e);
            }
        }
    };
}
 
Example #11
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 5 votes vote down vote up
private void readLooseRefs(final TreeMap<String, Ref> avail) throws TransportException {
    try {
        // S3 limits the size of the response to 1000 entries. Batch the requests.
        String prefix = resolveKey(ROOT_DIR + "refs");
        List<S3ObjectSummary> refs = getS3ObjectSummaries(prefix);
        for (final S3ObjectSummary ref : refs) {
            readRef(avail, "refs/" + ref.getKey().substring(prefix.length() + 1));
        }
    }
    catch (IOException e) {
        throw new TransportException(getURI(), JGitText.get().cannotListRefs, e);
    }
}
 
Example #12
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 5 votes vote down vote up
Map<String, Ref> readAdvertisedRefs() throws TransportException {
    final TreeMap<String, Ref> avail = new TreeMap<>();
    readPackedRefs(avail);
    readLooseRefs(avail);
    readRef(avail, Constants.HEAD);
    return avail;
}
 
Example #13
Source File: JGitSshSessionFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean setupJSch (FS fs, String host, CredentialItem.StringType identityFile, URIish uri, boolean preferAgent) throws TransportException {
    boolean agentUsed;
    if (sshConfig == null) {
        sshConfig = OpenSshConfig.get(fs);
    }
    final OpenSshConfig.Host hc = sshConfig.lookup(host);
    try {
        JSch jsch = getJSch(hc, fs);
        agentUsed = setupJSchIdentityRepository(jsch, identityFile.getValue(), preferAgent);
    } catch (JSchException ex) {
        throw new TransportException(uri, ex.getMessage(), ex);
    }
    return agentUsed;
}
 
Example #14
Source File: MultiUserSshSessionFactory.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public synchronized RemoteSession getSession(URIish uri,
                                             CredentialsProvider credentialsProvider, FS fs, int tms)
        throws TransportException {

    String user = uri.getUser();
    final String pass = uri.getPass();
    String host = uri.getHost();
    int port = uri.getPort();

    try {
        if (config == null)
            config = OpenSshConfig.get(fs);

        final OpenSshConfig.Host hc = config.lookup(host);
        host = hc.getHostName();
        if (port <= 0)
            port = hc.getPort();
        if (user == null)
            user = hc.getUser();

        Session session = createSession(credentialsProvider, fs, user,
                pass, host, port, hc);

        int retries = 0;
        while (!session.isConnected()) {
            try {
                retries++;
                session.connect(tms);
            } catch (JSchException e) {
                session.disconnect();
                session = null;
                // Make sure our known_hosts is not outdated
                knownHosts(getJSch(credentialsProvider, hc, fs), fs);

                if (isAuthenticationCanceled(e)) {
                    throw e;
                } else if (isAuthenticationFailed(e)
                        && credentialsProvider != null) {
                    // if authentication failed maybe credentials changed at
                    // the remote end therefore reset credentials and retry
                    if (retries < 3) {
                        credentialsProvider.reset(uri);
                        session = createSession(credentialsProvider, fs,
                                user, pass, host, port, hc);
                    } else
                        throw e;
                } else if (retries >= hc.getConnectionAttempts()) {
                    throw e;
                } else {
                    try {
                        Thread.sleep(1000);
                        session = createSession(credentialsProvider, fs,
                                user, pass, host, port, hc);
                    } catch (InterruptedException e1) {
                        throw new TransportException(
                                JGitText.get().transportSSHRetryInterrupt,
                                e1);
                    }
                }
            }
        }

        return new JschSession(session, uri);

    } catch (JSchException je) {
        final Throwable c = je.getCause();
        if (c instanceof UnknownHostException)
            throw new TransportException(uri, JGitText.get().unknownHost);
        if (c instanceof ConnectException)
            throw new TransportException(uri, c.getMessage());
        throw new TransportException(uri, je.getMessage(), je);
    }

}
 
Example #15
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 4 votes vote down vote up
public FetchConnection openFetch() throws TransportException {
    final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects");
    final WalkFetchConnection r = new WalkFetchConnection(this, c);
    r.available(c.readAdvertisedRefs());
    return r;
}
 
Example #16
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 4 votes vote down vote up
public PushConnection openPush() throws TransportException {
    final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects");
    final WalkPushConnection r = new WalkPushConnection(this, c);
    r.available(c.readAdvertisedRefs());
    return r;
}
 
Example #17
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 4 votes vote down vote up
public PushConnection openPush() throws TransportException {
    final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects");
    final WalkPushConnection r = new WalkPushConnection(this, c);
    r.available(c.readAdvertisedRefs());
    return r;
}
 
Example #18
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 4 votes vote down vote up
public FetchConnection openFetch() throws TransportException {
    final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects");
    final WalkFetchConnection r = new WalkFetchConnection(this, c);
    r.available(c.readAdvertisedRefs());
    return r;
}
 
Example #19
Source File: GitSshSessionFactory.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
	int port = uri.getPort();
	String user = uri.getUser();
	String pass = uri.getPass();
	if (credentialsProvider instanceof GitCredentialsProvider) {
		if (port <= 0)
			port = SSH_PORT;

		GitCredentialsProvider cp = (GitCredentialsProvider) credentialsProvider;
		if (user == null) {
			CredentialItem.Username u = new CredentialItem.Username();
			if (cp.supports(u) && cp.get(cp.getUri(), u)) {
				user = u.getValue();
			}
		}
		if (pass == null) {
			CredentialItem.Password p = new CredentialItem.Password();
			if (cp.supports(p) && cp.get(cp.getUri(), p)) {
				pass = new String(p.getValue());
			}
		}

		try {
			final SessionHandler session = new SessionHandler(user, uri.getHost(), port, cp.getKnownHosts(), cp.getPrivateKey(), cp.getPublicKey(),
					cp.getPassphrase());
			if (pass != null)
				session.setPassword(pass);
			if (!credentialsProvider.isInteractive()) {
				session.setUserInfo(new CredentialsProviderUserInfo(session.getSession(), credentialsProvider));
			}

			session.connect(tms);

			return new JschSession(session.getSession(), uri);
		} catch (JSchException e) {
			throw new TransportException(uri, e.getMessage(), e);
		}
	}
	return null;
}