]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/ua_cmds.c
Implement .help command.
[bacula/bacula] / bacula / src / dird / ua_cmds.c
1 /*
2  *
3  *   Bacula Director -- User Agent Commands
4  *
5  *     Kern Sibbald, September MM
6  *
7  *   Version $Id$
8  */
9
10 /*
11    Copyright (C) 2000-2004 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 as
15    published by the Free Software Foundation; either version 2 of
16    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 GNU
21    General Public License for more details.
22
23    You should have received a copy of the GNU General Public
24    License along with this program; if not, write to the Free
25    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
26    MA 02111-1307, USA.
27
28  */
29
30 #include "bacula.h"
31 #include "dird.h"
32
33 /* Imported subroutines */
34
35 /* Imported variables */
36 extern int r_first;
37 extern int r_last;
38 extern struct s_res resources[];
39 extern char my_name[];
40 extern jobq_t job_queue;              /* job queue */
41
42
43 extern char *list_pool;
44
45 /* Imported functions */
46 extern int status_cmd(UAContext *ua, const char *cmd);
47 extern int list_cmd(UAContext *ua, const char *cmd);
48 extern int llist_cmd(UAContext *ua, const char *cmd);
49 extern int show_cmd(UAContext *ua, const char *cmd);
50 extern int messagescmd(UAContext *ua, const char *cmd);
51 extern int autodisplay_cmd(UAContext *ua, const char *cmd);
52 extern int gui_cmd(UAContext *ua, const char *cmd);
53 extern int sqlquerycmd(UAContext *ua, const char *cmd);
54 extern int querycmd(UAContext *ua, const char *cmd);
55 extern int run_cmd(UAContext *ua, const char *cmd);
56 extern int retentioncmd(UAContext *ua, const char *cmd);
57 extern int prunecmd(UAContext *ua, const char *cmd);
58 extern int purgecmd(UAContext *ua, const char *cmd);
59 extern int restore_cmd(UAContext *ua, const char *cmd);
60 extern int label_cmd(UAContext *ua, const char *cmd);
61 extern int relabel_cmd(UAContext *ua, const char *cmd);
62 extern int update_slots(UAContext *ua);  /* ua_label.c */
63
64 /* Forward referenced functions */
65 static int add_cmd(UAContext *ua, const char *cmd);  
66 static int create_cmd(UAContext *ua, const char *cmd); 
67 static int cancel_cmd(UAContext *ua, const char *cmd); 
68 static int setdebug_cmd(UAContext *ua, const char *cmd);
69 static int trace_cmd(UAContext *ua, const char *cmd);
70 static int var_cmd(UAContext *ua, const char *cmd);
71 static int estimate_cmd(UAContext *ua, const char *cmd);
72 static int help_cmd(UAContext *ua, const char *cmd);
73 static int delete_cmd(UAContext *ua, const char *cmd);
74 static int use_cmd(UAContext *ua, const char *cmd);
75 static int unmount_cmd(UAContext *ua, const char *cmd);
76 static int version_cmd(UAContext *ua, const char *cmd);
77 static int automount_cmd(UAContext *ua, const char *cmd);
78 static int time_cmd(UAContext *ua, const char *cmd);
79 static int reload_cmd(UAContext *ua, const char *cmd);
80 static int update_volume(UAContext *ua);
81 static int update_pool(UAContext *ua);
82 static int delete_volume(UAContext *ua);
83 static int delete_pool(UAContext *ua);
84 static int delete_job(UAContext *ua);
85 static int mount_cmd(UAContext *ua, const char *cmd);
86 static int release_cmd(UAContext *ua, const char *cmd);
87 static int update_cmd(UAContext *ua, const char *cmd);
88 static int wait_cmd(UAContext *ua, const char *cmd);
89 static int setip_cmd(UAContext *ua, const char *cmd);
90
91 int qhelp_cmd(UAContext *ua, const char *cmd);
92 int quit_cmd(UAContext *ua, const char *cmd);
93
94
95 struct cmdstruct { const char *key; int (*func)(UAContext *ua, const char *cmd); const char *help; }; 
96 static struct cmdstruct commands[] = {
97  { N_("add"),        add_cmd,         _("add media to a pool")},
98  { N_("autodisplay"), autodisplay_cmd, _("autodisplay [on/off] -- console messages")},
99  { N_("automount"),   automount_cmd,  _("automount [on/off] -- after label")},
100  { N_("cancel"),     cancel_cmd,    _("cancel job=nnn -- cancel a job")},
101  { N_("create"),     create_cmd,    _("create DB Pool from resource")},  
102  { N_("delete"),     delete_cmd,    _("delete [pool=<pool-name> | media volume=<volume-name>]")},    
103  { N_("estimate"),   estimate_cmd,  _("performs FileSet estimate, listing gives full listing")},
104  { N_("exit"),       quit_cmd,      _("exit = quit")},
105  { N_("gui"),        gui_cmd,       _("gui [on/off] -- non-interactive gui mode")},
106  { N_("help"),       help_cmd,      _("print this command")},
107  { N_("list"),       list_cmd,      _("list [pools | jobs | jobtotals | media <pool> | files jobid=<nn>]; from catalog")},
108  { N_("label"),      label_cmd,     _("label a tape")},
109  { N_("llist"),      llist_cmd,     _("full or long list like list command")},
110  { N_("messages"),   messagescmd,   _("messages")},
111  { N_("mount"),      mount_cmd,     _("mount <storage-name>")},
112  { N_("prune"),      prunecmd,      _("prune expired records from catalog")},
113  { N_("purge"),      purgecmd,      _("purge records from catalog")},
114  { N_("quit"),       quit_cmd,      _("quit")},
115  { N_("query"),      querycmd,      _("query catalog")},
116  { N_("restore"),    restore_cmd,   _("restore files")},
117  { N_("relabel"),    relabel_cmd,   _("relabel a tape")},
118  { N_("release"),    release_cmd,   _("release <storage-name>")},
119  { N_("reload"),     reload_cmd,    _("reload conf file")},
120  { N_("run"),        run_cmd,       _("run <job-name>")},
121  { N_("status"),     status_cmd,    _("status [storage | client]=<name>")},
122  { N_("setdebug"),   setdebug_cmd,  _("sets debug level")},
123  { N_("setip"),      setip_cmd,     _("sets new client address -- if authorized")},
124  { N_("show"),       show_cmd,      _("show (resource records) [jobs | pools | ... | all]")},
125  { N_("sqlquery"),   sqlquerycmd,   _("use SQL to query catalog")}, 
126  { N_("time"),       time_cmd,      _("print current time")},
127  { N_("trace"),      trace_cmd,     _("turn on/off trace to file")},
128  { N_("unmount"),    unmount_cmd,   _("unmount <storage-name>")},
129  { N_("update"),     update_cmd,    _("update Volume or Pool")},
130  { N_("use"),        use_cmd,       _("use catalog xxx")},
131  { N_("var"),        var_cmd,       _("does variable expansion")},
132  { N_("version"),    version_cmd,   _("print Director version")},
133  { N_("wait"),       wait_cmd,      _("wait until no jobs are running")},
134              };
135 #define comsize (sizeof(commands)/sizeof(struct cmdstruct))
136
137 /*
138  * Execute a command from the UA
139  */
140 int do_a_command(UAContext *ua, const char *cmd)
141 {
142    unsigned int i;
143    int len, stat;
144    bool found = false;
145
146    stat = 1;
147
148    Dmsg1(200, "Command: %s\n", ua->UA_sock->msg);
149    if (ua->argc == 0) {
150       return 1;
151    }
152
153    len = strlen(ua->argk[0]);
154    for (i=0; i<comsize; i++) {     /* search for command */
155       if (strncasecmp(ua->argk[0],  _(commands[i].key), len) == 0) {
156          if (!acl_access_ok(ua, Command_ACL, ua->argk[0], len)) {
157             break;
158          }
159          stat = (*commands[i].func)(ua, cmd);   /* go execute command */
160          found = true;
161          break;
162       }
163    }
164    if (!found) {
165       bnet_fsend(ua->UA_sock, _("%s: is an illegal command.\n"), ua->argk[0]);
166    }
167    return stat;
168 }
169
170 /*
171  * This is a common routine used to stuff the Pool DB record defaults
172  *   into the Media DB record just before creating a media (Volume) 
173  *   record.
174  */
175 void set_pool_dbr_defaults_in_media_dbr(MEDIA_DBR *mr, POOL_DBR *pr)
176 {
177    mr->PoolId = pr->PoolId;
178    bstrncpy(mr->VolStatus, "Append", sizeof(mr->VolStatus));
179    mr->Recycle = pr->Recycle;
180    mr->VolRetention = pr->VolRetention;
181    mr->VolUseDuration = pr->VolUseDuration;
182    mr->MaxVolJobs = pr->MaxVolJobs;
183    mr->MaxVolFiles = pr->MaxVolFiles;
184    mr->MaxVolBytes = pr->MaxVolBytes;
185 }
186
187
188 /*
189  *  Add Volumes to an existing Pool
190  */
191 static int add_cmd(UAContext *ua, const char *cmd) 
192 {
193    POOL_DBR pr;
194    MEDIA_DBR mr;
195    int num, i, max, startnum;
196    int first_id = 0;
197    char name[MAX_NAME_LENGTH];
198    STORE *store;
199    int Slot = 0, InChanger = 0;
200
201    bsendmsg(ua, _(
202 "You probably don't want to be using this command since it\n"
203 "creates database records without labeling the Volumes.\n"
204 "You probably want to use the \"label\" command.\n\n"));
205
206    if (!open_db(ua)) {
207       return 1;
208    }
209
210    memset(&pr, 0, sizeof(pr));
211    memset(&mr, 0, sizeof(mr));
212
213    if (!get_pool_dbr(ua, &pr)) {
214       return 1;
215    }
216
217    Dmsg4(120, "id=%d Num=%d Max=%d type=%s\n", pr.PoolId, pr.NumVols,
218       pr.MaxVols, pr.PoolType);
219
220    while (pr.MaxVols > 0 && pr.NumVols >= pr.MaxVols) {
221       bsendmsg(ua, _("Pool already has maximum volumes = %d\n"), pr.MaxVols);
222       for (;;) {
223          if (!get_pint(ua, _("Enter new maximum (zero for unlimited): "))) {
224             return 1;
225          }
226          pr.MaxVols = ua->pint32_val;
227       }
228    }
229
230    /* Get media type */
231    if ((store = get_storage_resource(ua, 0)) != NULL) {
232       bstrncpy(mr.MediaType, store->media_type, sizeof(mr.MediaType));
233    } else if (!get_media_type(ua, mr.MediaType, sizeof(mr.MediaType))) {
234       return 1;
235    }
236       
237    if (pr.MaxVols == 0) {
238       max = 1000;
239    } else {
240       max = pr.MaxVols - pr.NumVols;
241    }
242    for (;;) {
243       char buf[100]; 
244       bsnprintf(buf, sizeof(buf), _("Enter number of Volumes to create. 0=>fixed name. Max=%d: "), max);
245       if (!get_pint(ua, buf)) {
246          return 1;
247       }
248       num = ua->pint32_val;
249       if (num < 0 || num > max) {
250          bsendmsg(ua, _("The number must be between 0 and %d\n"), max);
251          continue;
252       }
253       break;
254    }
255 getVolName:
256    if (num == 0) {
257       if (!get_cmd(ua, _("Enter Volume name: "))) {
258          return 1;
259       }
260    } else {
261       if (!get_cmd(ua, _("Enter base volume name: "))) {
262          return 1;
263       }
264    }
265    /* Don't allow | in Volume name because it is the volume separator character */
266    if (!is_volume_name_legal(ua, ua->cmd)) {
267       goto getVolName;
268    }
269    if (strlen(ua->cmd) >= MAX_NAME_LENGTH-10) {
270       bsendmsg(ua, _("Volume name too long.\n"));
271       goto getVolName;
272    }
273    if (strlen(ua->cmd) == 0) {
274       bsendmsg(ua, _("Volume name must be at least one character long.\n"));
275       goto getVolName;
276    }
277
278    bstrncpy(name, ua->cmd, sizeof(name));
279    if (num > 0) {
280       strcat(name, "%04d");
281
282       for (;;) {
283          if (!get_pint(ua, _("Enter the starting number: "))) {
284             return 1;
285          }
286          startnum = ua->pint32_val;
287          if (startnum < 1) {
288             bsendmsg(ua, _("Start number must be greater than zero.\n"));
289             continue;
290          }
291          break;
292       }
293    } else {
294       startnum = 1;
295       num = 1;
296    }
297
298    if (store && store->autochanger) {
299       if (!get_pint(ua, _("Enter slot (0 for none): "))) {
300          return 1;
301       }
302       Slot = ua->pint32_val;
303       if (!get_yesno(ua, _("InChanger? yes/no: "))) {
304          return 1;
305       }
306       InChanger = ua->pint32_val;
307    }
308            
309    set_pool_dbr_defaults_in_media_dbr(&mr, &pr);
310    for (i=startnum; i < num+startnum; i++) { 
311       bsnprintf(mr.VolumeName, sizeof(mr.VolumeName), name, i);
312       mr.Slot = Slot++;
313       mr.InChanger = InChanger;
314       Dmsg1(200, "Create Volume %s\n", mr.VolumeName);
315       if (!db_create_media_record(ua->jcr, ua->db, &mr)) {
316          bsendmsg(ua, "%s", db_strerror(ua->db));
317          return 1;
318       }
319       if (i == startnum) {
320          first_id = mr.PoolId;
321       }
322    }
323    pr.NumVols += num;
324    Dmsg0(200, "Update pool record.\n"); 
325    if (db_update_pool_record(ua->jcr, ua->db, &pr) != 1) {
326       bsendmsg(ua, "%s", db_strerror(ua->db));
327       return 1;
328    }
329    bsendmsg(ua, _("%d Volumes created in pool %s\n"), num, pr.Name);
330
331    return 1;
332 }
333
334 /*
335  * Turn auto mount on/off  
336  * 
337  *  automount on 
338  *  automount off
339  */
340 int automount_cmd(UAContext *ua, const char *cmd)
341 {
342    char *onoff;
343
344    if (ua->argc != 2) {
345       if (!get_cmd(ua, _("Turn on or off? "))) {
346             return 1;
347       }
348       onoff = ua->cmd;
349    } else {
350       onoff = ua->argk[1];
351    }
352
353    ua->automount = (strcasecmp(onoff, _("off")) == 0) ? 0 : 1;
354    return 1; 
355 }
356
357
358 /*
359  * Cancel a job
360  */
361 static int cancel_cmd(UAContext *ua, const char *cmd)
362 {
363    int i, ret;
364    int njobs = 0;
365    JCR *jcr = NULL;
366    char JobName[MAX_NAME_LENGTH];
367
368    if (!open_db(ua)) {
369       return 1;
370    }
371
372    for (i=1; i<ua->argc; i++) {
373       if (strcasecmp(ua->argk[i], _("jobid")) == 0) {
374          uint32_t JobId;
375          if (!ua->argv[i]) {
376             break;
377          }
378          JobId = str_to_int64(ua->argv[i]);
379          if (!(jcr=get_jcr_by_id(JobId))) {
380             bsendmsg(ua, _("JobId %d is not running.\n"),  JobId);
381             return 1;
382          }
383          break;
384       } else if (strcasecmp(ua->argk[i], _("job")) == 0) {
385          if (!ua->argv[i]) {
386             break;
387          }
388          if (!(jcr=get_jcr_by_partial_name(ua->argv[i]))) {
389             bsendmsg(ua, _("Job %s is not running.\n"), ua->argv[i]);
390             return 1;
391          }
392          break;
393       }
394    }
395    /* If we still do not have a jcr,
396     *   throw up a list and ask the user to select one.
397     */
398    if (!jcr) {
399       /* Count Jobs running */
400       lock_jcr_chain();
401       foreach_jcr(jcr) {
402          if (jcr->JobId == 0) {      /* this is us */
403             free_locked_jcr(jcr);
404             continue;
405          }
406          free_locked_jcr(jcr);
407          njobs++;
408       }
409       unlock_jcr_chain();
410
411       if (njobs == 0) {
412          bsendmsg(ua, _("No Jobs running.\n"));
413          return 1;
414       }
415       start_prompt(ua, _("Select Job:\n"));
416       lock_jcr_chain();
417       foreach_jcr(jcr) {
418          if (jcr->JobId == 0) {      /* this is us */
419             free_locked_jcr(jcr);
420             continue;
421          }
422          add_prompt(ua, jcr->Job);
423          free_locked_jcr(jcr);
424       }
425       unlock_jcr_chain();
426
427       if (do_prompt(ua, _("Job"),  _("Choose Job to cancel"), JobName, sizeof(JobName)) < 0) {
428          return 1;
429       }
430       if (njobs == 1) {
431          if (!get_yesno(ua, _("Confirm cancel (yes/no): ")) || ua->pint32_val == 0) {
432             return 1;
433          }
434       }
435       /* NOTE! This increments the ref_count */
436       jcr = get_jcr_by_full_name(JobName);
437       if (!jcr) {
438          bsendmsg(ua, _("Job %s not found.\n"), JobName);
439          return 1;
440       }
441    }
442
443    ret = cancel_job(ua, jcr);
444    free_jcr(jcr);
445
446    return ret;
447 }
448
449 /*
450  * This is a common routine to create or update a
451  *   Pool DB base record from a Pool Resource. We handle
452  *   the setting of MaxVols and NumVols slightly differently
453  *   depending on if we are creating the Pool or we are
454  *   simply bringing it into agreement with the resource (updage).
455  */
456 static void set_pooldbr_from_poolres(POOL_DBR *pr, POOL *pool, e_pool_op op)
457 {
458    strcpy(pr->PoolType, pool->pool_type);
459    if (op == POOL_OP_CREATE) {
460       pr->MaxVols = pool->max_volumes;
461       pr->NumVols = 0;
462    } else {          /* update pool */
463       if (pr->MaxVols != pool->max_volumes) {
464          pr->MaxVols = pool->max_volumes;
465       }
466       if (pr->MaxVols != 0 && pr->MaxVols < pr->NumVols) {
467          pr->MaxVols = pr->NumVols;
468       }
469    }
470    pr->UseOnce = pool->use_volume_once;
471    pr->UseCatalog = pool->use_catalog;
472    pr->AcceptAnyVolume = pool->accept_any_volume;
473    pr->Recycle = pool->Recycle;
474    pr->VolRetention = pool->VolRetention;
475    pr->VolUseDuration = pool->VolUseDuration;
476    pr->MaxVolJobs = pool->MaxVolJobs;
477    pr->MaxVolFiles = pool->MaxVolFiles;
478    pr->MaxVolBytes = pool->MaxVolBytes;
479    pr->AutoPrune = pool->AutoPrune;
480    pr->Recycle = pool->Recycle;
481    if (pool->label_format) {
482       strcpy(pr->LabelFormat, pool->label_format);
483    } else {
484       strcpy(pr->LabelFormat, "*");    /* none */
485    }
486 }
487
488
489 /*
490  * Create a pool record from a given Pool resource
491  *   Also called from backup.c
492  * Returns: -1  on error
493  *           0  record already exists
494  *           1  record created
495  */
496
497 int create_pool(JCR *jcr, B_DB *db, POOL *pool, e_pool_op op)
498 {
499    POOL_DBR  pr;
500
501    memset(&pr, 0, sizeof(POOL_DBR));
502
503    strcpy(pr.Name, pool->hdr.name);
504
505    if (db_get_pool_record(jcr, db, &pr)) {
506       /* Pool Exists */
507       if (op == POOL_OP_UPDATE) {  /* update request */
508          set_pooldbr_from_poolres(&pr, pool, op);
509          db_update_pool_record(jcr, db, &pr);
510       }
511       return 0;                       /* exists */
512    }
513
514    set_pooldbr_from_poolres(&pr, pool, op);
515
516    if (!db_create_pool_record(jcr, db, &pr)) {
517       return -1;                      /* error */
518    }
519    return 1;
520 }
521
522
523
524 /*
525  * Create a Pool Record in the database.
526  *  It is always created from the Resource record.
527  */
528 static int create_cmd(UAContext *ua, const char *cmd) 
529 {
530    POOL *pool;
531
532    if (!open_db(ua)) {
533       return 1;
534    }
535
536    pool = get_pool_resource(ua);
537    if (!pool) {
538       return 1;
539    }
540
541    switch (create_pool(ua->jcr, ua->db, pool, POOL_OP_CREATE)) {
542    case 0:
543       bsendmsg(ua, _("Error: Pool %s already exists.\n"
544                "Use update to change it.\n"), pool->hdr.name);
545       break;
546
547    case -1:
548       bsendmsg(ua, "%s", db_strerror(ua->db));
549       break;
550
551    default:
552      break;
553    }
554    bsendmsg(ua, _("Pool %s created.\n"), pool->hdr.name);
555    return 1;
556 }
557
558
559 /*
560  * Set a new address in a Client resource. We do this only
561  *  if the Console name is the same as the Client name 
562  *  and the Console can access the client.
563  */
564 static int setip_cmd(UAContext *ua, const char *cmd) 
565 {
566    CLIENT *client;
567    char mybuf[1024]; 
568    char *buf = mybuf;
569    if (!ua->cons || !acl_access_ok(ua, Client_ACL, ua->cons->hdr.name)) {
570       bsendmsg(ua, _("Illegal command from this console.\n"));
571       return 1;
572    }
573    LockRes();
574    client = (CLIENT *)GetResWithName(R_CLIENT, ua->cons->hdr.name);
575
576    if (!client) {
577       bsendmsg(ua, _("Client \"%s\" not found.\n"), ua->cons->hdr.name);
578       goto get_out;
579    }
580    if (client->address) {
581       free(client->address);
582    }
583 #ifdef HAVE_INET_NTOP
584    inet_ntop(ua->UA_sock->client_addr.sa_family, 
585                 &(ua->UA_sock->client_addr), buf,
586                 ua->UA_sock->client_addr.sa_family == AF_INET ?
587                 sizeof(sockaddr_in) : sizeof(sockaddr_in6));
588 #else
589    buf = inet_ntoa(((struct sockaddr_in *)&(ua->UA_sock->client_addr))->sin_addr);
590 #endif
591
592    client->address = bstrdup(buf);
593    bsendmsg(ua, _("Client \"%s\" address set to %s\n"),
594             client->hdr.name, client->address);
595 get_out:
596    UnlockRes();
597    return 1;
598 }
599
600
601 /*
602  * Update a Pool Record in the database.
603  *  It is always updated from the Resource record.
604  *
605  *    update pool=<pool-name>
606  *         updates pool from Pool resource
607  *    update media pool=<pool-name> volume=<volume-name>
608  *         changes pool info for volume
609  *    update slots [scan=...]
610  *         updates autochanger slots
611  */
612 static int update_cmd(UAContext *ua, const char *cmd) 
613 {
614    static const char *kw[] = {
615       N_("media"),  /* 0 */
616       N_("volume"), /* 1 */
617       N_("pool"),   /* 2 */
618       N_("slots"),  /* 3 */
619       NULL};
620
621    if (!open_db(ua)) {
622       return 1;
623    }
624
625    switch (find_arg_keyword(ua, kw)) {
626    case 0:
627    case 1:
628       update_volume(ua);
629       return 1;
630    case 2:
631       update_pool(ua);
632       return 1;
633    case 3:
634       update_slots(ua);
635       return 1;
636    default:
637       break;
638    }
639     
640    start_prompt(ua, _("Update choice:\n"));
641    add_prompt(ua, _("Volume parameters"));
642    add_prompt(ua, _("Pool from resource"));
643    add_prompt(ua, _("Slots from autochanger"));
644    switch (do_prompt(ua, _("item"), _("Choose catalog item to update"), NULL, 0)) {
645    case 0:
646       update_volume(ua);
647       break;
648    case 1:
649       update_pool(ua);
650       break;
651    case 2:
652       update_slots(ua);
653       break;
654    default:
655       break;
656    }
657    return 1;
658 }
659
660 static void update_volstatus(UAContext *ua, const char *val, MEDIA_DBR *mr)
661 {
662    POOLMEM *query = get_pool_memory(PM_MESSAGE);
663    const char *kw[] = {
664       "Append",
665       "Archive",
666       "Disabled",
667       "Full",
668       "Used", 
669       "Cleaning", 
670       "Recycle",
671       "Read-Only",
672       NULL};
673    bool found = false;
674    int i;
675
676    for (i=0; kw[i]; i++) {
677       if (strcasecmp(val, kw[i]) == 0) {
678          found = true;
679          break;
680       }
681    }
682    if (!found) {
683       bsendmsg(ua, _("Invalid VolStatus specified: %s\n"), val);
684    } else {
685       bstrncpy(mr->VolStatus, kw[i], sizeof(mr->VolStatus));
686       Mmsg(&query, "UPDATE Media SET VolStatus='%s' WHERE MediaId=%u",
687          mr->VolStatus, mr->MediaId);
688       if (!db_sql_query(ua->db, query, NULL, NULL)) {  
689          bsendmsg(ua, "%s", db_strerror(ua->db));
690       } else {
691          bsendmsg(ua, _("New Volume status is: %s\n"), mr->VolStatus);
692       }
693    }
694    free_pool_memory(query);
695 }
696
697 static void update_volretention(UAContext *ua, char *val, MEDIA_DBR *mr)
698 {
699    char ed1[150];
700    POOLMEM *query;
701    if (!duration_to_utime(val, &mr->VolRetention)) {
702       bsendmsg(ua, _("Invalid retention period specified: %s\n"), val);
703       return;
704    }
705    query = get_pool_memory(PM_MESSAGE);
706    Mmsg(&query, "UPDATE Media SET VolRetention=%s WHERE MediaId=%u",
707       edit_uint64(mr->VolRetention, ed1), mr->MediaId);
708    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
709       bsendmsg(ua, "%s", db_strerror(ua->db));
710    } else {
711       bsendmsg(ua, _("New retention period is: %s\n"),
712          edit_utime(mr->VolRetention, ed1, sizeof(ed1)));
713    }
714    free_pool_memory(query);
715 }
716
717 static void update_voluseduration(UAContext *ua, char *val, MEDIA_DBR *mr)
718 {
719    char ed1[150];
720    POOLMEM *query;
721
722    if (!duration_to_utime(val, &mr->VolUseDuration)) {
723       bsendmsg(ua, _("Invalid use duration specified: %s\n"), val);
724       return;
725    }
726    query = get_pool_memory(PM_MESSAGE);
727    Mmsg(&query, "UPDATE Media SET VolUseDuration=%s WHERE MediaId=%u",
728       edit_uint64(mr->VolUseDuration, ed1), mr->MediaId);
729    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
730       bsendmsg(ua, "%s", db_strerror(ua->db));
731    } else {
732       bsendmsg(ua, _("New use duration is: %s\n"),
733          edit_utime(mr->VolUseDuration, ed1, sizeof(ed1)));
734    }
735    free_pool_memory(query);
736 }
737
738 static void update_volmaxjobs(UAContext *ua, char *val, MEDIA_DBR *mr)
739 {
740    POOLMEM *query = get_pool_memory(PM_MESSAGE);
741    Mmsg(&query, "UPDATE Media SET MaxVolJobs=%s WHERE MediaId=%u",
742       val, mr->MediaId);
743    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
744       bsendmsg(ua, "%s", db_strerror(ua->db));
745    } else {
746       bsendmsg(ua, _("New max jobs is: %s\n"), val);
747    }
748    free_pool_memory(query);
749 }
750
751 static void update_volmaxfiles(UAContext *ua, char *val, MEDIA_DBR *mr)
752 {
753    POOLMEM *query = get_pool_memory(PM_MESSAGE);
754    Mmsg(&query, "UPDATE Media SET MaxVolFiles=%s WHERE MediaId=%u",
755       val, mr->MediaId);
756    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
757       bsendmsg(ua, "%s", db_strerror(ua->db));
758    } else {
759       bsendmsg(ua, _("New max files is: %s\n"), val);
760    }
761    free_pool_memory(query);
762 }
763
764 static void update_volmaxbytes(UAContext *ua, char *val, MEDIA_DBR *mr)
765 {
766    uint64_t maxbytes;
767    char ed1[50];
768    POOLMEM *query;
769
770    if (!size_to_uint64(val, strlen(val), &maxbytes)) {
771       bsendmsg(ua, _("Invalid max. bytes specification: %s\n"), val);
772       return;
773    } 
774    query = get_pool_memory(PM_MESSAGE);
775    Mmsg(&query, "UPDATE Media SET MaxVolBytes=%s WHERE MediaId=%u",
776       edit_uint64(maxbytes, ed1), mr->MediaId);
777    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
778       bsendmsg(ua, "%s", db_strerror(ua->db));
779    } else {
780       bsendmsg(ua, _("New Max bytes is: %s\n"), edit_uint64(maxbytes, ed1));
781    }
782    free_pool_memory(query);
783 }
784
785 static void update_volrecycle(UAContext *ua, char *val, MEDIA_DBR *mr)
786 {
787    int recycle;
788    POOLMEM *query;
789    if (strcasecmp(val, _("yes")) == 0) {
790       recycle = 1;
791    } else if (strcasecmp(val, _("no")) == 0) {
792       recycle = 0;
793    } else {
794       bsendmsg(ua, _("Invalid value. It must by yes or no.\n"));
795       return;
796    }
797    query = get_pool_memory(PM_MESSAGE);
798    Mmsg(&query, "UPDATE Media SET Recycle=%d WHERE MediaId=%u",
799       recycle, mr->MediaId);
800    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
801       bsendmsg(ua, "%s", db_strerror(ua->db));
802    } else {       
803       bsendmsg(ua, _("New Recycle flag is: %s\n"),
804          mr->Recycle==1?_("yes"):_("no"));
805    }
806    free_pool_memory(query);
807 }
808
809 /* Modify the Pool in which this Volume is located */
810 static void update_vol_pool(UAContext *ua, char *val, MEDIA_DBR *mr, POOL_DBR *opr)
811 {
812    POOL_DBR pr;
813    POOLMEM *query;
814
815    memset(&pr, 0, sizeof(pr));
816    bstrncpy(pr.Name, val, sizeof(pr.Name));
817    if (!get_pool_dbr(ua, &pr)) {
818       return;
819    }
820    mr->PoolId = pr.PoolId;            /* set new PoolId */
821    /*
822     */
823    query = get_pool_memory(PM_MESSAGE);
824    db_lock(ua->db);
825    Mmsg(&query, "UPDATE Media SET PoolId=%d WHERE MediaId=%u",
826       mr->PoolId, mr->MediaId);
827    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
828       bsendmsg(ua, "%s", db_strerror(ua->db));
829    } else {       
830       bsendmsg(ua, _("New Pool is: %s\n"), pr.Name);
831       opr->NumVols--;
832       if (!db_update_pool_record(ua->jcr, ua->db, opr)) {
833          bsendmsg(ua, "%s", db_strerror(ua->db));
834       }
835       pr.NumVols++;
836       if (!db_update_pool_record(ua->jcr, ua->db, &pr)) {
837          bsendmsg(ua, "%s", db_strerror(ua->db));
838       }
839       db_make_inchanger_unique(ua->jcr, ua->db, mr);
840    }
841    db_unlock(ua->db);
842    free_pool_memory(query);
843 }
844
845 /*
846  * Refresh the Volume information from the Pool record
847  */
848 static void update_volfrompool(UAContext *ua, MEDIA_DBR *mr)
849 {
850    POOL_DBR pr;
851
852    memset(&pr, 0, sizeof(pr));
853    pr.PoolId = mr->PoolId;
854    if (!get_pool_dbr(ua, &pr)) {
855       return;
856    }
857    set_pool_dbr_defaults_in_media_dbr(mr, &pr);
858    if (!db_update_media_defaults(ua->jcr, ua->db, mr)) {
859       bsendmsg(ua, _("Error updating Volume record: ERR=%s"), db_strerror(ua->db));
860    } else {
861       bsendmsg(ua, _("Volume defaults updated from Pool record.\n"));
862    }
863 }
864
865 /*
866  * Refresh the Volume information from the Pool record
867  *   for all Volumes
868  */
869 static void update_all_vols_from_pool(UAContext *ua)
870 {
871    POOL_DBR pr;
872    MEDIA_DBR mr;
873
874    memset(&pr, 0, sizeof(pr));
875    if (!get_pool_dbr(ua, &pr)) {
876       return;
877    }
878    memset(&mr, 0, sizeof(mr));
879    set_pool_dbr_defaults_in_media_dbr(&mr, &pr);
880    mr.PoolId = pr.PoolId;
881    if (!db_update_media_defaults(ua->jcr, ua->db, &mr)) {
882       bsendmsg(ua, _("Error updating Volume records: ERR=%s"), db_strerror(ua->db));
883    } else {
884       bsendmsg(ua, _("All Volume defaults updated from Pool record.\n"));
885    }
886 }
887
888
889 /*
890  * Update a media record -- allows you to change the
891  *  Volume status. E.g. if you want Bacula to stop
892  *  writing on the volume, set it to anything other
893  *  than Append.
894  */              
895 static int update_volume(UAContext *ua)
896 {
897    MEDIA_DBR mr;
898    POOL_DBR pr;
899    POOLMEM *query;
900    char ed1[130];
901    bool done = false;
902    const char *kw[] = {
903       N_("VolStatus"),                /* 0 */
904       N_("VolRetention"),             /* 1 */
905       N_("VolUse"),                   /* 2 */
906       N_("MaxVolJobs"),               /* 3 */
907       N_("MaxVolFiles"),              /* 4 */
908       N_("MaxVolBytes"),              /* 5 */
909       N_("Recycle"),                  /* 6 */
910       N_("Pool"),                     /* 7 */
911       N_("FromPool"),                 /* 8 */
912       N_("AllFromPool"),              /* 9 */
913       NULL };
914
915    for (int i=0; kw[i]; i++) {
916       int j;
917       POOL_DBR pr;
918       if ((j=find_arg_with_value(ua, kw[i])) > 0) {
919          if (i != 9 && !select_media_dbr(ua, &mr)) {
920             return 0;
921          }
922          switch (i) {
923          case 0:
924             update_volstatus(ua, ua->argv[j], &mr);
925             break;
926          case 1:
927             update_volretention(ua, ua->argv[j], &mr);
928             break;
929          case 2:
930             update_voluseduration(ua, ua->argv[j], &mr);
931             break;
932          case 3:
933             update_volmaxjobs(ua, ua->argv[j], &mr);
934             break;
935          case 4:
936             update_volmaxfiles(ua, ua->argv[j], &mr);
937             break;
938          case 5:
939             update_volmaxbytes(ua, ua->argv[j], &mr);
940             break;
941          case 6:
942             update_volrecycle(ua, ua->argv[j], &mr);
943             break;
944          case 7:
945             memset(&pr, 0, sizeof(POOL_DBR));
946             pr.PoolId = mr.PoolId;
947             if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
948                bsendmsg(ua, "%s", db_strerror(ua->db));
949                break;
950             }
951             update_vol_pool(ua, ua->argv[j], &mr, &pr);
952             break;
953          case 8:
954             update_volfrompool(ua, &mr);
955             break;
956          case 9:
957             update_all_vols_from_pool(ua);
958          }
959          done = true;
960       }
961    }
962
963    for ( ; !done; ) {
964       if (!select_media_dbr(ua, &mr)) {
965          return 0;
966       }
967       bsendmsg(ua, _("Updating Volume \"%s\"\n"), mr.VolumeName);
968       start_prompt(ua, _("Parameters to modify:\n"));
969       add_prompt(ua, _("Volume Status"));
970       add_prompt(ua, _("Volume Retention Period"));
971       add_prompt(ua, _("Volume Use Duration"));
972       add_prompt(ua, _("Maximum Volume Jobs"));
973       add_prompt(ua, _("Maximum Volume Files"));
974       add_prompt(ua, _("Maximum Volume Bytes"));
975       add_prompt(ua, _("Recycle Flag"));
976       add_prompt(ua, _("Slot"));
977       add_prompt(ua, _("InChanger Flag"));
978       add_prompt(ua, _("Volume Files"));
979       add_prompt(ua, _("Pool"));
980       add_prompt(ua, _("Volume from Pool"));
981       add_prompt(ua, _("All Volumes from Pool"));
982       add_prompt(ua, _("Done"));
983       switch (do_prompt(ua, "", _("Select parameter to modify"), NULL, 0)) {
984       case 0:                         /* Volume Status */
985          /* Modify Volume Status */
986          bsendmsg(ua, _("Current Volume status is: %s\n"), mr.VolStatus);
987          start_prompt(ua, _("Possible Values are:\n"));
988          add_prompt(ua, "Append");      /* Better not translate these as */
989          add_prompt(ua, "Archive");     /* They are known in the database code */
990          add_prompt(ua, "Disabled");
991          add_prompt(ua, "Full");
992          add_prompt(ua, "Used");
993          add_prompt(ua, "Cleaning");
994          if (strcmp(mr.VolStatus, "Purged") == 0) {
995             add_prompt(ua, "Recycle");
996          }
997          add_prompt(ua, "Read-Only");
998          if (do_prompt(ua, "", _("Choose new Volume Status"), ua->cmd, sizeof(mr.VolStatus)) < 0) {
999             return 1;
1000          }
1001          update_volstatus(ua, ua->cmd, &mr);
1002          break;
1003       case 1:                         /* Retention */
1004          bsendmsg(ua, _("Current retention period is: %s\n"),
1005             edit_utime(mr.VolRetention, ed1, sizeof(ed1)));
1006          if (!get_cmd(ua, _("Enter Volume Retention period: "))) {
1007             return 0;
1008          }
1009          update_volretention(ua, ua->cmd, &mr);
1010          break;
1011
1012       case 2:                         /* Use Duration */
1013          bsendmsg(ua, _("Current use duration is: %s\n"),
1014             edit_utime(mr.VolUseDuration, ed1, sizeof(ed1)));
1015          if (!get_cmd(ua, _("Enter Volume Use Duration: "))) {
1016             return 0;
1017          }
1018          update_voluseduration(ua, ua->cmd, &mr);
1019          break;
1020
1021       case 3:                         /* Max Jobs */
1022          bsendmsg(ua, _("Current max jobs is: %u\n"), mr.MaxVolJobs);
1023          if (!get_pint(ua, _("Enter new Maximum Jobs: "))) {
1024             return 0;
1025          }
1026          update_volmaxjobs(ua, ua->cmd, &mr);
1027          break;
1028
1029       case 4:                         /* Max Files */
1030          bsendmsg(ua, _("Current max files is: %u\n"), mr.MaxVolFiles);
1031          if (!get_pint(ua, _("Enter new Maximum Files: "))) {
1032             return 0;
1033          }
1034          update_volmaxfiles(ua, ua->cmd, &mr);
1035          break;
1036
1037       case 5:                         /* Max Bytes */
1038          bsendmsg(ua, _("Current value is: %s\n"), edit_uint64(mr.MaxVolBytes, ed1));
1039          if (!get_cmd(ua, _("Enter new Maximum Bytes: "))) {
1040             return 0;
1041          }
1042          update_volmaxbytes(ua, ua->cmd, &mr);
1043          break;
1044
1045
1046       case 6:                         /* Recycle */
1047          bsendmsg(ua, _("Current recycle flag is: %s\n"),
1048             mr.Recycle==1?_("yes"):_("no"));
1049          if (!get_yesno(ua, _("Enter new Recycle status: "))) {
1050             return 0;
1051          }
1052          update_volrecycle(ua, ua->cmd, &mr);
1053          break;
1054
1055       case 7:                         /* Slot */
1056          int Slot;
1057
1058          memset(&pr, 0, sizeof(POOL_DBR));
1059          pr.PoolId = mr.PoolId;
1060          if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
1061             bsendmsg(ua, "%s", db_strerror(ua->db));
1062             return 0;
1063          }
1064          bsendmsg(ua, _("Current Slot is: %d\n"), mr.Slot);
1065          if (!get_pint(ua, _("Enter new Slot: "))) {
1066             return 0;
1067          }
1068          Slot = ua->pint32_val;
1069          if (pr.MaxVols > 0 && Slot > (int)pr.MaxVols) {
1070             bsendmsg(ua, _("Invalid slot, it must be between 0 and %d\n"),
1071                pr.MaxVols);
1072             break;
1073          }
1074          mr.Slot = Slot;
1075          /*
1076           * Make sure to use db_update... rather than doing this directly,
1077           *   so that any Slot is handled correctly. 
1078           */
1079          if (!db_update_media_record(ua->jcr, ua->db, &mr)) {
1080             bsendmsg(ua, _("Error updating media record Slot: ERR=%s"), db_strerror(ua->db));
1081          } else {
1082             bsendmsg(ua, _("New Slot is: %d\n"), mr.Slot);
1083          }
1084          break;
1085
1086       case 8:                         /* InChanger */
1087          bsendmsg(ua, _("Current InChanger flag is: %d\n"), mr.InChanger);
1088          if (!get_yesno(ua, _("Set InChanger flag? yes/no: "))) {
1089             return 0;
1090          }
1091          mr.InChanger = ua->pint32_val;
1092          /*
1093           * Make sure to use db_update... rather than doing this directly,
1094           *   so that any Slot is handled correctly. 
1095           */
1096          if (!db_update_media_record(ua->jcr, ua->db, &mr)) {
1097             bsendmsg(ua, _("Error updating media record Slot: ERR=%s"), db_strerror(ua->db));
1098          } else {
1099             bsendmsg(ua, _("New InChanger flag is: %d\n"), mr.InChanger);
1100          }
1101          break;
1102
1103
1104       case 9:                         /* Volume Files */
1105          int32_t VolFiles;
1106          bsendmsg(ua, _("Warning changing Volume Files can result\n"
1107                         "in loss of data on your Volume\n\n"));
1108          bsendmsg(ua, _("Current Volume Files is: %u\n"), mr.VolFiles);
1109          if (!get_pint(ua, _("Enter new number of Files for Volume: "))) {
1110             return 0;
1111          }
1112          VolFiles = ua->pint32_val;
1113          if (VolFiles != (int)(mr.VolFiles + 1)) {
1114             bsendmsg(ua, _("Normally, you should only increase Volume Files by one!\n"));
1115             if (!get_yesno(ua, _("Continue? (yes/no): ")) || ua->pint32_val == 0) {
1116                break;
1117             }
1118          }
1119          query = get_pool_memory(PM_MESSAGE);
1120          Mmsg(&query, "UPDATE Media SET VolFiles=%u WHERE MediaId=%u",
1121             VolFiles, mr.MediaId);
1122          if (!db_sql_query(ua->db, query, NULL, NULL)) {  
1123             bsendmsg(ua, "%s", db_strerror(ua->db));
1124          } else {
1125             bsendmsg(ua, _("New Volume Files is: %u\n"), VolFiles);
1126          }
1127          free_pool_memory(query);
1128          break;
1129
1130       case 10:                        /* Volume's Pool */
1131          memset(&pr, 0, sizeof(POOL_DBR));
1132          pr.PoolId = mr.PoolId;
1133          if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
1134             bsendmsg(ua, "%s", db_strerror(ua->db));
1135             return 0;
1136          }
1137          bsendmsg(ua, _("Current Pool is: %s\n"), pr.Name);
1138          if (!get_cmd(ua, _("Enter new Pool name: "))) {
1139             return 0;
1140          }
1141          update_vol_pool(ua, ua->cmd, &mr, &pr);
1142          return 1;
1143
1144       case 11:
1145          update_volfrompool(ua, &mr);
1146          break;
1147       case 12:
1148          update_all_vols_from_pool(ua);
1149          break;
1150       default:                        /* Done or error */
1151          bsendmsg(ua, "Selection done.\n");
1152          return 1;
1153       }
1154    }
1155    return 1;
1156 }
1157
1158 /* 
1159  * Update pool record -- pull info from current POOL resource
1160  */
1161 static int update_pool(UAContext *ua)
1162 {
1163    POOL_DBR  pr;
1164    int id;
1165    POOL *pool;
1166    POOLMEM *query;       
1167    
1168    pool = get_pool_resource(ua);
1169    if (!pool) {
1170       return 0;
1171    }
1172
1173    memset(&pr, 0, sizeof(pr));
1174    strcpy(pr.Name, pool->hdr.name);
1175    if (!get_pool_dbr(ua, &pr)) {
1176       return 0;
1177    }
1178
1179    set_pooldbr_from_poolres(&pr, pool, POOL_OP_UPDATE); /* update */
1180
1181    id = db_update_pool_record(ua->jcr, ua->db, &pr);
1182    if (id <= 0) {
1183       bsendmsg(ua, _("db_update_pool_record returned %d. ERR=%s\n"),
1184          id, db_strerror(ua->db));
1185    }
1186    query = get_pool_memory(PM_MESSAGE);
1187    Mmsg(&query, list_pool, pr.PoolId);
1188    db_list_sql_query(ua->jcr, ua->db, query, prtit, ua, 1, HORZ_LIST);
1189    free_pool_memory(query);
1190    bsendmsg(ua, _("Pool DB record updated from resource.\n"));
1191    return 1;
1192 }
1193
1194
1195 static void do_storage_setdebug(UAContext *ua, STORE *store, int level, int trace_flag)
1196 {
1197    BSOCK *sd;
1198
1199    ua->jcr->store = store;
1200    /* Try connecting for up to 15 seconds */
1201    bsendmsg(ua, _("Connecting to Storage daemon %s at %s:%d\n"), 
1202       store->hdr.name, store->address, store->SDport);
1203    if (!connect_to_storage_daemon(ua->jcr, 1, 15, 0)) {
1204       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1205       return;
1206    }
1207    Dmsg0(120, _("Connected to storage daemon\n"));
1208    sd = ua->jcr->store_bsock;
1209    bnet_fsend(sd, "setdebug=%d trace=%d\n", level, trace_flag);
1210    if (bnet_recv(sd) >= 0) {
1211       bsendmsg(ua, "%s", sd->msg);
1212    }
1213    bnet_sig(sd, BNET_TERMINATE);
1214    bnet_close(sd);
1215    ua->jcr->store_bsock = NULL;
1216    return;  
1217 }
1218    
1219 static void do_client_setdebug(UAContext *ua, CLIENT *client, int level, int trace_flag)
1220 {
1221    BSOCK *fd;
1222
1223    /* Connect to File daemon */
1224
1225    ua->jcr->client = client;
1226    /* Try to connect for 15 seconds */
1227    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"), 
1228       client->hdr.name, client->address, client->FDport);
1229    if (!connect_to_file_daemon(ua->jcr, 1, 15, 0)) {
1230       bsendmsg(ua, _("Failed to connect to Client.\n"));
1231       return;
1232    }
1233    Dmsg0(120, "Connected to file daemon\n");
1234    fd = ua->jcr->file_bsock;
1235    bnet_fsend(fd, "setdebug=%d trace=%d\n", level, trace_flag);
1236    if (bnet_recv(fd) >= 0) {
1237       bsendmsg(ua, "%s", fd->msg);
1238    }
1239    bnet_sig(fd, BNET_TERMINATE);
1240    bnet_close(fd);
1241    ua->jcr->file_bsock = NULL;
1242    return;  
1243 }
1244
1245
1246 static void do_all_setdebug(UAContext *ua, int level, int trace_flag)
1247 {
1248    STORE *store, **unique_store;
1249    CLIENT *client, **unique_client;
1250    int i, j, found;
1251
1252    /* Director */
1253    debug_level = level;
1254
1255    /* Count Storage items */
1256    LockRes();
1257    store = NULL;
1258    for (i=0; (store = (STORE *)GetNextRes(R_STORAGE, (RES *)store)); i++)
1259       { }
1260    unique_store = (STORE **) malloc(i * sizeof(STORE));
1261    /* Find Unique Storage address/port */         
1262    store = (STORE *)GetNextRes(R_STORAGE, NULL);
1263    i = 0;
1264    unique_store[i++] = store;
1265    while ((store = (STORE *)GetNextRes(R_STORAGE, (RES *)store))) {
1266       found = 0;
1267       for (j=0; j<i; j++) {
1268          if (strcmp(unique_store[j]->address, store->address) == 0 &&
1269              unique_store[j]->SDport == store->SDport) {
1270             found = 1;
1271             break;
1272          }
1273       }
1274       if (!found) {
1275          unique_store[i++] = store;
1276          Dmsg2(140, "Stuffing: %s:%d\n", store->address, store->SDport);
1277       }
1278    }
1279    UnlockRes();
1280
1281    /* Call each unique Storage daemon */
1282    for (j=0; j<i; j++) {
1283       do_storage_setdebug(ua, unique_store[j], level, trace_flag);
1284    }
1285    free(unique_store);
1286
1287    /* Count Client items */
1288    LockRes();
1289    client = NULL;
1290    for (i=0; (client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client)); i++)
1291       { }
1292    unique_client = (CLIENT **) malloc(i * sizeof(CLIENT));
1293    /* Find Unique Client address/port */         
1294    client = (CLIENT *)GetNextRes(R_CLIENT, NULL);
1295    i = 0;
1296    unique_client[i++] = client;
1297    while ((client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client))) {
1298       found = 0;
1299       for (j=0; j<i; j++) {
1300          if (strcmp(unique_client[j]->address, client->address) == 0 &&
1301              unique_client[j]->FDport == client->FDport) {
1302             found = 1;
1303             break;
1304          }
1305       }
1306       if (!found) {
1307          unique_client[i++] = client;
1308          Dmsg2(140, "Stuffing: %s:%d\n", client->address, client->FDport);
1309       }
1310    }
1311    UnlockRes();
1312
1313    /* Call each unique File daemon */
1314    for (j=0; j<i; j++) {
1315       do_client_setdebug(ua, unique_client[j], level, trace_flag);
1316    }
1317    free(unique_client);
1318 }
1319
1320 /*
1321  * setdebug level=nn all trace=1/0
1322  */
1323 static int setdebug_cmd(UAContext *ua, const char *cmd)
1324 {
1325    STORE *store;
1326    CLIENT *client;
1327    int level;
1328    int trace_flag = -1;
1329    int i;
1330
1331    if (!open_db(ua)) {
1332       return 1;
1333    }
1334    Dmsg1(120, "setdebug:%s:\n", cmd);
1335
1336    level = -1;
1337    i = find_arg_with_value(ua, _("level"));
1338    if (i >= 0) {
1339       level = atoi(ua->argv[i]);
1340    }
1341    if (level < 0) {
1342       if (!get_pint(ua, _("Enter new debug level: "))) {
1343          return 1;
1344       }
1345       level = ua->pint32_val;
1346    }
1347
1348    /* Look for trace flag. -1 => not change */
1349    i = find_arg_with_value(ua, _("trace"));
1350    if (i >= 0) {
1351       trace_flag = atoi(ua->argv[i]);
1352       if (trace_flag > 0) {
1353          trace_flag = 1;
1354       }
1355    }
1356
1357    /* General debug? */
1358    for (i=1; i<ua->argc; i++) {
1359       if (strcasecmp(ua->argk[i], _("all")) == 0) {
1360          do_all_setdebug(ua, level, trace_flag);
1361          return 1;
1362       }
1363       if (strcasecmp(ua->argk[i], _("dir")) == 0 ||
1364           strcasecmp(ua->argk[i], _("director")) == 0) {
1365          debug_level = level;
1366          set_trace(trace_flag);
1367          return 1;
1368       }
1369       if (strcasecmp(ua->argk[i], _("client")) == 0 ||
1370           strcasecmp(ua->argk[i], _("fd")) == 0) {
1371          client = NULL;
1372          if (ua->argv[i]) {
1373             client = (CLIENT *)GetResWithName(R_CLIENT, ua->argv[i]);
1374             if (client) {
1375                do_client_setdebug(ua, client, level, trace_flag);
1376                return 1;
1377             }
1378          }
1379          client = select_client_resource(ua);   
1380          if (client) {
1381             do_client_setdebug(ua, client, level, trace_flag);
1382             return 1;
1383          }
1384       }
1385
1386       if (strcasecmp(ua->argk[i], _("store")) == 0 ||
1387           strcasecmp(ua->argk[i], _("storage")) == 0 ||
1388           strcasecmp(ua->argk[i], _("sd")) == 0) {
1389          store = NULL;
1390          if (ua->argv[i]) {
1391             store = (STORE *)GetResWithName(R_STORAGE, ua->argv[i]);
1392             if (store) {
1393                do_storage_setdebug(ua, store, level, trace_flag);
1394                return 1;
1395             }
1396          }
1397          store = get_storage_resource(ua, 0);
1398          if (store) {
1399             do_storage_setdebug(ua, store, level, trace_flag);
1400             return 1;
1401          }
1402       }
1403    } 
1404    /*
1405     * We didn't find an appropriate keyword above, so
1406     * prompt the user.
1407     */
1408    start_prompt(ua, _("Available daemons are: \n"));
1409    add_prompt(ua, _("Director"));
1410    add_prompt(ua, _("Storage"));
1411    add_prompt(ua, _("Client"));
1412    add_prompt(ua, _("All"));
1413    switch(do_prompt(ua, "", _("Select daemon type to set debug level"), NULL, 0)) {
1414    case 0:                         /* Director */
1415       debug_level = level;
1416       set_trace(trace_flag);
1417       break;
1418    case 1:
1419       store = get_storage_resource(ua, 0);
1420       if (store) {
1421          do_storage_setdebug(ua, store, level, trace_flag);
1422       }
1423       break;
1424    case 2:
1425       client = select_client_resource(ua);
1426       if (client) {
1427          do_client_setdebug(ua, client, level, trace_flag);
1428       }
1429       break;
1430    case 3:
1431       do_all_setdebug(ua, level, trace_flag);
1432       break;
1433    default:
1434       break;
1435    }
1436    return 1;
1437 }
1438
1439 /*
1440  * Turn debug tracing to file on/off
1441  */
1442 static int trace_cmd(UAContext *ua, const char *cmd)
1443 {
1444    char *onoff;
1445
1446    if (ua->argc != 2) {
1447       if (!get_cmd(ua, _("Turn on or off? "))) {
1448             return 1;
1449       }
1450       onoff = ua->cmd;
1451    } else {
1452       onoff = ua->argk[1];
1453    }
1454
1455    set_trace((strcasecmp(onoff, _("off")) == 0) ? false : true);
1456    return 1; 
1457
1458 }
1459
1460 static int var_cmd(UAContext *ua, const char *cmd)
1461 {
1462    POOLMEM *val = get_pool_memory(PM_FNAME);
1463    char *var;
1464
1465    if (!open_db(ua)) {
1466       return 1;
1467    }
1468    for (var=ua->cmd; *var != ' '; ) {    /* skip command */
1469       var++;
1470    }
1471    while (*var == ' ') {                 /* skip spaces */
1472       var++;
1473    }
1474    Dmsg1(100, "Var=%s:\n", var);
1475    variable_expansion(ua->jcr, var, &val);  
1476    bsendmsg(ua, "%s\n", val);
1477    free_pool_memory(val);
1478    return 1;
1479 }
1480
1481 static int estimate_cmd(UAContext *ua, const char *cmd)
1482 {
1483    JOB *job = NULL;
1484    CLIENT *client = NULL;
1485    FILESET *fileset = NULL;
1486    FILESET_DBR fsr;
1487    int listing = 0;
1488    char since[MAXSTRING];
1489    JCR *jcr = ua->jcr;
1490
1491    jcr->JobLevel = L_FULL;
1492    for (int i=1; i<ua->argc; i++) {
1493       if (strcasecmp(ua->argk[i], _("client")) == 0 ||
1494           strcasecmp(ua->argk[i], _("fd")) == 0) {
1495          if (ua->argv[i]) {
1496             client = (CLIENT *)GetResWithName(R_CLIENT, ua->argv[i]);
1497             continue;
1498          }
1499       }
1500       if (strcasecmp(ua->argk[i], _("job")) == 0) {
1501          if (ua->argv[i]) {
1502             job = (JOB *)GetResWithName(R_JOB, ua->argv[i]);
1503             continue;
1504          }
1505       }
1506       if (strcasecmp(ua->argk[i], _("fileset")) == 0) {
1507          if (ua->argv[i]) {
1508             fileset = (FILESET *)GetResWithName(R_FILESET, ua->argv[i]);
1509             continue;
1510          }
1511       }
1512       if (strcasecmp(ua->argk[i], _("listing")) == 0) {
1513          listing = 1;
1514          continue;
1515       }
1516       if (strcasecmp(ua->argk[i], _("level")) == 0) {
1517          if (!get_level_from_name(ua->jcr, ua->argv[i])) {
1518             bsendmsg(ua, _("Level %s not valid.\n"), ua->argv[i]);
1519          }
1520          continue;
1521       }
1522    } 
1523    if (!job && !(client && fileset)) {
1524       if (!(job = select_job_resource(ua))) {
1525          return 1;
1526       }
1527    }
1528    if (!job) {
1529       job = (JOB *)GetResWithName(R_JOB, ua->argk[1]);
1530       if (!job) {
1531          bsendmsg(ua, _("No job specified.\n"));
1532          return 1;
1533       }
1534    }
1535    if (!client) {
1536       client = job->client;
1537    }
1538    if (!fileset) {
1539       fileset = job->fileset;
1540    }
1541    jcr->client = client;
1542    jcr->fileset = fileset;
1543    close_db(ua);
1544    ua->catalog = client->catalog;
1545
1546    if (!open_db(ua)) {
1547       return 1;
1548    }
1549
1550    jcr->job = job;
1551    jcr->JobType = JT_BACKUP;
1552    init_jcr_job_record(jcr);
1553
1554    if (!get_or_create_client_record(jcr)) {
1555       return 1;
1556    }
1557    if (!get_or_create_fileset_record(jcr, &fsr)) {
1558       return 1;
1559    }
1560    
1561    get_level_since_time(ua->jcr, since, sizeof(since));
1562
1563    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"),
1564       job->client->hdr.name, job->client->address, job->client->FDport);
1565    if (!connect_to_file_daemon(jcr, 1, 15, 0)) {
1566       bsendmsg(ua, _("Failed to connect to Client.\n"));
1567       return 1;
1568    }
1569
1570    if (!send_include_list(jcr)) {
1571       bsendmsg(ua, _("Error sending include list.\n"));
1572       goto bail_out;
1573    }
1574
1575    if (!send_exclude_list(jcr)) {
1576       bsendmsg(ua, _("Error sending exclude list.\n"));
1577       goto bail_out;
1578    }
1579
1580    if (!send_level_command(jcr)) {
1581       goto bail_out;
1582    }
1583
1584    bnet_fsend(jcr->file_bsock, "estimate listing=%d\n", listing);
1585    while (bnet_recv(jcr->file_bsock) >= 0) {
1586       bsendmsg(ua, "%s", jcr->file_bsock->msg);
1587    }
1588
1589 bail_out:
1590    if (jcr->file_bsock) {
1591       bnet_sig(jcr->file_bsock, BNET_TERMINATE);
1592       bnet_close(jcr->file_bsock);
1593       jcr->file_bsock = NULL;
1594    }
1595    return 1;
1596 }
1597
1598
1599 /*
1600  * print time
1601  */
1602 static int time_cmd(UAContext *ua, const char *cmd)
1603 {
1604    char sdt[50];
1605    time_t ttime = time(NULL);
1606    struct tm tm;
1607    localtime_r(&ttime, &tm);
1608    strftime(sdt, sizeof(sdt), "%d-%b-%Y %H:%M:%S", &tm);
1609    bsendmsg(ua, "%s\n", sdt);
1610    return 1;
1611 }
1612
1613 /*
1614  * reload the conf file
1615  */
1616 extern "C" void reload_config(int sig);
1617
1618 static int reload_cmd(UAContext *ua, const char *cmd)
1619 {
1620    reload_config(1);   
1621    return 1;
1622 }
1623
1624
1625
1626 /*
1627  * Delete Pool records (should purge Media with it).
1628  *
1629  *  delete pool=<pool-name>
1630  *  delete volume pool=<pool-name> volume=<name>
1631  *  delete job jobid=xxx
1632  */
1633 static int delete_cmd(UAContext *ua, const char *cmd)
1634 {
1635    static const char *keywords[] = {
1636       N_("volume"),
1637       N_("pool"),
1638       N_("job"),
1639       N_("jobid"),
1640       NULL};
1641
1642    if (!open_db(ua)) {
1643       return 1;
1644    }
1645
1646    switch (find_arg_keyword(ua, keywords)) {      
1647    case 0:
1648       delete_volume(ua);     
1649       return 1;
1650    case 1:
1651       delete_pool(ua);
1652       return 1;
1653    case 2:
1654    case 3:
1655       int i;
1656       while ((i=find_arg(ua, _("jobid"))) > 0) {
1657          delete_job(ua);
1658          *ua->argk[i] = 0;         /* zap keyword already visited */
1659       }
1660       return 1;
1661    default:
1662       break;
1663    }
1664
1665    bsendmsg(ua, _(
1666 "In general it is not a good idea to delete either a\n"
1667 "Pool or a Volume since they may contain data.\n\n"));
1668
1669    switch (do_keyword_prompt(ua, _("Choose catalog item to delete"), keywords)) {
1670    case 0:
1671       delete_volume(ua);
1672       break;
1673    case 1:
1674       delete_pool(ua);
1675       break;
1676    case 2:
1677       delete_job(ua);
1678       return 1;
1679    default:
1680       bsendmsg(ua, _("Nothing done.\n"));
1681       break;
1682    }
1683    return 1;
1684 }
1685
1686 static int delete_job(UAContext *ua)
1687 {
1688    POOLMEM *query = get_pool_memory(PM_MESSAGE);
1689    JobId_t JobId;
1690
1691    int i = find_arg_with_value(ua, _("jobid"));
1692    if (i >= 0) {
1693       JobId = str_to_int64(ua->argv[i]);
1694    } else if (!get_pint(ua, _("Enter JobId to delete: "))) {
1695       return 0;
1696    } else {
1697       JobId = ua->pint32_val; 
1698    }
1699    Mmsg(&query, "DELETE FROM Job WHERE JobId=%u", JobId);
1700    db_sql_query(ua->db, query, NULL, (void *)NULL);
1701    Mmsg(&query, "DELETE FROM File WHERE JobId=%u", JobId);
1702    db_sql_query(ua->db, query, NULL, (void *)NULL);
1703    Mmsg(&query, "DELETE FROM JobMedia WHERE JobId=%u", JobId);
1704    db_sql_query(ua->db, query, NULL, (void *)NULL);
1705    free_pool_memory(query);
1706    bsendmsg(ua, _("Job %u and associated records deleted from the catalog.\n"), JobId);
1707    return 1;
1708 }
1709
1710 /*
1711  * Delete media records from database -- dangerous 
1712  */
1713 static int delete_volume(UAContext *ua)
1714 {
1715    MEDIA_DBR mr;
1716
1717    if (!select_media_dbr(ua, &mr)) {
1718       return 1;
1719    }
1720    bsendmsg(ua, _("\nThis command will delete volume %s\n"
1721       "and all Jobs saved on that volume from the Catalog\n"),
1722       mr.VolumeName);
1723
1724    if (!get_yesno(ua, _("Are you sure you want to delete this Volume? (yes/no): "))) {
1725       return 1;
1726    }
1727    if (ua->pint32_val) {
1728       db_delete_media_record(ua->jcr, ua->db, &mr);
1729    }
1730    return 1;
1731 }
1732
1733 /*
1734  * Delete a pool record from the database -- dangerous   
1735  */
1736 static int delete_pool(UAContext *ua)
1737 {
1738    POOL_DBR  pr;
1739    
1740    memset(&pr, 0, sizeof(pr));
1741
1742    if (!get_pool_dbr(ua, &pr)) {
1743       return 1;
1744    }
1745    if (!get_yesno(ua, _("Are you sure you want to delete this Pool? (yes/no): "))) {
1746       return 1;
1747    }
1748    if (ua->pint32_val) {
1749       db_delete_pool_record(ua->jcr, ua->db, &pr);
1750    }
1751    return 1;
1752 }
1753
1754
1755 static void do_mount_cmd(UAContext *ua, const char *command)
1756 {
1757    STORE *store;
1758    BSOCK *sd;
1759    char dev_name[MAX_NAME_LENGTH];
1760
1761
1762    if (!open_db(ua)) {
1763       return;
1764    }
1765    Dmsg2(120, "%s: %s\n", command, ua->UA_sock->msg);
1766
1767    store = get_storage_resource(ua, 1);
1768    if (!store) {
1769       return;
1770    }
1771
1772    Dmsg2(120, "Found storage, MediaType=%s DevName=%s\n",
1773       store->media_type, store->dev_name);
1774
1775    ua->jcr->store = store;
1776    if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
1777       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1778       return;
1779    }
1780    sd = ua->jcr->store_bsock;
1781    strcpy(dev_name, store->dev_name);
1782    bash_spaces(dev_name);
1783    bnet_fsend(sd, "%s %s", command, dev_name);
1784    while (bnet_recv(sd) >= 0) {
1785       bsendmsg(ua, "%s", sd->msg);
1786    }
1787    bnet_sig(sd, BNET_TERMINATE);
1788    bnet_close(sd);
1789    ua->jcr->store_bsock = NULL;
1790 }
1791
1792 /*
1793  * mount [storage | device] <name>
1794  */
1795 static int mount_cmd(UAContext *ua, const char *cmd)
1796 {
1797    do_mount_cmd(ua, "mount");          /* mount */
1798    return 1;
1799 }
1800
1801
1802 /*
1803  * unmount [storage | device] <name>
1804  */
1805 static int unmount_cmd(UAContext *ua, const char *cmd)
1806 {
1807    do_mount_cmd(ua, "unmount");          /* unmount */
1808    return 1;
1809 }
1810
1811
1812 /*
1813  * release [storage | device] <name>
1814  */
1815 static int release_cmd(UAContext *ua, const char *cmd)
1816 {
1817    do_mount_cmd(ua, "release");          /* release */
1818    return 1;
1819 }
1820
1821
1822 /*
1823  * Switch databases
1824  *   use catalog=<name>
1825  */
1826 static int use_cmd(UAContext *ua, const char *cmd)
1827 {
1828    CAT *oldcatalog, *catalog;
1829
1830
1831    close_db(ua);                      /* close any previously open db */
1832    oldcatalog = ua->catalog;
1833
1834    if (!(catalog = get_catalog_resource(ua))) {
1835       ua->catalog = oldcatalog;
1836    } else {
1837       ua->catalog = catalog;
1838    }
1839    if (open_db(ua)) {
1840       bsendmsg(ua, _("Using Catalog name=%s DB=%s\n"),
1841          ua->catalog->hdr.name, ua->catalog->db_name);
1842    }
1843    return 1;
1844 }
1845
1846 int quit_cmd(UAContext *ua, const char *cmd) 
1847 {
1848    ua->quit = TRUE;
1849    return 1;
1850 }
1851
1852 /*
1853  * Wait until no job is running 
1854  */
1855 int wait_cmd(UAContext *ua, const char *cmd) 
1856 {
1857    JCR *jcr;
1858    bmicrosleep(0, 200000);            /* let job actually start */
1859    for (bool running=true; running; ) {
1860       running = false;
1861       lock_jcr_chain();
1862       foreach_jcr(jcr) {
1863          if (jcr->JobId != 0) {
1864             running = true;
1865             free_locked_jcr(jcr);
1866             break;
1867          }
1868          free_locked_jcr(jcr);
1869       }
1870       unlock_jcr_chain();
1871       if (running) {
1872          bmicrosleep(1, 0);
1873       }
1874    }
1875    return 1;
1876 }
1877
1878
1879 static int help_cmd(UAContext *ua, const char *cmd)
1880 {
1881    unsigned int i;
1882
1883    bsendmsg(ua, _("  Command    Description\n  =======    ===========\n"));
1884    for (i=0; i<comsize; i++) {
1885       bsendmsg(ua, _("  %-10s %s\n"), _(commands[i].key), _(commands[i].help));
1886    }
1887    bsendmsg(ua, _("\nWhen at a prompt, entering a period cancels the command.\n\n"));
1888    return 1;
1889 }
1890
1891 int qhelp_cmd(UAContext *ua, const char *cmd)
1892 {
1893    unsigned int i;
1894
1895    for (i=0; i<comsize; i++) {
1896       bsendmsg(ua, _("%s %s\n"), _(commands[i].key), _(commands[i].help));
1897    }
1898    return 1;
1899 }
1900
1901 static int version_cmd(UAContext *ua, const char *cmd)
1902 {
1903    bsendmsg(ua, "%s Version: " VERSION " (" BDATE ")\n", my_name);
1904    return 1;
1905 }
1906
1907
1908 /* A bit brain damaged in that if the user has not done
1909  * a "use catalog xxx" command, we simply find the first
1910  * catalog resource and open it.
1911  */
1912 int open_db(UAContext *ua)
1913 {
1914    if (ua->db) {
1915       return 1;
1916    }
1917    if (!ua->catalog) {
1918       LockRes();
1919       ua->catalog = (CAT *)GetNextRes(R_CATALOG, NULL);
1920       UnlockRes();
1921       if (!ua->catalog) {    
1922          bsendmsg(ua, _("Could not find a Catalog resource\n"));
1923          return 0;
1924       } else {
1925          bsendmsg(ua, _("Using default Catalog name=%s DB=%s\n"), 
1926             ua->catalog->hdr.name, ua->catalog->db_name);
1927       }
1928    }
1929
1930    ua->jcr->catalog = ua->catalog;
1931
1932    Dmsg0(150, "Open database\n");
1933    ua->db = db_init_database(ua->jcr, ua->catalog->db_name, ua->catalog->db_user,
1934                              ua->catalog->db_password, ua->catalog->db_address,
1935                              ua->catalog->db_port, ua->catalog->db_socket);
1936    if (!ua->db || !db_open_database(ua->jcr, ua->db)) {
1937       bsendmsg(ua, _("Could not open database \"%s\".\n"),
1938                  ua->catalog->db_name);
1939       if (ua->db) {
1940          bsendmsg(ua, "%s", db_strerror(ua->db));
1941       }
1942       close_db(ua);
1943       return 0;
1944    }
1945    ua->jcr->db = ua->db;
1946    Dmsg1(150, "DB %s opened\n", ua->catalog->db_name);
1947    return 1;
1948 }
1949
1950 void close_db(UAContext *ua)
1951 {
1952    if (ua->db) {
1953       db_close_database(ua->jcr, ua->db);
1954       ua->db = NULL;
1955       if (ua->jcr) {
1956          ua->jcr->db = NULL;
1957       }
1958    }
1959 }