+static void telnet_history_go(struct connection *connection, int idx)
+{
+ struct telnet_connection *t_con = connection->priv;
+
+ if (t_con->history[idx]) {
+ telnet_clear_line(connection, t_con);
+ t_con->line_size = strlen(t_con->history[idx]);
+ t_con->line_cursor = t_con->line_size;
+ memcpy(t_con->line, t_con->history[idx], t_con->line_size);
+ telnet_write(connection, t_con->line, t_con->line_size);
+ t_con->current_history = idx;
+ }
+ t_con->state = TELNET_STATE_DATA;
+}
+
+static void telnet_history_up(struct connection *connection)
+{
+ struct telnet_connection *t_con = connection->priv;
+
+ size_t last_history = (t_con->current_history > 0) ?
+ t_con->current_history - 1 :
+ TELNET_LINE_HISTORY_SIZE-1;
+ telnet_history_go(connection, last_history);
+}
+
+static void telnet_history_down(struct connection *connection)
+{
+ struct telnet_connection *t_con = connection->priv;
+ size_t next_history;
+
+ next_history = (t_con->current_history + 1) % TELNET_LINE_HISTORY_SIZE;
+ telnet_history_go(connection, next_history);
+}
+
+static int telnet_history_print(struct connection *connection)
+{
+ struct telnet_connection *tc;
+
+ tc = connection->priv;
+
+ for (size_t i = 1; i < TELNET_LINE_HISTORY_SIZE; i++) {
+ char *line;
+
+ /*
+ * The tc->next_history line contains empty string (unless NULL), thus
+ * it is not printed.
+ */
+ line = tc->history[(tc->next_history + i) % TELNET_LINE_HISTORY_SIZE];
+
+ if (line) {
+ telnet_write(connection, line, strlen(line));
+ telnet_write(connection, "\r\n\x00", 3);
+ }
+ }
+
+ tc->line_size = 0;
+ tc->line_cursor = 0;
+
+ /* The prompt is always placed at the line beginning. */
+ telnet_write(connection, "\r", 1);
+
+ return telnet_prompt(connection);
+}
+
+static void telnet_move_cursor(struct connection *connection, size_t pos)
+{
+ struct telnet_connection *tc;
+ size_t tmp;
+
+ tc = connection->priv;
+
+ if (pos < tc->line_cursor) {
+ tmp = tc->line_cursor - pos;
+
+ for (size_t i = 0; i < tmp; i += 16)
+ telnet_write(connection, "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
+ MIN(tmp - i, 16));
+ } else {
+ tmp = pos - tc->line_cursor;
+
+ for (size_t i = 0; i < tmp; i += 16)
+ telnet_write(connection, tc->line + tc->line_cursor + i,
+ MIN(tmp - i, 16));
+ }
+
+ tc->line_cursor = pos;
+}
+
+static int telnet_input(struct connection *connection)