Search in sources :

Example 1 with Exception

use of com.tigervnc.rfb.Exception in project tigervnc by TigerVNC.

the class Parameters method loadViewerParameters.

public static String loadViewerParameters(String filename) throws Exception {
    String servername = "";
    String filepath;
    if (filename == null) {
        return loadFromReg();
    /*
      String homeDir = FileUtils.getVncHomeDir();
      if (homeDir == null)
        throw new Exception("Failed to read configuration file, "+
                            "can't obtain home directory path.");
      filepath = homeDir.concat("default.tigervnc");
      */
    } else {
        filepath = filename;
    }
    /* Read parameters from file */
    File f = new File(filepath);
    if (!f.exists() || !f.canRead()) {
        if (filename == null || filename.isEmpty())
            return null;
        throw new Exception(String.format("Failed to read configuration file, can't open %s", filepath));
    }
    String line = "";
    LineNumberReader reader;
    try {
        reader = new LineNumberReader(new FileReader(f));
    } catch (FileNotFoundException e) {
        throw new Exception(e.getMessage());
    }
    int lineNr = 0;
    while (line != null) {
        // Read the next line
        try {
            line = reader.readLine();
            lineNr = reader.getLineNumber();
            if (line == null)
                break;
        } catch (IOException e) {
            throw new Exception(String.format("Failed to read line %d in file %s: %s", lineNr, filepath, e.getMessage()));
        }
        // Make sure that the first line of the file has the file identifier string
        if (lineNr == 1) {
            if (line.equals(IDENTIFIER_STRING))
                continue;
            else
                throw new Exception(String.format("Configuration file %s is in an invalid format", filename));
        }
        // Skip empty lines and comments
        if (line.trim().isEmpty() || line.trim().startsWith("#"))
            continue;
        // Find the parameter value
        int idx = line.indexOf("=");
        if (idx == -1) {
            vlog.error(String.format("Failed to read line %d in file %s: %s", lineNr, filename, "Invalid format"));
            continue;
        }
        String value = line.substring(idx + 1).trim();
        // Will be set to false below if
        boolean invalidParameterName = true;
        if (line.substring(0, idx).trim().equalsIgnoreCase("ServerName")) {
            if (value.length() > 256) {
                vlog.error(String.format("Failed to read line %d in file %s: %s", lineNr, filepath, "Invalid format or too large value"));
                continue;
            }
            servername = value;
            invalidParameterName = false;
        } else {
            for (int i = 0; i < parameterArray.length; i++) {
                if (parameterArray[i] instanceof StringParameter) {
                    if (line.substring(0, idx).trim().equalsIgnoreCase(parameterArray[i].getName())) {
                        if (value.length() > 256) {
                            vlog.error(String.format("Failed to read line %d in file %s: %s", lineNr, filepath, "Invalid format or too large value"));
                            continue;
                        }
                        ((StringParameter) parameterArray[i]).setParam(value);
                        invalidParameterName = false;
                    }
                } else if (parameterArray[i] instanceof IntParameter) {
                    if (line.substring(0, idx).trim().equalsIgnoreCase(parameterArray[i].getName())) {
                        ((IntParameter) parameterArray[i]).setParam(value);
                        invalidParameterName = false;
                    }
                } else if (parameterArray[i] instanceof BoolParameter) {
                    if (line.substring(0, idx).trim().equalsIgnoreCase(parameterArray[i].getName())) {
                        ((BoolParameter) parameterArray[i]).setParam(value);
                        invalidParameterName = false;
                    }
                } else {
                    vlog.error(String.format("Unknown parameter type for parameter %s", parameterArray[i].getName()));
                }
            }
        }
        if (invalidParameterName)
            vlog.info(String.format("Unknown parameter %s on line %d in file %s", line, lineNr, filepath));
    }
    try {
        reader.close();
    } catch (IOException e) {
        vlog.info(e.getMessage());
    } finally {
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
        }
    }
    return servername;
}
Also used : FileNotFoundException(java.io.FileNotFoundException) FileReader(java.io.FileReader) IOException(java.io.IOException) File(java.io.File) IOException(java.io.IOException) Exception(com.tigervnc.rfb.Exception) FileNotFoundException(java.io.FileNotFoundException) LineNumberReader(java.io.LineNumberReader)

Example 2 with Exception

use of com.tigervnc.rfb.Exception in project tigervnc by TigerVNC.

the class Parameters method saveViewerParameters.

public static void saveViewerParameters(String filename, String servername) {
    // Write to the registry or a predefined file if no filename was specified.
    String filepath;
    if (filename == null || filename.isEmpty()) {
        saveToReg(servername);
        return;
    /*
      String homeDir = FileUtils.getVncHomeDir();
      if (homeDir == null)
        throw new Exception("Failed to read configuration file, "+
                            "can't obtain home directory path.");
      filepath = homeDir.concat("default.tigervnc");
      */
    } else {
        filepath = filename;
    }
    /* Write parameters to file */
    File f = new File(filepath);
    if (f.exists() && !f.canWrite())
        throw new Exception(String.format("Failed to write configuration file," + "can't open %s", filepath));
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(f, "UTF-8");
    } catch (java.lang.Exception e) {
        throw new Exception(e.getMessage());
    }
    pw.println(IDENTIFIER_STRING);
    pw.println("");
    if (servername != null && !servername.isEmpty()) {
        pw.println(String.format("ServerName=%s\n", servername));
        updateConnHistory(servername);
    }
    for (int i = 0; i < parameterArray.length; i++) {
        if (parameterArray[i] instanceof StringParameter) {
            // if (line.substring(0,idx).trim().equalsIgnoreCase(parameterArray[i].getName()))
            pw.println(String.format("%s=%s", parameterArray[i].getName(), parameterArray[i].getValueStr()));
        } else if (parameterArray[i] instanceof IntParameter) {
            // if (line.substring(0,idx).trim().equalsIgnoreCase(parameterArray[i].getName()))
            pw.println(String.format("%s=%s", parameterArray[i].getName(), parameterArray[i].getValueStr()));
        } else if (parameterArray[i] instanceof BoolParameter) {
            // if (line.substring(0,idx).trim().equalsIgnoreCase(parameterArray[i].getName()))
            pw.println(String.format("%s=%s", parameterArray[i].getName(), parameterArray[i].getValueStr()));
        } else {
            vlog.error(String.format("Unknown parameter type for parameter %s", parameterArray[i].getName()));
        }
    }
    pw.flush();
    pw.close();
}
Also used : File(java.io.File) IOException(java.io.IOException) Exception(com.tigervnc.rfb.Exception) FileNotFoundException(java.io.FileNotFoundException) PrintWriter(java.io.PrintWriter)

Example 3 with Exception

use of com.tigervnc.rfb.Exception in project tigervnc by TigerVNC.

the class Tunnel method isTunnelReady.

private static boolean isTunnelReady(int localPort) throws Exception {
    // test the local forwarding socket to make
    // sure the tunnel is up before connecting
    SocketAddress sockAddr = new InetSocketAddress("localhost", localPort);
    java.net.Socket socket = new java.net.Socket();
    boolean ready = false;
    try {
        socket.connect(sockAddr, 1000);
        ready = socket.isConnected();
        socket.close();
    } catch (IOException e) {
    // expected until tunnel is up
    } catch (java.lang.Exception e) {
        throw new Exception(e.getMessage());
    }
    return ready;
}
Also used : IOException(java.io.IOException) java.net(java.net) IOException(java.io.IOException) Exception(com.tigervnc.rfb.Exception) JSchException(com.jcraft.jsch.JSchException)

Example 4 with Exception

use of com.tigervnc.rfb.Exception in project tigervnc by TigerVNC.

the class Tunnel method fillCmdPattern.

private static String fillCmdPattern(String pattern, String gatewayHost, String remoteHost, int remotePort, int localPort) {
    boolean H_found = false, G_found = false, R_found = false, L_found = false;
    boolean P_found = false;
    String cmd = extSSHClient.getValue() + " ";
    pattern.replaceAll("^\\s+", "");
    String user = getSshUser();
    int sshPort = getSshPort();
    gatewayHost = user + "@" + gatewayHost;
    for (int i = 0; i < pattern.length(); i++) {
        if (pattern.charAt(i) == '%') {
            switch(pattern.charAt(++i)) {
                case 'H':
                    cmd += remoteHost;
                    H_found = true;
                    continue;
                case 'G':
                    cmd += gatewayHost;
                    G_found = true;
                    continue;
                case 'R':
                    cmd += remotePort;
                    R_found = true;
                    continue;
                case 'L':
                    cmd += localPort;
                    L_found = true;
                    continue;
                case 'P':
                    cmd += sshPort;
                    P_found = true;
                    continue;
            }
        }
        cmd += pattern.charAt(i);
    }
    if (pattern.length() > 1024)
        throw new Exception("Tunneling command is too long.");
    if (!H_found || !R_found || !L_found)
        throw new Exception("%H, %R or %L absent in tunneling command template.");
    if (!tunnel.getValue() && !G_found)
        throw new Exception("%G pattern absent in tunneling command template.");
    vlog.info("SSH command line: " + cmd);
    if (VncViewer.os.startsWith("windows"))
        cmd.replaceAll("\\\\", "\\\\\\\\");
    return cmd;
}
Also used : IOException(java.io.IOException) Exception(com.tigervnc.rfb.Exception) JSchException(com.jcraft.jsch.JSchException)

Example 5 with Exception

use of com.tigervnc.rfb.Exception in project tigervnc by TigerVNC.

the class Tunnel method createTunnelJSch.

private static void createTunnelJSch(String gatewayHost, String remoteHost, int remotePort, int localPort) throws Exception {
    JSch.setLogger(new MyJSchLogger());
    JSch jsch = new JSch();
    try {
        // NOTE: jsch does not support all ciphers.  User may be
        // prompted to accept host key authenticy even if
        // the key is in the known_hosts file.
        File knownHosts = new File(FileUtils.getHomeDir() + ".ssh" + FileUtils.getFileSeparator() + "known_hosts");
        if (knownHosts.exists() && knownHosts.canRead())
            jsch.setKnownHosts(knownHosts.getAbsolutePath());
        ArrayList<File> privateKeys = new ArrayList<File>();
        if (!getSshKey().isEmpty()) {
            byte[] keyPass = null, key;
            if (!sshKeyPass.getValue().isEmpty())
                keyPass = sshKeyPass.getValue().getBytes();
            jsch.addIdentity("TigerVNC", getSshKey().getBytes(), null, keyPass);
        } else if (!getSshKeyFile().isEmpty()) {
            File f = new File(getSshKeyFile());
            if (!f.exists() || !f.canRead())
                throw new Exception("Cannot access SSH key file " + getSshKeyFile());
            privateKeys.add(f);
        }
        for (Iterator<File> i = privateKeys.iterator(); i.hasNext(); ) {
            File privateKey = (File) i.next();
            if (privateKey.exists() && privateKey.canRead())
                if (!sshKeyPass.getValue().isEmpty())
                    jsch.addIdentity(privateKey.getAbsolutePath(), sshKeyPass.getValue());
                else
                    jsch.addIdentity(privateKey.getAbsolutePath());
        }
        String user = getSshUser();
        String label = new String("SSH Authentication");
        PasswdDialog dlg = new PasswdDialog(label, (user == null ? false : true), false);
        dlg.userEntry.setText(user != null ? user : "");
        File ssh_config = new File(sshConfig.getValue());
        if (ssh_config.exists() && ssh_config.canRead()) {
            ConfigRepository repo = OpenSSHConfig.parse(ssh_config.getAbsolutePath());
            jsch.setConfigRepository(repo);
        }
        Session session = jsch.getSession(user, gatewayHost, getSshPort());
        session.setUserInfo(dlg);
        // OpenSSHConfig doesn't recognize StrictHostKeyChecking
        if (session.getConfig("StrictHostKeyChecking") == null)
            session.setConfig("StrictHostKeyChecking", "ask");
        session.connect();
        if (gatewayHost.equals(remoteHost))
            session.setPortForwardingL(localPort, new String("localhost"), remotePort);
        else
            session.setPortForwardingL(localPort, remoteHost, remotePort);
    } catch (java.lang.Exception e) {
        throw new Exception(e.getMessage());
    }
}
Also used : ConfigRepository(com.jcraft.jsch.ConfigRepository) JSch(com.jcraft.jsch.JSch) IOException(java.io.IOException) Exception(com.tigervnc.rfb.Exception) JSchException(com.jcraft.jsch.JSchException) File(java.io.File) Session(com.jcraft.jsch.Session)

Aggregations

Exception (com.tigervnc.rfb.Exception)10 IOException (java.io.IOException)9 FileNotFoundException (java.io.FileNotFoundException)5 JSchException (com.jcraft.jsch.JSchException)4 File (java.io.File)3 Point (com.tigervnc.rfb.Point)2 SocketException (java.net.SocketException)2 ConfigRepository (com.jcraft.jsch.ConfigRepository)1 JSch (com.jcraft.jsch.JSch)1 Session (com.jcraft.jsch.Session)1 TcpSocket (com.tigervnc.network.TcpSocket)1 FileInputStream (java.io.FileInputStream)1 FileReader (java.io.FileReader)1 InputStream (java.io.InputStream)1 LineNumberReader (java.io.LineNumberReader)1 PrintWriter (java.io.PrintWriter)1 java.net (java.net)1 JOptionPane (javax.swing.JOptionPane)1