]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/label.c
Change set_label() to set_labeled() -- a bit clearer
[bacula/bacula] / bacula / src / stored / label.c
1 /*
2  *
3  *  label.c  Bacula routines to handle labels
4  *
5  *   Kern Sibbald, MM
6  *
7  *
8  *   Version $Id$
9  */
10 /*
11    Copyright (C) 2000-2005 Kern Sibbald
12
13    This program is free software; you can redistribute it and/or
14    modify it under the terms of the GNU General Public License as
15    published by the Free Software Foundation; either version 2 of
16    the License, or (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21    General Public License for more details.
22
23    You should have received a copy of the GNU General Public
24    License along with this program; if not, write to the Free
25    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
26    MA 02111-1307, USA.
27
28  */
29
30 #include "bacula.h"                   /* pull in global headers */
31 #include "stored.h"                   /* pull in Storage Deamon headers */
32
33 /* Forward referenced functions */
34 static void create_volume_label_record(DCR *dcr, DEV_RECORD *rec);
35
36 extern char my_name[];
37 extern int debug_level;
38
39 /*
40  * Read the volume label
41  *
42  *  If dcr->VolumeName == NULL, we accept any Bacula Volume
43  *  If dcr->VolumeName[0] == 0, we accept any Bacula Volume
44  *  otherwise dcr->VolumeName must match the Volume.
45  *
46  *  If VolName given, ensure that it matches
47  *
48  *  Returns VOL_  code as defined in record.h
49  *    VOL_NOT_READ
50  *    VOL_OK                          good label found
51  *    VOL_NO_LABEL                    volume not labeled
52  *    VOL_IO_ERROR                    I/O error reading tape
53  *    VOL_NAME_ERROR                  label has wrong name
54  *    VOL_CREATE_ERROR                Error creating label
55  *    VOL_VERSION_ERROR               label has wrong version
56  *    VOL_LABEL_ERROR                 bad label type
57  *    VOL_NO_MEDIA                    no media in drive
58  *
59  *  The dcr block is emptied on return, and the Volume is
60  *    rewound.
61  */
62 int read_dev_volume_label(DCR *dcr)
63 {
64    JCR *jcr = dcr->jcr;
65    DEVICE *dev = dcr->dev;
66    char *VolName = dcr->VolumeName;
67    DEV_RECORD *record;
68    bool ok = false;
69    DEV_BLOCK *block = dcr->block;
70    int stat;
71    bool want_ansi_label;
72
73    Dmsg3(100, "Enter read_volume_label device=%s vol=%s dev_Vol=%s\n",
74       dev->name(), VolName, dev->VolHdr.VolName);
75
76    if (!dev->is_open()) {
77       Emsg0(M_ABORT, 0, _("BAD call to read_dev_volume_label\n"));
78    }
79    if (dev->is_labeled()) {              /* did we already read label? */
80       /* Compare Volume Names allow special wild card */
81       if (VolName && *VolName && *VolName != '*' && strcmp(dev->VolHdr.VolName, VolName) != 0) {
82          Mmsg(jcr->errmsg, _("Wrong Volume mounted on device %s: Wanted %s have %s\n"),
83             dev->print_name(), VolName, dev->VolHdr.VolName);
84          /*
85           * Cancel Job if too many label errors
86           *  => we are in a loop
87           */
88          if (!dev->poll && jcr->label_errors++ > 100) {
89             Jmsg(jcr, M_FATAL, 0, "Too many tries: %s", jcr->errmsg);
90          }
91          return VOL_NAME_ERROR;
92       }
93       Dmsg0(30, "Leave read_volume_label() VOL_OK\n");
94       return VOL_OK;       /* label already read */
95    }
96
97    dev->state &= ~(ST_LABEL|ST_APPEND|ST_READ);  /* set no label, no append */
98    dev->label_type = B_BACULA_LABEL;
99
100    if (!rewind_dev(dev)) {
101       Mmsg(jcr->errmsg, _("Couldn't rewind device %s: ERR=%s\n"), 
102          dev->print_name(), strerror_dev(dev));
103       Dmsg1(30, "%s", jcr->errmsg);
104       return VOL_NO_MEDIA;
105    }
106    bstrncpy(dev->VolHdr.Id, "**error**", sizeof(dev->VolHdr.Id));
107
108   /* Read ANSI/IBM label if so requested */
109   
110   want_ansi_label = dcr->VolCatInfo.LabelType != B_BACULA_LABEL ||
111                     dcr->device->label_type != B_BACULA_LABEL;
112   if (want_ansi_label || dev_cap(dev, CAP_CHECKLABELS)) {
113       stat = read_ansi_ibm_label(dcr);            
114       /* If we want a label and didn't find it, return error */
115       if (want_ansi_label && stat != VOL_OK) {
116          empty_block(block);
117          rewind_dev(dev);
118          return stat;
119       }
120       if (stat == VOL_NAME_ERROR || stat == VOL_LABEL_ERROR) {
121          Mmsg(jcr->errmsg, _("Wrong Volume mounted on device %s: Wanted %s have %s\n"),
122               dev->print_name(), VolName, dev->VolHdr.VolName);
123          if (!dev->poll && jcr->label_errors++ > 100) {
124             Jmsg(jcr, M_FATAL, 0, "Too many tries: %s", jcr->errmsg);
125          }
126          empty_block(block);
127          rewind_dev(dev);
128          return stat;
129       }
130       if (stat != VOL_OK) {           /* Not an ANSI/IBM label, so re-read */
131          rewind_dev(dev);
132       }
133    }
134   
135    /* Read the Bacula Volume label block */
136    record = new_record();
137    empty_block(block);
138
139    Dmsg0(90, "Big if statement in read_volume_label\n");
140    if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
141       Mmsg(jcr->errmsg, _("Requested Volume \"%s\" on %s is not a Bacula "
142            "labeled Volume, because: ERR=%s"), NPRT(VolName), 
143            dev->print_name(), strerror_dev(dev));
144       Dmsg1(30, "%s", jcr->errmsg);
145    } else if (!read_record_from_block(block, record)) {
146       Mmsg(jcr->errmsg, _("Could not read Volume label from block.\n"));
147       Dmsg1(30, "%s", jcr->errmsg);
148    } else if (!unser_volume_label(dev, record)) {
149       Mmsg(jcr->errmsg, _("Could not unserialize Volume label: ERR=%s\n"),
150          strerror_dev(dev));
151       Dmsg1(30, "%s", jcr->errmsg);
152    } else if (strcmp(dev->VolHdr.Id, BaculaId) != 0 &&
153               strcmp(dev->VolHdr.Id, OldBaculaId) != 0) {
154       Mmsg(jcr->errmsg, _("Volume Header Id bad: %s\n"), dev->VolHdr.Id);
155       Dmsg1(30, "%s", jcr->errmsg);
156    } else {
157       ok = true;
158    }
159    free_record(record);               /* finished reading Volume record */
160    empty_block(block);                /* done with block */
161
162    if (!ok) {
163       if (forge_on || jcr->ignore_label_errors) {
164          dev->set_labeled();         /* set has Bacula label */
165          Jmsg(jcr, M_ERROR, 0, "%s", jcr->errmsg);
166          return VOL_OK;
167       }
168       rewind_dev(dev);
169       return VOL_NO_LABEL;
170    }
171
172    /* At this point, we have read the first Bacula block, and
173     * then read the Bacula Volume label. Now we need to
174     * make sure we have the right Volume.
175     */
176
177    /* If we are a streaming device, we only get one chance to read */
178    if (!dev_cap(dev, CAP_STREAM)) {
179       rewind_dev(dev);
180    }
181
182    if (dev->VolHdr.VerNum != BaculaTapeVersion &&
183        dev->VolHdr.VerNum != OldCompatibleBaculaTapeVersion1 &&
184        dev->VolHdr.VerNum != OldCompatibleBaculaTapeVersion2) {
185       Mmsg(jcr->errmsg, _("Volume on %s has wrong Bacula version. Wanted %d got %d\n"),
186          dev->print_name(), BaculaTapeVersion, dev->VolHdr.VerNum);
187       Dmsg1(30, "%s", jcr->errmsg);
188       return VOL_VERSION_ERROR;
189    }
190
191    /* We are looking for either an unused Bacula tape (PRE_LABEL) or
192     * a Bacula volume label (VOL_LABEL)
193     */
194    if (dev->VolHdr.LabelType != PRE_LABEL && dev->VolHdr.LabelType != VOL_LABEL) {
195       Mmsg(jcr->errmsg, _("Volume on %s has bad Bacula label type: %x\n"),
196           dev->print_name(), dev->VolHdr.LabelType);
197       Dmsg1(30, "%s", jcr->errmsg);
198       if (!dev->poll && jcr->label_errors++ > 100) {
199          Jmsg(jcr, M_FATAL, 0, "Too many tries: %s", jcr->errmsg);
200       }
201       return VOL_LABEL_ERROR;
202    }
203
204    dev->set_labeled();               /* set has Bacula label */
205
206    /* Compare Volume Names */
207    Dmsg2(30, "Compare Vol names: VolName=%s hdr=%s\n", VolName?VolName:"*", dev->VolHdr.VolName);
208    if (VolName && *VolName && *VolName != '*' && strcmp(dev->VolHdr.VolName, VolName) != 0) {
209       Mmsg(jcr->errmsg, _("Wrong Volume mounted on device %s: Wanted %s have %s\n"),
210            dev->print_name(), VolName, dev->VolHdr.VolName);
211       Dmsg1(30, "%s", jcr->errmsg);
212       /*
213        * Cancel Job if too many label errors
214        *  => we are in a loop
215        */
216       if (!dev->poll && jcr->label_errors++ > 100) {
217          Jmsg(jcr, M_FATAL, 0, "Too many tries: %s", jcr->errmsg);
218       }
219       return VOL_NAME_ERROR;
220    }
221    Dmsg1(30, "Copy vol_name=%s\n", dev->VolHdr.VolName);
222
223    if (debug_level >= 10) {
224       dump_volume_label(dev);
225    }
226    Dmsg0(30, "Leave read_volume_label() VOL_OK\n");
227    return VOL_OK;
228 }
229
230 /* Read the volume label by guessing the volume name. (only for DVD devices)
231  * write is true if we are reading the label before writing to the device.
232  *
233  * If the volume name cannot be guessed :
234  *  Writing : returns the label of the current file (on the harddisk).
235  *  Reading : returns an error
236  */
237 int read_dev_volume_label_guess(DCR *dcr, bool write) 
238 {
239    int vol_label_status;
240    DEVICE *dev = dcr->dev;
241    JCR *jcr = dcr->jcr;
242    Dmsg3(100, "Enter read_dev_volume_label_guess device=%s vol=%s dev_Vol=%s\n",
243          dev->print_name(), dcr->VolumeName, dev->VolHdr.VolName);
244    
245    if (!dev->is_dvd()) {
246       Dmsg0(100, "Leave read_dev_volume_label_guess !CAP_REQMOUNT\n");
247       return read_dev_volume_label(dcr);
248    }
249    
250    if (!write && (dcr->VolCatInfo.VolCatParts == 0)) {
251       Dmsg0(100, "Leave read_dev_volume_label_guess !writing, and VolCatParts == 0\n");
252       return read_dev_volume_label(dcr);
253    }
254    
255    /* For mounted devices, tries to guess the volume name, and read the label if possible.
256    */
257    if (open_guess_name_dev(dev) < 0) {     
258       if (!write || dcr->VolCatInfo.VolCatParts > 0) {
259          Mmsg2(jcr->errmsg, _("Requested Volume \"%s\" on %s is not a Bacula labeled Volume."),
260                dev->print_name(), dcr->VolumeName);
261          Dmsg0(100, "Leave read_dev_volume_label_guess VOL_IO_ERROR (!open_guess_name_dev)\n");
262          return VOL_NO_LABEL;
263       }
264       
265       if (write && dev->free_space_errno < 0) {
266          Dmsg0(100, "Leave read_dev_volume_label_guess !free_space VOL_NO_MEDIA\n");
267          Mmsg2(jcr->errmsg, _("free_space error on %s. The current medium is probably not writable: ERR=%s.\n"),
268                dev->print_name(), dev->errmsg);
269          return VOL_NO_MEDIA;
270       }
271       
272       /* If we can't guess the name, and we are writing, just reopen the right file with open_first_part. */
273       if (open_first_part(dev) < 0) {
274          berrno be;
275          Mmsg2(jcr->errmsg, _("open_first_part error on %s: ERR=%s.\n"),
276                dev->print_name(), be.strerror());
277          Dmsg0(100, "Leave read_dev_volume_label_guess VOL_IO_ERROR (!open_guess_name_dev && !open_first_part)\n");
278          return VOL_IO_ERROR;
279       }
280       
281       Dmsg0(100, "Leave read_dev_volume_label_guess !open_guess_name_dev\n");
282       return read_dev_volume_label(dcr);
283    } else {
284       if (write && dcr->dev->free_space_errno < 0) {
285          Dmsg0(100, "Leave read_dev_volume_label_guess !free_space VOL_NO_MEDIA\n");
286          Mmsg2(jcr->errmsg, _("free_space error on %s. The current medium is probably not writable: ERR=%s.\n"),
287                dev->print_name(), dev->errmsg);
288          return VOL_NO_MEDIA;
289       }
290       
291       vol_label_status = read_dev_volume_label(dcr);
292
293       if (!write || dcr->VolCatInfo.VolCatParts > 0) {
294          Dmsg0(100, "Leave read_dev_volume_label_guess (open_guess_name_dev && (!write || dcr->VolCatInfo.VolCatParts > 0))\n");
295          return vol_label_status;
296       }
297       
298       if (open_first_part(dcr->dev) < 0) {
299          berrno be;
300          Mmsg2(jcr->errmsg, _("open_first_part error on %s: ERR=%s.\n"),
301                dev->print_name(), be.strerror());
302          Dmsg0(100, "Leave read_dev_volume_label_guess VOL_IO_ERROR (open_guess_name_dev && !open_first_part)\n");
303          return VOL_IO_ERROR;
304       }
305       
306       /* When writing, if the guessed volume name is no the right volume name, 
307        * report the error, otherwise, just continue with the right file.
308        */
309       if (vol_label_status != VOL_NAME_ERROR) {
310          Dmsg0(100, "Leave read_dev_volume_label_guess (open_guess_name_dev && !VOL_NAME_ERROR)\n");
311          dev->clear_labeled();   
312          return read_dev_volume_label(dcr);
313       } else {
314          Dmsg0(100, "Leave read_dev_volume_label_guess (open_guess_name_dev && VOL_NAME_ERROR)\n");
315          return vol_label_status;
316       }
317    }
318 }
319
320 /*
321  * Put a volume label into the block
322  *
323  *  Returns: false on failure
324  *           true  on success
325  */
326 bool write_volume_label_to_block(DCR *dcr)
327 {
328    DEV_RECORD rec;
329    DEVICE *dev = dcr->dev;
330    JCR *jcr = dcr->jcr;
331    DEV_BLOCK *block = dcr->block;
332
333    Dmsg0(20, "write Label in write_volume_label_to_block()\n");
334    memset(&rec, 0, sizeof(rec));
335    rec.data = get_memory(SER_LENGTH_Volume_Label);
336    empty_block(block);                /* Volume label always at beginning */
337
338    create_volume_label_record(dcr, &rec);
339
340    block->BlockNumber = 0;
341    if (!write_record_to_block(block, &rec)) {
342       free_pool_memory(rec.data);
343       Jmsg1(jcr, M_FATAL, 0, _("Cannot write Volume label to block for device %s\n"),
344          dev->print_name());
345       return false;
346    } else {
347       Dmsg1(90, "Wrote label of %d bytes to block\n", rec.data_len);
348    }
349    free_pool_memory(rec.data);
350    return true;
351 }
352
353
354 /*
355  * Write a Volume Label
356  *  !!! Note, this is ONLY used for writing
357  *            a fresh volume label.  Any data
358  *            after the label will be destroyed,
359  *            in fact, we write the label 5 times !!!!
360  *
361  *  This routine expects that open_device() was previously called.
362  *
363  *  This routine should be used only when labeling a blank tape.
364  */
365 bool write_new_volume_label_to_dev(DCR *dcr, const char *VolName, const char *PoolName)
366 {
367    DEVICE *dev = dcr->dev;
368
369
370    Dmsg0(99, "write_volume_label()\n");
371    empty_block(dcr->block);
372
373    Dmsg1(100, "Label type=%d\n", dev->label_type);
374    if (!rewind_dev(dev)) {
375       memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
376       Dmsg2(30, "Bad status on %s from rewind: ERR=%s\n", dev->print_name(), strerror_dev(dev));
377       if (!forge_on) {
378          goto bail_out;
379       }
380    }
381
382    /* Create PRE_LABEL */
383    create_volume_label(dev, VolName, PoolName);
384
385    /*
386     * If we have already detected an ANSI label, re-read it
387     *   to skip past it. Otherwise, we write a new one if 
388     *   so requested.  
389     */
390    if (dev->label_type != B_BACULA_LABEL) {
391       if (read_ansi_ibm_label(dcr) != VOL_OK) {
392          rewind_dev(dev);
393          goto bail_out;
394       }
395    } else if (!write_ansi_ibm_labels(dcr, ANSI_VOL_LABEL, VolName)) {
396       goto bail_out;
397    }
398
399    create_volume_label_record(dcr, dcr->rec);
400    dcr->rec->Stream = 0;
401
402    /* Temporarily mark in append state to enable writing */
403    dev->set_append();
404    if (!write_record_to_block(dcr->block, dcr->rec)) {
405       Dmsg2(30, "Bad Label write on %s: ERR=%s\n", dev->print_name(), strerror_dev(dev));
406       goto bail_out;
407    } else {
408       Dmsg2(30, "Wrote label of %d bytes to %s\n", dcr->rec->data_len, dev->print_name());
409    }
410
411    Dmsg0(99, "Call write_block_to_dev()\n");
412    if (!write_block_to_dev(dcr)) {
413       Dmsg2(30, "Bad Label write on %s: ERR=%s\n", dev->print_name(), strerror_dev(dev));
414       goto bail_out;
415    }
416    Dmsg0(99, " Wrote block to device\n");
417
418    if (weof_dev(dev, 1) == 0) {
419       dev->set_labeled();
420       write_ansi_ibm_labels(dcr, ANSI_EOF_LABEL, dev->VolHdr.VolName);
421    }
422
423    if (debug_level >= 20)  {
424       dump_volume_label(dev);
425    }
426    dev->clear_append();               /* remove append since this is PRE_LABEL */
427    return true;
428
429 bail_out:
430    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
431    dev->clear_append();               /* remove append since this is PRE_LABEL */
432    return false;
433 }
434
435 /*
436  * Write a volume label. This is ONLY called if we have a valid Bacula
437  *   label of type PRE_LABEL;
438  *  Returns: true if OK
439  *           false if unable to write it
440  */
441 bool rewrite_volume_label(DCR *dcr, bool recycle)
442 {
443    DEVICE *dev = dcr->dev;
444    JCR *jcr = dcr->jcr;
445
446    Dmsg1(190, "set append found freshly labeled volume. dev=%x\n", dev);
447    dev->VolHdr.LabelType = VOL_LABEL; /* set Volume label */
448    dev->set_append();
449    if (!write_volume_label_to_block(dcr)) {
450       Dmsg0(200, "Error from write volume label.\n");
451       return false;
452    }
453    /*
454     * If we are not dealing with a streaming device,
455     *  write the block now to ensure we have write permission.
456     *  It is better to find out now rather than later.
457     * We do not write the block now if this is an ANSI label. This
458     *  avoids re-writing the ANSI label, which we do not want to do.
459     */
460    if (!dev_cap(dev, CAP_STREAM)) {
461       if (!rewind_dev(dev)) {
462          Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s: ERR=%s\n"),
463                dev->print_name(), strerror_dev(dev));
464       }
465       if (recycle) {
466          if (!truncate_dev(dev)) {
467             Jmsg2(jcr, M_WARNING, 0, _("Truncate error on device %s: ERR=%s\n"),
468                   dev->print_name(), strerror_dev(dev));
469          }
470       }
471
472       /*
473        * If we have already detected an ANSI label, re-read it
474        *   to skip past it. Otherwise, we write a new one if 
475        *   so requested.  
476        */
477       if (dev->label_type != B_BACULA_LABEL) {
478          if (read_ansi_ibm_label(dcr) != VOL_OK) {
479             rewind_dev(dev);
480             return false;
481          }
482       } else if (!write_ansi_ibm_labels (dcr, ANSI_VOL_LABEL, dev->VolHdr.VolName)) {
483          return false;
484       }
485
486       /* Attempt write to check write permission */
487       Dmsg0(200, "Attempt to write to device.\n");
488       if (!write_block_to_dev(dcr)) {
489          Jmsg2(jcr, M_ERROR, 0, _("Unable to write device %s: ERR=%s\n"),
490             dev->print_name(), strerror_dev(dev));
491          Dmsg0(200, "===ERROR write block to dev\n");
492          return false;
493       }
494    }
495    /* Set or reset Volume statistics */
496    dev->VolCatInfo.VolCatJobs = 0;
497    dev->VolCatInfo.VolCatFiles = 0;
498    dev->VolCatInfo.VolCatBytes = 1;
499    dev->VolCatInfo.VolCatErrors = 0;
500    dev->VolCatInfo.VolCatBlocks = 0;
501    dev->VolCatInfo.VolCatRBytes = 0;
502    if (recycle) {
503       dev->VolCatInfo.VolCatMounts++;
504       dev->VolCatInfo.VolCatRecycles++;
505    } else {
506       dev->VolCatInfo.VolCatMounts = 1;
507       dev->VolCatInfo.VolCatRecycles = 0;
508       dev->VolCatInfo.VolCatWrites = 1;
509       dev->VolCatInfo.VolCatReads = 1;
510    }
511    Dmsg0(100, "dir_update_vol_info. Set Append\n");
512    bstrncpy(dev->VolCatInfo.VolCatStatus, "Append", sizeof(dev->VolCatInfo.VolCatStatus));
513    if (!dir_update_volume_info(dcr, true)) {  /* indicate doing relabel */
514       return false;
515    }
516    if (recycle) {
517       Jmsg(jcr, M_INFO, 0, _("Recycled volume \"%s\" on device %s, all previous data lost.\n"),
518          dcr->VolumeName, dev->print_name());
519    } else {
520       Jmsg(jcr, M_INFO, 0, _("Wrote label to prelabeled Volume \"%s\" on device %s\n"),
521          dcr->VolumeName, dev->print_name());
522    }
523    /*
524     * End writing real Volume label (from pre-labeled tape), or recycling
525     *  the volume.
526     */
527    Dmsg0(200, "OK from rewite vol label.\n");
528    return true;
529 }
530
531
532 /*
533  *  create_volume_label_record
534  *   Serialize label (from dev->VolHdr structure) into device record.
535  *   Assumes that the dev->VolHdr structure is properly
536  *   initialized.
537 */
538 static void create_volume_label_record(DCR *dcr, DEV_RECORD *rec)
539 {
540    ser_declare;
541    struct date_time dt;
542    DEVICE *dev = dcr->dev;
543    JCR *jcr = dcr->jcr;
544
545    /* Serialize the label into the device record. */
546
547    rec->data = check_pool_memory_size(rec->data, SER_LENGTH_Volume_Label);
548    ser_begin(rec->data, SER_LENGTH_Volume_Label);
549    ser_string(dev->VolHdr.Id);
550
551    ser_uint32(dev->VolHdr.VerNum);
552
553    if (dev->VolHdr.VerNum >= 11) {
554       ser_btime(dev->VolHdr.label_btime);
555       dev->VolHdr.write_btime = get_current_btime();
556       ser_btime(dev->VolHdr.write_btime);
557       dev->VolHdr.write_date = 0;
558       dev->VolHdr.write_time = 0;
559    } else {
560       /* OLD WAY DEPRECATED */
561       ser_float64(dev->VolHdr.label_date);
562       ser_float64(dev->VolHdr.label_time);
563       get_current_time(&dt);
564       dev->VolHdr.write_date = dt.julian_day_number;
565       dev->VolHdr.write_time = dt.julian_day_fraction;
566    }
567    ser_float64(dev->VolHdr.write_date);   /* 0 if VerNum >= 11 */
568    ser_float64(dev->VolHdr.write_time);   /* 0  if VerNum >= 11 */
569
570    ser_string(dev->VolHdr.VolName);
571    ser_string(dev->VolHdr.PrevVolName);
572    ser_string(dev->VolHdr.PoolName);
573    ser_string(dev->VolHdr.PoolType);
574    ser_string(dev->VolHdr.MediaType);
575
576    ser_string(dev->VolHdr.HostName);
577    ser_string(dev->VolHdr.LabelProg);
578    ser_string(dev->VolHdr.ProgVersion);
579    ser_string(dev->VolHdr.ProgDate);
580
581    ser_end(rec->data, SER_LENGTH_Volume_Label);
582    rec->data_len = ser_length(rec->data);
583    rec->FileIndex = dev->VolHdr.LabelType;
584    rec->VolSessionId = jcr->VolSessionId;
585    rec->VolSessionTime = jcr->VolSessionTime;
586    rec->Stream = jcr->NumVolumes;
587    Dmsg2(100, "Created Vol label rec: FI=%s len=%d\n", FI_to_ascii(rec->FileIndex),
588       rec->data_len);
589 }
590
591
592 /*
593  * Create a volume label in memory
594  */
595 void create_volume_label(DEVICE *dev, const char *VolName, const char *PoolName)
596 {
597    DEVRES *device = (DEVRES *)dev->device;
598
599    Dmsg0(90, "Start create_volume_label()\n");
600
601    ASSERT(dev != NULL);
602
603    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
604
605    bstrncpy(dev->VolHdr.Id, BaculaId, sizeof(dev->VolHdr.Id));
606    dev->VolHdr.VerNum = BaculaTapeVersion;
607    dev->VolHdr.LabelType = PRE_LABEL;  /* Mark tape as unused */
608    bstrncpy(dev->VolHdr.VolName, VolName, sizeof(dev->VolHdr.VolName));
609    bstrncpy(dev->VolHdr.PoolName, PoolName, sizeof(dev->VolHdr.PoolName));
610    bstrncpy(dev->VolHdr.MediaType, device->media_type, sizeof(dev->VolHdr.MediaType));
611
612    bstrncpy(dev->VolHdr.PoolType, "Backup", sizeof(dev->VolHdr.PoolType));
613
614    dev->VolHdr.label_btime = get_current_btime();
615    dev->VolHdr.label_date = 0;
616    dev->VolHdr.label_time = 0;
617
618    if (gethostname(dev->VolHdr.HostName, sizeof(dev->VolHdr.HostName)) != 0) {
619       dev->VolHdr.HostName[0] = 0;
620    }
621    bstrncpy(dev->VolHdr.LabelProg, my_name, sizeof(dev->VolHdr.LabelProg));
622    sprintf(dev->VolHdr.ProgVersion, "Ver. %s %s", VERSION, BDATE);
623    sprintf(dev->VolHdr.ProgDate, "Build %s %s", __DATE__, __TIME__);
624    dev->set_labeled();               /* set has Bacula label */
625    if (debug_level >= 90) {
626       dump_volume_label(dev);
627    }
628 }
629
630 /*
631  * Create session label
632  *  The pool memory must be released by the calling program
633  */
634 void create_session_label(DCR *dcr, DEV_RECORD *rec, int label)
635 {
636    JCR *jcr = dcr->jcr;
637    ser_declare;
638
639    rec->VolSessionId   = jcr->VolSessionId;
640    rec->VolSessionTime = jcr->VolSessionTime;
641    rec->Stream         = jcr->JobId;
642
643    rec->data = check_pool_memory_size(rec->data, SER_LENGTH_Session_Label);
644    ser_begin(rec->data, SER_LENGTH_Session_Label);
645    ser_string(BaculaId);
646    ser_uint32(BaculaTapeVersion);
647
648    ser_uint32(jcr->JobId);
649
650    /* Changed in VerNum 11 */
651    ser_btime(get_current_btime());
652    ser_float64(0);
653
654    ser_string(dcr->pool_name);
655    ser_string(dcr->pool_type);
656    ser_string(jcr->job_name);         /* base Job name */
657    ser_string(jcr->client_name);
658
659    /* Added in VerNum 10 */
660    ser_string(jcr->Job);              /* Unique name of this Job */
661    ser_string(jcr->fileset_name);
662    ser_uint32(jcr->JobType);
663    ser_uint32(jcr->JobLevel);
664    /* Added in VerNum 11 */
665    ser_string(jcr->fileset_md5);
666
667    if (label == EOS_LABEL) {
668       ser_uint32(jcr->JobFiles);
669       ser_uint64(jcr->JobBytes);
670       ser_uint32(dcr->StartBlock);
671       ser_uint32(dcr->EndBlock);
672       ser_uint32(dcr->StartFile);
673       ser_uint32(dcr->EndFile);
674       ser_uint32(jcr->JobErrors);
675
676       /* Added in VerNum 11 */
677       ser_uint32(jcr->JobStatus);
678    }
679    ser_end(rec->data, SER_LENGTH_Session_Label);
680    rec->data_len = ser_length(rec->data);
681 }
682
683 /* Write session label
684  *  Returns: false on failure
685  *           true  on success
686  */
687 bool write_session_label(DCR *dcr, int label)
688 {
689    JCR *jcr = dcr->jcr;
690    DEVICE *dev = dcr->dev;
691    DEV_RECORD *rec;
692    DEV_BLOCK *block = dcr->block;
693
694    rec = new_record();
695    Dmsg1(90, "session_label record=%x\n", rec);
696    switch (label) {
697    case SOS_LABEL:
698       if (dev->is_tape()) {
699          dcr->StartBlock = dev->block_num;
700          dcr->StartFile  = dev->file;
701       } else {
702          dcr->StartBlock = (uint32_t)dev->file_addr;
703          dcr->StartFile = (uint32_t)(dev->file_addr >> 32);
704       }
705       break;
706    case EOS_LABEL:
707       if (dev->is_tape()) {
708          dcr->EndBlock = dev->EndBlock;
709          dcr->EndFile  = dev->EndFile;
710       } else {
711          dcr->EndBlock = (uint32_t)dev->file_addr;
712          dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
713       }
714       break;
715    default:
716       Jmsg1(jcr, M_ABORT, 0, _("Bad session label = %d\n"), label);
717       break;
718    }
719    create_session_label(dcr, rec, label);
720    rec->FileIndex = label;
721
722    /*
723     * We guarantee that the session record can totally fit
724     *  into a block. If not, write the block, and put it in
725     *  the next block. Having the sesssion record totally in
726     *  one block makes reading them much easier (no need to
727     *  read the next block).
728     */
729    if (!can_write_record_to_block(block, rec)) {
730       Dmsg0(100, "Cannot write session label to block.\n");
731       if (!write_block_to_device(dcr)) {
732          Dmsg0(90, "Got session label write_block_to_dev error.\n");
733          /* ****FIXME***** errno is not set here */
734          Jmsg(jcr, M_FATAL, 0, _("Error writing Session label to %s: %s\n"),
735                            dev_vol_name(dev), strerror(errno));
736          free_record(rec);
737          return false;
738       }
739    }
740    if (!write_record_to_block(block, rec)) {
741       Jmsg(jcr, M_FATAL, 0, _("Error writing Session label to %s: %s\n"),
742                         dev_vol_name(dev), strerror(errno));
743       free_record(rec);
744       return false;
745    }
746
747    Dmsg6(20, "Write sesson_label record JobId=%d FI=%s SessId=%d Strm=%s len=%d "
748              "remainder=%d\n", jcr->JobId,
749       FI_to_ascii(rec->FileIndex), rec->VolSessionId,
750       stream_to_ascii(rec->Stream, rec->FileIndex), rec->data_len,
751       rec->remainder);
752
753    free_record(rec);
754    Dmsg2(20, "Leave write_session_label Block=%d File=%d\n",
755       dev->block_num, dev->file);
756    return true;
757 }
758
759 /*  unser_volume_label
760  *
761  * Unserialize the Bacula Volume label into the device Volume_Label
762  * structure.
763  *
764  * Assumes that the record is already read.
765  *
766  * Returns: false on error
767  *          true  on success
768 */
769
770 bool unser_volume_label(DEVICE *dev, DEV_RECORD *rec)
771 {
772    ser_declare;
773
774    if (rec->FileIndex != VOL_LABEL && rec->FileIndex != PRE_LABEL) {
775       Mmsg3(dev->errmsg, _("Expecting Volume Label, got FI=%s Stream=%s len=%d\n"),
776               FI_to_ascii(rec->FileIndex),
777               stream_to_ascii(rec->Stream, rec->FileIndex),
778               rec->data_len);
779       if (!forge_on) {
780          return false;
781       }
782    }
783
784    dev->VolHdr.LabelType = rec->FileIndex;
785    dev->VolHdr.LabelSize = rec->data_len;
786
787
788    /* Unserialize the record into the Volume Header */
789    rec->data = check_pool_memory_size(rec->data, SER_LENGTH_Volume_Label);
790    ser_begin(rec->data, SER_LENGTH_Volume_Label);
791    unser_string(dev->VolHdr.Id);
792    unser_uint32(dev->VolHdr.VerNum);
793
794    if (dev->VolHdr.VerNum >= 11) {
795       unser_btime(dev->VolHdr.label_btime);
796       unser_btime(dev->VolHdr.write_btime);
797    } else { /* old way */
798       unser_float64(dev->VolHdr.label_date);
799       unser_float64(dev->VolHdr.label_time);
800    }
801    unser_float64(dev->VolHdr.write_date);    /* Unused with VerNum >= 11 */
802    unser_float64(dev->VolHdr.write_time);    /* Unused with VerNum >= 11 */
803
804    unser_string(dev->VolHdr.VolName);
805    unser_string(dev->VolHdr.PrevVolName);
806    unser_string(dev->VolHdr.PoolName);
807    unser_string(dev->VolHdr.PoolType);
808    unser_string(dev->VolHdr.MediaType);
809
810    unser_string(dev->VolHdr.HostName);
811    unser_string(dev->VolHdr.LabelProg);
812    unser_string(dev->VolHdr.ProgVersion);
813    unser_string(dev->VolHdr.ProgDate);
814
815    ser_end(rec->data, SER_LENGTH_Volume_Label);
816    Dmsg0(90, "ser_read_vol\n");
817    if (debug_level >= 90) {
818       dump_volume_label(dev);
819    }
820    return true;
821 }
822
823
824 bool unser_session_label(SESSION_LABEL *label, DEV_RECORD *rec)
825 {
826    ser_declare;
827
828    rec->data = check_pool_memory_size(rec->data, SER_LENGTH_Session_Label);
829    unser_begin(rec->data, SER_LENGTH_Session_Label);
830    unser_string(label->Id);
831    unser_uint32(label->VerNum);
832    unser_uint32(label->JobId);
833    if (label->VerNum >= 11) {
834       unser_btime(label->write_btime);
835    } else {
836       unser_float64(label->write_date);
837    }
838    unser_float64(label->write_time);
839    unser_string(label->PoolName);
840    unser_string(label->PoolType);
841    unser_string(label->JobName);
842    unser_string(label->ClientName);
843    if (label->VerNum >= 10) {
844       unser_string(label->Job);          /* Unique name of this Job */
845       unser_string(label->FileSetName);
846       unser_uint32(label->JobType);
847       unser_uint32(label->JobLevel);
848    }
849    if (label->VerNum >= 11) {
850       unser_string(label->FileSetMD5);
851    } else {
852       label->FileSetMD5[0] = 0;
853    }
854    if (rec->FileIndex == EOS_LABEL) {
855       unser_uint32(label->JobFiles);
856       unser_uint64(label->JobBytes);
857       unser_uint32(label->StartBlock);
858       unser_uint32(label->EndBlock);
859       unser_uint32(label->StartFile);
860       unser_uint32(label->EndFile);
861       unser_uint32(label->JobErrors);
862       if (label->VerNum >= 11) {
863          unser_uint32(label->JobStatus);
864       } else {
865          label->JobStatus = JS_Terminated; /* kludge */
866       }
867    }
868    return true;
869 }
870
871 void dump_volume_label(DEVICE *dev)
872 {
873    int dbl = debug_level;
874    uint32_t File;
875    const char *LabelType;
876    char buf[30];
877    struct tm tm;
878    struct date_time dt;
879
880    debug_level = 1;
881    File = dev->file;
882    switch (dev->VolHdr.LabelType) {
883    case PRE_LABEL:
884       LabelType = "PRE_LABEL";
885       break;
886    case VOL_LABEL:
887       LabelType = "VOL_LABEL";
888       break;
889    case EOM_LABEL:
890       LabelType = "EOM_LABEL";
891       break;
892    case SOS_LABEL:
893       LabelType = "SOS_LABEL";
894       break;
895    case EOS_LABEL:
896       LabelType = "EOS_LABEL";
897       break;
898    case EOT_LABEL:
899       goto bail_out;
900    default:
901       LabelType = buf;
902       sprintf(buf, "Unknown %d", dev->VolHdr.LabelType);
903       break;
904    }
905
906    Pmsg11(-1, "\nVolume Label:\n"
907 "Id                : %s"
908 "VerNo             : %d\n"
909 "VolName           : %s\n"
910 "PrevVolName       : %s\n"
911 "VolFile           : %d\n"
912 "LabelType         : %s\n"
913 "LabelSize         : %d\n"
914 "PoolName          : %s\n"
915 "MediaType         : %s\n"
916 "PoolType          : %s\n"
917 "HostName          : %s\n"
918 "",
919              dev->VolHdr.Id, dev->VolHdr.VerNum,
920              dev->VolHdr.VolName, dev->VolHdr.PrevVolName,
921              File, LabelType, dev->VolHdr.LabelSize,
922              dev->VolHdr.PoolName, dev->VolHdr.MediaType,
923              dev->VolHdr.PoolType, dev->VolHdr.HostName);
924
925    if (dev->VolHdr.VerNum >= 11) {
926       char dt[50];
927       bstrftime(dt, sizeof(dt), btime_to_unix(dev->VolHdr.label_btime));
928       Pmsg1(-1, "Date label written: %s\n", dt);
929    } else {
930    dt.julian_day_number   = dev->VolHdr.label_date;
931    dt.julian_day_fraction = dev->VolHdr.label_time;
932    tm_decode(&dt, &tm);
933    Pmsg5(-1,
934 "Date label written: %04d-%02d-%02d at %02d:%02d\n",
935       tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min);
936    }
937
938 bail_out:
939    debug_level = dbl;
940 }
941
942
943 static void dump_session_label(DEV_RECORD *rec, const char *type)
944 {
945    int dbl;
946    struct date_time dt;
947    struct tm tm;
948    SESSION_LABEL label;
949    char ec1[30], ec2[30], ec3[30], ec4[30], ec5[30], ec6[30], ec7[30];
950
951    unser_session_label(&label, rec);
952    dbl = debug_level;
953    debug_level = 1;
954    Pmsg7(-1, "\n%s Record:\n"
955 "JobId             : %d\n"
956 "VerNum            : %d\n"
957 "PoolName          : %s\n"
958 "PoolType          : %s\n"
959 "JobName           : %s\n"
960 "ClientName        : %s\n"
961 "",    type, label.JobId, label.VerNum,
962       label.PoolName, label.PoolType,
963       label.JobName, label.ClientName);
964
965    if (label.VerNum >= 10) {
966       Pmsg4(-1, ""
967 "Job (unique name) : %s\n"
968 "FileSet           : %s\n"
969 "JobType           : %c\n"
970 "JobLevel          : %c\n"
971 "", label.Job, label.FileSetName, label.JobType, label.JobLevel);
972    }
973
974    if (rec->FileIndex == EOS_LABEL) {
975       Pmsg8(-1, ""
976 "JobFiles          : %s\n"
977 "JobBytes          : %s\n"
978 "StartBlock        : %s\n"
979 "EndBlock          : %s\n"
980 "StartFile         : %s\n"
981 "EndFile           : %s\n"
982 "JobErrors         : %s\n"
983 "JobStatus         : %c\n"
984 "",
985          edit_uint64_with_commas(label.JobFiles, ec1),
986          edit_uint64_with_commas(label.JobBytes, ec2),
987          edit_uint64_with_commas(label.StartBlock, ec3),
988          edit_uint64_with_commas(label.EndBlock, ec4),
989          edit_uint64_with_commas(label.StartFile, ec5),
990          edit_uint64_with_commas(label.EndFile, ec6),
991          edit_uint64_with_commas(label.JobErrors, ec7),
992          label.JobStatus);
993    }
994    if (label.VerNum >= 11) {
995       char dt[50];
996       bstrftime(dt, sizeof(dt), btime_to_unix(label.write_btime));
997       Pmsg1(-1, _("Date written      : %s\n"), dt);
998    } else {
999       dt.julian_day_number   = label.write_date;
1000       dt.julian_day_fraction = label.write_time;
1001       tm_decode(&dt, &tm);
1002       Pmsg5(-1, _(""
1003 "Date written      : %04d-%02d-%02d at %02d:%02d\n"),
1004       tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min);
1005    }
1006
1007    debug_level = dbl;
1008 }
1009
1010 void dump_label_record(DEVICE *dev, DEV_RECORD *rec, int verbose)
1011 {
1012    const char *type;
1013    int dbl;
1014
1015    dbl = debug_level;
1016    debug_level = 1;
1017    switch (rec->FileIndex) {
1018    case PRE_LABEL:
1019       type = _("Fresh Volume");
1020       break;
1021    case VOL_LABEL:
1022       type = _("Volume");
1023       break;
1024    case SOS_LABEL:
1025       type = _("Begin Job Session");
1026       break;
1027    case EOS_LABEL:
1028       type = _("End Job Session");
1029       break;
1030    case EOM_LABEL:
1031       type = _("End of Media");
1032       break;
1033    case EOT_LABEL:
1034       type = ("End of Tape");
1035       break;
1036    default:
1037       type = _("Unknown");
1038       break;
1039    }
1040    if (verbose) {
1041       switch (rec->FileIndex) {
1042       case PRE_LABEL:
1043       case VOL_LABEL:
1044          unser_volume_label(dev, rec);
1045          dump_volume_label(dev);
1046          break;
1047       case SOS_LABEL:
1048          dump_session_label(rec, type);
1049          break;
1050       case EOS_LABEL:
1051          dump_session_label(rec, type);
1052          break;
1053       case EOM_LABEL:
1054          Pmsg5(-1, "%s Record: SessId=%d SessTime=%d JobId=%d DataLen=%d\n",
1055             type, rec->VolSessionId, rec->VolSessionTime, rec->Stream, rec->data_len);
1056          break;
1057       case EOT_LABEL:
1058          Pmsg0(-1, _("End of physical tape.\n"));
1059          break;
1060       default:
1061          Pmsg5(-1, "%s Record: SessId=%d SessTime=%d JobId=%d DataLen=%d\n",
1062             type, rec->VolSessionId, rec->VolSessionTime, rec->Stream, rec->data_len);
1063          break;
1064       }
1065    } else {
1066       SESSION_LABEL label;
1067       switch (rec->FileIndex) {
1068       case SOS_LABEL:
1069          unser_session_label(&label, rec);
1070          Pmsg6(-1, "%s Record: SessId=%d SessTime=%d JobId=%d Level=%c Type=%c\n",
1071             type, rec->VolSessionId, rec->VolSessionTime, rec->Stream,
1072             label.JobLevel, label.JobType);
1073          break;
1074       case EOS_LABEL:
1075          char ed1[30], ed2[30];
1076          unser_session_label(&label, rec);
1077          Pmsg6(-1, "%s Record: SessId=%d SessTime=%d JobId=%d Level=%c Type=%c\n",
1078             type, rec->VolSessionId, rec->VolSessionTime, rec->Stream,
1079             label.JobLevel, label.JobType);
1080          Pmsg4(-1, "   Files=%s Bytes=%s Errors=%d Status=%c\n",
1081             edit_uint64_with_commas(label.JobFiles, ed1),
1082             edit_uint64_with_commas(label.JobBytes, ed2),
1083             label.JobErrors, (char)label.JobStatus);
1084          break;
1085       case EOM_LABEL:
1086       case PRE_LABEL:
1087       case VOL_LABEL:
1088       default:
1089          Pmsg5(-1, "%s Record: SessId=%d SessTime=%d JobId=%d DataLen=%d\n",
1090       type, rec->VolSessionId, rec->VolSessionTime, rec->Stream, rec->data_len);
1091          break;
1092       case EOT_LABEL:
1093          break;
1094       }
1095    }
1096    debug_level = dbl;
1097 }