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

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