<commit_before>package jetbrains.buildServer.deployer.agent.ssh;

import com.jcraft.jsch.*;
import com.jcraft.jsch.agentproxy.AgentProxyException;
import com.jcraft.jsch.agentproxy.Connector;
import com.jcraft.jsch.agentproxy.ConnectorFactory;
import com.jcraft.jsch.agentproxy.RemoteIdentityRepository;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.InternalPropertiesHolder;
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.deployer.common.SSHRunnerConstants;
import jetbrains.buildServer.parameters.ProcessingResult;
import jetbrains.buildServer.util.FileUtil;
import jetbrains.buildServer.util.StringUtil;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;


public class SSHSessionProvider {

  public static final String TEAMCITY_DEPLOYER_SSH_CONFIG_PATH = "teamcity.deployer.ssh.config.path";
  public static final String TEAMCITY_DEPLOYER_SSH_DEFAULT_KEY = "teamcity.deployer.ssh.default.key";

  private final Logger myLog = Logger.getLogger(this.getClass());

  private Session mySession;
  private String myHost;
  private int myPort;
  private String myRemotePath;


  public SSHSessionProvider(@NotNull final BuildRunnerContext context, @NotNull final InternalPropertiesHolder holder) throws JSchException {

    final String target = context.getRunnerParameters().get(DeployerRunnerConstants.PARAM_TARGET_URL);
    final String portStr = context.getRunnerParameters().get(SSHRunnerConstants.PARAM_PORT);
    try {
      myPort = Integer.parseInt(portStr);
    } catch (NumberFormatException e) {
      myPort = 22;
    }

    final int delimiterIndex = target.indexOf(':');
    if (delimiterIndex > 0) {
      myHost = target.substring(0, delimiterIndex);
      final String remotePath = target.substring(delimiterIndex + 1);

      myRemotePath = remotePath.trim().replaceAll("\\\\", "/");
      if (new File(myRemotePath).isAbsolute() && !myRemotePath.startsWith("/")) {
        myRemotePath = "/" + myRemotePath;
      }
    } else {
      myHost = target;
      myRemotePath = "";
    }

    final String username = context.getRunnerParameters().get(DeployerRunnerConstants.PARAM_USERNAME);
    final String password = context.getRunnerParameters().get(DeployerRunnerConstants.PARAM_PASSWORD);
    final String authMethod = context.getRunnerParameters().get(SSHRunnerConstants.PARAM_AUTH_METHOD);

    JSch jsch = new JSch();
    JSch.setConfig("StrictHostKeyChecking", "no");

    myLog.debug("Initializing ssh session.");
    if (SSHRunnerConstants.AUTH_METHOD_DEFAULT_KEY.equals(authMethod)) {
      final String configPath = holder.getInternalProperty(TEAMCITY_DEPLOYER_SSH_CONFIG_PATH, System.getProperty("user.home") + File.separator + ".ssh" + File.separator + "config");
      //noinspection ConstantConditions
      final File config = new File(configPath);
      if (config.exists()) {
        myLog.debug("Found config at [" + config.getAbsolutePath() + "], reading.");
        initSessionSSHConfig(jsch, config);
      } else {
        final String keyPath = holder.getInternalProperty(TEAMCITY_DEPLOYER_SSH_DEFAULT_KEY, System.getProperty("user.home") + File.separator + ".ssh" + File.separator + "id_rsa");
        //noinspection ConstantConditions
        final File keyFile = new File(keyPath);
        myLog.debug("Using keyfile at [" + keyFile.getAbsolutePath() + "], load.");
        initSessionKeyFile(username, password, keyFile, jsch);
      }
    } else if (SSHRunnerConstants.AUTH_METHOD_CUSTOM_KEY.equals(authMethod)) {
      final String keyFilePath = context.getRunnerParameters().get(SSHRunnerConstants.PARAM_KEYFILE);
      final File keyFile = FileUtil.resolvePath(context.getBuild().getCheckoutDirectory(), keyFilePath);
      myLog.debug("Using keyfile at [" + keyFile.getAbsolutePath() + "], load.");
      initSessionKeyFile(username, password, keyFile, jsch);
    } else if (SSHRunnerConstants.AUTH_METHOD_SSH_AGENT.equals(authMethod)) {
      final ProcessingResult result = context.getParametersResolver().resolve("%env.SSH_AUTH_SOCK%");
      String socketPath = null;
      if (result.isFullyResolved()) {
        socketPath = result.getResult();<commit_msg>fix #60 fallback to default use key if no path is specified<commit_after>package jetbrains.buildServer.deployer.agent.ssh;

import com.jcraft.jsch.*;
import com.jcraft.jsch.agentproxy.AgentProxyException;
import com.jcraft.jsch.agentproxy.Connector;
import com.jcraft.jsch.agentproxy.ConnectorFactory;
import com.jcraft.jsch.agentproxy.RemoteIdentityRepository;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.InternalPropertiesHolder;
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.deployer.common.SSHRunnerConstants;
import jetbrains.buildServer.parameters.ProcessingResult;
import jetbrains.buildServer.util.FileUtil;
import jetbrains.buildServer.util.StringUtil;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;


public class SSHSessionProvider {

  public static final String TEAMCITY_DEPLOYER_SSH_CONFIG_PATH = "teamcity.deployer.ssh.config.path";
  public static final String TEAMCITY_DEPLOYER_SSH_DEFAULT_KEY = "teamcity.deployer.ssh.default.key";

  private final Logger myLog = Logger.getLogger(this.getClass());

  private Session mySession;
  private String myHost;
  private int myPort;
  private String myRemotePath;
  private final String myDefaultKeyPath = System.getProperty("user.home") + "/.ssh/id_rsa";


  public SSHSessionProvider(@NotNull final BuildRunnerContext context, @NotNull final InternalPropertiesHolder holder) throws JSchException {

    final String target = context.getRunnerParameters().get(DeployerRunnerConstants.PARAM_TARGET_URL);
    final String portStr = context.getRunnerParameters().get(SSHRunnerConstants.PARAM_PORT);
    try {
      myPort = Integer.parseInt(portStr);
    } catch (NumberFormatException e) {
      myPort = 22;
    }

    final int delimiterIndex = target.indexOf(':');
    if (delimiterIndex > 0) {
      myHost = target.substring(0, delimiterIndex);
      final String remotePath = target.substring(delimiterIndex + 1);

      myRemotePath = remotePath.trim().replaceAll("\\\\", "/");
      if (new File(myRemotePath).isAbsolute() && !myRemotePath.startsWith("/")) {
        myRemotePath = "/" + myRemotePath;
      }
    } else {
      myHost = target;
      myRemotePath = "";
    }

    final String username = context.getRunnerParameters().get(DeployerRunnerConstants.PARAM_USERNAME);
    final String password = context.getRunnerParameters().get(DeployerRunnerConstants.PARAM_PASSWORD);
    final String authMethod = context.getRunnerParameters().get(SSHRunnerConstants.PARAM_AUTH_METHOD);

    JSch jsch = new JSch();
    JSch.setConfig("StrictHostKeyChecking", "no");

    myLog.debug("Initializing ssh session.");
    if (SSHRunnerConstants.AUTH_METHOD_DEFAULT_KEY.equals(authMethod)) {
      final String configPath = holder.getInternalProperty(TEAMCITY_DEPLOYER_SSH_CONFIG_PATH, System.getProperty("user.home") + File.separator + ".ssh" + File.separator + "config");
      //noinspection ConstantConditions
      final File config = new File(configPath);
      if (config.exists()) {
        myLog.debug("Found config at [" + config.getAbsolutePath() + "], reading.");
        initSessionSSHConfig(jsch, config);
      } else {
        final String keyPath = holder.getInternalProperty(TEAMCITY_DEPLOYER_SSH_DEFAULT_KEY, myDefaultKeyPath);
        //noinspection ConstantConditions
        final File keyFile = new File(keyPath);
        myLog.debug("Using keyfile at [" + keyFile.getAbsolutePath() + "], load.");
        initSessionKeyFile(username, password, keyFile, jsch);
      }
    } else if (SSHRunnerConstants.AUTH_METHOD_CUSTOM_KEY.equals(authMethod)) {
      String keyFilePath = context.getRunnerParameters().get(SSHRunnerConstants.PARAM_KEYFILE);
      if (StringUtil.isEmpty(keyFilePath)) {
        keyFilePath = myDefaultKeyPath;
      }
      final File keyFile = FileUtil.resolvePath(context.getBuild().getCheckoutDirectory(), keyFilePath);
      myLog.debug("Using keyfile at [" + keyFile.getAbsolutePath() + "], load.");
      initSessionKeyFile(username, password, keyFile, jsch);
    } else if (SSHRunnerConstants.AUTH_METHOD_SSH_AGENT.equals(authMethod)) {
      final ProcessingResult result = context.getParametersResolver().resolve("%env.SSH_AUTH_SOCK%");
      String socketPath = null;
      if (result.isFullyResolved()) {
        socketPath = result.getResult();
{'fraction_non_alphanumeric': 0.10839642119752237, 'fraction_numerical': 0.001605872906629961, 'mean_word_length': 4.636069812540401, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2410379', 'n_tokens_mistral': 2566, 'n_tokens_neox': 2496, 'n_words': 473}