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