The afh receiver, documentation.
[paraslash.git] / interactive.c
1 /*
2  * Copyright (C) 2011-2012 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file interactive.c Readline abstraction for interactive sessions. */
8
9 #include <regex.h>
10 #include <stdbool.h>
11 #include <curses.h>
12 #include <readline/readline.h>
13 #include <readline/history.h>
14 #include <sys/ioctl.h>
15 #include <assert.h>
16 #include <signal.h>
17
18 #include "para.h"
19 #include "fd.h"
20 #include "buffer_tree.h"
21 #include "list.h"
22 #include "sched.h"
23 #include "interactive.h"
24 #include "string.h"
25 #include "error.h"
26
27 struct i9e_private {
28         struct i9e_client_info *ici;
29         FILE *stderr_stream;
30         char empty_line[1000];
31         struct task task;
32         struct btr_node *stdout_btrn;
33         bool line_handler_running;
34         bool input_eof;
35         bool caught_sigint;
36 };
37 static struct i9e_private i9e_private, *i9ep = &i9e_private;
38
39 static bool is_prefix(const char *partial, const char *full, size_t len)
40 {
41         if (len == 0)
42                 len = strlen(partial);
43         return !strncmp(partial, full, len);
44 }
45
46 /*
47  * Generator function for command completion. STATE lets us know whether
48  * to start from scratch; without any state (i.e. STATE == 0), then we
49  * start at the top of the list.
50  */
51 static char *command_generator(const char *text, int state)
52 {
53         static int list_index, len;
54         const char *name;
55         struct i9e_client_info *ici = i9ep->ici;
56
57         rl_attempted_completion_over = 1; /* disable filename completion */
58         /*
59          * If this is a new word to complete, initialize now. This includes
60          * saving the length of TEXT for efficiency, and initializing the index
61          * variable to 0.
62          */
63         if (state == 0) {
64                 list_index = 0;
65                 len = strlen(text);
66         }
67         /* Return the next name which partially matches from the command list. */
68         while ((name = ici->completers[list_index].name)) {
69                 list_index++;
70                 if (is_prefix(text, name, len))
71                         return para_strdup(name);
72         }
73         return NULL; /* no names matched */
74 }
75
76 static void reset_completion_result(struct i9e_completion_result *cr)
77 {
78         cr->dont_append_space = false;
79         cr->filename_completion_desired = false;
80         cr->matches = NULL;
81 }
82
83 static void create_matches(struct i9e_completion_info *ci,
84                 struct i9e_completer *completers,
85                 struct i9e_completion_result *cr)
86 {
87         int i, ret;
88
89         reset_completion_result(cr);
90
91         ret = create_argv(ci->buffer, " ", &ci->argv);
92         if (ret < 0 || !ci->argv[0])
93                 return;
94
95         ci->argc = ret;
96         ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
97         for (i = 0; completers[i].name; i++) {
98                 if (strcmp(completers[i].name, ci->argv[0]) != 0)
99                         continue;
100                 completers[i].completer(ci, cr);
101                 break;
102         }
103         PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
104                 ci->argv[ci->word_num]);
105         if (cr->matches)
106                 for (i = 0; cr->matches[i]; i++)
107                         PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
108 }
109
110 static char *completion_generator(const char *word, int state)
111 {
112         static int list_index;
113         static char **argv, **matches;
114         struct i9e_completer *completers = i9ep->ici->completers;
115         struct i9e_completion_info ci = {
116                 .word = (char *)word,
117                 .point = rl_point,
118                 .buffer = rl_line_buffer,
119         };
120         struct i9e_completion_result cr = {.matches = NULL};
121
122         if (state != 0)
123                 goto out;
124         /* clean up previous matches and set defaults */
125         free(matches);
126         matches = NULL;
127         free_argv(argv);
128         argv = NULL;
129         list_index = 0;
130         rl_completion_append_character = ' ';
131         rl_completion_suppress_append = false;
132         rl_attempted_completion_over = true;
133
134         create_matches(&ci, completers, &cr);
135
136         matches = cr.matches;
137         argv = ci.argv;
138         rl_completion_suppress_append = cr.dont_append_space;
139         rl_attempted_completion_over = !cr.filename_completion_desired;
140 out:
141         if (!matches)
142                 return NULL;
143         return matches[list_index++];
144 }
145
146 /*
147  * Attempt to complete on the contents of TEXT. START and END bound the
148  * region of rl_line_buffer that contains the word to complete.  TEXT is
149  * the word to complete.  We can use the entire contents of rl_line_buffer
150  * in case we want to do some simple parsing. Return the array of matches,
151  * or NULL if there aren't any.
152  */
153 static char **i9e_completer(const char *text, int start, __a_unused int end)
154 {
155         struct i9e_client_info *ici = i9ep->ici;
156
157         if (!ici->completers)
158                 return NULL;
159         /* Complete on command names if this is the first word in the line. */
160         if (start == 0)
161                 return rl_completion_matches(text, command_generator);
162         return rl_completion_matches(text, completion_generator);
163 }
164
165 /**
166  * Prepare writing to stdout.
167  *
168  * \param producer The buffer tree node which produces output.
169  *
170  * The i9e subsystem maintains a buffer tree node which may be attached to
171  * another node which generates output (a "producer"). When attached, the i9e
172  * buffer tree node copies the buffers generated by the producer to stdout.
173  *
174  * This function attaches the i9e input queue to an output queue of \a
175  * producer.
176  *
177  * \return Standard.
178  */
179 void i9e_attach_to_stdout(struct btr_node *producer)
180 {
181         btr_remove_node(&i9ep->stdout_btrn);
182         i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
183                 EMBRACE(.name = "interactive_stdout", .parent = producer));
184 }
185
186 static void wipe_bottom_line(void)
187 {
188         fprintf(i9ep->stderr_stream, "\r%s\r", i9ep->empty_line);
189 }
190
191 /**
192  * Reset the terminal and save the in-memory command line history.
193  *
194  * This should be called before the caller exits.
195  */
196 void i9e_close(void)
197 {
198         char *hf = i9ep->ici->history_file;
199
200         rl_deprep_terminal();
201         if (hf)
202                 write_history(hf);
203         wipe_bottom_line();
204 }
205
206 static void clear_bottom_line(void)
207 {
208         int point;
209         char *text;
210
211         if (rl_point == 0 && rl_end == 0)
212                 return wipe_bottom_line();
213         /*
214          * We might have a multi-line input that needs to be wiped here, so the
215          * simple printf("\r<space>\r") is insufficient. To workaround this, we
216          * remove the whole line, redisplay and restore the killed text.
217          */
218         point = rl_point;
219         text = rl_copy_text(0, rl_end);
220         rl_kill_full_line(0, 0);
221         rl_redisplay();
222         wipe_bottom_line(); /* wipe out the prompt */
223         rl_insert_text(text);
224         rl_point = point;
225 }
226
227 static bool input_available(void)
228 {
229         fd_set rfds;
230         struct timeval tv = {0, 0};
231         int ret;
232
233         FD_ZERO(&rfds);
234         FD_SET(i9ep->ici->fds[0], &rfds);
235         ret = para_select(1, &rfds, NULL, &tv);
236         return ret > 0;
237 }
238
239 static void i9e_line_handler(char *line)
240 {
241         int ret;
242
243         ret = i9ep->ici->line_handler(line);
244         if (ret < 0)
245                 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
246         rl_set_prompt("");
247         if (line) {
248                 if (!*line)
249                         rl_set_prompt(i9ep->ici->prompt);
250                 else
251                         add_history(line);
252                 free(line);
253         } else {
254                 rl_set_prompt("");
255                 i9ep->input_eof = true;
256         }
257 }
258
259 static void i9e_input(void)
260 {
261         do {
262                 rl_callback_read_char();
263         } while (input_available());
264 }
265
266 static void i9e_post_select(struct sched *s, struct task *t)
267 {
268         int ret;
269         struct btr_node *btrn = i9ep->stdout_btrn;
270         struct i9e_client_info *ici = i9ep->ici;
271         char *buf;
272         size_t sz;
273
274         if (i9ep->input_eof) {
275                 t->error = -E_I9E_EOF;
276                 return;
277         }
278         if (!btrn) {
279                 i9ep->caught_sigint = false;
280                 if (FD_ISSET(ici->fds[0], &s->rfds))
281                         i9e_input();
282                 return;
283         }
284         if (i9ep->caught_sigint)
285                 goto rm_btrn;
286         ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
287         if (ret < 0)
288                 goto rm_btrn;
289         sz = btr_next_buffer(btrn, &buf);
290         if (sz == 0)
291                 goto out;
292         ret = xwrite(ici->fds[1], buf, sz);
293         if (ret < 0)
294                 goto rm_btrn;
295         btr_consume(btrn, ret);
296         goto out;
297 rm_btrn:
298         btr_remove_node(&i9ep->stdout_btrn);
299         rl_set_prompt(i9ep->ici->prompt);
300         rl_redisplay();
301 out:
302         t->error = 0;
303 }
304
305 static void i9e_pre_select(struct sched *s, __a_unused struct task *t)
306 {
307         int ret;
308
309         if (i9ep->input_eof || i9ep->caught_sigint) {
310                 sched_min_delay(s);
311                 return;
312         }
313         if (i9ep->stdout_btrn) {
314                 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
315                 if (ret < 0) {
316                         sched_min_delay(s);
317                         return;
318                 }
319                 if (ret > 0)
320                         para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
321         }
322         /*
323          * fd[0] might have been reset to blocking mode if our job was moved to
324          * the background due to CTRL-Z or SIGSTOP, so set the fd back to
325          * nonblocking mode.
326          */
327         ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
328         if (ret < 0)
329                 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
330                         i9ep->ici->fds[0], para_strerror(-ret));
331         para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
332 }
333
334 static void update_winsize(void)
335 {
336         struct winsize w;
337         int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
338         int num_columns = 80;
339
340         if (ret >= 0) {
341                 assert(w.ws_col < sizeof(i9ep->empty_line));
342                 num_columns = w.ws_col;
343         }
344         memset(i9ep->empty_line, ' ', num_columns);
345         i9ep->empty_line[num_columns] = '\0';
346 }
347
348 /**
349  * Register the i9e task and initialize readline.
350  *
351  * \param ici The i9e configuration parameters set by the caller.
352  * \param s The scheduler instance to add the i9e task to.
353  *
354  * The caller must allocate and initialize the structure \a ici points to.
355  *
356  * \return Standard.
357  * \sa \ref register_task().
358  */
359 int i9e_open(struct i9e_client_info *ici, struct sched *s)
360 {
361         int ret;
362
363         if (!isatty(ici->fds[0]))
364                 return -E_I9E_SETUPTERM;
365         ret = mark_fd_nonblocking(ici->fds[0]);
366         if (ret < 0)
367                 return ret;
368         ret = mark_fd_nonblocking(ici->fds[1]);
369         if (ret < 0)
370                 return ret;
371         i9ep->task.pre_select = i9e_pre_select;
372         i9ep->task.post_select = i9e_post_select;
373         sprintf(i9ep->task.status, "i9e");
374         register_task(s, &i9ep->task);
375         rl_readline_name = "para_i9e";
376         rl_basic_word_break_characters = " ";
377         rl_attempted_completion_function = i9e_completer;
378         i9ep->ici = ici;
379         i9ep->stderr_stream = fdopen(ici->fds[2], "w");
380         setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
381
382         if (ici->history_file)
383                 read_history(ici->history_file);
384         update_winsize();
385         rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
386         return 1;
387 }
388
389 static void reset_line_state(void)
390 {
391         if (i9ep->stdout_btrn)
392                 return;
393         rl_on_new_line();
394         rl_reset_line_state();
395         rl_forced_update_display();
396 }
397
398 /**
399  * The log function of the i9e subsystem.
400  *
401  * \param ll Severity log level.
402  * \param fmt Printf-like format string.
403  *
404  * This clears the bottom line of the terminal if necessary and writes the
405  * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
406  * \ref i9e_open().
407  */
408 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
409 {
410         va_list argp;
411
412         if (ll < i9ep->ici->loglevel)
413                 return;
414         clear_bottom_line();
415         va_start(argp, fmt);
416         vfprintf(i9ep->stderr_stream, fmt, argp);
417         va_end(argp);
418         reset_line_state();
419 }
420
421 /**
422  * Tell i9e that the caller received a signal.
423  *
424  * \param sig_num The number of the signal received.
425  *
426  * Currently the function only cares about \p SIGINT, but this may change.
427  */
428 void i9e_signal_dispatch(int sig_num)
429 {
430         if (sig_num == SIGINT) {
431                 fprintf(i9ep->stderr_stream, "\n");
432                 rl_replace_line ("", false /* clear_undo */);
433                 reset_line_state();
434                 i9ep->caught_sigint = true;
435         }
436 }
437
438 /**
439  * Wrapper for select(2) which does not restart on interrupts.
440  *
441  * \param n \sa \ref para_select().
442  * \param readfds \sa \ref para_select().
443  * \param writefds \sa \ref para_select().
444  * \param timeout_tv \sa \ref para_select().
445  *
446  * \return \sa \ref para_select().
447  *
448  * The only difference between this function and \ref para_select() is that
449  * \ref i9e_select() returns zero if the select call returned \p EINTR.
450  */
451 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
452                 struct timeval *timeout_tv)
453 {
454         int ret = select(n, readfds, writefds, NULL, timeout_tv);
455
456         if (ret < 0) {
457                 if (errno == EINTR)
458                         ret = 0;
459                 else
460                         ret = -ERRNO_TO_PARA_ERROR(errno);
461         }
462         return ret;
463 }
464
465 /**
466  * Return the possible completions for a given word.
467  *
468  * \param word The word to complete.
469  * \param string_list All possible words in this context.
470  * \param result String list is returned here.
471  *
472  * This function never fails. If no completion was found, a string list of
473  * length zero is returned. In any case, the result must be freed by the caller
474  * using \ref free_argv().
475  *
476  * This function is independent of readline and may be called before
477  * i9e_open().
478  *
479  * \return The number of possible completions.
480  */
481 int i9e_extract_completions(const char *word, char **string_list,
482                 char ***result)
483 {
484         char **matches = para_malloc(sizeof(char *));
485         int match_count = 0, matches_len = 1;
486         char **p;
487         int len = strlen(word);
488
489         for (p = string_list; *p; p++) {
490                 if (!is_prefix(word, *p, len))
491                         continue;
492                 match_count++;
493                 if (match_count >= matches_len) {
494                         matches_len *= 2;
495                         matches = para_realloc(matches,
496                                 matches_len * sizeof(char *));
497                 }
498                 matches[match_count - 1] = para_strdup(*p);
499         }
500         matches[match_count] = NULL;
501         *result = matches;
502         return match_count;
503 }
504
505 /**
506  * Return the list of partially matching words.
507  *
508  * \param word The command to complete.
509  * \param completers The array containing all command names.
510  *
511  * This is similar to \ref i9e_extract_completions(), but completes on the
512  * command names in \a completers.
513  *
514  * \return See \ref i9e_extract_completions().
515  */
516 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
517 {
518         char **matches;
519         const char *cmd;
520         int i, match_count, len = strlen(word);
521
522         /*
523          * In contrast to completing against an arbitrary string list, here we
524          * know all possible completions and expect that there will not be many
525          * of them. So it should be OK to iterate twice over all commands which
526          * simplifies the code a bit.
527          */
528         for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
529                 if (is_prefix(word, cmd, len))
530                         match_count++;
531         }
532         matches = para_malloc((match_count + 1) * sizeof(*matches));
533         for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
534                 if (is_prefix(word, cmd, len))
535                         matches[match_count++] = para_strdup(cmd);
536         matches[match_count] = NULL;
537         return matches;
538 }
539
540 /**
541  * Complete according to the given options.
542  *
543  * \param opts All available options.
544  * \param ci Information which was passed to the completer.
545  * \param cr Result pointer.
546  *
547  * This convenience helper can be used to complete an option. The array of all
548  * possible options is passed as the first argument. Flags, i.e. options
549  * without an argument, are expected to be listed as strings of type "-X" in \a
550  * opts while options which require an argument should be passed with a
551  * trailing "=" character like "-X=".
552  *
553  * If the word can be uniquely completed to a flag option, an additional space
554  * character is appended to the output. For non-flag options no space character
555  * is appended.
556  */
557 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
558                 struct i9e_completion_result *cr)
559 {
560         int num_matches;
561
562         num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
563         if (num_matches == 1) {
564                 char *opt = cr->matches[0];
565                 char c = opt[strlen(opt) - 1];
566                 if (c == '=')
567                         cr->dont_append_space = true;
568         }
569 }
570
571 /**
572  * Print possible completions to stdout.
573  *
574  * \param completers The array of completion functions.
575  *
576  * At the end of the output a line starting with "-o=", followed by the
577  * (possibly empty) list of completion options is printed. Currently, the only
578  * two completion options are "nospace" and "filenames". The former indicates
579  * that no space should be appended even for a unique match while the latter
580  * indicates that usual filename completion should be performed in addition to
581  * the previously printed options.
582  *
583  * \return Standard.
584  */
585 int i9e_print_completions(struct i9e_completer *completers)
586 {
587         struct i9e_completion_result cr;
588         struct i9e_completion_info ci;
589         char *buf;
590         const char *end, *p;
591         int i, n, ret;
592
593         reset_completion_result(&cr);
594         buf = getenv("COMP_POINT");
595         ci.point = buf? atoi(buf) : 0;
596         ci.buffer = para_strdup(getenv("COMP_LINE"));
597
598         ci.argc = create_argv(ci.buffer, " ", &ci.argv);
599         ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
600
601         end = ci.buffer + ci.point;
602         for (p = end; p > ci.buffer && *p != ' '; p--)
603                 ; /* nothing */
604         if (*p == ' ')
605                 p++;
606
607         n = end - p + 1;
608         ci.word = para_malloc(n + 1);
609         strncpy(ci.word, p, n);
610         ci.word[n] = '\0';
611
612         PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
613                 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
614         if (ci.word_num == 0)
615                 cr.matches = i9e_complete_commands(ci.word, completers);
616         else
617                 create_matches(&ci, completers, &cr);
618         ret = 0;
619         if (cr.matches && cr.matches[0]) {
620                 for (i = 0; cr.matches[i]; i++)
621                         printf("%s\n", cr.matches[i]);
622                 ret = 1;
623         }
624         printf("-o=");
625         if (cr.dont_append_space)
626                 printf("nospace");
627         if (cr.filename_completion_desired)
628                 printf(",filenames");
629         printf("\n");
630         free_argv(cr.matches);
631         free_argv(ci.argv);
632         free(ci.buffer);
633         free(ci.word);
634         return ret;
635 }