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