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