+#ifdef HAVE_READLINE
+#define READLINE_LIBRARY 1
+#include "readline.h"
+#include "history.h"
+
+/* Get the first keyword of the line */
+static char *
+get_first_keyword()
+{
+ char *ret=NULL;
+ int len;
+ char *first_space = strchr(rl_line_buffer, ' ');
+ if (first_space) {
+ len = first_space - rl_line_buffer;
+ ret = (char *) malloc((len + 1) * sizeof(char));
+ memcpy(ret, rl_line_buffer, len);
+ ret[len]=0;
+ }
+ return ret;
+}
+
+/*
+ * Return the command before the current point.
+ * Set nb to the number of command to skip
+ */
+static char *
+get_previous_keyword(int current_point, int nb)
+{
+ int i, end=-1, start, inquotes=0;
+ char *s=NULL;
+
+ while (nb-- >= 0) {
+ /* first we look for a space before the current word */
+ for (i = current_point; i >= 0; i--) {
+ if (rl_line_buffer[i] == ' ' || rl_line_buffer[i] == '=') {
+ break;
+ }
+ }
+
+ /* find the end of the command */
+ for (; i >= 0; i--) {
+ if (rl_line_buffer[i] != ' ') {
+ end = i;
+ break;
+ }
+ }
+
+ /* no end of string */
+ if (end == -1) {
+ return NULL;
+ }
+
+ /* look for the start of the command */
+ for (start = end; start > 0; start--) {
+ if (rl_line_buffer[start] == '"') {
+ inquotes = !inquotes;
+ }
+ if ((rl_line_buffer[start - 1] == ' ') && inquotes == 0) {
+ break;
+ }
+ current_point = start;
+ }
+ }
+
+ s = (char *)malloc(end - start + 2);
+ memcpy(s, rl_line_buffer + start, end - start + 1);
+ s[end - start + 1] = 0;
+
+ // printf("=======> %i:%i <%s>\n", start, end, s);
+
+ return s;
+}
+
+/* Simple structure that will contain the completion list */
+struct ItemList {
+ alist list;
+};
+
+static ItemList *items = NULL;
+void init_items()
+{
+ if (!items) {
+ items = (ItemList*) malloc(sizeof(ItemList));
+ memset(items, 0, sizeof(ItemList));
+
+ } else {
+ items->list.destroy();
+ }
+
+ items->list.init();
+}
+
+/* Match a regexp and add the result to the items list
+ * This function is recursive
+ */
+static void match_kw(regex_t *preg, const char *what, int len, POOLMEM **buf)
+{
+ int rc, size;
+ int nmatch=20;
+ regmatch_t pmatch[nmatch];
+
+ if (len <= 0) {
+ return;
+ }
+ rc = regexec(preg, what, nmatch, pmatch, 0);
+ if (rc == 0) {
+#if 0
+ Pmsg1(0, "\n\n%s\n0123456789012345678901234567890123456789\n 10 20 30\n", what);
+ Pmsg2(0, "%i-%i\n", pmatch[0].rm_so, pmatch[0].rm_eo);
+ Pmsg2(0, "%i-%i\n", pmatch[1].rm_so, pmatch[1].rm_eo);
+ Pmsg2(0, "%i-%i\n", pmatch[2].rm_so, pmatch[2].rm_eo);
+ Pmsg2(0, "%i-%i\n", pmatch[3].rm_so, pmatch[3].rm_eo);
+#endif
+ size = pmatch[1].rm_eo - pmatch[1].rm_so;
+ *buf = check_pool_memory_size(*buf, size + 1);
+ memcpy(*buf, what+pmatch[1].rm_so, size);
+ (*buf)[size] = 0;
+
+ items->list.append(bstrdup(*buf));
+ /* We search for the next keyword in the line */
+ match_kw(preg, what + pmatch[1].rm_eo, len - pmatch[1].rm_eo, buf);
+ }
+}
+
+/* fill the items list with the output of the help command */
+void get_arguments(const char *what)
+{
+ regex_t preg;
+ POOLMEM *buf;
+ int rc;
+ init_items();
+
+ rc = regcomp(&preg, "(([a-z]+=)|([a-z]+)( |$))", REG_EXTENDED);
+ if (rc != 0) {
+ return;
+ }
+
+ buf = get_pool_memory(PM_MESSAGE);
+ UA_sock->fsend(".help item=%s", what);
+ while (UA_sock->recv() > 0) {
+ strip_trailing_junk(UA_sock->msg);
+ match_kw(&preg, UA_sock->msg, UA_sock->msglen, &buf);
+ }
+ free_pool_memory(buf);
+ regfree(&preg);
+}
+
+/* retreive a simple list (.pool, .client) and store it into items */
+void get_items(const char *what)
+{
+ init_items();
+
+ UA_sock->fsend("%s", what);
+ while (UA_sock->recv() > 0) {
+ strip_trailing_junk(UA_sock->msg);
+ items->list.append(bstrdup(UA_sock->msg));
+ }
+}
+
+typedef enum
+{
+ ITEM_ARG, /* item with simple list like .jobs */
+ ITEM_HELP /* use help item=xxx and detect all arguments */
+} cpl_item_t;
+
+/* 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 *item_generator(const char *text, int state,
+ const char *item, cpl_item_t type)
+{
+ static int list_index, len;
+ char *name;
+
+ /* 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)
+ {
+ list_index = 0;
+ len = strlen(text);
+ switch(type) {
+ case ITEM_ARG:
+ get_items(item);
+ break;
+ case ITEM_HELP:
+ get_arguments(item);
+ break;
+ }
+ }
+
+ /* Return the next name which partially matches from the command list. */
+ while (items && list_index < items->list.size())
+ {
+ name = (char *)items->list[list_index];
+ list_index++;
+
+ if (strncmp(name, text, len) == 0) {
+ char *ret = (char *) actuallymalloc(strlen(name)+1);
+ strcpy(ret, name);
+ return ret;
+ }
+ }
+
+ /* If no names matched, then return NULL. */
+ return ((char *)NULL);
+}
+
+/* gobal variables for the type and the item to search
+ * the readline API doesn' permit to pass user data.
+ */
+static const char *cpl_item;
+static cpl_item_t cpl_type;
+
+static char *cpl_generator(const char *text, int state)
+{
+ return item_generator(text, state, cpl_item, cpl_type);
+}
+
+/* this function is used to not use the default filename completion */
+static char *dummy_completion_function(const char *text, int state)
+{
+ return NULL;
+}
+
+struct cpl_keywords_t {
+ const char *key;
+ const char *cmd;
+};
+
+static struct cpl_keywords_t cpl_keywords[] = {
+ {"pool=", ".pool" },
+ {"fileset=", ".fileset" },
+ {"client=", ".client" },
+ {"job=", ".jobs" },
+ {"restore_job=",".jobs type=R" },
+ {"level=", ".level" },
+ {"storage=", ".storage" },
+ {"schedule=", ".schedule" },
+ {"volume=", ".media" },
+ {"oldvolume=", ".media" },
+ {"volstatus=", ".volstatus" },
+ {"ls", ".ls" },
+ {"cd", ".lsdir" },
+ {"mark", ".ls" },
+ {"m", ".ls" },
+ {"unmark", ".lsmark" },
+ {"catalog=", ".catalogs" },
+ {"actiononpurge=", ".actiononpurge" },
+ {"tags=", ".tags" },
+ {"recylepool=", ".pool" },
+ {"allfrompool=",".pool" }
+};
+#define key_size ((int)(sizeof(cpl_keywords)/sizeof(struct cpl_keywords_t)))
+
+/* Attempt to complete on the contents of TEXT. START and END bound the
+ * region of rl_line_buffer that contains the word to complete. TEXT is
+ * the word to complete. We can use the entire contents of rl_line_buffer
+ * in case we want to do some simple parsing. Return the array of matches,
+ * or NULL if there aren't any.
+ */
+static char **readline_completion(const char *text, int start, int end)
+{
+ bool found=false;
+ char **matches;
+ char *s, *cmd;
+ matches = (char **)NULL;
+
+ /* If this word is at the start of the line, then it is a command
+ * to complete. Otherwise it is the name of a file in the current
+ * directory.
+ */
+ s = get_previous_keyword(start, 0);
+ cmd = get_first_keyword();
+ if (s) {
+ for (int i=0; i < key_size; i++) {
+ if (!strcasecmp(s, cpl_keywords[i].key)) {
+ cpl_item = cpl_keywords[i].cmd;
+ cpl_type = ITEM_ARG;
+ matches = rl_completion_matches(text, cpl_generator);
+ found=true;
+ break;
+ }
+ }
+
+ if (!found) { /* we try to get help with the first command */
+ cpl_item = cmd;
+ cpl_type = ITEM_HELP;
+ /* we don't want to append " " at the end */
+ rl_completion_suppress_append=true;
+ matches = rl_completion_matches(text, cpl_generator);
+ }
+ free(s);
+ } else { /* nothing on the line, display all commands */
+ cpl_item = ".help all";
+ cpl_type = ITEM_ARG;
+ matches = rl_completion_matches(text, cpl_generator);
+ }
+ if (cmd) {
+ free(cmd);
+ }
+ return (matches);
+}
+
+static char eol = '\0';
+static int eolcmd(FILE *input, BSOCK *UA_sock)
+{
+ if ((argc > 1) && (strchr("!$%&'()*+,-/:;<>?[]^`{|}~", argk[1][0]) != NULL)) {
+ eol = argk[1][0];
+ } else if (argc == 1) {
+ eol = '\0';
+ } else {
+ sendit(_("Illegal separator character.\n"));
+ }
+ return 1;
+}
+
+/*
+ * Return 1 if OK
+ * 0 if no input
+ * -1 error (must stop)
+ */
+int
+get_cmd(FILE *input, const char *prompt, BSOCK *sock, int sec)
+{
+ static char *line = NULL;
+ static char *next = NULL;
+ static int do_history = 0;
+ char *command;
+
+ if (line == NULL) {
+ do_history = 0;
+ rl_catch_signals = 0; /* do it ourselves */
+ /* Here, readline does ***real*** malloc
+ * so, be we have to use the real free
+ */
+ line = readline((char *)prompt); /* cast needed for old readlines */
+ if (!line) {
+ return -1; /* error return and exit */
+ }
+ strip_trailing_junk(line);
+ command = line;
+ } else if (next) {
+ command = next + 1;
+ } else {
+ sendit(_("Command logic problem\n"));
+ sock->msglen = 0;
+ sock->msg[0] = 0;
+ return 0; /* No input */
+ }
+
+ /*
+ * Split "line" into multiple commands separated by the eol character.
+ * Each part is pointed to by "next" until finally it becomes null.
+ */
+ if (eol == '\0') {
+ next = NULL;
+ } else {
+ next = strchr(command, eol);
+ if (next) {
+ *next = '\0';
+ }
+ }
+ if (command != line && isatty(fileno(input))) {
+ senditf("%s%s\n", prompt, command);
+
+ } else {
+ /* Send the intput to the output file if needed */
+ if (teein && output != stdout) {
+ fputs(prompt, output);
+ fputs(command, output);
+ fputs("\n", output);
+ }
+ }
+
+ sock->msglen = pm_strcpy(&sock->msg, command);
+ if (sock->msglen) {
+ do_history++;
+ }
+
+ if (!next) {
+ if (do_history) {
+ add_history(line);
+ }
+ actuallyfree(line); /* allocated by readline() malloc */
+ line = NULL;
+ }
+ return 1; /* OK */
+}
+
+#else /* no readline, do it ourselves */
+
+#ifdef HAVE_CONIO
+static bool bisatty(int fd)
+{
+ if (no_conio) {
+ return false;
+ }
+ return isatty(fd);
+}
+#endif
+
+/*
+ * Returns: 1 if data available
+ * 0 if timeout
+ * -1 if error
+ */
+static int
+wait_for_data(int fd, int sec)
+{
+#if defined(HAVE_WIN32)
+ return 1;
+#else
+ for ( ;; ) {
+ switch(fd_wait_data(fd, WAIT_READ, sec, 0)) {
+ case 0: /* timeout */
+ return 0;
+ case -1:
+ if (errno == EINTR || errno == EAGAIN) {
+ continue;
+ }
+ return -1; /* error return */
+ default:
+ return 1;
+ }
+ }
+#endif
+}
+
+/*
+ * Get next input command from terminal.
+ *
+ * Returns: 1 if got input
+ * 0 if timeout
+ * -1 if EOF or error
+ */
+int
+get_cmd(FILE *input, const char *prompt, BSOCK *sock, int sec)
+{
+ int len;
+ if (!stop) {
+ if (output == stdout || teeout) {
+ sendit(prompt);
+ }
+ }
+again:
+ switch (wait_for_data(fileno(input), sec)) {
+ case 0:
+ return 0; /* timeout */
+ case -1:
+ return -1; /* error */
+ default:
+ len = sizeof_pool_memory(sock->msg) - 1;
+ if (stop) {
+ sleep(1);
+ goto again;
+ }
+#ifdef HAVE_CONIO
+ if (bisatty(fileno(input))) {
+ input_line(sock->msg, len);
+ break;
+ }
+#endif
+#ifdef HAVE_WIN32 /* use special console for input on win32 */
+ if (input == stdin) {
+ if (win32_cgets(sock->msg, len) == NULL) {
+ return -1;
+ }
+ }
+ else
+#endif
+ if (bfgets(sock->msg, input) == NULL) {
+ return -1;
+
+ }
+ break;
+ }
+ if (usrbrk()) {
+ clrbrk();
+ }
+ strip_trailing_junk(sock->msg);
+ sock->msglen = strlen(sock->msg);
+
+ /* Send input to log file if needed */
+ if (teein && output != stdout) {
+ fputs(sock->msg, output);
+ fputs("\n", output);
+ }
+
+ return 1;
+}
+
+#endif /* ! HAVE_READLINE */
+
+/* Routine to return true if user types break */
+int usrbrk()
+{
+ return brkflg;
+}
+
+/* Clear break flag */
+void clrbrk()
+{
+ brkflg = 0;
+}
+
+/* Interrupt caught here */
+static void sigintcatcher(int sig)
+{
+ brkflg++;
+ if (brkflg > 3) {
+ terminate_console(sig);
+ }
+ signal(SIGINT, sigintcatcher);
+}
+
+/* Trap Ctl-C */
+void trapctlc()
+{
+ signal(SIGINT, sigintcatcher);
+}
+
+static int console_update_history(const char *histfile)
+{
+ int ret=0;
+
+#ifdef HAVE_READLINE
+/*
+ * first, try to truncate the history file, and if it
+ * fails, the file is probably not present, and we
+ * can use write_history to create it
+ */
+
+ if (history_truncate_file(histfile, 100) == 0) {
+ ret = append_history(history_length, histfile);
+ } else {
+ ret = write_history(histfile);
+ }
+#endif
+
+ return ret;
+}
+
+static int console_init_history(const char *histfile)
+{
+ int ret=0;
+
+#ifdef HAVE_READLINE
+ using_history();
+ ret = read_history(histfile);
+ /* Tell the completer that we want a complete . */
+ rl_completion_entry_function = dummy_completion_function;
+ rl_attempted_completion_function = readline_completion;
+ rl_filename_completion_desired = 0;
+ stifle_history(100);
+#endif
+
+ return ret;
+}
+
+static bool select_director(const char *director, const char *console,
+ DIRRES **ret_dir, CONRES **ret_cons)
+{
+ int numcon=0, numdir=0;
+ int i=0, item=0;
+ BSOCK *UA_sock;
+ DIRRES *dir = NULL;
+ CONRES *cons = NULL;
+
+ *ret_cons = NULL;
+ *ret_dir = NULL;
+
+ LockRes();
+ numdir = 0;
+ foreach_res(dir, R_DIRECTOR) {
+ numdir++;
+ }
+ numcon = 0;
+ foreach_res(cons, R_CONSOLE) {
+ numcon++;
+ }
+ UnlockRes();
+
+ if (numdir == 1) { /* No choose */
+ dir = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
+ }
+
+ if (director) { /* Command line choice overwrite the no choose option */
+ LockRes();
+ foreach_res(dir, R_DIRECTOR) {
+ if (bstrcasecmp(dir->hdr.name, director)) {
+ break;
+ }
+ }
+ UnlockRes();
+ if (!dir) { /* Can't find Director used as argument */
+ senditf(_("Can't find %s in Director list\n"), director);
+ return 0;
+ }
+ }
+
+ if (dir == NULL) { /* prompt for director */
+ UA_sock = new_bsock();
+try_again:
+ sendit(_("Available Directors:\n"));
+ LockRes();
+ numdir = 0;
+ foreach_res(dir, R_DIRECTOR) {
+ senditf( _("%2d: %s at %s:%d\n"), 1+numdir++, dir->hdr.name,
+ dir->address, dir->DIRport);
+ }
+ UnlockRes();
+ if (get_cmd(stdin, _("Select Director by entering a number: "),
+ UA_sock, 600) < 0)
+ {
+ (void)WSACleanup(); /* Cleanup Windows sockets */
+ return 0;
+ }
+ if (!is_a_number(UA_sock->msg)) {
+ senditf(_("%s is not a number. You must enter a number between "
+ "1 and %d\n"),
+ UA_sock->msg, numdir);
+ goto try_again;
+ }
+ item = atoi(UA_sock->msg);
+ if (item < 0 || item > numdir) {
+ senditf(_("You must enter a number between 1 and %d\n"), numdir);
+ goto try_again;
+ }
+ free_bsock(UA_sock);
+ LockRes();
+ for (i=0; i<item; i++) {
+ dir = (DIRRES *)GetNextRes(R_DIRECTOR, (RES *)dir);
+ }
+ UnlockRes();
+ }
+ LockRes();
+ /* Look for a console linked to this director */
+ for (i=0; i<numcon; i++) {
+ cons = (CONRES *)GetNextRes(R_CONSOLE, (RES *)cons);
+ if (console) {
+ if (strcmp(cons->hdr.name, console) == 0) {
+ break;
+ }
+ } else if (cons->director && strcasecmp(cons->director, dir->hdr.name) == 0) {
+ break;
+ }
+ if (i == (numcon - 1)) {
+ cons = NULL;
+ }
+ }
+
+ if (cons == NULL && console != NULL) {
+ UnlockRes();
+ senditf(_("Can't find %s in Console list\n"), console);
+ return 0;
+ }
+
+ /* Look for the first non-linked console */
+ if (cons == NULL) {
+ for (i=0; i<numcon; i++) {
+ cons = (CONRES *)GetNextRes(R_CONSOLE, (RES *)cons);
+ if (cons->director == NULL) {
+ break;
+ }
+ if (i == (numcon - 1)) {
+ cons = NULL;
+ }
+ }
+ }
+
+ /* If no console, take first one */
+ if (!cons) {
+ cons = (CONRES *)GetNextRes(R_CONSOLE, (RES *)NULL);
+ }
+ UnlockRes();
+
+ *ret_dir = dir;
+ *ret_cons = cons;
+
+ return 1;
+}