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