source: branches/3.1/mondo/src/common/libmondo-stream.c @ 2937

Last change on this file since 2937 was 2937, checked in by Bruno Cornec, 9 years ago

svn merge -r 2849:2935 ../3.0

  • Adds 3 binaries called potentially by udev o support USB key mount at restore time (Victor Gattegno)
  • mindi only sets the boot flag of a USB device if none is present already (should avoid flip/flop situation)
  • Fix a compatibility bug in analyze-my-lvm whete exclude lists with '|' was incorrectly analyzed (' ' still expected)
  • Precise that -J is not supported by mondorestore yet.
  • Fix a compatibility bug in mindi where exclude lists with '|' was incorrectly analyzed (' ' still expected)
  • Install an MBR on USB devices when possible
  • Improve error message in case mondorestore isn't found
  • Adds support for more virtio devices for KVM restore
  • Improve mbr.bin handling
  • Fix an issue in test of FindKernel? for Xen and non Xen cases
    • Fix #492 by removing an extra useless fi
    • Move fvat nd fat modules to CDROM_MODS in order to have them in the initrd to support saving logs to a USB device e.g.
    • Fix an error when dmidecode reports comments before system name
    • Fix previous broken patch on comment management for bkphw
    • Improve msgs printed during kbd analysis
    • Fix a small remaining pb with new comment support
    • Try to again improve the mount/umount stuff in mondo -Adds mention to OEL, CentOS, ScientifLinux? as RHEL clones
  • Fix a panadoid_free done on the wrong variable (solve a memory leak)
  • Solve #495 by skipping the potential (auto-read-only) when analyzin /proc/mdstat result
  • Fix some markup in man pages
  • adds the post-nuke script sample for Debian (Guillaume Pernot/Andrée? Leidenfrost)
  • Avoid a useless umount when changing of afio set, let insist_on_cd check and perform if needed
  • Copy everything under .ssh of root account to allow for sshfs mount without passwd at restore time.
  • Adds support for bnx2i driver
  • Try to fix #496 by supporting the protocol in the output of the mount command (sshfs#...)
  • Uses the -d option of the mount command to avoid leaving loop devices in use. Probably provoked by the usage of a more recent busybox, but anyway that option doesn't hurt, and does nothing for non-loop devices. Should fix the problems reported on the ML with NFS and more than 8 ISO images (8 being the default number of loop devices available)
  • Attempt to fix #436 by adding some newtDrawForm where appropriate.
  • Fix bugs in the kernel detection routine of mindi (some echo were done without capturing their output, confusing the return). This should also help the Xen detection issue
  • Change the logging function to be nearer from 2.2.10, and start using some
  • Initialize some global fields with an empty string, now that newt Draws more regularly progress forms
  • Mindi progression still not good, but showing now 3% when calling mindi. Would need a specific handling for the progress bar to evolve more afterwards
  • Add compatibility with the latest SSSTK + PSP content for HP ProLiant? + branding homogeneous now. We only take conrep out of the SSSTK pending a package availability. Using hpacuscripting now. Review of parameters called following test made.
  • Fix #501 by pushing BOOT_SIZE to 36864 for certain Ubuntu cases
  • Fix some remaining inconsistencis in the ProLiant? HW backup. ready for usage.
  • Fix an issue on udevadm call (needs an intermediate variable)
  • Fix a remaining ProLiant? tool call
  • Remove again some wrong variable initialization for Net in order to not have strange messages now we call Draw more often
  • Adds support for hwaddr (MAC addresses) at restore time, and map to the correct NIC if it's found at restore time (based on code from Stefan Heijmans)
  • Try to Fix #499 by changing init in order to never exit, and rebooting using sysrq in /proc (not portable). Maybe should move to using a real init, and a separated rcS script.
  • Fixes the shell msg error by using setsid as per Busybox FAQ
  • Fix #491 by correctly checking Xen kernel used for a dom0 env (apollo13)
  • Improves logging in Die()
  • Improve again ProLiant? HW support, by adding references to the yet to come SSSTK rpm so that conrep is called at its future right place.
  • Improve mindi support for kernel 3.x
  • Fix #499 for good, by using a real init from busybox and moving our init script to etc/init.d/rcS. We also now call the reboot from busybox to exit, which indeed reset the system correctly (in a VM at least which wasn't the case before). Reauires a new mindi-busybox as well.
  • Attempt to solve #503 by handling /lib64 separately for udev and only if not a link (to /lib) for Ubuntu 64
  • Improve again previous tests for bug #503
  • Improve -d option description for NFS
  • Allow http download for ftp content
  • New italian mirror
  • Fix #505 by documenting environment variables
    • Fix a bug where on OBDR mode compression was turned off to create the OBDR content but not back on (report from the mailing list)
  • solve http://trac.mondorescue.org/ticket/520 by Victor Gattegno
  • Fix #524 as option -U needs a size also
  • Removes useless gendf option
  • Fix #511 now stabgrub is called also after conf file modifications
  • Adds support for SUID binaries
  • remove a useless xenkernelname variable from mindi
  • Should fix #512 by clearing old scratchdir before changing to a new
  • Simplify the function engaging SCSI for Smart Array controllers, and support as many controller as we have
  • Add some binaries used on SLES 10 by udev
  • Fix a syntax issue in newt-specific.c
  • Fix a memory free bug where a used variable was freed to early
  • Fix a memory free bug where a used variable was misused in asprintf/free
  • Fix #498 by using an external program (hpsa_obdr_mode) which can set the mode of the tape to CD-ROM or Sequential at will.

That program will have to be downloaded from http://cciss.sf.net

  • Adds support for the route command in mindi-busybox
  • Force block size back to 32768 in OBDR mode after skipping the 2 tape marks, to read the additional rootfs data corerctly - Fix #498 for good it seems
  • Adds support for a new pata_atiixp driver
  • Fix #525 and improve printing when no /etc/raidtab, but still md devices
  • Exclude /run similarly to /sys and /proc
  • Fix a bug in mindi when having multiple swap partiions with same starting string (/dev/dm-1 and /dev/dm-16). We now add a space in the grep to avoid mischoice.
  • Fix grub installation if we had to go in the hack part which wasn't using the correct variables to make decisions !
  • Remove all mention of mondorescue.com from code
  • Fix some website typo on the download page and precise that we now develop on Mageia
  • Exclude sysfs devpts and tmpfs partitions found in RHEL 6.2 from analyze by mindi (made error messages)
  • Force activation of first partition which should not be optional as everything is destroyed before
  • Fix a bug in analyze-my-lvm where LVs were created in random order (the one of lvscan) instead of using the dm-xxx order, which creates issues at restore time between the mapping created then and the one we had at backup time which could be inconssistent

-mondoarchive now exists if the mt command is missing when needed

  • Proper fix for analyze-my-lvm
  • Fix #500 and #473 by adding support of old metadata format for mdadm if using grub < 0.9x or lilo on a md boot device (to be tested)
  • Really never inject or eject when the -e option is passed or device is inappropriate (USB, Net, ...)
  • Fix #577 by having factor back as a float (not a long ! it's a decimal value) and making the appropriate cast.
  • Fix #578 by improving the regexp used for CD/DVD detection with -scanbus option
  • Adds more verbosity when LVM creation fails.
  • Fix #579 by checking with pipes on both sides of the string
  • debugfs should be excluded from the device considered for fstab analysis
  • Property svn:keywords set to Id
File size: 50.2 KB
Line 
1/* libmondo-stream.c
2   $Id: libmondo-stream.c 2937 2012-01-28 00:51:28Z bruno $
3
4...tools for talking to tapes, Monitas streams, etc.
5
6*/
7
8
9/**
10 * @file
11 * Functions for writing data to/reading data from streams (tape, CD stream, etc.)
12 */
13
14#include "my-stuff.h"
15#include "mr_mem.h"
16#include "mondostructures.h"
17#include "libmondo-devices.h"
18#include "lib-common-externs.h"
19#include "libmondo-stream.h"
20#include "libmondo-string-EXT.h"
21#include "libmondo-files-EXT.h"
22#include "libmondo-gui-EXT.h"
23#include "libmondo-fork-EXT.h"
24#include "libmondo-tools-EXT.h"
25#include "libmondo-fifo-EXT.h"
26
27#define EXTRA_TAPE_CHECKSUMS
28#define STR_HEADER  "Mondolicious, baby"
29
30/*@unused@*/
31//static char cvsid[] = "$Id: libmondo-stream.c 2937 2012-01-28 00:51:28Z bruno $";
32extern bool g_sigpipe;
33extern int g_tape_buffer_size_MB;
34
35extern char *g_getfacl;
36extern char *g_getfattr;
37extern char *MONDO_LOGFILE;
38
39/* Reference to global bkpinfo */
40extern struct s_bkpinfo *bkpinfo;
41
42/**
43 * @addtogroup globalGroup
44 * @{
45 */
46/**
47 * The file pointer for the opened tape/CD stream.
48 * Opened and closed by openin_tape(), openin_cdstream(),
49 * openout_tape(), openout_cdstream(), closein_tape(), closein_cdstream(),
50 * closeout_tape(), and closeout_cdstream().
51 */
52FILE *g_tape_stream = NULL;
53
54
55/**
56 * The position (in kilobytes) where we are on the tape.
57 */
58long long g_tape_posK = 0;
59
60/**
61 * The current media number we're using. This value is 1-based.
62 */
63int g_current_media_number = -1;
64
65/**
66 * The tape catalog that keeps track of files written to tape.
67 */
68struct s_tapecatalog *g_tapecatalog;
69
70/* @} - end of globalGroup */
71
72int write_backcatalog_to_tape();
73
74
75
76
77
78/**
79 * @addtogroup streamGroup
80 * @{
81 */
82/**
83 * Close the global output file descriptor which Mondo has used to read
84 * from the CD stream.
85 * @param bkpinfo The backup information structure. Passed directly to closein_tape().
86 * @return 0 for success, nonzero for failure.
87 * @note This should be called by restore processes only.
88 */
89int closein_cdstream()
90{
91    return (closein_tape());
92}
93
94
95/**
96 * Close the global output file descriptor which Mondo has used to read
97 * from buffer or dd, which read from the tape.
98 * @param bkpinfo The backup information structure. Unused.
99 * @return 0 for success, nonzero for failure.
100 * @note This should be called by restore processes only.
101 * @note This function also works for cdstreams for now, but don't count on this behavior.
102 * @bug @p bkpinfo parameter is unused.
103 */
104int closein_tape()
105{
106    /*@ int's ******************************************************* */
107    int retval = 0;
108    int res = 0;
109    int ctrl_chr = '\0';
110
111    /*@ buffers ***************************************************** */
112    char fname[MAX_STR_LEN];
113
114    /*@ long long's ************************************************* */
115    long long size;
116    char *blk;
117    int i;
118
119    blk = (char *) malloc(256 * 1024);
120
121    log_it("closein_tape() -- entering");
122    res = read_header_block_from_stream(&size, fname, &ctrl_chr);
123    retval += res;
124    if (ctrl_chr != BLK_END_OF_BACKUP) {
125        wrong_marker(BLK_END_OF_BACKUP, ctrl_chr);
126    }
127    res = read_header_block_from_stream(&size, fname, &ctrl_chr);
128    retval += res;
129    if (ctrl_chr != BLK_END_OF_TAPE) {
130        wrong_marker(BLK_END_OF_TAPE, ctrl_chr);
131    }
132    for (i = 0; i < 8 && !feof(g_tape_stream); i++) {
133        (void) fread(blk, 1, 256 * 1024, g_tape_stream);
134    }
135    sleep(1);
136    sync();
137    sleep(1);
138    paranoid_pclose(g_tape_stream);
139    log_it("closein_tape() -- leaving");
140    if (!bkpinfo->please_dont_eject) {
141        eject_device(bkpinfo->media_device);
142    }
143    paranoid_free(blk);
144    paranoid_free(g_tapecatalog);
145    return (retval);
146}
147
148
149
150/**
151 * Close the global output file descriptor which Mondo has been using to write
152 * to the tape device (via buffer or dd).
153 * @param bkpinfo The backup information structure. @c bkpinfo->media_size is the only field used.
154 * @return 0 for success, nonzero for failure.
155 * @note This should be called by backup processes only.
156 */
157int closeout_tape()
158{
159    /*@ int's ******************************************************* */
160    int retval = 0;
161//  int res = 0;
162//  int ctrl_chr = '\0';
163
164    /*@ buffers ***************************************************** */
165//  char fname[MAX_STR_LEN];
166
167    /*@ long long's ************************************************* */
168//  long long size;
169    int i;
170    char *blk;
171
172    blk = (char *) malloc(256 * 1024);
173
174    sleep(1);
175    sync();
176    sleep(1);
177    log_it("closeout_tape() -- entering");
178    retval +=
179        write_header_block_to_stream((off_t)0, "end-of-backup",
180                                     BLK_END_OF_BACKUP);
181    retval += write_header_block_to_stream((off_t)0, "end-of-tape", BLK_END_OF_TAPE);   /* just in case */
182/* write 1MB of crap */
183    for (i = 0; i < 256 * 1024; i++) {
184        blk[i] = (int) (random() & 0xFF);
185    }
186    for (i = 0; i < 4 * 8; i++) {
187        (void) fwrite(blk, 1, 256 * 1024, g_tape_stream);
188        if (should_we_write_to_next_tape
189            (bkpinfo->media_size[g_current_media_number], (off_t)256 * 1024)) {
190            start_to_write_to_next_tape();
191        }
192    }
193/* write 1MB of zeroes */
194/*
195    for (i = 0; i < 256*1024; i++)
196      {
197        blk[i] = 0;
198      }
199    for (i = 0; i < 4; i++)
200      {
201        fwrite (blk, 1, 256*1024, g_tape_stream);
202        if (should_we_write_to_next_tape (bkpinfo->media_size[g_current_media_number], 256*1024))
203          {
204            start_to_write_to_next_tape ();
205          }
206      }
207*/
208    sleep(2);
209    paranoid_pclose(g_tape_stream);
210    log_it("closeout_tape() -- leaving");
211    for (i = 0; i < g_tapecatalog->entries; i++) {
212        log_it("i=%d type=%s num=%d aux=%ld posK=%lld", i,
213               (g_tapecatalog->el[i].type ==
214                fileset) ? "fileset" : "bigslice",
215               g_tapecatalog->el[i].number, g_tapecatalog->el[i].aux,
216               g_tapecatalog->el[i].tape_posK);
217    }
218    paranoid_free(blk);
219    paranoid_free(g_tapecatalog);
220    return (retval);
221}
222
223
224
225bool mt_says_tape_exists(char *dev)
226{
227    char *command = NULL;
228    int res;
229
230    mr_asprintf(command, "mt -f %s status", dev);
231    res = run_program_and_log_output(command, 1);
232    mr_free(command);
233
234    if (res) {
235        return (FALSE);
236    } else {
237        return (TRUE);
238    }
239}
240
241
242
243/**
244 * Determine the name of the tape device. Tries the SCSI tape for
245 * this platform, then the IDE tape, then "/dev/st0", then "/dev/osst0".
246 * @return the allocated tape string if success, NULL if failure
247 */
248char *mr_find_tape_device(void) {
249
250    char *tmp = NULL;
251    char *command = NULL;
252    char *cdr_exe = NULL;
253    char *dev = NULL;
254    int res;
255
256    log_to_screen("I am looking for your tape streamer. Please wait.");
257
258    tmp = find_home_of_exe("cdrecord");
259    if (tmp) {
260        mr_asprintf(cdr_exe, "cdrecord");
261    } else {
262        mr_asprintf(cdr_exe, "dvdrecord");
263    }
264    mr_free(tmp);
265
266    mr_asprintf(command, "%s -scanbus 2> /dev/null | grep -i tape | wc -l", cdr_exe);
267    tmp = call_program_and_get_last_line_of_output(command,TRUE);
268    mr_free(command);
269
270    if (atoi(tmp) != 1) {
271        log_it("Either too few or too many tape streamers for me to detect...");
272        mr_asprintf(dev, "%s", VANILLA_SCSI_TAPE);
273        mr_free(tmp);
274        return(dev);
275    }
276    mr_free(tmp);
277
278    mr_asprintf(command, "%s -scanbus 2> /dev/null | tr -s '\t' ' ' | grep \"[0-9]*,[0-9]*,[0-9]*\" | grep -v \"[0-9]*) \\*\" | grep -i TAPE | cut -d' ' -f2 | head -n1", cdr_exe);
279    tmp = call_program_and_get_last_line_of_output(command,TRUE);
280    mr_free(command);
281
282    if (strlen(tmp) < 2) {
283        log_it("Could not find tape device");
284        mr_free(tmp);
285        return(NULL);
286    }
287    mr_free(tmp);
288
289    mr_asprintf(command, "%s -scanbus 2> /dev/null | tr -s '\t' ' ' | grep \"[0-9]*,[0-9]*,[0-9]*\" | grep -v \"[0-9]*) \\*\" | grep -i TAPE | cut -d' ' -f3 | cut -d')' -f1 | head -n1", cdr_exe);
290    mr_free(cdr_exe);
291    tmp = call_program_and_get_last_line_of_output(command,TRUE);
292    mr_free(command);
293
294    mr_asprintf(dev, "%s", "/dev/st");
295    mr_strcat(dev, tmp);            // e.g. '/dev/st0' becomes '/dev/stN'
296    mr_free(tmp);
297
298    res = 0;
299    if (!mt_says_tape_exists(dev)) {
300        mr_free(dev);
301        mr_asprintf(dev, "%s", ALT_TAPE);
302        if (!mt_says_tape_exists(dev)) {
303            log_it("Cannot openin %s", dev);
304            mr_free(dev);
305            mr_asprintf(dev, "/dev/st0");
306            if (!mt_says_tape_exists(dev)) {
307                log_it("Cannot openin %s", dev);
308                mr_free(dev);
309                mr_asprintf(dev, "/dev/osst0");
310                if (!mt_says_tape_exists(dev)) {
311                    mr_free(dev);
312                    res++;
313                } else {
314                    res = 0;
315                }
316            }
317        }
318    }
319
320    if (dev) {
321        log_it("At this point, dev = %s and res = %d", dev, res);
322    } else {
323        log_it("At this point, dev is NULL and res = %d", dev, res);
324    }
325
326    tmp = call_program_and_get_last_line_of_output(" cdrecord -scanbus 2> /dev/null | tr -s '\t' ' ' |  grep \"[0-9]*,[0-9]*,[0-9]*\" | grep -v \"[0-9]*) \\*\" | grep -i TAPE |  awk '{for(i=1; i<NF; i++) { if (index($i, \"GB\")>0) { print $i;};};};'",TRUE);
327
328    if (mt_says_tape_exists(dev)) {
329        res = 0;
330    } else {
331        log_it("Turning %s", dev);
332        mr_free(tmp);
333        mr_asprintf(tmp, "%s", (strrchr(dev, '/') != NULL) ? strrchr(dev, '/') : dev);
334        mr_free(dev);
335        mr_asprintf(dev, "/dev/os%s", tmp);
336        log_it("...into %s", dev);
337        if (mt_says_tape_exists(dev)) {
338            res = 0;
339        } else {
340            mr_free(dev);
341            res++;
342        }
343    }
344
345    if (dev) {
346        log_it("At this new point, dev = %s and res = %d", dev, res);
347    } else {
348        log_it("At this new point, dev is NULL and res = %d", res);
349    }
350
351    if (strlen(tmp) < 2) {
352        log_it("Warning - size of tape unknown");
353    }
354    mr_free(tmp);
355    return(dev);
356}
357
358
359int read_EXAT_files_from_tape(long long *ptmp_size, char *tmp_fname,
360                              int *pctrl_chr, char *xattr_fname,
361                              char *acl_fname)
362{
363    int res = 0;
364    char *fname = (char *)&res;                 /* Should NOT be NULL */
365    char *tmp = NULL;
366
367    // xattr
368    if (g_getfattr) {
369        res = read_header_block_from_stream(ptmp_size, fname, pctrl_chr);
370        if (*pctrl_chr != BLK_START_EXAT_FILE) {
371            wrong_marker(BLK_START_EXAT_FILE, *pctrl_chr);
372        }
373        if (strstr(fname, "xattr") == NULL) {
374            mr_asprintf(tmp,"Wrong order expected xattr, got %s, sunshine.", fname);
375            fatal_error(tmp);
376        }
377        read_file_from_stream_to_file(xattr_fname, *ptmp_size);
378        res = read_header_block_from_stream(ptmp_size, fname, pctrl_chr);
379        if (*pctrl_chr != BLK_STOP_EXAT_FILE) {
380            wrong_marker(BLK_STOP_EXAT_FILE, *pctrl_chr);
381        }
382        log_msg(1, "Got xattr");
383        res = read_header_block_from_stream(ptmp_size, fname, pctrl_chr);
384        if (*pctrl_chr != BLK_STOP_EXTENDED_ATTRIBUTES) {
385            wrong_marker(BLK_STOP_EXTENDED_ATTRIBUTES, *pctrl_chr);
386        }
387        res = read_header_block_from_stream(ptmp_size, fname, pctrl_chr);
388        if (*pctrl_chr == BLK_START_AN_AFIO_OR_SLICE) {
389            log_msg(1, "No acl attributes found, skipping to afio files");
390            return(0);
391        } else {
392            if (*pctrl_chr != BLK_START_EXTENDED_ATTRIBUTES) {
393                wrong_marker(BLK_START_EXTENDED_ATTRIBUTES, *pctrl_chr);
394            }
395        }
396    }
397    // acl
398    if (g_getfacl) {
399        res = read_header_block_from_stream(ptmp_size, fname, pctrl_chr);
400        if (*pctrl_chr != BLK_START_EXAT_FILE) {
401            wrong_marker(BLK_START_EXAT_FILE, *pctrl_chr);
402        }
403        if (strstr(fname, "acl") == NULL) {
404            mr_asprintf(tmp,"Wrong order expected acl, got %s, sunshine.", fname);
405            fatal_error(tmp);
406        }
407        read_file_from_stream_to_file(acl_fname, *ptmp_size);
408        res = read_header_block_from_stream(ptmp_size, fname, pctrl_chr);
409        if (*pctrl_chr != BLK_STOP_EXAT_FILE) {
410            wrong_marker(BLK_STOP_EXAT_FILE, *pctrl_chr);
411        }
412        res = read_header_block_from_stream(ptmp_size, fname, pctrl_chr);
413        if (*pctrl_chr != BLK_STOP_EXTENDED_ATTRIBUTES) {
414            wrong_marker(BLK_STOP_EXTENDED_ATTRIBUTES, *pctrl_chr);
415        }
416        log_msg(1, "Got acl");
417    }
418    // tarball itself
419    res = read_header_block_from_stream(ptmp_size, tmp_fname, pctrl_chr);
420    log_msg(1, "End of extended attributes, now looking for afioball");
421    return (0);
422}
423
424
425int write_EXAT_files_to_tape(char *xattr_fname,
426                             char *acl_fname)
427{
428    int res = 0;
429    if (g_getfattr) {
430    // xattr
431        write_header_block_to_stream(length_of_file(xattr_fname), xattr_fname,
432                             BLK_START_EXTENDED_ATTRIBUTES);
433        write_header_block_to_stream(length_of_file(xattr_fname), xattr_fname,
434                             BLK_START_EXAT_FILE);
435        write_file_to_stream_from_file(xattr_fname);
436        write_header_block_to_stream((off_t)-1, xattr_fname, BLK_STOP_EXAT_FILE);
437        write_header_block_to_stream(length_of_file(xattr_fname), xattr_fname,
438                             BLK_STOP_EXTENDED_ATTRIBUTES);
439    }
440    if (g_getfacl) {
441    // acl
442        write_header_block_to_stream(length_of_file(acl_fname), acl_fname,
443                             BLK_START_EXTENDED_ATTRIBUTES);
444        write_header_block_to_stream(length_of_file(acl_fname), acl_fname,
445                             BLK_START_EXAT_FILE);
446        write_file_to_stream_from_file(acl_fname);
447        write_header_block_to_stream((off_t)-1, acl_fname, BLK_STOP_EXAT_FILE);
448        write_header_block_to_stream(length_of_file(acl_fname), acl_fname,
449                             BLK_STOP_EXTENDED_ATTRIBUTES);
450    }
451    return (res);
452}
453
454
455
456
457/**
458 * Tell the user to insert tape @p tapeno and wait for it to settle (5 seconds).
459 * @param tapeno The tape number to insist on.
460 * @bug There is currently no way to actually verify that the user has actually
461 * inserted the right tape.
462 */
463void insist_on_this_tape_number(int tapeno)
464{
465    int i;
466    char *tmp = NULL;
467
468    log_it("Insisting on tape #%d", tapeno);
469    if (g_current_media_number != tapeno) {
470        mr_asprintf(tmp, "When the tape drive goes quiet, please insert volume %d in this series.", tapeno);
471        popup_and_OK(tmp);
472        mr_free(tmp);
473        open_evalcall_form("Waiting while the tape drive settles");
474    } else {
475        open_evalcall_form("Waiting while the tape drive rewinds");
476    }
477
478    for (i = 0; i <= 100; i += 2) {
479        usleep(100000);
480        update_evalcall_form(i);
481    }
482    close_evalcall_form();
483    log_it("I assume user has inserted it. They _say_ they have...");
484    g_current_media_number = tapeno;
485
486    //  log_it("g_current_media_number = %d", g_current_media_number);
487    log_it("OK, I've finished insisting. On with the revelry.");
488}
489
490
491
492
493/**
494 * Debugging aid - log the offset we're at on the tape (reading or writing).
495 */
496void log_tape_pos(void)
497{
498    /*@ buffers ***************************************************** */
499
500
501    /*@ end vars *************************************************** */
502
503    log_it("Tape position -- %ld KB (%ld MB)", (long) g_tape_posK,
504           (long) g_tape_posK >> 10);
505}
506
507
508
509
510/**
511 * Add a file to a collection of recently archived filesets/slices.
512 * The type is determined by the filename: if it contains ".afio." it is
513 * assumed to be a fileset, otherwise if it contains "slice" it's a slice,
514 * otherwise we generate a fatal_error().
515 * @param latest_fname The file to place in the collection.
516 * @return 0, always.
517 * @bug Return value is redundant.
518 * @bug The detection won't work for uncompressed afioballs (they end in ".afio", no dot afterwards). // Not true. They end in '.' -Hugo
519 */
520int maintain_collection_of_recent_archives(char *latest_fname)
521{
522    long long final_alleged_writeK, final_projected_certain_writeK,
523        final_actually_certain_writeK = 0, cposK, bufsize_K;
524    int last, curr, i;
525    t_archtype type = other;
526    char *command = NULL;
527    char *tmpdir = NULL;
528    char *old_fname = NULL;
529
530    bufsize_K = (long long) (1024LL * (1 + g_tape_buffer_size_MB));
531    if (strstr(latest_fname, ".afio.") || strstr(latest_fname, ".star.")) {
532        type = fileset;
533    } else if (strstr(latest_fname, "slice")) {
534        type = biggieslice;
535    } else {
536        log_it("fname = %s", latest_fname);
537        fatal_error("Unknown type. Internal error in maintain_collection_of_recent_archives()");
538    }
539    mr_asprintf(tmpdir, "%s/tmpfs/backcatalog", bkpinfo->tmpdir);
540    mkdir(tmpdir, 0x700);
541    mr_asprintf(command, "cp -f %s %s", latest_fname, tmpdir);
542    if (run_program_and_log_output(command, 6)) {
543        log_it("Warning - failed to copy %s to backcatalog at %s",
544               latest_fname, tmpdir);
545    }
546    mr_free(command);
547
548    last = g_tapecatalog->entries - 1;
549    if (last <= 0) {
550        log_it("Too early to start deleting from collection.");
551        mr_free(tmpdir);
552        return (0);
553    }
554    final_alleged_writeK = g_tapecatalog->el[last].tape_posK;
555    final_projected_certain_writeK = final_alleged_writeK - bufsize_K;
556    for (curr = last; curr >= 0; curr--) {
557        cposK = g_tapecatalog->el[curr].tape_posK;
558        if (cposK < final_projected_certain_writeK) {
559            final_actually_certain_writeK = cposK;
560            break;
561        }
562    }
563    if (curr < 0) {
564        log_it("Not far enough into tape to start deleting old archives from collection.");
565        mr_free(tmpdir);
566        return (0);
567    }
568
569    for (i = curr - 1; i >= 0 && curr - i < 10; i--) {
570        mr_asprintf(old_fname, "%s/%s", tmpdir, g_tapecatalog->el[i].fname);
571        unlink(old_fname);
572        mr_free(old_fname);
573    }
574    mr_free(tmpdir);
575    return (0);
576}
577
578
579
580
581/**
582 * Open the CD stream for input.
583 * @param bkpinfo The backup information structure. Passed to openin_tape().
584 * @return 0 for success, nonzero for failure.
585 * @note Equivalent to openin_tape() for now, but don't count on this behavior.
586 */
587int openin_cdstream()
588{
589    return (openin_tape());
590}
591
592/**
593 * FIFO used to read/write to the tape device.
594 * @bug This seems obsolete now that we call an external @c buffer program. Please look onto this.
595 */
596char g_tape_fifo[MAX_STR_LEN];
597
598
599
600int set_tape_block_size_with_mt(long internal_tape_block_size)
601{
602    char *tmp = NULL;
603    int res;
604
605    if (bkpinfo->media_device == NULL) {
606        return(1);
607    }
608
609    if (strncmp(bkpinfo->media_device, "/dev/", 5)) {
610        log_msg(1, "Not using 'mt setblk'. This isn't an actual /dev entry.");
611        return (0);
612    }
613    mr_asprintf(tmp, "mt -f %s setblk %ld", bkpinfo->media_device, internal_tape_block_size);
614    res = run_program_and_log_output(tmp, 3);
615    mr_free(tmp);
616    return (res);
617}
618
619/**
620 * Return the non-rewinding device when passed the normal one
621 * @param tapedev The tape device to open for writing.
622 * @note the caller needs to free the string returned
623 */
624char *get_non_rewind_dev(char *tapedev)
625{
626
627    char *ntapedev = NULL;
628    char *p = NULL;
629    char *q = NULL;
630    char *r = NULL;
631
632    ntapedev = (char *)malloc(strlen(tapedev)+sizeof(char));
633    p = strrchr(tapedev,'/');
634    if (p == NULL) {
635        log_it("Didn't find a '/' in %s",tapedev);
636        return(NULL);
637    }
638
639    /* Copy tapedev content up to the last / */
640    q = tapedev;
641    r = ntapedev;
642    while (q != p) {
643        *r = *q;
644        r++;
645        q++;
646    }
647    /* Copy the '/' */
648    *r = *q;
649    r++;
650    q++;
651    /* Adds a 'n' - non-rewinding */
652    *r = 'n';
653    r++;
654    /* Copy the rest of tapedev */
655    while (*q != '\0') {
656        *r = *q;
657        r++;
658        q++;
659    }
660    *r = '\0';
661    if (mt_says_tape_exists(ntapedev)) {
662        log_it("Non-rewinding tape device is %s",ntapedev);
663    } else {
664        log_it("Unable to find non-rewinding tape device.");
665        ntapedev = NULL;
666    }
667    return(ntapedev);
668}
669
670
671
672/**
673 * Handle OBDR if we were asked to do so
674 * @param tapedev The tape device to open for reading.
675 */
676int skip_obdr(void)
677{
678    char *command = NULL;
679    int res = 0;
680
681    if (bkpinfo->media_device == NULL) {
682        return(1);
683    }
684
685    log_it("Skipping OBDR headers");
686    mr_asprintf(command, "mt -f %s rewind",bkpinfo->media_device);
687    res = run_program_and_log_output(command, 1);
688    paranoid_free(command);
689
690    mr_asprintf(command, "mt -f %s fsf 2",bkpinfo->media_device);
691    res = run_program_and_log_output(command, 1);
692    paranoid_free(command);
693
694    set_tape_block_size_with_mt(bkpinfo->internal_tape_block_size);
695    return(res);
696}
697
698/**
699 * Handle OBDR if we were asked to do so
700 * @param tapedev The tape device to open for writing.
701 * @return 0 for success, nonzero for failure.
702 * @note This should be called ONLY from backup processes. It will OVERWRITE ANY
703 * EXISTING DATA on the tape!
704 */
705int create_obdr(void)
706{
707
708    char *command = NULL;
709    int res = 0;
710
711    if (bkpinfo->media_device == NULL) {
712        return(1);
713    }
714
715    log_it("Creating OBDR headers");
716    /* OBDR: First block 10 kB of zero bs = 512 */
717    mr_asprintf(command, "mt -f %s compression off",bkpinfo->media_device);
718    res = run_program_and_log_output(command, 1);
719    paranoid_free(command);
720
721    mr_asprintf(command, "mt -f %s rewind",bkpinfo->media_device);
722    res += run_program_and_log_output(command, 1);
723    paranoid_free(command);
724
725    set_tape_block_size_with_mt(512);
726
727    mr_asprintf(command, "dd if=/dev/zero of=%s bs=512 count=20",bkpinfo->media_device);
728    res += run_program_and_log_output(command, 1);
729    paranoid_free(command);
730
731    /* OBDR: then ISO boot image bs = 2048 */
732    set_tape_block_size_with_mt(2048);
733
734    mr_asprintf(command, "dd if=%s of=%s bs=2048",MINDI_CACHE"/mondorescue.iso",bkpinfo->media_device);
735    res += run_program_and_log_output(command, 1);
736    paranoid_free(command);
737
738    set_tape_block_size_with_mt(bkpinfo->internal_tape_block_size);
739
740    /* restore compression mode on */
741    mr_asprintf(&command, "mt -f %s compression on",bkpinfo->media_device);
742    res = run_program_and_log_output(command, 1);
743    paranoid_free(command);
744
745    return(res);
746}
747
748
749/**
750 * Open the tape device for input.
751 * @param bkpinfo The backup information structure. Fields used:
752 * - @c bkpinfo->media_device
753 * - @c bkpinfo->tmpdir
754 * @return 0 for success, nonzero for failure.
755 * @note This will also work with a cdstream for now, but don't count on this behavior.
756 */
757int openin_tape()
758{
759    /*@ buffer ***************************************************** */
760    char fname[MAX_STR_LEN];
761    char *datablock;
762    char *tmp = NULL;
763    char old_cwd[MAX_STR_LEN];
764    char *outfname = NULL;
765    /*@ int ******************************************************* */
766    int i;
767    int j;
768    int res = 0;
769    long length, templong;
770    size_t k;
771    int retval = 0;
772    int ctrl_chr;
773
774    /*@ long long ************************************************* */
775    long long size;
776
777    /*@ pointers ************************************************** */
778    FILE *fout;
779
780    /*@ end vars *************************************************** */
781
782    g_tapecatalog = mr_malloc(sizeof(struct s_tapecatalog));
783    g_tapecatalog->entries = 0;
784    g_tape_posK = 0;
785    if (g_tape_stream) {
786        log_it("FYI - I won't 'openin' the tape. It's already open.");
787        return (0);
788    }
789
790    // mondoarchive should have configured everything to give the right non-rew device
791    if ((bkpinfo->use_obdr) && (bkpinfo->media_device != NULL)) {
792        res = skip_obdr();
793        if (res != 0) {
794            log_it("Not able to skip OBDR - Restore will have to be done manually");
795        }
796    } else {
797        if (bkpinfo->media_device == NULL) {
798            log_it("Not able to skip OBDR - Restore will have to be done manually");
799            return (1);
800        }
801        set_tape_block_size_with_mt(bkpinfo->internal_tape_block_size);
802    }
803
804    insist_on_this_tape_number(1);
805    mr_asprintf(outfname, "%s/tmp/all.tar.gz", bkpinfo->tmpdir);
806    make_hole_for_file(outfname);
807
808    log_it("Opening IN tape");
809    if (!(g_tape_stream = open_device_via_buffer(bkpinfo->media_device, 'r', bkpinfo->internal_tape_block_size))) {
810        log_OS_error(g_tape_fifo);
811        log_to_screen("Cannot openin stream device");
812        mr_free(outfname);
813        return (1);
814    }
815    log_to_screen("Reading stream");
816    log_it("stream device = '%s'", bkpinfo->media_device);
817/* skip data disks */
818    open_evalcall_form("Skipping data disks on stream");
819    log_to_screen("Skipping data disks on stream");
820    if (!(fout = fopen(outfname, "w"))) {
821        log_OS_error(outfname);
822        log_to_screen("Cannot openout datadisk all.tar.gz file");
823        mr_free(outfname);
824        return (-1);
825    }
826    if (!(datablock = (char *) malloc(256 * 1024))) {
827        log_to_screen("Unable to malloc 256*1024");
828        mr_free(outfname);
829        finish(1);
830    }
831    for (i = 0; i < 32; i++) {
832        for (j = 0; j < 4; j++) {
833            for (length = 0, k = 0; length < 256 * 1024; length += k) {
834                k = fread(datablock + length, 1, 256 * 1024 - length,
835                          g_tape_stream);
836            }
837            (void) fwrite(datablock, 1, (size_t) length, fout);
838            g_tape_posK += length / 1024;
839        }
840        if (i > 8)              // otherwise, 'buffer' distorts calculations
841        {
842            templong = ((i - 8) * 4 + j) * 100 / (128 - 8 * 4);
843            update_evalcall_form((int) (templong));
844        }
845    }
846    paranoid_fclose(fout);
847    paranoid_free(datablock);
848
849/* find initial blocks */
850    res = read_header_block_from_stream(&size, fname, &ctrl_chr);
851    retval += res;
852    if (ctrl_chr != BLK_START_OF_TAPE) {
853        wrong_marker(BLK_START_OF_TAPE, ctrl_chr);
854    }
855    res = read_header_block_from_stream(&size, fname, &ctrl_chr);
856    retval += res;
857    if (ctrl_chr != BLK_START_OF_BACKUP) {
858        wrong_marker(BLK_START_OF_BACKUP, ctrl_chr);
859    }
860    close_evalcall_form();
861    log_it("Saved all.tar.gz to '%s'", outfname);
862    (void) getcwd(old_cwd, MAX_STR_LEN);
863    chdir(bkpinfo->tmpdir);
864    mr_asprintf(tmp, "tar -zxf %s ."MINDI_CACHE"/mondorestore.cfg 2> /dev/null", outfname);
865    paranoid_system(tmp);
866    mr_free(tmp);
867
868    paranoid_system("cp -f ."MINDI_CACHE"/mondorestore.cfg . 2> /dev/null");
869    chdir(old_cwd);
870    unlink(outfname);
871    mr_free(outfname);
872    return (retval);
873}
874
875
876/**
877 * Start writing to a CD stream.
878 * @param cddev The CD device to openout via cdrecord.
879 * @param speed The speed to write at.
880 * @return 0 for success, nonzero for failure.
881 * @note This should be called only from backup processes.
882 */
883int openout_cdstream(char *cddev, int speed)
884{
885    /*@ buffers ***************************************************** */
886    char *command = NULL;
887
888    /*@ end vars *************************************************** */
889
890    if (cddev == NULL) {
891        log_to_screen("Failed to openout NULL cddev");
892        return (1);
893    }
894    /*  add 'dummy' if testing */
895    mr_asprintf(command, "cdrecord -eject dev=%s speed=%d fs=24m -waiti - >> %s 2>> %s", cddev, speed, MONDO_LOGFILE, MONDO_LOGFILE);
896    /*  initialise the catalog */
897    g_current_media_number = 1;
898    if (!(g_tapecatalog = malloc(sizeof(struct s_tapecatalog)))) {
899        fatal_error("Cannot alloc mem for tape catalog");
900    }
901    g_tapecatalog->entries = 0;
902    /* log stuff */
903    log_it("Opening OUT cdstream with the command");
904    log_it(command);
905    /*  log_it("Let's see what happens, shall we?"); */
906    g_tape_stream = popen(command, "w");
907    mr_free(command);
908
909    if (g_tape_stream) {
910        return (0);
911    } else {
912        log_to_screen("Failed to openout to cdstream (fifo)");
913        return (1);
914    }
915}
916
917
918/**
919 * Start writing to a tape device for the backup.
920 * Handle OBDR if we were asked to do so
921 * @param tapedev The tape device to open for writing.
922 * @return 0 for success, nonzero for failure.
923 * @note This should be called ONLY from backup processes. It will OVERWRITE ANY
924 * EXISTING DATA on the tape!
925 */
926int openout_tape() {
927
928g_current_media_number = 1;
929if (g_tape_stream) {
930    log_it("FYI - I won't 'openout' the tape. It's already open.");
931    return (0);
932}
933if (bkpinfo->media_device == NULL) {
934    log_it("Unable to openout NULL dvice");
935    return(1);
936}
937g_tapecatalog = mr_malloc(sizeof(struct s_tapecatalog));
938g_tapecatalog->entries = 0;
939g_tape_posK = 0;
940
941if (bkpinfo->use_obdr) {
942    create_obdr();
943} else {
944    set_tape_block_size_with_mt(bkpinfo->internal_tape_block_size);
945}
946log_it("Opening OUT tape");
947if (!(g_tape_stream = open_device_via_buffer(bkpinfo->media_device, 'w', bkpinfo->internal_tape_block_size))) {
948    log_OS_error(g_tape_fifo);
949    log_to_screen("Cannot openin stream device");
950    return (1);
951}
952return (0);
953}
954
955
956
957
958/**
959 * Copy a file from the opened stream (CD or tape) to @p outfile.
960 * @param outfile The file to write to.
961 * @param size The size of the file in the input stream.
962 * @return 0 for success, nonzero for failure.
963 */
964int
965read_file_from_stream_to_file(char *outfile, long long size)
966{
967
968    /*@ int ******************************************************** */
969    int res;
970
971    /*@ end vars *************************************************** */
972
973    res = read_file_from_stream_FULL(outfile, NULL, size);
974
975    return (res);
976}
977
978
979
980/**
981 * Copy a file from the currently opened stream (CD or tape) to the stream indicated
982 * by @p fout.
983 * @param bkpinfo The backup information structure. @c bkpinfo->media_size is the only field used.
984 * @param fout The stream to write the file to.
985 * @param size The size of the file in bytes.
986 * @return 0 for success, nonzero for failure.
987 */
988int
989read_file_from_stream_to_stream(FILE * fout, long long size)
990{
991
992    /*@ int ******************************************************** */
993    int res;
994
995    /*@ end vars *************************************************** */
996
997    res = read_file_from_stream_FULL(NULL, fout, size);
998/*  fflush(g_tape_stream);
999  fflush(fout);*/
1000    return (res);
1001}
1002
1003
1004
1005/**
1006 * Copy a file from the currently opened stream (CD or tape) to either a
1007 * @c FILE pointer indicating a currently-opened file, or a filename indicating
1008 * a new file to create. This is the backbone function that read_file_from_stream_to_file()
1009 * and read_file_from_stream_to_stream() are wrappers for.
1010 * @param bkpinfo The backup information structure. @c bkpinfo->media_size is the only field used.
1011 * @param outfname If non-NULL, write to this file.
1012 * @param foutstream If non-NULL, write to this stream.
1013 * @param orig_size The original length of the file in bytes.
1014 * @return 0 for success, nonzero for failure.
1015 * @note Only @b one of @p outfname or @p foutstream may be non-NULL.
1016 */
1017int
1018read_file_from_stream_FULL(char *outfname, FILE * foutstream, long long orig_size)
1019{
1020    /*@ buffers ***************************************************** */
1021    char *datablock;
1022    char *temp_fname;
1023    char *temp_cksum;
1024    char *actual_cksum = NULL;
1025
1026    /*@ int ********************************************************* */
1027    int retval = 0;
1028#ifdef EXTRA_TAPE_CHECKSUMS
1029    int i, ch;
1030#endif
1031    int noof_blocks;
1032    int ctrl_chr;
1033    int res;
1034    /*@ pointers **************************************************** */
1035    FILE *fout;
1036
1037    /*@ long    ***************************************************** */
1038    long bytes_to_write = 0L /*,i */ ;
1039//  long bytes_successfully_read_in_this_time = 0;
1040
1041    /*@ long long *************************************************** */
1042    long long temp_size, size;
1043    long bytes_read, bytes_to_read;
1044    long long total_read_from_tape_for_this_file = 0;
1045    long long where_I_was_before_tape_change = 0;
1046    /*@ unsigned int ************************************************ */
1047    /*  unsigned int ch; */
1048    unsigned int crc16;
1049    unsigned int crctt;
1050
1051    bool had_to_resync = FALSE;
1052
1053    /*@ init  ******************************************************* */
1054    malloc_string(temp_fname);
1055    malloc_string(temp_cksum);
1056    datablock = malloc(TAPE_BLOCK_SIZE);
1057    crc16 = 0;
1058    crctt = 0;
1059    size = orig_size;
1060
1061    /*@ end vars *************************************************** */
1062
1063    res = read_header_block_from_stream(&temp_size, temp_fname, &ctrl_chr);
1064    if (orig_size != temp_size && orig_size != -1) {
1065        log_to_screen("output file's size should be %ld K but is apparently %ld K", (long) size >> 10, (long) temp_size >> 10);
1066    }
1067    if (ctrl_chr != BLK_START_FILE) {
1068        wrong_marker(BLK_START_FILE, ctrl_chr);
1069        return (1);
1070    }
1071
1072    if (foutstream) {
1073        fout = foutstream;
1074    } else {
1075        fout = fopen(outfname, "w");
1076    }
1077    if (!fout) {
1078        log_OS_error(outfname);
1079        log_to_screen("Cannot openout file");
1080        return (1);
1081    }
1082    total_read_from_tape_for_this_file = 0;
1083    for (noof_blocks = 0; size > 0;
1084         noof_blocks++, size -=
1085         bytes_to_write, total_read_from_tape_for_this_file +=
1086         bytes_read) {
1087        bytes_to_write =
1088            (size < TAPE_BLOCK_SIZE) ? (long) size : TAPE_BLOCK_SIZE;
1089        bytes_to_read = TAPE_BLOCK_SIZE;
1090        bytes_read = fread(datablock, 1, bytes_to_read, g_tape_stream);
1091        while (bytes_read < bytes_to_read) {    // next tape!
1092//    crctt=crc16=0;
1093            where_I_was_before_tape_change = size;
1094            log_msg(4, "where_I_was_... = %lld",
1095                    where_I_was_before_tape_change);
1096            start_to_read_from_next_tape();
1097            log_msg(4, "Started reading from next tape.");
1098            skip_incoming_files_until_we_find_this_one(temp_fname);
1099            log_msg(4, "Skipped irrelevant files OK.");
1100            for (size = orig_size; size > where_I_was_before_tape_change;
1101                 size -= bytes_to_write) {
1102                bytes_read =
1103                    fread(datablock, 1, bytes_to_read, g_tape_stream);
1104            }
1105            log_msg(4, "'size' is now %lld (should be %lld)", size,
1106                    where_I_was_before_tape_change);
1107            log_to_screen("Successfully re-sync'd tape");
1108            had_to_resync = TRUE;
1109            bytes_read = fread(datablock, 1, bytes_to_read, g_tape_stream);
1110        }
1111
1112        (void) fwrite(datablock, 1, (size_t) bytes_to_write, fout); // for blocking reasons, bytes_successfully_read_in isn't necessarily the same as bytes_to_write
1113
1114#ifdef EXTRA_TAPE_CHECKSUMS
1115        for (i = 0; i < (int) bytes_to_write; i++) {
1116            ch = datablock[i];
1117            crc16 = updcrcr(crc16, (unsigned) ch);
1118            crctt = updcrc(crctt, (unsigned) ch);
1119        }
1120#endif
1121    }
1122    log_msg(6, "Total read from tape for this file = %lld",
1123            total_read_from_tape_for_this_file);
1124    log_msg(6, ".......................... Should be %lld", orig_size);
1125    g_tape_posK += total_read_from_tape_for_this_file / 1024;
1126    mr_asprintf(actual_cksum, "%04x%04x", crc16, crctt);
1127    if (foutstream) {           /*log_it("Finished writing to foutstream"); */
1128    } else {
1129        paranoid_fclose(fout);
1130    }
1131    res = read_header_block_from_stream(&temp_size, temp_cksum, &ctrl_chr);
1132    if (ctrl_chr != BLK_STOP_FILE) {
1133        wrong_marker(BLK_STOP_FILE, ctrl_chr);
1134    }
1135    if (strcmp(temp_cksum, actual_cksum)) {
1136        log_to_screen("actual cksum=%s; recorded cksum=%s", actual_cksum, temp_cksum);
1137        log_to_screen("%s (%ld K) is corrupt on tape", temp_fname, (long) orig_size >> 10);
1138        retval++;
1139    }
1140    mr_free(actual_cksum);
1141
1142    paranoid_free(datablock);
1143    paranoid_free(temp_fname);
1144    paranoid_free(temp_cksum);
1145    return (retval);
1146}
1147
1148
1149
1150/**
1151 * Read a header block from the currently opened stream (CD or tape).
1152 * This block indicates the length of the following file (if it's file-related)
1153 * the filename (if it's file-related), and the block type.
1154 * @param plen Where to put the length of the file. Valid only for file-related header blocks.
1155 * @param filename Where to put the name of the file. Valid only for file-related header blocks.
1156 * @param pcontrol_char Where to put the type of block (e.g. start-file, end-file, start-tape, ...)
1157 * @return 0 for success, nonzero for failure.
1158 * @note If you read a marker (@p pcontrol_char) you're not expecting, you can call wrong_marker().
1159 */
1160int
1161read_header_block_from_stream(long long *plen, char *filename,
1162                              int *pcontrol_char)
1163{
1164
1165    /*@ buffers ***************************************************** */
1166    char *tempblock;
1167
1168    /*@ int ********************************************************* */
1169    int i, retval;
1170
1171    /*@ end vars *************************************************** */
1172
1173    tempblock = (char *) malloc((size_t) TAPE_BLOCK_SIZE);
1174
1175    for (i = 0; i < (int) TAPE_BLOCK_SIZE; i++) {
1176        tempblock[i] = 0;
1177    }
1178    while (!(*pcontrol_char = tempblock[7000])) {
1179        g_tape_posK +=
1180            fread(tempblock, 1, (size_t) TAPE_BLOCK_SIZE,
1181                  g_tape_stream) / 1024;
1182    }
1183    memcpy((char *) plen, tempblock + 7001, sizeof(long long));
1184    if (strcmp(tempblock + 6000 + *pcontrol_char, STR_HEADER)) {
1185        log_it("Bad header block at %ld K", (long) g_tape_posK);
1186    }
1187    strcpy(filename, tempblock + 1000);
1188    if (*pcontrol_char == BLK_ABORTED_BACKUP) {
1189        log_to_screen("I can't verify an aborted backup.");
1190        retval = 1;
1191    } else {
1192        retval = 0;
1193    }
1194    for (i = 1000; i < 1020; i++) {
1195        if (tempblock[i] < 32 || tempblock[i] > 126) {
1196            tempblock[i] = ' ';
1197        }
1198    }
1199    tempblock[i] = '\0';
1200    log_msg(6, "%s (fname=%s, size=%ld K)",
1201            marker_to_string(*pcontrol_char), tempblock + 1000,
1202            (long) (*plen) >> 10);
1203    paranoid_free(tempblock);
1204    return (retval);
1205}
1206
1207
1208
1209/**
1210 * Add specified file/slice to the internal catalog of all archives written.
1211 * This lets us restart on a new CD/tape/whatever if it runs out of room. We just
1212 * write the last [buffer size] MB from the catalog to the new tape, so we know
1213 * we have @e all archives on some CD/tape/whatever.
1214 * @param type The type of file we're cataloging (afioball, slice, something else)
1215 * @param number The fileset number or biggiefile number.
1216 * @param aux The slice number if it's a biggiefile, or any other additional info.
1217 * @param fn The original full pathname of the file we're recording.
1218 * @return The index of the record we just added.
1219 */
1220int register_in_tape_catalog(t_archtype type, int number, long aux,
1221                             char *fn)
1222{
1223    int last;
1224    char fname[MAX_TAPECAT_FNAME_LEN+1];
1225    char *p;
1226
1227    p = strrchr(fn, '/');
1228    if (p) {
1229        p++;
1230    } else {
1231        p = fn;
1232    }
1233    strncpy(fname, p, MAX_TAPECAT_FNAME_LEN);
1234    fname[MAX_TAPECAT_FNAME_LEN] = '\0';
1235    last = g_tapecatalog->entries;
1236    if (last >= MAX_TAPECATALOG_ENTRIES) {
1237        log_it
1238            ("Warning - can't log #%d in tape catalog - too many entries already",
1239             number);
1240        return (-1);
1241    }
1242    g_tapecatalog->el[last].type = type;
1243    g_tapecatalog->el[last].number = number;
1244    g_tapecatalog->el[last].aux = aux;
1245    g_tapecatalog->el[last].tape_posK = g_tape_posK;
1246    strcpy(g_tapecatalog->el[last].fname, fname);
1247    g_tapecatalog->entries++;
1248    return (last);              // returns the index of the record we've jsut added
1249}
1250
1251
1252
1253
1254/**
1255 * Decide whether we should start a new tape. This is TRUE if we've run out of tape
1256 * (got SIGPIPE) or look like we will.
1257 * @param mediasize The size of the tape in megabytes.
1258 * @param length_of_incoming_file The length of the file we're about to write, in bytes.
1259 * @bug This seems like it'll only work for media_size != autodetect, but Mondo only allows
1260 * autodetecting the size. Huh?
1261 */
1262
1263/* BERLIOS: Should be reviewed for mediasize being a off_t ??? */
1264bool
1265should_we_write_to_next_tape(long mediasize,
1266                             off_t length_of_incoming_file)
1267{
1268    /*@ bool's ***************************************************** */
1269    bool we_need_a_new_tape = FALSE;
1270
1271    /*@ end vars *************************************************** */
1272
1273    if (mediasize == 0) {
1274        return (FALSE);
1275    }
1276    if (mediasize > 0 && (g_tape_posK >> 10 >= mediasize)) {
1277        log_it("mediasize = %ld", mediasize);
1278        we_need_a_new_tape = TRUE;
1279        log_to_screen("Should have started a new tape/CD already");
1280    }
1281    if ((g_tape_posK + length_of_incoming_file / 1024) >> 10 >=
1282        mediasize - (SLICE_SIZE * 4 / 1024)) {
1283        log_it("g_tape_posK = %ld\nmediasize = %ld\n", g_tape_posK,
1284               mediasize);
1285        we_need_a_new_tape = TRUE;
1286    }
1287    return (we_need_a_new_tape);
1288}
1289
1290
1291/**
1292 * Seek through the stream until we find a header block where the NAME field matches
1293 * @p the_file_I_was_reading. This is useful if you've just started reading from
1294 * a new tape and want to find the file you were reading when the tape ended.
1295 * @param the_file_I_was_reading File name to look for.
1296 * @return 0 for success, nonzero for failure.
1297 */
1298int skip_incoming_files_until_we_find_this_one(char
1299                                               *the_file_I_was_reading)
1300{
1301    char *pA;
1302    char *pB;
1303    int res;
1304    int ctrl_chr;
1305    char *temp_fname;
1306    char *datablock;
1307    long long temp_size, size;
1308    long bytes_to_write;
1309
1310    datablock = malloc(TAPE_BLOCK_SIZE);
1311    malloc_string(temp_fname);
1312    pB = strrchr(the_file_I_was_reading, '/');
1313    if (pB) {
1314        pB++;
1315    } else {
1316        pB = the_file_I_was_reading;
1317    }
1318    log_msg(1, "skip_incoming_..(%s)", pB);
1319    log_msg(2, "Looking for initial START_AN_AFIO_OR_SLICE");
1320    ctrl_chr = -1;
1321    while (ctrl_chr != BLK_START_AN_AFIO_OR_SLICE) {
1322        res =
1323            read_header_block_from_stream(&temp_size, temp_fname, &ctrl_chr);
1324        if (ctrl_chr == BLK_START_AN_AFIO_OR_SLICE) {
1325            break;
1326        }
1327        log_msg(1, "%lld %s %c", temp_size, temp_fname, ctrl_chr);
1328        wrong_marker(BLK_START_AN_AFIO_OR_SLICE, ctrl_chr);
1329        log_msg(3, "Still trying to re-sync w/ tape");
1330    }
1331    while (ctrl_chr != BLK_START_FILE) {
1332        res =
1333            read_header_block_from_stream(&temp_size, temp_fname, &ctrl_chr);
1334        if (ctrl_chr == BLK_START_FILE) {
1335            break;
1336        }
1337        log_msg(1, "%lld %s %c", temp_size, temp_fname, ctrl_chr);
1338        wrong_marker(BLK_START_FILE, ctrl_chr);
1339        log_msg(3, "Still trying to re-sync w/ tape");
1340    }
1341    pA = strrchr(temp_fname, '/');
1342    if (pA) {
1343        pA++;
1344    } else {
1345        pA = temp_fname;
1346    }
1347    pB = strrchr(the_file_I_was_reading, '/');
1348    if (pB) {
1349        pB++;
1350    } else {
1351        pB = the_file_I_was_reading;
1352    }
1353    while (strcmp(pA, pB)) {
1354        log_msg(6, "Skipping %s (it's not %s)", temp_fname, the_file_I_was_reading);
1355        for (size = temp_size; size > 0; size -= bytes_to_write) {
1356            bytes_to_write =
1357                (size < TAPE_BLOCK_SIZE) ? (long) size : TAPE_BLOCK_SIZE;
1358            // FIXME - needs error-checking and -catching
1359            fread(datablock, 1, (size_t) TAPE_BLOCK_SIZE, g_tape_stream);
1360        }
1361        res =
1362            read_header_block_from_stream(&temp_size, temp_fname, &ctrl_chr);
1363        if (ctrl_chr != BLK_STOP_FILE) {
1364            wrong_marker(BLK_STOP_FILE, ctrl_chr);
1365        }
1366        res =
1367            read_header_block_from_stream(&temp_size, temp_fname, &ctrl_chr);
1368        if (ctrl_chr != BLK_STOP_AN_AFIO_OR_SLICE) {
1369            wrong_marker(BLK_STOP_AN_AFIO_OR_SLICE, ctrl_chr);
1370        }
1371        res =
1372            read_header_block_from_stream(&temp_size, temp_fname, &ctrl_chr);
1373        if (ctrl_chr != BLK_START_AN_AFIO_OR_SLICE) {
1374            wrong_marker(BLK_START_AN_AFIO_OR_SLICE, ctrl_chr);
1375        }
1376        res =
1377            read_header_block_from_stream(&temp_size, temp_fname, &ctrl_chr);
1378        if (ctrl_chr != BLK_START_FILE) {
1379            wrong_marker(BLK_START_FILE, ctrl_chr);
1380        }
1381        pA = strrchr(temp_fname, '/');
1382        if (pA) {
1383            pA++;
1384        } else {
1385            pA = temp_fname;
1386        }
1387        pB = strrchr(the_file_I_was_reading, '/');
1388        if (pB) {
1389            pB++;
1390        } else {
1391            pB = the_file_I_was_reading;
1392        }
1393    }
1394    log_msg(2, "Reading %s (it matches %s)", temp_fname, the_file_I_was_reading);
1395    paranoid_free(temp_fname);
1396    paranoid_free(datablock);
1397    return (0);
1398}
1399
1400
1401/**
1402 * Start to read from the next tape. Assumes the user has already inserted it.
1403 * @param bkpinfo The backup information structure. @c bkpinfo->media_device is the only field used.
1404 * @return 0 for success, nonzero for failure.
1405 */
1406int start_to_read_from_next_tape()
1407{
1408    /*@ int ********************************************************* */
1409    int res = 0;
1410    char *sz_msg;
1411    int ctrlchr;
1412    long long temp_size;
1413    malloc_string(sz_msg);
1414    /*@ end vars *************************************************** */
1415
1416    if (bkpinfo->media_device == NULL) {
1417        log_it("Unable to open in from NULL device");
1418        return (1);
1419    }
1420
1421    paranoid_pclose(g_tape_stream);
1422    sync();
1423    sync();
1424    sync();
1425    log_it("Next tape requested.");
1426    insist_on_this_tape_number(g_current_media_number + 1); // will increment it, too
1427    log_it("Opening IN the next tape");
1428    if (!(g_tape_stream = open_device_via_buffer(bkpinfo->media_device, 'r', bkpinfo->internal_tape_block_size))) {
1429        log_OS_error(g_tape_fifo);
1430        log_to_screen("Cannot openin stream device");
1431        return (1);
1432    }
1433    g_tape_posK = 0;
1434    g_sigpipe = FALSE;
1435    res += read_header_block_from_stream(&temp_size, sz_msg, &ctrlchr); /* just in case */
1436    if (ctrlchr != BLK_START_OF_TAPE) {
1437        wrong_marker(BLK_START_OF_TAPE, ctrlchr);
1438    }
1439    res += read_header_block_from_stream(&temp_size, sz_msg, &ctrlchr); /* just in case */
1440    if (ctrlchr != BLK_START_OF_BACKUP) {
1441        wrong_marker(BLK_START_OF_BACKUP, ctrlchr);
1442    } else {
1443        log_msg(3, "Next tape opened OK. Whoopee!");
1444    }
1445    paranoid_free(sz_msg);
1446    return (res);
1447}
1448
1449
1450
1451/**
1452 * Start to write to the next tape. Assume the user has already inserted it.
1453 * @param bkpinfo The backup information structure. @c bkpinfo->media_device is the only field used.
1454 * @return 0 for success, nonzero for failure.
1455 */
1456int start_to_write_to_next_tape()
1457{
1458    int res = 0;
1459    char *command = NULL;
1460
1461    if (bkpinfo->media_device == NULL) {
1462        log_it("Unable to open out from NULL device");
1463        return (1);
1464    }
1465
1466    paranoid_pclose(g_tape_stream);
1467    sync();
1468    sync();
1469    sync();
1470    log_it("New tape requested.");
1471    insist_on_this_tape_number(g_current_media_number + 1); // will increment g_current_media, too
1472    if (g_current_media_number > MAX_NOOF_MEDIA) {
1473        res++;
1474        log_to_screen("Too many tapes. Man, you need to use nfs!");
1475    }
1476    if (bkpinfo->backup_media_type == cdstream) {
1477        mr_asprintf(command, "cdrecord -eject dev=%s speed=%d fs=24m -waiti - >> %s 2>> %s", bkpinfo->media_device, bkpinfo->cdrw_speed, MONDO_LOGFILE, MONDO_LOGFILE);
1478        log_it("Opening OUT to next CD with the command");
1479        log_it(command);
1480        log_it("Let's see what happens, shall we?");
1481        g_tape_stream = popen(command, "w");
1482        mr_free(command);
1483
1484        if (!g_tape_stream) {
1485            log_to_screen("Failed to openout to cdstream (fifo)");
1486            return (1);
1487        }
1488    } else {
1489        log_it("Opening OUT to next tape");
1490        if (!(g_tape_stream = open_device_via_buffer(bkpinfo->media_device, 'w', bkpinfo->internal_tape_block_size))) {
1491            log_OS_error(g_tape_fifo);
1492            log_to_screen("Cannot openin stream device");
1493            return (1);
1494        }
1495    }
1496    g_tape_posK = 0;
1497    g_sigpipe = FALSE;
1498    res += write_header_block_to_stream((off_t)0, "start-of-tape", BLK_START_OF_TAPE);  /* just in case */
1499    res += write_header_block_to_stream((off_t)0, "start-of-backup", BLK_START_OF_BACKUP);  /* just in case */
1500    return (res);
1501}
1502
1503
1504
1505
1506/**
1507 * Write a bufferfull of the most recent archives to the tape. The
1508 * rationale behind this is a bit complex. If the previous tape ended
1509 * suddenly (EOF or otherwise) some archives were probably left in the
1510 * buffer. That means that Mondo thinks they have been written, but
1511 * the external binary @c buffer has not actually written them. So to
1512 * be safe, we start the new tape by writing the last bufferfull from
1513 * the old one. This insures that all archives will be on at least
1514 * one tape. Sounds inelegant, but it works.
1515 * @param bkpinfo The backup information structure. @c bkpinfo->tmpdir is the only field used.
1516 * @return 0 for success, nonzero for failure.
1517 */
1518int write_backcatalog_to_tape()
1519{
1520    int i, last, res = 0;
1521    char *fname = NULL;
1522
1523    log_msg(2, "I am now writing back catalog to tape");
1524    last = g_tapecatalog->entries - 1;
1525    for (i = 0; i <= last; i++) {
1526        mr_asprintf(fname, "%s/tmpfs/backcatalog/%s", bkpinfo->tmpdir, g_tapecatalog->el[i].fname);
1527        if (!does_file_exist(fname)) {
1528            log_msg(6, "Can't write %s - it doesn't exist.", fname);
1529        } else {
1530            write_header_block_to_stream(length_of_file(fname),
1531                                         "start-backcatalog-afio-or-slice",
1532                                         BLK_START_AN_AFIO_OR_SLICE);
1533            log_msg(2, "Writing %s", fname);
1534            if (write_file_to_stream_from_file(fname)) {
1535                res++;
1536                log_msg(2, "%s failed", fname);
1537            }
1538            if (i != last) {
1539                write_header_block_to_stream((off_t)0,
1540                                             "stop-backcatalog-afio-or-slice",
1541                                             BLK_STOP_AN_AFIO_OR_SLICE);
1542            }
1543        }
1544        mr_free(fname);
1545    }
1546    log_msg(2, "Finished writing back catalog to tape");
1547    return (res);
1548}
1549
1550
1551
1552/**
1553 * Write all.tar.gz (produced by Mindi) to the first 32M of the first tape.
1554 * @param fname The path to all.tar.gz.
1555 * @return 0 for success, nonzero for failure.
1556 */
1557int write_data_disks_to_stream(char *fname)
1558{
1559    /*@ pointers *************************************************** */
1560    FILE *fin;
1561
1562    /*@ long ******************************************************* */
1563    long m = -1;
1564    long templong;
1565
1566    /*@ int ******************************************************** */
1567    int i, j;
1568
1569    /*@ buffers **************************************************** */
1570    char tempblock[256 * 1024];
1571
1572    /*@ end vars *************************************************** */
1573
1574    open_evalcall_form("Writing data disks to tape");
1575    log_to_screen("Writing data disks to tape");
1576    log_it("Data disks = %s", fname);
1577    if (!does_file_exist(fname)) {
1578        log_to_screen("Cannot find %s", fname);
1579        return (1);
1580    }
1581    if (!(fin = fopen(fname, "r"))) {
1582        log_OS_error(fname);
1583        fatal_error("Cannot openin the data disk");
1584    }
1585    for (i = 0; i < 32; i++) {  /* 32MB */
1586        for (j = 0; j < 4; j++) {   /* 256K x 4 = 1MB (1024K) */
1587            if (!feof(fin)) {
1588                m = (long) fread(tempblock, 1, 256 * 1024, fin);
1589            } else {
1590                m = 0;
1591            }
1592            for (; m < 256 * 1024; m++) {
1593                tempblock[m] = '\0';
1594            }
1595            g_tape_posK +=
1596                fwrite(tempblock, 1, 256 * 1024, g_tape_stream) / 1024;
1597        }
1598        if (i > g_tape_buffer_size_MB)  // otherwise, 'buffer' distorts calculations
1599        {
1600            templong = ((i - 8) * 4 + j) * 100 / (128 - 8 * 4);
1601            update_evalcall_form((int) (templong));
1602        }
1603    }
1604    paranoid_fclose(fin);
1605    close_evalcall_form();
1606    return (0);
1607}
1608
1609
1610
1611
1612/**
1613 * Copy @p infile to the opened stream (CD or tape).
1614 * @param bkpinfo The backup information structure. @c bkpinfo->media_size is the only field used.
1615 * @param infile The file to write to the stream.
1616 * @return 0 for success, nonzero for failure.
1617 */
1618int write_file_to_stream_from_file(char *infile)
1619{
1620    /*@ buffers **************************************************** */
1621    char datablock[TAPE_BLOCK_SIZE];
1622    char *checksum = NULL;
1623    char *infile_basename;
1624
1625    /*@ int ******************************************************** */
1626    int retval = 0;
1627    int noof_blocks;
1628
1629    /*  unsigned int ch; */
1630    unsigned int crc16;
1631    unsigned int crctt;
1632
1633    /*@ pointers *************************************************** */
1634    FILE *fin;
1635    char *p;
1636
1637    /*@ long ******************************************************* */
1638    long bytes_to_read = 0;
1639    long i;
1640
1641    off_t filesize;
1642
1643#ifdef EXTRA_TAPE_CHECKSUMS
1644    int ch;
1645#endif
1646
1647    /*@ initialize ************************************************ */
1648    crc16 = 0;
1649    crctt = 0;
1650
1651
1652
1653    /*@ end vars *************************************************** */
1654
1655    infile_basename = strrchr(infile, '/');
1656    if (infile_basename) {
1657        infile_basename++;
1658    } else {
1659        infile_basename = infile;
1660    }
1661    filesize = length_of_file(infile);
1662    if (should_we_write_to_next_tape
1663        (bkpinfo->media_size[g_current_media_number], filesize)) {
1664        start_to_write_to_next_tape();
1665        write_backcatalog_to_tape();
1666    }
1667    p = strrchr(infile, '/');
1668    if (!p) {
1669        p = infile;
1670    } else {
1671        p++;
1672    }
1673    log_it("Writing file '%s' to tape (%ld KB)", p, (long) filesize >> 10);
1674    write_header_block_to_stream(filesize, infile_basename,
1675                                 BLK_START_FILE);
1676//go_here_to_restart_saving_of_file:
1677    if (!(fin = fopen(infile, "r"))) {
1678        log_OS_error(infile);
1679        return (1);
1680    }
1681    for (noof_blocks = 0; filesize > 0;
1682         noof_blocks++, filesize -= bytes_to_read) {
1683        if (filesize < TAPE_BLOCK_SIZE) {
1684            bytes_to_read = (long) filesize;
1685            for (i = 0; i < TAPE_BLOCK_SIZE; i++) {
1686                datablock[i] = '\0';
1687            }
1688        } else {
1689            bytes_to_read = TAPE_BLOCK_SIZE;
1690        }
1691        (void) fread(datablock, 1, (size_t) bytes_to_read, fin);
1692        g_tape_posK +=
1693            fwrite(datablock, 1, /*bytes_to_read */ 
1694                   (size_t) TAPE_BLOCK_SIZE,
1695                   g_tape_stream) / 1024;
1696        if (g_sigpipe) {
1697            log_it("Sigpipe occurred recently. I'll start a new tape.");
1698            fclose(fin);
1699            g_sigpipe = FALSE;
1700            start_to_write_to_next_tape();
1701            write_backcatalog_to_tape();    // kinda-sorta recursive :)
1702            return (0);
1703        }
1704#ifdef EXTRA_TAPE_CHECKSUMS
1705        for (i = 0; i < bytes_to_read; i++) {
1706            ch = datablock[i];
1707            crc16 = updcrcr(crc16, (unsigned) ch);
1708            crctt = updcrc(crctt, (unsigned) ch);
1709        }
1710#endif
1711    }
1712    paranoid_fclose(fin);
1713    mr_asprintf(checksum, "%04x%04x", crc16, crctt);
1714    /* BERLIOS: what does it do ??? */
1715    write_header_block_to_stream((off_t)g_current_media_number, checksum, BLK_STOP_FILE);
1716    mr_free(checksum);
1717
1718//  log_it("File '%s' written to tape.", infile);
1719    return (retval);
1720}
1721
1722
1723
1724
1725
1726/**
1727 * Write a header block to the opened stream (CD or tape).
1728 * @param length_of_incoming_file The length to store in the header block.
1729 * Usually matters only if this is a file-related header, in which case it should
1730 * be the length of the file that will follow.
1731 * @param filename The filename to store in the header block. Usually matters
1732 * only if this is a file-related header, in which case this should be the name
1733 * if the file that will follow.
1734 * @param control_char The type of header block this is (start-file, end-file, start-tape, ...)
1735 * @return 0 for success, nonzero for failure.
1736 */
1737int
1738write_header_block_to_stream(off_t length_of_incoming_file,
1739                             char *filename, int control_char)
1740{
1741    /*@ buffers **************************************************** */
1742    char tempblock[TAPE_BLOCK_SIZE];
1743    char *p;
1744
1745    /*@ int ******************************************************** */
1746    int i;
1747
1748    off_t olen;
1749
1750    /*@ end vars *************************************************** */
1751
1752
1753    olen = length_of_incoming_file;
1754    p = strrchr(filename, '/'); /* Make 'em go, "Unnnh!" Oh wait, that was _Master_ P... */
1755    if (!p) {
1756        p = filename;
1757    } else {
1758        p++;
1759    }
1760    if (!g_tape_stream) {
1761        log_to_screen("You're not backing up to tape. Why write a tape header?");
1762        return (1);
1763    }
1764    for (i = 0; i < (int) TAPE_BLOCK_SIZE; i++) {
1765        tempblock[i] = 0;
1766    }
1767    sprintf(tempblock + 6000 + control_char, STR_HEADER);
1768    tempblock[7000] = control_char;
1769    memcpy(tempblock + 7001, (char *) &olen, sizeof(off_t));
1770    strcpy(tempblock + 1000, filename);
1771    g_tape_posK += fwrite(tempblock, 1, (size_t) TAPE_BLOCK_SIZE, g_tape_stream) / 1024;
1772    log_msg(6, "%s (fname=%s, size=%ld K)", marker_to_string(control_char), p, (long) length_of_incoming_file >> 10);
1773    return (0);
1774}
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785/**
1786 * Log (to screen) an erroneous marker, along with what it should have been.
1787 * @param should_be What we were expecting.
1788 * @param it_is What we got.
1789 */
1790void wrong_marker(int should_be, int it_is)
1791{
1792    log_to_screen("Wrong marker! (Should be %s, is actually %s)", marker_to_string(should_be), marker_to_string(it_is));
1793}
1794
1795/* @} - end of streamGroup */
Note: See TracBrowser for help on using the repository browser.