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