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