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