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