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