source: MondoRescue/branches/2.2.2/mondo/src/common/libmondo-stream.c @ 1316

Last change on this file since 1316 was 1316, checked in by Bruno Cornec, 13 years ago

MONDO_LOGFILE is rather a char* exported by each main program (consolidation of those mecanisms in .h files with ps_*)

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