]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dircmd.c
Backport from Bacula Enterprise
[bacula/bacula] / bacula / src / stored / dircmd.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2015 Kern Sibbald
5    Copyright (C) 2001-2014 Free Software Foundation Europe e.V.
6
7    The original author of Bacula is Kern Sibbald, with contributions
8    from many others, a complete list can be found in the file AUTHORS.
9
10    You may use this file and others of this release according to the
11    license defined in the LICENSE file, which includes the Affero General
12    Public License, v3.0 ("AGPLv3") and some additional permissions and
13    terms pursuant to its AGPLv3 Section 7.
14
15    This notice must be preserved when any source code is 
16    conveyed and/or propagated.
17
18    Bacula(R) is a registered trademark of Kern Sibbald.
19 */
20 /*
21  *  This file handles accepting Director Commands
22  *
23  *    Most Director commands are handled here, with the
24  *    exception of the Job command command and subsequent
25  *    subcommands that are handled
26  *    in job.c.
27  *
28  *    N.B. in this file, in general we must use P(dev->mutex) rather
29  *      than dev->rLock() so that we can examine the blocked
30  *      state rather than blocking ourselves because a Job
31  *      thread has the device blocked. In some "safe" cases,
32  *      we can do things to a blocked device. CAREFUL!!!!
33  *
34  *    File daemon commands are handled in fdcmd.c
35  *
36  *     Written by Kern Sibbald, May MMI
37  *
38  */
39
40 #include "bacula.h"
41 #include "stored.h"
42
43 /* Exported variables */
44
45 /* Imported variables */
46 extern BSOCK *filed_chan;
47 extern struct s_last_job last_job;
48 extern bool init_done;
49
50 /* Static variables */
51 static char derrmsg[]     = "3900 Invalid command:";
52 static char OKsetdebug[]  = "3000 OK setdebug=%ld trace=%ld options=%s tags=%s\n";
53 static char invalid_cmd[] = "3997 Invalid command for a Director with Monitor directive enabled.\n";
54 static char OK_bootstrap[]    = "3000 OK bootstrap\n";
55 static char ERROR_bootstrap[] = "3904 Error bootstrap\n";
56 static char OKclient[] = "3000 OK client command\n";
57
58 /* Imported functions */
59 extern void terminate_child();
60 extern bool job_cmd(JCR *jcr);
61 extern bool use_cmd(JCR *jcr);
62 extern bool run_cmd(JCR *jcr);
63 extern bool status_cmd(JCR *sjcr);
64 extern bool qstatus_cmd(JCR *jcr);
65 //extern bool query_cmd(JCR *jcr);
66
67 /* Forward referenced functions */
68 static bool client_cmd(JCR *jcr);
69 static bool storage_cmd(JCR *jcr);
70 static bool label_cmd(JCR *jcr);
71 static bool die_cmd(JCR *jcr);
72 static bool relabel_cmd(JCR *jcr);
73 static bool readlabel_cmd(JCR *jcr);
74 static bool release_cmd(JCR *jcr);
75 static bool setdebug_cmd(JCR *jcr);
76 static bool cancel_cmd(JCR *cjcr);
77 static bool mount_cmd(JCR *jcr);
78 static bool unmount_cmd(JCR *jcr);
79 static bool enable_cmd(JCR *jcr);
80 static bool disable_cmd(JCR *jcr);
81 //static bool action_on_purge_cmd(JCR *jcr);
82 static bool bootstrap_cmd(JCR *jcr);
83 static bool changer_cmd(JCR *sjcr);
84 static bool do_label(JCR *jcr, int relabel);
85 static DCR *find_device(JCR *jcr, POOL_MEM &dev_name,
86                         POOLMEM *media_type, int drive);
87 static void read_volume_label(JCR *jcr, DCR *dcr, DEVICE *dev, int Slot);
88 static void label_volume_if_ok(DCR *dcr, char *oldname,
89                                char *newname, char *poolname,
90                                int Slot, int relabel);
91 static bool try_autoload_device(JCR *jcr, DCR *dcr, int slot, const char *VolName);
92 static void send_dir_busy_message(BSOCK *dir, DEVICE *dev);
93
94 /* Responses send to Director for storage command */
95 static char BADcmd[]  = "2902 Bad %s\n";
96 static char OKstore[] = "2000 OK storage\n";
97
98 /* Commands received from director that need scanning */
99 static char storaddr[] = "storage address=%s port=%d ssl=%d Job=%127s Authentication=%127s";
100
101 struct s_cmds {
102    const char *cmd;
103    bool (*func)(JCR *jcr);
104    bool monitoraccess;                      /* set if monitors can access this cmd */
105 };
106
107 /*
108  * The following are the recognized commands from the Director.
109  */
110 static struct s_cmds cmds[] = {
111    {"JobId=",      job_cmd,         0},     /* start Job */
112    {"autochanger", changer_cmd,     0},
113    {"bootstrap",   bootstrap_cmd,   0},
114    {"cancel",      cancel_cmd,      0},
115    {"client",      client_cmd,      0},     /* client address */
116    {".die",        die_cmd,         0},
117    {"label",       label_cmd,       0},     /* label a tape */
118    {"mount",       mount_cmd,       0},
119    {"enable",      enable_cmd,       0},
120    {"disable",     disable_cmd,       0},
121    {"readlabel",   readlabel_cmd,   0},
122    {"release",     release_cmd,     0},
123    {"relabel",     relabel_cmd,     0},     /* relabel a tape */
124    {"setdebug=",   setdebug_cmd,    0},     /* set debug level */
125    {"status",      status_cmd,      1},
126    {".status",     qstatus_cmd,     1},
127    {"stop",        cancel_cmd,      0},
128    {"storage",     storage_cmd,     0},     /* get SD addr from Dir */
129    {"unmount",     unmount_cmd,     0},
130    {"use storage=", use_cmd,        0},
131    {"run",         run_cmd,         0},
132 // {"query",       query_cmd,       0},
133    {NULL,        NULL}                      /* list terminator */
134 };
135
136
137 /*
138  * Connection request. We accept connections either from the
139  *  Director or a Client (File daemon).
140  *
141  * Note, we are running as a separate thread of the Storage daemon.
142  *  and it is because a Director has made a connection with
143  *  us on the "Message" channel.
144  *
145  * Basic tasks done here:
146  *  - Create a JCR record
147  *  - If it was from the FD, call handle_filed_connection()
148  *  - Authenticate the Director
149  *  - We wait for a command
150  *  - We execute the command
151  *  - We continue or exit depending on the return status
152  */
153 void *handle_connection_request(void *arg)
154 {
155    BSOCK *bs = (BSOCK *)arg;
156    JCR *jcr;
157    int i;
158    bool found, quit;
159    int bnet_stat = 0;
160    char tbuf[100];
161
162    if (bs->recv() <= 0) {
163       Jmsg1(NULL, M_ERROR, 0, _("Connection request from %s failed.\n"), bs->who());
164       bmicrosleep(5, 0);   /* make user wait 5 seconds */
165       bs->destroy();
166       return NULL;
167    }
168
169    /* Check for client connection */
170    if (is_client_connection(bs)) {
171       handle_client_connection(bs);
172       return NULL;
173    }
174
175    /*
176     * This is a connection from the Director, so setup a JCR
177     */
178    Dmsg1(050, "Got a DIR connection at %s\n", bstrftimes(tbuf, sizeof(tbuf),
179          (utime_t)time(NULL)));
180    jcr = new_jcr(sizeof(JCR), stored_free_jcr); /* create Job Control Record */
181    jcr->dir_bsock = bs;               /* save Director bsock */
182    jcr->dir_bsock->set_jcr(jcr);
183    jcr->dcrs = New(alist(10, not_owned_by_alist));
184    create_jobmedia_queue(jcr);
185    /* Initialize FD start condition variable */
186    int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
187    if (errstat != 0) {
188       berrno be;
189       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
190       goto bail_out;
191    }
192
193    Dmsg0(1000, "stored in start_job\n");
194
195    /*
196     * Validate then authenticate the Director
197     */
198    if (!validate_dir_hello(jcr)) {
199       goto bail_out;
200    }
201    if (!authenticate_director(jcr)) {
202       Jmsg(jcr, M_FATAL, 0, _("Unable to authenticate Director\n"));
203       goto bail_out;
204    }
205    Dmsg0(90, "Message channel init completed.\n");
206
207    for (quit=false; !quit;) {
208       /* Read command */
209       if ((bnet_stat = bs->recv()) <= 0) {
210          break;               /* connection terminated */
211       }
212       Dmsg1(199, "<dird: %s\n", bs->msg);
213       /* Ensure that device initialization is complete */
214       while (!init_done) {
215          bmicrosleep(1, 0);
216       }
217       found = false;
218       for (i=0; cmds[i].cmd; i++) {
219         if (strncmp(cmds[i].cmd, bs->msg, strlen(cmds[i].cmd)) == 0) {
220            if ((!cmds[i].monitoraccess) && (jcr->director->monitor)) {
221               Dmsg1(100, "Command \"%s\" is invalid.\n", cmds[i].cmd);
222               bs->fsend(invalid_cmd);
223               bs->signal(BNET_EOD);
224               break;
225            }
226            Dmsg1(200, "Do command: %s\n", cmds[i].cmd);
227            if (!cmds[i].func(jcr)) { /* do command */
228               quit = true; /* error, get out */
229               Dmsg1(190, "Command %s requests quit\n", cmds[i].cmd);
230            }
231            found = true;             /* indicate command found */
232            break;
233         }
234       }
235       if (!found) {                   /* command not found */
236         POOL_MEM err_msg;
237         Mmsg(err_msg, "%s %s\n", derrmsg, bs->msg);
238         bs->fsend(err_msg.c_str());
239         break;
240       }
241    }
242 bail_out:
243    generate_daemon_event(jcr, "JobEnd");
244    generate_plugin_event(jcr, bsdEventJobEnd);
245    flush_jobmedia_queue(jcr);
246    dequeue_messages(jcr);             /* send any queued messages */
247    bs->signal(BNET_TERMINATE);
248    free_plugins(jcr);                 /* release instantiated plugins */
249    free_jcr(jcr);
250    return NULL;
251 }
252
253
254 /*
255  * Force SD to die, and hopefully dump itself.  Turned on only
256  *  in development version.
257  */
258 static bool die_cmd(JCR *jcr)
259 {
260 #ifdef DEVELOPER
261    JCR *djcr = NULL;
262    int a;
263    BSOCK *dir = jcr->dir_bsock;
264    pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;
265
266    if (strstr(dir->msg, "deadlock")) {
267       Pmsg0(000, "I have been requested to deadlock ...\n");
268       P(m);
269       P(m);
270    }
271
272    Pmsg1(000, "I have been requested to die ... (%s)\n", dir->msg);
273    a = djcr->JobId;   /* ref NULL pointer */
274    djcr->JobId = a;
275 #endif
276    return 0;
277 }
278
279 /*
280  * Get address of client from Director
281  *   This initiates SD Calls Client.
282  *   We attempt to connect to the client (an FD or SD) and
283  *   authenticate it.
284  */
285 static bool client_cmd(JCR *jcr)
286 {
287    int client_port;                 /* client port */
288    int enable_ssl;                 /* enable ssl */
289    BSOCK *dir = jcr->dir_bsock;
290    BSOCK *cl = new_bsock();        /* client bsock */
291
292    Dmsg1(100, "ClientCmd: %s", dir->msg);
293    jcr->sd_calls_client = true;
294    if (sscanf(dir->msg, "client address=%s port=%d ssl=%d", &jcr->client_addr, &client_port,
295               &enable_ssl) != 3) {
296       pm_strcpy(jcr->errmsg, dir->msg);
297       Jmsg(jcr, M_FATAL, 0, _("Bad client command: %s"), jcr->errmsg);
298       Dmsg1(050, "Bad client command: %s", jcr->errmsg);
299       goto bail_out;
300    }
301
302    Dmsg3(110, "Connect to client: %s:%d ssl=%d\n", jcr->client_addr, client_port,
303          enable_ssl);
304    /* Open command communications with Client */
305    /* Try to connect for 1 hour at 10 second intervals */
306    if (!cl->connect(jcr, 10, (int)me->ClientConnectTimeout, me->heartbeat_interval,
307                 _("Client daemon"), jcr->client_addr, NULL, client_port, 1)) {
308       /* destroy() OK because cl is local */
309       cl->destroy();
310       Jmsg(jcr, M_FATAL, 0, _("Failed to connect to Client daemon: %s:%d\n"),
311           jcr->client_addr, client_port);
312       Dmsg2(100, "Failed to connect to Client daemon: %s:%d\n",
313           jcr->client_addr, client_port);
314       goto bail_out;
315    }
316    Dmsg0(110, "SD connection OK to Client.\n");
317
318    jcr->file_bsock = cl;
319    jcr->file_bsock->set_jcr(jcr);
320    if (!send_hello_client(jcr, jcr->Job)) {
321       goto bail_out;
322    }
323
324    /* Send OK to Director */
325    return dir->fsend(OKclient);
326
327 bail_out:
328    jcr->setJobStatus(JS_ErrorTerminated);
329    dir->fsend("3902 Bad %s cmd\n", "client");
330    return 0;
331 }
332
333 /*
334  * Get address of storage daemon from Director
335  */
336 static bool storage_cmd(JCR *jcr)
337 {
338    int stored_port;                /* storage daemon port */
339    int enable_ssl;                 /* enable ssl to sd */
340    char sd_auth_key[200];
341    BSOCK *dir = jcr->dir_bsock;
342    BSOCK *sd = new_bsock();        /* storage daemon bsock */
343    char Job[MAX_NAME_LENGTH];
344
345    Dmsg1(050, "StorageCmd: %s", dir->msg);
346    if (sscanf(dir->msg, storaddr, &jcr->stored_addr, &stored_port,
347               &enable_ssl, Job, sd_auth_key) != 5) {
348       pm_strcpy(jcr->errmsg, dir->msg);
349       Jmsg(jcr, M_FATAL, 0, _("Bad storage command: %s"), jcr->errmsg);
350       Pmsg1(010, "Bad storage command: %s", jcr->errmsg);
351       goto bail_out;
352    }
353
354    unbash_spaces(Job);
355    if (jcr->sd_auth_key) {
356       bfree_and_null(jcr->sd_auth_key);
357       jcr->sd_auth_key = bstrdup(sd_auth_key);
358    }
359    if (stored_port != 0) {
360       Dmsg2(050, "sd_calls=%d sd_client=%d\n", jcr->sd_calls_client,
361          jcr->sd_client);
362       jcr->sd_calls_client = false;   /* We are doing the connecting */
363       Dmsg3(050, "Connect to storage and wait: %s:%d ssl=%d\n", jcr->stored_addr, stored_port,
364             enable_ssl);
365       /* Open command communications with Storage daemon */
366       /* Try to connect for 1 hour at 10 second intervals */
367       if (!sd->connect(jcr, 10, (int)me->ClientConnectTimeout, me->heartbeat_interval,
368                 _("Storage daemon"), jcr->stored_addr, NULL, stored_port, 1)) {
369          /* destroy() OK because sd is local */
370          sd->destroy();
371          Jmsg(jcr, M_FATAL, 0, _("Failed to connect to Storage daemon: %s:%d\n"),
372              jcr->stored_addr, stored_port);
373          Dmsg2(010, "Failed to connect to Storage daemon: %s:%d\n",
374              jcr->stored_addr, stored_port);
375          goto bail_out;
376       }
377
378       Dmsg0(050, "Connection OK to SD.\n");
379
380       jcr->store_bsock = sd;
381    } else {                      /* The storage daemon called us */
382       jcr->sd_calls_client = true;
383       /* We should already have a storage connection! */
384       if (jcr->file_bsock && jcr->store_bsock == NULL) {
385          jcr->store_bsock = jcr->file_bsock;
386       }
387       if (jcr->store_bsock == NULL) {
388          Jmsg0(jcr, M_FATAL, 0, _("In storage_cmd port==0, no prior Storage connection.\n"));
389          Pmsg0(010, "In storage_cmd port==0, no prior Storage connection.\n");
390          goto bail_out;
391       }
392    }
393
394    if (!send_hello_sd(jcr, Job)) {
395       goto bail_out;
396    }
397
398    if (!authenticate_storagedaemon(jcr)) {
399       goto bail_out;
400    }
401    /*
402     * We are a client so we read from the socket we just
403     *   opened as if we were a FD, so set file_bsock and
404     *   clear the store_bsock.
405     */
406    jcr->file_bsock = jcr->store_bsock;
407    jcr->store_bsock = NULL;
408    jcr->authenticated = true;    /* Dir authentication is sufficient */
409    Dmsg1(050, "=== Storage_cmd authenticated Job=%s with SD.\n", Job);
410
411    /* Send OK to Director */
412    return dir->fsend(OKstore);
413
414 bail_out:
415    Dmsg0(100, "Send storage command failed.\n");
416    dir->fsend(BADcmd, "storage");
417    return false;
418 }
419
420
421 /*
422  * Set debug level as requested by the Director
423  *
424  */
425 static bool setdebug_cmd(JCR *jcr)
426 {
427    BSOCK *dir = jcr->dir_bsock;
428    int32_t trace_flag, lvl, hangup, blowup;
429    int64_t level, level_tags = 0;
430    char options[60];
431    char tags[512];
432    *tags = *options = 0;
433
434    Dmsg1(10, "setdebug_cmd: %s", dir->msg);
435
436    if (sscanf(dir->msg, "setdebug=%ld trace=%ld hangup=%ld blowup=%ld options=%55s tags=%511s",
437               &lvl, &trace_flag, &hangup, &blowup, options, tags) != 6)
438    {
439       if (sscanf(dir->msg, "setdebug=%ld trace=%ld", &lvl, &trace_flag) != 2 || lvl < 0) {
440          dir->fsend(_("3991 Bad setdebug command: %s\n"), dir->msg);
441          return 0;
442       }
443    }
444    level = lvl;
445    set_trace(trace_flag);
446    set_hangup(hangup);
447    set_blowup(blowup);
448    set_debug_flags(options);
449    if (!debug_parse_tags(tags, &level_tags)) {
450       *tags = 0;
451    }
452    if (level >= 0) {
453       debug_level = level;
454    }
455    debug_level_tags = level_tags;
456
457    return dir->fsend(OKsetdebug, lvl, trace_flag, options, tags);
458 }
459
460
461 /*
462  * Cancel a Job
463  *   Be careful, we switch to using the job's JCR! So, using
464  *   BSOCKs on that jcr can have two threads in the same code.
465  */
466 static bool cancel_cmd(JCR *cjcr)
467 {
468    BSOCK *dir = cjcr->dir_bsock;
469    int oldStatus;
470    char Job[MAX_NAME_LENGTH];
471    JCR *jcr;
472    int status;
473    const char *reason;
474
475    if (sscanf(dir->msg, "cancel Job=%127s", Job) == 1) {
476       status = JS_Canceled;
477       reason = "canceled";
478    } else if (sscanf(dir->msg, "stop Job=%127s", Job) == 1) {
479       status = JS_Incomplete;
480       reason = "stopped";
481    } else {
482       dir->fsend(_("3903 Error scanning cancel command.\n"));
483       goto bail_out;
484    }
485    if (!(jcr=get_jcr_by_full_name(Job))) {
486       dir->fsend(_("3904 Job %s not found.\n"), Job);
487    } else {
488       oldStatus = jcr->JobStatus;
489       jcr->setJobStatus(status);
490       Dmsg2(800, "Cancel JobId=%d %p\n", jcr->JobId, jcr);
491       if (!jcr->authenticated && oldStatus == JS_WaitFD) {
492          pthread_cond_signal(&jcr->job_start_wait); /* wake waiting thread */
493       }
494       if (jcr->file_bsock) {
495          jcr->file_bsock->set_terminated();
496          jcr->file_bsock->set_timed_out();
497          Dmsg2(800, "Term bsock jid=%d %p\n", jcr->JobId, jcr);
498       } else {
499          /* Still waiting for FD to connect, release it */
500          pthread_cond_signal(&jcr->job_start_wait); /* wake waiting job */
501          Dmsg2(800, "Signal FD connect jid=%d %p\n", jcr->JobId, jcr);
502       }
503       /* If thread waiting on mount, wake him */
504       if (jcr->dcr && jcr->dcr->dev && jcr->dcr->dev->waiting_for_mount()) {
505          pthread_cond_broadcast(&jcr->dcr->dev->wait_next_vol);
506          Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
507          pthread_cond_broadcast(&wait_device_release);
508       }
509       if (jcr->read_dcr && jcr->read_dcr->dev && jcr->read_dcr->dev->waiting_for_mount()) {
510          pthread_cond_broadcast(&jcr->read_dcr->dev->wait_next_vol);
511          Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
512          pthread_cond_broadcast(&wait_device_release);
513       }
514       jcr->my_thread_send_signal(TIMEOUT_SIGNAL);
515       dir->fsend(_("3000 JobId=%ld Job=\"%s\" marked to be %s.\n"),
516          jcr->JobId, jcr->Job, reason);
517       free_jcr(jcr);
518    }
519
520 bail_out:
521    dir->signal(BNET_EOD);
522    return 1;
523 }
524
525 /*
526  * Label a Volume
527  *
528  */
529 static bool label_cmd(JCR *jcr)
530 {
531    return do_label(jcr, 0);
532 }
533
534 static bool relabel_cmd(JCR *jcr)
535 {
536    return do_label(jcr, 1);
537 }
538
539 static bool do_label(JCR *jcr, int relabel)
540 {
541    POOLMEM *newname, *oldname, *poolname, *mtype;
542    POOL_MEM dev_name;
543    BSOCK *dir = jcr->dir_bsock;
544    DCR *dcr;
545    DEVICE *dev;
546    bool ok = false;
547    int32_t slot, drive;
548
549    newname = get_memory(dir->msglen+1);
550    oldname = get_memory(dir->msglen+1);
551    poolname = get_memory(dir->msglen+1);
552    mtype = get_memory(dir->msglen+1);
553    if (relabel) {
554       if (sscanf(dir->msg, "relabel %127s OldName=%127s NewName=%127s PoolName=%127s "
555                  "MediaType=%127s Slot=%d drive=%d",
556                   dev_name.c_str(), oldname, newname, poolname, mtype,
557                   &slot, &drive) == 7) {
558          ok = true;
559       }
560    } else {
561       *oldname = 0;
562       if (sscanf(dir->msg, "label %127s VolumeName=%127s PoolName=%127s "
563                  "MediaType=%127s Slot=%d drive=%d",
564           dev_name.c_str(), newname, poolname, mtype, &slot, &drive) == 6) {
565          ok = true;
566       }
567    }
568    if (ok) {
569       unbash_spaces(newname);
570       unbash_spaces(oldname);
571       unbash_spaces(poolname);
572       unbash_spaces(mtype);
573       dcr = find_device(jcr, dev_name, mtype, drive);
574       if (dcr) {
575          dev = dcr->dev;
576          dev->Lock();                 /* Use P to avoid indefinite block */
577          if (!dev->is_open() && !dev->is_busy()) {
578             Dmsg1(400, "Can %slabel. Device is not open\n", relabel?"re":"");
579             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
580             dev->close();
581          /* Under certain "safe" conditions, we can steal the lock */
582          } else if (dev->can_steal_lock()) {
583             Dmsg0(400, "Can relabel. can_steal_lock\n");
584             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
585          } else if (dev->is_busy() || dev->is_blocked()) {
586             send_dir_busy_message(dir, dev);
587          } else {                     /* device not being used */
588             Dmsg0(400, "Can relabel. device not used\n");
589             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
590          }
591          dev->Unlock();
592          free_dcr(dcr);
593       } else {
594          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), dev_name.c_str());
595       }
596    } else {
597       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
598       pm_strcpy(jcr->errmsg, dir->msg);
599       dir->fsend(_("3903 Error scanning label command: %s\n"), jcr->errmsg);
600    }
601    free_memory(oldname);
602    free_memory(newname);
603    free_memory(poolname);
604    free_memory(mtype);
605    dir->signal(BNET_EOD);
606    return true;
607 }
608
609 /*
610  * Read the tape label and determine if we can safely
611  * label the tape (not a Bacula volume), then label it.
612  *
613  *  Enter with the mutex set
614  */
615 static void label_volume_if_ok(DCR *dcr, char *oldname,
616                                char *newname, char *poolname,
617                                int slot, int relabel)
618 {
619    BSOCK *dir = dcr->jcr->dir_bsock;
620    bsteal_lock_t hold;
621    DEVICE *dev = dcr->dev;
622    int label_status;
623    int mode;
624    const char *volname = (relabel == 1) ? oldname : newname;
625
626    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
627    Dmsg1(100, "Stole device %s lock, writing label.\n", dev->print_name());
628
629    Dmsg0(90, "try_autoload_device - looking for volume_info\n");
630    if (!try_autoload_device(dcr->jcr, dcr, slot, volname)) {
631       goto bail_out;                  /* error */
632    }
633
634    /* Ensure that the device is open -- autoload_device() closes it */
635    if (dev->is_tape()) {
636       mode = OPEN_READ_WRITE;
637    } else {
638       mode = CREATE_READ_WRITE;
639    }
640
641    if (relabel) {
642       dev->truncating = true;         /* let open() know we will truncate it */
643    }
644    /* Set old volume name for open if relabeling */
645    dcr->setVolCatName(volname);
646    if (!dev->open(dcr, mode)) {
647       dir->fsend(_("3910 Unable to open device \"%s\": ERR=%s\n"),
648          dev->print_name(), dev->bstrerror());
649       goto bail_out;
650    }
651
652    /* See what we have for a Volume */
653    label_status = read_dev_volume_label(dcr);
654
655    /* Set new volume name */
656    dcr->setVolCatName(newname);
657    switch(label_status) {
658    case VOL_NAME_ERROR:
659    case VOL_VERSION_ERROR:
660    case VOL_LABEL_ERROR:
661    case VOL_OK:
662       if (!relabel) {
663          dir->fsend(_(
664             "3920 Cannot label Volume because it is already labeled: \"%s\"\n"),
665              dev->VolHdr.VolumeName);
666          break;
667       }
668
669       /* Relabel request. If oldname matches, continue */
670       if (strcmp(oldname, dev->VolHdr.VolumeName) != 0) {
671          dir->fsend(_("3921 Wrong volume mounted.\n"));
672          break;
673       }
674       if (dev->label_type != B_BACULA_LABEL) {
675          dir->fsend(_("3922 Cannot relabel an ANSI/IBM labeled Volume.\n"));
676          break;
677       }
678       /* Fall through wanted! */
679    case VOL_IO_ERROR:
680    case VOL_NO_LABEL:
681       if (!write_new_volume_label_to_dev(dcr, newname, poolname,
682               relabel, true /* write dvd now */)) {
683          dir->fsend(_("3912 Failed to label Volume: ERR=%s\n"), dev->bstrerror());
684          break;
685       }
686       bstrncpy(dcr->VolumeName, newname, sizeof(dcr->VolumeName));
687       /* The following 3000 OK label. string is scanned in ua_label.c */
688       int type;
689       if (dev->dev_type == B_FILE_DEV) {
690          type = dev->dev_type;
691       } else {
692          type = 0;
693       }
694       dir->fsend("3000 OK label. VolBytes=%lld VolABytes=%lld VolType=%d Volume=\"%s\" Device=%s\n",
695                  dev->VolCatInfo.VolCatBytes, dev->VolCatInfo.VolCatAdataBytes,
696                  type, newname, dev->print_name());
697       break;
698    case VOL_TYPE_ERROR:
699       dir->fsend(_("3915 Failed to label Volume: ERR=%s\n"), dev->errmsg);
700       break;
701    case VOL_NO_MEDIA:
702       dir->fsend(_("3914 Failed to label Volume (no media): ERR=%s\n"), dev->bstrerror());
703       break;
704    default:
705       dir->fsend(_("3913 Cannot label Volume. "
706                    "Unknown status %d from read_volume_label()\n"), label_status);
707       break;
708    }
709
710 bail_out:
711    if (dev->is_open() && !dev->has_cap(CAP_ALWAYSOPEN)) {
712       dev->close();
713    }
714    if (!dev->is_open()) {
715       dev->clear_volhdr();
716    }
717    volume_unused(dcr);                   /* no longer using volume */
718    give_back_device_lock(dev, &hold);
719    return;
720 }
721
722
723 /*
724  * Read the tape label
725  *
726  *  Enter with the mutex set
727  */
728 static bool read_label(DCR *dcr)
729 {
730    int ok;
731    JCR *jcr = dcr->jcr;
732    BSOCK *dir = jcr->dir_bsock;
733    bsteal_lock_t hold;
734    DEVICE *dev = dcr->dev;
735
736    steal_device_lock(dev, &hold, BST_DOING_ACQUIRE);
737
738    dcr->VolumeName[0] = 0;
739    dev->clear_labeled();              /* force read of label */
740    switch (read_dev_volume_label(dcr)) {
741    case VOL_OK:
742       dir->fsend(_("3001 Mounted Volume: %s\n"), dev->VolHdr.VolumeName);
743       ok = true;
744       break;
745    default:
746       dir->fsend(_("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
747          dev->print_name(), jcr->errmsg);
748       ok = false;
749       break;
750    }
751    volume_unused(dcr);
752    give_back_device_lock(dev, &hold);
753    return ok;
754 }
755
756 /*
757  * Searches for device by name, and if found, creates a dcr and
758  *  returns it.
759  */
760 static DCR *find_device(JCR *jcr, POOL_MEM &devname,
761                         POOLMEM *media_type, int drive)
762 {
763    DEVRES *device;
764    AUTOCHANGER *changer;
765    bool found = false;
766    DCR *dcr = NULL;
767
768    unbash_spaces(devname);
769    foreach_res(device, R_DEVICE) {
770       /* Find resource, and make sure we were able to open it */
771       if (strcmp(device->hdr.name, devname.c_str()) == 0 &&
772           (!media_type || strcmp(device->media_type, media_type) ==0)) {
773          if (!device->dev) {
774             device->dev = init_dev(jcr, device);
775          }
776          if (!device->dev) {
777             Jmsg(jcr, M_WARNING, 0, _("\n"
778                "     Device \"%s\" requested by DIR could not be opened or does not exist.\n"),
779                  devname.c_str());
780             continue;
781          }
782          Dmsg1(20, "Found device %s\n", device->hdr.name);
783          found = true;
784          break;
785       }
786    }
787    if (!found) {
788       foreach_res(changer, R_AUTOCHANGER) {
789          /* Find resource, and make sure we were able to open it */
790          if (strcmp(devname.c_str(), changer->hdr.name) == 0) {
791             /* Try each device in this AutoChanger */
792             foreach_alist(device, changer->device) {
793                Dmsg1(100, "Try changer device %s\n", device->hdr.name);
794                if (!device->dev) {
795                   device->dev = init_dev(jcr, device);
796                }
797                if (!device->dev) {
798                   Dmsg1(100, "Device %s could not be opened. Skipped\n", devname.c_str());
799                   Jmsg(jcr, M_WARNING, 0, _("\n"
800                      "     Device \"%s\" in changer \"%s\" requested by DIR could not be opened or does not exist.\n"),
801                        device->hdr.name, devname.c_str());
802                   continue;
803                }
804                if (!device->dev->autoselect) {
805                   Dmsg1(100, "Device %s not autoselect skipped.\n", devname.c_str());
806                   continue;              /* device is not available */
807                } else if (!device->dev->enabled) {
808                   Dmsg1(100, "Device %s disabled skipped.\n", devname.c_str());
809                   continue;              /* device disabled */
810                }
811                if ((drive < 0 || drive == (int)device->dev->drive_index) &&
812                    (!media_type || strcmp(device->media_type, media_type) ==0)) {
813                   Dmsg1(20, "Found changer device %s\n", device->hdr.name);
814                   found = true;
815                   break;
816                }
817                Dmsg3(100, "Device %s drive wrong: want=%d got=%d skipping\n",
818                   devname.c_str(), drive, (int)device->dev->drive_index);
819             }
820             break;                    /* we found it but could not open a device */
821          }
822       }
823    }
824
825    if (found) {
826       Dmsg1(100, "Found device %s\n", device->hdr.name);
827       dcr = new_dcr(jcr, NULL, device->dev);
828       dcr->device = device;
829    }
830    return dcr;
831 }
832
833 /*
834  * Mount command from Director
835  */
836 static bool mount_cmd(JCR *jcr)
837 {
838    POOL_MEM devname;
839    BSOCK *dir = jcr->dir_bsock;
840    DEVICE *dev;
841    DCR *dcr;
842    int32_t drive;      /* device index */
843    int32_t slot;
844    bool ok;
845
846    Dmsg1(100, "%s\n", dir->msg);
847    ok = sscanf(dir->msg, "mount %127s drive=%d slot=%d", devname.c_str(),
848                &drive, &slot) == 3;
849    if (!ok) {
850       slot = 0;
851       ok = sscanf(dir->msg, "mount %127s drive=%d", devname.c_str(), &drive) == 2;
852    }
853    Dmsg3(100, "ok=%d device_index=%d slot=%d\n", ok, drive, slot);
854    if (ok) {
855       dcr = find_device(jcr, devname, NULL, drive);
856       if (dcr) {
857          dev = dcr->dev;
858          dev->Lock();                 /* Use P to avoid indefinite block */
859          Dmsg2(100, "mount cmd blocked=%d must_unload=%d\n", dev->blocked(),
860             dev->must_unload());
861          switch (dev->blocked()) {         /* device blocked? */
862          case BST_WAITING_FOR_SYSOP:
863             /* Someone is waiting, wake him */
864             Dmsg0(100, "Waiting for mount. Attempting to wake thread\n");
865             dev->set_blocked(BST_MOUNT);
866             dir->fsend("3001 OK mount requested. %sDevice=%s\n",
867                        slot>0?_("Specified slot ignored. "):"",
868                        dev->print_name());
869             Dmsg1(100, "JobId=%u broadcast wait_next_vol\n", (uint32_t)dcr->jcr->JobId);
870             pthread_cond_broadcast(&dev->wait_next_vol);
871             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
872             pthread_cond_broadcast(&wait_device_release);
873             break;
874
875          /* In both of these two cases, we (the user) unmounted the Volume */
876          case BST_UNMOUNTED_WAITING_FOR_SYSOP:
877          case BST_UNMOUNTED:
878             Dmsg2(100, "Unmounted changer=%d slot=%d\n", dev->is_autochanger(), slot);
879             if (dev->is_autochanger() && slot > 0) {
880                try_autoload_device(jcr, dcr, slot, "");
881             }
882             /* We freed the device, so reopen it and wake any waiting threads */
883             if (!dev->open(dcr, OPEN_READ_ONLY)) {
884                dir->fsend(_("3901 Unable to open device \"%s\": ERR=%s\n"),
885                   dev->print_name(), dev->bstrerror());
886                if (dev->blocked() == BST_UNMOUNTED) {
887                   /* We blocked the device, so unblock it */
888                   Dmsg0(100, "Unmounted. Unblocking device\n");
889                   unblock_device(dev);
890                }
891                break;
892             }
893             read_dev_volume_label(dcr);
894             if (dev->blocked() == BST_UNMOUNTED) {
895                /* We blocked the device, so unblock it */
896                Dmsg0(100, "Unmounted. Unblocking device\n");
897                read_label(dcr);       /* this should not be necessary */
898                unblock_device(dev);
899             } else {
900                Dmsg0(100, "Unmounted waiting for mount. Attempting to wake thread\n");
901                dev->set_blocked(BST_MOUNT);
902             }
903             if (dev->is_labeled()) {
904                dir->fsend(_("3001 Device \"%s\" is mounted with Volume \"%s\"\n"),
905                   dev->print_name(), dev->VolHdr.VolumeName);
906             } else {
907                dir->fsend(_("3905 Device \"%s\" open but no Bacula volume is mounted.\n"
908                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
909                           dev->print_name());
910             }
911             pthread_cond_broadcast(&dev->wait_next_vol);
912             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
913             pthread_cond_broadcast(&wait_device_release);
914             break;
915
916          case BST_DOING_ACQUIRE:
917             dir->fsend(_("3001 Device \"%s\" is doing acquire.\n"),
918                        dev->print_name());
919             break;
920
921          case BST_WRITING_LABEL:
922             dir->fsend(_("3903 Device \"%s\" is being labeled.\n"),
923                dev->print_name());
924             break;
925
926          case BST_NOT_BLOCKED:
927             Dmsg2(100, "Not blocked changer=%d slot=%d\n", dev->is_autochanger(), slot);
928             if (dev->is_autochanger() && slot > 0) {
929                try_autoload_device(jcr, dcr, slot, "");
930             }
931             if (dev->is_open()) {
932                if (dev->is_labeled()) {
933                   dir->fsend(_("3001 Device \"%s\" is mounted with Volume \"%s\"\n"),
934                      dev->print_name(), dev->VolHdr.VolumeName);
935                } else {
936                   dir->fsend(_("3905 Device \"%s\" open but no Bacula volume is mounted.\n"
937                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
938                              dev->print_name());
939                }
940             } else if (dev->is_tape()) {
941                if (!dev->open(dcr, OPEN_READ_ONLY)) {
942                   dir->fsend(_("3901 Unable to open device \"%s\": ERR=%s\n"),
943                      dev->print_name(), dev->bstrerror());
944                   break;
945                }
946                read_label(dcr);
947                if (dev->is_labeled()) {
948                   dir->fsend(_("3001 Device \"%s\" is already mounted with Volume \"%s\"\n"),
949                      dev->print_name(), dev->VolHdr.VolumeName);
950                } else {
951                   dir->fsend(_("3905 Device \"%s\" open but no Bacula volume is mounted.\n"
952                                     "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
953                              dev->print_name());
954                }
955                if (dev->is_open() && !dev->has_cap(CAP_ALWAYSOPEN)) {
956                   dev->close();
957                }
958             } else if (dev->is_unmountable()) {
959                if (dev->mount(1)) {
960                   dir->fsend(_("3002 Device \"%s\" is mounted.\n"), dev->print_name());
961                } else {
962                   dir->fsend(_("3907 %s"), dev->bstrerror());
963                }
964             } else { /* must be file */
965                dir->fsend(_("3906 File device \"%s\" is always mounted.\n"),
966                   dev->print_name());
967                pthread_cond_broadcast(&dev->wait_next_vol);
968                Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
969                pthread_cond_broadcast(&wait_device_release);
970             }
971             break;
972
973          case BST_RELEASING:
974             dir->fsend(_("3930 Device \"%s\" is being released.\n"), dev->print_name());
975             break;
976
977          default:
978             dir->fsend(_("3905 Unknown wait state %d\n"), dev->blocked());
979             break;
980          }
981          dev->Unlock();
982          free_dcr(dcr);
983       } else {
984          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
985       }
986    } else {
987       pm_strcpy(jcr->errmsg, dir->msg);
988       dir->fsend(_("3909 Error scanning mount command: %s\n"), jcr->errmsg);
989    }
990    dir->signal(BNET_EOD);
991    return true;
992 }
993
994 /* enable command from Director */
995 static bool enable_cmd(JCR *jcr)
996 {
997    POOL_MEM devname;
998    BSOCK *dir = jcr->dir_bsock;
999    DEVICE *dev;
1000    DCR *dcr;
1001    int32_t drive;
1002    bool ok;
1003
1004    ok = sscanf(dir->msg, "enable %127s drive=%d", devname.c_str(),
1005                &drive) == 2;
1006    Dmsg3(100, "ok=%d device=%s device_index=%d\n", ok, devname.c_str(), drive);
1007    if (ok) {
1008       dcr = find_device(jcr, devname, NULL, drive);
1009       if (dcr) {
1010          dev = dcr->dev;
1011          dev->Lock();                 /* Use P to avoid indefinite block */
1012          dev->enabled = true;
1013          dir->fsend(_("3002 Device \"%s\" enabled.\n"), dev->print_name());
1014          dev->Unlock();
1015          free_dcr(dcr);
1016       }
1017    } else {
1018       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1019       pm_strcpy(jcr->errmsg, dir->msg);
1020       dir->fsend(_("3907 Error scanning \"enable\" command: %s\n"), jcr->errmsg);
1021    }
1022    dir->signal(BNET_EOD);
1023    return true;
1024 }
1025
1026 /* enable command from Director */
1027 static bool disable_cmd(JCR *jcr)
1028 {
1029    POOL_MEM devname;
1030    BSOCK *dir = jcr->dir_bsock;
1031    DEVICE *dev;
1032    DCR *dcr;
1033    int32_t drive;
1034    bool ok;
1035
1036    ok = sscanf(dir->msg, "disable %127s drive=%d", devname.c_str(),
1037                &drive) == 2;
1038    Dmsg3(100, "ok=%d device=%s device_index=%d\n", ok, devname.c_str(), drive);
1039    if (ok) {
1040       dcr = find_device(jcr, devname, NULL, drive);
1041       if (dcr) {
1042          dev = dcr->dev;
1043          dev->Lock();
1044          dev->enabled = false;
1045          dir->fsend(_("3002 Device \"%s\" disabled.\n"), dev->print_name());
1046          dev->Unlock();
1047          free_dcr(dcr);
1048       }
1049    } else {
1050       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1051       pm_strcpy(jcr->errmsg, dir->msg);
1052       dir->fsend(_("3907 Error scanning \"disable\" command: %s\n"), jcr->errmsg);
1053    }
1054    dir->signal(BNET_EOD);
1055    return true;
1056 }
1057
1058
1059 /*
1060  * unmount command from Director
1061  */
1062 static bool unmount_cmd(JCR *jcr)
1063 {
1064    POOL_MEM devname;
1065    BSOCK *dir = jcr->dir_bsock;
1066    DEVICE *dev;
1067    DCR *dcr;
1068    int32_t drive;
1069
1070    if (sscanf(dir->msg, "unmount %127s drive=%d", devname.c_str(), &drive) == 2) {
1071       dcr = find_device(jcr, devname, NULL, drive);
1072       if (dcr) {
1073          dev = dcr->dev;
1074          dev->Lock();                 /* Use P to avoid indefinite block */
1075          if (!dev->is_open()) {
1076             if (!dev->is_busy()) {
1077                unload_autochanger(dcr, -1);
1078             }
1079             if (dev->is_unmountable()) {
1080                if (dev->unmount(0)) {
1081                   dir->fsend(_("3002 Device \"%s\" unmounted.\n"),
1082                      dev->print_name());
1083                } else {
1084                   dir->fsend(_("3907 %s"), dev->bstrerror());
1085                }
1086             } else {
1087                Dmsg0(90, "Device already unmounted\n");
1088                dir->fsend(_("3901 Device \"%s\" is already unmounted.\n"),
1089                   dev->print_name());
1090             }
1091          } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
1092             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
1093                dev->blocked());
1094             if (!unload_autochanger(dcr, -1)) {
1095                /*
1096                 * ***FIXME**** what is this ???? -- probably we had
1097                 *   the wrong volume so we must free it and try again. KES
1098                 */
1099                dev->close();
1100                free_volume(dev);
1101             }
1102             if (dev->is_unmountable() && !dev->unmount(0)) {
1103                dir->fsend(_("3907 %s"), dev->bstrerror());
1104             } else {
1105                dev->set_blocked(BST_UNMOUNTED_WAITING_FOR_SYSOP);
1106                dir->fsend(_("3001 Device \"%s\" unmounted.\n"),
1107                   dev->print_name());
1108             }
1109
1110          } else if (dev->blocked() == BST_DOING_ACQUIRE) {
1111             dir->fsend(_("3902 Device \"%s\" is busy in acquire.\n"),
1112                dev->print_name());
1113
1114          } else if (dev->blocked() == BST_WRITING_LABEL) {
1115             dir->fsend(_("3903 Device \"%s\" is being labeled.\n"),
1116                dev->print_name());
1117
1118          } else if (dev->is_busy()) {
1119             send_dir_busy_message(dir, dev);
1120          } else {                     /* device not being used */
1121             Dmsg0(90, "Device not in use, unmounting\n");
1122             /* On FreeBSD, I am having ASSERT() failures in block_device()
1123              * and I can only imagine that the thread id that we are
1124              * leaving in no_wait_id is being re-used. So here,
1125              * we simply do it by hand.  Gross, but a solution.
1126              */
1127             /*  block_device(dev, BST_UNMOUNTED); replace with 2 lines below */
1128             dev->set_blocked(BST_UNMOUNTED);
1129             clear_thread_id(dev->no_wait_id);
1130             if (!unload_autochanger(dcr, -1)) {
1131                dev->close();
1132                free_volume(dev);
1133             }
1134             if (dev->is_unmountable() && !dev->unmount(0)) {
1135                dir->fsend(_("3907 %s"), dev->bstrerror());
1136             } else {
1137                dir->fsend(_("3002 Device \"%s\" unmounted.\n"),
1138                   dev->print_name());
1139             }
1140          }
1141          dev->Unlock();
1142          free_dcr(dcr);
1143       } else {
1144          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1145       }
1146    } else {
1147       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1148       pm_strcpy(jcr->errmsg, dir->msg);
1149       dir->fsend(_("3907 Error scanning unmount command: %s\n"), jcr->errmsg);
1150    }
1151    dir->signal(BNET_EOD);
1152    return true;
1153 }
1154
1155 #if 0
1156 /*
1157  * The truncate command will recycle a volume. The director can call this
1158  * after purging a volume so that disk space will not be wasted. Only useful
1159  * for File Storage, of course.
1160  *
1161  *
1162  * It is currently disabled
1163  */
1164 static bool action_on_purge_cmd(JCR *jcr)
1165 {
1166    BSOCK *dir = jcr->dir_bsock;
1167
1168    char devname[MAX_NAME_LENGTH];
1169    char volumename[MAX_NAME_LENGTH];
1170    int32_t action;
1171
1172    /* TODO: Need to find a free device and ask for slot to the director */
1173    if (sscanf(dir->msg,
1174               "action_on_purge %127s vol=%127s action=%d",
1175               devname, volumename, &action)!= 5)
1176    {
1177       dir->fsend(_("3916 Error scanning action_on_purge command\n"));
1178       goto done;
1179    }
1180    unbash_spaces(volumename);
1181    unbash_spaces(devname);
1182
1183    /* Check if action is correct */
1184    if (action & AOP_TRUNCTATE) {
1185
1186    }
1187    /* ... */
1188
1189 done:
1190    dir->signal(BNET_EOD);
1191    return true;
1192 }
1193 #endif
1194
1195 /*
1196  * Release command from Director. This rewinds the device and if
1197  *   configured does a offline and ensures that Bacula will
1198  *   re-read the label of the tape before continuing. This gives
1199  *   the operator the chance to change the tape anytime before the
1200  *   next job starts.
1201  */
1202 static bool release_cmd(JCR *jcr)
1203 {
1204    POOL_MEM devname;
1205    BSOCK *dir = jcr->dir_bsock;
1206    DEVICE *dev;
1207    DCR *dcr;
1208    int32_t drive;
1209
1210    if (sscanf(dir->msg, "release %127s drive=%d", devname.c_str(), &drive) == 2) {
1211       dcr = find_device(jcr, devname, NULL, drive);
1212       if (dcr) {
1213          dev = dcr->dev;
1214          dev->Lock();                 /* Use P to avoid indefinite block */
1215          if (!dev->is_open()) {
1216             if (!dev->is_busy()) {
1217                unload_autochanger(dcr, -1);
1218             }
1219             Dmsg0(90, "Device already released\n");
1220             dir->fsend(_("3921 Device \"%s\" already released.\n"),
1221                dev->print_name());
1222
1223          } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
1224             Dmsg2(90, "%d waiter dev_block=%d.\n", dev->num_waiting,
1225                dev->blocked());
1226             unload_autochanger(dcr, -1);
1227             dir->fsend(_("3922 Device \"%s\" waiting for sysop.\n"),
1228                dev->print_name());
1229
1230          } else if (dev->blocked() == BST_UNMOUNTED_WAITING_FOR_SYSOP) {
1231             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
1232                dev->blocked());
1233             dir->fsend(_("3922 Device \"%s\" waiting for mount.\n"),
1234                dev->print_name());
1235
1236          } else if (dev->blocked() == BST_DOING_ACQUIRE) {
1237             dir->fsend(_("3923 Device \"%s\" is busy in acquire.\n"),
1238                dev->print_name());
1239
1240          } else if (dev->blocked() == BST_WRITING_LABEL) {
1241             dir->fsend(_("3914 Device \"%s\" is being labeled.\n"),
1242                dev->print_name());
1243
1244          } else if (dev->is_busy()) {
1245             send_dir_busy_message(dir, dev);
1246          } else {                     /* device not being used */
1247             Dmsg0(90, "Device not in use, releasing\n");
1248             dcr->release_volume();
1249             dir->fsend(_("3022 Device \"%s\" released.\n"),
1250                dev->print_name());
1251          }
1252          dev->Unlock();
1253          free_dcr(dcr);
1254       } else {
1255          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1256       }
1257    } else {
1258       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1259       pm_strcpy(jcr->errmsg, dir->msg);
1260       dir->fsend(_("3927 Error scanning release command: %s\n"), jcr->errmsg);
1261    }
1262    dir->signal(BNET_EOD);
1263    return true;
1264 }
1265
1266 static pthread_mutex_t bsr_mutex = PTHREAD_MUTEX_INITIALIZER;
1267 static uint32_t bsr_uniq = 0;
1268
1269 static bool get_bootstrap_file(JCR *jcr, BSOCK *sock)
1270 {
1271    POOLMEM *fname = get_pool_memory(PM_FNAME);
1272    FILE *bs;
1273    bool ok = false;
1274
1275    if (jcr->RestoreBootstrap) {
1276       unlink(jcr->RestoreBootstrap);
1277       free_pool_memory(jcr->RestoreBootstrap);
1278    }
1279    P(bsr_mutex);
1280    bsr_uniq++;
1281    Mmsg(fname, "%s/%s.%s.%d.bootstrap", me->working_directory, me->hdr.name,
1282       jcr->Job, bsr_uniq);
1283    V(bsr_mutex);
1284    Dmsg1(400, "bootstrap=%s\n", fname);
1285    jcr->RestoreBootstrap = fname;
1286    bs = fopen(fname, "a+b");           /* create file */
1287    if (!bs) {
1288       berrno be;
1289       Jmsg(jcr, M_FATAL, 0, _("Could not create bootstrap file %s: ERR=%s\n"),
1290          jcr->RestoreBootstrap, be.bstrerror());
1291       goto bail_out;
1292    }
1293    Dmsg0(150, "=== Bootstrap file ===\n");
1294    while (sock->recv() >= 0) {
1295        Dmsg1(150, "%s", sock->msg);
1296        fputs(sock->msg, bs);
1297    }
1298    fclose(bs);
1299    Dmsg0(150, "=== end bootstrap file ===\n");
1300    jcr->bsr = parse_bsr(jcr, jcr->RestoreBootstrap);
1301    if (!jcr->bsr) {
1302       Jmsg(jcr, M_FATAL, 0, _("Error parsing bootstrap file.\n"));
1303       goto bail_out;
1304    }
1305    if (chk_dbglvl(150)) {
1306       dump_bsr(jcr->bsr, true);
1307    }
1308    /* If we got a bootstrap, we are reading, so create read volume list */
1309    create_restore_volume_list(jcr);
1310    ok = true;
1311
1312 bail_out:
1313    unlink(jcr->RestoreBootstrap);
1314    free_pool_memory(jcr->RestoreBootstrap);
1315    jcr->RestoreBootstrap = NULL;
1316    if (!ok) {
1317       sock->fsend(ERROR_bootstrap);
1318       return false;
1319    }
1320    return sock->fsend(OK_bootstrap);
1321 }
1322
1323 static bool bootstrap_cmd(JCR *jcr)
1324 {
1325    return get_bootstrap_file(jcr, jcr->dir_bsock);
1326 }
1327
1328 /*
1329  * Autochanger command from Director
1330  */
1331 static bool changer_cmd(JCR *jcr)
1332 {
1333    POOL_MEM devname;
1334    BSOCK *dir = jcr->dir_bsock;
1335    DEVICE *dev;
1336    DCR *dcr;
1337    const char *cmd = NULL;
1338    bool ok = false;
1339    /*
1340     * A safe_cmd may call autochanger script but does not load/unload
1341     *    slots so it can be done at the same time that the drive is open.
1342     */
1343    bool safe_cmd = false;
1344
1345    if (sscanf(dir->msg, "autochanger listall %127s", devname.c_str()) == 1) {
1346       cmd = "listall";
1347       safe_cmd = ok = true;
1348    } else if (sscanf(dir->msg, "autochanger list %127s", devname.c_str()) == 1) {
1349       cmd = "list";
1350       safe_cmd = ok = true;
1351    } else if (sscanf(dir->msg, "autochanger slots %127s", devname.c_str()) == 1) {
1352       cmd = "slots";
1353       safe_cmd = ok = true;
1354    } else if (sscanf(dir->msg, "autochanger drives %127s", devname.c_str()) == 1) {
1355       cmd = "drives";
1356       safe_cmd = ok = true;
1357    }
1358    if (ok) {
1359       dcr = find_device(jcr, devname, NULL, -1);
1360       if (dcr) {
1361          dev = dcr->dev;
1362          dev->Lock();                 /* Use P to avoid indefinite block */
1363          if (!dev->device->changer_res) {
1364             dir->fsend(_("3998 Device \"%s\" is not an autochanger.\n"),
1365                dev->print_name());
1366          /* Under certain "safe" conditions, we can steal the lock */
1367          } else if (safe_cmd || !dev->is_open() || dev->can_steal_lock()) {
1368             autochanger_cmd(dcr, dir, cmd);
1369          } else if (dev->is_busy() || dev->is_blocked()) {
1370             send_dir_busy_message(dir, dev);
1371          } else {                     /* device not being used */
1372             autochanger_cmd(dcr, dir, cmd);
1373          }
1374          dev->Unlock();
1375          free_dcr(dcr);
1376       } else {
1377          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1378       }
1379    } else {  /* error on scanf */
1380       pm_strcpy(jcr->errmsg, dir->msg);
1381       dir->fsend(_("3909 Error scanning autochanger drives/list/slots command: %s\n"),
1382          jcr->errmsg);
1383    }
1384    dir->signal(BNET_EOD);
1385    return true;
1386 }
1387
1388 /*
1389  * Read and return the Volume label
1390  */
1391 static bool readlabel_cmd(JCR *jcr)
1392 {
1393    POOL_MEM devname;
1394    BSOCK *dir = jcr->dir_bsock;
1395    DEVICE *dev;
1396    DCR *dcr;
1397    int32_t Slot, drive;
1398
1399    if (sscanf(dir->msg, "readlabel %127s Slot=%d drive=%d", devname.c_str(),
1400        &Slot, &drive) == 3) {
1401       dcr = find_device(jcr, devname, NULL, drive);
1402       if (dcr) {
1403          dev = dcr->dev;
1404          dev->Lock();                 /* Use P to avoid indefinite block */
1405          if (!dev->is_open()) {
1406             read_volume_label(jcr, dcr, dev, Slot);
1407             dev->close();
1408          /* Under certain "safe" conditions, we can steal the lock */
1409          } else if (dev->can_steal_lock()) {
1410             read_volume_label(jcr, dcr, dev, Slot);
1411          } else if (dev->is_busy() || dev->is_blocked()) {
1412             send_dir_busy_message(dir, dev);
1413          } else {                     /* device not being used */
1414             read_volume_label(jcr, dcr, dev, Slot);
1415          }
1416          dev->Unlock();
1417          free_dcr(dcr);
1418       } else {
1419          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1420       }
1421    } else {
1422       pm_strcpy(jcr->errmsg, dir->msg);
1423       dir->fsend(_("3909 Error scanning readlabel command: %s\n"), jcr->errmsg);
1424    }
1425    dir->signal(BNET_EOD);
1426    return true;
1427 }
1428
1429
1430 /*
1431  * Read the tape label
1432  *
1433  *  Enter with the mutex set
1434  */
1435 static void read_volume_label(JCR *jcr, DCR *dcr, DEVICE *dev, int Slot)
1436 {
1437    BSOCK *dir = jcr->dir_bsock;
1438    bsteal_lock_t hold;
1439
1440    dcr->set_dev(dev);
1441    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
1442
1443    if (!try_autoload_device(jcr, dcr, Slot, "")) {
1444       goto bail_out;                  /* error */
1445    }
1446
1447    dev->clear_labeled();              /* force read of label */
1448    switch (read_dev_volume_label(dcr)) {
1449    case VOL_OK:
1450       /* DO NOT add quotes around the Volume name. It is scanned in the DIR */
1451       dir->fsend(_("3001 Volume=%s Slot=%d\n"), dev->VolHdr.VolumeName, Slot);
1452       Dmsg1(100, "Volume: %s\n", dev->VolHdr.VolumeName);
1453       break;
1454    default:
1455       dir->fsend(_("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
1456                  dev->print_name(), jcr->errmsg);
1457       break;
1458    }
1459
1460 bail_out:
1461    give_back_device_lock(dev, &hold);
1462    return;
1463 }
1464
1465 static bool try_autoload_device(JCR *jcr, DCR *dcr, int slot, const char *VolName)
1466 {
1467    BSOCK *dir = jcr->dir_bsock;
1468
1469    bstrncpy(dcr->VolumeName, VolName, sizeof(dcr->VolumeName));
1470    dcr->VolCatInfo.Slot = slot;
1471    dcr->VolCatInfo.InChanger = slot > 0;
1472    if (autoload_device(dcr, 0, dir) < 0) {    /* autoload if possible */
1473       return false;
1474    }
1475    return true;
1476 }
1477
1478 static void send_dir_busy_message(BSOCK *dir, DEVICE *dev)
1479 {
1480    if (dev->is_blocked()) {
1481       switch (dev->blocked()) {
1482       case BST_UNMOUNTED:
1483          dir->fsend(_("3931 Device \"%s\" is BLOCKED. user unmounted.\n"),
1484             dev->print_name());
1485          break;
1486       case BST_UNMOUNTED_WAITING_FOR_SYSOP:
1487          dir->fsend(_("3932 Device \"%s\" is BLOCKED. user unmounted during wait for media/mount.\n"),
1488              dev->print_name());
1489          break;
1490       case BST_WAITING_FOR_SYSOP:
1491          dir->fsend(_("3933 Device \"%s\" is BLOCKED waiting for media.\n"),
1492             dev->print_name());
1493          break;
1494       case BST_DOING_ACQUIRE:
1495          dir->fsend(_("3934 Device \"%s\" is being initialized.\n"),
1496             dev->print_name());
1497          break;
1498       case BST_WRITING_LABEL:
1499          dir->fsend(_("3935 Device \"%s\" is blocked labeling a Volume.\n"),
1500             dev->print_name());
1501          break;
1502       default:
1503          dir->fsend(_("3935 Device \"%s\" is blocked for unknown reason.\n"),
1504             dev->print_name());
1505          break;
1506       }
1507    } else if (dev->can_read()) {
1508        dir->fsend(_("3936 Device \"%s\" is busy reading.\n"),
1509                    dev->print_name());;
1510    } else {
1511        dir->fsend(_("3937 Device \"%s\" is busy with writers=%d reserved=%d.\n"),
1512           dev->print_name(), dev->num_writers, dev->num_reserved());
1513    }
1514 }