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