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