source: trunk/mondo/mondo/common/libmondo-stream.c @ 507

Last change on this file since 507 was 507, checked in by bcornec, 13 years ago

merge -r489:506 $SVN_M/branches/stable

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