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

Last change on this file since 1081 was 1081, checked in by bruno, 12 years ago

merge -r1078:1080 $SVN_M/branches/stable

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