]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dircmd.c
12c67cb156946e1ee5b9fb17e93454a9e0df7dfa
[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. In some "safe" cases,
12  *      we can do things to a blocked device. CAREFUL!!!!
13  *
14  *    File daemon commands are handled in fdcmd.c
15  *
16  *     Kern Sibbald, May MMI
17  *
18  *   Version $Id$
19  *
20  */
21 /*
22    Copyright (C) 2001-2005 Kern Sibbald
23
24    This program is free software; you can redistribute it and/or
25    modify it under the terms of the GNU General Public License as
26    published by the Free Software Foundation; either version 2 of
27    the License, or (at your option) any later version.
28
29    This program is distributed in the hope that it will be useful,
30    but WITHOUT ANY WARRANTY; without even the implied warranty of
31    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
32    General Public License for more details.
33
34    You should have received a copy of the GNU General Public
35    License along with this program; if not, write to the Free
36    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
37    MA 02111-1307, USA.
38
39  */
40
41 #include "bacula.h"
42 #include "stored.h"
43
44 /* Exported variables */
45
46 /* Imported variables */
47 extern BSOCK *filed_chan;
48 extern int r_first, r_last;
49 extern struct s_res resources[];
50 extern char my_name[];
51 extern time_t daemon_start_time;
52 extern struct s_last_job last_job;
53
54 /* Static variables */
55 static char derrmsg[]       = "3900 Invalid command\n";
56 static char OKsetdebug[]   = "3000 OK setdebug=%d\n";
57 static char illegal_cmd[] = "3997 Illegal command for a Director with Monitor directive enabled\n";
58
59 /* Imported functions */
60 extern void terminate_child();
61 extern bool job_cmd(JCR *jcr);
62 extern bool status_cmd(JCR *sjcr);
63 extern bool qstatus_cmd(JCR *jcr);
64
65 /* Forward referenced functions */
66 static bool label_cmd(JCR *jcr);
67 static bool relabel_cmd(JCR *jcr);
68 static bool readlabel_cmd(JCR *jcr);
69 static bool release_cmd(JCR *jcr);
70 static bool setdebug_cmd(JCR *jcr);
71 static bool cancel_cmd(JCR *cjcr);
72 static bool mount_cmd(JCR *jcr);
73 static bool unmount_cmd(JCR *jcr);
74 static bool autochanger_cmd(JCR *sjcr);
75 static bool do_label(JCR *jcr, int relabel);
76 static DEVICE *find_device(JCR *jcr, POOL_MEM &dname);
77 static void read_volume_label(JCR *jcr, DEVICE *dev, int Slot);
78 static void label_volume_if_ok(JCR *jcr, DEVICE *dev, char *oldname,
79                                char *newname, char *poolname,
80                                int Slot, int relabel);
81 static bool try_autoload_device(JCR *jcr, int slot, const char *VolName);
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", autochanger_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    {NULL,        NULL}                      /* list terminator */
107 };
108
109
110 /*
111  * Connection request. We accept connections either from the
112  *  Director or a Client (File daemon).
113  *
114  * Note, we are running as a seperate thread of the Storage daemon.
115  *  and it is because a Director has made a connection with
116  *  us on the "Message" channel.
117  *
118  * Basic tasks done here:
119  *  - Create a JCR record
120  *  - If it was from the FD, call handle_filed_connection()
121  *  - Authenticate the Director
122  *  - We wait for a command
123  *  - We execute the command
124  *  - We continue or exit depending on the return status
125  */
126 void *handle_connection_request(void *arg)
127 {
128    BSOCK *bs = (BSOCK *)arg;
129    JCR *jcr;
130    int i;
131    bool found, quit;
132    int bnet_stat = 0;
133    char name[MAX_NAME_LENGTH];
134
135    if (bnet_recv(bs) <= 0) {
136       Emsg0(M_ERROR, 0, _("Connection request failed.\n"));
137       bnet_close(bs);
138       return NULL;
139    }
140
141    /*
142     * Do a sanity check on the message received
143     */
144    if (bs->msglen < 25 || bs->msglen > (int)sizeof(name)-25) {
145       Emsg1(M_ERROR, 0, _("Invalid connection. Len=%d\n"), bs->msglen);
146       bnet_close(bs);
147       return NULL;
148    }
149    /*
150     * See if this is a File daemon connection. If so
151     *   call FD handler.
152     */
153    Dmsg1(110, "Conn: %s", bs->msg);
154    if (sscanf(bs->msg, "Hello Start Job %127s", name) == 1) {
155       handle_filed_connection(bs, name);
156       return NULL;
157    }
158
159    Dmsg0(110, "Start Dir Job\n");
160    jcr = new_jcr(sizeof(JCR), stored_free_jcr); /* create Job Control Record */
161    jcr->dir_bsock = bs;               /* save Director bsock */
162    jcr->dir_bsock->jcr = jcr;
163    /* Initialize FD start condition variable */
164    int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
165    if (errstat != 0) {
166       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), strerror(errstat));
167       goto bail_out;
168    }
169
170    Dmsg0(1000, "stored in start_job\n");
171
172    /*
173     * Authenticate the Director
174     */
175    if (!authenticate_director(jcr)) {
176       Jmsg(jcr, M_FATAL, 0, _("Unable to authenticate Director\n"));
177       goto bail_out;
178    }
179    Dmsg0(90, "Message channel init completed.\n");
180
181    for (quit=0; !quit;) {
182       /* Read command */
183       if ((bnet_stat = bnet_recv(bs)) <= 0) {
184          break;               /* connection terminated */
185       }
186       Dmsg1(199, "<dird: %s\n", bs->msg);
187       found = false;
188       for (i=0; cmds[i].cmd; i++) {
189         if (strncmp(cmds[i].cmd, bs->msg, strlen(cmds[i].cmd)) == 0) {
190            if ((!cmds[i].monitoraccess) && (jcr->director->monitor)) {
191               Dmsg1(100, "Command %s illegal.\n", cmds[i].cmd);
192               bnet_fsend(bs, illegal_cmd);
193               bnet_sig(bs, BNET_EOD);
194               break;
195            }
196            if (!cmds[i].func(jcr)) { /* do command */
197               quit = true; /* error, get out */
198               Dmsg1(190, "Command %s requsts quit\n", cmds[i].cmd);
199            }
200            found = true;             /* indicate command found */
201            break;
202         }
203       }
204       if (!found) {                   /* command not found */
205         bnet_fsend(bs, derrmsg);
206         break;
207       }
208    }
209 bail_out:
210    dequeue_messages(jcr);             /* send any queued messages */
211    bnet_sig(bs, BNET_TERMINATE);
212    free_jcr(jcr);
213    return NULL;
214 }
215
216 /*
217  * Set debug level as requested by the Director
218  *
219  */
220 static bool setdebug_cmd(JCR *jcr)
221 {
222    BSOCK *dir = jcr->dir_bsock;
223    int level, trace_flag;
224
225    Dmsg1(10, "setdebug_cmd: %s", dir->msg);
226    if (sscanf(dir->msg, "setdebug=%d trace=%d", &level, &trace_flag) != 2 || level < 0) {
227       bnet_fsend(dir, "3991 Bad setdebug command: %s\n", dir->msg);
228       return 0;
229    }
230    debug_level = level;
231    set_trace(trace_flag);
232    return bnet_fsend(dir, OKsetdebug, level);
233 }
234
235
236 /*
237  * Cancel a Job
238  */
239 static bool cancel_cmd(JCR *cjcr)
240 {
241    BSOCK *dir = cjcr->dir_bsock;
242    int oldStatus;
243    char Job[MAX_NAME_LENGTH];
244    JCR *jcr;
245
246    if (sscanf(dir->msg, "cancel Job=%127s", Job) == 1) {
247       if (!(jcr=get_jcr_by_full_name(Job))) {
248          bnet_fsend(dir, _("3992 Job %s not found.\n"), Job);
249       } else {
250          P(jcr->mutex);
251          oldStatus = jcr->JobStatus;
252          set_jcr_job_status(jcr, JS_Canceled);
253          if (!jcr->authenticated && oldStatus == JS_WaitFD) {
254             pthread_cond_signal(&jcr->job_start_wait); /* wake waiting thread */
255          }
256          V(jcr->mutex);
257          if (jcr->file_bsock) {
258             bnet_sig(jcr->file_bsock, BNET_TERMINATE);
259          }
260          /* If thread waiting on mount, wake him */
261          if (jcr->dcr && jcr->dcr->dev &&
262               (jcr->dcr->dev->dev_blocked == BST_WAITING_FOR_SYSOP ||
263                jcr->dcr->dev->dev_blocked == BST_UNMOUNTED ||
264                jcr->dcr->dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP)) {
265              pthread_cond_signal(&jcr->dcr->dev->wait_next_vol);
266          }
267          bnet_fsend(dir, _("3000 Job %s marked to be canceled.\n"), jcr->Job);
268          free_jcr(jcr);
269       }
270    } else {
271       bnet_fsend(dir, _("3993 Error scanning cancel command.\n"));
272    }
273    bnet_sig(dir, BNET_EOD);
274    return 1;
275 }
276
277 /*
278  * Label a tape
279  *
280  */
281 static bool label_cmd(JCR *jcr)
282 {
283    return do_label(jcr, 0);
284 }
285
286 static bool relabel_cmd(JCR *jcr)
287 {
288    return do_label(jcr, 1);
289 }
290
291 static bool do_label(JCR *jcr, int relabel)
292 {
293    POOLMEM *newname, *oldname, *poolname, *mtype;
294    POOL_MEM dname;
295    BSOCK *dir = jcr->dir_bsock;
296    DEVICE *dev;
297    bool ok = false;
298    int slot;
299
300    newname = get_memory(dir->msglen+1);
301    oldname = get_memory(dir->msglen+1);
302    poolname = get_memory(dir->msglen+1);
303    mtype = get_memory(dir->msglen+1);
304    if (relabel) {
305       if (sscanf(dir->msg, "relabel %127s OldName=%127s NewName=%127s PoolName=%127s MediaType=%127s Slot=%d",
306           dname.c_str(), oldname, newname, poolname, mtype, &slot) == 6) {
307          ok = true;
308       }
309    } else {
310       *oldname = 0;
311       if (sscanf(dir->msg, "label %127s VolumeName=%127s PoolName=%127s MediaType=%127s Slot=%d",
312           dname.c_str(), newname, poolname, mtype, &slot) == 5) {
313          ok = true;
314       }
315    }
316    if (ok) {
317       unbash_spaces(newname);
318       unbash_spaces(oldname);
319       unbash_spaces(poolname);
320       unbash_spaces(mtype);
321       dev = find_device(jcr, dname);
322       if (dev) {
323          /******FIXME**** compare MediaTypes */
324          P(dev->mutex);               /* Use P to avoid indefinite block */
325          if (!(dev->state & ST_OPENED)) {
326             label_volume_if_ok(jcr, dev, oldname, newname, poolname, slot, relabel);
327             force_close_dev(dev);
328          /* Under certain "safe" conditions, we can steal the lock */
329          } else if (dev->dev_blocked &&
330                     (dev->dev_blocked == BST_UNMOUNTED ||
331                      dev->dev_blocked == BST_WAITING_FOR_SYSOP ||
332                      dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP)) {
333             label_volume_if_ok(jcr, dev, oldname, newname, poolname, slot, relabel);
334          } else if (dev_state(dev, ST_READ) || dev->num_writers) {
335             if (dev_state(dev, ST_READ)) {
336                 bnet_fsend(dir, _("3911 Device %s is busy with 1 reader.\n"),
337                    dev_name(dev));
338             } else {
339                 bnet_fsend(dir, _("3912 Device %s is busy with %d writer(s).\n"),
340                    dev_name(dev), dev->num_writers);
341             }
342          } else {                     /* device not being used */
343             label_volume_if_ok(jcr, dev, oldname, newname, poolname, slot, relabel);
344          }
345          V(dev->mutex);
346       } else {
347          bnet_fsend(dir, _("3999 Device \"%s\" not found\n"), dname.c_str());
348       }
349    } else {
350       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
351       pm_strcpy(jcr->errmsg, dir->msg);
352       bnet_fsend(dir, _("3903 Error scanning label command: %s\n"), jcr->errmsg);
353    }
354    free_memory(oldname);
355    free_memory(newname);
356    free_memory(poolname);
357    free_memory(mtype);
358    bnet_sig(dir, BNET_EOD);
359    return true;
360 }
361
362 /*
363  * Read the tape label and determine if we can safely
364  * label the tape (not a Bacula volume), then label it.
365  *
366  *  Enter with the mutex set
367  */
368 static void label_volume_if_ok(JCR *jcr, DEVICE *dev, char *oldname,
369                                char *newname, char *poolname,
370                                int slot, int relabel)
371 {
372    BSOCK *dir = jcr->dir_bsock;
373    bsteal_lock_t hold;
374    DCR *dcr = jcr->dcr;
375    int label_status;
376
377    dcr->dev = dev;
378    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
379
380    if (!try_autoload_device(jcr, slot, newname)) {
381       goto bail_out;                  /* error */
382    }
383
384    /* See what we have for a Volume */
385    label_status = read_dev_volume_label(dcr);
386    
387    if (dev_cap(dev, CAP_REQMOUNT)) {
388       label_status = read_dev_volume_label_guess(dcr, 1);
389    }
390    else {
391       label_status = read_dev_volume_label(dcr);
392    }
393    
394    switch(label_status) {
395    case VOL_NAME_ERROR:
396    case VOL_VERSION_ERROR:
397    case VOL_LABEL_ERROR:
398    case VOL_OK:
399       if (!relabel) {
400          bnet_fsend(dir, _(
401             "3911 Cannot label Volume because it is already labeled: \"%s\"\n"),
402              dev->VolHdr.VolName);
403          break;
404       }
405       /* Relabel request. If oldname matches, continue */
406       if (strcmp(oldname, dev->VolHdr.VolName) != 0) {
407          bnet_fsend(dir, _("Wrong volume mounted.\n"));
408          break;
409       }
410       /* Fall through wanted! */
411    case VOL_IO_ERROR:
412    case VOL_NO_LABEL:
413       if (!write_new_volume_label_to_dev(dcr, newname, poolname)) {
414          bnet_fsend(dir, _("3912 Failed to label Volume: ERR=%s\n"), strerror_dev(dev));
415          break;
416       }
417       bstrncpy(dcr->VolumeName, newname, sizeof(dcr->VolumeName));
418       /* The following 3000 OK label. string is scanned in ua_label.c */
419       bnet_fsend(dir, "3000 OK label. Volume=%s Device=%s\n",
420          newname, dev_name(dev));
421       break;
422    case VOL_NO_MEDIA:
423       bnet_fsend(dir, _("3912 Failed to label Volume: ERR=%s\n"), strerror_dev(dev));
424       break;
425    default:
426       bnet_fsend(dir, _("3913 Cannot label Volume. "
427 "Unknown status %d from read_volume_label()\n"), label_status);
428       break;
429    }
430
431 bail_out:
432    give_back_device_lock(dev, &hold);
433    return;
434 }
435
436
437 /*
438  * Read the tape label
439  *
440  *  Enter with the mutex set
441  */
442 static bool read_label(DCR *dcr)
443 {
444    int ok;
445    JCR *jcr = dcr->jcr;
446    BSOCK *dir = jcr->dir_bsock;
447    bsteal_lock_t hold;
448    DEVICE *dev = dcr->dev;
449
450    steal_device_lock(dev, &hold, BST_DOING_ACQUIRE);
451
452    dcr->VolumeName[0] = 0;
453    dev->state &= ~ST_LABEL;           /* force read of label */
454    switch (read_dev_volume_label(dcr)) {
455    case VOL_OK:
456       bnet_fsend(dir, _("3001 Mounted Volume: %s\n"), dev->VolHdr.VolName);
457       ok = true;
458       break;
459    default:
460       bnet_fsend(dir, _("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
461          dev_name(dev), jcr->errmsg);
462       ok = false;
463       break;
464    }
465    give_back_device_lock(dev, &hold);
466    return ok;
467 }
468
469 static DEVICE *find_device(JCR *jcr, POOL_MEM &dname)
470 {
471    DEVRES *device;
472    bool found = false;
473
474    unbash_spaces(dname);
475    LockRes();
476    foreach_res(device, R_DEVICE) {
477       /* Find resource, and make sure we were able to open it */
478       if (strcmp(device->hdr.name, dname.c_str()) == 0 && device->dev) {
479          Dmsg1(20, "Found device %s\n", device->hdr.name);
480          jcr->device = device;
481          found = true;
482          break;
483       }
484    }
485    if (found) {
486       /*
487        * ****FIXME*****  device->dev may not point to right device
488        *  if there are multiple devices open
489        */
490       jcr->dcr = new_dcr(jcr, device->dev);
491       UnlockRes();
492       return jcr->dcr->dev;
493    }
494    UnlockRes();
495    return NULL;
496 }
497
498
499 /*
500  * Mount command from Director
501  */
502 static bool mount_cmd(JCR *jcr)
503 {
504    POOL_MEM dname;
505    BSOCK *dir = jcr->dir_bsock;
506    DEVICE *dev;
507    DCR *dcr;
508
509    if (sscanf(dir->msg, "mount %127s", dname.c_str()) == 1) {
510       dev = find_device(jcr, dname);
511       dcr = jcr->dcr;
512       if (dev) {
513          P(dev->mutex);               /* Use P to avoid indefinite block */
514          switch (dev->dev_blocked) {         /* device blocked? */
515          case BST_WAITING_FOR_SYSOP:
516             /* Someone is waiting, wake him */
517             Dmsg0(100, "Waiting for mount. Attempting to wake thread\n");
518             dev->dev_blocked = BST_MOUNT;
519             bnet_fsend(dir, "3001 OK mount. Device=%s\n", dev_name(dev));
520             pthread_cond_signal(&dev->wait_next_vol);
521             break;
522
523          /* In both of these two cases, we (the user) unmounted the Volume */
524          case BST_UNMOUNTED_WAITING_FOR_SYSOP:
525          case BST_UNMOUNTED:
526             /* We freed the device, so reopen it and wake any waiting threads */
527             if (open_dev(dev, NULL, OPEN_READ_WRITE) < 0) {
528                bnet_fsend(dir, _("3901 open device failed: ERR=%s\n"),
529                   strerror_dev(dev));
530                break;
531             }
532             read_dev_volume_label(dcr);
533             if (dev->dev_blocked == BST_UNMOUNTED) {
534                /* We blocked the device, so unblock it */
535                Dmsg0(100, "Unmounted. Unblocking device\n");
536                read_label(dcr);       /* this should not be necessary */
537                unblock_device(dev);
538             } else {
539                Dmsg0(100, "Unmounted waiting for mount. Attempting to wake thread\n");
540                dev->dev_blocked = BST_MOUNT;
541             }
542             if (dev_state(dev, ST_LABEL)) {
543                bnet_fsend(dir, _("3001 Device %s is mounted with Volume \"%s\"\n"),
544                   dev_name(dev), dev->VolHdr.VolName);
545             } else {
546                bnet_fsend(dir, _("3905 Device %s open but no Bacula volume is mounted.\n"
547                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
548                           dev_name(dev));
549             }
550             pthread_cond_signal(&dev->wait_next_vol);
551             break;
552
553          case BST_DOING_ACQUIRE:
554             bnet_fsend(dir, _("3001 Device %s is mounted; doing acquire.\n"),
555                        dev_name(dev));
556             break;
557
558          case BST_WRITING_LABEL:
559             bnet_fsend(dir, _("3903 Device %s is being labeled.\n"), dev_name(dev));
560             break;
561
562          case BST_NOT_BLOCKED:
563             if (dev_state(dev, ST_OPENED)) {
564                if (dev_state(dev, ST_LABEL)) {
565                   bnet_fsend(dir, _("3001 Device %s is mounted with Volume \"%s\"\n"),
566                      dev_name(dev), dev->VolHdr.VolName);
567                } else {
568                   bnet_fsend(dir, _("3905 Device %s open but no Bacula volume is mounted.\n"
569                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
570                              dev_name(dev));
571                }
572             } else {
573                if (!dev_is_tape(dev)) {
574                   bnet_fsend(dir, _("3906 cannot mount non-tape.\n"));
575                   break;
576                }
577                if (open_dev(dev, NULL, OPEN_READ_WRITE) < 0) {
578                   bnet_fsend(dir, _("3901 open device failed: ERR=%s\n"),
579                      strerror_dev(dev));
580                   break;
581                }
582                read_label(dcr);
583                if (dev_state(dev, ST_LABEL)) {
584                   bnet_fsend(dir, _("3001 Device %s is already mounted with Volume \"%s\"\n"),
585                      dev_name(dev), dev->VolHdr.VolName);
586                } else {
587                   bnet_fsend(dir, _("3905 Device %s open but no Bacula volume is mounted.\n"
588                                     "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
589                              dev_name(dev));
590                }
591             }
592             break;
593
594          default:
595             bnet_fsend(dir, _("3905 Bizarre wait state %d\n"), dev->dev_blocked);
596             break;
597          }
598          V(dev->mutex);
599       } else {
600          bnet_fsend(dir, _("3999 Device \"%s\" not found\n"), dname.c_str());
601       }
602    } else {
603       pm_strcpy(jcr->errmsg, dir->msg);
604       bnet_fsend(dir, _("3909 Error scanning mount command: %s\n"), jcr->errmsg);
605    }
606    bnet_sig(dir, BNET_EOD);
607    return true;
608 }
609
610 /*
611  * unmount command from Director
612  */
613 static bool unmount_cmd(JCR *jcr)
614 {
615    POOL_MEM dname;
616    BSOCK *dir = jcr->dir_bsock;
617    DEVICE *dev;
618
619    if (sscanf(dir->msg, "unmount %127s", dname.c_str()) == 1) {
620       dev = find_device(jcr, dname);
621       if (dev) {
622          P(dev->mutex);               /* Use P to avoid indefinite block */
623          if (!(dev->state & ST_OPENED)) {
624             Dmsg0(90, "Device already unmounted\n");
625             bnet_fsend(dir, _("3901 Device \"%s\" is already unmounted.\n"), dev_name(dev));
626
627          } else if (dev->dev_blocked == BST_WAITING_FOR_SYSOP) {
628             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
629                dev->dev_blocked);
630             open_dev(dev, NULL, 0);     /* fake open for close */
631             offline_or_rewind_dev(dev);
632             force_close_dev(dev);
633             dev->dev_blocked = BST_UNMOUNTED_WAITING_FOR_SYSOP;
634             bnet_fsend(dir, _("3001 Device \"%s\" unmounted.\n"), dev_name(dev));
635
636          } else if (dev->dev_blocked == BST_DOING_ACQUIRE) {
637             bnet_fsend(dir, _("3902 Device \"%s\" is busy in acquire.\n"), dev_name(dev));
638
639          } else if (dev->dev_blocked == BST_WRITING_LABEL) {
640             bnet_fsend(dir, _("3903 Device \"%s\" is being labeled.\n"), dev_name(dev));
641
642          } else if (dev_state(dev, ST_READ) || dev->num_writers) {
643             if (dev_state(dev, ST_READ)) {
644                 Dmsg0(90, "Device in read mode\n");
645                 bnet_fsend(dir, _("3904 Device \"%s\" is busy reading.\n"), dev_name(dev));
646             } else {
647                 Dmsg1(90, "Device busy with %d writers\n", dev->num_writers);
648                 bnet_fsend(dir, _("3905 Device %s is busy with %d writer(s).\n"),
649                    dev_name(dev), dev->num_writers);
650             }
651
652          } else {                     /* device not being used */
653             Dmsg0(90, "Device not in use, unmounting\n");
654             /* On FreeBSD, I am having ASSERT() failures in block_device()
655              * and I can only imagine that the thread id that we are
656              * leaving in no_wait_id is being re-used. So here,
657              * we simply do it by hand.  Gross, but a solution.
658              */
659             /*  block_device(dev, BST_UNMOUNTED); replace with 2 lines below */
660             dev->dev_blocked = BST_UNMOUNTED;
661             dev->no_wait_id = 0;
662             open_dev(dev, NULL, 0);     /* fake open for close */
663             offline_or_rewind_dev(dev);
664             force_close_dev(dev);
665             bnet_fsend(dir, _("3002 Device %s unmounted.\n"), dev_name(dev));
666          }
667          V(dev->mutex);
668       } else {
669          bnet_fsend(dir, _("3999 Device \"%s\" not found\n"), dname.c_str());
670       }
671    } else {
672       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
673       pm_strcpy(jcr->errmsg, dir->msg);
674       bnet_fsend(dir, _("3907 Error scanning unmount command: %s\n"), jcr->errmsg);
675    }
676    bnet_sig(dir, BNET_EOD);
677    return true;
678 }
679
680 /*
681  * Release command from Director. This rewinds the device and if
682  *   configured does a offline and ensures that Bacula will
683  *   re-read the label of the tape before continuing. This gives
684  *   the operator the chance to change the tape anytime before the
685  *   next job starts.
686  */
687 static bool release_cmd(JCR *jcr)
688 {
689    POOL_MEM dname;
690    BSOCK *dir = jcr->dir_bsock;
691    DEVICE *dev;
692
693    if (sscanf(dir->msg, "release %127s", dname.c_str()) == 1) {
694       dev = find_device(jcr, dname);
695       if (dev) {
696          P(dev->mutex);               /* Use P to avoid indefinite block */
697          if (!(dev->state & ST_OPENED)) {
698             Dmsg0(90, "Device already released\n");
699             bnet_fsend(dir, _("3911 Device %s already released.\n"), dev_name(dev));
700
701          } else if (dev->dev_blocked == BST_WAITING_FOR_SYSOP ||
702                     dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP) {
703             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
704                dev->dev_blocked);
705             bnet_fsend(dir, _("3912 Device %s waiting for mount.\n"), dev_name(dev));
706
707          } else if (dev->dev_blocked == BST_DOING_ACQUIRE) {
708             bnet_fsend(dir, _("3913 Device %s is busy in acquire.\n"), dev_name(dev));
709
710          } else if (dev->dev_blocked == BST_WRITING_LABEL) {
711             bnet_fsend(dir, _("3914 Device %s is being labeled.\n"), dev_name(dev));
712
713          } else if (dev_state(dev, ST_READ) || dev->num_writers) {
714             if (dev_state(dev, ST_READ)) {
715                 Dmsg0(90, "Device in read mode\n");
716                 bnet_fsend(dir, _("3915 Device %s is busy with 1 reader.\n"), dev_name(dev));
717             } else {
718                 Dmsg1(90, "Device busy with %d writers\n", dev->num_writers);
719                 bnet_fsend(dir, _("3916 Device %s is busy with %d writer(s).\n"),
720                    dev_name(dev), dev->num_writers);
721             }
722
723          } else {                     /* device not being used */
724             Dmsg0(90, "Device not in use, unmounting\n");
725             release_volume(jcr->dcr);
726             bnet_fsend(dir, _("3012 Device %s released.\n"), dev_name(dev));
727          }
728          V(dev->mutex);
729       } else {
730          bnet_fsend(dir, _("3999 Device \"%s\" not found\n"), dname.c_str());
731       }
732    } else {
733       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
734       pm_strcpy(jcr->errmsg, dir->msg);
735       bnet_fsend(dir, _("3917 Error scanning release command: %s\n"), jcr->errmsg);
736    }
737    bnet_sig(dir, BNET_EOD);
738    return true;
739 }
740
741
742
743 /*
744  * Autochanger command from Director
745  */
746 static bool autochanger_cmd(JCR *jcr)
747 {
748    POOL_MEM dname;
749    BSOCK *dir = jcr->dir_bsock;
750    DEVICE *dev;
751    DCR *dcr;
752
753    if (sscanf(dir->msg, "autochanger list %127s ", dname.c_str()) == 1) {
754       dev = find_device(jcr, dname);
755       dcr = jcr->dcr;
756       if (dev) {
757          P(dev->mutex);               /* Use P to avoid indefinite block */
758          if (!dev_is_tape(dev)) {
759             bnet_fsend(dir, _("3995 Device %s is not an autochanger.\n"), dev_name(dev));
760          } else if (!(dev->state & ST_OPENED)) {
761             autochanger_list(dcr, dir);
762          /* Under certain "safe" conditions, we can steal the lock */
763          } else if (dev->dev_blocked &&
764                     (dev->dev_blocked == BST_UNMOUNTED ||
765                      dev->dev_blocked == BST_WAITING_FOR_SYSOP ||
766                      dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP)) {
767             autochanger_list(dcr, dir);
768          } else if (dev_state(dev, ST_READ) || dev->num_writers) {
769             if (dev_state(dev, ST_READ)) {
770                 bnet_fsend(dir, _("3901 Device %s is busy with 1 reader.\n"), dev_name(dev));
771             } else {
772                 bnet_fsend(dir, _("3902 Device %s is busy with %d writer(s).\n"),
773                    dev_name(dev), dev->num_writers);
774             }
775          } else {                     /* device not being used */
776             autochanger_list(dcr, dir);
777          }
778          V(dev->mutex);
779       } else {
780          bnet_fsend(dir, _("3999 Device \"%s\" not found\n"), dname.c_str());
781       }
782    } else {  /* error on scanf */
783       pm_strcpy(jcr->errmsg, dir->msg);
784       bnet_fsend(dir, _("3908 Error scanning autocharger list command: %s\n"),
785          jcr->errmsg);
786    }
787    bnet_sig(dir, BNET_EOD);
788    return true;
789 }
790
791 /*
792  * Read and return the Volume label
793  */
794 static bool readlabel_cmd(JCR *jcr)
795 {
796    POOL_MEM dname;
797    BSOCK *dir = jcr->dir_bsock;
798    DEVICE *dev;
799    int Slot;
800
801    if (sscanf(dir->msg, "readlabel %127s Slot=%d", dname.c_str(), &Slot) == 2) {
802       dev = find_device(jcr, dname);
803       if (dev) {
804          P(dev->mutex);               /* Use P to avoid indefinite block */
805          if (!dev_state(dev, ST_OPENED)) {
806             read_volume_label(jcr, dev, Slot);
807             force_close_dev(dev);
808          /* Under certain "safe" conditions, we can steal the lock */
809          } else if (dev->dev_blocked &&
810                     (dev->dev_blocked == BST_UNMOUNTED ||
811                      dev->dev_blocked == BST_WAITING_FOR_SYSOP ||
812                      dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP)) {
813             read_volume_label(jcr, dev, Slot);
814          } else if (dev_state(dev, ST_READ) || dev->num_writers) {
815             if (dev_state(dev, ST_READ)) {
816                 bnet_fsend(dir, _("3911 Device %s is busy with 1 reader.\n"),
817                             dev_name(dev));
818             } else {
819                 bnet_fsend(dir, _("3912 Device %s is busy with %d writer(s).\n"),
820                    dev_name(dev), dev->num_writers);
821             }
822          } else {                     /* device not being used */
823             read_volume_label(jcr, dev, Slot);
824          }
825          V(dev->mutex);
826       } else {
827          bnet_fsend(dir, _("3999 Device \"%s\" not found\n"), dname.c_str());
828       }
829    } else {
830       pm_strcpy(jcr->errmsg, dir->msg);
831       bnet_fsend(dir, _("3909 Error scanning readlabel command: %s\n"), jcr->errmsg);
832    }
833    bnet_sig(dir, BNET_EOD);
834    return true;
835 }
836
837 /*
838  * Read the tape label
839  *
840  *  Enter with the mutex set
841  */
842 static void read_volume_label(JCR *jcr, DEVICE *dev, int Slot)
843 {
844    BSOCK *dir = jcr->dir_bsock;
845    bsteal_lock_t hold;
846    DCR *dcr = jcr->dcr;
847
848    dcr->dev = dev;
849    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
850
851    if (!try_autoload_device(jcr, Slot, "")) {
852       goto bail_out;                  /* error */
853    }
854
855    dev->state &= ~ST_LABEL;           /* force read of label */
856    switch (read_dev_volume_label(dcr)) {
857    case VOL_OK:
858       /* DO NOT add quotes around the Volume name. It is scanned in the DIR */
859       bnet_fsend(dir, _("3001 Volume=%s Slot=%d\n"), dev->VolHdr.VolName, Slot);
860       Dmsg1(100, "Volume: %s\n", dev->VolHdr.VolName);
861       break;
862    default:
863       bnet_fsend(dir, _("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
864                  dev_name(dev), jcr->errmsg);
865       break;
866    }
867
868 bail_out:
869    give_back_device_lock(dev, &hold);
870    return;
871 }
872
873 static bool try_autoload_device(JCR *jcr, int slot, const char *VolName)
874 {
875    DCR *dcr = jcr->dcr;
876    BSOCK *dir = jcr->dir_bsock;
877    DEVICE *dev = dcr->dev;
878
879    bstrncpy(dcr->VolumeName, VolName, sizeof(dcr->VolumeName));
880    dcr->VolCatInfo.Slot = slot;
881    dcr->VolCatInfo.InChanger = slot > 0;
882    if (autoload_device(dcr, 0, dir) < 0) {    /* autoload if possible */
883       return false;
884    }
885
886    /* Ensure that the device is open -- autoload_device() closes it */
887    for ( ; !(dev->state & ST_OPENED); ) {
888       if (open_dev(dev, dcr->VolumeName, OPEN_READ_WRITE) < 0) {
889          bnet_fsend(dir, _("3910 Unable to open device %s. ERR=%s\n"),
890             dev_name(dev), strerror_dev(dev));
891          return false;
892       }
893    }
894    return true;
895 }