2 Bacula® - The Network Backup Solution
4 Copyright (C) 2000-2010 Free Software Foundation Europe e.V.
6 The main author of Bacula is Kern Sibbald, with contributions from
7 many others, a complete list can be found in the file AUTHORS.
8 This program is Free Software; you can redistribute it and/or
9 modify it under the terms of version three of the GNU Affero General Public
10 License as published by the Free Software Foundation and included
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU Affero General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23 Bacula® is a registered trademark of Kern Sibbald.
24 The licensor of Bacula is the Free Software Foundation Europe
25 (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26 Switzerland, email:ftf@fsfeurope.org.
30 * Bacula Console interface to the Director
32 * Kern Sibbald, September MM
37 #include "console_conf.h"
47 #define con_set_zed_keys();
53 #if defined(HAVE_WIN32)
54 #define isatty(fd) (fd==0)
57 /* Exported variables */
59 //extern int rl_catch_signals;
61 /* Imported functions */
62 int authenticate_director(JCR *jcr, DIRRES *director, CONRES *cons);
63 extern bool parse_cons_config(CONFIG *config, const char *configfile, int exit_code);
65 /* Forward referenced functions */
66 static void terminate_console(int sig);
67 static int check_resources();
68 int get_cmd(FILE *input, const char *prompt, BSOCK *sock, int sec);
69 static int do_outputcmd(FILE *input, BSOCK *UA_sock);
70 void senditf(const char *fmt, ...);
71 void sendit(const char *buf);
73 extern "C" void got_sigstop(int sig);
74 extern "C" void got_sigcontinue(int sig);
75 extern "C" void got_sigtout(int sig);
76 extern "C" void got_sigtin(int sig);
79 /* Static variables */
80 static char *configfile = NULL;
81 static BSOCK *UA_sock = NULL;
82 static DIRRES *dir = NULL;
83 static CONRES *cons = NULL;
84 static FILE *output = stdout;
85 static bool teeout = false; /* output to output and stdout */
86 static bool stop = false;
87 static bool no_conio = false;
88 static int timeout = 0;
92 static char *argk[MAX_CMD_ARGS];
93 static char *argv[MAX_CMD_ARGS];
94 static CONFIG *config;
97 /* Command prototypes */
98 static int versioncmd(FILE *input, BSOCK *UA_sock);
99 static int inputcmd(FILE *input, BSOCK *UA_sock);
100 static int outputcmd(FILE *input, BSOCK *UA_sock);
101 static int teecmd(FILE *input, BSOCK *UA_sock);
102 static int quitcmd(FILE *input, BSOCK *UA_sock);
103 static int helpcmd(FILE *input, BSOCK *UA_sock);
104 static int echocmd(FILE *input, BSOCK *UA_sock);
105 static int timecmd(FILE *input, BSOCK *UA_sock);
106 static int sleepcmd(FILE *input, BSOCK *UA_sock);
107 static int execcmd(FILE *input, BSOCK *UA_sock);
109 static int eolcmd(FILE *input, BSOCK *UA_sock);
111 # ifndef HAVE_REGEX_H
112 # include "lib/bregex.h"
120 #define CONFIG_FILE "bconsole.conf" /* default configuration file */
126 "\nVersion: " VERSION " (" BDATE ") %s %s %s\n\n"
127 "Usage: bconsole [-s] [-c config_file] [-d debug_level]\n"
128 " -D <dir> select a Director\n"
129 " -l list Directors defined\n"
130 " -c <file> set configuration file to file\n"
131 " -d <nn> set debug level to <nn>\n"
132 " -dt print timestamp in debug output\n"
135 " -u <nn> set command execution timeout to <nn> seconds\n"
136 " -t test - read configuration and exit\n"
137 " -? print this message.\n"
138 "\n"), 2000, HOST_OS, DISTNAME, DISTVER);
143 void got_sigstop(int sig)
149 void got_sigcontinue(int sig)
155 void got_sigtout(int sig)
157 // printf("Got tout\n");
161 void got_sigtin(int sig)
163 // printf("Got tin\n");
167 static int zed_keyscmd(FILE *input, BSOCK *UA_sock)
174 * These are the @command
176 struct cmdstruct { const char *key; int (*func)(FILE *input, BSOCK *UA_sock); const char *help; };
177 static struct cmdstruct commands[] = {
178 { N_("input"), inputcmd, _("input from file")},
179 { N_("output"), outputcmd, _("output to file")},
180 { N_("quit"), quitcmd, _("quit")},
181 { N_("tee"), teecmd, _("output to file and terminal")},
182 { N_("sleep"), sleepcmd, _("sleep specified time")},
183 { N_("time"), timecmd, _("print current time")},
184 { N_("version"), versioncmd, _("print Console's version")},
185 { N_("echo"), echocmd, _("echo command string")},
186 { N_("exec"), execcmd, _("execute an external command")},
187 { N_("exit"), quitcmd, _("exit = quit")},
188 { N_("zed_keys"), zed_keyscmd, _("zed_keys = use zed keys instead of bash keys")},
189 { N_("help"), helpcmd, _("help listing")},
191 { N_("separator"), eolcmd, _("set command separator")},
194 #define comsize ((int)(sizeof(commands)/sizeof(struct cmdstruct)))
196 static int do_a_command(FILE *input, BSOCK *UA_sock)
207 Dmsg1(120, "Command: %s\n", UA_sock->msg);
213 if (*cmd == '#') { /* comment */
217 for (i=0; i<comsize; i++) { /* search for command */
218 if (strncasecmp(cmd, _(commands[i].key), len) == 0) {
219 stat = (*commands[i].func)(input, UA_sock); /* go execute command */
225 pm_strcat(&UA_sock->msg, _(": is an invalid command\n"));
226 UA_sock->msglen = strlen(UA_sock->msg);
227 sendit(UA_sock->msg);
233 static void read_and_process_input(FILE *input, BSOCK *UA_sock)
235 const char *prompt = "*";
236 bool at_prompt = false;
237 int tty_input = isatty(fileno(input));
242 if (at_prompt) { /* don't prompt multiple times */
249 stat = get_cmd(input, prompt, UA_sock, 30);
257 /* Reading input from a file */
258 int len = sizeof_pool_memory(UA_sock->msg) - 1;
262 if (fgets(UA_sock->msg, len, input) == NULL) {
265 sendit(UA_sock->msg); /* echo to terminal */
266 strip_trailing_junk(UA_sock->msg);
267 UA_sock->msglen = strlen(UA_sock->msg);
272 break; /* error or interrupt */
273 } else if (stat == 0) { /* timeout */
274 if (strcmp(prompt, "*") == 0) {
275 tid = start_bsock_timer(UA_sock, timeout);
276 UA_sock->fsend(".messages");
277 stop_bsock_timer(tid);
283 /* @ => internal command for us */
284 if (UA_sock->msg[0] == '@') {
285 parse_args(UA_sock->msg, &args, &argc, argk, argv, MAX_CMD_ARGS);
286 if (!do_a_command(input, UA_sock)) {
291 tid = start_bsock_timer(UA_sock, timeout);
292 if (!UA_sock->send()) { /* send command */
293 stop_bsock_timer(tid);
296 stop_bsock_timer(tid);
298 if (strcmp(UA_sock->msg, ".quit") == 0 || strcmp(UA_sock->msg, ".exit") == 0) {
301 tid = start_bsock_timer(UA_sock, timeout);
302 while ((stat = UA_sock->recv()) >= 0) {
309 /* Suppress output if running in background or user hit ctl-c */
310 if (!stop && !usrbrk()) {
311 sendit(UA_sock->msg);
314 stop_bsock_timer(tid);
323 if (is_bnet_stop(UA_sock)) {
324 break; /* error or term */
325 } else if (stat == BNET_SIGNAL) {
326 if (UA_sock->msglen == BNET_SUB_PROMPT) {
329 Dmsg1(100, "Got poll %s\n", bnet_sig_to_ascii(UA_sock));
335 * Call-back for reading a passphrase for an encrypted PEM file
336 * This function uses getpass(),
337 * which uses a static buffer and is NOT thread-safe.
339 static int tls_pem_callback(char *buf, int size, const void *userdata)
342 const char *prompt = (const char *)userdata;
343 # if defined(HAVE_WIN32)
345 if (win32_cgets(buf, size) == NULL) {
354 passwd = getpass(prompt);
355 bstrncpy(buf, passwd, size);
365 #define READLINE_LIBRARY 1
366 #include "readline.h"
369 /* Get the first keyword of the line */
375 char *first_space = strchr(rl_line_buffer, ' ');
377 len = first_space - rl_line_buffer;
378 ret = (char *) malloc((len + 1) * sizeof(char));
379 memcpy(ret, rl_line_buffer, len);
386 * Return the command before the current point.
387 * Set nb to the number of command to skip
390 get_previous_keyword(int current_point, int nb)
392 int i, end=-1, start, inquotes=0;
396 /* first we look for a space before the current word */
397 for (i = current_point; i >= 0; i--) {
398 if (rl_line_buffer[i] == ' ' || rl_line_buffer[i] == '=') {
403 /* find the end of the command */
404 for (; i >= 0; i--) {
405 if (rl_line_buffer[i] != ' ') {
411 /* no end of string */
416 /* look for the start of the command */
417 for (start = end; start > 0; start--) {
418 if (rl_line_buffer[start] == '"') {
419 inquotes = !inquotes;
421 if ((rl_line_buffer[start - 1] == ' ') && inquotes == 0) {
424 current_point = start;
428 s = (char *)malloc(end - start + 2);
429 memcpy(s, rl_line_buffer + start, end - start + 1);
430 s[end - start + 1] = 0;
432 // printf("=======> %i:%i <%s>\n", start, end, s);
437 /* Simple structure that will contain the completion list */
442 static ItemList *items = NULL;
446 items = (ItemList*) malloc(sizeof(ItemList));
447 memset(items, 0, sizeof(ItemList));
450 items->list.destroy();
456 /* Match a regexp and add the result to the items list
457 * This function is recursive
459 static void match_kw(regex_t *preg, const char *what, int len, POOLMEM **buf)
463 regmatch_t pmatch[20];
468 rc = regexec(preg, what, nmatch, pmatch, 0);
471 Pmsg1(0, "\n\n%s\n0123456789012345678901234567890123456789\n 10 20 30\n", what);
472 Pmsg2(0, "%i-%i\n", pmatch[0].rm_so, pmatch[0].rm_eo);
473 Pmsg2(0, "%i-%i\n", pmatch[1].rm_so, pmatch[1].rm_eo);
474 Pmsg2(0, "%i-%i\n", pmatch[2].rm_so, pmatch[2].rm_eo);
475 Pmsg2(0, "%i-%i\n", pmatch[3].rm_so, pmatch[3].rm_eo);
477 size = pmatch[1].rm_eo - pmatch[1].rm_so;
478 *buf = check_pool_memory_size(*buf, size + 1);
479 memcpy(*buf, what+pmatch[1].rm_so, size);
482 items->list.append(bstrdup(*buf));
483 /* We search for the next keyword in the line */
484 match_kw(preg, what + pmatch[1].rm_eo, len - pmatch[1].rm_eo, buf);
488 /* fill the items list with the output of the help command */
489 void get_arguments(const char *what)
496 rc = regcomp(&preg, "(([a-z]+=)|([a-z]+)( |$))", REG_EXTENDED);
501 buf = get_pool_memory(PM_MESSAGE);
502 UA_sock->fsend(".help item=%s", what);
503 while (UA_sock->recv() > 0) {
504 strip_trailing_junk(UA_sock->msg);
505 match_kw(&preg, UA_sock->msg, UA_sock->msglen, &buf);
507 free_pool_memory(buf);
511 /* retreive a simple list (.pool, .client) and store it into items */
512 void get_items(const char *what)
516 UA_sock->fsend("%s", what);
517 while (UA_sock->recv() > 0) {
518 strip_trailing_junk(UA_sock->msg);
519 items->list.append(bstrdup(UA_sock->msg));
525 ITEM_ARG, /* item with simple list like .job */
526 ITEM_HELP /* use help item=xxx and detect all arguments */
529 /* Generator function for command completion. STATE lets us know whether
530 * to start from scratch; without any state (i.e. STATE == 0), then we
531 * start at the top of the list.
533 static char *item_generator(const char *text, int state,
534 const char *item, cpl_item_t type)
536 static int list_index, len;
539 /* If this is a new word to complete, initialize now. This includes
540 * saving the length of TEXT for efficiency, and initializing the index
557 /* Return the next name which partially matches from the command list. */
558 while (items && list_index < items->list.size())
560 name = (char *)items->list[list_index];
563 if (strncmp(name, text, len) == 0) {
564 char *ret = (char *) actuallymalloc(strlen(name)+1);
570 /* If no names matched, then return NULL. */
571 return ((char *)NULL);
574 /* gobal variables for the type and the item to search
575 * the readline API doesn' permit to pass user data.
577 static const char *cpl_item;
578 static cpl_item_t cpl_type;
580 static char *cpl_generator(const char *text, int state)
582 return item_generator(text, state, cpl_item, cpl_type);
585 /* this function is used to not use the default filename completion */
586 static char *dummy_completion_function(const char *text, int state)
591 struct cpl_keywords_t {
596 static struct cpl_keywords_t cpl_keywords[] = {
598 {"fileset=", ".fileset" },
599 {"client=", ".client" },
601 {"level=", ".level" },
602 {"storage=", ".storage" },
603 {"schedule=", ".schedule" },
604 {"volume=", ".media" },
605 {"oldvolume=", ".media" },
606 {"volstatus=", ".volstatus" },
611 {"unmark", ".lsmark" },
612 {"actiononpurge=", ".actiononpurge" }
614 #define key_size ((int)(sizeof(cpl_keywords)/sizeof(struct cpl_keywords_t)))
616 /* Attempt to complete on the contents of TEXT. START and END bound the
617 * region of rl_line_buffer that contains the word to complete. TEXT is
618 * the word to complete. We can use the entire contents of rl_line_buffer
619 * in case we want to do some simple parsing. Return the array of matches,
620 * or NULL if there aren't any.
622 static char **readline_completion(const char *text, int start, int end)
627 matches = (char **)NULL;
629 /* If this word is at the start of the line, then it is a command
630 * to complete. Otherwise it is the name of a file in the current
633 s = get_previous_keyword(start, 0);
634 cmd = get_first_keyword();
636 for (int i=0; i < key_size; i++) {
637 if (!strcasecmp(s, cpl_keywords[i].key)) {
638 cpl_item = cpl_keywords[i].cmd;
640 matches = rl_completion_matches(text, cpl_generator);
646 if (!found) { /* we try to get help with the first command */
648 cpl_type = ITEM_HELP;
649 /* we don't want to append " " at the end */
650 rl_completion_suppress_append=true;
651 matches = rl_completion_matches(text, cpl_generator);
654 } else { /* nothing on the line, display all commands */
655 cpl_item = ".help all";
657 matches = rl_completion_matches(text, cpl_generator);
665 static char eol = '\0';
666 static int eolcmd(FILE *input, BSOCK *UA_sock)
668 if ((argc > 1) && (strchr("!$%&'()*+,-/:;<>?[]^`{|}~", argk[1][0]) != NULL)) {
670 } else if (argc == 1) {
673 sendit(_("Illegal separator character.\n"));
679 get_cmd(FILE *input, const char *prompt, BSOCK *sock, int sec)
681 static char *line = NULL;
682 static char *next = NULL;
683 static int do_history = 0;
688 rl_catch_signals = 0; /* do it ourselves */
689 /* Here, readline does ***real*** malloc
690 * so, be we have to use the real free
692 line = readline((char *)prompt); /* cast needed for old readlines */
696 strip_trailing_junk(line);
701 sendit(_("Command logic problem\n"));
708 * Split "line" into multiple commands separated by the eol character.
709 * Each part is pointed to by "next" until finally it becomes null.
714 next = strchr(command, eol);
719 if (command != line && isatty(fileno(input))) {
720 senditf("%s%s\n", prompt, command);
723 sock->msglen = pm_strcpy(&sock->msg, command);
732 actuallyfree(line); /* allocated by readline() malloc */
738 #else /* no readline, do it ourselves */
741 static bool bisatty(int fd)
751 * Returns: 1 if data available
756 wait_for_data(int fd, int sec)
758 #if defined(HAVE_WIN32)
768 FD_SET((unsigned)fd, &fdset);
769 switch(select(fd + 1, &fdset, NULL, NULL, &tv)) {
770 case 0: /* timeout */
773 if (errno == EINTR || errno == EAGAIN) {
776 return -1; /* error return */
785 * Get next input command from terminal.
787 * Returns: 1 if got input
792 get_cmd(FILE *input, const char *prompt, BSOCK *sock, int sec)
796 if (output == stdout || teeout) {
801 switch (wait_for_data(fileno(input), sec)) {
803 return 0; /* timeout */
805 return -1; /* error */
807 len = sizeof_pool_memory(sock->msg) - 1;
813 if (bisatty(fileno(input))) {
814 input_line(sock->msg, len);
818 #ifdef HAVE_WIN32 /* use special console for input on win32 */
819 if (input == stdin) {
820 if (win32_cgets(sock->msg, len) == NULL) {
826 if (fgets(sock->msg, len, input) == NULL) {
835 strip_trailing_junk(sock->msg);
836 sock->msglen = strlen(sock->msg);
840 #endif /* ! HAVE_READLINE */
843 static int console_update_history(const char *histfile)
848 /* first, try to truncate the history file, and if it
849 * fail, the file is probably not present, and we
850 * can use write_history to create it
853 if (history_truncate_file(histfile, 100) == 0) {
854 ret = append_history(history_length, histfile);
856 ret = write_history(histfile);
864 static int console_init_history(const char *histfile)
871 ret = read_history(histfile);
872 /* Tell the completer that we want a complete . */
873 rl_completion_entry_function = dummy_completion_function;
874 rl_attempted_completion_function = readline_completion;
875 rl_filename_completion_desired = 0;
882 bool select_director(const char *director, DIRRES **ret_dir, CONRES **ret_cons)
884 int numcon=0, numdir=0;
889 struct sockaddr client_addr;
890 memset(&client_addr, 0, sizeof(client_addr));
897 foreach_res(dir, R_DIRECTOR) {
901 foreach_res(cons, R_CONSOLE) {
906 if (numdir == 1) { /* No choose */
907 dir = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
910 if (director) { /* Command line choice overwrite the no choose option */
912 foreach_res(dir, R_DIRECTOR) {
913 if (bstrcmp(dir->hdr.name, director)) {
918 if (!dir) { /* Can't find Director used as argument */
919 senditf(_("Can't find %s in Director list\n"), director);
924 if (!dir) { /* prompt for director */
925 UA_sock = init_bsock(NULL, 0, "", "", 0, &client_addr);
927 sendit(_("Available Directors:\n"));
930 foreach_res(dir, R_DIRECTOR) {
931 senditf( _("%2d: %s at %s:%d\n"), 1+numdir++, dir->hdr.name,
932 dir->address, dir->DIRport);
935 if (get_cmd(stdin, _("Select Director by entering a number: "),
938 (void)WSACleanup(); /* Cleanup Windows sockets */
941 if (!is_a_number(UA_sock->msg)) {
942 senditf(_("%s is not a number. You must enter a number between "
944 UA_sock->msg, numdir);
947 item = atoi(UA_sock->msg);
948 if (item < 0 || item > numdir) {
949 senditf(_("You must enter a number between 1 and %d\n"), numdir);
954 for (i=0; i<item; i++) {
955 dir = (DIRRES *)GetNextRes(R_DIRECTOR, (RES *)dir);
960 /* Look for a console linked to this director */
961 for (i=0; i<numcon; i++) {
962 cons = (CONRES *)GetNextRes(R_CONSOLE, (RES *)cons);
963 if (cons->director && strcmp(cons->director, dir->hdr.name) == 0) {
968 /* Look for the first non-linked console */
970 for (i=0; i<numcon; i++) {
971 cons = (CONRES *)GetNextRes(R_CONSOLE, (RES *)cons);
972 if (cons->director == NULL)
978 /* If no console, take first one */
980 cons = (CONRES *)GetNextRes(R_CONSOLE, (RES *)NULL);
990 /*********************************************************************
992 * Main Bacula Console -- User Interface Program
995 int main(int argc, char *argv[])
999 bool list_directors=false;
1000 bool no_signals = false;
1001 bool test_config = false;
1005 setlocale(LC_ALL, "");
1006 bindtextdomain("bacula", LOCALEDIR);
1007 textdomain("bacula");
1011 my_name_is(argc, argv, "bconsole");
1012 init_msg(NULL, NULL);
1013 working_directory = "/tmp";
1014 args = get_pool_memory(PM_FNAME);
1016 while ((ch = getopt(argc, argv, "D:lbc:d:nstu:?")) != -1) {
1018 case 'D': /* Director */
1022 director = bstrdup(optarg);
1026 list_directors = true;
1030 case 'c': /* configuration file */
1031 if (configfile != NULL) {
1034 configfile = bstrdup(optarg);
1038 if (*optarg == 't') {
1039 dbg_timestamp = true;
1041 debug_level = atoi(optarg);
1042 if (debug_level <= 0) {
1048 case 'n': /* no conio */
1052 case 's': /* turn off signals */
1061 timeout = atoi(optarg);
1074 init_signals(terminate_console);
1078 #if !defined(HAVE_WIN32)
1079 /* Override Bacula default signals */
1080 signal(SIGQUIT, SIG_IGN);
1081 signal(SIGTSTP, got_sigstop);
1082 signal(SIGCONT, got_sigcontinue);
1083 signal(SIGTTIN, got_sigtin);
1084 signal(SIGTTOU, got_sigtout);
1095 if (configfile == NULL) {
1096 configfile = bstrdup(CONFIG_FILE);
1099 config = new_config_parser();
1100 parse_cons_config(config, configfile, M_ERROR_TERM);
1102 if (init_crypto() != 0) {
1103 Emsg0(M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
1106 if (!check_resources()) {
1107 Emsg1(M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
1114 if (list_directors) {
1116 foreach_res(dir, R_DIRECTOR) {
1117 senditf("%s\n", dir->hdr.name);
1123 terminate_console(0);
1127 memset(&jcr, 0, sizeof(jcr));
1129 (void)WSA_Init(); /* Initialize Windows sockets */
1131 start_watchdog(); /* Start socket watchdog */
1133 if(!select_director(director, &dir, &cons)) {
1137 senditf(_("Connecting to Director %s:%d\n"), dir->address,dir->DIRport);
1140 /* Initialize Console TLS context */
1141 if (cons && (cons->tls_enable || cons->tls_require)) {
1142 /* Generate passphrase prompt */
1143 bsnprintf(buf, sizeof(buf), "Passphrase for Console \"%s\" TLS private key: ", cons->hdr.name);
1145 /* Initialize TLS context:
1146 * Args: CA certfile, CA certdir, Certfile, Keyfile,
1147 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer
1149 cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
1150 cons->tls_ca_certdir, cons->tls_certfile,
1151 cons->tls_keyfile, tls_pem_callback, &buf, NULL, true);
1153 if (!cons->tls_ctx) {
1154 senditf(_("Failed to initialize TLS context for Console \"%s\".\n"),
1156 terminate_console(0);
1161 /* Initialize Director TLS context */
1162 if (dir->tls_enable || dir->tls_require) {
1163 /* Generate passphrase prompt */
1164 bsnprintf(buf, sizeof(buf), "Passphrase for Director \"%s\" TLS private key: ", dir->hdr.name);
1166 /* Initialize TLS context:
1167 * Args: CA certfile, CA certdir, Certfile, Keyfile,
1168 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1169 dir->tls_ctx = new_tls_context(dir->tls_ca_certfile,
1170 dir->tls_ca_certdir, dir->tls_certfile,
1171 dir->tls_keyfile, tls_pem_callback, &buf, NULL, true);
1173 if (!dir->tls_ctx) {
1174 senditf(_("Failed to initialize TLS context for Director \"%s\".\n"),
1176 terminate_console(0);
1181 if (dir->heartbeat_interval) {
1182 heart_beat = dir->heartbeat_interval;
1184 heart_beat = cons->heartbeat_interval;
1188 UA_sock = bnet_connect(NULL, 5, 15, heart_beat, "Director daemon", dir->address,
1189 NULL, dir->DIRport, 0);
1190 if (UA_sock == NULL) {
1191 terminate_console(0);
1194 jcr.dir_bsock = UA_sock;
1196 /* If cons==NULL, default console will be used */
1197 if (!authenticate_director(&jcr, dir, cons)) {
1198 terminate_console(0);
1202 Dmsg0(40, "Opened connection with Director daemon\n");
1204 sendit(_("Enter a period to cancel a command.\n"));
1206 /* Read/Update history file if HOME exists */
1207 POOL_MEM history_file;
1209 /* Run commands in ~/.bconsolerc if any */
1210 char *env = getenv("HOME");
1213 pm_strcpy(&UA_sock->msg, env);
1214 pm_strcat(&UA_sock->msg, "/.bconsolerc");
1215 fd = fopen(UA_sock->msg, "rb");
1217 read_and_process_input(fd, UA_sock);
1221 pm_strcpy(history_file, env);
1222 pm_strcat(history_file, "/.bconsole_history");
1223 console_init_history(history_file.c_str());
1226 read_and_process_input(stdin, UA_sock);
1229 UA_sock->signal(BNET_TERMINATE); /* send EOF */
1234 console_update_history(history_file.c_str());
1237 terminate_console(0);
1241 /* Cleanup and then exit */
1242 static void terminate_console(int sig)
1245 static bool already_here = false;
1247 if (already_here) { /* avoid recursive temination problems */
1250 already_here = true;
1252 config->free_resources();
1256 free_pool_memory(args);
1260 (void)WSACleanup(); /* Cleanup Windows sockets */
1261 lmgr_cleanup_main();
1270 * Make a quick check to see that we have all the
1273 static int check_resources()
1282 foreach_res(director, R_DIRECTOR) {
1285 /* tls_require implies tls_enable */
1286 if (director->tls_require) {
1288 director->tls_enable = true;
1290 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1295 tls_needed = director->tls_enable || director->tls_authenticate;
1297 if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && tls_needed) {
1298 Emsg2(M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1299 " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
1300 " At least one CA certificate store is required.\n"),
1301 director->hdr.name, configfile);
1307 Emsg1(M_FATAL, 0, _("No Director resource defined in %s\n"
1308 "Without that I don't how to speak to the Director :-(\n"), configfile);
1313 /* Loop over Consoles */
1314 foreach_res(cons, R_CONSOLE) {
1315 /* tls_require implies tls_enable */
1316 if (cons->tls_require) {
1318 cons->tls_enable = true;
1320 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1325 tls_needed = cons->tls_enable || cons->tls_authenticate;
1326 if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir) && tls_needed) {
1327 Emsg2(M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1328 " or \"TLS CA Certificate Dir\" are defined for Console \"%s\" in %s.\n"),
1329 cons->hdr.name, configfile);
1339 static int versioncmd(FILE *input, BSOCK *UA_sock)
1341 senditf("Version: " VERSION " (" BDATE ") %s %s %s\n",
1342 HOST_OS, DISTNAME, DISTVER);
1346 static int inputcmd(FILE *input, BSOCK *UA_sock)
1351 sendit(_("Too many arguments on input command.\n"));
1355 sendit(_("First argument to input command must be a filename.\n"));
1358 fd = fopen(argk[1], "rb");
1361 senditf(_("Cannot open file %s for input. ERR=%s\n"),
1362 argk[1], be.bstrerror());
1365 read_and_process_input(fd, UA_sock);
1370 /* Send output to both termina and specified file */
1371 static int teecmd(FILE *input, BSOCK *UA_sock)
1374 return do_outputcmd(input, UA_sock);
1377 /* Send output to specified "file" */
1378 static int outputcmd(FILE *input, BSOCK *UA_sock)
1381 return do_outputcmd(input, UA_sock);
1385 static int do_outputcmd(FILE *input, BSOCK *UA_sock)
1388 const char *mode = "a+b";
1391 sendit(_("Too many arguments on output/tee command.\n"));
1395 if (output != stdout) {
1405 fd = fopen(argk[1], mode);
1408 senditf(_("Cannot open file %s for output. ERR=%s\n"),
1409 argk[1], be.bstrerror(errno));
1417 * exec "some-command" [wait-seconds]
1419 static int execcmd(FILE *input, BSOCK *UA_sock)
1427 sendit(_("Too many arguments. Enclose command in double quotes.\n"));
1431 wait = atoi(argk[2]);
1433 bpipe = open_bpipe(argk[1], wait, "r");
1436 senditf(_("Cannot popen(\"%s\", \"r\"): ERR=%s\n"),
1437 argk[1], be.bstrerror(errno));
1441 while (fgets(line, sizeof(line), bpipe->rfd)) {
1442 senditf("%s", line);
1444 stat = close_bpipe(bpipe);
1448 senditf(_("Autochanger error: ERR=%s\n"), be.bstrerror());
1454 static int echocmd(FILE *input, BSOCK *UA_sock)
1456 for (int i=1; i < argc; i++) {
1457 senditf("%s ", argk[i]);
1463 static int quitcmd(FILE *input, BSOCK *UA_sock)
1468 static int helpcmd(FILE *input, BSOCK *UA_sock)
1471 for (i=0; i<comsize; i++) {
1472 senditf(" %-10s %s\n", commands[i].key, commands[i].help);
1478 static int sleepcmd(FILE *input, BSOCK *UA_sock)
1481 sleep(atoi(argk[1]));
1487 static int timecmd(FILE *input, BSOCK *UA_sock)
1490 time_t ttime = time(NULL);
1492 (void)localtime_r(&ttime, &tm);
1493 strftime(sdt, sizeof(sdt), "%d-%b-%Y %H:%M:%S", &tm);
1499 * Send a line to the output file and or the terminal
1501 void senditf(const char *fmt,...)
1506 va_start(arg_ptr, fmt);
1507 bvsnprintf(buf, sizeof(buf), (char *)fmt, arg_ptr);
1512 void sendit(const char *buf)
1516 if (output == stdout || teeout) {
1519 * Here, we convert every \n into \r\n because the
1520 * terminal is in raw mode when we are using
1523 for (p=q=buf; (p=strchr(q, '\n')); ) {
1526 memcpy(obuf, q, len);
1528 memcpy(obuf+len, "\r\n", 3);
1529 q = ++p; /* point after \n */
1530 fputs(obuf, output);
1537 if (output != stdout) {