]> git.sur5r.net Git - bacula/bacula/blobdiff - bacula/src/console/console.c
Update version to indicate base jobs added
[bacula/bacula] / bacula / src / console / console.c
index 56d7a4ca765e54171dd55c15ec6ddbb4d4e9edae..05892a718a776169146ca3d604688d5ff53fc06a 100644 (file)
@@ -1,7 +1,7 @@
 /*
    Bacula® - The Network Backup Solution
 
-   Copyright (C) 2000-2008 Free Software Foundation Europe e.V.
+   Copyright (C) 2000-2009 Free Software Foundation Europe e.V.
 
    The main author of Bacula is Kern Sibbald, with contributions from
    many others, a complete list can be found in the file AUTHORS.
@@ -86,6 +86,7 @@ static FILE *output = stdout;
 static bool teeout = false;               /* output to output and stdout */
 static bool stop = false;
 static bool no_conio = false;
+static int timeout = 0;
 static int argc;
 static int numdir;
 static int numcon;
@@ -101,12 +102,20 @@ static int inputcmd(FILE *input, BSOCK *UA_sock);
 static int outputcmd(FILE *input, BSOCK *UA_sock);
 static int teecmd(FILE *input, BSOCK *UA_sock);
 static int quitcmd(FILE *input, BSOCK *UA_sock);
+static int helpcmd(FILE *input, BSOCK *UA_sock);
 static int echocmd(FILE *input, BSOCK *UA_sock);
 static int timecmd(FILE *input, BSOCK *UA_sock);
 static int sleepcmd(FILE *input, BSOCK *UA_sock);
 static int execcmd(FILE *input, BSOCK *UA_sock);
 #ifdef HAVE_READLINE
 static int eolcmd(FILE *input, BSOCK *UA_sock);
+
+# ifndef HAVE_REGEX_H
+#  include "lib/bregex.h"
+# else
+#  include <regex.h>
+# endif
+
 #endif
 
 
@@ -123,6 +132,7 @@ PROG_COPYRIGHT
 "       -dt         print timestamp in debug output\n"
 "       -n          no conio\n"
 "       -s          no signals\n"
+"       -u <nn>     set command execution timeout to <nn> seconds\n"
 "       -t          test - read configuration and exit\n"
 "       -?          print this message.\n"
 "\n"), 2000, HOST_OS, DISTNAME, DISTVER);
@@ -176,11 +186,12 @@ static struct cmdstruct commands[] = {
  { N_("exec"),       execcmd,      _("execute an external command")},
  { N_("exit"),       quitcmd,      _("exit = quit")},
  { N_("zed_keys"),   zed_keyscmd,  _("zed_keys = use zed keys instead of bash keys")},
+ { N_("help"),       helpcmd,      _("help listing")},
 #ifdef HAVE_READLINE
  { N_("separator"),  eolcmd,       _("set command separator")},
 #endif
              };
-#define comsize (sizeof(commands)/sizeof(struct cmdstruct))
+#define comsize ((int)(sizeof(commands)/sizeof(struct cmdstruct)))
 
 static int do_a_command(FILE *input, BSOCK *UA_sock)
 {
@@ -225,6 +236,7 @@ static void read_and_process_input(FILE *input, BSOCK *UA_sock)
    bool at_prompt = false;
    int tty_input = isatty(fileno(input));
    int stat;
+   btimer_t *tid=NULL;
 
    for ( ;; ) {
       if (at_prompt) {                /* don't prompt multiple times */
@@ -260,7 +272,9 @@ static void read_and_process_input(FILE *input, BSOCK *UA_sock)
          break;                       /* error or interrupt */
       } else if (stat == 0) {         /* timeout */
          if (strcmp(prompt, "*") == 0) {
+            tid = start_bsock_timer(UA_sock, timeout);
             bnet_fsend(UA_sock, ".messages");
+            stop_bsock_timer(tid);
          } else {
             continue;
          }
@@ -274,13 +288,17 @@ static void read_and_process_input(FILE *input, BSOCK *UA_sock)
             }
             continue;
          }
+         tid = start_bsock_timer(UA_sock, timeout);
          if (!bnet_send(UA_sock)) {   /* send command */
+            stop_bsock_timer(tid);
             break;                    /* error */
          }
+         stop_bsock_timer(tid);
       }
       if (strcmp(UA_sock->msg, ".quit") == 0 || strcmp(UA_sock->msg, ".exit") == 0) {
          break;
       }
+      tid = start_bsock_timer(UA_sock, timeout);
       while ((stat = bnet_recv(UA_sock)) >= 0) {
          if (at_prompt) {
             if (!stop) {
@@ -293,6 +311,7 @@ static void read_and_process_input(FILE *input, BSOCK *UA_sock)
             sendit(UA_sock->msg);
          }
       }
+      stop_bsock_timer(tid);
       if (usrbrk() > 1) {
          break;
       } else {
@@ -344,10 +363,300 @@ static int tls_pem_callback(char *buf, int size, const void *userdata)
 
 #ifdef HAVE_READLINE
 #define READLINE_LIBRARY 1
-#undef free
 #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[20];
+
+   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 .job */
+   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=",       ".job"           },
+   {"level=",     ".level"         },
+   {"storage=",   ".storage"       },
+   {"schedule=",  ".schedule"      },
+   {"volume=",    ".media"         },
+   {"oldvolume=", ".media"         },
+   {"volstatus=", ".volstatus"     },
+   {"actiononpurge=", ".actiononpurge" }
+};
+#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)
 {
@@ -372,6 +681,9 @@ get_cmd(FILE *input, const char *prompt, BSOCK *sock, int sec)
    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) {
          exit(1);
@@ -412,7 +724,7 @@ get_cmd(FILE *input, const char *prompt, BSOCK *sock, int sec)
       if (do_history) {
         add_history(line);
       }
-      free(line);
+      actuallyfree(line);       /* allocated by readline() malloc */
       line = NULL;
    }
    return 1;
@@ -552,7 +864,10 @@ static int console_init_history(const char *histfile)
 
    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;
 #endif
 
    return ret;
@@ -576,12 +891,13 @@ int main(int argc, char *argv[])
    textdomain("bacula");
 
    init_stack_dump();
+   lmgr_init_thread();
    my_name_is(argc, argv, "bconsole");
    init_msg(NULL, NULL);
    working_directory = "/tmp";
    args = get_pool_memory(PM_FNAME);
 
-   while ((ch = getopt(argc, argv, "bc:d:nst?")) != -1) {
+   while ((ch = getopt(argc, argv, "bc:d:nstu:?")) != -1) {
       switch (ch) {
       case 'c':                    /* configuration file */
          if (configfile != NULL) {
@@ -613,6 +929,10 @@ int main(int argc, char *argv[])
          test_config = true;
          break;
 
+      case 'u':
+         timeout = atoi(optarg);
+         break;
+
       case '?':
       default:
          usage();
@@ -672,6 +992,8 @@ int main(int argc, char *argv[])
 
    (void)WSA_Init();                        /* Initialize Windows sockets */
 
+   start_watchdog();                        /* Start socket watchdog */
+
    LockRes();
    numdir = 0;
    foreach_res(dir, R_DIRECTOR) {
@@ -861,6 +1183,7 @@ static void terminate_console(int sig)
       exit(1);
    }
    already_here = true;
+   stop_watchdog();
    config->free_resources();
    free(config);
    config = NULL;
@@ -870,6 +1193,8 @@ static void terminate_console(int sig)
       con_term();
    }
    (void)WSACleanup();               /* Cleanup Windows sockets */
+   lmgr_cleanup_main();
+
    if (sig != 0) {
       exit(1);
    }
@@ -1064,8 +1389,7 @@ static int execcmd(FILE *input, BSOCK *UA_sock)
 static int echocmd(FILE *input, BSOCK *UA_sock)
 {
    for (int i=1; i < argc; i++) {
-      senditf("%s", argk[i]);
-      sendit(" ");
+      senditf("%s ", argk[i]);
    }
    sendit("\n");
    return 1;
@@ -1076,6 +1400,16 @@ static int quitcmd(FILE *input, BSOCK *UA_sock)
    return 0;
 }
 
+static int helpcmd(FILE *input, BSOCK *UA_sock)
+{
+   int i;
+   for (i=0; i<comsize; i++) { 
+      senditf("  %-10s %s\n", commands[i].key, commands[i].help);
+   }
+   return 1;   
+}
+
+
 static int sleepcmd(FILE *input, BSOCK *UA_sock)
 {
    if (argc > 1) {