]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/console/console.c
BFILE I/O, new console @ commands, regression, file mode restore fixes
[bacula/bacula] / bacula / src / console / console.c
1 /*
2  *
3  *   Bacula Console interface to the Director
4  *
5  *     Kern Sibbald, September MM
6  *
7  *     Version $Id$
8  */
9
10 /*
11    Copyright (C) 2000, 2001 Kern Sibbald and John Walker
12
13    This program is free software; you can redistribute it and/or
14    modify it under the terms of the GNU General Public License
15    as published by the Free Software Foundation; either version 2
16    of the License, or (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21    GNU General Public License for more details.
22
23    You should have received a copy of the GNU General Public License
24    along with this program; if not, write to the Free Software
25    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
26  */
27
28 #include "bacula.h"
29 #include "console_conf.h"
30 #include "jcr.h"
31  
32 /* Imported functions */
33 int authenticate_director(JCR *jcr, DIRRES *director);
34
35        
36 /* Exported variables */
37
38
39 #ifdef HAVE_CYGWIN
40 int rl_catch_signals;
41 #else
42 extern int rl_catch_signals;
43 #endif
44
45 /* Forward referenced functions */
46 static void terminate_console(int sig);
47 int get_cmd(FILE *input, char *prompt, BSOCK *sock, int sec);
48 static int do_outputcmd(FILE *input, BSOCK *UA_sock);
49 static void sendit(char *fmt, ...);
50
51 /* Static variables */
52 static char *configfile = NULL;
53 static BSOCK *UA_sock = NULL;
54 static DIRRES *dir; 
55 static FILE *output = stdout;
56 int tee = 0;                          /* output to output and stdout */
57 static int stop = FALSE;
58 static int argc;
59 static POOLMEM *args;
60 static char *argk[MAX_CMD_ARGS];
61 static char *argv[MAX_CMD_ARGS];
62
63 /* Command prototypes */
64 static int versioncmd(FILE *input, BSOCK *UA_sock);
65 static int inputcmd(FILE *input, BSOCK *UA_sock);
66 static int outputcmd(FILE *input, BSOCK *UA_sock);
67 static int teecmd(FILE *input, BSOCK *UA_sock);
68 static int quitcmd(FILE *input, BSOCK *UA_sock);
69 static int timecmd(FILE *input, BSOCK *UA_sock);
70 static int sleepcmd(FILE *input, BSOCK *UA_sock);
71
72
73 #define CONFIG_FILE "./console.conf"   /* default configuration file */
74
75 static void usage()
76 {
77    fprintf(stderr,
78 "\nVersion: " VERSION " (" BDATE ")\n\n"
79 "Usage: console [-s] [-c config_file] [-d debug_level] [config_file]\n"
80 "       -c <file>   set configuration file to file\n"
81 "       -dnn        set debug level to nn\n"
82 "       -s          no signals\n"
83 "       -t          test - read configuration and exit\n"
84 "       -?          print this message.\n"  
85 "\n");
86
87    exit(1);
88 }
89
90
91 void got_stop(int sig)
92 {
93    stop = TRUE;
94 }
95
96 void got_continue(int sig)
97 {
98    stop = FALSE;
99 }
100
101 void got_tout(int sig) 
102 {
103 // printf("Got tout\n");
104 }
105
106 void got_tin(int sig)
107 {   
108 // printf("Got tin\n");
109 }
110
111 struct cmdstruct { char *key; int (*func)(FILE *input, BSOCK *UA_sock); char *help; }; 
112 static struct cmdstruct commands[] = {
113  { N_("input"),      inputcmd,     _("input from file")},
114  { N_("output"),     outputcmd,    _("output to file")},
115  { N_("quit"),       quitcmd,      _("quit")},
116  { N_("tee"),        teecmd,       _("output to file and terminal")},
117  { N_("sleep"),      sleepcmd,     _("sleep specified time")},
118  { N_("time"),       timecmd,      _("print current time")},
119  { N_("version"),    versioncmd,   _("print Console's version")},
120  { N_("exit"),       quitcmd,      _("exit = quit")},
121              };
122 #define comsize (sizeof(commands)/sizeof(struct cmdstruct))
123
124 static int do_a_command(FILE *input, BSOCK *UA_sock)
125 {
126    unsigned int i;
127    int stat;
128    int found;
129    int len;
130    char *cmd;
131
132    found = 0;
133    stat = 1;
134
135    Dmsg1(120, "Command: %s\n", UA_sock->msg);
136    if (argc == 0) {
137       return 1;
138    }
139
140    cmd = argk[0]+1;
141    if (*cmd == '#') {                 /* comment */
142       return 1;
143    }
144    len = strlen(cmd);
145    for (i=0; i<comsize; i++) {     /* search for command */
146       if (strncasecmp(cmd,  _(commands[i].key), len) == 0) {
147          stat = (*commands[i].func)(input, UA_sock);   /* go execute command */
148          found = 1;
149          break;
150       }
151    }
152    if (!found) {
153       pm_strcat(&UA_sock->msg, _(": is an illegal command\n"));
154       UA_sock->msglen = strlen(UA_sock->msg);
155       fputs(UA_sock->msg, output);
156       fflush(output);
157    }
158    return stat;
159 }
160
161
162 static void read_and_process_input(FILE *input, BSOCK *UA_sock) 
163 {
164    char *prompt = "*";
165    int at_prompt = FALSE;
166    int tty_input = isatty(fileno(input));
167    int stat;
168
169    for ( ;; ) { 
170       if (at_prompt) {                /* don't prompt multiple times */
171          prompt = "";
172       } else {
173          prompt = "*";
174          at_prompt = TRUE;
175       }
176       if (tty_input) {
177          stat = get_cmd(input, prompt, UA_sock, 30);
178       } else {
179          int len = sizeof_pool_memory(UA_sock->msg) - 1;
180          if (fgets(UA_sock->msg, len, input) == NULL) {
181             stat = -1;
182          } else {
183             strip_trailing_junk(UA_sock->msg);
184             UA_sock->msglen = strlen(UA_sock->msg);
185             stat = 1;
186          }
187       }
188       if (stat < 0) {
189          break;                       /* error */
190       } else if (stat == 0) {         /* timeout */
191          bnet_fsend(UA_sock, ".messages");
192       } else {
193          at_prompt = FALSE;
194          /* @ => internal command for us */
195          if (UA_sock->msg[0] == '@') {
196             parse_command_args(UA_sock->msg, args, &argc, argk, argv);
197             if (!do_a_command(input, UA_sock)) {
198                break;
199             }
200             continue;
201          }
202          if (!bnet_send(UA_sock)) {   /* send command */
203             break;                    /* error */
204          }
205       }
206       if (strcmp(UA_sock->msg, ".quit") == 0 || strcmp(UA_sock->msg, ".exit") == 0) {
207          break;
208       }
209       while ((stat = bnet_recv(UA_sock)) >= 0) {
210          if (at_prompt) {
211             if (!stop) {
212                sendit("\n");
213             }
214             at_prompt = FALSE;
215          }
216          if (!stop) {
217             sendit("%s", UA_sock->msg);
218          }
219       }
220       if (!stop) {
221          fflush(stdout);
222       }
223       if (is_bnet_stop(UA_sock)) {
224          break;                       /* error or term */
225       } else if (stat == BNET_SIGNAL) {
226          if (UA_sock->msglen == BNET_PROMPT) {
227             at_prompt = TRUE;
228          }
229          Dmsg1(100, "Got poll %s\n", bnet_sig_to_ascii(UA_sock));
230       }
231    }
232 }
233
234
235 /*********************************************************************
236  *
237  *         Main Bacula Console -- User Interface Program
238  *
239  */
240 int main(int argc, char *argv[])
241 {
242    int ch, i, ndir, item;
243    int no_signals = FALSE;
244    int test_config = FALSE;
245    JCR jcr;
246
247    init_stack_dump();
248    my_name_is(argc, argv, "console");
249    init_msg(NULL, NULL);
250    working_directory = "/tmp";
251    args = get_pool_memory(PM_FNAME);
252
253    while ((ch = getopt(argc, argv, "bc:d:r:st?")) != -1) {
254       switch (ch) {
255          case 'c':                    /* configuration file */
256             if (configfile != NULL) {
257                free(configfile);
258             }
259             configfile = bstrdup(optarg);
260             break;
261
262          case 'd':
263             debug_level = atoi(optarg);
264             if (debug_level <= 0) {
265                debug_level = 1;
266             }
267             break;
268
269          case 's':                    /* turn off signals */
270             no_signals = TRUE;
271             break;
272
273          case 't':
274             test_config = TRUE;
275             break;
276
277          case '?':
278          default:
279             usage();
280
281       }  
282    }
283    argc -= optind;
284    argv += optind;
285
286    if (!no_signals) {
287       init_signals(terminate_console);
288    }
289    signal(SIGCHLD, SIG_IGN);
290    signal(SIGTSTP, got_stop);
291    signal(SIGCONT, got_continue);
292    signal(SIGTTIN, got_tin);
293    signal(SIGTTOU, got_tout);
294
295    if (argc) {
296       usage();
297    }
298
299    if (configfile == NULL) {
300       configfile = bstrdup(CONFIG_FILE);
301    }
302
303    parse_config(configfile);
304
305    LockRes();
306    ndir = 0;
307    for (dir=NULL; (dir = (DIRRES *)GetNextRes(R_DIRECTOR, (RES *)dir)); ) {
308       ndir++;
309    }
310    UnlockRes();
311    if (ndir == 0) {
312       Emsg1(M_ERROR_TERM, 0, "No Director resource defined in %s\n\
313 Without that I don't how to speak to the Director :-(\n", configfile);
314    }
315
316    if (test_config) {
317       terminate_console(0);
318       exit(0);
319    }
320
321    memset(&jcr, 0, sizeof(jcr));
322
323    if (ndir > 1) {
324       UA_sock = init_bsock(NULL, 0, "", "", 0);
325 try_again:
326       sendit("Available Directors:\n");
327       LockRes();
328       ndir = 0;
329       for (dir = NULL; (dir = (DIRRES *)GetNextRes(R_DIRECTOR, (RES *)dir)); ) {
330          fprintf(output, "%d  %s at %s:%d\n", 1+ndir++, dir->hdr.name, dir->address,
331             dir->DIRport);
332       }
333       UnlockRes();
334       if (get_cmd(stdin, "Select Director: ", UA_sock, 600) < 0) {
335          return 1;
336       }
337       item = atoi(UA_sock->msg);
338       if (item < 0 || item > ndir) {
339          sendit("You must enter a number between 1 and %d\n", ndir);
340          goto try_again;
341       }
342       LockRes();
343       dir = NULL;
344       for (i=0; i<item; i++) {
345          dir = (DIRRES *)GetNextRes(R_DIRECTOR, (RES *)dir);
346       }
347       UnlockRes();
348       term_bsock(UA_sock);
349    } else {
350       LockRes();
351       dir = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
352       UnlockRes();
353    }
354       
355
356    sendit("Connecting to Director %s:%d\n", dir->address,dir->DIRport);
357    UA_sock = bnet_connect(NULL, 5, 15, "Director daemon", dir->address, 
358                           NULL, dir->DIRport, 0);
359    if (UA_sock == NULL) {
360       terminate_console(0);
361       return 1;
362    }
363    jcr.dir_bsock = UA_sock;
364    if (!authenticate_director(&jcr, dir)) {
365       fprintf(stderr, "ERR=%s", UA_sock->msg);
366       terminate_console(0);
367       return 1;
368    }
369
370    Dmsg0(40, "Opened connection with Director daemon\n");
371
372    read_and_process_input(stdin, UA_sock);
373
374    if (UA_sock) {
375       bnet_sig(UA_sock, BNET_TERMINATE); /* send EOF */
376       bnet_close(UA_sock);
377    }
378
379    terminate_console(0);
380    return 0;
381 }
382
383
384 /* Cleanup and then exit */
385 static void terminate_console(int sig)
386 {
387    static int already_here = FALSE;
388
389    if (already_here) {                /* avoid recursive temination problems */
390       exit(1);
391    }
392    already_here = TRUE;
393    free_pool_memory(args);
394    exit(0);
395 }
396
397 #ifdef HAVE_READLINE
398 #undef free
399 #include "readline/readline.h"
400 #include "readline/history.h"
401
402
403 int 
404 get_cmd(FILE *input, char *prompt, BSOCK *sock, int sec)
405 {
406    char *line;
407
408    rl_catch_signals = 0;              /* do it ourselves */
409    line = readline(prompt);
410
411    if (!line) {
412       exit(1);
413    }
414    strcpy(sock->msg, line);
415    strip_trailing_junk(sock->msg);
416    sock->msglen = strlen(sock->msg);
417    if (sock->msglen) {
418       add_history(sock->msg);
419    }
420    free(line);
421    return 1;
422 }
423
424 #else /* no readline, do it ourselves */
425
426 /*
427  *   Returns: 1 if data available
428  *            0 if timeout
429  *           -1 if error
430  */
431 static int
432 wait_for_data(int fd, int sec)
433 {
434    fd_set fdset;
435    struct timeval tv;
436
437    FD_ZERO(&fdset);
438    FD_SET(fd, &fdset);
439    tv.tv_sec = sec;
440    tv.tv_usec = 0;
441    for ( ;; ) {
442       switch(select(fd + 1, &fdset, NULL, NULL, &tv)) {
443          case 0:                         /* timeout */
444             return 0;
445          case -1:
446             if (errno == EINTR || errno == EAGAIN) {
447                continue;
448             }
449             return -1;                  /* error return */
450          default:
451             return 1;
452       }
453    }
454 }
455
456 /*      
457  * Get next input command from terminal. 
458  *
459  *   Returns: 1 if got input
460  *            0 if timeout
461  *           -1 if EOF or error
462  */
463 int 
464 get_cmd(FILE *input, char *prompt, BSOCK *sock, int sec)
465 {
466    int len;  
467    if (!stop) {
468       if (output == stdout || tee) {
469          fputs(prompt, stdout);
470          fflush(stdout);
471       }
472    }
473 again:
474    switch (wait_for_data(fileno(input), sec)) {
475       case 0:
476          return 0;                    /* timeout */
477       case -1: 
478          return -1;                   /* error */
479       default:
480          len = sizeof_pool_memory(sock->msg) - 1;
481          if (stop) {
482             goto again;
483          }
484          if (fgets(sock->msg, len, input) == NULL) {
485             return -1;
486          }
487          break;
488    }
489    strip_trailing_junk(sock->msg);
490    sock->msglen = strlen(sock->msg);
491    return 1;
492 }
493
494 #endif
495
496 static int versioncmd(FILE *input, BSOCK *UA_sock)
497 {
498    sendit("Version: " VERSION " (" BDATE ")\n");
499    return 1;
500 }
501
502 static int inputcmd(FILE *input, BSOCK *UA_sock)
503 {
504    FILE *fd;
505
506    if (argc > 2) {
507       sendit("Too many arguments.\n");
508       return 0;
509    }
510    if (argc == 1) {
511       sendit("First argument must be a filename.\n");
512       return 0;
513    }
514    fd = fopen(argk[1], "r");
515    if (!fd) {
516       sendit("Cannot open file. ERR=%s\n", strerror(errno));
517       return 0; 
518    }
519    read_and_process_input(fd, UA_sock);
520    fclose(fd);
521    return 1;
522 }
523
524 static int teecmd(FILE *input, BSOCK *UA_sock)
525 {
526    tee = 1;
527    return do_outputcmd(input, UA_sock);
528 }
529
530 static int outputcmd(FILE *input, BSOCK *UA_sock)
531 {
532    tee = 0;
533    return do_outputcmd(input, UA_sock);
534 }
535
536
537 static int do_outputcmd(FILE *input, BSOCK *UA_sock)
538 {
539    FILE *fd;
540    char *mode = "a+";
541
542    if (argc > 3) {
543       sendit("Too many arguments.\n");
544       return 1;
545    }
546    if (argc == 1) {
547       if (output != stdout) {
548          fclose(output);
549          output = stdout;
550          tee = 0;
551       }
552       return 1;
553    }
554    if (argc == 3) {
555       mode = argk[2];
556    }
557    fd = fopen(argk[1], mode);
558    if (!fd) {
559       sendit("Cannot open file. ERR=%s\n", strerror(errno));
560       return 1; 
561    }
562    output = fd;
563    return 1;
564 }
565
566 static int quitcmd(FILE *input, BSOCK *UA_sock)
567 {
568    return 0;
569 }
570
571 static int sleepcmd(FILE *input, BSOCK *UA_sock)
572 {
573    if (argc > 1) {
574       sleep(atoi(argk[1]));
575    }
576    return 1;
577 }
578
579
580 static int timecmd(FILE *input, BSOCK *UA_sock)
581 {
582    char sdt[50];
583    time_t ttime = time(NULL);
584    struct tm tm;
585    localtime_r(&ttime, &tm);
586    strftime(sdt, sizeof(sdt), "%d-%b-%Y %H:%M:%S", &tm);
587    sendit(sdt);
588    sendit("\n");
589    return 1;
590 }
591
592 static void sendit(char *fmt,...)
593 {
594     char buf[3000];
595     va_list arg_ptr;
596
597     va_start(arg_ptr, fmt);
598     bvsnprintf(buf, sizeof(buf), (char *)fmt, arg_ptr);
599     va_end(arg_ptr);
600     fputs(buf, output);
601     if (tee) {
602        fputs(buf, stdout);
603     }
604     fflush(stdout);
605 }