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

Last change on this file since 955 was 955, checked in by bruno, 13 years ago

fix a difference with trunk

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