]> git.sur5r.net Git - bacula/bacula/blobdiff - bacula/src/qt-console/console/console.cpp
kes Fix sscanf problems reported by Peter Buschman that caused
[bacula/bacula] / bacula / src / qt-console / console / console.cpp
index 6d00ef71de6f9ae10166d33ccc8230db741a119f..dbbc6f38df0c4ddcff3d978276a7680b22a2a67e 100644 (file)
  *
  */ 
 
-#include <QAbstractEventDispatcher>
+//#include <QAbstractEventDispatcher>
 #include "bat.h"
 #include "console.h"
+#include "restore.h"
+#include "select.h"
+#include "run/run.h"
+
+static int tls_pem_callback(char *buf, int size, const void *userdata);
+
 
 Console::Console(QStackedWidget *parent)
 {
@@ -44,48 +50,74 @@ Console::Console(QStackedWidget *parent)
    m_parent = parent;
    m_closeable = false;
    m_console = this;
-   (void)parent;
 
    setupUi(this);
    m_sock = NULL;
    m_at_prompt = false;
+   m_at_main_prompt = false;
    m_textEdit = textEdit;   /* our console screen */
    m_cursor = new QTextCursor(m_textEdit->document());
    mainWin->actionConnect->setIcon(QIcon(":images/disconnected.png"));
 
-   /* Check for messages every 5 seconds */
-// m_timer = new QTimer(this);
-// QWidget::connect(m_timer, SIGNAL(timeout()), this, SLOT(poll_messages()));
-// m_timer->start(5000);
+   m_timer = NULL;
+   m_contextActions.append(actionStatusDir);
+   m_contextActions.append(actionConsoleHelp);
+   m_contextActions.append(actionRequestMessages);
+   m_contextActions.append(actionConsoleReload);
+   connect(actionStatusDir, SIGNAL(triggered()), this, SLOT(status_dir()));
+   connect(actionConsoleHelp, SIGNAL(triggered()), this, SLOT(consoleHelp()));
+   connect(actionConsoleReload, SIGNAL(triggered()), this, SLOT(consoleReload()));
+   connect(actionRequestMessages, SIGNAL(triggered()), this, SLOT(messages()));
 }
 
 Console::~Console()
 {
 }
 
+void Console::startTimer()
+{
+   m_timer = new QTimer(this);
+   QWidget::connect(m_timer, SIGNAL(timeout()), this, SLOT(poll_messages()));
+   m_timer->start(mainWin->m_checkMessagesInterval*1000);
+}
+
+void Console::stopTimer()
+{
+   if (m_timer) {
+      QWidget::disconnect(m_timer, SIGNAL(timeout()), this, SLOT(poll_messages()));
+      m_timer->stop();
+      delete m_timer;
+      m_timer = NULL;
+   }
+}
+      
 void Console::poll_messages()
 {
    m_messages_pending = true;
+   if ((m_at_main_prompt) && (mainWin->m_checkMessages)){
+      write(".messages");
+      displayToPrompt();
+   }
 }
 
 /* Terminate any open socket */
 void Console::terminate()
 {
    if (m_sock) {
+      stopTimer();
       m_sock->close();
       m_sock = NULL;
    }
-// m_timer->stop();
 }
 
 /*
- * Connect to Director. If there are more than one, put up
- * a modal dialog so that the user chooses one.
+ * Connect to Director. 
  */
-void Console::connect()
+void Console::connect_dir()
 {
    JCR jcr;
    utime_t heart_beat;
+   char buf[1024];
 
    m_textEdit = textEdit;   /* our console screen */
 
@@ -108,9 +140,51 @@ void Console::connect()
    
    LockRes();
    /* If cons==NULL, default console will be used */
-   CONRES *cons = (CONRES *)GetNextRes(R_CONSOLE, (RES *)NULL);
+   CONRES *cons = (CONRES *)GetNextRes(R_CONSOLE, NULL);
    UnlockRes();
 
+   /* Initialize Console TLS context once */
+   if (cons && !cons->tls_ctx && (cons->tls_enable || cons->tls_require)) {
+      /* Generate passphrase prompt */
+      bsnprintf(buf, sizeof(buf), "Passphrase for Console \"%s\" TLS private key: ", 
+                cons->name());
+
+      /* Initialize TLS context:
+       * Args: CA certfile, CA certdir, Certfile, Keyfile,
+       * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer   
+       */
+      cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
+         cons->tls_ca_certdir, cons->tls_certfile,
+         cons->tls_keyfile, tls_pem_callback, &buf, NULL, true);
+
+      if (!cons->tls_ctx) {
+         display_textf(_("Failed to initialize TLS context for Console \"%s\".\n"),
+            m_dir->name());
+         return;
+      }
+   }
+
+   /* Initialize Director TLS context once */
+   if (!m_dir->tls_ctx && (m_dir->tls_enable || m_dir->tls_require)) {
+      /* Generate passphrase prompt */
+      bsnprintf(buf, sizeof(buf), "Passphrase for Director \"%s\" TLS private key: ", 
+                m_dir->name());
+
+      /* Initialize TLS context:
+       * Args: CA certfile, CA certdir, Certfile, Keyfile,
+       * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
+      m_dir->tls_ctx = new_tls_context(m_dir->tls_ca_certfile,
+                          m_dir->tls_ca_certdir, m_dir->tls_certfile,
+                          m_dir->tls_keyfile, tls_pem_callback, &buf, NULL, true);
+
+      if (!m_dir->tls_ctx) {
+         display_textf(_("Failed to initialize TLS context for Director \"%s\".\n"),
+            m_dir->name());
+         mainWin->set_status("Connection failed");
+         return;
+      }
+   }
+
    if (m_dir->heartbeat_interval) {
       heart_beat = m_dir->heartbeat_interval;
    } else if (cons) {
@@ -135,10 +209,13 @@ void Console::connect()
 
    jcr.dir_bsock = m_sock;
 
-   if (!authenticate_director(&jcr, m_dir, cons)) {
-      display_text(m_sock->msg);
+   if (!authenticate_director(&jcr, m_dir, cons, buf, sizeof(buf))) {
+      display_text(buf);
       return;
    }
+   if (buf[0]) {
+      display_text(buf);
+   }
 
    /* Give GUI a chance */
    app->processEvents();
@@ -146,23 +223,24 @@ void Console::connect()
    mainWin->set_status(_("Initializing ..."));
 
    /* Set up input notifier */
-   m_notifier = new QSocketNotifier(m_sock->fd, QSocketNotifier::Read, 0);
+   m_notifier = new QSocketNotifier(m_sock->m_fd, QSocketNotifier::Read, 0);
    QObject::connect(m_notifier, SIGNAL(activated(int)), this, SLOT(read_dir(int)));
 
    write(".api 1");
-   discardToPrompt();
+   displayToPrompt();
 
    beginNewCommand();
    dir_cmd(".jobs", job_list);
    dir_cmd(".clients", client_list);
    dir_cmd(".filesets", fileset_list);  
-   dir_cmd(".messages", messages_list);
+   dir_cmd(".msgs", messages_list);
    dir_cmd(".pools", pool_list);
    dir_cmd(".storage", storage_list);
    dir_cmd(".types", type_list);
    dir_cmd(".levels", level_list);
 
    mainWin->set_status(_("Connected"));
+   startTimer();                      /* start message timer */
    return;
 }
 
@@ -182,6 +260,7 @@ bool Console::dir_cmd(const char *cmd, QStringList &results)
    notify(false);
    write(cmd);
    while ((stat = read()) > 0) {
+      if (mainWin->m_displayAll) display_text(msg());
       strip_trailing_junk(msg());
       results << msg();
    }
@@ -201,11 +280,13 @@ bool Console::sql_cmd(QString &query, QStringList &results)
  */
 bool Console::sql_cmd(const char *query, QStringList &results)
 {
-   if (!is_connectedGui())
-      return false;
    int stat;
    POOL_MEM cmd(PM_MESSAGE);
 
+   if (!is_connectedGui()) {
+      return false;
+   }
+
    notify(false);
    
    pm_strcpy(cmd, ".sql query=\"");
@@ -213,6 +294,7 @@ bool Console::sql_cmd(const char *query, QStringList &results)
    pm_strcat(cmd, "\"");
    write(cmd.c_str());
    while ((stat = read()) > 0) {
+      if (mainWin->m_displayAll) display_text(msg());
       strip_trailing_junk(msg());
       results << msg();
    }
@@ -237,6 +319,7 @@ bool Console::get_job_defaults(struct job_defaults &job_defs)
    scmd = QString(".defaults job=\"%1\"").arg(job_defs.job_name);
    write(scmd);
    while ((stat = read()) > 0) {
+      if (mainWin->m_displayAll) display_text(msg());
       def = strchr(msg(), '=');
       if (!def) {
          continue;
@@ -293,18 +376,6 @@ bool Console::get_job_defaults(struct job_defaults &job_defs)
       }
    }
 
-#ifdef xxx
-   bsnprintf(cmd, sizeof(cmd), "job=%s pool=%s client=%s storage=%s where=%s\n"
-      "level=%s type=%s fileset=%s catalog=%s enabled=%d\n",
-      job_defs.job_name.toUtf8().data(), job_defs.pool_name.toUtf8().data(), 
-      job_defs.client_name.toUtf8().data(), 
-      job_defs.pool_name.toUtf8().data(), job_defs.messages_name.toUtf8().data(), 
-      job_defs.store_name.toUtf8().data(),
-      job_defs.where.toUtf8().data(), job_defs.level.toUtf8().data(), 
-      job_defs.type.toUtf8().data(), job_defs.fileset_name.toUtf8().data(),
-      job_defs.catalog_name.toUtf8().data(), job_defs.enabled);
-#endif
-
    notify(true);
    return true;
 
@@ -399,15 +470,21 @@ void Console::display_textf(const char *fmt, ...)
 
 void Console::display_text(const QString buf)
 {
-   m_cursor->movePosition(QTextCursor::End);
    m_cursor->insertText(buf);
+   update_cursor();
 }
 
 
 void Console::display_text(const char *buf)
 {
-   m_cursor->movePosition(QTextCursor::End);
    m_cursor->insertText(buf);
+   update_cursor();
+}
+
+void Console::display_html(const QString buf)
+{
+   m_cursor->insertHtml(buf);
+   update_cursor();
 }
 
 /* Position cursor to end of screen */
@@ -443,6 +520,7 @@ void Console::write_dir(const char *msg)
       QTreeWidgetItem *item = mainWin->getFromHash(this);
       item->setForeground(0, redBrush);
       m_at_prompt = false;
+      m_at_main_prompt = false;
    }
 }
 
@@ -453,49 +531,56 @@ int Console::write(const QString msg)
 
 int Console::write(const char *msg)
 {
+   if (!m_sock) {
+      return -1;
+   }
    m_sock->msglen = pm_strcpy(m_sock->msg, msg);
    m_at_prompt = false;
-   if (commDebug) Pmsg1(000, "send: %s\n", msg);
+   m_at_main_prompt = false;
+   if (mainWin->m_commDebug) Pmsg1(000, "send: %s\n", msg);
    return m_sock->send();
+
 }
 
 /*
- * Get to main command prompt 
+ * Get to main command prompt -- i.e. abort any subcommand
  */
 void Console::beginNewCommand()
 {
-   write(".\n");
-   while (read() > 0) {
-   }
-   write(".\n");
-   while (read() > 0) {
-   }
-   write(".\n");
-   while (read() > 0) {
+   for (int i=0; i < 3; i++) {
+      write(".");
+      while (read() > 0) {
+         if (mainWin->m_displayAll) display_text(msg());
+      }
+      if (m_at_main_prompt) {
+         break;
+      }
    }
    display_text("\n");
 }
 
 void Console::displayToPrompt()
 { 
-   int stat;
-   if (commDebug) Pmsg0(000, "DisplaytoPrompt\n");
+   int stat = 0;
+   if (mainWin->m_commDebug) Pmsg0(000, "DisplaytoPrompt\n");
    while (!m_at_prompt) {
       if ((stat=read()) > 0) {
          display_text(msg());
       }
    }
-   if (commDebug) Pmsg1(000, "endDisplaytoPrompt=%d\n", stat);
+   if (mainWin->m_commDebug) Pmsg1(000, "endDisplaytoPrompt=%d\n", stat);
 }
 
 void Console::discardToPrompt()
 { 
-   int stat;
-   if (commDebug) Pmsg0(000, "discardToPrompt\n");
+   int stat = 0;
+   if (mainWin->m_commDebug) Pmsg0(000, "discardToPrompt\n");
    while (!m_at_prompt) {
-      stat = read();
+      if ((stat=read()) > 0) {
+         if (mainWin->m_displayAll) display_text(msg());
+      }
    }
-   if (commDebug) Pmsg1(000, "endDisplayToPrompt=%d\n", stat);
+   if (mainWin->m_commDebug) Pmsg1(000, "endDisplayToPrompt=%d\n", stat);
 }
 
 
@@ -522,75 +607,87 @@ int Console::read()
          if (m_at_prompt) {
             display_text("\n");
             m_at_prompt = false;
+            m_at_main_prompt = false;
          }
-         if (commDebug) Pmsg1(000, "got: %s", m_sock->msg);
+         if (mainWin->m_commDebug) Pmsg1(000, "got: %s", m_sock->msg);
       }
       switch (m_sock->msglen) {
-      case BNET_SERVER_READY:
-         if (m_api_set && m_messages_pending) {
-            write_dir(".messages");
-            m_messages_pending = false;
-         }
-         m_at_prompt = true;
-         continue;
       case BNET_MSGS_PENDING:
-         if (commDebug) Pmsg0(000, "MSGS PENDING\n");
-         m_messages_pending = true;
+         if (mainWin->m_commDebug) Pmsg0(000, "MSGS PENDING\n");
+         write_dir(".messages");
+         displayToPrompt();
+         m_messages_pending = false;
          continue;
       case BNET_CMD_OK:
-         if (commDebug) Pmsg0(000, "CMD OK\n");
+         if (mainWin->m_commDebug) Pmsg0(000, "CMD OK\n");
          m_at_prompt = false;
+         m_at_main_prompt = false;
+         mainWin->set_status(_("Command completed ..."));
          continue;
       case BNET_CMD_BEGIN:
-         if (commDebug) Pmsg0(000, "CMD BEGIN\n");
+         if (mainWin->m_commDebug) Pmsg0(000, "CMD BEGIN\n");
          m_at_prompt = false;
+         m_at_main_prompt = false;
+         mainWin->set_status(_("Processing command ..."));
          continue;
+      case BNET_MAIN_PROMPT:
+         if (mainWin->m_commDebug) Pmsg0(000, "MAIN PROMPT\n");
+         m_at_prompt = true;
+         m_at_main_prompt = true;
+         mainWin->set_status(_("At main prompt waiting for input ..."));
+         QApplication::restoreOverrideCursor();
+         break;
       case BNET_PROMPT:
-         if (commDebug) Pmsg0(000, "PROMPT\n");
+         if (mainWin->m_commDebug) Pmsg0(000, "PROMPT\n");
          m_at_prompt = true;
+         m_at_main_prompt = false;
          mainWin->set_status(_("At prompt waiting for input ..."));
-         update_cursor();
          QApplication::restoreOverrideCursor();
          break;
       case BNET_CMD_FAILED:
-         if (commDebug) Pmsg0(000, "CMD FAIL\n");
-         mainWin->set_status(_("Command failed. At prompt waiting for input ..."));
-         update_cursor();
+         if (mainWin->m_commDebug) Pmsg0(000, "CMD FAILED\n");
+         mainWin->set_status(_("Command failed."));
          QApplication::restoreOverrideCursor();
          break;
       /* We should not get this one */
       case BNET_EOD:
-         if (commDebug) Pmsg0(000, "EOD\n");
+         if (mainWin->m_commDebug) Pmsg0(000, "EOD\n");
          mainWin->set_status_ready();
-         update_cursor();
          QApplication::restoreOverrideCursor();
          if (!m_api_set) {
             break;
          }
          continue;
       case BNET_START_SELECT:
+         if (mainWin->m_commDebug) Pmsg0(000, "START SELECT\n");
          new selectDialog(this);    
          break;
       case BNET_RUN_CMD:
-         new runCmdDialog(this);
+         if (mainWin->m_commDebug) Pmsg0(000, "RUN CMD\n");
+         new runCmdPage();
          break;
       case BNET_ERROR_MSG:
+         if (mainWin->m_commDebug) Pmsg0(000, "ERROR MSG\n");
          m_sock->recv();              /* get the message */
          display_text(msg());
          QMessageBox::critical(this, "Error", msg(), QMessageBox::Ok);
          break;
       case BNET_WARNING_MSG:
+         if (mainWin->m_commDebug) Pmsg0(000, "WARNING MSG\n");
          m_sock->recv();              /* get the message */
          display_text(msg());
          QMessageBox::critical(this, "Warning", msg(), QMessageBox::Ok);
          break;
       case BNET_INFO_MSG:
+         if (mainWin->m_commDebug) Pmsg0(000, "INFO MSG\n");
          m_sock->recv();              /* get the message */
          display_text(msg());
          mainWin->set_status(msg());
          break;
       }
       if (is_bnet_stop(m_sock)) {         /* error or term request */
+         if (mainWin->m_commDebug) Pmsg0(000, "BNET STOP\n");
+         stopTimer();
          m_sock->close();
          m_sock = NULL;
          mainWin->actionConnect->setIcon(QIcon(":images/disconnected.png"));
@@ -610,13 +707,10 @@ int Console::read()
 }
 
 /* Called by signal when the Director has output for us */
-void Console::read_dir(int fd)
+void Console::read_dir(int /* fd */)
 {
-   int stat;
-   (void)fd;
-
-   if (commDebug) Pmsg0(000, "read_dir\n");
-   while ((stat = read()) >= 0) {
+   if (mainWin->m_commDebug) Pmsg0(000, "read_dir\n");
+   while (read() >= 0) {
       display_text(msg());
    }
 }
@@ -659,11 +753,90 @@ bool Console::is_connectedGui()
    if (is_connected()) {
       return true;
    } else {
+      QString message("Director ");
+      message += " is currently disconnected\n  Please reconnect!!";
+      QMessageBox::warning(this, "Bat",
+         tr(message.toUtf8().data()), QMessageBox::Ok );
+      return false;
+   }
+}
+
+/*
+ * A temporary function to prevent connecting to the director if the director
+ * is busy with a restore.
+ */
+bool Console::preventInUseConnect()
+{
+   if (!is_connected()) {
+      QString message("Director ");
+      message += m_dir->name();
+      message += " is currently disconnected\n  Please reconnect!!";
+      QMessageBox::warning(this, "Bat",
+         tr(message.toUtf8().data()), QMessageBox::Ok );
+      return false;
+   } else if (!m_at_main_prompt){
+      QString message("Director ");
+      message += m_dir->name();
+      message += " is currently busy\n  Please complete restore or other "
+                 " operation !!  This is a limitation that will be resolved before a beta"
+                 " release.  This is currently an alpha release.";
+      QMessageBox::warning(this, "Bat",
+         tr(message.toUtf8().data()), QMessageBox::Ok );
+      return false;
+   } else if (!m_at_prompt){
       QString message("Director ");
       message += m_dir->name();
-      message += " is curerntly disconnected\n  Please reconnect!!";
-      QMessageBox::warning(this, tr("Bat"),
+      message += " is currently not at a prompt\n  Please try again!!";
+      QMessageBox::warning(this, "Bat",
          tr(message.toUtf8().data()), QMessageBox::Ok );
       return false;
+   } else {
+      return true;
    }
 }
+
+/*
+ * Call-back for reading a passphrase for an encrypted PEM file
+ * This function uses getpass(), 
+ *  which uses a static buffer and is NOT thread-safe.
+ */
+static int tls_pem_callback(char *buf, int size, const void *userdata)
+{
+   (void)size;
+   (void)userdata;
+#ifdef HAVE_TLS
+   const char *prompt = (const char *)userdata;
+# if defined(HAVE_WIN32)
+   sendit(prompt);
+   if (win32_cgets(buf, size) == NULL) {
+      buf[0] = 0;
+      return 0;
+   } else {
+      return strlen(buf);
+   }
+# else
+   char *passwd;
+
+   passwd = getpass(prompt);
+   bstrncpy(buf, passwd, size);
+   return strlen(buf);
+# endif
+#else
+   buf[0] = 0;
+   return 0;
+#endif
+}
+
+/* Slot for responding to page selectors status help command */
+void Console::consoleHelp()
+{
+   QString cmd("help");
+   consoleCommand(cmd);
+}
+
+/* Slot for responding to page selectors reload bacula-dir.conf */
+void Console::consoleReload()
+{
+   QString cmd("reload");
+   consoleCommand(cmd);
+}