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