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

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