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

Last change on this file since 147 was 147, checked in by bcornec, 14 years ago

Quality errors handled

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