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

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

Improvements for USB support in mindi when called from mondo
Changelogs in C files removed from common

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