]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dircmd.c
a7b631a8311ab2b069c55360cc89a3acaab936ba
[bacula/bacula] / bacula / src / stored / dircmd.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2001-2008 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version two of the GNU General Public
10    License as published by the Free Software Foundation and included
11    in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of John Walker.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  *  This file handles accepting Director Commands
30  *
31  *    Most Director commands are handled here, with the
32  *    exception of the Job command command and subsequent
33  *    subcommands that are handled
34  *    in job.c.
35  *
36  *    N.B. in this file, in general we must use P(dev->mutex) rather
37  *      than dev->r_lock() so that we can examine the blocked
38  *      state rather than blocking ourselves because a Job
39  *      thread has the device blocked. In some "safe" cases,
40  *      we can do things to a blocked device. CAREFUL!!!!
41  *
42  *    File daemon commands are handled in fdcmd.c
43  *
44  *     Kern Sibbald, May MMI
45  *
46  *   Version $Id$
47  *
48  */
49
50 #include "bacula.h"
51 #include "stored.h"
52
53 /* Exported variables */
54
55 /* Imported variables */
56 extern BSOCK *filed_chan;
57 extern int r_first, r_last;
58 extern struct s_res resources[];
59 extern struct s_last_job last_job;
60 extern bool init_done;
61
62 /* Static variables */
63 static char derrmsg[]     = "3900 Invalid command\n";
64 static char OKsetdebug[]  = "3000 OK setdebug=%d\n";
65 static char invalid_cmd[] = "3997 Invalid command for a Director with Monitor directive enabled.\n";
66
67 /* Imported functions */
68 extern void terminate_child();
69 extern bool job_cmd(JCR *jcr);
70 extern bool use_cmd(JCR *jcr);
71 extern bool run_cmd(JCR *jcr);
72 extern bool status_cmd(JCR *sjcr);
73 extern bool qstatus_cmd(JCR *jcr);
74 //extern bool query_cmd(JCR *jcr);
75
76 /* Forward referenced functions */
77 static bool label_cmd(JCR *jcr);
78 static bool die_cmd(JCR *jcr);
79 static bool relabel_cmd(JCR *jcr);
80 static bool readlabel_cmd(JCR *jcr);
81 static bool release_cmd(JCR *jcr);
82 static bool setdebug_cmd(JCR *jcr);
83 static bool cancel_cmd(JCR *cjcr);
84 static bool mount_cmd(JCR *jcr);
85 static bool unmount_cmd(JCR *jcr);
86 static bool bootstrap_cmd(JCR *jcr);
87 static bool changer_cmd(JCR *sjcr);
88 static bool do_label(JCR *jcr, int relabel);
89 static DCR *find_device(JCR *jcr, POOL_MEM &dev_name, int drive);
90 static void read_volume_label(JCR *jcr, DCR *dcr, DEVICE *dev, int Slot);
91 static void label_volume_if_ok(DCR *dcr, char *oldname,
92                                char *newname, char *poolname,
93                                int Slot, int relabel);
94 static bool try_autoload_device(JCR *jcr, DCR *dcr, int slot, const char *VolName);
95 static void send_dir_busy_message(BSOCK *dir, DEVICE *dev);
96
97 struct s_cmds {
98    const char *cmd;
99    bool (*func)(JCR *jcr);
100    int monitoraccess; /* specify if monitors have access to this function */
101 };
102
103 /*
104  * The following are the recognized commands from the Director.
105  */
106 static struct s_cmds cmds[] = {
107    {"JobId=",      job_cmd,         0},     /* start Job */
108    {"autochanger", changer_cmd,     0},
109    {"bootstrap",   bootstrap_cmd,   0},
110    {"cancel",      cancel_cmd,      0},
111    {".die",        die_cmd,         0},
112    {"label",       label_cmd,       0},     /* label a tape */
113    {"mount",       mount_cmd,       0},
114    {"readlabel",   readlabel_cmd,   0},
115    {"release",     release_cmd,     0},
116    {"relabel",     relabel_cmd,     0},     /* relabel a tape */
117    {"setdebug=",   setdebug_cmd,    0},     /* set debug level */
118    {"status",      status_cmd,      1},
119    {".status",     qstatus_cmd,     1},
120    {"unmount",     unmount_cmd,     0},
121    {"use storage=", use_cmd,        0},
122    {"run",         run_cmd,         0},
123 // {"query",       query_cmd,       0},
124    {NULL,        NULL}                      /* list terminator */
125 };
126
127
128 /*
129  * Connection request. We accept connections either from the
130  *  Director or a Client (File daemon).
131  *
132  * Note, we are running as a seperate thread of the Storage daemon.
133  *  and it is because a Director has made a connection with
134  *  us on the "Message" channel.
135  *
136  * Basic tasks done here:
137  *  - Create a JCR record
138  *  - If it was from the FD, call handle_filed_connection()
139  *  - Authenticate the Director
140  *  - We wait for a command
141  *  - We execute the command
142  *  - We continue or exit depending on the return status
143  */
144 void *handle_connection_request(void *arg)
145 {
146    BSOCK *bs = (BSOCK *)arg;
147    JCR *jcr;
148    int i;
149    bool found, quit;
150    int bnet_stat = 0;
151    char name[500];
152
153    if (bs->recv() <= 0) {
154       Emsg0(M_ERROR, 0, _("Connection request failed.\n"));
155       bs->close();
156       return NULL;
157    }
158
159    /*
160     * Do a sanity check on the message received
161     */
162    if (bs->msglen < 25 || bs->msglen > (int)sizeof(name)) {
163       Dmsg1(000, "<filed: %s", bs->msg);
164       Emsg1(M_ERROR, 0, _("Invalid connection. Len=%d\n"), bs->msglen);
165       bs->close();
166       return NULL;
167    }
168    /*
169     * See if this is a File daemon connection. If so
170     *   call FD handler.
171     */
172    Dmsg1(110, "Conn: %s", bs->msg);
173    if (debug_level == 3) {
174       Dmsg1(000, "<filed: %s", bs->msg);
175    }
176    if (sscanf(bs->msg, "Hello Start Job %127s", name) == 1) {
177       Dmsg0(110, "Got a FD connection\n");
178       handle_filed_connection(bs, name);
179       return NULL;
180    }
181
182    /* 
183     * This is a connection from the Director, so setup a JCR 
184     */
185    Dmsg0(110, "Got a DIR connection\n");
186    jcr = new_jcr(sizeof(JCR), stored_free_jcr); /* create Job Control Record */
187    jcr->dir_bsock = bs;               /* save Director bsock */
188    jcr->dir_bsock->set_jcr(jcr);
189    jcr->dcrs = New(alist(10, not_owned_by_alist));
190    /* Initialize FD start condition variable */
191    int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
192    if (errstat != 0) {
193       berrno be;
194       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
195       goto bail_out;
196    }
197
198    Dmsg0(1000, "stored in start_job\n");
199
200    /*
201     * Authenticate the Director
202     */
203    if (!authenticate_director(jcr)) {
204       Jmsg(jcr, M_FATAL, 0, _("Unable to authenticate Director\n"));
205       goto bail_out;
206    }
207    Dmsg0(90, "Message channel init completed.\n");
208
209    for (quit=false; !quit;) {
210       /* Read command */
211       if ((bnet_stat = bs->recv()) <= 0) {
212          break;               /* connection terminated */
213       }
214       Dmsg1(199, "<dird: %s\n", bs->msg);
215       /* Ensure that device initialization is complete */
216       while (!init_done) {
217          bmicrosleep(1, 0);
218       }
219       found = false;
220       for (i=0; cmds[i].cmd; i++) {
221         if (strncmp(cmds[i].cmd, bs->msg, strlen(cmds[i].cmd)) == 0) {
222            if ((!cmds[i].monitoraccess) && (jcr->director->monitor)) {
223               Dmsg1(100, "Command \"%s\" is invalid.\n", cmds[i].cmd);
224               bs->fsend(invalid_cmd);
225               bs->signal(BNET_EOD);
226               break;
227            }
228            Dmsg1(200, "Do command: %s\n", cmds[i].cmd);
229            if (!cmds[i].func(jcr)) { /* do command */
230               quit = true; /* error, get out */
231               Dmsg1(190, "Command %s reqeusts quit\n", cmds[i].cmd);
232            }
233            found = true;             /* indicate command found */
234            break;
235         }
236       }
237       if (!found) {                   /* command not found */
238         bs->fsend(derrmsg);
239         break;
240       }
241    }
242 bail_out:
243    generate_daemon_event(jcr, "JobEnd");
244    dequeue_messages(jcr);             /* send any queued messages */
245    bs->signal(BNET_TERMINATE);
246    free_jcr(jcr);
247    return NULL;
248 }
249
250
251 /*
252  * Force SD to die, and hopefully dump itself.  Turned on only
253  *  in development version.
254  */
255 static bool die_cmd(JCR *jcr)
256 {
257 #ifdef DEVELOPER
258    JCR *djcr = NULL;
259    int a;
260    Pmsg0(000, "I have been requested to die ...");
261    a = djcr->JobId;   /* ref NULL pointer */
262 #endif
263    return 0;
264 }
265
266      
267
268 /*
269  * Set debug level as requested by the Director
270  *
271  */
272 static bool setdebug_cmd(JCR *jcr)
273 {
274    BSOCK *dir = jcr->dir_bsock;
275    int level, trace_flag;
276
277    Dmsg1(10, "setdebug_cmd: %s", dir->msg);
278    if (sscanf(dir->msg, "setdebug=%d trace=%d", &level, &trace_flag) != 2 || level < 0) {
279       dir->fsend(_("3991 Bad setdebug command: %s\n"), dir->msg);
280       return 0;
281    }
282    debug_level = level;
283    set_trace(trace_flag);
284    return dir->fsend(OKsetdebug, level);
285 }
286
287
288 /*
289  * Cancel a Job
290  */
291 static bool cancel_cmd(JCR *cjcr)
292 {
293    BSOCK *dir = cjcr->dir_bsock;
294    int oldStatus;
295    char Job[MAX_NAME_LENGTH];
296    JCR *jcr;
297
298    if (sscanf(dir->msg, "cancel Job=%127s", Job) == 1) {
299       if (!(jcr=get_jcr_by_full_name(Job))) {
300          dir->fsend(_("3904 Job %s not found.\n"), Job);
301       } else {
302          oldStatus = jcr->JobStatus;
303          set_jcr_job_status(jcr, JS_Canceled);
304          if (!jcr->authenticated && oldStatus == JS_WaitFD) {
305             pthread_cond_signal(&jcr->job_start_wait); /* wake waiting thread */
306          }
307          if (jcr->file_bsock) {
308             bnet_sig(jcr->file_bsock, BNET_TERMINATE);
309          } else {
310             /* Still waiting for FD to connect, release it */
311             pthread_cond_signal(&jcr->job_start_wait); /* wake waiting job */
312          }
313          /* If thread waiting on mount, wake him */
314          if (jcr->dcr && jcr->dcr->dev && jcr->dcr->dev->waiting_for_mount()) {
315             pthread_cond_broadcast(&jcr->dcr->dev->wait_next_vol);
316             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
317             pthread_cond_broadcast(&wait_device_release);
318          }
319          if (jcr->read_dcr && jcr->read_dcr->dev && jcr->read_dcr->dev->waiting_for_mount()) {
320             pthread_cond_broadcast(&jcr->read_dcr->dev->wait_next_vol);
321             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
322             pthread_cond_broadcast(&wait_device_release);
323          }
324          Jmsg(jcr, M_INFO, 0, _("Job %s marked to be canceled.\n"), jcr->Job);
325          dir->fsend(_("3000 Job %s marked to be canceled.\n"), jcr->Job);
326          free_jcr(jcr);
327       }
328    } else {
329       dir->fsend(_("3903 Error scanning cancel command.\n"));
330    }
331    dir->signal(BNET_EOD);
332    return 1;
333 }
334
335 /*
336  * Label a Volume
337  *
338  */
339 static bool label_cmd(JCR *jcr)
340 {
341    return do_label(jcr, 0);
342 }
343
344 static bool relabel_cmd(JCR *jcr)
345 {
346    return do_label(jcr, 1);
347 }
348
349 static bool do_label(JCR *jcr, int relabel)
350 {
351    POOLMEM *newname, *oldname, *poolname, *mtype;
352    POOL_MEM dev_name;
353    BSOCK *dir = jcr->dir_bsock;
354    DCR *dcr;
355    DEVICE *dev;
356    bool ok = false;
357    int slot;
358    int drive;
359
360    newname = get_memory(dir->msglen+1);
361    oldname = get_memory(dir->msglen+1);
362    poolname = get_memory(dir->msglen+1);
363    mtype = get_memory(dir->msglen+1);
364    if (relabel) {
365       if (sscanf(dir->msg, "relabel %127s OldName=%127s NewName=%127s PoolName=%127s "
366                  "MediaType=%127s Slot=%d drive=%d",
367                   dev_name.c_str(), oldname, newname, poolname, mtype, 
368                   &slot, &drive) == 7) {
369          ok = true;
370       }
371    } else {
372       *oldname = 0;
373       if (sscanf(dir->msg, "label %127s VolumeName=%127s PoolName=%127s "
374                  "MediaType=%127s Slot=%d drive=%d", 
375           dev_name.c_str(), newname, poolname, mtype, &slot, &drive) == 6) {
376          ok = true;
377       }
378    }
379    if (ok) {
380       unbash_spaces(newname);
381       unbash_spaces(oldname);
382       unbash_spaces(poolname);
383       unbash_spaces(mtype);
384       dcr = find_device(jcr, dev_name, drive);
385       if (dcr) {
386          dev = dcr->dev;
387          dev->dlock();                 /* Use P to avoid indefinite block */
388          if (!dev->is_open()) {
389             Dmsg1(400, "Can %slabel. Device is not open\n", relabel?"re":"");
390             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
391             dev->close();
392          /* Under certain "safe" conditions, we can steal the lock */
393          } else if (dev->can_steal_lock()) {
394             Dmsg0(400, "Can relabel. can_steal_lock\n");
395             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
396          } else if (dev->is_busy() || dev->is_blocked()) {
397             send_dir_busy_message(dir, dev);
398          } else {                     /* device not being used */
399             Dmsg0(400, "Can relabel. device not used\n");
400             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
401          }
402          dev->dunlock();
403          free_dcr(dcr);
404       } else {
405          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), dev_name.c_str());
406       }
407    } else {
408       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
409       pm_strcpy(jcr->errmsg, dir->msg);
410       dir->fsend(_("3903 Error scanning label command: %s\n"), jcr->errmsg);
411    }
412    free_memory(oldname);
413    free_memory(newname);
414    free_memory(poolname);
415    free_memory(mtype);
416    dir->signal(BNET_EOD);
417    return true;
418 }
419
420 /*
421  * Read the tape label and determine if we can safely
422  * label the tape (not a Bacula volume), then label it.
423  *
424  *  Enter with the mutex set
425  */
426 static void label_volume_if_ok(DCR *dcr, char *oldname,
427                                char *newname, char *poolname,
428                                int slot, int relabel)
429 {
430    BSOCK *dir = dcr->jcr->dir_bsock;
431    bsteal_lock_t hold;
432    DEVICE *dev = dcr->dev;
433    int label_status;
434    int mode;
435    const char *volname = (relabel == 1) ? oldname : newname;
436    char ed1[50];
437
438    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
439    Dmsg1(100, "Stole device %s lock, writing label.\n", dev->print_name());
440
441
442    Dmsg0(90, "try_autoload_device - looking for volume_info\n");
443    if (!try_autoload_device(dcr->jcr, dcr, slot, volname)) {
444       goto bail_out;                  /* error */
445    }
446
447    /* Ensure that the device is open -- autoload_device() closes it */
448    if (dev->is_tape()) {
449       mode = OPEN_READ_WRITE;
450    } else {
451       mode = CREATE_READ_WRITE;
452    }
453
454    if (relabel) {
455       dev->truncating = true;         /* let open() know we will truncate it */
456    }
457    /* Set old volume name for open if relabeling */
458    bstrncpy(dcr->VolCatInfo.VolCatName, volname, sizeof(dcr->VolCatInfo.VolCatName));
459    if (dev->open(dcr, mode) < 0) {
460       dir->fsend(_("3910 Unable to open device %s: ERR=%s\n"),
461          dev->print_name(), dev->bstrerror());
462       goto bail_out;      
463    }
464
465    /* See what we have for a Volume */
466    label_status = read_dev_volume_label(dcr);
467    
468    /* Set new volume name */
469    bstrncpy(dcr->VolCatInfo.VolCatName, newname, sizeof(dcr->VolCatInfo.VolCatName));
470    switch(label_status) {
471    case VOL_NAME_ERROR:
472    case VOL_VERSION_ERROR:
473    case VOL_LABEL_ERROR:
474    case VOL_OK:
475       if (!relabel) {
476          dir->fsend(_(
477             "3920 Cannot label Volume because it is already labeled: \"%s\"\n"),
478              dev->VolHdr.VolumeName);
479          break;
480       }
481
482       /* Relabel request. If oldname matches, continue */
483       if (strcmp(oldname, dev->VolHdr.VolumeName) != 0) {
484          dir->fsend(_("3921 Wrong volume mounted.\n"));
485          break;
486       }
487       if (dev->label_type != B_BACULA_LABEL) {
488          dir->fsend(_("3922 Cannot relabel an ANSI/IBM labeled Volume.\n"));
489          break;
490       }
491       /* Fall through wanted! */
492    case VOL_IO_ERROR:
493    case VOL_NO_LABEL:
494       if (!write_new_volume_label_to_dev(dcr, newname, poolname, 
495            relabel, true /* write dvd now */)) {
496          dir->fsend(_("3912 Failed to label Volume: ERR=%s\n"), dev->bstrerror());
497          break;
498       }
499       bstrncpy(dcr->VolumeName, newname, sizeof(dcr->VolumeName));
500       /* The following 3000 OK label. string is scanned in ua_label.c */
501       dir->fsend("3000 OK label. VolBytes=%s DVD=%d Volume=\"%s\" Device=%s\n",
502                  edit_uint64(dev->VolCatInfo.VolCatBytes, ed1),
503                  dev->is_dvd()?1:0, newname, dev->print_name());
504       break;
505    case VOL_NO_MEDIA:
506       dir->fsend(_("3914 Failed to label Volume (no media): ERR=%s\n"), dev->bstrerror());
507       break;
508    default:
509       dir->fsend(_("3913 Cannot label Volume. "
510 "Unknown status %d from read_volume_label()\n"), label_status);
511       break;
512    }
513
514 bail_out:
515    if (!dev->is_open()) {
516       dev->clear_volhdr();
517    }
518    volume_unused(dcr);                   /* no longer using volume */
519    give_back_device_lock(dev, &hold);
520    return;
521 }
522
523
524 /*
525  * Read the tape label
526  *
527  *  Enter with the mutex set
528  */
529 static bool read_label(DCR *dcr)
530 {
531    int ok;
532    JCR *jcr = dcr->jcr;
533    BSOCK *dir = jcr->dir_bsock;
534    bsteal_lock_t hold;
535    DEVICE *dev = dcr->dev;
536
537    steal_device_lock(dev, &hold, BST_DOING_ACQUIRE);
538
539    dcr->VolumeName[0] = 0;
540    dev->clear_labeled();              /* force read of label */
541    switch (read_dev_volume_label(dcr)) {
542    case VOL_OK:
543       dir->fsend(_("3001 Mounted Volume: %s\n"), dev->VolHdr.VolumeName);
544       ok = true;
545       break;
546    default:
547       dir->fsend(_("3902 Cannot mount Volume on Storage Device %s because:\n%s"),
548          dev->print_name(), jcr->errmsg);
549       ok = false;
550       break;
551    }
552    volume_unused(dcr);
553    give_back_device_lock(dev, &hold);
554    return ok;
555 }
556
557 /* 
558  * Searches for device by name, and if found, creates a dcr and
559  *  returns it.
560  */
561 static DCR *find_device(JCR *jcr, POOL_MEM &devname, int drive)
562 {
563    DEVRES *device;
564    AUTOCHANGER *changer;
565    bool found = false;
566    DCR *dcr = NULL;
567
568    unbash_spaces(devname);
569    foreach_res(device, R_DEVICE) {
570       /* Find resource, and make sure we were able to open it */
571       if (strcmp(device->hdr.name, devname.c_str()) == 0) {
572          if (!device->dev) {
573             device->dev = init_dev(jcr, device);
574          }
575          if (!device->dev) {
576             Jmsg(jcr, M_WARNING, 0, _("\n"
577                "     Device \"%s\" requested by DIR could not be opened or does not exist.\n"),
578                  devname.c_str());
579             continue;
580          }
581          Dmsg1(20, "Found device %s\n", device->hdr.name);
582          found = true;
583          break;
584       }
585    }
586    if (!found) {
587       foreach_res(changer, R_AUTOCHANGER) {
588          /* Find resource, and make sure we were able to open it */
589          if (strcmp(devname.c_str(), changer->hdr.name) == 0) {
590             /* Try each device in this AutoChanger */
591             foreach_alist(device, changer->device) {
592                Dmsg1(100, "Try changer device %s\n", device->hdr.name);
593                if (!device->dev) {
594                   device->dev = init_dev(jcr, device);
595                }
596                if (!device->dev) {
597                   Dmsg1(100, "Device %s could not be opened. Skipped\n", devname.c_str());
598                   Jmsg(jcr, M_WARNING, 0, _("\n"
599                      "     Device \"%s\" in changer \"%s\" requested by DIR could not be opened or does not exist.\n"),
600                        device->hdr.name, devname.c_str());
601                   continue;
602                }
603                if (!device->dev->autoselect) {
604                   Dmsg1(100, "Device %s not autoselect skipped.\n", devname.c_str());
605                   continue;              /* device is not available */
606                }
607                if (drive < 0 || drive == (int)device->dev->drive_index) {
608                   Dmsg1(20, "Found changer device %s\n", device->hdr.name);
609                   found = true;
610                   break;
611                }
612                Dmsg3(100, "Device %s drive wrong: want=%d got=%d skipping\n",
613                   devname.c_str(), drive, (int)device->dev->drive_index);
614             }
615             break;                    /* we found it but could not open a device */
616          }
617       }
618    }
619
620    if (found) {
621       Dmsg1(100, "Found device %s\n", device->hdr.name);
622       dcr = new_dcr(jcr, NULL, device->dev);
623       dcr->device = device;
624    }
625    return dcr;
626 }
627
628
629 /*
630  * Mount command from Director
631  */
632 static bool mount_cmd(JCR *jcr)
633 {
634    POOL_MEM devname;
635    BSOCK *dir = jcr->dir_bsock;
636    DEVICE *dev;
637    DCR *dcr;
638    int drive;
639    int slot = 0;
640    bool ok;
641
642    ok = sscanf(dir->msg, "mount %127s drive=%d slot=%d", devname.c_str(), 
643                &drive, &slot) == 3;
644    if (!ok) {
645       ok = sscanf(dir->msg, "mount %127s drive=%d", devname.c_str(), &drive) == 2;
646    }
647    if (ok) {
648       dcr = find_device(jcr, devname, drive);
649       if (dcr) {
650          dev = dcr->dev;
651          dev->dlock();                 /* Use P to avoid indefinite block */
652          Dmsg1(100, "mount cmd blocked=%d\n", dev->blocked());
653          switch (dev->blocked()) {         /* device blocked? */
654          case BST_WAITING_FOR_SYSOP:
655             /* Someone is waiting, wake him */
656             Dmsg0(100, "Waiting for mount. Attempting to wake thread\n");
657             dev->set_blocked(BST_MOUNT);
658             dir->fsend("3001 OK mount. Device=%s\n", 
659                dev->print_name());
660             pthread_cond_broadcast(&dev->wait_next_vol);
661             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
662             pthread_cond_broadcast(&wait_device_release);
663             break;
664
665          /* In both of these two cases, we (the user) unmounted the Volume */
666          case BST_UNMOUNTED_WAITING_FOR_SYSOP:
667          case BST_UNMOUNTED:
668             if (dev->is_autochanger() && slot > 0) {
669                try_autoload_device(jcr, dcr, slot, "");
670             }
671             /* We freed the device, so reopen it and wake any waiting threads */
672             if (dev->open(dcr, OPEN_READ_ONLY) < 0) {
673                dir->fsend(_("3901 open device failed: ERR=%s\n"),
674                   dev->bstrerror());
675                if (dev->blocked() == BST_UNMOUNTED) {
676                   /* We blocked the device, so unblock it */
677                   Dmsg0(100, "Unmounted. Unblocking device\n");
678                   unblock_device(dev);
679                }
680                break;
681             }
682             read_dev_volume_label(dcr);
683             if (dev->blocked() == BST_UNMOUNTED) {
684                /* We blocked the device, so unblock it */
685                Dmsg0(100, "Unmounted. Unblocking device\n");
686                read_label(dcr);       /* this should not be necessary */
687                unblock_device(dev);
688             } else {
689                Dmsg0(100, "Unmounted waiting for mount. Attempting to wake thread\n");
690                dev->set_blocked(BST_MOUNT);
691             }
692             if (dev->is_labeled()) {
693                dir->fsend(_("3001 Device %s is mounted with Volume \"%s\"\n"),
694                   dev->print_name(), dev->VolHdr.VolumeName);
695             } else {
696                dir->fsend(_("3905 Device %s open but no Bacula volume is mounted.\n"
697                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
698                           dev->print_name());
699             }
700             pthread_cond_broadcast(&dev->wait_next_vol);
701             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
702             pthread_cond_broadcast(&wait_device_release);
703             break;
704
705          case BST_DOING_ACQUIRE:
706             dir->fsend(_("3001 Device %s is doing acquire.\n"),
707                        dev->print_name());
708             break;
709
710          case BST_WRITING_LABEL:
711             dir->fsend(_("3903 Device %s is being labeled.\n"), 
712                dev->print_name());
713             break;
714
715          case BST_NOT_BLOCKED:
716             if (dev->is_autochanger() && slot > 0) {
717                try_autoload_device(jcr, dcr, slot, "");
718             }
719             if (dev->is_open()) {
720                if (dev->is_labeled()) {
721                   dir->fsend(_("3001 Device %s is mounted with Volume \"%s\"\n"),
722                      dev->print_name(), dev->VolHdr.VolumeName);
723                } else {
724                   dir->fsend(_("3905 Device %s open but no Bacula volume is mounted.\n"
725                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
726                              dev->print_name());
727                }
728             } else if (dev->is_tape()) {
729                if (dev->open(dcr, OPEN_READ_ONLY) < 0) {
730                   dir->fsend(_("3901 open device failed: ERR=%s\n"),
731                      dev->bstrerror());
732                   break;
733                }
734                read_label(dcr);
735                if (dev->is_labeled()) {
736                   dir->fsend(_("3001 Device %s is already mounted with Volume \"%s\"\n"),
737                      dev->print_name(), dev->VolHdr.VolumeName);
738                } else {
739                   dir->fsend(_("3905 Device %s open but no Bacula volume is mounted.\n"
740                                     "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
741                              dev->print_name());
742                }
743             } else if (dev->is_unmountable()) {
744                if (dev->mount(1)) {
745                   dir->fsend(_("3002 Device %s is mounted.\n"), 
746                      dev->print_name());
747                } else {
748                   dir->fsend(_("3907 %s"), dev->bstrerror());
749                } 
750             } else { /* must be file */
751                dir->fsend(_("3906 File device %s is always mounted.\n"),
752                   dev->print_name());
753             }
754             break;
755
756          default:
757             dir->fsend(_("3905 Bizarre wait state %d\n"), dev->blocked());
758             break;
759          }
760          dev->dunlock();
761          free_dcr(dcr);
762       } else {
763          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
764       }
765    } else {
766       pm_strcpy(jcr->errmsg, dir->msg);
767       dir->fsend(_("3909 Error scanning mount command: %s\n"), jcr->errmsg);
768    }
769    dir->signal(BNET_EOD);
770    return true;
771 }
772
773 /*
774  * unmount command from Director
775  */
776 static bool unmount_cmd(JCR *jcr)
777 {
778    POOL_MEM devname;
779    BSOCK *dir = jcr->dir_bsock;
780    DEVICE *dev;
781    DCR *dcr;
782    int drive;
783
784    if (sscanf(dir->msg, "unmount %127s drive=%d", devname.c_str(), &drive) == 2) {
785       dcr = find_device(jcr, devname, drive);
786       if (dcr) {
787          dev = dcr->dev;
788          dev->dlock();                 /* Use P to avoid indefinite block */
789          if (!dev->is_open()) {
790             if (!dev->is_busy()) {
791                unload_autochanger(dcr, -1);          
792             }
793             if (dev->is_unmountable()) {
794                if (dev->unmount(0)) {
795                   dir->fsend(_("3002 Device %s unmounted.\n"), 
796                      dev->print_name());
797                } else {
798                   dir->fsend(_("3907 %s"), dev->bstrerror());
799                } 
800             } else {
801                Dmsg0(90, "Device already unmounted\n");
802                dir->fsend(_("3901 Device %s is already unmounted.\n"), 
803                   dev->print_name());
804             }
805          } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
806             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
807                dev->blocked());
808             if (!unload_autochanger(dcr, -1)) {
809                /* ***FIXME**** what is this ????  */
810                dev->close();
811             }
812             if (dev->is_unmountable() && !dev->unmount(0)) {
813                dir->fsend(_("3907 %s"), dev->bstrerror());
814             } else {
815                dev->set_blocked(BST_UNMOUNTED_WAITING_FOR_SYSOP);
816                dir->fsend(_("3001 Device %s unmounted.\n"), 
817                   dev->print_name());
818             }
819
820          } else if (dev->blocked() == BST_DOING_ACQUIRE) {
821             dir->fsend(_("3902 Device %s is busy in acquire.\n"), 
822                dev->print_name());
823
824          } else if (dev->blocked() == BST_WRITING_LABEL) {
825             dir->fsend(_("3903 Device %s is being labeled.\n"), 
826                dev->print_name());
827
828          } else if (dev->is_busy()) {
829             send_dir_busy_message(dir, dev);
830          } else {                     /* device not being used */
831             Dmsg0(90, "Device not in use, unmounting\n");
832             /* On FreeBSD, I am having ASSERT() failures in block_device()
833              * and I can only imagine that the thread id that we are
834              * leaving in no_wait_id is being re-used. So here,
835              * we simply do it by hand.  Gross, but a solution.
836              */
837             /*  block_device(dev, BST_UNMOUNTED); replace with 2 lines below */
838             dev->set_blocked(BST_UNMOUNTED);
839             dev->no_wait_id = 0;
840             if (!unload_autochanger(dcr, -1)) {
841                dev->close();
842             }
843             if (dev->is_unmountable() && !dev->unmount(0)) {
844                dir->fsend(_("3907 %s"), dev->bstrerror());
845             } else {
846                dir->fsend(_("3002 Device %s unmounted.\n"), 
847                   dev->print_name());
848             }
849          }
850          dev->dunlock();
851          free_dcr(dcr);
852       } else {
853          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
854       }
855    } else {
856       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
857       pm_strcpy(jcr->errmsg, dir->msg);
858       dir->fsend(_("3907 Error scanning unmount command: %s\n"), jcr->errmsg);
859    }
860    dir->signal(BNET_EOD);
861    return true;
862 }
863
864 /*
865  * Release command from Director. This rewinds the device and if
866  *   configured does a offline and ensures that Bacula will
867  *   re-read the label of the tape before continuing. This gives
868  *   the operator the chance to change the tape anytime before the
869  *   next job starts.
870  */
871 static bool release_cmd(JCR *jcr)
872 {
873    POOL_MEM devname;
874    BSOCK *dir = jcr->dir_bsock;
875    DEVICE *dev;
876    DCR *dcr;
877    int drive;
878
879    if (sscanf(dir->msg, "release %127s drive=%d", devname.c_str(), &drive) == 2) {
880       dcr = find_device(jcr, devname, drive);
881       if (dcr) {
882          dev = dcr->dev;
883          dev->dlock();                 /* Use P to avoid indefinite block */
884          if (!dev->is_open()) {
885             if (!dev->is_busy()) {
886                unload_autochanger(dcr, -1);
887             }
888             Dmsg0(90, "Device already released\n");
889             dir->fsend(_("3921 Device %s already released.\n"), 
890                dev->print_name());
891
892          } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
893             Dmsg2(90, "%d waiter dev_block=%d.\n", dev->num_waiting,
894                dev->blocked());
895             unload_autochanger(dcr, -1);
896             dir->fsend(_("3922 Device %s waiting for sysop.\n"), 
897                dev->print_name());
898
899          } else if (dev->blocked() == BST_UNMOUNTED_WAITING_FOR_SYSOP) {
900             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
901                dev->blocked());
902             dir->fsend(_("3922 Device %s waiting for mount.\n"), 
903                dev->print_name());
904
905          } else if (dev->blocked() == BST_DOING_ACQUIRE) {
906             dir->fsend(_("3923 Device %s is busy in acquire.\n"), 
907                dev->print_name());
908
909          } else if (dev->blocked() == BST_WRITING_LABEL) {
910             dir->fsend(_("3914 Device %s is being labeled.\n"), 
911                dev->print_name());
912
913          } else if (dev->is_busy()) {
914             send_dir_busy_message(dir, dev);
915          } else {                     /* device not being used */
916             Dmsg0(90, "Device not in use, releaseing\n");
917             unload_autochanger(dcr, -1);
918             release_volume(dcr);
919             dir->fsend(_("3022 Device %s released.\n"), 
920                dev->print_name());
921          }
922          dev->dunlock();
923          free_dcr(dcr);
924       } else {
925          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
926       }
927    } else {
928       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
929       pm_strcpy(jcr->errmsg, dir->msg);
930       dir->fsend(_("3927 Error scanning release command: %s\n"), jcr->errmsg);
931    }
932    dir->signal(BNET_EOD);
933    return true;
934 }
935
936
937 static bool bootstrap_cmd(JCR *jcr)
938 {
939    return get_bootstrap_file(jcr, jcr->dir_bsock);
940 }
941
942 /*
943  * Autochanger command from Director
944  */
945 static bool changer_cmd(JCR *jcr)
946 {
947    POOL_MEM devname;
948    BSOCK *dir = jcr->dir_bsock;
949    DEVICE *dev;
950    DCR *dcr;
951    const char *cmd = NULL;
952    bool ok = false;
953    /*
954     * A safe_cmd may call autochanger script but does not load/unload
955     *    slots so it can be done at the same time that the drive is open.
956     */
957    bool safe_cmd = false;
958
959    if (sscanf(dir->msg, "autochanger list %127s", devname.c_str()) == 1) {
960       cmd = "list";
961       safe_cmd = ok = true;
962    } else if (sscanf(dir->msg, "autochanger slots %127s", devname.c_str()) == 1) {
963       cmd = "slots";
964       safe_cmd = ok = true;
965    } else if (sscanf(dir->msg, "autochanger drives %127s", devname.c_str()) == 1) {
966       cmd = "drives";
967       safe_cmd = ok = true;
968    }
969    if (ok) {
970       dcr = find_device(jcr, devname, -1);
971       if (dcr) {
972          dev = dcr->dev;
973          dev->dlock();                 /* Use P to avoid indefinite block */
974          if (!dev->device->changer_res) {
975             dir->fsend(_("3995 Device %s is not an autochanger.\n"), 
976                dev->print_name());
977          /* Under certain "safe" conditions, we can steal the lock */
978          } else if (safe_cmd || !dev->is_open() || dev->can_steal_lock()) {
979             autochanger_cmd(dcr, dir, cmd);
980          } else if (dev->is_busy() || dev->is_blocked()) {
981             send_dir_busy_message(dir, dev);
982          } else {                     /* device not being used */
983             autochanger_cmd(dcr, dir, cmd);
984          }
985          dev->dunlock();
986          free_dcr(dcr);
987       } else {
988          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
989       }
990    } else {  /* error on scanf */
991       pm_strcpy(jcr->errmsg, dir->msg);
992       dir->fsend(_("3908 Error scanning autocharger drives/list/slots command: %s\n"),
993          jcr->errmsg);
994    }
995    dir->signal(BNET_EOD);
996    return true;
997 }
998
999 /*
1000  * Read and return the Volume label
1001  */
1002 static bool readlabel_cmd(JCR *jcr)
1003 {
1004    POOL_MEM devname;
1005    BSOCK *dir = jcr->dir_bsock;
1006    DEVICE *dev;
1007    DCR *dcr;
1008    int Slot;
1009    int drive;
1010
1011    if (sscanf(dir->msg, "readlabel %127s Slot=%d drive=%d", devname.c_str(), 
1012        &Slot, &drive) == 3) {
1013       dcr = find_device(jcr, devname, drive);
1014       if (dcr) {
1015          dev = dcr->dev;
1016          dev->dlock();                 /* Use P to avoid indefinite block */
1017          if (!dev->is_open()) {
1018             read_volume_label(jcr, dcr, dev, Slot);
1019             dev->close();
1020          /* Under certain "safe" conditions, we can steal the lock */
1021          } else if (dev->can_steal_lock()) {
1022             read_volume_label(jcr, dcr, dev, Slot);
1023          } else if (dev->is_busy() || dev->is_blocked()) {
1024             send_dir_busy_message(dir, dev);
1025          } else {                     /* device not being used */
1026             read_volume_label(jcr, dcr, dev, Slot);
1027          }
1028          dev->dunlock();
1029          free_dcr(dcr);
1030       } else {
1031          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1032       }
1033    } else {
1034       pm_strcpy(jcr->errmsg, dir->msg);
1035       dir->fsend(_("3909 Error scanning readlabel command: %s\n"), jcr->errmsg);
1036    }
1037    dir->signal(BNET_EOD);
1038    return true;
1039 }
1040
1041
1042 /*
1043  * Read the tape label
1044  *
1045  *  Enter with the mutex set
1046  */
1047 static void read_volume_label(JCR *jcr, DCR *dcr, DEVICE *dev, int Slot)
1048 {
1049    BSOCK *dir = jcr->dir_bsock;
1050    bsteal_lock_t hold;
1051
1052    dcr->dev = dev;
1053    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
1054
1055    if (!try_autoload_device(jcr, dcr, Slot, "")) {
1056       goto bail_out;                  /* error */
1057    }
1058
1059    dev->clear_labeled();              /* force read of label */
1060    switch (read_dev_volume_label(dcr)) {
1061    case VOL_OK:
1062       /* DO NOT add quotes around the Volume name. It is scanned in the DIR */
1063       dir->fsend(_("3001 Volume=%s Slot=%d\n"), dev->VolHdr.VolumeName, Slot);
1064       Dmsg1(100, "Volume: %s\n", dev->VolHdr.VolumeName);
1065       break;
1066    default:
1067       dir->fsend(_("3902 Cannot mount Volume on Storage Device %s because:\n%s"),
1068                  dev->print_name(), jcr->errmsg);
1069       break;
1070    }
1071
1072 bail_out:
1073    give_back_device_lock(dev, &hold);
1074    return;
1075 }
1076
1077 static bool try_autoload_device(JCR *jcr, DCR *dcr, int slot, const char *VolName)
1078 {
1079    BSOCK *dir = jcr->dir_bsock;
1080
1081    bstrncpy(dcr->VolumeName, VolName, sizeof(dcr->VolumeName));
1082    dcr->VolCatInfo.Slot = slot;
1083    dcr->VolCatInfo.InChanger = slot > 0;
1084    if (autoload_device(dcr, 0, dir) < 0) {    /* autoload if possible */
1085       return false;
1086    }
1087    return true;
1088 }
1089
1090 static void send_dir_busy_message(BSOCK *dir, DEVICE *dev)
1091 {
1092    if (dev->is_blocked()) {
1093       switch (dev->blocked()) {
1094       case BST_UNMOUNTED:
1095          dir->fsend(_("3931 Device %s is BLOCKED. user unmounted.\n"),
1096             dev->print_name());
1097          break;
1098       case BST_UNMOUNTED_WAITING_FOR_SYSOP:
1099          dir->fsend(_("3932 Device %s is BLOCKED. user unmounted during wait for media/mount.\n"),
1100              dev->print_name());
1101          break;
1102       case BST_WAITING_FOR_SYSOP:
1103          dir->fsend(_("3933 Device %s is BLOCKED waiting for media.\n"),
1104             dev->print_name());
1105          break;
1106       case BST_DOING_ACQUIRE:
1107          dir->fsend(_("3934 Device %s is being initialized.\n"),
1108             dev->print_name());
1109          break;
1110       case BST_WRITING_LABEL:
1111          dir->fsend(_("3935 Device %s is blocked labeling a Volume.\n"),
1112             dev->print_name());
1113          break;
1114       default:
1115          dir->fsend(_("3935 Device %s is blocked for unknown reason.\n"),
1116             dev->print_name());
1117          break;
1118       }
1119    } else if (dev->can_read()) {
1120        dir->fsend(_("3936 Device %s is busy reading.\n"),
1121                    dev->print_name());;
1122    } else {
1123        dir->fsend(_("3937 Device %s is busy with %d writer(s).\n"),
1124           dev->print_name(), dev->num_writers);
1125    }
1126 }