/* SPDX-License-Identifier: GPL-2.0 */ /** \file interactive.c Readline abstraction for interactive sessions. */ #include "para.h" #include #include #include #include #include "fd.h" #include "buffer_tree.h" #include "list.h" #include "sched.h" #include "interactive.h" #include "string.h" #include "error.h" struct i9e_private { struct i9e_client_info *ici; FILE *stderr_stream; int num_columns; int num_key_bindings; char empty_line[1000]; char key_sequence[32]; unsigned key_sequence_length; struct task *task; struct btr_node *stdout_btrn; bool last_write_was_status; bool input_eof; bool caught_sigint; bool caught_sigterm; Keymap standard_km; Keymap bare_km; int fd_flags[2]; }; static struct i9e_private i9e_private, *i9ep = &i9e_private; /** * Return the error state of the i9e task. * * This is mainly useful for other tasks to tell whether the i9e task is still * running. * * \return A negative return value of zero means the i9e task terminated. Only * in this case it is safe to call i9e_close(). */ int i9e_get_error(void) { return task_status(i9ep->task); } static bool is_prefix(const char *partial, const char *full, size_t len) { if (len == 0) len = strlen(partial); return !strncmp(partial, full, len); } /* * Generator function for command completion. STATE lets us know whether * to start from scratch; without any state (i.e. STATE == 0), then we * start at the top of the list. */ static char *command_generator(const char *text, int state) { static int list_index, len; const char *name; struct i9e_client_info *ici = i9ep->ici; rl_attempted_completion_over = 1; /* disable filename completion */ /* * If this is a new word to complete, initialize now. This includes * saving the length of TEXT for efficiency, and initializing the index * variable to 0. */ if (state == 0) { list_index = 0; len = strlen(text); } /* Return the next name which partially matches from the command list. */ while ((name = ici->completers[list_index].name)) { list_index++; if (is_prefix(text, name, len)) return para_strdup(name); } return NULL; /* no names matched */ } static void reset_completion_result(struct i9e_completion_result *cr) { cr->dont_append_space = false; cr->filename_completion_desired = false; cr->matches = NULL; } static void create_matches(struct i9e_completion_info *ci, const struct i9e_completer *completers, struct i9e_completion_result *cr) { int i, ret; reset_completion_result(cr); ret = create_argv(ci->buffer, " ", &ci->argv); if (ret < 0 || !ci->argv[0]) return; ci->argc = ret; ci->word_num = compute_word_num(ci->buffer, " ", ci->point); for (i = 0; completers[i].name; i++) { if (strcmp(completers[i].name, ci->argv[0]) != 0) continue; completers[i].completer(ci, cr); break; } PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num, ci->argv[ci->word_num]); if (cr->matches) for (i = 0; cr->matches[i]; i++) PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]); } static char *completion_generator(const char *word, int state) { static int list_index; static char **argv, **matches; const struct i9e_completer *completers = i9ep->ici->completers; struct i9e_completion_info ci = { .word = (char *)word, .point = rl_point, .buffer = rl_line_buffer, }; struct i9e_completion_result cr = {.matches = NULL}; if (state != 0) goto out; /* clean up previous matches and set defaults */ free(matches); matches = NULL; free_argv(argv); argv = NULL; list_index = 0; rl_completion_append_character = ' '; rl_completion_suppress_append = false; rl_attempted_completion_over = true; create_matches(&ci, completers, &cr); matches = cr.matches; argv = ci.argv; rl_completion_suppress_append = cr.dont_append_space; rl_attempted_completion_over = !cr.filename_completion_desired; out: if (!matches) return NULL; return matches[list_index++]; } /** * Prepare writing to stdout. * * \param producer The buffer tree node which produces output. * * The i9e subsystem maintains a buffer tree node which may be attached to * another node which generates output (a "producer"). When attached, the i9e * buffer tree node copies the buffers generated by the producer to stdout. * This function attaches the i9e input queue to an output queue of producer. */ void i9e_attach_to_stdout(struct btr_node *producer) { btr_remove_node(&i9ep->stdout_btrn); i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description) EMBRACE(.name = "interactive_stdout", .parent = producer)); rl_set_keymap(i9ep->bare_km); } static void wipe_bottom_line(void) { fprintf(i9ep->stderr_stream, "\r%s\r", i9ep->empty_line); } #ifndef RL_FREE_KEYMAP_DECLARED /** * Free all storage associated with a keymap. * * This function is not declared in the readline headers although the symbol is * exported and the function is documented in the readline info file. So we * have to declare it here. * * \param keymap The keymap to deallocate. */ void rl_free_keymap(Keymap keymap); #endif /** * Reset the terminal and save the in-memory command line history. * * This should be called before the caller exits. */ void i9e_close(void) { char *hf = i9ep->ici->history_file; rl_free_keymap(i9ep->bare_km); rl_callback_handler_remove(); if (hf) write_history(hf); clear_history(); wipe_bottom_line(); fcntl(i9ep->ici->fds[0], F_SETFL, i9ep->fd_flags[0]); fcntl(i9ep->ici->fds[1], F_SETFL, i9ep->fd_flags[1]); } static void clear_bottom_line(void) { int point; char *text; if (rl_point == 0 && rl_end == 0) return wipe_bottom_line(); /* * We might have a multi-line input that needs to be wiped here, so the * simple printf("\r\r") is insufficient. To workaround this, we * remove the whole line, redisplay and restore the killed text. */ point = rl_point; text = rl_copy_text(0, rl_end); rl_kill_full_line(0, 0); rl_redisplay(); wipe_bottom_line(); /* wipe out the prompt */ rl_insert_text(text); free(text); rl_point = point; } static void i9e_line_handler(char *line) { int ret; struct btr_node *dummy; if (!line) { i9ep->input_eof = true; return; } if (!*line) goto free_line; rl_set_prompt(""); dummy = btr_new_node(&(struct btr_node_description) EMBRACE(.name = "dummy line handler")); i9e_attach_to_stdout(dummy); ret = i9ep->ici->line_handler(line); if (ret < 0) PARA_WARNING_LOG("%s\n", para_strerror(-ret)); add_history(line); btr_remove_node(&dummy); free_line: free(line); } static int i9e_post_monitor(__a_unused struct sched *s, __a_unused void *context) { int ret; struct i9e_client_info *ici = i9ep->ici; char *buf; size_t sz, consumed = 0; ret = -E_EOF; if (i9ep->input_eof) goto rm_btrn; ret = -E_I9E_TERM_RQ; if (i9ep->caught_sigterm) goto rm_btrn; ret = 0; if (i9ep->caught_sigint) goto rm_btrn; while (read_ok(i9ep->ici->fds[0]) > 0) { if (i9ep->stdout_btrn) { while (i9ep->key_sequence_length < sizeof(i9ep->key_sequence) - 1) { buf = i9ep->key_sequence + i9ep->key_sequence_length; ret = read(i9ep->ici->fds[0], buf, 1); if (ret < 0) { ret = -ERRNO_TO_PARA_ERROR(errno); goto rm_btrn; } if (ret == 0) { ret = -E_EOF; goto rm_btrn; } buf[1] = '\0'; i9ep->key_sequence_length++; rl_stuff_char((int)(unsigned char)*buf); rl_callback_read_char(); if (read_ok(i9ep->ici->fds[0]) <= 0) break; } i9ep->key_sequence_length = 0; } else rl_callback_read_char(); ret = 0; } if (!i9ep->stdout_btrn) goto out; ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF); if (ret < 0) { ret = 0; goto rm_btrn; } if (ret == 0) goto out; again: sz = btr_next_buffer(i9ep->stdout_btrn, &buf); if (sz == 0) goto out; if (i9ep->last_write_was_status) fprintf(i9ep->stderr_stream, "\n"); i9ep->last_write_was_status = false; ret = xwrite(ici->fds[1], buf, sz); if (ret < 0) goto rm_btrn; btr_consume(i9ep->stdout_btrn, ret); consumed += ret; if (ret == sz && consumed < 10000) goto again; goto out; rm_btrn: if (i9ep->stdout_btrn) { wipe_bottom_line(); btr_remove_node(&i9ep->stdout_btrn); rl_set_keymap(i9ep->standard_km); rl_set_prompt(i9ep->ici->prompt); rl_redisplay(); } if (ret < 0) wipe_bottom_line(); out: i9ep->caught_sigint = false; return ret; } static void i9e_pre_monitor(struct sched *s, __a_unused void *context) { int ret; if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) { sched_min_delay(s); return; } if (i9ep->stdout_btrn) { ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF); if (ret < 0) { sched_min_delay(s); return; } if (ret > 0) sched_monitor_writefd(i9ep->ici->fds[1], s); } /* * fd[0] might have been reset to blocking mode if our job was moved to * the background due to CTRL-Z or SIGSTOP, so set the fd back to * nonblocking mode. */ ret = mark_fd_nonblocking(i9ep->ici->fds[0]); if (ret < 0) PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n", i9ep->ici->fds[0], para_strerror(-ret)); sched_monitor_readfd(i9ep->ici->fds[0], s); } static void update_winsize(void) { struct winsize w; int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w); if (ret >= 0) { assert(w.ws_col < sizeof(i9ep->empty_line)); i9ep->num_columns = w.ws_col; } else i9ep->num_columns = 80; memset(i9ep->empty_line, ' ', i9ep->num_columns); i9ep->empty_line[i9ep->num_columns] = '\0'; } static int dispatch_key(__a_unused int count, __a_unused int key) { int i, ret; again: if (i9ep->key_sequence_length == 0) return 0; for (i = i9ep->num_key_bindings - 1; i >= 0; i--) { if (strcmp(i9ep->key_sequence, i9ep->ici->bound_keyseqs[i])) continue; i9ep->key_sequence[0] = '\0'; i9ep->key_sequence_length = 0; ret = i9ep->ici->key_handler(i); return ret < 0? ret : 0; } PARA_WARNING_LOG("ignoring key %d\n", i9ep->key_sequence[0]); /* * We received an undefined key sequence. Throw away the first byte, * and try to parse the remainder. */ memmove(i9ep->key_sequence, i9ep->key_sequence + 1, i9ep->key_sequence_length); /* move also terminating zero byte */ i9ep->key_sequence_length--; goto again; } /* * Calls either command_generator() or completion_generator() via * rl_completion_matches(). May set rl_attempted_completion_over to instruct * readline to not perform its default completion even if no matches are * returned. */ static char **attempt_completion(const char *text, int start, __a_unused int end) { struct i9e_client_info *ici = i9ep->ici; if (!ici->completers) return NULL; /* Complete on command names if this is the first word in the line. */ if (start == 0) return rl_completion_matches(text, command_generator); return rl_completion_matches(text, completion_generator); } /** * Register the i9e task and initialize readline. * * \param ici The i9e configuration parameters set by the caller. * \param s The scheduler instance to add the i9e task to. * * The i9e client info structure must be allocated and initialized by the * caller before this function is called. * * \return Standard. */ int i9e_open(struct i9e_client_info *ici, struct sched *s) { int ret; memset(i9ep, 0, sizeof(struct i9e_private)); if (!isatty(ici->fds[0])) return -E_I9E_SETUPTERM; ret = fcntl(ici->fds[0], F_GETFL); if (ret < 0) return -E_I9E_SETUPTERM; i9ep->fd_flags[0] = ret; ret = fcntl(ici->fds[1], F_GETFL); if (ret < 0) return -E_I9E_SETUPTERM; i9ep->fd_flags[1] = ret; ret = mark_fd_nonblocking(ici->fds[0]); if (ret < 0) return ret; ret = mark_fd_nonblocking(ici->fds[1]); if (ret < 0) return ret; i9ep->task = task_register(&(struct task_info) { .name = "i9e", .pre_monitor = i9e_pre_monitor, .post_monitor = i9e_post_monitor, .context = i9ep, }, s); rl_readline_name = "para_i9e"; rl_basic_word_break_characters = " "; rl_attempted_completion_function = attempt_completion; i9ep->ici = ici; i9ep->stderr_stream = fdopen(ici->fds[2], "w"); setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0); i9ep->standard_km = rl_get_keymap(); i9ep->bare_km = rl_make_bare_keymap(); if (ici->bound_keyseqs) { char *seq; int i; /* bind each key sequence to our dispatcher */ for (i = 0; (seq = ici->bound_keyseqs[i]); i++) { if (strlen(seq) >= sizeof(i9ep->key_sequence) - 1) { PARA_WARNING_LOG("ignoring overlong key %s\n", seq); continue; } if (rl_bind_keyseq_in_map(seq, dispatch_key, i9ep->bare_km) != 0) PARA_WARNING_LOG("could not bind #%d: %s\n", i, seq); } i9ep->num_key_bindings = i; } if (ici->history_file) read_history(ici->history_file); update_winsize(); if (ici->producer) { rl_callback_handler_install("", i9e_line_handler); i9e_attach_to_stdout(ici->producer); } else rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler); return 1; } static void reset_line_state(void) { if (i9ep->stdout_btrn) return; rl_on_new_line(); rl_reset_line_state(); rl_forced_update_display(); } /** * The log function of the i9e subsystem. * * \param ll Severity log level. * \param fmt Printf-like format string. * * This clears the bottom line of the terminal if necessary and writes the * formatted string to fd[2], where fd[] is the array provided earlier in * \ref i9e_open(). */ __printf_2_3 void i9e_log(int ll, const char* fmt,...) { va_list argp; if (ll < i9ep->ici->loglevel) return; clear_bottom_line(); va_start(argp, fmt); vfprintf(i9ep->stderr_stream, fmt, argp); va_end(argp); reset_line_state(); i9ep->last_write_was_status = false; } /** * Print the current status to stderr. * * \param buf The text to print. * \param len The number of bytes in the buffer. * * This clears the bottom line, moves to the beginning of the line and prints * the given text. If the length of this text exceeds the width of the * terminal, the text is shortened by leaving out a part in the middle. */ void i9e_print_status_bar(char *buf, unsigned len) { size_t x = i9ep->num_columns, y = (x - 4) / 2; assert(x >= 6); if (len > x) { buf[y] = '\0'; fprintf(i9ep->stderr_stream, "\r%s", buf); fprintf(i9ep->stderr_stream, " .. "); fprintf(i9ep->stderr_stream, "%s", buf + len - y); } else { char scratch[1000]; y = x - len; scratch[0] = '\r'; strcpy(scratch + 1, buf); memset(scratch + 1 + len, ' ', y); scratch[1 + len + y] = '\r'; scratch[2 + len + y] = '\0'; fprintf(i9ep->stderr_stream, "\r%s", scratch); } i9ep->last_write_was_status = true; } /** * Tell i9e that the caller received a signal. * * \param sig_num The number of the signal received. */ void i9e_signal_dispatch(int sig_num) { if (sig_num == SIGWINCH) return update_winsize(); if (sig_num == SIGINT) { fprintf(i9ep->stderr_stream, "\n"); rl_replace_line ("", false /* clear_undo */); reset_line_state(); i9ep->caught_sigint = true; } if (sig_num == SIGTERM) i9ep->caught_sigterm = true; } /** * Wrapper for poll(2) which handles EINTR and returns paraslash error codes. * * \param fds See poll(2). * \param nfds See poll(2). * \param timeout See poll(2). * * \return See poll(2). * * The only difference between this function and \ref xpoll() is that \ref * i9e_poll() returns zero if the system call was interrupted while xpoll() * restarts the system call in this case. */ int i9e_poll(struct pollfd *fds, nfds_t nfds, int timeout) { int ret = poll(fds, nfds, timeout); if (ret < 0) { if (errno == EINTR) ret = 0; else ret = -ERRNO_TO_PARA_ERROR(errno); } return ret; } /** * Return the possible completions for a given word. * * \param word The word to complete. * \param string_list All possible words in this context. * \param result String list is returned here. * * This function never fails. If no completion was found, a string list of * length zero is returned. In any case, the result must be freed by the caller * using \ref free_argv(). * * This function is independent of readline and may be called before * i9e_open(). * * \return The number of possible completions. */ int i9e_extract_completions(const char *word, char * const *string_list, char ***result) { char **matches = alloc(sizeof(char *)); int match_count = 0, matches_len = 1; int len = strlen(word); for (char * const *p = string_list; *p; p++) { if (!is_prefix(word, *p, len)) continue; match_count++; if (match_count >= matches_len) { matches_len *= 2; matches = arr_realloc(matches, matches_len, sizeof(char *)); } matches[match_count - 1] = para_strdup(*p); } matches[match_count] = NULL; *result = matches; return match_count; } /** * Return the list of partially matching words. * * \param word The command to complete. * \param completers The array containing all command names. * * This is similar to \ref i9e_extract_completions(), but completes on the * command names in the completers array. * * \return See \ref i9e_extract_completions(). */ char **i9e_complete_commands(const char *word, const struct i9e_completer *completers) { char **matches; const char *cmd; int i, match_count, len = strlen(word); /* * In contrast to completing against an arbitrary string list, here we * know all possible completions and expect that there will not be many * of them. So it should be OK to iterate twice over all commands which * simplifies the code a bit. */ for (i = 0, match_count = 0; (cmd = completers[i].name); i++) { if (is_prefix(word, cmd, len)) match_count++; } matches = arr_alloc(match_count + 1, sizeof(*matches)); for (i = 0, match_count = 0; (cmd = completers[i].name); i++) if (is_prefix(word, cmd, len)) matches[match_count++] = para_strdup(cmd); matches[match_count] = NULL; return matches; } /** * Complete according to the given options. * * \param opts All available options. * \param ci Information which was passed to the completer. * \param cr Result pointer. * * This helper returns the possible tab-completions of an option. The * array of all possible options is passed as the first argument. Flags, * i.e. options without an argument, are expected as strings such as "-X" * while options which require an argument are expected to be of the form * "-X=", i.e., contain a trailing "=". * * If the word can be uniquely completed to a flag option, an additional space * character is appended to the output. For non-flag options no space character * is appended. */ void i9e_complete_option(char * const *opts, struct i9e_completion_info *ci, struct i9e_completion_result *cr) { int num_matches; num_matches = i9e_extract_completions(ci->word, opts, &cr->matches); if (num_matches == 1) { char *opt = cr->matches[0]; char c = opt[strlen(opt) - 1]; if (c == '=') cr->dont_append_space = true; } } /** * Return the number of non-option arguments encountered so far. * * This counts the number of arguments up to the current word which are neither * options nor arguments to options. * * \param opts NULL terminated array of short and long options, may be NULL. * \param ci Provided by i9e in completion context. * * For convenience, NULL can be passed as the option array pointer to * indicate that the subcommand has no options. In this case the function * returns the word number stored in the completion info structure. * * \return Zero means that the cursor is positioned at the first non-option * argument. */ unsigned i9e_get_nonopt_argnum(char * const *opts, struct i9e_completion_info *ci) { bool prev_is_option_with_arg = false; unsigned num_non_option_args = 0; if (!opts) return ci->word_num; for (unsigned n = 0; n < ci->word_num; n++) { unsigned m; const char *arg = ci->argv[n]; if (prev_is_option_with_arg) { prev_is_option_with_arg = false; continue; } if (!strcmp(arg, "--")) { prev_is_option_with_arg = false; continue; } if (arg[0] != '-') { num_non_option_args++; prev_is_option_with_arg = false; continue; } for (m = 0; opts[m]; m++) { const char *opt = opts[m]; size_t len = strlen(opt); if (opt[len - 1] != '=') { if (strcmp(opt, arg)) continue; /* opt without arg */ prev_is_option_with_arg = false; break; } if (strncmp(opt, arg, len - 1)) continue; if (arg[len - 1] == '\0') { /* --opt-with-arg */ prev_is_option_with_arg = true; break; } if (arg[len - 1] == '=') { /* --opt-with-arg= */ prev_is_option_with_arg = false; break; } /* --opt-with-arg-garbage, no match */ } if (!opts[m]) { /* no match */ num_non_option_args++; prev_is_option_with_arg = false; } } return num_non_option_args; } /** * Find out whether the current word is an argument to an option. * * This handles both the --opt=arg and --opt arg syntax to specify option * arguments. * * \param opts NULL-terminated array of short and long options. * \param ci Provided by i9e in completion context. * * \return If the current word is an option argument, the function returns * the index into the option array which corresponds to the matching option. * Otherwise, -1 is returned. */ int i9e_cword_is_option_arg(char * const *opts, struct i9e_completion_info *ci) { const char *prev; /* Return -1 if cursor is at first word or if we've seen "--". */ if (ci->word_num == 0) return -1; for (unsigned n = 0; n < ci->word_num; n++) if (!strcmp(ci->argv[n], "--")) return -1; prev = ci->argv[ci->word_num - 1]; for (unsigned n = 0; opts[n]; n++) { const char *opt = opts[n]; size_t len = strlen(opt); assert(len > 0); if (opt[len - 1] != '=') continue; if (!strncmp(opt, ci->word, len)) return n; /* --opt=arg */ if (!strncmp(opt, prev, len - 1) && prev[len - 1] == '\0') return n; /* --opt arg */ } return -1; } /** * Print possible completions to stdout. * * \param completers The array of completion functions. * * At the end of the output a line starting with "-o=", followed by the * (possibly empty) list of completion options is printed. Currently, the only * two completion options are "nospace" and "filenames". The former indicates * that no space should be appended even for a unique match while the latter * indicates that usual filename completion should be performed in addition to * the previously printed options. * * \return Standard. */ int i9e_print_completions(const struct i9e_completer *completers) { struct i9e_completion_result cr; struct i9e_completion_info ci; char *buf; const char *end, *p; int i, n, ret; reset_completion_result(&cr); buf = getenv("COMP_POINT"); ci.point = buf? atoi(buf) : 0; ci.buffer = para_strdup(getenv("COMP_LINE")); ci.argc = create_argv(ci.buffer, " ", &ci.argv); ci.word_num = compute_word_num(ci.buffer, " ", ci.point); /* determine the current word to complete */ end = ci.buffer + ci.point; if (*end == ' ') { if (ci.point == 0 || ci.buffer[ci.point - 1] == ' ') { ci.word = para_strdup(NULL); goto create_matches; } else /* The cursor is positioned right after a word */ end--; } for (p = end; p > ci.buffer && *p != ' '; p--) ; /* nothing */ if (*p == ' ') p++; n = end - p + 1; ci.word = alloc(n + 1); strncpy(ci.word, p, n); ci.word[n] = '\0'; create_matches: PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n", ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word); if (ci.word_num == 0) cr.matches = i9e_complete_commands(ci.word, completers); else create_matches(&ci, completers, &cr); ret = 0; if (cr.matches && cr.matches[0]) { for (i = 0; cr.matches[i]; i++) printf("%s\n", cr.matches[i]); ret = 1; } printf("-o="); if (cr.dont_append_space) printf("nospace"); if (cr.filename_completion_desired) printf(",filenames"); printf("\n"); free_argv(cr.matches); free_argv(ci.argv); free(ci.buffer); free(ci.word); return ret; } /** * Complete on severity strings. * * \param ci See struct \ref i9e_completer. * \param cr See struct \ref i9e_completer. * * This is used by para_client and para_audioc which need the same completion * primitive for the ll server/audiod command. Both define their own completer * which is implemented as a trivial wrapper that calls this function. */ void i9e_ll_completer(struct i9e_completion_info *ci, struct i9e_completion_result *cr) { char * const sev[] = {SEVERITIES, NULL}; if (ci->word_num != 1) { cr->matches = NULL; return; } i9e_extract_completions(ci->word, sev, &cr->matches); }