source: branches/stable/mondo/src/common/libmondo-stream.c @ 1175

Last change on this file since 1175 was 1175, checked in by Bruno Cornec, 13 years ago

Merge trunk memory management for libmondo-stream.c

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