]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dircmd.c
abf9f1a990751d22243ff3db3118ad4b71ad36cf
[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 = NULL;;
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          uint32_t max_jobs;
576          dev = dcr->dev;
577          ok = true;
578          dev->Lock();                 /* Use P to avoid indefinite block */
579          max_jobs = dev->max_concurrent_jobs;
580          dev->max_concurrent_jobs = 1;
581          bstrncpy(dcr->VolumeName, newname, sizeof(dcr->VolumeName));
582          if (dcr->can_i_write_volume()) {
583             if (reserve_volume(dcr, newname) == NULL) {
584                ok = false;
585             }
586             Dmsg1(000, "Reserved volume \"%s\"\n", newname);
587          } else {
588             ok = false;
589          }
590          if (!ok) {
591             Dmsg2(000, "Reserve error on volume \"%s\": ERR=%s\n", newname, jcr->errmsg);
592             dir->fsend(_("3908 Error reserving volume: %s\n"), jcr->errmsg);
593             dev->max_concurrent_jobs = max_jobs;
594             dev->Unlock();
595             goto bail_out;
596          }
597          if (!dev->is_open() && !dev->is_busy()) {
598             Dmsg1(400, "Can %slabel. Device is not open\n", relabel?"re":"");
599             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
600             dev->close();
601          /* Under certain "safe" conditions, we can steal the lock */
602          } else if (dev->can_steal_lock()) {
603             Dmsg0(400, "Can relabel. can_steal_lock\n");
604             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
605          } else if (dev->is_busy() || dev->is_blocked()) {
606             send_dir_busy_message(dir, dev);
607          } else {                     /* device not being used */
608             Dmsg0(400, "Can relabel. device not used\n");
609             label_volume_if_ok(dcr, oldname, newname, poolname, slot, relabel);
610          }
611          dev->max_concurrent_jobs = max_jobs;
612          volume_unused(dcr);
613          dev->Unlock();
614       } else {
615          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), dev_name.c_str());
616       }
617    } else {
618       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
619       pm_strcpy(jcr->errmsg, dir->msg);
620       dir->fsend(_("3903 Error scanning label command: %s\n"), jcr->errmsg);
621    }
622 bail_out:
623    if (dcr) {
624       free_dcr(dcr);
625    }
626    free_memory(oldname);
627    free_memory(newname);
628    free_memory(poolname);
629    free_memory(mtype);
630    dir->signal(BNET_EOD);
631    return true;
632 }
633
634 /*
635  * Read the tape label and determine if we can safely
636  * label the tape (not a Bacula volume), then label it.
637  *
638  *  Enter with the mutex set
639  */
640 static void label_volume_if_ok(DCR *dcr, char *oldname,
641                                char *newname, char *poolname,
642                                int slot, int relabel)
643 {
644    BSOCK *dir = dcr->jcr->dir_bsock;
645    bsteal_lock_t hold;
646    DEVICE *dev = dcr->dev;
647    int label_status;
648    int mode;
649    const char *volname = (relabel == 1) ? oldname : newname;
650
651    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
652    Dmsg1(100, "Stole device %s lock, writing label.\n", dev->print_name());
653
654    Dmsg0(90, "try_autoload_device - looking for volume_info\n");
655    if (!try_autoload_device(dcr->jcr, dcr, slot, volname)) {
656       goto bail_out;                  /* error */
657    }
658
659    /* Ensure that the device is open -- autoload_device() closes it */
660    if (dev->is_tape()) {
661       mode = OPEN_READ_WRITE;
662    } else {
663       mode = CREATE_READ_WRITE;
664    }
665
666    if (relabel) {
667       dev->truncating = true;         /* let open() know we will truncate it */
668    }
669    /* Set old volume name for open if relabeling */
670    dcr->setVolCatName(volname);
671    if (!dev->open(dcr, mode)) {
672       dir->fsend(_("3910 Unable to open device \"%s\": ERR=%s\n"),
673          dev->print_name(), dev->bstrerror());
674       goto bail_out;
675    }
676
677    /* See what we have for a Volume */
678    label_status = read_dev_volume_label(dcr);
679
680    /* Set new volume name */
681    dcr->setVolCatName(newname);
682    switch(label_status) {
683    case VOL_NAME_ERROR:
684    case VOL_VERSION_ERROR:
685    case VOL_LABEL_ERROR:
686    case VOL_OK:
687       if (!relabel) {
688          dir->fsend(_(
689             "3920 Cannot label Volume because it is already labeled: \"%s\"\n"),
690              dev->VolHdr.VolumeName);
691          break;
692       }
693
694       /* Relabel request. If oldname matches, continue */
695       if (strcmp(oldname, dev->VolHdr.VolumeName) != 0) {
696          dir->fsend(_("3921 Wrong volume mounted.\n"));
697          break;
698       }
699       if (dev->label_type != B_BACULA_LABEL) {
700          dir->fsend(_("3922 Cannot relabel an ANSI/IBM labeled Volume.\n"));
701          break;
702       }
703       /* Fall through wanted! */
704    case VOL_IO_ERROR:
705    case VOL_NO_LABEL:
706       if (!write_new_volume_label_to_dev(dcr, newname, poolname,
707               relabel, true /* write dvd now */)) {
708          dir->fsend(_("3912 Failed to label Volume: ERR=%s\n"), dcr->jcr->errmsg);
709          break;
710       }
711       bstrncpy(dcr->VolumeName, newname, sizeof(dcr->VolumeName));
712       /* The following 3000 OK label. string is scanned in ua_label.c */
713       int type;
714       if (dev->dev_type == B_FILE_DEV) {
715          type = dev->dev_type;
716       } else {
717          type = 0;
718       }
719       dir->fsend("3000 OK label. VolBytes=%lld VolABytes=%lld VolType=%d Volume=\"%s\" Device=%s\n",
720                  dev->VolCatInfo.VolCatBytes, dev->VolCatInfo.VolCatAdataBytes,
721                  type, newname, dev->print_name());
722       break;
723    case VOL_TYPE_ERROR:
724       dir->fsend(_("3912 Failed to label Volume: ERR=%s\n"), dcr->jcr->errmsg);
725       break;
726    case VOL_NO_MEDIA:
727       dir->fsend(_("3914 Failed to label Volume (no media): ERR=%s\n"), dcr->jcr->errmsg);
728       break;
729    default:
730       dir->fsend(_("3913 Cannot label Volume. "
731                    "Unknown status %d from read_volume_label()\n"), label_status);
732       break;
733    }
734
735 bail_out:
736    if (dev->is_open() && !dev->has_cap(CAP_ALWAYSOPEN)) {
737       dev->close();
738    }
739    if (!dev->is_open()) {
740       dev->clear_volhdr();
741    }
742    volume_unused(dcr);                   /* no longer using volume */
743    give_back_device_lock(dev, &hold);
744    return;
745 }
746
747
748 /*
749  * Read the tape label
750  *
751  *  Enter with the mutex set
752  */
753 static bool read_label(DCR *dcr)
754 {
755    int ok;
756    JCR *jcr = dcr->jcr;
757    BSOCK *dir = jcr->dir_bsock;
758    bsteal_lock_t hold;
759    DEVICE *dev = dcr->dev;
760
761    steal_device_lock(dev, &hold, BST_DOING_ACQUIRE);
762
763    dcr->VolumeName[0] = 0;
764    dev->clear_labeled();              /* force read of label */
765    switch (read_dev_volume_label(dcr)) {
766    case VOL_OK:
767       dir->fsend(_("3001 Mounted Volume: %s\n"), dev->VolHdr.VolumeName);
768       ok = true;
769       break;
770    default:
771       dir->fsend(_("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
772          dev->print_name(), jcr->errmsg);
773       ok = false;
774       break;
775    }
776    volume_unused(dcr);
777    give_back_device_lock(dev, &hold);
778    return ok;
779 }
780
781 /*
782  * Searches for device by name, and if found, creates a dcr and
783  *  returns it.
784  */
785 static DCR *find_device(JCR *jcr, POOL_MEM &devname,
786                         POOLMEM *media_type, int drive)
787 {
788    DEVRES *device;
789    AUTOCHANGER *changer;
790    bool found = false;
791    DCR *dcr = NULL;
792
793    unbash_spaces(devname);
794    foreach_res(device, R_DEVICE) {
795       /* Find resource, and make sure we were able to open it */
796       if (strcmp(device->hdr.name, devname.c_str()) == 0 &&
797           (!media_type || strcmp(device->media_type, media_type) ==0)) {
798          if (!device->dev) {
799             device->dev = init_dev(jcr, device);
800          }
801          if (!device->dev) {
802             Jmsg(jcr, M_WARNING, 0, _("\n"
803                "     Device \"%s\" requested by DIR could not be opened or does not exist.\n"),
804                  devname.c_str());
805             continue;
806          }
807          Dmsg1(20, "Found device %s\n", device->hdr.name);
808          found = true;
809          break;
810       }
811    }
812    if (!found) {
813       foreach_res(changer, R_AUTOCHANGER) {
814          /* Find resource, and make sure we were able to open it */
815          if (strcmp(devname.c_str(), changer->hdr.name) == 0) {
816             /* Try each device in this AutoChanger */
817             foreach_alist(device, changer->device) {
818                Dmsg1(100, "Try changer device %s\n", device->hdr.name);
819                if (!device->dev) {
820                   device->dev = init_dev(jcr, device);
821                }
822                if (!device->dev) {
823                   Dmsg1(100, "Device %s could not be opened. Skipped\n", devname.c_str());
824                   Jmsg(jcr, M_WARNING, 0, _("\n"
825                      "     Device \"%s\" in changer \"%s\" requested by DIR could not be opened or does not exist.\n"),
826                        device->hdr.name, devname.c_str());
827                   continue;
828                }
829                if (!device->dev->autoselect) {
830                   Dmsg1(100, "Device %s not autoselect skipped.\n", devname.c_str());
831                   continue;              /* device is not available */
832                } else if (!device->dev->enabled) {
833                   Dmsg1(100, "Device %s disabled skipped.\n", devname.c_str());
834                   continue;              /* device disabled */
835                }
836                if ((drive < 0 || drive == (int)device->dev->drive_index) &&
837                    (!media_type || strcmp(device->media_type, media_type) ==0)) {
838                   Dmsg1(20, "Found changer device %s\n", device->hdr.name);
839                   found = true;
840                   break;
841                }
842                Dmsg3(100, "Device %s drive wrong: want=%d got=%d skipping\n",
843                   devname.c_str(), drive, (int)device->dev->drive_index);
844             }
845             break;                    /* we found it but could not open a device */
846          }
847       }
848    }
849
850    if (found) {
851       Dmsg1(100, "Found device %s\n", device->hdr.name);
852       dcr = new_dcr(jcr, NULL, device->dev);
853       dcr->device = device;
854    }
855    return dcr;
856 }
857
858 /*
859  * Mount command from Director
860  */
861 static bool mount_cmd(JCR *jcr)
862 {
863    POOL_MEM devname;
864    BSOCK *dir = jcr->dir_bsock;
865    DEVICE *dev;
866    DCR *dcr;
867    int32_t drive;      /* device index */
868    int32_t slot;
869    bool ok;
870
871    Dmsg1(100, "%s\n", dir->msg);
872    ok = sscanf(dir->msg, "mount %127s drive=%d slot=%d", devname.c_str(),
873                &drive, &slot) == 3;
874    if (!ok) {
875       slot = 0;
876       ok = sscanf(dir->msg, "mount %127s drive=%d", devname.c_str(), &drive) == 2;
877    }
878    Dmsg3(100, "ok=%d device_index=%d slot=%d\n", ok, drive, slot);
879    if (ok) {
880       dcr = find_device(jcr, devname, NULL, drive);
881       if (dcr) {
882          dev = dcr->dev;
883          dev->Lock();                 /* Use P to avoid indefinite block */
884          Dmsg2(100, "mount cmd blocked=%d must_unload=%d\n", dev->blocked(),
885             dev->must_unload());
886          switch (dev->blocked()) {         /* device blocked? */
887          case BST_WAITING_FOR_SYSOP:
888             /* Someone is waiting, wake him */
889             Dmsg0(100, "Waiting for mount. Attempting to wake thread\n");
890             dev->set_blocked(BST_MOUNT);
891             dir->fsend("3001 OK mount requested. %sDevice=%s\n",
892                        slot>0?_("Specified slot ignored. "):"",
893                        dev->print_name());
894             Dmsg1(100, "JobId=%u broadcast wait_next_vol\n", (uint32_t)dcr->jcr->JobId);
895             pthread_cond_broadcast(&dev->wait_next_vol);
896             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
897             pthread_cond_broadcast(&wait_device_release);
898             break;
899
900          /* In both of these two cases, we (the user) unmounted the Volume */
901          case BST_UNMOUNTED_WAITING_FOR_SYSOP:
902          case BST_UNMOUNTED:
903             Dmsg2(100, "Unmounted changer=%d slot=%d\n", dev->is_autochanger(), slot);
904             if (dev->is_autochanger() && slot > 0) {
905                try_autoload_device(jcr, dcr, slot, "");
906             }
907             /* We freed the device, so reopen it and wake any waiting threads */
908             if (!dev->open(dcr, OPEN_READ_ONLY)) {
909                dir->fsend(_("3901 Unable to open device \"%s\": ERR=%s\n"),
910                   dev->print_name(), dev->bstrerror());
911                if (dev->blocked() == BST_UNMOUNTED) {
912                   /* We blocked the device, so unblock it */
913                   Dmsg0(100, "Unmounted. Unblocking device\n");
914                   unblock_device(dev);
915                }
916                break;
917             }
918             read_dev_volume_label(dcr);
919             if (dev->blocked() == BST_UNMOUNTED) {
920                /* We blocked the device, so unblock it */
921                Dmsg0(100, "Unmounted. Unblocking device\n");
922                read_label(dcr);       /* this should not be necessary */
923                unblock_device(dev);
924             } else {
925                Dmsg0(100, "Unmounted waiting for mount. Attempting to wake thread\n");
926                dev->set_blocked(BST_MOUNT);
927             }
928             if (dev->is_labeled()) {
929                dir->fsend(_("3001 Device \"%s\" is mounted with Volume \"%s\"\n"),
930                   dev->print_name(), dev->VolHdr.VolumeName);
931             } else {
932                dir->fsend(_("3905 Device \"%s\" open but no Bacula volume is mounted.\n"
933                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
934                           dev->print_name());
935             }
936             pthread_cond_broadcast(&dev->wait_next_vol);
937             Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
938             pthread_cond_broadcast(&wait_device_release);
939             break;
940
941          case BST_DOING_ACQUIRE:
942             dir->fsend(_("3001 Device \"%s\" is doing acquire.\n"),
943                        dev->print_name());
944             break;
945
946          case BST_WRITING_LABEL:
947             dir->fsend(_("3903 Device \"%s\" is being labeled.\n"),
948                dev->print_name());
949             break;
950
951          case BST_NOT_BLOCKED:
952             Dmsg2(100, "Not blocked changer=%d slot=%d\n", dev->is_autochanger(), slot);
953             if (dev->is_autochanger() && slot > 0) {
954                try_autoload_device(jcr, dcr, slot, "");
955             }
956             if (dev->is_open()) {
957                if (dev->is_labeled()) {
958                   dir->fsend(_("3001 Device \"%s\" is mounted with Volume \"%s\"\n"),
959                      dev->print_name(), dev->VolHdr.VolumeName);
960                } else {
961                   dir->fsend(_("3905 Device \"%s\" open but no Bacula volume is mounted.\n"
962                                  "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
963                              dev->print_name());
964                }
965             } else if (dev->is_tape()) {
966                if (!dev->open(dcr, OPEN_READ_ONLY)) {
967                   dir->fsend(_("3901 Unable to open device \"%s\": ERR=%s\n"),
968                      dev->print_name(), dev->bstrerror());
969                   break;
970                }
971                read_label(dcr);
972                if (dev->is_labeled()) {
973                   dir->fsend(_("3001 Device \"%s\" is already mounted with Volume \"%s\"\n"),
974                      dev->print_name(), dev->VolHdr.VolumeName);
975                } else {
976                   dir->fsend(_("3905 Device \"%s\" open but no Bacula volume is mounted.\n"
977                                     "If this is not a blank tape, try unmounting and remounting the Volume.\n"),
978                              dev->print_name());
979                }
980                if (dev->is_open() && !dev->has_cap(CAP_ALWAYSOPEN)) {
981                   dev->close();
982                }
983             } else if (dev->is_unmountable()) {
984                if (dev->mount(1)) {
985                   dir->fsend(_("3002 Device \"%s\" is mounted.\n"), dev->print_name());
986                } else {
987                   dir->fsend(_("3907 %s"), dev->bstrerror());
988                }
989             } else { /* must be file */
990                dir->fsend(_("3906 File device \"%s\" is always mounted.\n"),
991                   dev->print_name());
992                pthread_cond_broadcast(&dev->wait_next_vol);
993                Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)dcr->jcr->JobId);
994                pthread_cond_broadcast(&wait_device_release);
995             }
996             break;
997
998          case BST_RELEASING:
999             dir->fsend(_("3930 Device \"%s\" is being released.\n"), dev->print_name());
1000             break;
1001
1002          default:
1003             dir->fsend(_("3905 Unknown wait state %d\n"), dev->blocked());
1004             break;
1005          }
1006          dev->Unlock();
1007          free_dcr(dcr);
1008       } else {
1009          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1010       }
1011    } else {
1012       pm_strcpy(jcr->errmsg, dir->msg);
1013       dir->fsend(_("3909 Error scanning mount command: %s\n"), jcr->errmsg);
1014    }
1015    dir->signal(BNET_EOD);
1016    return true;
1017 }
1018
1019 /* enable command from Director */
1020 static bool enable_cmd(JCR *jcr)
1021 {
1022    POOL_MEM devname;
1023    BSOCK *dir = jcr->dir_bsock;
1024    DEVICE *dev;
1025    DCR *dcr;
1026    int32_t drive;
1027    bool ok;
1028
1029    ok = sscanf(dir->msg, "enable %127s drive=%d", devname.c_str(),
1030                &drive) == 2;
1031    Dmsg3(100, "ok=%d device=%s device_index=%d\n", ok, devname.c_str(), drive);
1032    if (ok) {
1033       dcr = find_device(jcr, devname, NULL, drive);
1034       if (dcr) {
1035          dev = dcr->dev;
1036          dev->Lock();                 /* Use P to avoid indefinite block */
1037          dev->enabled = true;
1038          dir->fsend(_("3002 Device \"%s\" enabled.\n"), dev->print_name());
1039          dev->Unlock();
1040          free_dcr(dcr);
1041       }
1042    } else {
1043       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1044       pm_strcpy(jcr->errmsg, dir->msg);
1045       dir->fsend(_("3907 Error scanning \"enable\" command: %s\n"), jcr->errmsg);
1046    }
1047    dir->signal(BNET_EOD);
1048    return true;
1049 }
1050
1051 /* enable command from Director */
1052 static bool disable_cmd(JCR *jcr)
1053 {
1054    POOL_MEM devname;
1055    BSOCK *dir = jcr->dir_bsock;
1056    DEVICE *dev;
1057    DCR *dcr;
1058    int32_t drive;
1059    bool ok;
1060
1061    ok = sscanf(dir->msg, "disable %127s drive=%d", devname.c_str(),
1062                &drive) == 2;
1063    Dmsg3(100, "ok=%d device=%s device_index=%d\n", ok, devname.c_str(), drive);
1064    if (ok) {
1065       dcr = find_device(jcr, devname, NULL, drive);
1066       if (dcr) {
1067          dev = dcr->dev;
1068          dev->Lock();
1069          dev->enabled = false;
1070          dir->fsend(_("3002 Device \"%s\" disabled.\n"), dev->print_name());
1071          dev->Unlock();
1072          free_dcr(dcr);
1073       }
1074    } else {
1075       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1076       pm_strcpy(jcr->errmsg, dir->msg);
1077       dir->fsend(_("3907 Error scanning \"disable\" command: %s\n"), jcr->errmsg);
1078    }
1079    dir->signal(BNET_EOD);
1080    return true;
1081 }
1082
1083
1084 /*
1085  * unmount command from Director
1086  */
1087 static bool unmount_cmd(JCR *jcr)
1088 {
1089    POOL_MEM devname;
1090    BSOCK *dir = jcr->dir_bsock;
1091    DEVICE *dev;
1092    DCR *dcr;
1093    int32_t drive;
1094
1095    if (sscanf(dir->msg, "unmount %127s drive=%d", devname.c_str(), &drive) == 2) {
1096       dcr = find_device(jcr, devname, NULL, drive);
1097       if (dcr) {
1098          dev = dcr->dev;
1099          dev->Lock();                 /* Use P to avoid indefinite block */
1100          if (!dev->is_open()) {
1101             if (!dev->is_busy()) {
1102                unload_autochanger(dcr, -1);
1103             }
1104             if (dev->is_unmountable()) {
1105                if (dev->unmount(0)) {
1106                   dir->fsend(_("3002 Device \"%s\" unmounted.\n"),
1107                      dev->print_name());
1108                } else {
1109                   dir->fsend(_("3907 %s"), dev->bstrerror());
1110                }
1111             } else {
1112                Dmsg0(90, "Device already unmounted\n");
1113                dir->fsend(_("3901 Device \"%s\" is already unmounted.\n"),
1114                   dev->print_name());
1115             }
1116          } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
1117             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
1118                dev->blocked());
1119             if (!unload_autochanger(dcr, -1)) {
1120                /*
1121                 * ***FIXME**** what is this ???? -- probably we had
1122                 *   the wrong volume so we must free it and try again. KES
1123                 */
1124                dev->close();
1125                free_volume(dev);
1126             }
1127             if (dev->is_unmountable() && !dev->unmount(0)) {
1128                dir->fsend(_("3907 %s"), dev->bstrerror());
1129             } else {
1130                dev->set_blocked(BST_UNMOUNTED_WAITING_FOR_SYSOP);
1131                dir->fsend(_("3001 Device \"%s\" unmounted.\n"),
1132                   dev->print_name());
1133             }
1134
1135          } else if (dev->blocked() == BST_DOING_ACQUIRE) {
1136             dir->fsend(_("3902 Device \"%s\" is busy in acquire.\n"),
1137                dev->print_name());
1138
1139          } else if (dev->blocked() == BST_WRITING_LABEL) {
1140             dir->fsend(_("3903 Device \"%s\" is being labeled.\n"),
1141                dev->print_name());
1142
1143          } else if (dev->is_busy()) {
1144             send_dir_busy_message(dir, dev);
1145          } else {                     /* device not being used */
1146             Dmsg0(90, "Device not in use, unmounting\n");
1147             /* On FreeBSD, I am having ASSERT() failures in block_device()
1148              * and I can only imagine that the thread id that we are
1149              * leaving in no_wait_id is being re-used. So here,
1150              * we simply do it by hand.  Gross, but a solution.
1151              */
1152             /*  block_device(dev, BST_UNMOUNTED); replace with 2 lines below */
1153             dev->set_blocked(BST_UNMOUNTED);
1154             clear_thread_id(dev->no_wait_id);
1155             if (!unload_autochanger(dcr, -1)) {
1156                dev->close();
1157                free_volume(dev);
1158             }
1159             if (dev->is_unmountable() && !dev->unmount(0)) {
1160                dir->fsend(_("3907 %s"), dev->bstrerror());
1161             } else {
1162                dir->fsend(_("3002 Device \"%s\" unmounted.\n"),
1163                   dev->print_name());
1164             }
1165          }
1166          dev->Unlock();
1167          free_dcr(dcr);
1168       } else {
1169          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1170       }
1171    } else {
1172       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1173       pm_strcpy(jcr->errmsg, dir->msg);
1174       dir->fsend(_("3907 Error scanning unmount command: %s\n"), jcr->errmsg);
1175    }
1176    dir->signal(BNET_EOD);
1177    return true;
1178 }
1179
1180 #if 0
1181 /*
1182  * The truncate command will recycle a volume. The director can call this
1183  * after purging a volume so that disk space will not be wasted. Only useful
1184  * for File Storage, of course.
1185  *
1186  *
1187  * It is currently disabled
1188  */
1189 static bool action_on_purge_cmd(JCR *jcr)
1190 {
1191    BSOCK *dir = jcr->dir_bsock;
1192
1193    char devname[MAX_NAME_LENGTH];
1194    char volumename[MAX_NAME_LENGTH];
1195    int32_t action;
1196
1197    /* TODO: Need to find a free device and ask for slot to the director */
1198    if (sscanf(dir->msg,
1199               "action_on_purge %127s vol=%127s action=%d",
1200               devname, volumename, &action)!= 5)
1201    {
1202       dir->fsend(_("3916 Error scanning action_on_purge command\n"));
1203       goto done;
1204    }
1205    unbash_spaces(volumename);
1206    unbash_spaces(devname);
1207
1208    /* Check if action is correct */
1209    if (action & AOP_TRUNCTATE) {
1210
1211    }
1212    /* ... */
1213
1214 done:
1215    dir->signal(BNET_EOD);
1216    return true;
1217 }
1218 #endif
1219
1220 /*
1221  * Release command from Director. This rewinds the device and if
1222  *   configured does a offline and ensures that Bacula will
1223  *   re-read the label of the tape before continuing. This gives
1224  *   the operator the chance to change the tape anytime before the
1225  *   next job starts.
1226  */
1227 static bool release_cmd(JCR *jcr)
1228 {
1229    POOL_MEM devname;
1230    BSOCK *dir = jcr->dir_bsock;
1231    DEVICE *dev;
1232    DCR *dcr;
1233    int32_t drive;
1234
1235    if (sscanf(dir->msg, "release %127s drive=%d", devname.c_str(), &drive) == 2) {
1236       dcr = find_device(jcr, devname, NULL, drive);
1237       if (dcr) {
1238          dev = dcr->dev;
1239          dev->Lock();                 /* Use P to avoid indefinite block */
1240          if (!dev->is_open()) {
1241             if (!dev->is_busy()) {
1242                unload_autochanger(dcr, -1);
1243             }
1244             Dmsg0(90, "Device already released\n");
1245             dir->fsend(_("3921 Device \"%s\" already released.\n"),
1246                dev->print_name());
1247
1248          } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
1249             Dmsg2(90, "%d waiter dev_block=%d.\n", dev->num_waiting,
1250                dev->blocked());
1251             unload_autochanger(dcr, -1);
1252             dir->fsend(_("3922 Device \"%s\" waiting for sysop.\n"),
1253                dev->print_name());
1254
1255          } else if (dev->blocked() == BST_UNMOUNTED_WAITING_FOR_SYSOP) {
1256             Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
1257                dev->blocked());
1258             dir->fsend(_("3922 Device \"%s\" waiting for mount.\n"),
1259                dev->print_name());
1260
1261          } else if (dev->blocked() == BST_DOING_ACQUIRE) {
1262             dir->fsend(_("3923 Device \"%s\" is busy in acquire.\n"),
1263                dev->print_name());
1264
1265          } else if (dev->blocked() == BST_WRITING_LABEL) {
1266             dir->fsend(_("3914 Device \"%s\" is being labeled.\n"),
1267                dev->print_name());
1268
1269          } else if (dev->is_busy()) {
1270             send_dir_busy_message(dir, dev);
1271          } else {                     /* device not being used */
1272             Dmsg0(90, "Device not in use, releasing\n");
1273             dcr->release_volume();
1274             dir->fsend(_("3022 Device \"%s\" released.\n"),
1275                dev->print_name());
1276          }
1277          dev->Unlock();
1278          free_dcr(dcr);
1279       } else {
1280          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1281       }
1282    } else {
1283       /* NB dir->msg gets clobbered in bnet_fsend, so save command */
1284       pm_strcpy(jcr->errmsg, dir->msg);
1285       dir->fsend(_("3927 Error scanning release command: %s\n"), jcr->errmsg);
1286    }
1287    dir->signal(BNET_EOD);
1288    return true;
1289 }
1290
1291 static pthread_mutex_t bsr_mutex = PTHREAD_MUTEX_INITIALIZER;
1292 static uint32_t bsr_uniq = 0;
1293
1294 static bool get_bootstrap_file(JCR *jcr, BSOCK *sock)
1295 {
1296    POOLMEM *fname = get_pool_memory(PM_FNAME);
1297    FILE *bs;
1298    bool ok = false;
1299
1300    if (jcr->RestoreBootstrap) {
1301       unlink(jcr->RestoreBootstrap);
1302       free_pool_memory(jcr->RestoreBootstrap);
1303    }
1304    P(bsr_mutex);
1305    bsr_uniq++;
1306    Mmsg(fname, "%s/%s.%s.%d.bootstrap", me->working_directory, me->hdr.name,
1307       jcr->Job, bsr_uniq);
1308    V(bsr_mutex);
1309    Dmsg1(400, "bootstrap=%s\n", fname);
1310    jcr->RestoreBootstrap = fname;
1311    bs = fopen(fname, "a+b");           /* create file */
1312    if (!bs) {
1313       berrno be;
1314       Jmsg(jcr, M_FATAL, 0, _("Could not create bootstrap file %s: ERR=%s\n"),
1315          jcr->RestoreBootstrap, be.bstrerror());
1316       goto bail_out;
1317    }
1318    Dmsg0(150, "=== Bootstrap file ===\n");
1319    while (sock->recv() >= 0) {
1320        Dmsg1(150, "%s", sock->msg);
1321        fputs(sock->msg, bs);
1322    }
1323    fclose(bs);
1324    Dmsg0(150, "=== end bootstrap file ===\n");
1325    jcr->bsr = parse_bsr(jcr, jcr->RestoreBootstrap);
1326    if (!jcr->bsr) {
1327       Jmsg(jcr, M_FATAL, 0, _("Error parsing bootstrap file.\n"));
1328       goto bail_out;
1329    }
1330    if (chk_dbglvl(150)) {
1331       dump_bsr(jcr->bsr, true);
1332    }
1333    /* If we got a bootstrap, we are reading, so create read volume list */
1334    create_restore_volume_list(jcr);
1335    ok = true;
1336
1337 bail_out:
1338    unlink(jcr->RestoreBootstrap);
1339    free_pool_memory(jcr->RestoreBootstrap);
1340    jcr->RestoreBootstrap = NULL;
1341    if (!ok) {
1342       sock->fsend(ERROR_bootstrap);
1343       return false;
1344    }
1345    return sock->fsend(OK_bootstrap);
1346 }
1347
1348 static bool bootstrap_cmd(JCR *jcr)
1349 {
1350    return get_bootstrap_file(jcr, jcr->dir_bsock);
1351 }
1352
1353 /*
1354  * Autochanger command from Director
1355  */
1356 static bool changer_cmd(JCR *jcr)
1357 {
1358    POOL_MEM devname;
1359    BSOCK *dir = jcr->dir_bsock;
1360    DEVICE *dev;
1361    DCR *dcr;
1362    const char *cmd = NULL;
1363    bool ok = false;
1364    /*
1365     * A safe_cmd may call autochanger script but does not load/unload
1366     *    slots so it can be done at the same time that the drive is open.
1367     */
1368    bool safe_cmd = false;
1369
1370    if (sscanf(dir->msg, "autochanger listall %127s", devname.c_str()) == 1) {
1371       cmd = "listall";
1372       safe_cmd = ok = true;
1373    } else if (sscanf(dir->msg, "autochanger list %127s", devname.c_str()) == 1) {
1374       cmd = "list";
1375       safe_cmd = ok = true;
1376    } else if (sscanf(dir->msg, "autochanger slots %127s", devname.c_str()) == 1) {
1377       cmd = "slots";
1378       safe_cmd = ok = true;
1379    } else if (sscanf(dir->msg, "autochanger drives %127s", devname.c_str()) == 1) {
1380       cmd = "drives";
1381       safe_cmd = ok = true;
1382    }
1383    if (ok) {
1384       dcr = find_device(jcr, devname, NULL, -1);
1385       if (dcr) {
1386          dev = dcr->dev;
1387          dev->Lock();                 /* Use P to avoid indefinite block */
1388          if (!dev->device->changer_res) {
1389             dir->fsend(_("3998 Device \"%s\" is not an autochanger.\n"),
1390                dev->print_name());
1391          /* Under certain "safe" conditions, we can steal the lock */
1392          } else if (safe_cmd || !dev->is_open() || dev->can_steal_lock()) {
1393             autochanger_cmd(dcr, dir, cmd);
1394          } else if (dev->is_busy() || dev->is_blocked()) {
1395             send_dir_busy_message(dir, dev);
1396          } else {                     /* device not being used */
1397             autochanger_cmd(dcr, dir, cmd);
1398          }
1399          dev->Unlock();
1400          free_dcr(dcr);
1401       } else {
1402          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1403       }
1404    } else {  /* error on scanf */
1405       pm_strcpy(jcr->errmsg, dir->msg);
1406       dir->fsend(_("3909 Error scanning autochanger drives/list/slots command: %s\n"),
1407          jcr->errmsg);
1408    }
1409    dir->signal(BNET_EOD);
1410    return true;
1411 }
1412
1413 /*
1414  * Read and return the Volume label
1415  */
1416 static bool readlabel_cmd(JCR *jcr)
1417 {
1418    POOL_MEM devname;
1419    BSOCK *dir = jcr->dir_bsock;
1420    DEVICE *dev;
1421    DCR *dcr;
1422    int32_t Slot, drive;
1423
1424    if (sscanf(dir->msg, "readlabel %127s Slot=%d drive=%d", devname.c_str(),
1425        &Slot, &drive) == 3) {
1426       dcr = find_device(jcr, devname, NULL, drive);
1427       if (dcr) {
1428          dev = dcr->dev;
1429          dev->Lock();                 /* Use P to avoid indefinite block */
1430          if (!dev->is_open()) {
1431             read_volume_label(jcr, dcr, dev, Slot);
1432             dev->close();
1433          /* Under certain "safe" conditions, we can steal the lock */
1434          } else if (dev->can_steal_lock()) {
1435             read_volume_label(jcr, dcr, dev, Slot);
1436          } else if (dev->is_busy() || dev->is_blocked()) {
1437             send_dir_busy_message(dir, dev);
1438          } else {                     /* device not being used */
1439             read_volume_label(jcr, dcr, dev, Slot);
1440          }
1441          dev->Unlock();
1442          free_dcr(dcr);
1443       } else {
1444          dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"), devname.c_str());
1445       }
1446    } else {
1447       pm_strcpy(jcr->errmsg, dir->msg);
1448       dir->fsend(_("3909 Error scanning readlabel command: %s\n"), jcr->errmsg);
1449    }
1450    dir->signal(BNET_EOD);
1451    return true;
1452 }
1453
1454
1455 /*
1456  * Read the tape label
1457  *
1458  *  Enter with the mutex set
1459  */
1460 static void read_volume_label(JCR *jcr, DCR *dcr, DEVICE *dev, int Slot)
1461 {
1462    BSOCK *dir = jcr->dir_bsock;
1463    bsteal_lock_t hold;
1464
1465    dcr->set_dev(dev);
1466    steal_device_lock(dev, &hold, BST_WRITING_LABEL);
1467
1468    if (!try_autoload_device(jcr, dcr, Slot, "")) {
1469       goto bail_out;                  /* error */
1470    }
1471
1472    dev->clear_labeled();              /* force read of label */
1473    switch (read_dev_volume_label(dcr)) {
1474    case VOL_OK:
1475       /* DO NOT add quotes around the Volume name. It is scanned in the DIR */
1476       dir->fsend(_("3001 Volume=%s Slot=%d\n"), dev->VolHdr.VolumeName, Slot);
1477       Dmsg1(100, "Volume: %s\n", dev->VolHdr.VolumeName);
1478       break;
1479    default:
1480       dir->fsend(_("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
1481                  dev->print_name(), jcr->errmsg);
1482       break;
1483    }
1484
1485 bail_out:
1486    give_back_device_lock(dev, &hold);
1487    return;
1488 }
1489
1490 static bool try_autoload_device(JCR *jcr, DCR *dcr, int slot, const char *VolName)
1491 {
1492    BSOCK *dir = jcr->dir_bsock;
1493
1494    bstrncpy(dcr->VolumeName, VolName, sizeof(dcr->VolumeName));
1495    dcr->VolCatInfo.Slot = slot;
1496    dcr->VolCatInfo.InChanger = slot > 0;
1497    if (autoload_device(dcr, 0, dir) < 0) {    /* autoload if possible */
1498       return false;
1499    }
1500    return true;
1501 }
1502
1503 static void send_dir_busy_message(BSOCK *dir, DEVICE *dev)
1504 {
1505    if (dev->is_blocked()) {
1506       switch (dev->blocked()) {
1507       case BST_UNMOUNTED:
1508          dir->fsend(_("3931 Device \"%s\" is BLOCKED. user unmounted.\n"),
1509             dev->print_name());
1510          break;
1511       case BST_UNMOUNTED_WAITING_FOR_SYSOP:
1512          dir->fsend(_("3932 Device \"%s\" is BLOCKED. user unmounted during wait for media/mount.\n"),
1513              dev->print_name());
1514          break;
1515       case BST_WAITING_FOR_SYSOP:
1516          dir->fsend(_("3933 Device \"%s\" is BLOCKED waiting for media.\n"),
1517             dev->print_name());
1518          break;
1519       case BST_DOING_ACQUIRE:
1520          dir->fsend(_("3934 Device \"%s\" is being initialized.\n"),
1521             dev->print_name());
1522          break;
1523       case BST_WRITING_LABEL:
1524          dir->fsend(_("3935 Device \"%s\" is blocked labeling a Volume.\n"),
1525             dev->print_name());
1526          break;
1527       default:
1528          dir->fsend(_("3935 Device \"%s\" is blocked for unknown reason.\n"),
1529             dev->print_name());
1530          break;
1531       }
1532    } else if (dev->can_read()) {
1533        dir->fsend(_("3936 Device \"%s\" is busy reading.\n"),
1534                    dev->print_name());;
1535    } else {
1536        dir->fsend(_("3937 Device \"%s\" is busy with writers=%d reserved=%d.\n"),
1537           dev->print_name(), dev->num_writers, dev->num_reserved());
1538    }
1539 }