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

Last change on this file since 1939 was 1939, checked in by bruno, 11 years ago

svn merge -r 1923:1938 $SVN_M/branches/2.2.6

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