Search in sources :

Example 16 with Terminal

use of org.jline.terminal.Terminal in project jPOS by jpos.

the class CLI method buildTerminal.

private Terminal buildTerminal(InputStream in, OutputStream out) throws IOException {
    TerminalBuilder builder = TerminalBuilder.builder();
    builder.streams(in, out).system(System.in == in);
    Terminal t = builder.build();
    Attributes attr = t.getAttributes();
    attr.getOutputFlags().addAll(EnumSet.of(Attributes.OutputFlag.ONLCR, Attributes.OutputFlag.OPOST));
    t.setAttributes(attr);
    return t;
}
Also used : Attributes(org.jline.terminal.Attributes) Terminal(org.jline.terminal.Terminal) TerminalBuilder(org.jline.terminal.TerminalBuilder)

Example 17 with Terminal

use of org.jline.terminal.Terminal in project Payara by payara.

the class LocalOSGiShellCommand method executeCommand.

@Override
protected int executeCommand() throws CommandException, CommandValidationException {
    LineReader reader = null;
    if (cmd == null) {
        throw new CommandException("Remote command 'osgi' is not available.");
    }
    // restore echo flag, saved in validate
    programOpts.setEcho(echo);
    try {
        if (encoding != null) {
            // see Configuration.getEncoding()...
            System.setProperty("input.encoding", encoding);
        }
        String[] args = new String[] { REMOTE_COMMAND, "asadmin-osgi-shell" };
        args = enhanceForTarget(args);
        shellType = cmd.executeAndReturnOutput(args).trim();
        if (file == null) {
            if (terminal != null) {
                // Pause the asadmin terminal
                terminal.pause();
            }
            System.out.println(strings.get("multimodeIntro"));
            Terminal osgiShellTerminal = TerminalBuilder.builder().name(REMOTE_COMMAND).system(true).streams(new FileInputStream(FileDescriptor.in), System.out).build();
            reader = LineReaderBuilder.builder().appName(REMOTE_COMMAND).terminal(osgiShellTerminal).completer(getCommandCompleter()).build();
            reader.unsetOpt(LineReader.Option.INSERT_TAB);
            return executeCommands(reader);
        }
        printPrompt = false;
        if (!file.canRead()) {
            throw new CommandException("File: " + file + " can not be read");
        }
        try (Terminal osgiShellTerminal = new ExternalTerminal(REMOTE_COMMAND, "", new FileInputStream(file), new NullOutputStream(), encoding != null ? Charset.forName(encoding) : Charset.defaultCharset())) {
            reader = LineReaderBuilder.builder().terminal(osgiShellTerminal).appName(REMOTE_COMMAND).build();
            // NB: wrapper on general in/out stream does not need closing by try-with-resource
            return executeCommands(reader);
        }
    } catch (IOException e) {
        throw new CommandException(e);
    } finally {
        if (reader != null && reader.getTerminal() != null) {
            try {
                reader.getTerminal().close();
            } catch (IOException ioe) {
                logger.log(Level.WARNING, "Error closing OSFI Shell terminal", ioe);
            }
        }
    }
}
Also used : LineReader(org.jline.reader.LineReader) ExternalTerminal(org.jline.terminal.impl.ExternalTerminal) InvalidCommandException(org.glassfish.api.admin.InvalidCommandException) CommandException(org.glassfish.api.admin.CommandException) ExternalTerminal(org.jline.terminal.impl.ExternalTerminal) Terminal(org.jline.terminal.Terminal)

Example 18 with Terminal

use of org.jline.terminal.Terminal in project karaf by apache.

the class WatchAction method execute.

@Override
public Object execute() throws Exception {
    if (arguments == null || arguments.length() == 0) {
        System.err.println("Argument expected");
    } else {
        WatchTask watchTask = new WatchTask();
        executorService.scheduleAtFixedRate(watchTask, 0, interval, TimeUnit.SECONDS);
        try {
            Terminal terminal = (Terminal) session.get(".jline.terminal");
            Terminal.SignalHandler prev = terminal.handle(Terminal.Signal.INT, this::abort);
            Attributes attr = terminal.enterRawMode();
            try {
                reading = Thread.currentThread();
                while (terminal.reader().read(1) == NonBlockingReader.READ_EXPIRED) ;
            } finally {
                reading = null;
                terminal.setAttributes(attr);
                terminal.handle(Terminal.Signal.INT, prev);
            }
        } catch (InterruptedIOException e) {
        // Ignore
        } finally {
            abort = true;
            executorService.shutdownNow();
        }
    }
    return null;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) Attributes(org.jline.terminal.Attributes) Terminal(org.jline.terminal.Terminal)

Example 19 with Terminal

use of org.jline.terminal.Terminal in project karaf by apache.

the class Main method main.

public static void main(String[] args) throws Exception {
    ClientConfig config = new ClientConfig(args);
    SimpleLogger.setLevel(config.getLevel());
    if (config.getFile() != null) {
        StringBuilder sb = new StringBuilder();
        sb.setLength(0);
        try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(config.getFile())))) {
            for (int c = reader.read(); c >= 0; c = reader.read()) {
                sb.append((char) c);
            }
        }
        config.setCommand(sb.toString());
    } else if (config.isBatch()) {
        StringBuilder sb = new StringBuilder();
        sb.setLength(0);
        Reader reader = new BufferedReader(new InputStreamReader(System.in));
        for (int c = reader.read(); c >= 0; c = reader.read()) {
            sb.append((char) c);
        }
        config.setCommand(sb.toString());
    }
    try (SshClient client = ClientBuilder.builder().build()) {
        FilePasswordProvider passwordProvider = null;
        final Console console = System.console();
        if (console != null) {
            passwordProvider = (session, resourceKey, retryIndex) -> {
                char[] pwd = console.readPassword("Enter password for " + resourceKey + ": ");
                return new String(pwd);
            };
            client.setFilePasswordProvider(passwordProvider);
            client.setUserInteraction(new UserInteraction() {

                @Override
                public void welcome(ClientSession s, String banner, String lang) {
                    System.out.println(banner);
                }

                @Override
                public String[] interactive(ClientSession s, String name, String instruction, String lang, String[] prompt, boolean[] echo) {
                    String[] answers = new String[prompt.length];
                    try {
                        for (int i = 0; i < prompt.length; i++) {
                            if (echo[i]) {
                                answers[i] = console.readLine(prompt[i] + " ");
                            } else {
                                answers[i] = new String(console.readPassword(prompt[i] + " "));
                            }
                            if (answers[i] == null) {
                                return null;
                            }
                        }
                        return answers;
                    } catch (IOError e) {
                        return null;
                    }
                }

                @Override
                public boolean isInteractionAllowed(ClientSession session) {
                    return true;
                }

                @Override
                public void serverVersionInfo(ClientSession session, List<String> lines) {
                }

                @Override
                public String getUpdatedPassword(ClientSession session, String prompt, String lang) {
                    return null;
                }
            });
        }
        if (config.getUser() == null || config.getUser().isEmpty()) {
            while (true) {
                String user = console.readLine("Enter user: ");
                if (user == null || user.isEmpty()) {
                    System.err.println("User must not be empty!");
                } else {
                    config.setUser(user);
                    break;
                }
            }
        } else if (console != null) {
            console.printf("Logging in as %s\n", config.getUser());
        }
        setupAgent(config.getUser(), config.getKeyFile(), client, passwordProvider);
        // define hearbeat (for the keep alive) and timeouts
        // TODO this should be dealt by Apache SSH client directly using .ssh/config
        CoreModuleProperties.HEARTBEAT_INTERVAL.set(client, Duration.ofMillis(60000));
        CoreModuleProperties.IDLE_TIMEOUT.set(client, Duration.ofMillis(config.getIdleTimeout()));
        CoreModuleProperties.NIO2_READ_TIMEOUT.set(client, Duration.ofMillis(config.getIdleTimeout()));
        // TODO: remove the line below when SSHD-732 is fixed
        // client.setKeyPairProvider(new FileKeyPairProvider());
        client.start();
        ClientSession session = connectWithRetries(client, config);
        if (config.getPassword() != null) {
            session.addPasswordIdentity(config.getPassword());
        }
        session.auth().verify();
        int exitStatus = 0;
        String type = System.getProperty(TerminalBuilder.PROP_TYPE);
        if (type == null) {
            type = System.getenv("TERM");
        }
        if (type == null) {
            type = Terminal.TYPE_DUMB;
        }
        try (Terminal terminal = TerminalBuilder.builder().nativeSignals(true).type(type).signalHandler(Terminal.SignalHandler.SIG_IGN).build()) {
            if (config.getCommand().length() > 0) {
                ChannelExec channel = session.createExecChannel(config.getCommand() + "\n");
                channel.setIn(new ByteArrayInputStream(new byte[0]));
                if (!config.isBatch()) {
                    new Thread(() -> {
                        while (true) {
                            try {
                                int a = System.in.read();
                                if (a == -1) {
                                    channel.close(true);
                                    break;
                                }
                                Thread.sleep(1000);
                            } catch (Exception e) {
                            // ignore
                            }
                        }
                    }).start();
                }
                channel.setAgentForwarding(true);
                NoCloseOutputStream output = new NoCloseOutputStream(terminal.output());
                channel.setOut(output);
                channel.setErr(output);
                channel.open().verify();
                channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
                if (channel.getExitStatus() != null) {
                    exitStatus = channel.getExitStatus();
                }
            } else {
                ChannelShell channel = session.createShellChannel();
                Attributes attributes = terminal.enterRawMode();
                try {
                    Map<PtyMode, Integer> modes = new HashMap<>();
                    // Control chars
                    modes.put(PtyMode.VINTR, attributes.getControlChar(ControlChar.VINTR));
                    modes.put(PtyMode.VQUIT, attributes.getControlChar(ControlChar.VQUIT));
                    modes.put(PtyMode.VERASE, attributes.getControlChar(ControlChar.VERASE));
                    modes.put(PtyMode.VKILL, attributes.getControlChar(ControlChar.VKILL));
                    modes.put(PtyMode.VEOF, attributes.getControlChar(ControlChar.VEOF));
                    modes.put(PtyMode.VEOL, attributes.getControlChar(ControlChar.VEOL));
                    modes.put(PtyMode.VEOL2, attributes.getControlChar(ControlChar.VEOL2));
                    modes.put(PtyMode.VSTART, attributes.getControlChar(ControlChar.VSTART));
                    modes.put(PtyMode.VSTOP, attributes.getControlChar(ControlChar.VSTOP));
                    modes.put(PtyMode.VSUSP, attributes.getControlChar(ControlChar.VSUSP));
                    modes.put(PtyMode.VDSUSP, attributes.getControlChar(ControlChar.VDSUSP));
                    modes.put(PtyMode.VREPRINT, attributes.getControlChar(ControlChar.VREPRINT));
                    modes.put(PtyMode.VWERASE, attributes.getControlChar(ControlChar.VWERASE));
                    modes.put(PtyMode.VLNEXT, attributes.getControlChar(ControlChar.VLNEXT));
                    modes.put(PtyMode.VSTATUS, attributes.getControlChar(ControlChar.VSTATUS));
                    modes.put(PtyMode.VDISCARD, attributes.getControlChar(ControlChar.VDISCARD));
                    // Input flags
                    modes.put(PtyMode.IGNPAR, getFlag(attributes, InputFlag.IGNPAR));
                    modes.put(PtyMode.PARMRK, getFlag(attributes, InputFlag.PARMRK));
                    modes.put(PtyMode.INPCK, getFlag(attributes, InputFlag.INPCK));
                    modes.put(PtyMode.ISTRIP, getFlag(attributes, InputFlag.ISTRIP));
                    modes.put(PtyMode.INLCR, getFlag(attributes, InputFlag.INLCR));
                    modes.put(PtyMode.IGNCR, getFlag(attributes, InputFlag.IGNCR));
                    modes.put(PtyMode.ICRNL, getFlag(attributes, InputFlag.ICRNL));
                    modes.put(PtyMode.IXON, getFlag(attributes, InputFlag.IXON));
                    modes.put(PtyMode.IXANY, getFlag(attributes, InputFlag.IXANY));
                    modes.put(PtyMode.IXOFF, getFlag(attributes, InputFlag.IXOFF));
                    // Local flags
                    modes.put(PtyMode.ISIG, getFlag(attributes, LocalFlag.ISIG));
                    modes.put(PtyMode.ICANON, getFlag(attributes, LocalFlag.ICANON));
                    modes.put(PtyMode.ECHO, getFlag(attributes, LocalFlag.ECHO));
                    modes.put(PtyMode.ECHOE, getFlag(attributes, LocalFlag.ECHOE));
                    modes.put(PtyMode.ECHOK, getFlag(attributes, LocalFlag.ECHOK));
                    modes.put(PtyMode.ECHONL, getFlag(attributes, LocalFlag.ECHONL));
                    modes.put(PtyMode.NOFLSH, getFlag(attributes, LocalFlag.NOFLSH));
                    modes.put(PtyMode.TOSTOP, getFlag(attributes, LocalFlag.TOSTOP));
                    modes.put(PtyMode.IEXTEN, getFlag(attributes, LocalFlag.IEXTEN));
                    // Output flags
                    modes.put(PtyMode.OPOST, getFlag(attributes, OutputFlag.OPOST));
                    modes.put(PtyMode.ONLCR, getFlag(attributes, OutputFlag.ONLCR));
                    modes.put(PtyMode.OCRNL, getFlag(attributes, OutputFlag.OCRNL));
                    modes.put(PtyMode.ONOCR, getFlag(attributes, OutputFlag.ONOCR));
                    modes.put(PtyMode.ONLRET, getFlag(attributes, OutputFlag.ONLRET));
                    channel.setPtyModes(modes);
                    channel.setPtyColumns(terminal.getWidth());
                    channel.setPtyLines(terminal.getHeight());
                    channel.setAgentForwarding(true);
                    channel.setEnv("TERM", terminal.getType());
                    String ctype = System.getenv("LC_CTYPE");
                    if (ctype == null) {
                        ctype = Locale.getDefault().toString() + "." + System.getProperty("input.encoding", Charset.defaultCharset().name());
                    }
                    channel.setEnv("LC_CTYPE", ctype);
                    channel.setIn(new NoCloseInputStream(terminal.input()));
                    channel.setOut(new NoCloseOutputStream(terminal.output()));
                    channel.setErr(new NoCloseOutputStream(terminal.output()));
                    channel.open().verify();
                    Terminal.SignalHandler prevWinchHandler = terminal.handle(Terminal.Signal.WINCH, signal -> {
                        try {
                            Size size = terminal.getSize();
                            channel.sendWindowChange(size.getColumns(), size.getRows());
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    Terminal.SignalHandler prevQuitHandler = terminal.handle(Terminal.Signal.QUIT, signal -> {
                        try {
                            channel.getInvertedIn().write(attributes.getControlChar(Attributes.ControlChar.VQUIT));
                            channel.getInvertedIn().flush();
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    Terminal.SignalHandler prevIntHandler = terminal.handle(Terminal.Signal.INT, signal -> {
                        try {
                            channel.getInvertedIn().write(attributes.getControlChar(Attributes.ControlChar.VINTR));
                            channel.getInvertedIn().flush();
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    Terminal.SignalHandler prevStopHandler = terminal.handle(Terminal.Signal.TSTP, signal -> {
                        try {
                            channel.getInvertedIn().write(attributes.getControlChar(Attributes.ControlChar.VDSUSP));
                            channel.getInvertedIn().flush();
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    try {
                        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
                    } finally {
                        terminal.handle(Terminal.Signal.WINCH, prevWinchHandler);
                        terminal.handle(Terminal.Signal.INT, prevIntHandler);
                        terminal.handle(Terminal.Signal.TSTP, prevStopHandler);
                        terminal.handle(Terminal.Signal.QUIT, prevQuitHandler);
                    }
                    if (channel.getExitStatus() != null) {
                        exitStatus = channel.getExitStatus();
                    }
                } finally {
                    terminal.setAttributes(attributes);
                }
            }
        }
        System.exit(exitStatus);
    } catch (Throwable t) {
        if (config.getLevel() > SimpleLogger.WARN) {
            t.printStackTrace();
        } else {
            System.err.println(t.getMessage());
        }
        System.exit(1);
    }
}
Also used : SshClient(org.apache.sshd.client.SshClient) HashMap(java.util.HashMap) Size(org.jline.terminal.Size) Attributes(org.jline.terminal.Attributes) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) ChannelShell(org.apache.sshd.client.channel.ChannelShell) ClientSession(org.apache.sshd.client.session.ClientSession) Console(java.io.Console) InputStreamReader(java.io.InputStreamReader) PtyMode(org.apache.sshd.common.channel.PtyMode) IOException(java.io.IOException) Terminal(org.jline.terminal.Terminal) FileInputStream(java.io.FileInputStream) ChannelExec(org.apache.sshd.client.channel.ChannelExec) RuntimeSshException(org.apache.sshd.common.RuntimeSshException) IOException(java.io.IOException) NoCloseInputStream(org.apache.sshd.common.util.io.input.NoCloseInputStream) IOError(java.io.IOError) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) UserInteraction(org.apache.sshd.client.auth.keyboard.UserInteraction) FilePasswordProvider(org.apache.sshd.common.config.keys.FilePasswordProvider) NoCloseOutputStream(org.apache.sshd.common.util.io.output.NoCloseOutputStream)

Example 20 with Terminal

use of org.jline.terminal.Terminal in project karaf by apache.

the class LocalConsoleManager method start.

public void start() throws Exception {
    final Terminal terminal = TerminalBuilder.builder().nativeSignals(true).signalHandler(Terminal.SignalHandler.SIG_IGN).build();
    final Subject subject = createLocalKarafSubject();
    this.session = JaasHelper.doAs(subject, (PrivilegedAction<Session>) () -> {
        String encoding = getEncoding();
        PrintStream pout = new PrintStream(terminal.output()) {

            @Override
            public void close() {
            // do nothing
            }
        };
        session = sessionFactory.create(terminal.input(), pout, pout, new JLineTerminal(terminal), encoding, LocalConsoleManager.this::close);
        session.put(Session.IS_LOCAL, true);
        registration = bundleContext.registerService(Session.class, session, null);
        String name = "Karaf local console user " + ShellUtil.getCurrentUserName();
        boolean delayconsole = Boolean.parseBoolean(System.getProperty(KARAF_DELAY_CONSOLE));
        if (delayconsole) {
            watcher = new DelayedStarted(session, name, bundleContext, System.in);
            new Thread(watcher, name).start();
        } else {
            new Thread(session, name).start();
        }
        return session;
    });
// TODO: register the local session so that ssh can add the agent
// registration = bundleContext.register(CommandSession.class, console.getSession(), null);
}
Also used : JLineTerminal(org.apache.karaf.shell.impl.console.JLineTerminal) PrintStream(java.io.PrintStream) PrivilegedAction(java.security.PrivilegedAction) JLineTerminal(org.apache.karaf.shell.impl.console.JLineTerminal) Terminal(org.jline.terminal.Terminal) Subject(javax.security.auth.Subject) Session(org.apache.karaf.shell.api.console.Session)

Aggregations

Terminal (org.jline.terminal.Terminal)39 LineReader (org.jline.reader.LineReader)14 IOException (java.io.IOException)13 InputStream (java.io.InputStream)8 EndOfFileException (org.jline.reader.EndOfFileException)8 UserInterruptException (org.jline.reader.UserInterruptException)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 Attributes (org.jline.terminal.Attributes)7 PrintStream (java.io.PrintStream)6 Path (java.nio.file.Path)6 CommandSession (org.apache.felix.service.command.CommandSession)6 OutputStream (java.io.OutputStream)5 ArrayList (java.util.ArrayList)5 InputStreamReader (java.io.InputStreamReader)4 Reader (java.io.Reader)4 ParsedLine (org.jline.reader.ParsedLine)4 BufferedReader (java.io.BufferedReader)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3