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

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

merge -r671:686 $SVN_M/branches/stable

  • Property svn:keywords set to Id
File size: 46.8 KB
Line 
1/* $Id: libmondo-stream.c 687 2006-07-17 13:39:42Z 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 687 2006-07-17 13:39:42Z 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((off_t)0, "end-of-backup",
159                                     BLK_END_OF_BACKUP);
160    retval += write_header_block_to_stream((off_t)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], (off_t)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((off_t)-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((off_t)-1, acl_fname, BLK_STOP_EXAT_FILE);
394    write_header_block_to_stream(length_of_file(xattr_fname), xattr_fname,
395                                 BLK_STOP_EXTENDED_ATTRIBUTES);
396    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 */
1064
1065/* BERLIOS: Should be reviewed for mediasize being a off_t ??? */
1066bool
1067should_we_write_to_next_tape(long mediasize,
1068                             off_t 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((off_t)0, "start-of-tape", BLK_START_OF_TAPE);  /* just in case */
1308    res += write_header_block_to_stream((off_t)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((off_t)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    off_t filesize;
1451
1452#ifdef EXTRA_TAPE_CHECKSUMS
1453    int ch;
1454#endif
1455
1456    /*@ initialize ************************************************ */
1457    crc16 = 0;
1458    crctt = 0;
1459
1460    /*@ end vars *************************************************** */
1461
1462    infile_basename = strrchr(infile, '/');
1463    if (infile_basename) {
1464        infile_basename++;
1465    } else {
1466        infile_basename = infile;
1467    }
1468    filesize = length_of_file(infile);
1469    if (should_we_write_to_next_tape
1470        (bkpinfo->media_size[g_current_media_number], filesize)) {
1471        start_to_write_to_next_tape(bkpinfo);
1472        write_backcatalog_to_tape(bkpinfo);
1473    }
1474    p = strrchr(infile, '/');
1475    if (!p) {
1476        p = infile;
1477    } else {
1478        p++;
1479    }
1480    asprintf(&tmp, "Writing file '%s' to tape (%ld KB)", p,
1481             (long) filesize >> 10);
1482    log_it(tmp);
1483    paranoid_free(tmp);
1484
1485    write_header_block_to_stream(filesize, infile_basename,
1486                                 BLK_START_FILE);
1487//go_here_to_restart_saving_of_file:
1488    if (!(fin = fopen(infile, "r"))) {
1489        log_OS_error(infile);
1490        return (1);
1491    }
1492    for (noof_blocks = 0; filesize > 0;
1493         noof_blocks++, filesize -= bytes_to_read) {
1494        if (filesize < TAPE_BLOCK_SIZE) {
1495            bytes_to_read = (long) filesize;
1496            for (i = 0; i < TAPE_BLOCK_SIZE; i++) {
1497                datablock[i] = '\0';
1498            }
1499        } else {
1500            bytes_to_read = TAPE_BLOCK_SIZE;
1501        }
1502        (void) fread(datablock, 1, (size_t) bytes_to_read, fin);
1503        g_tape_posK += fwrite(datablock, 1, /*bytes_to_read */
1504                              (size_t) TAPE_BLOCK_SIZE,
1505                              g_tape_stream) / 1024;
1506        if (g_sigpipe) {
1507            iamhere("Sigpipe occurred recently. I'll start a new tape.");
1508            fclose(fin);
1509            g_sigpipe = FALSE;
1510            start_to_write_to_next_tape(bkpinfo);
1511            write_backcatalog_to_tape(bkpinfo); // kinda-sorta recursive :)
1512            return (0);
1513        }
1514#ifdef EXTRA_TAPE_CHECKSUMS
1515        for (i = 0; i < bytes_to_read; i++) {
1516            ch = datablock[i];
1517            crc16 = updcrcr(crc16, (unsigned) ch);
1518            crctt = updcrc(crctt, (unsigned) ch);
1519        }
1520#endif
1521    }
1522    paranoid_fclose(fin);
1523    asprintf(&checksum, "%04x%04x", crc16, crctt);
1524    /* BERLIOS: what does it do ??? */
1525    write_header_block_to_stream((off_t)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(off_t 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    off_t olen;
1557
1558    /*@ end vars *************************************************** */
1559
1560
1561    olen = length_of_incoming_file;
1562    p = strrchr(filename, '/'); /* Make 'em go, "Unnnh!" Oh wait, that was _Master_ P... */
1563    if (!p) {
1564        p = filename;
1565    } else {
1566        p++;
1567    }
1568    if (!g_tape_stream) {
1569        log_to_screen
1570            (_("You're not backing up to tape. Why write a tape header?"));
1571        return (1);
1572    }
1573    for (i = 0; i < (int) TAPE_BLOCK_SIZE; i++) {
1574        tempblock[i] = 0;
1575    }
1576    sprintf(tempblock + 6000 + control_char, "Mondolicious, baby");
1577    tempblock[7000] = control_char;
1578    memcpy(tempblock + 7001, (char *) &olen, sizeof(off_t));
1579    strcpy(tempblock + 1000, filename);
1580    g_tape_posK +=
1581        fwrite(tempblock, 1, (size_t) TAPE_BLOCK_SIZE,
1582               g_tape_stream) / 1024;
1583    asprintf(&tmp, "%s (fname=%s, size=%ld K)",
1584             marker_to_string(control_char), p,
1585             (long) length_of_incoming_file >> 10);
1586    log_msg(6, tmp);
1587    paranoid_free(tmp);
1588    return (0);
1589}
1590
1591
1592/**
1593 * Log (to screen) an erroneous marker, along with what it should have been.
1594 * @param should_be What we were expecting.
1595 * @param it_is What we got.
1596 */
1597void wrong_marker(int should_be, int it_is)
1598{
1599    /*@ buffer ***************************************************** */
1600    char *tmp;
1601
1602
1603    /*@ end vars *************************************************** */
1604    asprintf(&tmp, _("Wrong marker! (Should be %s, is actually %s)"),
1605             marker_to_string(should_be), marker_to_string(it_is));
1606    log_to_screen(tmp);
1607    paranoid_free(tmp);
1608}
1609
1610/* @} - end of streamGroup */
Note: See TracBrowser for help on using the repository browser.