Ejemplo n.º 1
0
  public static int _main(String[] _args) throws Exception {
    List<String> args = Arrays.asList(_args);
    List<KeyPair> candidateKeys = new ArrayList<KeyPair>();
    boolean sshAuthRequestedExplicitly = false;

    String url = System.getenv("JENKINS_URL");

    if (url == null) url = System.getenv("HUDSON_URL");

    while (!args.isEmpty()) {
      String head = args.get(0);
      if (head.equals("-s") && args.size() >= 2) {
        url = args.get(1);
        args = args.subList(2, args.size());
        continue;
      }
      if (head.equals("-i") && args.size() >= 2) {
        File f = new File(args.get(1));
        if (!f.exists()) {
          printUsage(Messages.CLI_NoSuchFileExists(f));
          return -1;
        }
        try {
          candidateKeys.add(loadKey(f));
        } catch (IOException e) {
          throw new Exception("Failed to load key: " + f, e);
        } catch (GeneralSecurityException e) {
          throw new Exception("Failed to load key: " + f, e);
        }
        args = args.subList(2, args.size());
        sshAuthRequestedExplicitly = true;
        continue;
      }
      break;
    }

    if (url == null) {
      printUsage(Messages.CLI_NoURL());
      return -1;
    }

    if (args.isEmpty()) args = Arrays.asList("help"); // default to help

    if (candidateKeys.isEmpty()) addDefaultPrivateKeyLocations(candidateKeys);

    CLI cli = new CLI(new URL(url));
    try {
      if (!candidateKeys.isEmpty()) {
        try {
          // TODO: server verification
          cli.authenticate(candidateKeys);
        } catch (IllegalStateException e) {
          if (sshAuthRequestedExplicitly) {
            System.err.println("The server doesn't support public key authentication");
            return -1;
          }
        } catch (UnsupportedOperationException e) {
          if (sshAuthRequestedExplicitly) {
            System.err.println("The server doesn't support public key authentication");
            return -1;
          }
        } catch (GeneralSecurityException e) {
          if (sshAuthRequestedExplicitly) {
            System.err.println(e.getMessage());
            LOGGER.log(FINE, e.getMessage(), e);
            return -1;
          }
          System.err.println(
              "Failed to authenticate with your SSH keys. Proceeding with anonymous access");
          LOGGER.log(
              FINE,
              "Failed to authenticate with your SSH keys. Proceeding with anonymous access",
              e);
        }
      }

      // execute the command
      // Arrays.asList is not serializable --- see 6835580
      args = new ArrayList<String>(args);
      return cli.execute(args, System.in, System.out, System.err);
    } finally {
      cli.close();
    }
  }