]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dircmd.c
5f2d2a71918425ea5ead7aa3953f0545e967e3a2
[bacula/bacula] / bacula / src / stored / dircmd.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2017 Kern Sibbald
5
6    The original author of Bacula is Kern Sibbald, with contributions
7    from many others, a complete list can be found in the file AUTHORS.
8
9    You may use this file and others of this release according to the
10    license defined in the LICENSE file, which includes the Affero General
11    Public License, v3.0 ("AGPLv3") and some additional permissions and
12    terms pursuant to its AGPLv3 Section 7.
13
14    This notice must be preserved when any source code is
15    conveyed and/or propagated.
16
17    Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20  *  This file handles accepting Director Commands
21  *
22  *    Most Director commands are handled here, with the
23  *    exception of the Job command command and subsequent
24  *    subcommands that are handled
25  *    in job.c.
26  *
27  *    N.B. in this file, in general we must use P(dev->mutex) rather
28  *      than dev->rLock() so that we can examine the blocked
29  *      state rather than blocking ourselves because a Job
30  *      thread has the device blocked. In some "safe" cases,
31  *      we can do things to a blocked device. CAREFUL!!!!
32  *
33  *    File daemon commands are handled in fdcmd.c
34  *
35  *     Written by Kern Sibbald, May MMI
36  *
37  */
38
39 #include "bacula.h"
40 #include "stored.h"
41
42 /* Exported variables */
43
44 /* Imported variables */
45 extern BSOCK *filed_chan;
46 extern struct s_last_job last_job;
47 extern bool init_done;
48
49 /* Static variables */
50 static char derrmsg[]     = "3900 Invalid command:";
51 static char OKsetdebug[]  = "3000 OK setdebug=%ld trace=%ld options=%s tags=%s\n";
52 static char invalid_cmd[] = "3997 Invalid command for a Director with Monitor directive enabled.\n";
53 static char OK_bootstrap[]    = "3000 OK bootstrap\n";
54 static char ERROR_bootstrap[] = "3904 Error bootstrap\n";
55 static char OKclient[] = "3000 OK client command\n";
56
57 /* Imported functions */
58 extern void terminate_child();
59 extern bool job_cmd(JCR *jcr);
60 extern bool use_cmd(JCR *jcr);
61 extern bool run_cmd(JCR *jcr);
62 extern bool status_cmd(JCR *sjcr);
63 extern bool qstatus_cmd(JCR *jcr);
64 //extern bool query_cmd(JCR *jcr);
65
66 /* Forward referenced functions */
67 static bool client_cmd(JCR *jcr);
68 static bool storage_cmd(JCR *jcr);
69 static bool label_cmd(JCR *jcr);
70 static bool die_cmd(JCR *jcr);
71 static bool relabel_cmd(JCR *jcr);
72 static bool truncate_cache_cmd(JCR *jcr);
73 static bool upload_cmd(JCR *jcr);
74 static bool readlabel_cmd(JCR *jcr);
75 static bool release_cmd(JCR *jcr);
76 static bool setdebug_cmd(JCR *jcr);
77 static bool cancel_cmd(JCR *cjcr);
78 static bool mount_cmd(JCR *jcr);
79 static bool unmount_cmd(JCR *jcr);
80 static bool enable_cmd(JCR *jcr);
81 static bool disable_cmd(JCR *jcr);
82 //static bool action_on_purge_cmd(JCR *jcr);
83 static bool bootstrap_cmd(JCR *jcr);
84 static bool cloud_list_cmd(JCR *jcr);
85 static bool cloud_prunecache_cmd(JCR *jcr);
86 static bool changer_cmd(JCR *sjcr);
87 static bool do_label(JCR *jcr, int relabel);
88 static DCR *find_device(JCR *jcr, POOL_MEM &dev_name,
89                         POOLMEM *media_type, int drive);
90 static DCR *find_any_device(JCR *jcr, POOL_MEM &dev_name,
91                         POOLMEM *media_type, int drive);
92 static void read_volume_label(JCR *jcr, DCR *dcr, DEVICE *dev, int Slot);
93 static void label_volume_if_ok(DCR *dcr, char *oldname,
94                                char *newname, char *poolname,
95                                int Slot, int relabel);
96 static bool try_autoload_device(JCR *jcr, DCR *dcr, int slot, const char *VolName);
97 static void send_dir_busy_message(BSOCK *dir, DEVICE *dev);
98
99 /* Responses send to Director for storage command */
100 static char BADcmd[]  = "2902 Bad %s\n";
101 static char OKstore[] = "2000 OK storage\n";
102
103 /* Commands received from director that need scanning */
104 static char storaddr[] = "storage address=%s port=%d ssl=%d Job=%127s Authentication=%127s";
105
106 struct s_cmds {
107    const char *cmd;
108    bool (*func)(JCR *jcr);
109    bool monitoraccess;                      /* set if monitors can access this cmd */
110 };
111
112 /*
113  * The following are the recognized commands from the Director.
114  */
115 static struct s_cmds cmds[] = {
116    {"JobId=",      job_cmd,         0},     /* start Job */
117    {"autochanger", changer_cmd,     0},
118    {"bootstrap",   bootstrap_cmd,   0},
119    {"cancel",      cancel_cmd,      0},
120    {"client",      client_cmd,      0},     /* client address */
121    {".die",        die_cmd,         0},
122    {"label",       label_cmd,       0},     /* label a tape */
123    {"mount",       mount_cmd,       0},
124    {"enable",      enable_cmd,      0},
125    {"disable",     disable_cmd,     0},
126    {"readlabel",   readlabel_cmd,   0},
127    {"release",     release_cmd,     0},
128    {"relabel",     relabel_cmd,     0},     /* relabel a tape */
129    {"setdebug=",   setdebug_cmd,    0},     /* set debug level */
130    {"status",      status_cmd,      1},
131    {".status",     qstatus_cmd,     1},
132    {"stop",        cancel_cmd,      0},
133    {"storage",     storage_cmd,     0},     /* get SD addr from Dir */
134    {"truncate",    truncate_cache_cmd, 0},
135    {"upload",      upload_cmd,      0},
136    {"prunecache",  cloud_prunecache_cmd, 0},
137    {"cloudlist",   cloud_list_cmd,  0},     /* List volumes/parts in the cloud */
138    {"unmount",     unmount_cmd,     0},
139    {"use storage=", use_cmd,        0},
140    {"run",         run_cmd,         0},
141 // {"query",       query_cmd,       0},
142    {NULL,        NULL}                      /* list terminator */
143 };
144
145
146 /*
147  * Connection request. We accept connections either from the
148  *  Director or a Client (File daemon).
149  *
150  * Note, we are running as a separate thread of the Storage daemon.
151  *  and it is because a Director has made a connection with
152  *  us on the "Message" channel.
153  *
154  * Basic tasks done here:
155  *  - Create a JCR record
156  *  - If it was from the FD, call handle_filed_connection()
157  *  - Authenticate the Director
158  *  - We wait for a command
159  *  - We execute the command
160  *  - We continue or exit depending on the return status
161  */
162 void *handle_connection_request(void *arg)
163 {
164    BSOCK *bs = (BSOCK *)arg;
165    JCR *jcr;
166    int i;
167    bool found, quit;
168    int bnet_stat = 0;
169    char tbuf[100];
170
171    if (bs->recv() <= 0) {
172       Jmsg1(NULL, M_ERROR, 0, _("Connection request from %s failed.\n"), bs->who());
173       bmicrosleep(5, 0);   /* make user wait 5 seconds */
174       bs->destroy();
175       return NULL;
176    }
177
178    /* Check for client connection */
179    if (is_client_connection(bs)) {
180       handle_client_connection(bs);
181       return NULL;
182    }
183
184    /*
185     * This is a connection from the Director, so setup a JCR
186     */
187    Dmsg1(050, "Got a DIR connection at %s\n", bstrftimes(tbuf, sizeof(tbuf),
188          (utime_t)time(NULL)));
189    jcr = new_jcr(sizeof(JCR), stored_free_jcr); /* create Job Control Record */
190    jcr->dir_bsock = bs;               /* save Director bsock */
191    jcr->dir_bsock->set_jcr(jcr);
192    jcr->dcrs = New(alist(10, not_owned_by_alist));
193    create_jobmedia_queue(jcr);
194    /* Initialize FD start condition variable */
195    int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
196    if (errstat != 0) {
197       berrno be;
198       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
199       goto bail_out;
200    }
201
202    Dmsg0(1000, "stored in start_job\n");
203
204    /*
205     * Validate then authenticate the Director
206     */
207    if (!validate_dir_hello(jcr)) {
208       goto bail_out;
209    }
210    if (!authenticate_director(jcr)) {
211       Jmsg(jcr, M_FATAL, 0, _("[SF0100] Unable to authenticate Director\n"));
212       goto bail_out;
213    }
214    Dmsg0(90, "Message channel init completed.\n");
215
216    dequeue_messages(jcr);     /* dequeue any daemon messages */
217
218    for (quit=false; !quit;) {
219       /* Read command */
220       if ((bnet_stat = bs->recv()) <= 0) {
221          break;               /* connection terminated */
222       }
223       Dmsg1(199, "<dird: %s", bs->msg);
224       /* Ensure that device initialization is complete */
225       while (!init_done) {
226          bmicrosleep(1, 0);
227       }
228       found = false;
229       for (i=0; cmds[i].cmd; i++) {
230         if (strncmp(cmds[i].cmd, bs->msg, strlen(cmds[i].cmd)) == 0) {
231            if ((!cmds[i].monitoraccess) && (jcr->director->monitor)) {
232               Dmsg1(100, "Command \"%s\" is invalid.\n", cmds[i].cmd);
233               bs->fsend(invalid_cmd);
234               bs->signal(BNET_EOD);
235               break;
236            }
237            Dmsg1(200, "Do command: %s\n", cmds[i].cmd);
238            if (!cmds[i].func(jcr)) { /* do command */
239               quit = true; /* error, get out */
240               Dmsg1(190, "Command %s requests quit\n", cmds[i].cmd);
241            }
242            found = true;             /* indicate command found */
243            break;
244         }
245       }
246       if (!found) {                   /* command not found */
247         POOL_MEM err_msg;
248         Mmsg(err_msg, "%s %s\n", derrmsg, bs->msg);
249         bs->fsend(err_msg.c_str());
250         break;
251       }
252    }
253 bail_out:
254    generate_daemon_event(jcr, "JobEnd");
255    generate_plugin_event(jcr, bsdEventJobEnd);
256    flush_jobmedia_queue(jcr);
257    dequeue_messages(jcr);             /* send any queued messages */
258    bs->signal(BNET_TERMINATE);
259    free_plugins(jcr);                 /* release instantiated plugins */
260    free_jcr(jcr);
261    return NULL;
262 }
263
264
265 /*
266  * Force SD to die, and hopefully dump itself.  Turned on only
267  *  in development version.
268  */
269 static bool die_cmd(JCR *jcr)
270 {
271 #ifdef DEVELOPER
272    JCR *djcr = NULL;
273    int a;
274    BSOCK *dir = jcr->dir_bsock;
275    pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;
276
277    if (strstr(dir->msg, "deadlock")) {
278       Pmsg0(000, "I have been requested to deadlock ...\n");
279       P(m);
280       P(m);
281    }
282
283    Pmsg1(000, "I have been requested to die ... (%s)\n", dir->msg);
284    a = djcr->JobId;   /* ref NULL pointer */
285    djcr->JobId = a;
286 #endif
287    return 0;
288 }
289
290 /*
291  * Get address of client from Director
292  *   This initiates SD Calls Client.
293  *   We attempt to connect to the client (an FD or SD) and
294  *   authenticate it.
295  */
296 static bool client_cmd(JCR *jcr)
297 {
298    int client_port;                 /* client port */
299    int enable_ssl;                 /* enable ssl */
300    BSOCK *dir = jcr->dir_bsock;
301    BSOCK *cl = new_bsock();        /* client bsock */
302
303    Dmsg1(100, "ClientCmd: %s", dir->msg);
304    jcr->sd_calls_client = true;
305    if (sscanf(dir->msg, "client address=%s port=%d ssl=%d", &jcr->client_addr, &client_port,
306               &enable_ssl) != 3) {
307       pm_strcpy(jcr->errmsg, dir->msg);
308       Jmsg(jcr, M_FATAL, 0, _("[SF0101] Bad client command: %s"), jcr->errmsg);
309       Dmsg1(050, "Bad client command: %s", jcr->errmsg);
310       goto bail_out;
311    }
312
313    Dmsg3(110, "Connect to client: %s:%d ssl=%d\n", jcr->client_addr, client_port,
314          enable_ssl);
315    /* Open command communications with Client */
316    /* Try to connect for 1 hour at 10 second intervals */
317    if (!cl->connect(jcr, 10, (int)me->ClientConnectTimeout, me->heartbeat_interval,
318                 _("Client daemon"), jcr->client_addr, NULL, client_port, 1)) {
319       /* destroy() OK because cl is local */
320       cl->destroy();
321       Jmsg(jcr, M_FATAL, 0, _("[SF0102] Failed to connect to Client daemon: %s:%d\n"),
322           jcr->client_addr, client_port);
323       Dmsg2(100, "Failed to connect to Client daemon: %s:%d\n",
324           jcr->client_addr, client_port);
325       goto bail_out;
326    }
327    Dmsg0(110, "SD connection OK to Client.\n");
328
329    jcr->file_bsock = cl;
330    jcr->file_bsock->set_jcr(jcr);
331    if (!send_hello_client(jcr, jcr->Job)) {
332       goto bail_out;
333    }
334
335    /* Send OK to Director */
336    return dir->fsend(OKclient);
337
338 bail_out:
339    jcr->setJobStatus(JS_ErrorTerminated);
340    dir->fsend("3902 Bad %s cmd\n", "client");
341    return 0;
342 }
343
344 /*
345  * Get address of storage daemon from Director
346  */
347 static bool storage_cmd(JCR *jcr)
348 {
349    int stored_port;                /* storage daemon port */
350    int enable_ssl;                 /* enable ssl to sd */
351    char sd_auth_key[200];
352    BSOCK *dir = jcr->dir_bsock;
353    BSOCK *sd = new_bsock();        /* storage daemon bsock */
354    char Job[MAX_NAME_LENGTH];
355
356    Dmsg1(050, "StorageCmd: %s", dir->msg);
357    if (sscanf(dir->msg, storaddr, &jcr->stored_addr, &stored_port,
358               &enable_ssl, Job, sd_auth_key) != 5) {
359       pm_strcpy(jcr->errmsg, dir->msg);
360       Jmsg(jcr, M_FATAL, 0, _("[SF0103] Bad storage command: %s"), jcr->errmsg);
361       Pmsg1(010, "Bad storage command: %s", jcr->errmsg);
362       goto bail_out;
363    }
364
365    unbash_spaces(Job);
366    if (jcr->sd_auth_key) {
367       bfree_and_null(jcr->sd_auth_key);
368       jcr->sd_auth_key = bstrdup(sd_auth_key);
369    }
370    if (stored_port != 0) {
371       Dmsg2(050, "sd_calls=%d sd_client=%d\n", jcr->sd_calls_client,
372          jcr->sd_client);
373       jcr->sd_calls_client = false;   /* We are doing the connecting */
374       Dmsg3(050, "Connect to storage and wait: %s:%d ssl=%d\n", jcr->stored_addr, stored_port,
375             enable_ssl);
376       /* Open command communications with Storage daemon */
377       /* Try to connect for 1 hour at 10 second intervals */
378       if (!sd->connect(jcr, 10, (int)me->ClientConnectTimeout, me->heartbeat_interval,
379                 _("Storage daemon"), jcr->stored_addr, NULL, stored_port, 1)) {
380          /* destroy() OK because sd is local */
381          sd->destroy();
382          Jmsg(jcr, M_FATAL, 0, _("[SF0104] Failed to connect to Storage daemon: %s:%d\n"),
383              jcr->stored_addr, stored_port);
384          Dmsg2(010, "Failed to connect to Storage daemon: %s:%d\n",
385              jcr->stored_addr, stored_port);
386          goto bail_out;
387       }
388
389       Dmsg0(050, "Connection OK to SD.\n");
390
391       jcr->store_bsock = sd;
392    } else {                      /* The storage daemon called us */
393       jcr->sd_calls_client = true;
394       /* We should already have a storage connection! */
395       if (jcr->file_bsock && jcr->store_bsock == NULL) {
396          jcr->store_bsock = jcr->file_bsock;
397       }
398       if (jcr->store_bsock == NULL) {
399          Jmsg0(jcr, M_FATAL, 0, _("[SF0105] In storage_cmd port==0, no prior Storage connection.\n"));
400          Pmsg0(010, "In storage_cmd port==0, no prior Storage connection.\n");
401          goto bail_out;
402       }
403    }
404
405    if (!send_hello_sd(jcr, Job)) {
406       goto bail_out;
407    }
408
409    if (!authenticate_storagedaemon(jcr)) {
410       goto bail_out;
411    }
412    /*
413     * We are a client so we read from the socket we just
414     *   opened as if we were a FD, so set file_bsock and
415     *   clear the store_bsock.
416     */
417    jcr->file_bsock = jcr->store_bsock;
418    jcr->store_bsock = NULL;
419    jcr->authenticated = true;    /* Dir authentication is sufficient */
420    Dmsg1(050, "=== Storage_cmd authenticated Job=%s with SD.\n", Job);
421
422    /* Send OK to Director */
423    return dir->fsend(OKstore);
424
425 bail_out:
426    Dmsg0(100, "Send storage command failed.\n");
427    dir->fsend(BADcmd, "storage");
428    return false;
429 }
430
431
432 /*
433  * Set debug level as requested by the Director
434  *
435  */
436 static bool setdebug_cmd(JCR *jcr)
437 {
438    BSOCK *dir = jcr->dir_bsock;
439    int32_t trace_flag, lvl, hangup, blowup;
440    int64_t level, level_tags = 0;
441    char options[60];
442    char tags[512];
443    *tags = *options = 0;
444
445    Dmsg1(10, "setdebug_cmd: %s", dir->msg);
446
447    if (sscanf(dir->msg, "setdebug=%ld trace=%ld hangup=%ld blowup=%ld options=%55s tags=%511s",
448               &lvl, &trace_flag, &hangup, &blowup, options, tags) != 6)
449    {
450       if (sscanf(dir->msg, "setdebug=%ld trace=%ld", &lvl, &trace_flag) != 2 || lvl < 0) {
451          dir->fsend(_("3991 Bad setdebug command: %s\n"), dir->msg);
452          return 0;
453       }
454    }
455    level = lvl;
456    set_trace(trace_flag);
457    set_hangup(hangup);
458    set_blowup(blowup);
459    set_debug_flags(options);
460    if (!debug_parse_tags(tags, &level_tags)) {
461       *tags = 0;
462    }
463    if (level >= 0) {
464       debug_level = level;
465    }
466    debug_level_tags = level_tags;
467
468    /* TODO: Temp code to activate the new BSR optimisation code */
469    for (char *p = options; *p ; p++) {
470       switch(*p) {
471       case 'i':                 /* Use new match_bsr() code */
472          use_new_match_all = 1;
473          break;
474       case '0':
475          use_new_match_all = 0;
476          break;
477       }
478    }
479    /* **** */
480
481    return dir->fsend(OKsetdebug, lvl, trace_flag, options, tags);
482 }
483
484
485 /*
486  * Cancel a Job
487  *   Be careful, we switch to using the job's JCR! So, using
488  *   BSOCKs on that jcr can have two threads in the same code.
489  */
490 static bool cancel_cmd(JCR *cjcr)
491 {
492    BSOCK *dir = cjcr->dir_bsock;
493    int oldStatus;
494    char Job[MAX_NAME_LENGTH];
495    JCR *jcr;
496    int status;
497    const char *reason;
498
499    if (sscanf(dir->msg, "cancel Job=%127s", Job) == 1) {
500       status = JS_Canceled;
501       reason = "canceled";
502    } else if (sscanf(dir->msg, "stop Job=%127s", Job) == 1) {
503       status = JS_Incomplete;
504       reason = "stopped";
505    } else {
506       dir->fsend(_("3903 Error scanning cancel command.\n"));
507       goto bail_out;
508    }
509    if (!(jcr=get_jcr_by_full_name(Job))) {
510       dir->fsend(_("3904 Job %s not found.\n"), Job);
511    } else {
512       oldStatus = jcr->JobStatus;
513       jcr->setJobStatus(status);
514       Dmsg2(800, "Cancel JobId=%d %p\n", jcr->JobId, jcr);
515       if (!jcr->authenticated && oldStatus == JS_WaitFD) {
516          pthread_cond_signal(&jcr->job_start_wait); /* wake waiting thread */
517       }
518       if (jcr->file_bsock) {
519          jcr->file_bsock->set_terminated();
520          jcr->file_bsock->set_timed_out();
521          Dmsg2(800, "Term bsock jid=%d %p\n", jcr->JobId, jcr);
522       } else {
523          /* Still waiting for FD to connect, release it */
524          pthread_cond_signal(&jcr->job_start_wait); /* wake waiting job */
525          Dmsg2(800, "Signal FD connect jid=%d %p\n", jcr->JobId, jcr);
526       }
527       /* If thread waiting on mount, wake him */
528       if (jcr->dcr && jcr->dcr->dev && jcr->dcr->dev->waiting_for_mount()) {
529          pthread_cond_broadcast(&jcr->dcr->dev->wait_next_vol);
530          Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
531          pthread_cond_broadcast(&wait_device_release);
532       }
533       if (jcr->read_dcr && jcr->read_dcr->dev && jcr->read_dcr->dev->waiting_for_mount()) {
534          pthread_cond_broadcast(&jcr->read_dcr->dev->wait_next_vol);
535          Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
536          pthread_cond_broadcast(&wait_device_release);
537       }
538       jcr->my_thread_send_signal(TIMEOUT_SIGNAL);
539       dir->fsend(_("3000 JobId=%ld Job=\"%s\" marked to be %s.\n"),
540          jcr->JobId, jcr->Job, reason);
541       free_jcr(jcr);
542    }
543
544 bail_out:
545    dir->signal(BNET_EOD);
546    return 1;
547 }
548
549 /*
550  * Label a Volume
551  *
552  */
553 static bool label_cmd(JCR *jcr)
554 {
555    return do_label(jcr, 0);
556 }
557
558 static bool relabel_cmd(JCR *jcr)
559 {
560    return do_label(jcr, 1);
561 }
562
563 static bool do_label(JCR *jcr, int relabel)
564 {
565    POOLMEM *newname, *oldname, *poolname, *mtype;
566    POOL_MEM dev_name;
567    BSOCK *dir = jcr->dir_bsock;
568    DCR *dcr = NULL;;
569    DEVICE *dev;
570    bool ok = false;
571    int32_t slot, drive;
572
573    newname = get_memory(dir->msglen+1);
574    oldname = get_memory(dir->msglen+1);
575    poolname = get_memory(dir->msglen+1);
576    mtype = get_memory(dir->msglen+1);
577    if (relabel) {
578       if (sscanf(dir->msg, "relabel %127s OldName=%127s NewName=%127s PoolName=%127s "
579                  "MediaType=%127s Slot=%d drive=%d",
580                   dev_name.c_str(), oldname, newname, poolname, mtype,
581                   &slot, &drive) == 7) {
582          ok = true;
583       }
584    } else {
585       *oldname = 0;
586       if (sscanf(dir->msg, "label %127s VolumeName=%127s PoolName=%127s "
587                  "MediaType=%127s Slot=%d drive=%d",
588           dev_name.c_str(), newname, poolname, mtype, &slot, &drive) == 6) {
589          ok = true;
590       }
591    }
592    if (ok) {
593       unbash_spaces(newname);
594       unbash_spaces(oldname);
595       unbash_spaces(poolname);
596       unbash_spaces(mtype);
597       dcr = find_device(jcr, dev_name, mtype, drive);
598       if (dcr) {
599          uint32_t max_jobs;
600          dev = dcr->dev;
601          ok = true;
602          dev->Lock();                 /* Use P to avoid indefinite block */
603          max_jobs = dev->max_concurrent_jobs;
604          dev->max_concurrent_jobs = 1;
605          bstrncpy(dcr->VolumeName, newname, sizeof(dcr->VolumeName));
606          if (dcr->can_i_write_volume()) {
607             if (reserve_volume(dcr, newname) == NULL) {
608                ok = false;
609             }
610             Dmsg1(400, "Reserved volume \"%s\"\n", newname);
611          } else {
612             ok = false;
613          }
614          if (!ok) {
615             dir->fsend(_("3908 Error reserving volume: %s\n"), jcr->errmsg);
616             dev->max_concurrent_jobs = max_jobs;
617             dev->Unlock();
618             goto bail_out;
619          }
620
621          /* some command use recv and don't accept catalog update.
622           * it's not the case here, so we force dir_update_volume_info catalog update */ 
623          dcr->force_update_volume_info = true;
624
625          if (!dev->is_open() && !dev->is_busy()) {
626             Dmsg1(400, "Can %slabel. Device is not open\n", relabel?"re":"");
627             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
628             dev->close(dcr);
629          /* Under certain "safe" conditions, we can steal the lock */
630          } else if (dev->can_steal_lock()) {
631             Dmsg0(400, "Can relabel. can_steal_lock\n");
632             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
633          } else if (dev->is_busy() || dev->is_blocked()) {
634             send_dir_busy_message(dir, dev);
635          } else {                     /* device not being used */
636             Dmsg0(400, "Can relabel. device not used\n");
637             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
638          }
639          dev->max_concurrent_jobs = max_jobs;
640          volume_unused(dcr);
641          dev->Unlock();
642 #ifdef DEVELOPER
643          if (chk_dbglvl(DT_VOLUME)) {
644             Dmsg0(0, "Waiting few seconds to force a bug...\n");
645             bmicrosleep(30, 0);
646             Dmsg0(0, "Doing free_volume()\n");
647          }
648 #endif
649       } else {
650          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), dev_name.c_str());
651       }
652    } else {
653       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
654       pm_strcpy(jcr->errmsg, dir->msg);
655       dir->fsend(_("3903 Error scanning label command: %s\n"), jcr->errmsg);
656    }
657 bail_out:
658    if (dcr) {
659       free_dcr(dcr);
660    }
661    free_memory(oldname);
662    free_memory(newname);
663    free_memory(poolname);
664    free_memory(mtype);
665    dir->signal(BNET_EOD);
666    return true;
667 }
668
669 /*
670  * Handles truncate cache commands
671  */
672 static bool truncate_cache_cmd(JCR *jcr)
673 {
674    POOLMEM *volname, *poolname, *mtype;
675    POOL_MEM dev_name;
676    BSOCK *dir = jcr->dir_bsock;
677    DCR *dcr = NULL;;
678    DEVICE *dev;
679    bool ok = false;
680    int32_t slot, drive;
681    int nbpart = 0;
682    int64_t size = 0;
683    char ed1[50];
684
685    volname = get_memory(dir->msglen+1);
686    poolname = get_memory(dir->msglen+1);
687    mtype = get_memory(dir->msglen+1);
688    if (sscanf(dir->msg, "truncate cache Storage=%127s Volume=%127s PoolName=%127s "
689               "MediaType=%127s Slot=%d drive=%d",
690                dev_name.c_str(), volname, poolname, mtype,
691                &slot, &drive) == 6) {
692       ok = true;
693    }
694    if (ok) {
695       unbash_spaces(volname);
696       unbash_spaces(poolname);
697       unbash_spaces(mtype);
698       dcr = find_device(jcr, dev_name, mtype, drive);
699       if (dcr) {
700          uint32_t max_jobs;
701          dev = dcr->dev;
702          ok = true;
703          dev->Lock();                 /* Use P to avoid indefinite block */
704          max_jobs = dev->max_concurrent_jobs;
705          dev->max_concurrent_jobs = 1;
706          bstrncpy(dcr->VolumeName, volname, sizeof(dcr->VolumeName));
707          if (dcr->can_i_write_volume()) {
708             if (reserve_volume(dcr, volname) == NULL) {
709                ok = false;
710             }
711             Dmsg1(400, "Reserved volume \"%s\"\n", volname);
712          } else {
713             ok = false;
714          }
715          if (!ok) {
716             dir->fsend(_("3908 Error reserving volume \"%s\": %s\n"), volname, jcr->errmsg);
717             dev->max_concurrent_jobs = max_jobs;
718             dev->Unlock();
719             goto bail_out;
720          }
721          if ((!dev->is_open() && !dev->is_busy()) || dev->can_steal_lock()) {
722             Dmsg0(400, "Call truncate_cache\n");
723             nbpart = dev->truncate_cache(dcr, volname, &size);
724             if (nbpart >= 0) {
725                dir->fsend(_("3000 OK truncate cache for volume \"%s\" %d part(s) %sB\n"),
726                           volname, nbpart, edit_uint64_with_suffix(size, ed1));
727             } else {
728                dir->fsend(_("3900 Truncate cache for volume \"%s\" failed. ERR=%s\n"), volname, dev->errmsg);
729             }
730          } else if (dev->is_busy() || dev->is_blocked()) {
731             send_dir_busy_message(dir, dev);
732          } else {                     /* device not being used */
733             Dmsg0(400, "Call truncate_cache\n");
734             nbpart = dev->truncate_cache(dcr, volname, &size);
735             if (nbpart >= 0) {
736                dir->fsend(_("3000 OK truncate cache for volume \"%s\" %d part(s) %sB\n"), volname,
737                           nbpart, edit_uint64_with_suffix(size, ed1));
738             } else {
739                dir->fsend(_("3900 Truncate cache for volume \"%s\" failed. ERR=%s\n"), volname, dev->errmsg);
740             }
741          }
742          dev->max_concurrent_jobs = max_jobs;
743          volume_unused(dcr);
744          dev->Unlock();
745 #ifdef DEVELOPER
746          if (chk_dbglvl(DT_VOLUME)) {
747             Dmsg0(0, "Waiting few seconds to force a bug...\n");
748             bmicrosleep(30, 0);
749             Dmsg0(0, "Doing free_volume()\n");
750          }
751 #endif
752       } else {
753          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), dev_name.c_str());
754       }
755    } else {
756       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
757       pm_strcpy(jcr->errmsg, dir->msg);
758       dir->fsend(_("3911 Error scanning truncate command: %s\n"), jcr->errmsg);
759    }
760 bail_out:
761    if (dcr) {
762       free_dcr(dcr);
763    }
764    free_memory(volname);
765    free_memory(poolname);
766    free_memory(mtype);
767    dir->signal(BNET_EOD);
768    return true;
769 }
770
771 static bool cloud_prunecache_cmd(JCR *jcr)
772 {
773    /* TODO: Implement a function to prune the cache of a cloud device */
774    jcr->dir_bsock->fsend(_("3900 Not yet implemented\n"));
775    return true;
776 }
777
778 /* List volumes in the cloud */
779 static bool cloud_list_cmd(JCR *jcr)
780 {
781    jcr->dir_bsock->fsend(_("3900 Not yet implemented\n"));
782    return true;
783 }
784
785 /*
786  * Handles upload cache to Cloud command
787  */
788 static bool upload_cmd(JCR *jcr)
789 {
790    POOLMEM *volname, *poolname, *mtype, *err;
791    POOL_MEM dev_name;
792    BSOCK *dir = jcr->dir_bsock;
793    DCR *dcr = NULL;
794    DEVICE *dev;
795    bool ok = false;
796    int32_t slot, drive;
797
798    volname = get_memory(dir->msglen+1);
799    poolname = get_memory(dir->msglen+1);
800    mtype = get_memory(dir->msglen+1);
801    err = get_pool_memory(PM_MESSAGE);
802    *volname = *poolname = *mtype = *err = 0;
803
804    if (sscanf(dir->msg, "upload Storage=%127s Volume=%127s PoolName=%127s "
805               "MediaType=%127s Slot=%d drive=%d",
806                dev_name.c_str(), volname, poolname, mtype,
807                &slot, &drive) == 6) {
808       ok = true;
809    }
810    if (ok) {
811       unbash_spaces(volname);
812       unbash_spaces(poolname);
813       unbash_spaces(mtype);
814       dcr = find_device(jcr, dev_name, mtype, drive);
815       if (dcr) {
816          uint32_t max_jobs;
817          dev = dcr->dev;
818          ok = true;
819          dev->Lock();                 /* Use P to avoid indefinite block */
820          max_jobs = dev->max_concurrent_jobs;
821          dev->max_concurrent_jobs = 1;
822          bstrncpy(dcr->VolumeName, volname, sizeof(dcr->VolumeName));
823          if (dcr->can_i_write_volume()) {
824             if (reserve_volume(dcr, volname) == NULL) {
825                ok = false;
826             }
827             Dmsg1(400, "Reserved volume \"%s\"\n", volname);
828          } else {
829             ok = false;
830          }
831          if (!ok) {
832             dir->fsend(_("3908 Error reserving volume \"%s\": %s\n"), volname, jcr->errmsg);
833             dev->max_concurrent_jobs = max_jobs;
834             dev->Unlock();
835             goto bail_out;
836          }
837          if ((!dev->is_open() && !dev->is_busy()) || dev->can_steal_lock()) {
838             Dmsg0(400, "Can upload, because device is not open.\n");
839             dev->setVolCatName(volname);
840             dev->part = 0;
841             if (dev->open_device(dcr, OPEN_READ_WRITE)) {
842                ok = dev->upload_cache(dcr, volname, err);
843                dev->part = 0;
844                dev->close(dcr);
845                dev->end_of_job(dcr);
846             }
847          } else if (dev->is_busy() || dev->is_blocked()) {
848             send_dir_busy_message(dir, dev);
849          } else {                     /* device not being used */
850             Dmsg0(400, "Can upload, because device not used\n");
851             dev->setVolCatName(volname);
852             dev->part = 0;
853             if (dev->open_device(dcr, OPEN_READ_WRITE)) {
854                ok = dev->upload_cache(dcr, volname, err);
855                dev->part = 0;
856                dev->close(dcr);
857                dev->end_of_job(dcr);
858             }
859          }
860          dev->max_concurrent_jobs = max_jobs;
861          volume_unused(dcr);
862          dev->Unlock();
863 #ifdef DEVELOPER
864          if (chk_dbglvl(DT_VOLUME)) {
865             Dmsg0(0, "Waiting few seconds to force a bug...\n");
866             bmicrosleep(30, 0);
867             Dmsg0(0, "Doing free_volume()\n");
868          }
869 #endif
870       } else {
871          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), dev_name.c_str());
872       }
873    } else {
874       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
875       pm_strcpy(jcr->errmsg, dir->msg);
876       dir->fsend(_("3912 Error scanning upload command: ERR=%s\n"), jcr->errmsg);
877    }
878 bail_out:
879    if (ok) {
880       dir->fsend(_("3000 OK upload.\n"));
881    } else {
882       dir->fsend(_("3999 Error with the upload: ERR=%s\n"), err);
883    }
884    if (dcr) {
885       free_dcr(dcr);
886    }
887    free_pool_memory(err);
888    free_memory(volname);
889    free_memory(poolname);
890    free_memory(mtype);
891    dir->signal(BNET_EOD);
892    return true;
893 }
894
895
896 /*
897  * Read the tape label and determine if we can safely
898  * label the tape (not a Bacula volume), then label it.
899  *
900  *  Enter with the mutex set
901  */
902 static void label_volume_if_ok(DCR *dcr, char *oldname,
903                                char *newname, char *poolname,
904                                int slot, int relabel)
905 {
906    BSOCK *dir = dcr->jcr->dir_bsock;
907    bsteal_lock_t hold;
908    DEVICE *dev = dcr->dev;
909    int label_status;
910    int mode;
911    const char *volname = (relabel == 1) ? oldname : newname;
912    uint64_t volCatBytes;
913
914    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
915    Dmsg1(100, "Stole device %s lock, writing label.\n", dev->print_name());
916
917    Dmsg0(90, "try_autoload_device - looking for volume_info\n");
918    if (!try_autoload_device(dcr->jcr, dcr, slot, volname)) {
919       goto bail_out;                  /* error */
920    }
921
922
923    if (relabel) {
924       dev->truncating = true;         /* let open_device() know we will truncate it */
925    }
926    /* Set old volume name for open if relabeling */
927    dcr->setVolCatName(volname);
928
929    /* Ensure that the device is open -- autoload_device() closes it */
930    if (dev->is_tape()) {
931       mode = OPEN_READ_WRITE;
932    } else {
933       mode = CREATE_READ_WRITE;
934    }
935    if (!dev->open_device(dcr, mode)) {
936       dir->fsend(_("3929 Unable to open device \"%s\": ERR=%s\n"),
937          dev->print_name(), dev->bstrerror());
938       goto bail_out;
939    }
940
941    /* See what we have for a Volume */
942    label_status = dev->read_dev_volume_label(dcr);
943
944    /* Set new volume name */
945    dcr->setVolCatName(newname);
946    switch(label_status) {
947    case VOL_NAME_ERROR:
948    case VOL_VERSION_ERROR:
949    case VOL_LABEL_ERROR:
950    case VOL_OK:
951       if (!relabel) {
952          dir->fsend(_(
953             "3920 Cannot label Volume because it is already labeled: \"%s\"\n"),
954              dev->VolHdr.VolumeName);
955          break;
956       }
957
958       /* Relabel request. If oldname matches, continue */
959       if (strcmp(oldname, dev->VolHdr.VolumeName) != 0) {
960          dir->fsend(_("3921 Wrong volume mounted.\n"));
961          break;
962       }
963       if (dev->label_type != B_BACULA_LABEL) {
964          dir->fsend(_("3922 Cannot relabel an ANSI/IBM labeled Volume.\n"));
965          break;
966       }
967       /* Fall through wanted! */
968    case VOL_IO_ERROR:
969    case VOL_NO_LABEL:
970       if (!dev->write_volume_label(dcr, newname, poolname,
971               relabel, true /* write label now */)) {
972          dir->fsend(_("3912 Failed to label Volume %s: ERR=%s\n"),
973             newname, dcr->jcr->errmsg);
974          break;
975       }
976       volCatBytes = dev->VolCatInfo.VolCatBytes;
977       /*
978       * After writing label, create a new part
979       */
980       if (dev->is_cloud()) {
981          dev->set_append();
982          if (!dev->open_next_part(dcr)) {
983             dir->fsend(_("3913 Failed to open next part: ERR=%s\n"), dcr->jcr->errmsg);
984             break;
985          }
986       }
987       bstrncpy(dcr->VolumeName, newname, sizeof(dcr->VolumeName));
988       /* The following 3000 OK label. string is scanned in ua_label.c */
989       int type;
990       if (dev->dev_type == B_FILE_DEV || dev->dev_type == B_ALIGNED_DEV ||
991           dev->dev_type == B_CLOUD_DEV)
992       {
993          type = dev->dev_type;
994       } else {
995          type = 0;
996       }
997       dir->fsend("3000 OK label. VolBytes=%lld VolABytes=%lld VolType=%d Volume=\"%s\" Device=%s\n",
998                  volCatBytes, dev->VolCatInfo.VolCatAdataBytes,
999                  type, newname, dev->print_name());
1000       break;
1001    case VOL_TYPE_ERROR:
1002       dir->fsend(_("3917 Failed to label Volume: ERR=%s\n"), dcr->jcr->errmsg);
1003       break;
1004    case VOL_NO_MEDIA:
1005       dir->fsend(_("3918 Failed to label Volume (no media): ERR=%s\n"), dcr->jcr->errmsg);
1006       break;
1007    default:
1008       dir->fsend(_("3919 Cannot label Volume. "
1009                    "Unknown status %d from read_volume_label()\n"), label_status);
1010       break;
1011    }
1012
1013 bail_out:
1014    if (dev->is_open() && !dev->has_cap(CAP_ALWAYSOPEN)) {
1015       dev->close(dcr);
1016    }
1017    
1018    dev->end_of_job(dcr);
1019    
1020    if (!dev->is_open()) {
1021       dev->clear_volhdr();
1022    }
1023    volume_unused(dcr);                   /* no longer using volume */
1024    give_back_device_lock(dev, &hold);
1025    return;
1026 }
1027
1028
1029 /*
1030  * Read the tape label
1031  *
1032  *  Enter with the mutex set
1033  */
1034 static bool read_label(DCR *dcr)
1035 {
1036    int ok;
1037    JCR *jcr = dcr->jcr;
1038    BSOCK *dir = jcr->dir_bsock;
1039    bsteal_lock_t hold;
1040    DEVICE *dev = dcr->dev;
1041
1042    steal_device_lock(dev, &hold, BST_DOING_ACQUIRE);
1043
1044    dcr->VolumeName[0] = 0;
1045    dev->clear_labeled();              /* force read of label */
1046    switch (dev->read_dev_volume_label(dcr)) {
1047    case VOL_OK:
1048       dir->fsend(_("3001 Mounted Volume: %s\n"), dev->VolHdr.VolumeName);
1049       ok = true;
1050       break;
1051    default:
1052       dir->fsend(_("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
1053          dev->print_name(), jcr->errmsg);
1054       ok = false;
1055       break;
1056    }
1057    volume_unused(dcr);
1058    give_back_device_lock(dev, &hold);
1059    return ok;
1060 }
1061
1062 /*
1063  * Searches for device by name, and if found, creates a dcr and
1064  *  returns it.
1065  */
1066 static DCR *find_device(JCR *jcr, POOL_MEM &devname,
1067                         POOLMEM *media_type, int drive)
1068 {
1069    DEVRES *device;
1070    AUTOCHANGER *changer;
1071    bool found = false;
1072    DCR *dcr = NULL;
1073
1074    unbash_spaces(devname);
1075    foreach_res(device, R_DEVICE) {
1076       /* Find resource, and make sure we were able to open it */
1077       if (strcmp(device->hdr.name, devname.c_str()) == 0 &&
1078           (!media_type || strcmp(device->media_type, media_type) ==0)) {
1079          if (!device->dev) {
1080             device->dev = init_dev(jcr, device);
1081          }
1082          if (!device->dev) {
1083             Jmsg(jcr, M_WARNING, 0, _("\n"
1084                "[SW0106] Device \"%s\" requested by DIR could not be opened or does not exist.\n"),
1085                  devname.c_str());
1086             continue;
1087          }
1088          Dmsg1(20, "Found device %s\n", device->hdr.name);
1089          found = true;
1090          break;
1091       }
1092    }
1093    if (!found) {
1094       foreach_res(changer, R_AUTOCHANGER) {
1095          /* Find resource, and make sure we were able to open it */
1096          if (strcmp(devname.c_str(), changer->hdr.name) == 0) {
1097             /* Try each device in this AutoChanger */
1098             foreach_alist(device, changer->device) {
1099                Dmsg1(100, "Try changer device %s\n", device->hdr.name);
1100                if (!device->dev) {
1101                   device->dev = init_dev(jcr, device);
1102                }
1103                if (!device->dev) {
1104                   Dmsg1(100, "Device %s could not be opened. Skipped\n", devname.c_str());
1105                   Jmsg(jcr, M_WARNING, 0, _("\n"
1106                      "[SW0107] Device \"%s\" in changer \"%s\" requested by DIR could not be opened or does not exist.\n"),
1107                        device->hdr.name, devname.c_str());
1108                   continue;
1109                }
1110                if (!device->dev->autoselect) {
1111                   Dmsg1(100, "Device %s not autoselect skipped.\n", devname.c_str());
1112                   continue;              /* device is not available */
1113                } else if (!device->dev->enabled) {
1114                   Dmsg1(100, "Device %s disabled skipped.\n", devname.c_str());
1115                   continue;              /* device disabled */
1116                }
1117                if ((drive < 0 || drive == (int)device->dev->drive_index) &&
1118                    (!media_type || strcmp(device->media_type, media_type) ==0)) {
1119                   Dmsg1(20, "Found changer device %s\n", device->hdr.name);
1120                   found = true;
1121                   break;
1122                }
1123                Dmsg3(100, "Device %s drive wrong: want=%d got=%d skipping\n",
1124                   devname.c_str(), drive, (int)device->dev->drive_index);
1125             }
1126             break;                    /* we found it but could not open a device */
1127          }
1128       }
1129    }
1130
1131    if (found) {
1132       Dmsg1(100, "Found device %s\n", device->hdr.name);
1133       dcr = new_dcr(jcr, NULL, device->dev);
1134       dcr->device = device;
1135    }
1136    return dcr;
1137 }
1138
1139 /*
1140  * Find even disabled devices so that we can enable them
1141  *   ***FIXME*** This could probably be merged with find_device with another
1142  *   argument, but this is easier for the moment.
1143  */
1144 static DCR *find_any_device(JCR *jcr, POOL_MEM &devname,
1145                         POOLMEM *media_type, int drive)
1146 {
1147    DEVRES *device;
1148    AUTOCHANGER *changer;
1149    bool found = false;
1150    DCR *dcr = NULL;
1151
1152    unbash_spaces(devname);
1153    foreach_res(device, R_DEVICE) {
1154       /* Find resource, and make sure we were able to open it */
1155       if (strcmp(device->hdr.name, devname.c_str()) == 0 &&
1156           (!media_type || strcmp(device->media_type, media_type) ==0)) {
1157          if (!device->dev) {
1158             device->dev = init_dev(jcr, device);
1159          }
1160          if (!device->dev) {
1161             Jmsg(jcr, M_WARNING, 0, _("\n"
1162                "[SW0108] Device \"%s\" requested by DIR could not be opened or does not exist.\n"),
1163                  devname.c_str());
1164             continue;
1165          }
1166          Dmsg1(20, "Found device %s\n", device->hdr.name);
1167          found = true;
1168          break;
1169       }
1170    }
1171    if (!found) {
1172       foreach_res(changer, R_AUTOCHANGER) {
1173          /* Find resource, and make sure we were able to open it */
1174          if (strcmp(devname.c_str(), changer->hdr.name) == 0) {
1175             /* Try each device in this AutoChanger */
1176             foreach_alist(device, changer->device) {
1177                Dmsg1(100, "Try changer device %s\n", device->hdr.name);
1178                if (!device->dev) {
1179                   device->dev = init_dev(jcr, device);
1180                }
1181                if (!device->dev) {
1182                   Dmsg1(100, "Device %s could not be opened. Skipped\n", devname.c_str());
1183                   Jmsg(jcr, M_WARNING, 0, _("\n"
1184                      "[SW0109] Device \"%s\" in changer \"%s\" requested by DIR could not be opened or does not exist.\n"),
1185                        device->hdr.name, devname.c_str());
1186                   continue;
1187                }
1188                if ((drive < 0 || drive == (int)device->dev->drive_index) &&
1189                    (!media_type || strcmp(device->media_type, media_type) ==0)) {
1190                   Dmsg1(20, "Found changer device %s\n", device->hdr.name);
1191                   found = true;
1192                   break;
1193                }
1194                Dmsg3(100, "Device %s drive wrong: want=%d got=%d skipping\n",
1195                   devname.c_str(), drive, (int)device->dev->drive_index);
1196             }
1197             break;                    /* we found it but could not open a device */
1198          }
1199       }
1200    }
1201
1202    if (found) {
1203       Dmsg1(100, "Found device %s\n", device->hdr.name);
1204       dcr = new_dcr(jcr, NULL, device->dev);
1205       dcr->device = device;
1206    }
1207    return dcr;
1208 }
1209
1210
1211 /*
1212  * Mount command from Director
1213  */
1214 static bool mount_cmd(JCR *jcr)
1215 {
1216    POOL_MEM devname;
1217    BSOCK *dir = jcr->dir_bsock;
1218    DEVICE *dev;
1219    DCR *dcr;
1220    int32_t drive;      /* device index */
1221    int32_t slot;
1222    bool ok;
1223
1224    Dmsg1(100, "%s\n", dir->msg);
1225    ok = sscanf(dir->msg, "mount %127s drive=%d slot=%d", devname.c_str(),
1226                &drive, &slot) == 3;
1227    Dmsg3(100, "ok=%d device_index=%d slot=%d\n", ok, drive, slot);
1228    if (ok) {
1229       dcr = find_device(jcr, devname, NULL, drive);
1230       if (dcr) {
1231          dev = dcr->dev;
1232          dev->Lock();                 /* Use P to avoid indefinite block */
1233          Dmsg2(100, "mount cmd blocked=%d must_unload=%d\n", dev->blocked(),
1234             dev->must_unload());
1235          switch (dev->blocked()) {         /* device blocked? */
1236          case BST_WAITING_FOR_SYSOP:
1237             /* Someone is waiting, wake him */
1238             Dmsg0(100, "Waiting for mount. Attempting to wake thread\n");
1239             dev->set_blocked(BST_MOUNT);
1240             dir->fsend("3001 OK mount requested. %sDevice=%s\n",
1241                        slot>0?_("Specified slot ignored. "):"",
1242                        dev->print_name());
1243             Dmsg1(100, "JobId=%u broadcast wait_next_vol\n", (uint32_t)dcr->jcr->JobId);
1244             pthread_cond_broadcast(&dev->wait_next_vol);
1245             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
1246             pthread_cond_broadcast(&wait_device_release);
1247             break;
1248
1249          /* In both of these two cases, we (the user) unmounted the Volume */
1250          case BST_UNMOUNTED_WAITING_FOR_SYSOP:
1251          case BST_UNMOUNTED:
1252             Dmsg2(100, "Unmounted changer=%d slot=%d\n", dev->is_autochanger(), slot);
1253             if (dev->is_autochanger() && slot > 0) {
1254                try_autoload_device(jcr, dcr, slot, "");
1255             }
1256             /* We freed the device, so reopen it and wake any waiting threads */
1257             if (!dev->open_device(dcr, OPEN_READ_ONLY)) {
1258                dir->fsend(_("3901 Unable to open device \"%s\": ERR=%s\n"),
1259                   dev->print_name(), dev->bstrerror());
1260                if (dev->blocked() == BST_UNMOUNTED) {
1261                   /* We blocked the device, so unblock it */
1262                   Dmsg0(100, "Unmounted. Unblocking device\n");
1263                   unblock_device(dev);
1264                }
1265                break;
1266             }
1267             dev->read_dev_volume_label(dcr);
1268             if (dev->blocked() == BST_UNMOUNTED) {
1269                /* We blocked the device, so unblock it */
1270                Dmsg0(100, "Unmounted. Unblocking device\n");
1271                read_label(dcr);       /* this should not be necessary */
1272                unblock_device(dev);
1273             } else {
1274                Dmsg0(100, "Unmounted waiting for mount. Attempting to wake thread\n");
1275                dev->set_blocked(BST_MOUNT);
1276             }
1277             if (dev->is_labeled()) {
1278                dir->fsend(_("3001 Device \"%s\" is mounted with Volume \"%s\"\n"),
1279                   dev->print_name(), dev->VolHdr.VolumeName);
1280             } else {
1281                dir->fsend(_("3905 Device \"%s\" open but no Bacula volume is mounted.\n"
1282                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
1283                           dev->print_name());
1284             }
1285             pthread_cond_broadcast(&dev->wait_next_vol);
1286             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
1287             pthread_cond_broadcast(&wait_device_release);
1288             break;
1289
1290          case BST_DOING_ACQUIRE:
1291             dir->fsend(_("3001 Device \"%s\" is doing acquire.\n"),
1292                        dev->print_name());
1293             break;
1294
1295          case BST_WRITING_LABEL:
1296             dir->fsend(_("3903 Device \"%s\" is being labeled.\n"),
1297                dev->print_name());
1298             break;
1299
1300          case BST_NOT_BLOCKED:
1301             Dmsg2(100, "Not blocked changer=%d slot=%d\n", dev->is_autochanger(), slot);
1302             if (dev->is_autochanger() && slot > 0) {
1303                try_autoload_device(jcr, dcr, slot, "");
1304             }
1305             if (dev->is_open()) {
1306                if (dev->is_labeled()) {
1307                   dir->fsend(_("3001 Device \"%s\" is mounted with Volume \"%s\"\n"),
1308                      dev->print_name(), dev->VolHdr.VolumeName);
1309                } else {
1310                   dir->fsend(_("3905 Device \"%s\" open but no Bacula volume is mounted.\n"
1311                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
1312                              dev->print_name());
1313                }
1314             } else if (dev->is_tape()) {
1315                if (!dev->open_device(dcr, OPEN_READ_ONLY)) {
1316                   dir->fsend(_("3901 Unable to open device \"%s\": ERR=%s\n"),
1317                      dev->print_name(), dev->bstrerror());
1318                   break;
1319                }
1320                read_label(dcr);
1321                if (dev->is_labeled()) {
1322                   dir->fsend(_("3001 Device \"%s\" is already mounted with Volume \"%s\"\n"),
1323                      dev->print_name(), dev->VolHdr.VolumeName);
1324                } else {
1325                   dir->fsend(_("3905 Device \"%s\" open but no Bacula volume is mounted.\n"
1326                                     "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
1327                              dev->print_name());
1328                }
1329                if (dev->is_open() && !dev->has_cap(CAP_ALWAYSOPEN)) {
1330                   dev->close(dcr);
1331                }
1332             } else if (dev->is_unmountable()) {
1333                if (dev->mount(1)) {
1334                   dir->fsend(_("3002 Device \"%s\" is mounted.\n"), dev->print_name());
1335                } else {
1336                   dir->fsend(_("3907 %s"), dev->bstrerror());
1337                }
1338             } else { /* must be file */
1339                dir->fsend(_("3906 File device \"%s\" is always mounted.\n"),
1340                   dev->print_name());
1341                pthread_cond_broadcast(&dev->wait_next_vol);
1342                Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
1343                pthread_cond_broadcast(&wait_device_release);
1344             }
1345             break;
1346
1347          case BST_RELEASING:
1348             dir->fsend(_("3930 Device \"%s\" is being released.\n"), dev->print_name());
1349             break;
1350
1351          default:
1352             dir->fsend(_("3905 Unknown wait state %d\n"), dev->blocked());
1353             break;
1354          }
1355          dev->Unlock();
1356          free_dcr(dcr);
1357       } else {
1358          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1359       }
1360    } else {
1361       pm_strcpy(jcr->errmsg, dir->msg);
1362       dir->fsend(_("3909 Error scanning mount command: %s\n"), jcr->errmsg);
1363    }
1364    dir->signal(BNET_EOD);
1365    return true;
1366 }
1367
1368 /* enable command from Director */
1369 static bool enable_cmd(JCR *jcr)
1370 {
1371    POOL_MEM devname;
1372    BSOCK *dir = jcr->dir_bsock;
1373    DEVICE *dev;
1374    DCR *dcr;
1375    int32_t drive;
1376    bool ok;
1377    int deleted;
1378
1379    ok = sscanf(dir->msg, "enable %127s drive=%d", devname.c_str(),
1380                &drive) == 2;
1381    Dmsg3(100, "ok=%d device=%s device_index=%d\n", ok, devname.c_str(), drive);
1382    if (ok) {
1383       dcr = find_any_device(jcr, devname, NULL, drive);
1384       if (dcr) {
1385          dev = dcr->dev;
1386          dev->Lock();                 /* Use P to avoid indefinite block */
1387          if (dev->enabled) {
1388             dir->fsend(_("3003 Device \"%s\" already enabled.\n"), dev->print_name());
1389          } else {
1390             dev->enabled = true;
1391             dir->fsend(_("3002 Device \"%s\" enabled.\n"), dev->print_name());
1392          }
1393          deleted = dev->delete_alerts();
1394          if (deleted > 0) {
1395             dir->fsend(_("3004 Device \"%s\" deleted %d alert%s.\n"),
1396                 dev->print_name(), deleted, deleted>1?"s":"");
1397          }
1398          dev->Unlock();
1399          free_dcr(dcr);
1400       }
1401    } else {
1402       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1403       pm_strcpy(jcr->errmsg, dir->msg);
1404       dir->fsend(_("3907 Error scanning \"enable\" command: %s\n"), jcr->errmsg);
1405    }
1406    dir->signal(BNET_EOD);
1407    return true;
1408 }
1409
1410 /* enable command from Director */
1411 static bool disable_cmd(JCR *jcr)
1412 {
1413    POOL_MEM devname;
1414    BSOCK *dir = jcr->dir_bsock;
1415    DEVICE *dev;
1416    DCR *dcr;
1417    int32_t drive;
1418    bool ok;
1419
1420    ok = sscanf(dir->msg, "disable %127s drive=%d", devname.c_str(),
1421                &drive) == 2;
1422    Dmsg3(100, "ok=%d device=%s device_index=%d\n", ok, devname.c_str(), drive);
1423    if (ok) {
1424       dcr = find_device(jcr, devname, NULL, drive);
1425       if (dcr) {
1426          dev = dcr->dev;
1427          dev->Lock();
1428          dev->enabled = false;
1429          dir->fsend(_("3002 Device \"%s\" disabled.\n"), dev->print_name());
1430          dev->Unlock();
1431          free_dcr(dcr);
1432       }
1433    } else {
1434       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1435       pm_strcpy(jcr->errmsg, dir->msg);
1436       dir->fsend(_("3907 Error scanning \"disable\" command: %s\n"), jcr->errmsg);
1437    }
1438    dir->signal(BNET_EOD);
1439    return true;
1440 }
1441
1442
1443 /*
1444  * unmount command from Director
1445  */
1446 static bool unmount_cmd(JCR *jcr)
1447 {
1448    POOL_MEM devname;
1449    BSOCK *dir = jcr->dir_bsock;
1450    DEVICE *dev;
1451    DCR *dcr;
1452    int32_t drive;
1453
1454    if (sscanf(dir->msg, "unmount %127s drive=%d", devname.c_str(), &drive) == 2) {
1455       dcr = find_device(jcr, devname, NULL, drive);
1456       if (dcr) {
1457          dev = dcr->dev;
1458          dev->Lock();                 /* Use P to avoid indefinite block */
1459          if (!dev->is_open()) {
1460             if (!dev->is_busy()) {
1461                unload_autochanger(dcr, -1);
1462             }
1463             if (dev->is_unmountable()) {
1464                if (dev->unmount(0)) {
1465                   dir->fsend(_("3002 Device \"%s\" unmounted.\n"),
1466                      dev->print_name());
1467                } else {
1468                   dir->fsend(_("3907 %s"), dev->bstrerror());
1469                }
1470             } else {
1471                Dmsg0(90, "Device already unmounted\n");
1472                dir->fsend(_("3901 Device \"%s\" is already unmounted.\n"),
1473                   dev->print_name());
1474             }
1475          } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
1476             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
1477                dev->blocked());
1478             if (!unload_autochanger(dcr, -1)) {
1479                /*
1480                 * ***FIXME**** what is this ???? -- probably we had
1481                 *   the wrong volume so we must free it and try again. KES
1482                 */
1483                dev->close(dcr);
1484                free_volume(dev);
1485             }
1486             if (dev->is_unmountable() && !dev->unmount(0)) {
1487                dir->fsend(_("3907 %s"), dev->bstrerror());
1488             } else {
1489                dev->set_blocked(BST_UNMOUNTED_WAITING_FOR_SYSOP);
1490                dir->fsend(_("3001 Device \"%s\" unmounted.\n"),
1491                   dev->print_name());
1492             }
1493
1494          } else if (dev->blocked() == BST_DOING_ACQUIRE) {
1495             dir->fsend(_("3902 Device \"%s\" is busy in acquire.\n"),
1496                dev->print_name());
1497
1498          } else if (dev->blocked() == BST_WRITING_LABEL) {
1499             dir->fsend(_("3903 Device \"%s\" is being labeled.\n"),
1500                dev->print_name());
1501
1502          } else if (dev->is_busy()) {
1503             send_dir_busy_message(dir, dev);
1504          } else {                     /* device not being used */
1505             Dmsg0(90, "Device not in use, unmounting\n");
1506             /* On FreeBSD, I am having ASSERT() failures in block_device()
1507              * and I can only imagine that the thread id that we are
1508              * leaving in no_wait_id is being re-used. So here,
1509              * we simply do it by hand.  Gross, but a solution.
1510              */
1511             /*  block_device(dev, BST_UNMOUNTED); replace with 2 lines below */
1512             dev->set_blocked(BST_UNMOUNTED);
1513             clear_thread_id(dev->no_wait_id);
1514             if (!unload_autochanger(dcr, -1)) {
1515                dev->close(dcr);
1516                free_volume(dev);
1517             }
1518             if (dev->is_unmountable() && !dev->unmount(0)) {
1519                dir->fsend(_("3907 %s"), dev->bstrerror());
1520             } else {
1521                dir->fsend(_("3002 Device \"%s\" unmounted.\n"),
1522                   dev->print_name());
1523             }
1524          }
1525          dev->Unlock();
1526          free_dcr(dcr);
1527       } else {
1528          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1529       }
1530    } else {
1531       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1532       pm_strcpy(jcr->errmsg, dir->msg);
1533       dir->fsend(_("3907 Error scanning unmount command: %s\n"), jcr->errmsg);
1534    }
1535    dir->signal(BNET_EOD);
1536    return true;
1537 }
1538
1539 #if 0
1540 /*
1541  * The truncate command will recycle a volume. The director can call this
1542  * after purging a volume so that disk space will not be wasted. Only useful
1543  * for File Storage, of course.
1544  *
1545  *
1546  * It is currently disabled
1547  */
1548 static bool action_on_purge_cmd(JCR *jcr)
1549 {
1550    BSOCK *dir = jcr->dir_bsock;
1551
1552    char devname[MAX_NAME_LENGTH];
1553    char volumename[MAX_NAME_LENGTH];
1554    int32_t action;
1555
1556    /* TODO: Need to find a free device and ask for slot to the director */
1557    if (sscanf(dir->msg,
1558               "action_on_purge %127s vol=%127s action=%d",
1559               devname, volumename, &action)!= 5)
1560    {
1561       dir->fsend(_("3916 Error scanning action_on_purge command\n"));
1562       goto done;
1563    }
1564    unbash_spaces(volumename);
1565    unbash_spaces(devname);
1566
1567    /* Check if action is correct */
1568    if (action & AOP_TRUNCTATE) {
1569
1570    }
1571    /* ... */
1572
1573 done:
1574    dir->signal(BNET_EOD);
1575    return true;
1576 }
1577 #endif
1578
1579 /*
1580  * Release command from Director. This rewinds the device and if
1581  *   configured does a offline and ensures that Bacula will
1582  *   re-read the label of the tape before continuing. This gives
1583  *   the operator the chance to change the tape anytime before the
1584  *   next job starts.
1585  */
1586 static bool release_cmd(JCR *jcr)
1587 {
1588    POOL_MEM devname;
1589    BSOCK *dir = jcr->dir_bsock;
1590    DEVICE *dev;
1591    DCR *dcr;
1592    int32_t drive;
1593
1594    if (sscanf(dir->msg, "release %127s drive=%d", devname.c_str(), &drive) == 2) {
1595       dcr = find_device(jcr, devname, NULL, drive);
1596       if (dcr) {
1597          dev = dcr->dev;
1598          dev->Lock();                 /* Use P to avoid indefinite block */
1599          if (!dev->is_open()) {
1600             if (!dev->is_busy()) {
1601                unload_autochanger(dcr, -1);
1602             }
1603             Dmsg0(90, "Device already released\n");
1604             dir->fsend(_("3921 Device \"%s\" already released.\n"),
1605                dev->print_name());
1606
1607          } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
1608             Dmsg2(90, "%d waiter dev_block=%d.\n", dev->num_waiting,
1609                dev->blocked());
1610             unload_autochanger(dcr, -1);
1611             dir->fsend(_("3922 Device \"%s\" waiting for sysop.\n"),
1612                dev->print_name());
1613
1614          } else if (dev->blocked() == BST_UNMOUNTED_WAITING_FOR_SYSOP) {
1615             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
1616                dev->blocked());
1617             dir->fsend(_("3922 Device \"%s\" waiting for mount.\n"),
1618                dev->print_name());
1619
1620          } else if (dev->blocked() == BST_DOING_ACQUIRE) {
1621             dir->fsend(_("3923 Device \"%s\" is busy in acquire.\n"),
1622                dev->print_name());
1623
1624          } else if (dev->blocked() == BST_WRITING_LABEL) {
1625             dir->fsend(_("3914 Device \"%s\" is being labeled.\n"),
1626                dev->print_name());
1627
1628          } else if (dev->is_busy()) {
1629             send_dir_busy_message(dir, dev);
1630          } else {                     /* device not being used */
1631             Dmsg0(90, "Device not in use, releasing\n");
1632             dcr->release_volume();
1633             dir->fsend(_("3022 Device \"%s\" released.\n"),
1634                dev->print_name());
1635          }
1636          dev->Unlock();
1637          free_dcr(dcr);
1638       } else {
1639          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1640       }
1641    } else {
1642       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1643       pm_strcpy(jcr->errmsg, dir->msg);
1644       dir->fsend(_("3927 Error scanning release command: %s\n"), jcr->errmsg);
1645    }
1646    dir->signal(BNET_EOD);
1647    return true;
1648 }
1649
1650 static pthread_mutex_t bsr_mutex = PTHREAD_MUTEX_INITIALIZER;
1651 static uint32_t bsr_uniq = 0;
1652
1653 static bool get_bootstrap_file(JCR *jcr, BSOCK *sock)
1654 {
1655    POOLMEM *fname = get_pool_memory(PM_FNAME);
1656    FILE *bs;
1657    bool ok = false;
1658
1659    if (jcr->RestoreBootstrap) {
1660       unlink(jcr->RestoreBootstrap);
1661       free_pool_memory(jcr->RestoreBootstrap);
1662    }
1663    P(bsr_mutex);
1664    bsr_uniq++;
1665    Mmsg(fname, "%s/%s.%s.%d.bootstrap", me->working_directory, me->hdr.name,
1666       jcr->Job, bsr_uniq);
1667    V(bsr_mutex);
1668    Dmsg1(400, "bootstrap=%s\n", fname);
1669    jcr->RestoreBootstrap = fname;
1670    bs = bfopen(fname, "a+b");           /* create file */
1671    if (!bs) {
1672       berrno be;
1673       Jmsg(jcr, M_FATAL, 0, _("[SF0110] Could not create bootstrap file %s: ERR=%s\n"),
1674          jcr->RestoreBootstrap, be.bstrerror());
1675       goto bail_out;
1676    }
1677    Dmsg0(150, "=== Bootstrap file ===\n");
1678    while (sock->recv() >= 0) {
1679        Dmsg1(150, "%s", sock->msg);
1680        fputs(sock->msg, bs);
1681    }
1682    fclose(bs);
1683    Dmsg0(150, "=== end bootstrap file ===\n");
1684    jcr->bsr = parse_bsr(jcr, jcr->RestoreBootstrap);
1685    if (!jcr->bsr) {
1686       Jmsg(jcr, M_FATAL, 0, _("[SF0111] Error parsing bootstrap file.\n"));
1687       goto bail_out;
1688    }
1689    if (chk_dbglvl(150)) {
1690       dump_bsr(NULL, jcr->bsr, true);
1691    }
1692
1693    /* If we got a bootstrap, we are reading, so create read volume list */
1694    create_restore_volume_list(jcr, true /* store the volumes in the global vol_read list */);
1695    ok = true;
1696
1697 bail_out:
1698    unlink(jcr->RestoreBootstrap);
1699    free_pool_memory(jcr->RestoreBootstrap);
1700    jcr->RestoreBootstrap = NULL;
1701    if (!ok) {
1702       sock->fsend(ERROR_bootstrap);
1703       return false;
1704    }
1705    return sock->fsend(OK_bootstrap);
1706 }
1707
1708 static bool bootstrap_cmd(JCR *jcr)
1709 {
1710    return get_bootstrap_file(jcr, jcr->dir_bsock);
1711 }
1712
1713 /*
1714  * Autochanger command from Director
1715  */
1716 static bool changer_cmd(JCR *jcr)
1717 {
1718    POOL_MEM devname;
1719    BSOCK *dir = jcr->dir_bsock;
1720    DEVICE *dev;
1721    DCR *dcr;
1722    const char *cmd = NULL;
1723    bool ok = false;
1724    /*
1725     * A safe_cmd may call autochanger script but does not load/unload
1726     *    slots so it can be done at the same time that the drive is open.
1727     */
1728    bool safe_cmd = false;
1729
1730    if (sscanf(dir->msg, "autochanger listall %127s", devname.c_str()) == 1) {
1731       cmd = "listall";
1732       safe_cmd = ok = true;
1733    } else if (sscanf(dir->msg, "autochanger list %127s", devname.c_str()) == 1) {
1734       cmd = "list";
1735       safe_cmd = ok = true;
1736    } else if (sscanf(dir->msg, "autochanger slots %127s", devname.c_str()) == 1) {
1737       cmd = "slots";
1738       safe_cmd = ok = true;
1739    } else if (sscanf(dir->msg, "autochanger drives %127s", devname.c_str()) == 1) {
1740       cmd = "drives";
1741       safe_cmd = ok = true;
1742    }
1743    if (ok) {
1744       dcr = find_device(jcr, devname, NULL, -1);
1745       if (dcr) {
1746          dev = dcr->dev;
1747          dev->Lock();                 /* Use P to avoid indefinite block */
1748          if (!dev->device->changer_res) {
1749             dir->fsend(_("3998 Device \"%s\" is not an autochanger.\n"),
1750                dev->print_name());
1751          /* Under certain "safe" conditions, we can steal the lock */
1752          } else if (safe_cmd || !dev->is_open() || dev->can_steal_lock()) {
1753             autochanger_cmd(dcr, dir, cmd);
1754          } else if (dev->is_busy() || dev->is_blocked()) {
1755             send_dir_busy_message(dir, dev);
1756          } else {                     /* device not being used */
1757             autochanger_cmd(dcr, dir, cmd);
1758          }
1759          dev->Unlock();
1760          free_dcr(dcr);
1761       } else {
1762          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1763       }
1764    } else {  /* error on scanf */
1765       pm_strcpy(jcr->errmsg, dir->msg);
1766       dir->fsend(_("3909 Error scanning autochanger drives/list/slots command: %s\n"),
1767          jcr->errmsg);
1768    }
1769    dir->signal(BNET_EOD);
1770    return true;
1771 }
1772
1773 /*
1774  * Read and return the Volume label
1775  */
1776 static bool readlabel_cmd(JCR *jcr)
1777 {
1778    POOL_MEM devname;
1779    BSOCK *dir = jcr->dir_bsock;
1780    DEVICE *dev;
1781    DCR *dcr;
1782    int32_t Slot, drive;
1783
1784    if (sscanf(dir->msg, "readlabel %127s Slot=%d drive=%d", devname.c_str(),
1785        &Slot, &drive) == 3) {
1786       dcr = find_device(jcr, devname, NULL, drive);
1787       if (dcr) {
1788          dev = dcr->dev;
1789          dev->Lock();                 /* Use P to avoid indefinite block */
1790          if (!dev->is_open()) {
1791             read_volume_label(jcr, dcr, dev, Slot);
1792             dev->close(dcr);
1793          /* Under certain "safe" conditions, we can steal the lock */
1794          } else if (dev->can_steal_lock()) {
1795             read_volume_label(jcr, dcr, dev, Slot);
1796          } else if (dev->is_busy() || dev->is_blocked()) {
1797             send_dir_busy_message(dir, dev);
1798          } else {                     /* device not being used */
1799             read_volume_label(jcr, dcr, dev, Slot);
1800          }
1801          dev->Unlock();
1802          free_dcr(dcr);
1803       } else {
1804          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1805       }
1806    } else {
1807       pm_strcpy(jcr->errmsg, dir->msg);
1808       dir->fsend(_("3909 Error scanning readlabel command: %s\n"), jcr->errmsg);
1809    }
1810    dir->signal(BNET_EOD);
1811    return true;
1812 }
1813
1814
1815 /*
1816  * Read the tape label
1817  *
1818  *  Enter with the mutex set
1819  */
1820 static void read_volume_label(JCR *jcr, DCR *dcr, DEVICE *dev, int Slot)
1821 {
1822    BSOCK *dir = jcr->dir_bsock;
1823    bsteal_lock_t hold;
1824
1825    dcr->set_dev(dev);
1826    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
1827
1828    if (!try_autoload_device(jcr, dcr, Slot, "")) {
1829       goto bail_out;                  /* error */
1830    }
1831
1832    dev->clear_labeled();              /* force read of label */
1833    switch (dev->read_dev_volume_label(dcr)) {
1834    case VOL_OK:
1835       /* DO NOT add quotes around the Volume name. It is scanned in the DIR */
1836       dir->fsend(_("3001 Volume=%s Slot=%d\n"), dev->VolHdr.VolumeName, Slot);
1837       Dmsg1(100, "Volume: %s\n", dev->VolHdr.VolumeName);
1838       break;
1839    default:
1840       dir->fsend(_("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
1841                  dev->print_name(), jcr->errmsg);
1842       break;
1843    }
1844
1845 bail_out:
1846    give_back_device_lock(dev, &hold);
1847    return;
1848 }
1849
1850 static bool try_autoload_device(JCR *jcr, DCR *dcr, int slot, const char *VolName)
1851 {
1852    BSOCK *dir = jcr->dir_bsock;
1853
1854    bstrncpy(dcr->VolumeName, VolName, sizeof(dcr->VolumeName));
1855    dcr->VolCatInfo.Slot = slot;
1856    dcr->VolCatInfo.InChanger = slot > 0;
1857    if (autoload_device(dcr, 0, dir) < 0) {    /* autoload if possible */
1858       return false;
1859    }
1860    return true;
1861 }
1862
1863 static void send_dir_busy_message(BSOCK *dir, DEVICE *dev)
1864 {
1865    if (dev->is_blocked()) {
1866       switch (dev->blocked()) {
1867       case BST_UNMOUNTED:
1868          dir->fsend(_("3931 Device \"%s\" is BLOCKED. user unmounted.\n"),
1869             dev->print_name());
1870          break;
1871       case BST_UNMOUNTED_WAITING_FOR_SYSOP:
1872          dir->fsend(_("3932 Device \"%s\" is BLOCKED. user unmounted during wait for media/mount.\n"),
1873              dev->print_name());
1874          break;
1875       case BST_WAITING_FOR_SYSOP:
1876          dir->fsend(_("3933 Device \"%s\" is BLOCKED waiting for media.\n"),
1877             dev->print_name());
1878          break;
1879       case BST_DOING_ACQUIRE:
1880          dir->fsend(_("3934 Device \"%s\" is being initialized.\n"),
1881             dev->print_name());
1882          break;
1883       case BST_WRITING_LABEL:
1884          dir->fsend(_("3935 Device \"%s\" is blocked labeling a Volume.\n"),
1885             dev->print_name());
1886          break;
1887       default:
1888          dir->fsend(_("3935 Device \"%s\" is blocked for unknown reason.\n"),
1889             dev->print_name());
1890          break;
1891       }
1892    } else if (dev->can_read()) {
1893        dir->fsend(_("3936 Device \"%s\" is busy reading.\n"),
1894                    dev->print_name());;
1895    } else {
1896        dir->fsend(_("3937 Device \"%s\" is busy with writers=%d reserved=%d.\n"),
1897           dev->print_name(), dev->num_writers, dev->num_reserved());
1898    }
1899 }