source: branches/3.0/mondo/src/common/libmondo-stream.c @ 2900

Last change on this file since 2900 was 2900, checked in by bruno, 8 years ago

r4382@localhost: bruno | 2011-10-29 00:44:58 +0200

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