source: MondoRescue/branches/2.2.10/mondo/src/common/libmondo-stream.c @ 2325

Last change on this file since 2325 was 2325, checked in by Bruno Cornec, 12 years ago

r3336@localhost: bruno | 2009-08-11 16:32:36 +0200

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