]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/ua_cmds.c
8146d281d4d8a3b82edfdf4295aeeea25a9581dd
[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    }
866    db_unlock(ua->db);
867    free_pool_memory(query);
868 }
869
870 /*
871  * Refresh the Volume information from the Pool record
872  */
873 static void update_volfrompool(UAContext *ua, MEDIA_DBR *mr)
874 {
875    POOL_DBR pr;
876
877    memset(&pr, 0, sizeof(pr));
878    pr.PoolId = mr->PoolId;
879    if (!db_get_pool_record(ua->jcr, ua->db, &pr) ||
880        !acl_access_ok(ua, Pool_ACL, pr.Name)) {
881       return;
882    }
883    set_pool_dbr_defaults_in_media_dbr(mr, &pr);
884    if (!db_update_media_defaults(ua->jcr, ua->db, mr)) {
885       bsendmsg(ua, _("Error updating Volume record: ERR=%s"), db_strerror(ua->db));
886    } else {
887       bsendmsg(ua, _("Volume defaults updated from \"%s\" Pool record.\n"),
888          pr.Name);
889    }
890 }
891
892 /*
893  * Refresh the Volume information from the Pool record
894  *   for all Volumes
895  */
896 static void update_all_vols_from_pool(UAContext *ua)
897 {
898    POOL_DBR pr;
899    MEDIA_DBR mr;
900
901    memset(&pr, 0, sizeof(pr));
902    memset(&mr, 0, sizeof(mr));
903    if (!get_pool_dbr(ua, &pr)) {
904       return;
905    }
906    set_pool_dbr_defaults_in_media_dbr(&mr, &pr);
907    mr.PoolId = pr.PoolId;
908    if (!db_update_media_defaults(ua->jcr, ua->db, &mr)) {
909       bsendmsg(ua, _("Error updating Volume records: ERR=%s"), db_strerror(ua->db));
910    } else {
911       bsendmsg(ua, _("All Volume defaults updated from Pool record.\n"));
912    }
913 }
914
915
916 /*
917  * Update a media record -- allows you to change the
918  *  Volume status. E.g. if you want Bacula to stop
919  *  writing on the volume, set it to anything other
920  *  than Append.
921  */
922 static int update_volume(UAContext *ua)
923 {
924    MEDIA_DBR mr;
925    POOL_DBR pr;
926    POOLMEM *query;
927    char ed1[130];
928    bool done = false;
929    const char *kw[] = {
930       N_("VolStatus"),                /* 0 */
931       N_("VolRetention"),             /* 1 */
932       N_("VolUse"),                   /* 2 */
933       N_("MaxVolJobs"),               /* 3 */
934       N_("MaxVolFiles"),              /* 4 */
935       N_("MaxVolBytes"),              /* 5 */
936       N_("Recycle"),                  /* 6 */
937       N_("Pool"),                     /* 7 */
938       N_("FromPool"),                 /* 8 */
939       N_("AllFromPool"),              /* 9 */
940       NULL };
941
942    for (int i=0; kw[i]; i++) {
943       int j;
944       POOL_DBR pr;
945       if ((j=find_arg_with_value(ua, kw[i])) > 0) {
946          if (i != 9 && !select_media_dbr(ua, &mr)) {
947             return 0;
948          }
949          switch (i) {
950          case 0:
951             update_volstatus(ua, ua->argv[j], &mr);
952             break;
953          case 1:
954             update_volretention(ua, ua->argv[j], &mr);
955             break;
956          case 2:
957             update_voluseduration(ua, ua->argv[j], &mr);
958             break;
959          case 3:
960             update_volmaxjobs(ua, ua->argv[j], &mr);
961             break;
962          case 4:
963             update_volmaxfiles(ua, ua->argv[j], &mr);
964             break;
965          case 5:
966             update_volmaxbytes(ua, ua->argv[j], &mr);
967             break;
968          case 6:
969             update_volrecycle(ua, ua->argv[j], &mr);
970             break;
971          case 7:
972             memset(&pr, 0, sizeof(POOL_DBR));
973             pr.PoolId = mr.PoolId;
974             if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
975                bsendmsg(ua, "%s", db_strerror(ua->db));
976                break;
977             }
978             update_vol_pool(ua, ua->argv[j], &mr, &pr);
979             break;
980          case 8:
981             update_volfrompool(ua, &mr);
982             return 1;
983          case 9:
984             update_all_vols_from_pool(ua);
985             return 1;
986          }
987          done = true;
988       }
989    }
990
991    for ( ; !done; ) {
992       if (!select_media_dbr(ua, &mr)) {
993          return 0;
994       }
995       bsendmsg(ua, _("Updating Volume \"%s\"\n"), mr.VolumeName);
996       start_prompt(ua, _("Parameters to modify:\n"));
997       add_prompt(ua, _("Volume Status"));
998       add_prompt(ua, _("Volume Retention Period"));
999       add_prompt(ua, _("Volume Use Duration"));
1000       add_prompt(ua, _("Maximum Volume Jobs"));
1001       add_prompt(ua, _("Maximum Volume Files"));
1002       add_prompt(ua, _("Maximum Volume Bytes"));
1003       add_prompt(ua, _("Recycle Flag"));
1004       add_prompt(ua, _("Slot"));
1005       add_prompt(ua, _("InChanger Flag"));
1006       add_prompt(ua, _("Volume Files"));
1007       add_prompt(ua, _("Pool"));
1008       add_prompt(ua, _("Volume from Pool"));
1009       add_prompt(ua, _("All Volumes from Pool"));
1010       add_prompt(ua, _("Done"));
1011       switch (do_prompt(ua, "", _("Select parameter to modify"), NULL, 0)) {
1012       case 0:                         /* Volume Status */
1013          /* Modify Volume Status */
1014          bsendmsg(ua, _("Current Volume status is: %s\n"), mr.VolStatus);
1015          start_prompt(ua, _("Possible Values are:\n"));
1016          add_prompt(ua, "Append");      /* Better not translate these as */
1017          add_prompt(ua, "Archive");     /* They are known in the database code */
1018          add_prompt(ua, "Disabled");
1019          add_prompt(ua, "Full");
1020          add_prompt(ua, "Used");
1021          add_prompt(ua, "Cleaning");
1022          if (strcmp(mr.VolStatus, "Purged") == 0) {
1023             add_prompt(ua, "Recycle");
1024          }
1025          add_prompt(ua, "Read-Only");
1026          if (do_prompt(ua, "", _("Choose new Volume Status"), ua->cmd, sizeof(mr.VolStatus)) < 0) {
1027             return 1;
1028          }
1029          update_volstatus(ua, ua->cmd, &mr);
1030          break;
1031       case 1:                         /* Retention */
1032          bsendmsg(ua, _("Current retention period is: %s\n"),
1033             edit_utime(mr.VolRetention, ed1, sizeof(ed1)));
1034          if (!get_cmd(ua, _("Enter Volume Retention period: "))) {
1035             return 0;
1036          }
1037          update_volretention(ua, ua->cmd, &mr);
1038          break;
1039
1040       case 2:                         /* Use Duration */
1041          bsendmsg(ua, _("Current use duration is: %s\n"),
1042             edit_utime(mr.VolUseDuration, ed1, sizeof(ed1)));
1043          if (!get_cmd(ua, _("Enter Volume Use Duration: "))) {
1044             return 0;
1045          }
1046          update_voluseduration(ua, ua->cmd, &mr);
1047          break;
1048
1049       case 3:                         /* Max Jobs */
1050          bsendmsg(ua, _("Current max jobs is: %u\n"), mr.MaxVolJobs);
1051          if (!get_pint(ua, _("Enter new Maximum Jobs: "))) {
1052             return 0;
1053          }
1054          update_volmaxjobs(ua, ua->cmd, &mr);
1055          break;
1056
1057       case 4:                         /* Max Files */
1058          bsendmsg(ua, _("Current max files is: %u\n"), mr.MaxVolFiles);
1059          if (!get_pint(ua, _("Enter new Maximum Files: "))) {
1060             return 0;
1061          }
1062          update_volmaxfiles(ua, ua->cmd, &mr);
1063          break;
1064
1065       case 5:                         /* Max Bytes */
1066          bsendmsg(ua, _("Current value is: %s\n"), edit_uint64(mr.MaxVolBytes, ed1));
1067          if (!get_cmd(ua, _("Enter new Maximum Bytes: "))) {
1068             return 0;
1069          }
1070          update_volmaxbytes(ua, ua->cmd, &mr);
1071          break;
1072
1073
1074       case 6:                         /* Recycle */
1075          bsendmsg(ua, _("Current recycle flag is: %s\n"),
1076             mr.Recycle==1?_("yes"):_("no"));
1077          if (!get_yesno(ua, _("Enter new Recycle status: "))) {
1078             return 0;
1079          }
1080          update_volrecycle(ua, ua->cmd, &mr);
1081          break;
1082
1083       case 7:                         /* Slot */
1084          int Slot;
1085
1086          memset(&pr, 0, sizeof(POOL_DBR));
1087          pr.PoolId = mr.PoolId;
1088          if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
1089             bsendmsg(ua, "%s", db_strerror(ua->db));
1090             return 0;
1091          }
1092          bsendmsg(ua, _("Current Slot is: %d\n"), mr.Slot);
1093          if (!get_pint(ua, _("Enter new Slot: "))) {
1094             return 0;
1095          }
1096          Slot = ua->pint32_val;
1097          if (pr.MaxVols > 0 && Slot > (int)pr.MaxVols) {
1098             bsendmsg(ua, _("Invalid slot, it must be between 0 and %d\n"),
1099                pr.MaxVols);
1100             break;
1101          }
1102          mr.Slot = Slot;
1103          /*
1104           * Make sure to use db_update... rather than doing this directly,
1105           *   so that any Slot is handled correctly.
1106           */
1107          if (!db_update_media_record(ua->jcr, ua->db, &mr)) {
1108             bsendmsg(ua, _("Error updating media record Slot: ERR=%s"), db_strerror(ua->db));
1109          } else {
1110             bsendmsg(ua, _("New Slot is: %d\n"), mr.Slot);
1111          }
1112          break;
1113
1114       case 8:                         /* InChanger */
1115          bsendmsg(ua, _("Current InChanger flag is: %d\n"), mr.InChanger);
1116          if (!get_yesno(ua, _("Set InChanger flag? yes/no: "))) {
1117             return 0;
1118          }
1119          mr.InChanger = ua->pint32_val;
1120          /*
1121           * Make sure to use db_update... rather than doing this directly,
1122           *   so that any Slot is handled correctly.
1123           */
1124          if (!db_update_media_record(ua->jcr, ua->db, &mr)) {
1125             bsendmsg(ua, _("Error updating media record Slot: ERR=%s"), db_strerror(ua->db));
1126          } else {
1127             bsendmsg(ua, _("New InChanger flag is: %d\n"), mr.InChanger);
1128          }
1129          break;
1130
1131
1132       case 9:                         /* Volume Files */
1133          int32_t VolFiles;
1134          bsendmsg(ua, _("Warning changing Volume Files can result\n"
1135                         "in loss of data on your Volume\n\n"));
1136          bsendmsg(ua, _("Current Volume Files is: %u\n"), mr.VolFiles);
1137          if (!get_pint(ua, _("Enter new number of Files for Volume: "))) {
1138             return 0;
1139          }
1140          VolFiles = ua->pint32_val;
1141          if (VolFiles != (int)(mr.VolFiles + 1)) {
1142             bsendmsg(ua, _("Normally, you should only increase Volume Files by one!\n"));
1143             if (!get_yesno(ua, _("Continue? (yes/no): ")) || ua->pint32_val == 0) {
1144                break;
1145             }
1146          }
1147          query = get_pool_memory(PM_MESSAGE);
1148          Mmsg(query, "UPDATE Media SET VolFiles=%u WHERE MediaId=%s",
1149             VolFiles, edit_int64(mr.MediaId, ed1));
1150          if (!db_sql_query(ua->db, query, NULL, NULL)) {
1151             bsendmsg(ua, "%s", db_strerror(ua->db));
1152          } else {
1153             bsendmsg(ua, _("New Volume Files is: %u\n"), VolFiles);
1154          }
1155          free_pool_memory(query);
1156          break;
1157
1158       case 10:                        /* Volume's Pool */
1159          memset(&pr, 0, sizeof(POOL_DBR));
1160          pr.PoolId = mr.PoolId;
1161          if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
1162             bsendmsg(ua, "%s", db_strerror(ua->db));
1163             return 0;
1164          }
1165          bsendmsg(ua, _("Current Pool is: %s\n"), pr.Name);
1166          if (!get_cmd(ua, _("Enter new Pool name: "))) {
1167             return 0;
1168          }
1169          update_vol_pool(ua, ua->cmd, &mr, &pr);
1170          return 1;
1171
1172       case 11:
1173          update_volfrompool(ua, &mr);
1174          return 1;
1175       case 12:
1176          update_all_vols_from_pool(ua);
1177          return 1;
1178       default:                        /* Done or error */
1179          bsendmsg(ua, "Selection done.\n");
1180          return 1;
1181       }
1182    }
1183    return 1;
1184 }
1185
1186 /*
1187  * Update pool record -- pull info from current POOL resource
1188  */
1189 static int update_pool(UAContext *ua)
1190 {
1191    POOL_DBR  pr;
1192    int id;
1193    POOL *pool;
1194    POOLMEM *query;
1195
1196    pool = get_pool_resource(ua);
1197    if (!pool) {
1198       return 0;
1199    }
1200
1201    memset(&pr, 0, sizeof(pr));
1202    bstrncpy(pr.Name, pool->hdr.name, sizeof(pr.Name));
1203    if (!get_pool_dbr(ua, &pr)) {
1204       return 0;
1205    }
1206
1207    set_pooldbr_from_poolres(&pr, pool, POOL_OP_UPDATE); /* update */
1208
1209    id = db_update_pool_record(ua->jcr, ua->db, &pr);
1210    if (id <= 0) {
1211       bsendmsg(ua, _("db_update_pool_record returned %d. ERR=%s\n"),
1212          id, db_strerror(ua->db));
1213    }
1214    query = get_pool_memory(PM_MESSAGE);
1215    Mmsg(query, list_pool, pr.PoolId);
1216    db_list_sql_query(ua->jcr, ua->db, query, prtit, ua, 1, HORZ_LIST);
1217    free_pool_memory(query);
1218    bsendmsg(ua, _("Pool DB record updated from resource.\n"));
1219    return 1;
1220 }
1221
1222
1223 static void do_storage_setdebug(UAContext *ua, STORE *store, int level, int trace_flag)
1224 {
1225    BSOCK *sd;
1226    JCR *jcr = ua->jcr;
1227
1228    set_storage(jcr, store);
1229    /* Try connecting for up to 15 seconds */
1230    bsendmsg(ua, _("Connecting to Storage daemon %s at %s:%d\n"),
1231       store->hdr.name, store->address, store->SDport);
1232    if (!connect_to_storage_daemon(jcr, 1, 15, 0)) {
1233       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1234       return;
1235    }
1236    Dmsg0(120, _("Connected to storage daemon\n"));
1237    sd = jcr->store_bsock;
1238    bnet_fsend(sd, "setdebug=%d trace=%d\n", level, trace_flag);
1239    if (bnet_recv(sd) >= 0) {
1240       bsendmsg(ua, "%s", sd->msg);
1241    }
1242    bnet_sig(sd, BNET_TERMINATE);
1243    bnet_close(sd);
1244    jcr->store_bsock = NULL;
1245    return;
1246 }
1247
1248 static void do_client_setdebug(UAContext *ua, CLIENT *client, int level, int trace_flag)
1249 {
1250    BSOCK *fd;
1251
1252    /* Connect to File daemon */
1253
1254    ua->jcr->client = client;
1255    /* Try to connect for 15 seconds */
1256    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"),
1257       client->hdr.name, client->address, client->FDport);
1258    if (!connect_to_file_daemon(ua->jcr, 1, 15, 0)) {
1259       bsendmsg(ua, _("Failed to connect to Client.\n"));
1260       return;
1261    }
1262    Dmsg0(120, "Connected to file daemon\n");
1263    fd = ua->jcr->file_bsock;
1264    bnet_fsend(fd, "setdebug=%d trace=%d\n", level, trace_flag);
1265    if (bnet_recv(fd) >= 0) {
1266       bsendmsg(ua, "%s", fd->msg);
1267    }
1268    bnet_sig(fd, BNET_TERMINATE);
1269    bnet_close(fd);
1270    ua->jcr->file_bsock = NULL;
1271    return;
1272 }
1273
1274
1275 static void do_all_setdebug(UAContext *ua, int level, int trace_flag)
1276 {
1277    STORE *store, **unique_store;
1278    CLIENT *client, **unique_client;
1279    int i, j, found;
1280
1281    /* Director */
1282    debug_level = level;
1283
1284    /* Count Storage items */
1285    LockRes();
1286    store = NULL;
1287    i = 0;
1288    foreach_res(store, R_STORAGE) {
1289       i++;
1290    }
1291    unique_store = (STORE **) malloc(i * sizeof(STORE));
1292    /* Find Unique Storage address/port */
1293    store = (STORE *)GetNextRes(R_STORAGE, NULL);
1294    i = 0;
1295    unique_store[i++] = store;
1296    while ((store = (STORE *)GetNextRes(R_STORAGE, (RES *)store))) {
1297       found = 0;
1298       for (j=0; j<i; j++) {
1299          if (strcmp(unique_store[j]->address, store->address) == 0 &&
1300              unique_store[j]->SDport == store->SDport) {
1301             found = 1;
1302             break;
1303          }
1304       }
1305       if (!found) {
1306          unique_store[i++] = store;
1307          Dmsg2(140, "Stuffing: %s:%d\n", store->address, store->SDport);
1308       }
1309    }
1310    UnlockRes();
1311
1312    /* Call each unique Storage daemon */
1313    for (j=0; j<i; j++) {
1314       do_storage_setdebug(ua, unique_store[j], level, trace_flag);
1315    }
1316    free(unique_store);
1317
1318    /* Count Client items */
1319    LockRes();
1320    client = NULL;
1321    i = 0;
1322    foreach_res(client, R_CLIENT) {
1323       i++;
1324    }
1325    unique_client = (CLIENT **) malloc(i * sizeof(CLIENT));
1326    /* Find Unique Client address/port */
1327    client = (CLIENT *)GetNextRes(R_CLIENT, NULL);
1328    i = 0;
1329    unique_client[i++] = client;
1330    while ((client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client))) {
1331       found = 0;
1332       for (j=0; j<i; j++) {
1333          if (strcmp(unique_client[j]->address, client->address) == 0 &&
1334              unique_client[j]->FDport == client->FDport) {
1335             found = 1;
1336             break;
1337          }
1338       }
1339       if (!found) {
1340          unique_client[i++] = client;
1341          Dmsg2(140, "Stuffing: %s:%d\n", client->address, client->FDport);
1342       }
1343    }
1344    UnlockRes();
1345
1346    /* Call each unique File daemon */
1347    for (j=0; j<i; j++) {
1348       do_client_setdebug(ua, unique_client[j], level, trace_flag);
1349    }
1350    free(unique_client);
1351 }
1352
1353 /*
1354  * setdebug level=nn all trace=1/0
1355  */
1356 static int setdebug_cmd(UAContext *ua, const char *cmd)
1357 {
1358    STORE *store;
1359    CLIENT *client;
1360    int level;
1361    int trace_flag = -1;
1362    int i;
1363
1364    if (!open_db(ua)) {
1365       return 1;
1366    }
1367    Dmsg1(120, "setdebug:%s:\n", cmd);
1368
1369    level = -1;
1370    i = find_arg_with_value(ua, _("level"));
1371    if (i >= 0) {
1372       level = atoi(ua->argv[i]);
1373    }
1374    if (level < 0) {
1375       if (!get_pint(ua, _("Enter new debug level: "))) {
1376          return 1;
1377       }
1378       level = ua->pint32_val;
1379    }
1380
1381    /* Look for trace flag. -1 => not change */
1382    i = find_arg_with_value(ua, _("trace"));
1383    if (i >= 0) {
1384       trace_flag = atoi(ua->argv[i]);
1385       if (trace_flag > 0) {
1386          trace_flag = 1;
1387       }
1388    }
1389
1390    /* General debug? */
1391    for (i=1; i<ua->argc; i++) {
1392       if (strcasecmp(ua->argk[i], _("all")) == 0) {
1393          do_all_setdebug(ua, level, trace_flag);
1394          return 1;
1395       }
1396       if (strcasecmp(ua->argk[i], _("dir")) == 0 ||
1397           strcasecmp(ua->argk[i], _("director")) == 0) {
1398          debug_level = level;
1399          set_trace(trace_flag);
1400          return 1;
1401       }
1402       if (strcasecmp(ua->argk[i], _("client")) == 0 ||
1403           strcasecmp(ua->argk[i], _("fd")) == 0) {
1404          client = NULL;
1405          if (ua->argv[i]) {
1406             client = (CLIENT *)GetResWithName(R_CLIENT, ua->argv[i]);
1407             if (client) {
1408                do_client_setdebug(ua, client, level, trace_flag);
1409                return 1;
1410             }
1411          }
1412          client = select_client_resource(ua);
1413          if (client) {
1414             do_client_setdebug(ua, client, level, trace_flag);
1415             return 1;
1416          }
1417       }
1418
1419       if (strcasecmp(ua->argk[i], _("store")) == 0 ||
1420           strcasecmp(ua->argk[i], _("storage")) == 0 ||
1421           strcasecmp(ua->argk[i], _("sd")) == 0) {
1422          store = NULL;
1423          if (ua->argv[i]) {
1424             store = (STORE *)GetResWithName(R_STORAGE, ua->argv[i]);
1425             if (store) {
1426                do_storage_setdebug(ua, store, level, trace_flag);
1427                return 1;
1428             }
1429          }
1430          store = get_storage_resource(ua, 0);
1431          if (store) {
1432             do_storage_setdebug(ua, store, level, trace_flag);
1433             return 1;
1434          }
1435       }
1436    }
1437    /*
1438     * We didn't find an appropriate keyword above, so
1439     * prompt the user.
1440     */
1441    start_prompt(ua, _("Available daemons are: \n"));
1442    add_prompt(ua, _("Director"));
1443    add_prompt(ua, _("Storage"));
1444    add_prompt(ua, _("Client"));
1445    add_prompt(ua, _("All"));
1446    switch(do_prompt(ua, "", _("Select daemon type to set debug level"), NULL, 0)) {
1447    case 0:                         /* Director */
1448       debug_level = level;
1449       set_trace(trace_flag);
1450       break;
1451    case 1:
1452       store = get_storage_resource(ua, 0);
1453       if (store) {
1454          do_storage_setdebug(ua, store, level, trace_flag);
1455       }
1456       break;
1457    case 2:
1458       client = select_client_resource(ua);
1459       if (client) {
1460          do_client_setdebug(ua, client, level, trace_flag);
1461       }
1462       break;
1463    case 3:
1464       do_all_setdebug(ua, level, trace_flag);
1465       break;
1466    default:
1467       break;
1468    }
1469    return 1;
1470 }
1471
1472 /*
1473  * Turn debug tracing to file on/off
1474  */
1475 static int trace_cmd(UAContext *ua, const char *cmd)
1476 {
1477    char *onoff;
1478
1479    if (ua->argc != 2) {
1480       if (!get_cmd(ua, _("Turn on or off? "))) {
1481             return 1;
1482       }
1483       onoff = ua->cmd;
1484    } else {
1485       onoff = ua->argk[1];
1486    }
1487
1488    set_trace((strcasecmp(onoff, _("off")) == 0) ? false : true);
1489    return 1;
1490
1491 }
1492
1493 static int var_cmd(UAContext *ua, const char *cmd)
1494 {
1495    POOLMEM *val = get_pool_memory(PM_FNAME);
1496    char *var;
1497
1498    if (!open_db(ua)) {
1499       return 1;
1500    }
1501    for (var=ua->cmd; *var != ' '; ) {    /* skip command */
1502       var++;
1503    }
1504    while (*var == ' ') {                 /* skip spaces */
1505       var++;
1506    }
1507    Dmsg1(100, "Var=%s:\n", var);
1508    variable_expansion(ua->jcr, var, &val);
1509    bsendmsg(ua, "%s\n", val);
1510    free_pool_memory(val);
1511    return 1;
1512 }
1513
1514 static int estimate_cmd(UAContext *ua, const char *cmd)
1515 {
1516    JOB *job = NULL;
1517    CLIENT *client = NULL;
1518    FILESET *fileset = NULL;
1519    FILESET_DBR fsr;
1520    int listing = 0;
1521    char since[MAXSTRING];
1522    JCR *jcr = ua->jcr;
1523
1524    jcr->JobLevel = L_FULL;
1525    for (int i=1; i<ua->argc; i++) {
1526       if (strcasecmp(ua->argk[i], _("client")) == 0 ||
1527           strcasecmp(ua->argk[i], _("fd")) == 0) {
1528          if (ua->argv[i]) {
1529             client = (CLIENT *)GetResWithName(R_CLIENT, ua->argv[i]);
1530             continue;
1531          }
1532       }
1533       if (strcasecmp(ua->argk[i], _("job")) == 0) {
1534          if (ua->argv[i]) {
1535             job = (JOB *)GetResWithName(R_JOB, ua->argv[i]);
1536             continue;
1537          }
1538       }
1539       if (strcasecmp(ua->argk[i], _("fileset")) == 0) {
1540          if (ua->argv[i]) {
1541             fileset = (FILESET *)GetResWithName(R_FILESET, ua->argv[i]);
1542             continue;
1543          }
1544       }
1545       if (strcasecmp(ua->argk[i], _("listing")) == 0) {
1546          listing = 1;
1547          continue;
1548       }
1549       if (strcasecmp(ua->argk[i], _("level")) == 0) {
1550          if (!get_level_from_name(ua->jcr, ua->argv[i])) {
1551             bsendmsg(ua, _("Level %s not valid.\n"), ua->argv[i]);
1552          }
1553          continue;
1554       }
1555    }
1556    if (!job && !(client && fileset)) {
1557       if (!(job = select_job_resource(ua))) {
1558          return 1;
1559       }
1560    }
1561    if (!job) {
1562       job = (JOB *)GetResWithName(R_JOB, ua->argk[1]);
1563       if (!job) {
1564          bsendmsg(ua, _("No job specified.\n"));
1565          return 1;
1566       }
1567    }
1568    if (!client) {
1569       client = job->client;
1570    }
1571    if (!fileset) {
1572       fileset = job->fileset;
1573    }
1574    jcr->client = client;
1575    jcr->fileset = fileset;
1576    close_db(ua);
1577    ua->catalog = client->catalog;
1578
1579    if (!open_db(ua)) {
1580       return 1;
1581    }
1582
1583    jcr->job = job;
1584    jcr->JobType = JT_BACKUP;
1585    init_jcr_job_record(jcr);
1586
1587    if (!get_or_create_client_record(jcr)) {
1588       return 1;
1589    }
1590    if (!get_or_create_fileset_record(jcr, &fsr)) {
1591       return 1;
1592    }
1593
1594    get_level_since_time(ua->jcr, since, sizeof(since));
1595
1596    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"),
1597       job->client->hdr.name, job->client->address, job->client->FDport);
1598    if (!connect_to_file_daemon(jcr, 1, 15, 0)) {
1599       bsendmsg(ua, _("Failed to connect to Client.\n"));
1600       return 1;
1601    }
1602
1603    if (!send_include_list(jcr)) {
1604       bsendmsg(ua, _("Error sending include list.\n"));
1605       goto bail_out;
1606    }
1607
1608    if (!send_exclude_list(jcr)) {
1609       bsendmsg(ua, _("Error sending exclude list.\n"));
1610       goto bail_out;
1611    }
1612
1613    if (!send_level_command(jcr)) {
1614       goto bail_out;
1615    }
1616
1617    bnet_fsend(jcr->file_bsock, "estimate listing=%d\n", listing);
1618    while (bnet_recv(jcr->file_bsock) >= 0) {
1619       bsendmsg(ua, "%s", jcr->file_bsock->msg);
1620    }
1621
1622 bail_out:
1623    if (jcr->file_bsock) {
1624       bnet_sig(jcr->file_bsock, BNET_TERMINATE);
1625       bnet_close(jcr->file_bsock);
1626       jcr->file_bsock = NULL;
1627    }
1628    return 1;
1629 }
1630
1631
1632 /*
1633  * print time
1634  */
1635 static int time_cmd(UAContext *ua, const char *cmd)
1636 {
1637    char sdt[50];
1638    time_t ttime = time(NULL);
1639    struct tm tm;
1640    localtime_r(&ttime, &tm);
1641    strftime(sdt, sizeof(sdt), "%d-%b-%Y %H:%M:%S", &tm);
1642    bsendmsg(ua, "%s\n", sdt);
1643    return 1;
1644 }
1645
1646 /*
1647  * reload the conf file
1648  */
1649 extern "C" void reload_config(int sig);
1650
1651 static int reload_cmd(UAContext *ua, const char *cmd)
1652 {
1653    reload_config(1);
1654    return 1;
1655 }
1656
1657 /*
1658  * Delete Pool records (should purge Media with it).
1659  *
1660  *  delete pool=<pool-name>
1661  *  delete volume pool=<pool-name> volume=<name>
1662  *  delete job jobid=xxx
1663  */
1664 static int delete_cmd(UAContext *ua, const char *cmd)
1665 {
1666    static const char *keywords[] = {
1667       N_("volume"),
1668       N_("pool"),
1669       N_("job"),
1670       N_("jobid"),
1671       NULL};
1672
1673    if (!open_db(ua)) {
1674       return 1;
1675    }
1676
1677    switch (find_arg_keyword(ua, keywords)) {
1678    case 0:
1679       delete_volume(ua);
1680       return 1;
1681    case 1:
1682       delete_pool(ua);
1683       return 1;
1684    case 2:
1685    case 3:
1686       int i;
1687       while ((i=find_arg(ua, _("jobid"))) > 0) {
1688          delete_job(ua);
1689          *ua->argk[i] = 0;         /* zap keyword already visited */
1690       }
1691       return 1;
1692    default:
1693       break;
1694    }
1695
1696    bsendmsg(ua, _(
1697 "In general it is not a good idea to delete either a\n"
1698 "Pool or a Volume since they may contain data.\n\n"));
1699
1700    switch (do_keyword_prompt(ua, _("Choose catalog item to delete"), keywords)) {
1701    case 0:
1702       delete_volume(ua);
1703       break;
1704    case 1:
1705       delete_pool(ua);
1706       break;
1707    case 2:
1708       delete_job(ua);
1709       return 1;
1710    default:
1711       bsendmsg(ua, _("Nothing done.\n"));
1712       break;
1713    }
1714    return 1;
1715 }
1716
1717
1718 /*
1719  * delete_job has been modified to parse JobID lists like the
1720  * following:
1721  * delete job JobID=3,4,6,7-11,14
1722  *
1723  * Thanks to Phil Stracchino for the above addition.
1724  */
1725
1726 static void delete_job(UAContext *ua)
1727 {
1728    JobId_t JobId;
1729    char *s,*sep,*tok;
1730
1731    int i = find_arg_with_value(ua, _("jobid"));
1732    if (i >= 0) {
1733       if (strchr(ua->argv[i], ',') != NULL || strchr(ua->argv[i], '-') != NULL) {
1734         s = bstrdup(ua->argv[i]);
1735         tok = s;
1736         /*
1737          * We could use strtok() here.  But we're not going to, because:
1738          * (a) strtok() is deprecated, having been replaced by strsep();
1739          * (b) strtok() is broken in significant ways.
1740          * we could use strsep() instead, but it's not universally available.
1741          * so we grow our own using strchr().
1742          */
1743         sep = strchr(tok, ',');
1744         while (sep != NULL) {
1745            *sep = '\0';
1746            if (strchr(tok, '-')) {
1747                delete_job_id_range(ua, tok);
1748            } else {
1749               JobId = str_to_int64(tok);
1750               do_job_delete(ua, JobId);
1751            }
1752            tok = ++sep;
1753            sep = strchr(tok, ',');
1754         }
1755         /* pick up the last token */
1756         if (strchr(tok, '-')) {
1757             delete_job_id_range(ua, tok);
1758         } else {
1759             JobId = str_to_int64(tok);
1760             do_job_delete(ua, JobId);
1761         }
1762
1763          free(s);
1764       } else {
1765          JobId = str_to_int64(ua->argv[i]);
1766         do_job_delete(ua, JobId);
1767       }
1768    } else if (!get_pint(ua, _("Enter JobId to delete: "))) {
1769       return;
1770    } else {
1771       JobId = ua->int64_val;
1772       do_job_delete(ua, JobId);
1773    }
1774 }
1775
1776 /*
1777  * we call delete_job_id_range to parse range tokens and iterate over ranges
1778  */
1779 static void delete_job_id_range(UAContext *ua, char *tok)
1780 {
1781    char *tok2;
1782    JobId_t j,j1,j2;
1783
1784    tok2 = strchr(tok, '-');
1785    *tok2 = '\0';
1786    tok2++;
1787    j1 = str_to_int64(tok);
1788    j2 = str_to_int64(tok2);
1789    for (j=j1; j<=j2; j++) {
1790       do_job_delete(ua, j);
1791    }
1792 }
1793
1794 /*
1795  * do_job_delete now performs the actual delete operation atomically
1796  * we always return 1 because C++ is pissy about void functions
1797  */
1798
1799 static void do_job_delete(UAContext *ua, JobId_t JobId)
1800 {
1801    POOLMEM *query = get_pool_memory(PM_MESSAGE);
1802    char ed1[50];
1803
1804    Mmsg(query, "DELETE FROM Job WHERE JobId=%s", edit_int64(JobId, ed1));
1805    db_sql_query(ua->db, query, NULL, (void *)NULL);
1806    Mmsg(query, "DELETE FROM File WHERE JobId=%s", edit_int64(JobId, ed1));
1807    db_sql_query(ua->db, query, NULL, (void *)NULL);
1808    Mmsg(query, "DELETE FROM JobMedia WHERE JobId=%s", edit_int64(JobId, ed1));
1809    db_sql_query(ua->db, query, NULL, (void *)NULL);
1810    free_pool_memory(query);
1811    bsendmsg(ua, _("Job %s and associated records deleted from the catalog.\n"), edit_int64(JobId, ed1));
1812 }
1813
1814 /*
1815  * Delete media records from database -- dangerous
1816  */
1817 static int delete_volume(UAContext *ua)
1818 {
1819    MEDIA_DBR mr;
1820
1821    if (!select_media_dbr(ua, &mr)) {
1822       return 1;
1823    }
1824    bsendmsg(ua, _("\nThis command will delete volume %s\n"
1825       "and all Jobs saved on that volume from the Catalog\n"),
1826       mr.VolumeName);
1827
1828    if (!get_yesno(ua, _("Are you sure you want to delete this Volume? (yes/no): "))) {
1829       return 1;
1830    }
1831    if (ua->pint32_val) {
1832       db_delete_media_record(ua->jcr, ua->db, &mr);
1833    }
1834    return 1;
1835 }
1836
1837 /*
1838  * Delete a pool record from the database -- dangerous
1839  */
1840 static int delete_pool(UAContext *ua)
1841 {
1842    POOL_DBR  pr;
1843
1844    memset(&pr, 0, sizeof(pr));
1845
1846    if (!get_pool_dbr(ua, &pr)) {
1847       return 1;
1848    }
1849    if (!get_yesno(ua, _("Are you sure you want to delete this Pool? (yes/no): "))) {
1850       return 1;
1851    }
1852    if (ua->pint32_val) {
1853       db_delete_pool_record(ua->jcr, ua->db, &pr);
1854    }
1855    return 1;
1856 }
1857
1858
1859 static void do_mount_cmd(UAContext *ua, const char *command)
1860 {
1861    STORE *store;
1862    BSOCK *sd;
1863    JCR *jcr = ua->jcr;
1864    char dev_name[MAX_NAME_LENGTH];
1865
1866    if (!open_db(ua)) {
1867       return;
1868    }
1869    Dmsg2(120, "%s: %s\n", command, ua->UA_sock->msg);
1870
1871    store = get_storage_resource(ua, 1);
1872    if (!store) {
1873       return;
1874    }
1875
1876    Dmsg2(120, "Found storage, MediaType=%s DevName=%s\n",
1877       store->media_type, store->dev_name());
1878
1879    set_storage(jcr, store);
1880    if (!connect_to_storage_daemon(jcr, 10, SDConnectTimeout, 1)) {
1881       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1882       return;
1883    }
1884    sd = jcr->store_bsock;
1885    bstrncpy(dev_name, store->dev_name(), sizeof(dev_name));
1886    bash_spaces(dev_name);
1887    bnet_fsend(sd, "%s %s", command, dev_name);
1888    while (bnet_recv(sd) >= 0) {
1889       bsendmsg(ua, "%s", sd->msg);
1890    }
1891    bnet_sig(sd, BNET_TERMINATE);
1892    bnet_close(sd);
1893    jcr->store_bsock = NULL;
1894 }
1895
1896 /*
1897  * mount [storage | device] <name>
1898  */
1899 static int mount_cmd(UAContext *ua, const char *cmd)
1900 {
1901    do_mount_cmd(ua, "mount");          /* mount */
1902    return 1;
1903 }
1904
1905
1906 /*
1907  * unmount [storage | device] <name>
1908  */
1909 static int unmount_cmd(UAContext *ua, const char *cmd)
1910 {
1911    do_mount_cmd(ua, "unmount");          /* unmount */
1912    return 1;
1913 }
1914
1915
1916 /*
1917  * release [storage | device] <name>
1918  */
1919 static int release_cmd(UAContext *ua, const char *cmd)
1920 {
1921    do_mount_cmd(ua, "release");          /* release */
1922    return 1;
1923 }
1924
1925
1926 /*
1927  * Switch databases
1928  *   use catalog=<name>
1929  */
1930 static int use_cmd(UAContext *ua, const char *cmd)
1931 {
1932    CAT *oldcatalog, *catalog;
1933
1934
1935    close_db(ua);                      /* close any previously open db */
1936    oldcatalog = ua->catalog;
1937
1938    if (!(catalog = get_catalog_resource(ua))) {
1939       ua->catalog = oldcatalog;
1940    } else {
1941       ua->catalog = catalog;
1942    }
1943    if (open_db(ua)) {
1944       bsendmsg(ua, _("Using Catalog name=%s DB=%s\n"),
1945          ua->catalog->hdr.name, ua->catalog->db_name);
1946    }
1947    return 1;
1948 }
1949
1950 int quit_cmd(UAContext *ua, const char *cmd)
1951 {
1952    ua->quit = TRUE;
1953    return 1;
1954 }
1955
1956 /*
1957  * Wait until no job is running
1958  */
1959 int wait_cmd(UAContext *ua, const char *cmd)
1960 {
1961    JCR *jcr;
1962    bmicrosleep(0, 200000);            /* let job actually start */
1963    for (bool running=true; running; ) {
1964       running = false;
1965       lock_jcr_chain();
1966       foreach_jcr(jcr) {
1967          if (jcr->JobId != 0) {
1968             running = true;
1969             free_locked_jcr(jcr);
1970             break;
1971          }
1972          free_locked_jcr(jcr);
1973       }
1974       unlock_jcr_chain();
1975       if (running) {
1976          bmicrosleep(1, 0);
1977       }
1978    }
1979    return 1;
1980 }
1981
1982
1983 static int help_cmd(UAContext *ua, const char *cmd)
1984 {
1985    unsigned int i;
1986
1987    bsendmsg(ua, _("  Command    Description\n  =======    ===========\n"));
1988    for (i=0; i<comsize; i++) {
1989       bsendmsg(ua, _("  %-10s %s\n"), _(commands[i].key), _(commands[i].help));
1990    }
1991    bsendmsg(ua, _("\nWhen at a prompt, entering a period cancels the command.\n\n"));
1992    return 1;
1993 }
1994
1995 int qhelp_cmd(UAContext *ua, const char *cmd)
1996 {
1997    unsigned int i;
1998
1999    for (i=0; i<comsize; i++) {
2000       bsendmsg(ua, _("%s %s\n"), _(commands[i].key), _(commands[i].help));
2001    }
2002    return 1;
2003 }
2004
2005 static int version_cmd(UAContext *ua, const char *cmd)
2006 {
2007    bsendmsg(ua, "%s Version: " VERSION " (" BDATE ")\n", my_name);
2008    return 1;
2009 }
2010
2011
2012 /* A bit brain damaged in that if the user has not done
2013  * a "use catalog xxx" command, we simply find the first
2014  * catalog resource and open it.
2015  */
2016 int open_db(UAContext *ua)
2017 {
2018    if (ua->db) {
2019       return 1;
2020    }
2021    if (!ua->catalog) {
2022       LockRes();
2023       ua->catalog = (CAT *)GetNextRes(R_CATALOG, NULL);
2024       UnlockRes();
2025       if (!ua->catalog) {
2026          bsendmsg(ua, _("Could not find a Catalog resource\n"));
2027          return 0;
2028       } else {
2029          bsendmsg(ua, _("Using default Catalog name=%s DB=%s\n"),
2030             ua->catalog->hdr.name, ua->catalog->db_name);
2031       }
2032    }
2033
2034    ua->jcr->catalog = ua->catalog;
2035
2036    Dmsg0(150, "Open database\n");
2037    ua->db = db_init_database(ua->jcr, ua->catalog->db_name, ua->catalog->db_user,
2038                              ua->catalog->db_password, ua->catalog->db_address,
2039                              ua->catalog->db_port, ua->catalog->db_socket,
2040                              ua->catalog->mult_db_connections);
2041    if (!ua->db || !db_open_database(ua->jcr, ua->db)) {
2042       bsendmsg(ua, _("Could not open database \"%s\".\n"),
2043                  ua->catalog->db_name);
2044       if (ua->db) {
2045          bsendmsg(ua, "%s", db_strerror(ua->db));
2046       }
2047       close_db(ua);
2048       return 0;
2049    }
2050    ua->jcr->db = ua->db;
2051    Dmsg1(150, "DB %s opened\n", ua->catalog->db_name);
2052    return 1;
2053 }
2054
2055 void close_db(UAContext *ua)
2056 {
2057    if (ua->db) {
2058       db_close_database(ua->jcr, ua->db);
2059       ua->db = NULL;
2060       if (ua->jcr) {
2061          ua->jcr->db = NULL;
2062       }
2063    }
2064 }