source: trunk/mondo/mondo/mondorestore/mondo-restore.c @ 59

Last change on this file since 59 was 59, checked in by bcornec, 14 years ago

Trunk: indent on all source files

  • Property svn:keywords set to Id
File size: 113.3 KB
Line 
1/***************************************************************************
2       mondo-restore.c  -  restores mondoarchive data
3                             -------------------
4    begin                : Fri May 19 2000
5    copyright            : (C) 2000 by Hugo Rabson
6    email                : Hugo Rabson <hugorabson@msn.com>
7    cvsid                : $Id: mondo-restore.c 59 2005-10-10 23:34:31Z bcornec $
8***************************************************************************/
9
10/***************************************************************************
11 *                                                                         *
12 *   This program is free software; you can redistribute it and/or modify  *
13 *   it under the terms of the GNU General Public License as published by  *
14 *   the Free Software Foundation; either version 2 of the License, or     *
15 *   (at your option) any later version.                                   *
16 *                                                                         *
17 ***************************************************************************/
18
19/***************************************************************************
20 *                         Change Log                                      *
21 ***************************************************************************
22.
23
24
2507/26
26- workaround - if not /dev then don't call partimagehack
27
2807/21
29- if switch to Interactive Mode during nuke then don't nuke twice :) just once
30
3107/18
32- better support of users who boot from LVM CD and nuke-restore non-LVM backups
33
3407/10
35- when using 'star', exclude all 'not removed.' messages from log (misleading, they are)
36- try w/ ACLs, then w/o ACLs if star fails w/ ACLs
37- added ACL, xattr support for afio
38
3906/26
40- remove make_relevant_partition_bootable(); roll into mondo-prep.c
41- changed various newtDrawRootText() calls to use g_noof_rows instead of
42  integers
43
4406/19
45- don't try to access biggiestruct before it is populated w/ data relating
46  to biggiefile; instead, use control char to find out if biggiefile is
47  to be restored w/ partimagehack or not
48- added AUX_VER
49
5006/15
51- read_cfg_file_into_bkpinfo() --- use user-supplied 'isodir' instead of
52  archive's 'isodir' if different
53  Conor Daly <conor.daly@met.ie>
54
5506/17
56- restore with partimagehack if NTFS device; dd, if non-NTFS device
57
5806/14
59- unmount all; remount, run grub-mr; unmount again
60
6104/09
62- fixed subset restoration bug introduced when I added 'star' support
63
6404/04
65- cleaned up restore_a_tarball_from_stream()
66
6704/03
68- added star support
69- pause for 3s between partitioning and formatting (if in Nuke Mode)
70
7103/28
72- check that g_mountlist_fname was correcfly set; abort if it wasn't
73
7403/25
75- removed dev_null code
76
7703/22/04
78- added mode_of_file()
79- added code to check for unauthorised modification of /dev/null
80  by afio (for instance)
81
8212/27/03
83- check /tmp/cmdline instead of /proc/cmdline if on FreeBSD
84
8511/15
86- added g_fprep
87- "Switch to interactive mode?" msg is now more informative
88
8911/05
90- after 'Are you sure?' when user specifies / as restore path, set
91  restore_path[] to "" so that files are restored to [blank]/file/name :)
92
9310/29
94- moved "No restoring or comparing will take place today" block
95  up to before iso_fiddly_bits (if iso) is called - fix bug
96  if you're in ISO Mode and you say "exit to shell"
97
9810/22
99- swapped calls to chmod() and chown() after restoration
100  of big files (Jens)
101
10210/21
103- changed "/mnt/cdrom" to MNT_CDROM
104
10510/19
106- restore biggiefiles selectively from CD properly
107- use find_my_editor() to find pico/vi/whatever
108- better use of call_program_and_get_last_line_of_output() to
109  scan /proc/cmdline
110
11110/18
112- don't report 'missing compressor' if no compressor used at all
113
11410/14
115- log afio's error messages to /var/log/mondo-archive.log
116  when restoring :)
117- call vi if pico is not available
118
11910/09
120- better logging if fatal error (cannot openout bigfile)
121- better GUI feedback when restoring big files
122- restore_everything() now uses s_node* instead of char*
123- ditto restore_all_*_from_*()
124
12510/02
126- succinct msg instead of pop-ups, if used -H
127
12809/27
129- tweaked restore-time gui
130
13109/26
132- proper reporting of DVD/CDR/etc. type in displayed dialogs
133
13409/23
135- malloc/free global strings in new subroutines - malloc_libmondo_global_strings()
136  and free_libmondo_global_strings() - which are in libmondo-tools.c
137
13809/21
139- trying to fix "mondorestore <no params>" segfault
140
14109/18
142- better remounting of /
143- cleaned up run_grub()
144- sensible command-line handling in Live Mode
145
14609/17
147- cleaned up GRUB installer script a bit
148
14909/15
150- remount / as r/w if in disaster recovery mode;
151  helps for b0rken distros
152
15309/13
154- major NTFS hackage
155
15609/12
157- changed some in-sub var decl'ns to malloc()'s
158
15909/05
160- don't let me run unless I'm root
161- finished NTFS/partimagehack support (CD only); working on tape now
162
16309/01
164- fixed cosmetic bug in biggiefile restore window
165
16606/01 - 08/31
167- added code to main() to make sure NFS
168  (backup) share is mounted in Nuke and Compare Modes
169- added code to run_grub() to mount /boot before running grub-install
170- fixed some stray assert()'s in restore_a_biggiefile_from_stream()
171- fixed bugs in extract_config_file_from_ramdisk()
172  and get_cfg_file_from_archive() which
173  stopped fape+floppy users from being able to
174  boot from floppy and leave floppy in drive :)
175- added hooks to partimage for doing imagedevs
176- fixed calls to popup_and_get_string()
177
17805/01 - 05/31
179- fixed biggiefile atime/utime dates restoration bug, I think
180- added misc clean-up (Steve Hindle)
181- fixed support for subdir-within-NFS-mount
182- if nuke mode fails & user reverts to interactive mode _and succeeds_,
183  don't claim nuke mode aborted :)
184- unmount_all_devices() uses mountlist->el[lino].mountpt
185  instead of mountlist->el[lino].device where possible
186- added Joshua Oreman's FreeBSD patches
187- copied missing paragraph from 1.6x's read_cfg_file_into_bkpinfo()
188  to 1.7x's; affected tape streamer users (badly!)
189- cleaned up some paranoid assert()'s
190- use which("post-nuke") instead of find_home_of_exe("post-nuke")
191- fixed "Don't eject while restoring" mode
192- get_cfg_file_from_archive() --- also recovers mountlist.txt now :)
193- don't eject if 'donteject' is in kernel's command line
194- added 'don't panic' msg to start of log
195
19604/01 - 04/30
197- added text mode (cat /proc/cmdline; if textonly then text mode is on)
198- delete /var/lock/subsys/ * when nuking
199- don't resize mountlist if "noresize" present in /proc/cmdline
200- changed from chmod -R 1777 tmp to chmod 1777 tmp
201- replace newtFinished() and newtInit() with
202  newtSuspend() and newtResume()
203- get_cfg_file_from_archive() returns 1 instead of aborting now
204- read_cfg_file_into_bkpinfo) --- if autorun CD but its config
205  file indicates a non-CD backup media then ask, just in case
206- sped up restore_a_tarball_from_CD() a bit
207- line 4469 --- if post-nuke not found then don't run it :)
208- replaced "/mnt/RESTORING" with MNT_RESTORING (#define'd)
209- moved compare_*() into mondorestore/mondo-rstr-compare.c
210- moved some RAID subroutines into common/libmondo-raid.c
211- fixed some iso live compare problems
212- replaced FILELIST_FULL with g_filelist_full and FILELIST_FULL_STUB;
213  g_filelist_full being the full path of the filelist.full text file and
214  FILELIST_FULL_STUB being "tmp/filelist.full" (relative path);
215- ditto BIGGIELIST_TXT, MONDO_CFG_FILE
216- added lots of assert()'s and log_OS_error()'s
217- in Nuke Mode, check mountlist's sanity before doing anything else;
218  if it fails sanity test, offer to revert to Interactive Mode (or abort)
219- copy log to /mnt/RESTORING/root at end
220- read_cfg_file_into_bkpinfo() --- read iso-dev and isodir if bkptype==iso
221- line 1701 --- delete ramdisk file after extracting config info
222- moved call to make_relevant_partitions_bootable() from
223  within run_boot_loader() to within interactive_mode() and
224  nuke_mode(), after unmounting disks
225- if editing fstab or *.conf, try to use pico if available
226- better calling of make-me-bootable
227- don't sort mountlist anywhere anymore except _locally_ in
228  mount_all_devices() and unmount_all_devices()
229- edit fstab, grub.conf _after_ stabgrub-me if it fails
230- run_boot_loader() --- backup all crucial files to /etc/ *.pristine first
231- added iso_fiddly_bits()
232- fixed ISO mode support
233- mount_cdrom() only searches for device if NOT in disaster recovery mode
234- changed lost of system()'s into run_program_and_log_output()'s
235- don't eject if bkpinfo->please_dont_eject_when_restoring
236- cleaned up post-nuke handling code
237- always eject CD at end, unless bkpinfo->please_dont_...
238- misc clean-up (Tom Mortell)
239- afio uses -c (1024L*1024L)/TAPE_BLOCK_SIZE now
240  instead of -c 1024
241
24201/01 - 03/31/2003
243- commented out sort_... line (BB)
244- clean-up (Stan Benoit)
245- added code for LVM and SW Raid (Brian Borgeson)
246- line 814 - added -p to 'mkdir -p tmp'
247- mount_cdrom() - calls find_cdrom_device() if
248  bkpinfo->media_device is blank (to fill it)
249
25011/01 - 12/31/2002
251- mount_cdrom() better at handling multiple CD drives
252- minor clean-up in restore_a_tarball_from_CD()
253- if --live-from-cd then assume restoring live from CD
254- tweaked it to run better w/ ArkLinux
255- create /mnt/RESTORING/mnt/.boot.d for Gentoo users
256  after restoring
257- cleaned up iso_mode(); no longer asks for NFS info 3 times
258- mount_cdrom() was trying to mount /mnt/isodir/%s/%d.iso;
259  is now just %s/%d.iso
260- mount/unmount /boot if necessary (Gentoo)
261- added RAW MBR support; added run_raw_mbr() for the purpose
262- unmount & remount supermounts at start/end of live restore
263- copy /tmp/mountlist.txt to /tmp/mountlist.txt.orig at start
264- cleaned up string-handling in get_cfg_info_from_archives()
265- fixed run_grub() to call new stabgrub-me script
266- popup list of changed files after Compare Mode
267- permit mondorestore --edit-mountlist even if live mode
268- create a repaired copy of grub-install which is RAID-friendly;
269  use it when initializing boot sector with run_grub()
270- use grub-MR instead of grub-install
271- fixed read_cfg_file_into_bkpinfo() to ignore cfg file's backup_media_type
272  if user has already specified a backup media type interactively
273
27410/01 - 10/31
275- run_grub() will let you specify the boot device as well as edit the system
276  files, if grub-install fails
277- fixed bug in fwrite() call in restore_biggiefile_from_CD()
278- fixed bug affecting restoration of bigfiles from CD's w/0 compression
279- run_grub() will run 'grub-install {boot device}' instead of
280  'grub-install (hd0)'
281
28209/01 - 09/30
283- use /tmp/tmpfs/mondo.tmp instead of /tmp/mondo.tmp
284- initialize MOUNTLIST_FNAME at start of main()
285- differential-related cleanup
286- better handling of CD-ROM drives which aren't /dev/cdrom :)
287- run_program_and_log_output() now takes boolean operator to specify
288  whether it will log its activities in the event of _success_
289- always load config file from archive before operating on it
290- moved some subroutines around; now closer to alphabetical order
291- changed mount.mindi to mount.bootisk
292- mount disks readonly if in Compare Mode
293- set /dev/null's permissions to 777, just in case it somehow gets mangled
294  ...which apparently happen with some devfs-based Linux distributions
295- remove /var/run/ *.pid after restoring
296- move spurious lockfiles from /home/ * to /home/ * /.disabled
297- if Interactive Mode then ask user which media, etc. (i.e. catchall mode
298  is now same as Interactive Mode)
299
30008/01 - 08/30
301- use data structure to store the fname, checksum, mods & perms of each bigfile
302  ... biggiestruct :)
303- if a filelist is tiny (2 bytes or less) then ignore it
304- insist_on_this_cd_number() --- now takes 2 params, not 1
305- re-enabled 'g_current_media_number = 1' in restore_everything()
306- added same to compare_mode()
307- replaced lots of global char[]'s with malloc()'s
308- if differential backup then don't permit formatting or fdisking,
309  whether Interactive or Nuke mode
310- added call to register_pid() at start of main()
311- if Nuke Mode & it succeeds then ask user if they have contributed yet
312- changed tape-size to media-size (config file)
313- changed using_* to backup_media_type
314- changed *_from_tape to *_from_stream
315
31607/01 - 07/31
317- added find_and_mount_actual_cdrom()
318- temp dir is always random
319- skip tarballs if they don't contain files we're looking for
320  (used to read the whole thing & _then_ skip)
321- use media_size[1] instead of media_size[0]
322- fixed serious bug in line 1546 - should have been !=, not ==; stopped
323  mondorestore from correctly restoring big files
324- bigfile piping enhancements (Philippe de Muyter)
325- unmount CD-ROM after restoring from live filesystem
326- TAPE_BLOCK_SIZE treated as %ld, not %d
327
32806/01 - 06/30
329- added signal-trapping
330- disabled 'nr-failed-disks' flag
331- fixed problem w/selective restore
332- don't change /tmp's permissions unless it doesn't exist & must be created
333- fixed bug in --mbr
334- is_file_in_list() enhanced to exclude /mnt/RESTORING or whatever
335- added support for uncompressed archives
336- --monitas-live now accepts path-to-restore_to_, not just path to restore
337- added some debugging/tracking code to the NFS section
338- various monitas-related enhancements
339- added --isonuke and --mbr switches
340- better logging in run_grub()
341- improved --monitas-live
342- mkdir -p /mnt/RESTORING/var/run/console just in case user excludes it
343- afio now uses 16MB buffer instead of 8MB
344- always use bkpinfo->media_size[0], now that -s has been expanded
345- popup and ask where to restore data, if restoring selectively
346
34705/01 - 05/31
348- add '--monitas' flag
349- don't run chmod -R 1777 /mnt/RESTORING/tmp before unmounting unless
350  restoring at the time...
351
35204/01 - 04/30
353- delete old /tmp/filelist.full,biggielist.txt if found when restoring to
354  live filesystem
355- replace MONDO_VERSION #define with VERSION from ../config.h
356- write fname of bigfile to screen when having trouble reading/comparing it
357- if restoring to live filesystem then wipe /tmp/tmpfs/ * afterwards
358- removed spurious finish(0) from main()
359
36003/01 - 03/31/2002
361- if /tmp/m*ndo-restore.cfg not found then assume live restore; restore
362  to / instead of /mnt/RESTORING
363- clean up is_file_in_list() to deal with the /mnt/RESTORING/ prefix
364- exclude leading '/' from filelist.restore-these
365- if /tmp/fstab.new exists then use _it_ instead of /tmp/fstab to label
366  ext2 or ext3 partitions
367- improved logging
368
369[...]
370
37107/10/2001 --- first incarnation
372*/
373
374
375/**
376 * @file
377 * The main file for mondorestore.
378 */
379
380/**************************************************************************
381 * #include statements                                                    *
382 **************************************************************************/
383#include <pthread.h>
384#include "../common/my-stuff.h"
385#include "../common/mondostructures.h"
386#include "../common/libmondo.h"
387#include "mr-externs.h"
388#include "mondo-restore.h"
389#include "mondo-rstr-compare-EXT.h"
390#include "mondo-rstr-tools-EXT.h"
391
392extern void success_message(void);
393extern void twenty_seconds_til_yikes(void);
394
395
396/* For use in other programs (ex. XMondo) */
397#ifdef MONDORESTORE_MODULE
398#define main __mondorestore_main
399#define g_ISO_restore_mode __mondorestore_g_ISO_restore_mode
400#endif
401
402#ifndef VERSION
403#define VERSION AUX_VER
404#endif
405
406char g_version[] = VERSION;
407
408
409//static char cvsid[] = "$Id: mondo-restore.c 59 2005-10-10 23:34:31Z bcornec $";
410
411/**************************************************************************
412 * Globals                                                                *
413 **************************************************************************/
414extern char *g_tmpfs_mountpt;   // declared in libmondo-tools.c
415extern struct s_bkpinfo *g_bkpinfo_DONTUSETHIS; // used by finish() to free
416                                                // up global bkpinfo struct
417extern bool g_text_mode;
418extern FILE *g_fprep;
419extern double g_kernel_version;
420extern int g_partition_table_locked_up;
421extern int g_noof_rows;
422
423extern int partition_everything(struct mountlist_itself *mountlist);
424
425
426/**
427 * @name Restore-Time Globals
428 * @ingroup globalGroup
429 * @{
430 */
431/**
432 * If TRUE, then SIGPIPE was just caught.
433 * Set by the signal handler; cleared after it's handled.
434 */
435bool g_sigpipe_caught = FALSE;
436
437/**
438 * If TRUE, then we're restoring from ISOs or an NFS server.
439 * If FALSE, then we're restoring from some kind of real media (tape, CD, etc.)
440 */
441bool g_ISO_restore_mode = FALSE;    /* are we in Iso Mode? */
442
443/**
444 * If TRUE, then we have had a successful "nuke" restore.
445 */
446bool g_I_have_just_nuked = FALSE;
447
448/**
449 * The device to mount to get at the ISO images. Ignored unless @p g_ISO_restore_mode.
450 */
451char *g_isodir_device;
452
453/**
454 * The format of @p g_isodir_device. Ignored unless @p g_ISO_restore_mode.
455 */
456char *g_isodir_format;
457
458/**
459 * The location of 'biggielist.txt', containing the biggiefiles on the current archive set.
460 */
461char *g_biggielist_txt;
462
463/**
464 * The location of 'filelist.full', containing all files (<em>including biggiefiles</em>) on
465 * the current archive set.
466 */
467char *g_filelist_full;
468
469/**
470 * The location of a file containing a list of the devices that were archived
471 * as images, not as individual files.
472 */
473char *g_filelist_imagedevs;
474
475/**
476 * The location of a file containing a list of imagedevs to actually restore.
477 * @see g_filelist_imagedevs
478 */
479char *g_imagedevs_restthese;
480
481/**
482 * The location of 'mondo-restore.cfg', containing the metadata
483 * information for this backup.
484 */
485char *g_mondo_cfg_file;
486
487/**
488 * The location of 'mountlist.txt', containing the information on the
489 * user's partitions and hard drives.
490 */
491char *g_mountlist_fname;
492
493/**
494 * Mondo's home directory during backup. Unused in mondo-restore; included
495 * to avoid link errors.
496 */
497char *g_mondo_home;
498
499/* @} - end of "Restore-Time Globals" in globalGroup */
500
501
502
503extern int copy_from_src_to_dest(FILE * f_orig, FILE * f_archived,
504                                 char direction);
505
506
507
508/**************************************************************************
509 * COMPAQ PROLIANT Stuff:  needs some special help                        *
510**************************************************************************/
511
512/**
513 * The message to display if we detect that the user is using a Compaq Proliant.
514 */
515#define COMPAQ_PROLIANTS_SUCK "Partition and format your disk using Compaq's disaster recovery CD. After you've done that, please reboot with your Mondo CD/floppy in Interactive Mode."
516
517
518
519
520/**
521 * Allow the user to modify the mountlist before we partition & format their drives.
522 * @param bkpinfo The backup information structure. @c disaster_recovery is the only field used.
523 * @param mountlist The mountlist to let the user modify.
524 * @param raidlist The raidlist that goes with @p mountlist.
525 * @return 0 for success, nonzero for failure.
526 * @ingroup restoreGuiGroup
527 */
528int let_user_edit_the_mountlist(struct s_bkpinfo *bkpinfo,
529                                struct mountlist_itself *mountlist,
530                                struct raidlist_itself *raidlist)
531{
532    int retval = 0, res = 0;
533
534    log_msg(2, "let_user_edit_the_mountlist() --- starting");
535
536    assert(bkpinfo != NULL);
537    assert(mountlist != NULL);
538    assert(raidlist != NULL);
539    if (!bkpinfo->disaster_recovery) {
540        strcpy(g_mountlist_fname, "/tmp/mountlist.txt");
541        log_msg(2, "I guess you're testing edit_mountlist()");
542    }
543    if (!does_file_exist(g_mountlist_fname)) {
544        log_to_screen(g_mountlist_fname);
545        log_to_screen("does not exist");
546        return (1);
547    }
548
549    retval = load_mountlist(mountlist, g_mountlist_fname);
550    load_raidtab_into_raidlist(raidlist, RAIDTAB_FNAME);
551    if (retval) {
552        log_to_screen
553            ("Warning - load_raidtab_into_raidlist returned an error");
554    }
555    res = edit_mountlist(g_mountlist_fname, mountlist, raidlist);
556    if (res) {
557        return (1);
558    }
559
560    save_mountlist_to_disk(mountlist, g_mountlist_fname);
561    save_raidlist_to_raidtab(raidlist, RAIDTAB_FNAME);
562
563    log_to_screen("I have finished editing the mountlist for you.");
564
565    return (retval);
566}
567
568
569
570
571
572/**
573 * Determine whether @p mountlist contains a Compaq diagnostic partition.
574 * @param mountlist The mountlist to examine.
575 * @return TRUE if there's a Compaq diagnostic partition; FALSE if not.
576 * @ingroup restoreUtilityGroup
577 */
578bool
579partition_table_contains_Compaq_diagnostic_partition(struct
580                                                     mountlist_itself *
581                                                     mountlist)
582{
583    int i;
584
585    assert(mountlist != NULL);
586
587    for (i = 0; i < mountlist->entries; i++) {
588        if (strstr(mountlist->el[i].format, "ompaq")) {
589            log_msg(2, "mountlist[%d] (%s) is %s (Compaq alert!)",
590                    i, mountlist->el[i].device, mountlist->el[i].format);
591
592            return (TRUE);
593        }
594    }
595    return (FALSE);
596}
597
598/**************************************************************************
599 *END_PARTITION_TABLE_CONTAINS_COMPAQ_DIAGNOSTIC_PARTITION                *
600 **************************************************************************/
601
602
603/**
604 * Allow the user to abort the backup if we find that there is a Compaq diagnostic partition.
605 * @note This function does not actually check for the presence of a Compaq partition.
606 * @ingroup restoreUtilityGroup
607 */
608void offer_to_abort_because_Compaq_Proliants_suck(void)
609{
610    popup_and_OK(COMPAQ_PROLIANTS_SUCK);
611    if (ask_me_yes_or_no
612        ("Would you like to reboot and use your Compaq CD to prep your hard drive?"))
613    {
614        fatal_error
615            ("Aborting. Please reboot and prep your hard drive with your Compaq CD.");
616    }
617}
618
619/**************************************************************************
620 *END_OFFER_TO_ABORT_BECAUSE_COMPAQ_PROLIANTS_SUCK                        *
621 **************************************************************************/
622
623
624
625/**
626 * Call interactive_mode(), nuke_mode(), or compare_mode() depending on the user's choice.
627 * @param bkpinfo The backup information structure. Most fields are used.
628 * @param mountlist The mountlist containing information about the user's partitions.
629 * @param raidlist The raidlist to go with @p mountlist.
630 * @return The return code from the mode function called.
631 * @ingroup restoreGroup
632 */
633int
634catchall_mode(struct s_bkpinfo *bkpinfo,
635              struct mountlist_itself *mountlist,
636              struct raidlist_itself *raidlist)
637{
638    char c, *tmp;
639    int retval = 0;
640
641    iamhere("inside catchall");
642    assert(bkpinfo != NULL);
643    assert(mountlist != NULL);
644    assert(raidlist != NULL);
645    malloc_string(tmp);
646    iamhere("pre wrm");
647    c = which_restore_mode();
648    iamhere("post wrm");
649    if (c == 'I' || c == 'N' || c == 'C') {
650        interactively_obtain_media_parameters_from_user(bkpinfo, FALSE);
651    } else {
652        popup_and_OK("No restoring or comparing will take place today.");
653        if (is_this_device_mounted("/mnt/cdrom")) {
654            run_program_and_log_output("umount /mnt/cdrom", FALSE);
655        }
656        if (g_ISO_restore_mode) {
657            sprintf(tmp, "umount %s", bkpinfo->isodir);
658            run_program_and_log_output(tmp, FALSE);
659        }
660        paranoid_MR_finish(0);
661    }
662
663    iamhere("post int");
664
665    if (bkpinfo->backup_media_type == iso) {
666        if (iso_fiddly_bits(bkpinfo, (c == 'N') ? TRUE : FALSE)) {
667            log_msg(2,
668                    "catchall_mode --- iso_fiddly_bits returned w/ error");
669            return (1);
670        } else {
671            log_msg(2, "catchall_mode --- iso_fiddly_bits ok");
672        }
673    }
674
675    if (c == 'I') {
676        log_msg(2, "IM selected");
677        retval += interactive_mode(bkpinfo, mountlist, raidlist);
678    } else if (c == 'N') {
679        log_msg(2, "NM selected");
680        retval += nuke_mode(bkpinfo, mountlist, raidlist);
681    } else if (c == 'C') {
682        log_msg(2, "CM selected");
683        retval += compare_mode(bkpinfo, mountlist, raidlist);
684    }
685    paranoid_free(tmp);
686    return (retval);
687}
688
689/**************************************************************************
690 *END_CATCHALL_MODE                                                      *
691 **************************************************************************/
692
693/**************************************************************************
694 *END_  EXTRACT_CONFIG_FILE_FROM_RAMDISK                                  *
695 **************************************************************************/
696
697
698/**
699 * Locate an executable in the directory structure rooted at @p restg.
700 * @param out_path Where to put the executable.
701 * @param fname The basename of the executable.
702 * @param restg The directory structure to look in.
703 * @note If it could not be found in @p restg then @p fname is put in @p out_path.
704 * @ingroup restoreUtilityGroup
705 */
706void
707find_pathname_of_executable_preferably_in_RESTORING(char *out_path,
708                                                    char *fname,
709                                                    char *restg)
710{
711    assert(out_path != NULL);
712    assert_string_is_neither_NULL_nor_zerolength(fname);
713
714    sprintf(out_path, "%s/sbin/%s", restg, fname);
715    if (does_file_exist(out_path)) {
716        sprintf(out_path, "%s/usr/sbin/%s", restg, fname);
717        if (does_file_exist(out_path)) {
718            sprintf(out_path, "%s/bin/%s", restg, fname);
719            if (does_file_exist(out_path)) {
720                sprintf(out_path, "%s/usr/bin/%s", restg, fname);
721                if (does_file_exist(out_path)) {
722                    strcpy(out_path, fname);
723                }
724            }
725        }
726    }
727}
728
729/**************************************************************************
730 *END_FIND_PATHNAME_OF_EXECUTABLE_PREFERABLY_IN_RESTORING                 *
731 **************************************************************************/
732
733
734
735
736/**
737 * @addtogroup restoreGroup
738 * @{
739 */
740/**
741 * Restore the user's data, in a disaster recovery situation, prompting the
742 * user about whether or not to do every step.
743 * The user can edit the mountlist, choose files to restore, etc.
744 * @param bkpinfo The backup information structure. Most fields are used.
745 * @param mountlist The mountlist containing information about the user's partitions.
746 * @param raidlist The raidlist to go with @p mountlist.
747 * @return 0 for success, or the number of errors encountered.
748 */
749int
750interactive_mode(struct s_bkpinfo *bkpinfo,
751                 struct mountlist_itself *mountlist,
752                 struct raidlist_itself *raidlist)
753{
754    int retval = 0;
755    int res;
756    int ptn_errs = 0;
757    int fmt_errs = 0;
758
759    bool done;
760    bool restore_all;
761
762  /** needs malloc **********/
763    char *tmp;
764    char *fstab_fname;
765    char *old_restpath;
766
767    struct s_node *filelist;
768
769    /* try to partition and format */
770
771    log_msg(2, "interactive_mode --- starting (great, assertions OK)");
772
773    malloc_string(tmp);
774    malloc_string(fstab_fname);
775    malloc_string(old_restpath);
776    assert(bkpinfo != NULL);
777    assert(mountlist != NULL);
778    assert(raidlist != NULL);
779
780    log_msg(2, "interactive_mode --- assertions OK");
781
782    if (g_text_mode) {
783        if (!ask_me_yes_or_no
784            ("Interactive Mode + textonly = experimental! Proceed anyway?"))
785        {
786            fatal_error("Wise move.");
787        }
788    }
789
790    iamhere("About to load config file");
791    get_cfg_file_from_archive_or_bust(bkpinfo);
792    read_cfg_file_into_bkpinfo(g_mondo_cfg_file, bkpinfo);
793    iamhere("Done loading config file; resizing ML");
794#ifdef __FreeBSD__
795    if (strstr
796        (call_program_and_get_last_line_of_output("cat /tmp/cmdline"),
797         "noresize"))
798#else
799    if (strstr
800        (call_program_and_get_last_line_of_output("cat /proc/cmdline"),
801         "noresize"))
802#endif
803    {
804        log_msg(1, "Not resizing mountlist.");
805    } else {
806        resize_mountlist_proportionately_to_suit_new_drives(mountlist);
807    }
808    for (done = FALSE; !done;) {
809        iamhere("About to edit mountlist");
810        if (g_text_mode) {
811            save_mountlist_to_disk(mountlist, g_mountlist_fname);
812            sprintf(tmp, "%s %s", find_my_editor(), g_mountlist_fname);
813            res = system(tmp);
814            load_mountlist(mountlist, g_mountlist_fname);
815        } else {
816            res = edit_mountlist(g_mountlist_fname, mountlist, raidlist);
817        }
818        iamhere("Finished editing mountlist");
819        if (res) {
820            paranoid_MR_finish(1);
821        }
822        log_msg(2, "Proceeding...");
823        save_mountlist_to_disk(mountlist, g_mountlist_fname);
824        save_raidlist_to_raidtab(raidlist, RAIDTAB_FNAME);
825        mvaddstr_and_log_it(1, 30, "Restoring Interactively");
826        if (bkpinfo->differential) {
827            log_to_screen("Because this is a differential backup, disk");
828            log_to_screen
829                (" partitioning and formatting will not take place.");
830            done = TRUE;
831        } else {
832            if (ask_me_yes_or_no
833                ("Do you want to erase and partition your hard drives?")) {
834                if (partition_table_contains_Compaq_diagnostic_partition
835                    (mountlist)) {
836                    offer_to_abort_because_Compaq_Proliants_suck();
837                    done = TRUE;
838                } else {
839                    twenty_seconds_til_yikes();
840                    g_fprep = fopen("/tmp/prep.sh", "w");
841                    ptn_errs = partition_everything(mountlist);
842                    if (ptn_errs) {
843                        log_to_screen
844                            ("Warning. Errors occurred during disk partitioning.");
845                    }
846
847                    fmt_errs = format_everything(mountlist, FALSE);
848                    if (!fmt_errs) {
849                        log_to_screen
850                            ("Errors during disk partitioning were handled OK.");
851                        log_to_screen
852                            ("Partitions were formatted OK despite those errors.");
853                        ptn_errs = 0;
854                    }
855                    if (!ptn_errs && !fmt_errs) {
856                        done = TRUE;
857                    }
858                }
859                paranoid_fclose(g_fprep);
860            } else {
861                mvaddstr_and_log_it(g_currentY++, 0,
862                                    "User opted not to partition the devices");
863                if (ask_me_yes_or_no
864                    ("Do you want to format your hard drives?")) {
865                    fmt_errs = format_everything(mountlist, TRUE);
866                    if (!fmt_errs) {
867                        done = TRUE;
868                    }
869                } else {
870                    ptn_errs = fmt_errs = 0;
871                    done = TRUE;
872                }
873            }
874            if (fmt_errs) {
875                mvaddstr_and_log_it(g_currentY++,
876                                    0,
877                                    "Errors occurred. Please repartition and format drives manually.");
878                done = FALSE;
879            }
880            if (ptn_errs & !fmt_errs) {
881                mvaddstr_and_log_it(g_currentY++,
882                                    0,
883                                    "Errors occurred during partitioning. Formatting, however, went OK.");
884                done = TRUE;
885            }
886            if (!done) {
887                if (!ask_me_yes_or_no("Re-edit the mountlist?")) {
888                    retval++;
889                    goto end_of_func;
890                }
891            }
892        }
893    }
894
895    /* mount */
896    if (mount_all_devices(mountlist, TRUE)) {
897        unmount_all_devices(mountlist);
898        retval++;
899        goto end_of_func;
900    }
901    /* restore */
902    if ((restore_all =
903         ask_me_yes_or_no("Do you want me to restore all of your data?")))
904    {
905        log_msg(1, "Restoring all data");
906        retval += restore_everything(bkpinfo, NULL);
907    } else
908        if ((restore_all =
909             ask_me_yes_or_no
910             ("Do you want me to restore _some_ of your data?"))) {
911        strcpy(old_restpath, bkpinfo->restore_path);
912        for (done = FALSE; !done;) {
913            unlink("/tmp/filelist.full");
914            filelist = process_filelist_and_biggielist(bkpinfo);
915            /* Now you have /tmp/tmpfs/filelist.restore-these and /tmp/tmpfs/biggielist.restore-these;
916               the former is a list of regular files; the latter, biggiefiles and imagedevs.
917             */
918            if (filelist) {
919              gotos_suck:
920                strcpy(tmp, old_restpath);
921// (NB: %s is where your filesystem is mounted now, by default)", MNT_RESTORING);
922                if (popup_and_get_string
923                    ("Restore path", "Restore files to where?", tmp,
924                     MAX_STR_LEN / 4)) {
925                    if (!strcmp(tmp, "/")) {
926                        if (!ask_me_yes_or_no("Are you sure?")) {
927                            goto gotos_suck;
928                        }
929                        tmp[0] = '\0';  // so we restore to [blank]/file/name :)
930                    }
931                    strcpy(bkpinfo->restore_path, tmp);
932                    log_msg(1, "Restoring subset");
933                    retval += restore_everything(bkpinfo, filelist);
934                    free_filelist(filelist);
935                } else {
936                    strcpy(bkpinfo->restore_path, old_restpath);
937                    free_filelist(filelist);
938                }
939                if (!ask_me_yes_or_no
940                    ("Restore another subset of your backup?")) {
941                    done = TRUE;
942                }
943            } else {
944                done = TRUE;
945            }
946        }
947        strcpy(old_restpath, bkpinfo->restore_path);
948    } else {
949        mvaddstr_and_log_it(g_currentY++,
950                            0,
951                            "User opted not to restore any data.                                  ");
952    }
953    if (retval) {
954        mvaddstr_and_log_it(g_currentY++,
955                            0,
956                            "Errors occurred during the restore phase.            ");
957    }
958
959    if (ask_me_yes_or_no("Initialize the boot loader?")) {
960        run_boot_loader(TRUE);
961    } else {
962        mvaddstr_and_log_it(g_currentY++,
963                            0,
964                            "User opted not to initialize the boot loader.");
965    }
966
967//  run_program_and_log_output("cp -af /etc/lvm " MNT_RESTORING "/etc/", 1);
968    protect_against_braindead_sysadmins();
969    //  modify_rclocal_one_time( MNT_RESTORING "/etc" );
970    retval += unmount_all_devices(mountlist);
971    /*  if (restore_some || restore_all || */
972    if (ask_me_yes_or_no
973        ("Label your ext2 and ext3 partitions if necessary?")) {
974        mvaddstr_and_log_it(g_currentY, 0,
975                            "Using e2label to label your ext2,3 partitions");
976        if (does_file_exist("/tmp/fstab.new")) {
977            strcpy(fstab_fname, "/tmp/fstab.new");
978        } else {
979            strcpy(fstab_fname, "/tmp/fstab");
980        }
981        sprintf(tmp,
982                "label-partitions-as-necessary %s < %s >> %s 2>> %s",
983                g_mountlist_fname, fstab_fname, MONDO_LOGFILE,
984                MONDO_LOGFILE);
985        res = system(tmp);
986        if (res) {
987            log_to_screen
988                ("label-partitions-as-necessary returned an error");
989            mvaddstr_and_log_it(g_currentY++, 74, "Failed.");
990        } else {
991            mvaddstr_and_log_it(g_currentY++, 74, "Done.");
992        }
993        retval += res;
994    }
995
996    iamhere("About to leave interactive_mode()");
997    if (retval) {
998        mvaddstr_and_log_it(g_currentY++,
999                            0,
1000                            "Warning - errors occurred during the restore phase.");
1001    }
1002  end_of_func:
1003    paranoid_free(tmp);
1004    paranoid_free(fstab_fname);
1005    paranoid_free(old_restpath);
1006    iamhere("Leaving interactive_mode()");
1007    return (retval);
1008}
1009
1010/**************************************************************************
1011 *END_INTERACTIVE_MODE                                                    *
1012 **************************************************************************/
1013
1014
1015
1016/**
1017 * Run an arbitrary restore mode (prompt the user), but from ISO images
1018 * instead of real media.
1019 * @param bkpinfo The backup information structure. Most fields are used.
1020 * @param mountlist The mountlist containing information about the user's partitions.
1021 * @param raidlist The raidlist that goes with @p mountlist.
1022 * @param nuke_me_please If TRUE, we plan to run Nuke Mode.
1023 * @return 0 for success, or the number of errors encountered.
1024 */
1025int
1026iso_mode(struct s_bkpinfo *bkpinfo,
1027         struct mountlist_itself *mountlist,
1028         struct raidlist_itself *raidlist, bool nuke_me_please)
1029{
1030    char c;
1031    int retval = 0;
1032
1033    assert(bkpinfo != NULL);
1034    assert(mountlist != NULL);
1035    assert(raidlist != NULL);
1036    if (iso_fiddly_bits(bkpinfo, nuke_me_please)) {
1037        log_msg(1, "iso_mode --- returning w/ error");
1038        return (1);
1039    } else {
1040        c = which_restore_mode();
1041        if (c == 'I' || c == 'N' || c == 'C') {
1042            interactively_obtain_media_parameters_from_user(bkpinfo,
1043                                                            FALSE);
1044        }
1045        if (c == 'I') {
1046            retval += interactive_mode(bkpinfo, mountlist, raidlist);
1047        } else if (c == 'N') {
1048            retval += nuke_mode(bkpinfo, mountlist, raidlist);
1049        } else if (c == 'C') {
1050            retval += compare_mode(bkpinfo, mountlist, raidlist);
1051        } else {
1052            log_to_screen("OK, I shan't restore/compare any files.");
1053        }
1054    }
1055    if (is_this_device_mounted(MNT_CDROM)) {
1056        paranoid_system("umount " MNT_CDROM);
1057    }
1058//  if (! already_mounted)
1059//    {
1060    if (system("umount /tmp/isodir 2> /dev/null")) {
1061        log_to_screen
1062            ("WARNING - unable to unmount device where the ISO files are stored.");
1063    }
1064//    }
1065    return (retval);
1066}
1067
1068/**************************************************************************
1069 *END_ISO_MODE                                                            *
1070 **************************************************************************/
1071
1072
1073/*            MONDO - saving your a$$ since Feb 18th, 2000            */
1074
1075
1076
1077
1078/**
1079 * Restore the user's data automatically (no prompts), after a twenty-second
1080 * warning period.
1081 * @param bkpinfo The backup information structure. Most fields are used.
1082 * @param mountlist The mountlist containing information about the user's partitions.
1083 * @param raidlist The raidlist that goes with @p mountlist.
1084 * @return 0 for success, or the number of errors encountered.
1085 * @warning <b><i>THIS WILL ERASE ALL EXISTING DATA!</i></b>
1086 */
1087int
1088nuke_mode(struct s_bkpinfo *bkpinfo,
1089          struct mountlist_itself *mountlist,
1090          struct raidlist_itself *raidlist)
1091{
1092    int retval = 0;
1093    int res = 0;
1094    bool boot_loader_installed = FALSE;
1095  /** malloc **/
1096    char tmp[MAX_STR_LEN], tmpA[MAX_STR_LEN], tmpB[MAX_STR_LEN],
1097        tmpC[MAX_STR_LEN];
1098
1099    assert(bkpinfo != NULL);
1100    assert(mountlist != NULL);
1101    assert(raidlist != NULL);
1102
1103    log_msg(2, "nuke_mode --- starting");
1104
1105    get_cfg_file_from_archive_or_bust(bkpinfo);
1106    load_mountlist(mountlist, g_mountlist_fname);   // in case read_cfg_file_into_bkpinfo updated the mountlist
1107#ifdef __FreeBSD__
1108    if (strstr
1109        (call_program_and_get_last_line_of_output("cat /tmp/cmdline"),
1110         "noresize"))
1111#else
1112    if (strstr
1113        (call_program_and_get_last_line_of_output("cat /proc/cmdline"),
1114         "noresize"))
1115#endif
1116    {
1117        log_msg(2, "Not resizing mountlist.");
1118    } else {
1119        resize_mountlist_proportionately_to_suit_new_drives(mountlist);
1120    }
1121    if (!evaluate_mountlist(mountlist, tmpA, tmpB, tmpC)) {
1122        sprintf(tmp,
1123                "Mountlist analyzed. Result: \"%s %s %s\" Switch to Interactive Mode?",
1124                tmpA, tmpB, tmpC);
1125        if (ask_me_yes_or_no(tmp)) {
1126            retval = interactive_mode(bkpinfo, mountlist, raidlist);
1127            finish(retval);
1128        } else {
1129            fatal_error("Nuke Mode aborted. ");
1130        }
1131    }
1132    save_mountlist_to_disk(mountlist, g_mountlist_fname);
1133    mvaddstr_and_log_it(1, 30, "Restoring Automatically");
1134    if (bkpinfo->differential) {
1135        log_to_screen("Because this is a differential backup, disk");
1136        log_to_screen("partitioning and formatting will not take place.");
1137        res = 0;
1138    } else {
1139        if (partition_table_contains_Compaq_diagnostic_partition
1140            (mountlist)) {
1141            offer_to_abort_because_Compaq_Proliants_suck();
1142        } else {
1143            twenty_seconds_til_yikes();
1144            g_fprep = fopen("/tmp/prep.sh", "w");
1145#ifdef __FreeBSD__
1146            if (strstr
1147                (call_program_and_get_last_line_of_output
1148                 ("cat /tmp/cmdline"), "nopart"))
1149#else
1150            if (strstr
1151                (call_program_and_get_last_line_of_output
1152                 ("cat /proc/cmdline"), "nopart"))
1153#endif
1154            {
1155                log_msg(2,
1156                        "Not partitioning drives due to 'nopart' option.");
1157                res = 0;
1158            } else {
1159                res = partition_everything(mountlist);
1160                if (res) {
1161                    log_to_screen
1162                        ("Warning. Errors occurred during partitioning.");
1163                    res = 0;
1164                }
1165            }
1166            retval += res;
1167            if (!res) {
1168                log_to_screen("Preparing to format your disk(s)");
1169                sleep(1);
1170                system("sync");
1171                log_to_screen("Please wait. This may take a few minutes.");
1172                res += format_everything(mountlist, FALSE);
1173            }
1174            paranoid_fclose(g_fprep);
1175        }
1176    }
1177    retval += res;
1178    if (res) {
1179        mvaddstr_and_log_it(g_currentY++,
1180                            0,
1181                            "Failed to partition and/or format your hard drives.");
1182
1183        if (ask_me_yes_or_no("Try in interactive mode instead?")) {
1184            retval = interactive_mode(bkpinfo, mountlist, raidlist);
1185            goto after_the_nuke;
1186        } else
1187            if (!ask_me_yes_or_no
1188                ("Would you like to try to proceed anyway?")) {
1189            return (retval);
1190        }
1191    }
1192    retval = mount_all_devices(mountlist, TRUE);
1193    if (retval) {
1194        unmount_all_devices(mountlist);
1195        log_to_screen
1196            ("Unable to mount all partitions. Sorry, I cannot proceed.");
1197        return (retval);
1198    }
1199    iamhere("Restoring everything");
1200    retval += restore_everything(bkpinfo, NULL);
1201    if (!run_boot_loader(FALSE)) {
1202        log_msg(1,
1203                "Great! Boot loader was installed. No need for msg at end.");
1204        boot_loader_installed = TRUE;
1205    }
1206    protect_against_braindead_sysadmins();
1207//  run_program_and_log_output("cp -af /etc/lvm " MNT_RESTORING "/etc/", 1);
1208    //  modify_rclocal_one_time( MNT_RESTORING "/etc" );
1209    retval += unmount_all_devices(mountlist);
1210    mvaddstr_and_log_it(g_currentY,
1211                        0,
1212                        "Using e2label to label your ext2,3 partitions");
1213
1214    sprintf(tmp, "label-partitions-as-necessary %s < /tmp/fstab",
1215            g_mountlist_fname);
1216    res = run_program_and_log_output(tmp, TRUE);
1217    if (res) {
1218        log_to_screen("label-partitions-as-necessary returned an error");
1219        mvaddstr_and_log_it(g_currentY++, 74, "Failed.");
1220    } else {
1221        mvaddstr_and_log_it(g_currentY++, 74, "Done.");
1222    }
1223    retval += res;
1224
1225  after_the_nuke:
1226    if (retval) {
1227        log_to_screen("Errors occurred during the nuke phase.");
1228    } else if (strstr(call_program_and_get_last_line_of_output("cat /proc/cmdline"), "RESTORE"))    // Bruno's thing
1229    {
1230        log_to_screen
1231            ("PC was restored successfully. Thank you for using Mondo Rescue.");
1232        log_to_screen
1233            ("Please visit http://www.mondorescue.org and thank the dev team.");
1234    } else {
1235#ifdef FREELOADER
1236        success_message();
1237#else
1238        log_to_screen("PC was restored successfully!");
1239#endif
1240    }
1241    g_I_have_just_nuked = TRUE;
1242/*
1243  if (!boot_loader_installed && !does_file_exist(DO_MBR_PLEASE))
1244    {
1245      log_to_screen("PLEASE RUN 'mondorestore --mbr' NOW TO INITIALIZE YOUR BOOT SECTOR");
1246      write_one_liner_data_file(DO_MBR_PLEASE, "mondorestore --mbr");
1247    }
1248*/
1249    return (retval);
1250}
1251
1252/**************************************************************************
1253 *END_NUKE_MODE                                                           *
1254 **************************************************************************/
1255
1256
1257
1258/**
1259 * Restore the user's data (or a subset of it) to the live filesystem.
1260 * This should not be called if we're booted from CD!
1261 * @param bkpinfo The backup information structure. Most fields are used.
1262 * @return 0 for success, or the number of errors encountered.
1263 */
1264int restore_to_live_filesystem(struct s_bkpinfo *bkpinfo)
1265{
1266    int retval = 0;
1267
1268  /** malloc **/
1269    char *old_restpath;
1270
1271    struct mountlist_itself *mountlist;
1272//  static
1273    struct raidlist_itself *raidlist;
1274    struct s_node *filelist;
1275
1276    log_msg(1, "restore_to_live_filesystem() - starting");
1277    assert(bkpinfo != NULL);
1278    malloc_string(old_restpath);
1279    mountlist = malloc(sizeof(struct mountlist_itself));
1280    raidlist = malloc(sizeof(struct raidlist_itself));
1281    if (!mountlist || !raidlist) {
1282        fatal_error("Cannot malloc() mountlist and/or raidlist");
1283    }
1284
1285    strcpy(bkpinfo->restore_path, "/");
1286    if (!g_restoring_live_from_cd) {
1287        popup_and_OK
1288            ("Please insert tape/CD/boot floppy, then hit 'OK' to continue.");
1289        sleep(1);
1290    }
1291    interactively_obtain_media_parameters_from_user(bkpinfo, FALSE);
1292    log_msg(2, "bkpinfo->media_device = %s", bkpinfo->media_device);
1293    if (!bkpinfo->media_device[0]) {
1294        log_msg(2, "Warning - failed to find media dev");
1295    }
1296
1297
1298    log_msg(2, "bkpinfo->isodir = %s", bkpinfo->isodir);
1299
1300    open_evalcall_form("Thinking...");
1301
1302    get_cfg_file_from_archive_or_bust(bkpinfo);
1303    read_cfg_file_into_bkpinfo(g_mondo_cfg_file, bkpinfo);
1304    load_mountlist(mountlist, g_mountlist_fname);   // in case read_cfg_file_into_bkpinfo
1305
1306    close_evalcall_form();
1307    retval = load_mountlist(mountlist, g_mountlist_fname);
1308    load_raidtab_into_raidlist(raidlist, RAIDTAB_FNAME);
1309    filelist = process_filelist_and_biggielist(bkpinfo);
1310    if (filelist) {
1311        save_filelist(filelist, "/tmp/selected-files.txt");
1312        strcpy(old_restpath, bkpinfo->restore_path);
1313        if (popup_and_get_string("Restore path",
1314                                 "Restore files to where? )",
1315                                 bkpinfo->restore_path, MAX_STR_LEN / 4)) {
1316            iamhere("Restoring everything");
1317            retval += restore_everything(bkpinfo, filelist);
1318            free_filelist(filelist);
1319            strcpy(bkpinfo->restore_path, old_restpath);
1320        } else {
1321            free_filelist(filelist);
1322        }
1323        strcpy(bkpinfo->restore_path, old_restpath);
1324    }
1325    if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
1326        log_msg(2,
1327                "I probably don't need to unmount or eject the CD-ROM but I'm doing it anyway.");
1328    }
1329    run_program_and_log_output("umount " MNT_CDROM, FALSE);
1330    if (!bkpinfo->please_dont_eject) {
1331        eject_device(bkpinfo->media_device);
1332    }
1333    paranoid_free(old_restpath);
1334    free(mountlist);
1335    free(raidlist);
1336    return (retval);
1337}
1338
1339/**************************************************************************
1340 *END_RESTORE_TO_LIVE_FILESYSTEM                                          *
1341 **************************************************************************/
1342
1343/* @} - end of restoreGroup */
1344
1345
1346#include <utime.h>
1347/**
1348 * @addtogroup LLrestoreGroup
1349 * @{
1350 */
1351/**
1352 * Restore biggiefile @p bigfileno from the currently mounted CD.
1353 * @param bkpinfo The backup information structure. Fields used:
1354 * - @c bkpinfo->backup_media_type
1355 * - @c bkpinfo->restore_path
1356 * @param bigfileno The biggiefile number (starting from 0) to restore.
1357 * @param filelist The node structure containing the list of files to restore.
1358 * If the biggiefile is not in this list, it will be skipped (return value will
1359 * still indicate success).
1360 * @return 0 for success (or skip), nonzero for failure.
1361 */
1362int
1363restore_a_biggiefile_from_CD(struct s_bkpinfo *bkpinfo,
1364                             long bigfileno,
1365                             struct s_node *filelist,
1366                             char *pathname_of_last_file_restored)
1367{
1368    FILE *fin;
1369    FILE *fout;
1370    FILE *fbzip2;
1371
1372  /** malloc ***/
1373    char *checksum, *outfile_fname, *tmp, *bzip2_command,
1374        *partimagehack_command, *suffix, *sz_devfile;
1375    char *bigblk;
1376    char *p;
1377    int retval = 0;
1378    int finished = FALSE;
1379    long sliceno;
1380    long siz;
1381    char partimagehack_fifo[MAX_STR_LEN];
1382    char *file_to_openout = NULL;
1383    struct s_filename_and_lstat_info biggiestruct;
1384    struct utimbuf the_utime_buf, *ubuf;
1385    bool use_partimage_hack = FALSE;
1386    pid_t pid;
1387    int res = 0;
1388    int old_loglevel;
1389    char sz_msg[MAX_STR_LEN];
1390    struct s_node *node;
1391
1392    old_loglevel = g_loglevel;
1393    ubuf = &the_utime_buf;
1394    assert(bkpinfo != NULL);
1395
1396    malloc_string(checksum);
1397    malloc_string(outfile_fname);
1398    malloc_string(tmp);
1399    malloc_string(bzip2_command);
1400    malloc_string(partimagehack_command);
1401    malloc_string(suffix);
1402    malloc_string(sz_devfile);
1403
1404    pathname_of_last_file_restored[0] = '\0';
1405    if (!(bigblk = malloc(TAPE_BLOCK_SIZE))) {
1406        fatal_error("Cannot malloc bigblk");
1407    }
1408
1409    if (!(fin = fopen(slice_fname(bigfileno, 0, ARCHIVES_PATH, ""), "r"))) {
1410        log_to_screen("Cannot even open bigfile's info file");
1411        return (1);
1412    }
1413
1414    memset((void *) &biggiestruct, 0, sizeof(biggiestruct));
1415    if (fread((void *) &biggiestruct, 1, sizeof(biggiestruct), fin) <
1416        sizeof(biggiestruct)) {
1417        log_msg(2, "Warning - unable to get biggiestruct of bigfile #%d",
1418                bigfileno + 1);
1419    }
1420    paranoid_fclose(fin);
1421
1422    strcpy(checksum, biggiestruct.checksum);
1423
1424    if (!checksum[0]) {
1425        sprintf(tmp, "Warning - bigfile %ld does not have a checksum",
1426                bigfileno + 1);
1427        log_msg(3, tmp);
1428        p = checksum;
1429    }
1430
1431    if (!strncmp(biggiestruct.filename, "/dev/", 5))    // Whether NTFS or not :)
1432    {
1433        strcpy(outfile_fname, biggiestruct.filename);
1434    } else {
1435        sprintf(outfile_fname, "%s/%s", bkpinfo->restore_path,
1436                biggiestruct.filename);
1437    }
1438
1439    /* skip file if we have a selective restore subset & it doesn't match */
1440    if (filelist != NULL) {
1441        node = find_string_at_node(filelist, biggiestruct.filename);
1442        if (!node) {
1443            log_msg(0, "Skipping %s (name isn't in filelist)",
1444                    biggiestruct.filename);
1445            pathname_of_last_file_restored[0] = '\0';
1446            return (0);
1447        } else if (!(node->selected)) {
1448            log_msg(1, "Skipping %s (name isn't in biggielist subset)",
1449                    biggiestruct.filename);
1450            pathname_of_last_file_restored[0] = '\0';
1451            return (0);
1452        }
1453    }
1454    /* otherwise, continue */
1455
1456    log_msg(1, "DEFINITELY restoring %s", biggiestruct.filename);
1457    if (biggiestruct.use_partimagehack) {
1458        if (strncmp(biggiestruct.filename, "/dev/", 5)) {
1459            log_msg(1,
1460                    "I was in error when I set biggiestruct.use_partimagehack to TRUE.");
1461            log_msg(1, "%s isn't even in /dev", biggiestruct.filename);
1462            biggiestruct.use_partimagehack = FALSE;
1463        }
1464    }
1465
1466    if (biggiestruct.use_partimagehack) // if it's an NTFS device
1467//  if (!strncmp ( biggiestruct.filename, "/dev/", 5))
1468    {
1469        g_loglevel = 4;
1470        use_partimage_hack = TRUE;
1471        log_msg(2,
1472                "Calling partimagehack in background because %s is an NTFS /dev entry",
1473                outfile_fname);
1474        sprintf(sz_devfile, "/tmp/%d.%d.000", (int) (random() % 32768),
1475                (int) (random() % 32768));
1476        mkfifo(sz_devfile, 0x770);
1477        strcpy(partimagehack_fifo, sz_devfile);
1478        file_to_openout = partimagehack_fifo;
1479        switch (pid = fork()) {
1480        case -1:
1481            fatal_error("Fork failure");
1482        case 0:
1483            log_msg(3,
1484                    "CHILD - fip - calling feed_outfrom_partimage(%s, %s)",
1485                    biggiestruct.filename, partimagehack_fifo);
1486            res =
1487                feed_outfrom_partimage(biggiestruct.filename,
1488                                       partimagehack_fifo);
1489//          log_msg(3, "CHILD - fip - exiting");
1490            exit(res);
1491            break;
1492        default:
1493            log_msg(3,
1494                    "feed_into_partimage() called in background --- pid=%ld",
1495                    (long int) (pid));
1496        }
1497    } else {
1498        use_partimage_hack = FALSE;
1499        partimagehack_fifo[0] = '\0';
1500        file_to_openout = outfile_fname;
1501        if (!does_file_exist(outfile_fname))    // yes, it looks weird with the '!' but it's correct that way
1502        {
1503            make_hole_for_file(outfile_fname);
1504        }
1505    }
1506
1507    sprintf(tmp, "Reassembling big file %ld (%s)", bigfileno + 1,
1508            outfile_fname);
1509    log_msg(2, tmp);
1510
1511    /*
1512       last slice is zero-length and uncompressed; when we find it, we stop.
1513       We DON'T wait until there are no more slices; if we did that,
1514       We might stop at end of CD, not at last slice (which is 0-len and uncompd)
1515     */
1516
1517    strncpy(pathname_of_last_file_restored, biggiestruct.filename,
1518            MAX_STR_LEN - 1);
1519    pathname_of_last_file_restored[MAX_STR_LEN - 1] = '\0';
1520
1521    log_msg(3, "file_to_openout = %s", file_to_openout);
1522    if (!(fout = fopen(file_to_openout, "w"))) {
1523        log_to_screen("Cannot openout outfile_fname - hard disk full?");
1524        return (1);
1525    }
1526    log_msg(3, "Opened out to %s", outfile_fname);  // CD/DVD --> mondorestore --> partimagehack --> hard disk itself
1527
1528    for (sliceno = 1, finished = FALSE; !finished;) {
1529        if (!does_file_exist
1530            (slice_fname(bigfileno, sliceno, ARCHIVES_PATH, ""))
1531            &&
1532            !does_file_exist(slice_fname
1533                             (bigfileno, sliceno, ARCHIVES_PATH, "lzo"))
1534            &&
1535            !does_file_exist(slice_fname
1536                             (bigfileno, sliceno, ARCHIVES_PATH, "bz2"))) {
1537            log_msg(3,
1538                    "Cannot find a data slice or terminator slice on CD %d",
1539                    g_current_media_number);
1540            g_current_media_number++;
1541            sprintf(tmp,
1542                    "Asking for %s #%d so that I may read slice #%ld\n",
1543                    media_descriptor_string(bkpinfo->backup_media_type),
1544                    g_current_media_number, sliceno);
1545            log_msg(2, tmp);
1546            sprintf(tmp, "Restoring from %s #%d",
1547                    media_descriptor_string(bkpinfo->backup_media_type),
1548                    g_current_media_number);
1549            log_to_screen(tmp);
1550            insist_on_this_cd_number(bkpinfo, g_current_media_number);
1551            log_to_screen("Continuing to restore.");
1552        } else {
1553            strcpy(tmp,
1554                   slice_fname(bigfileno, sliceno, ARCHIVES_PATH, ""));
1555            if (does_file_exist(tmp) && length_of_file(tmp) == 0) {
1556                log_msg(2,
1557                        "End of bigfile # %ld (slice %ld is the terminator)",
1558                        bigfileno + 1, sliceno);
1559                finished = TRUE;
1560                continue;
1561            } else {
1562                if (does_file_exist
1563                    (slice_fname
1564                     (bigfileno, sliceno, ARCHIVES_PATH, "lzo"))) {
1565                    strcpy(bzip2_command, "lzop");
1566                    strcpy(suffix, "lzo");
1567                } else
1568                    if (does_file_exist
1569                        (slice_fname
1570                         (bigfileno, sliceno, ARCHIVES_PATH, "bz2"))) {
1571                    strcpy(bzip2_command, "bzip2");
1572                    strcpy(suffix, "bz2");
1573                } else
1574                    if (does_file_exist
1575                        (slice_fname
1576                         (bigfileno, sliceno, ARCHIVES_PATH, ""))) {
1577                    strcpy(bzip2_command, "");
1578                    strcpy(suffix, "");
1579                } else {
1580                    log_to_screen("OK, that's pretty fsck0red...");
1581                    return (1);
1582                }
1583            }
1584            if (bzip2_command[0] != '\0') {
1585                sprintf(bzip2_command + strlen(bzip2_command),
1586                        " -dc %s 2>> %s",
1587                        slice_fname(bigfileno, sliceno, ARCHIVES_PATH,
1588                                    suffix), MONDO_LOGFILE);
1589            } else {
1590                sprintf(bzip2_command, "cat %s 2>> %s",
1591                        slice_fname(bigfileno, sliceno, ARCHIVES_PATH,
1592                                    suffix), MONDO_LOGFILE);
1593            }
1594            sprintf(tmp, "Working on %s #%d, file #%ld, slice #%ld    ",
1595                    media_descriptor_string(bkpinfo->backup_media_type),
1596                    g_current_media_number, bigfileno + 1, sliceno);
1597            log_msg(2, tmp);
1598
1599            if (!g_text_mode) {
1600                newtDrawRootText(0, g_noof_rows - 2, tmp);
1601                newtRefresh();
1602                strip_spaces(tmp);
1603                update_progress_form(tmp);
1604            }
1605            if (!(fbzip2 = popen(bzip2_command, "r"))) {
1606                fatal_error("Can't run popen command");
1607            }
1608            while (!feof(fbzip2)) {
1609                siz = fread(bigblk, 1, TAPE_BLOCK_SIZE, fbzip2);
1610                if (siz > 0) {
1611                    sprintf(sz_msg, "Read %ld from fbzip2", siz);
1612                    siz = fwrite(bigblk, 1, siz, fout);
1613                    sprintf(sz_msg + strlen(sz_msg),
1614                            "; written %ld to fout", siz);
1615//        log_msg(2. sz_msg);
1616                }
1617            }
1618            paranoid_pclose(fbzip2);
1619
1620
1621            sliceno++;
1622            g_current_progress++;
1623        }
1624    }
1625/*
1626  memset(bigblk, TAPE_BLOCK_SIZE, 1); // This all looks very fishy...
1627  fwrite( bigblk, 1, TAPE_BLOCK_SIZE, fout);
1628  fwrite( bigblk, 1, TAPE_BLOCK_SIZE, fout);
1629  fwrite( bigblk, 1, TAPE_BLOCK_SIZE, fout);
1630  fwrite( bigblk, 1, TAPE_BLOCK_SIZE, fout);
1631*/
1632    paranoid_fclose(fout);
1633    g_loglevel = old_loglevel;
1634
1635    if (use_partimage_hack) {
1636        log_msg(3, "Waiting for partimage to finish");
1637        sprintf(tmp,
1638                " ps ax | grep \" partimagehack \" | grep -v grep > /dev/null 2> /dev/null");
1639        while (system(tmp) == 0) {
1640            sleep(1);
1641        }
1642        log_it("OK, partimage has really finished");
1643    }
1644
1645    if (strcmp(outfile_fname, "/dev/null")) {
1646        chown(outfile_fname, biggiestruct.properties.st_uid,
1647              biggiestruct.properties.st_gid);
1648        chmod(outfile_fname, biggiestruct.properties.st_mode);
1649        ubuf->actime = biggiestruct.properties.st_atime;
1650        ubuf->modtime = biggiestruct.properties.st_mtime;
1651        utime(outfile_fname, ubuf);
1652    }
1653    paranoid_free(bigblk);
1654    paranoid_free(checksum);
1655    paranoid_free(outfile_fname);
1656    paranoid_free(tmp);
1657    paranoid_free(bzip2_command);
1658    paranoid_free(partimagehack_command);
1659    paranoid_free(suffix);
1660    paranoid_free(sz_devfile);
1661
1662    return (retval);
1663}
1664
1665/**************************************************************************
1666 *END_ RESTORE_A_BIGGIEFILE_FROM_CD                                       *
1667 **************************************************************************/
1668
1669
1670
1671/**
1672 * Restore a biggiefile from the currently opened stream.
1673 * @param bkpinfo The backup information structure. Fields used:
1674 * - @c bkpinfo->restore_path
1675 * - @c bkpinfo->zip_exe
1676 * @param orig_bf_fname The original filename of the biggiefile.
1677 * @param biggiefile_number The number of the biggiefile (starting from 0).
1678 * @param orig_checksum Unused.
1679 * @param biggiefile_size Unused.
1680 * @param filelist The node structure containing the list of files to be restored.
1681 * If @p orig_bf_fname is not in the list, it will be ignored.
1682 * @return 0 for success (or skip), nonzero for failure.
1683 * @bug orig_checksum and biggiefile_size are unused (except to check that they are non-NULL).
1684 */
1685int restore_a_biggiefile_from_stream(struct s_bkpinfo *bkpinfo, char *orig_bf_fname, long biggiefile_number, char *orig_checksum,   //UNUSED
1686                                     long long biggiefile_size, //UNUSED
1687                                     struct s_node *filelist,
1688                                     int use_partimagehack,
1689                                     char *pathname_of_last_file_restored)
1690{
1691    FILE *pout;
1692    FILE *fin;
1693
1694  /** mallocs ********/
1695    char *tmp;
1696    char *command;
1697    char *outfile_fname;
1698    char *partimagehack_command;
1699    char *sz_devfile;
1700    char *partimagehack_fifo;
1701    char *file_to_openout = NULL;
1702
1703    struct s_node *node;
1704
1705    int old_loglevel;
1706    long current_slice_number = 0;
1707    int retval = 0;
1708    int res = 0;
1709    int ctrl_chr = '\0';
1710    long long slice_siz;
1711    bool dummy_restore = FALSE;
1712    bool use_partimage_hack = FALSE;
1713    pid_t pid;
1714    struct s_filename_and_lstat_info biggiestruct;
1715    struct utimbuf the_utime_buf, *ubuf;
1716    ubuf = &the_utime_buf;
1717
1718    malloc_string(tmp);
1719    malloc_string(partimagehack_fifo);
1720    malloc_string(outfile_fname);
1721    malloc_string(command);
1722    malloc_string(sz_devfile);
1723    malloc_string(partimagehack_command);
1724    old_loglevel = g_loglevel;
1725    assert(bkpinfo != NULL);
1726    assert(orig_bf_fname != NULL);
1727    assert(orig_checksum != NULL);
1728
1729    pathname_of_last_file_restored[0] = '\0';
1730    if (use_partimagehack == BLK_START_A_PIHBIGGIE) {
1731        use_partimagehack = 1;
1732        log_msg(1, "%s --- pih=YES", orig_bf_fname);
1733    } else if (use_partimagehack == BLK_START_A_NORMBIGGIE) {
1734        use_partimagehack = 0;
1735        log_msg(1, "%s --- pih=NO", orig_bf_fname);
1736    } else {
1737        use_partimagehack = 0;
1738        log_msg(1, "%s --- pih=NO (weird marker though)", orig_bf_fname);
1739    }
1740
1741    strncpy(pathname_of_last_file_restored, orig_bf_fname,
1742            MAX_STR_LEN - 1);
1743    pathname_of_last_file_restored[MAX_STR_LEN - 1] = '\0';
1744
1745    /* open out to biggiefile to be restored (or /dev/null if biggiefile is not to be restored) */
1746
1747    if (filelist != NULL) {
1748        node = find_string_at_node(filelist, orig_bf_fname);
1749        if (!node) {
1750            dummy_restore = TRUE;
1751            log_msg(1,
1752                    "Skipping big file %ld (%s) - not in biggielist subset",
1753                    biggiefile_number + 1, orig_bf_fname);
1754            pathname_of_last_file_restored[0] = '\0';
1755        } else if (!(node->selected)) {
1756            dummy_restore = TRUE;
1757            log_msg(1, "Skipping %s (name isn't in biggielist subset)",
1758                    orig_bf_fname);
1759            pathname_of_last_file_restored[0] = '\0';
1760        }
1761    }
1762
1763    if (use_partimagehack) {
1764        if (strncmp(orig_bf_fname, "/dev/", 5)) {
1765            log_msg(1,
1766                    "I was in error when I set use_partimagehack to TRUE.");
1767            log_msg(1, "%s isn't even in /dev", orig_bf_fname);
1768            use_partimagehack = FALSE;
1769        }
1770    }
1771
1772    if (use_partimagehack) {
1773        g_loglevel = 4;
1774        strcpy(outfile_fname, orig_bf_fname);
1775        use_partimage_hack = TRUE;
1776        log_msg(2,
1777                "Calling partimagehack in background because %s is a /dev entry",
1778                outfile_fname);
1779        sprintf(sz_devfile, "/tmp/%d.%d.000", (int) (random() % 32768),
1780                (int) (random() % 32768));
1781        mkfifo(sz_devfile, 0x770);
1782        strcpy(partimagehack_fifo, sz_devfile);
1783        file_to_openout = partimagehack_fifo;
1784        switch (pid = fork()) {
1785        case -1:
1786            fatal_error("Fork failure");
1787        case 0:
1788            log_msg(3,
1789                    "CHILD - fip - calling feed_outfrom_partimage(%s, %s)",
1790                    outfile_fname, partimagehack_fifo);
1791            res =
1792                feed_outfrom_partimage(outfile_fname, partimagehack_fifo);
1793//          log_msg(3, "CHILD - fip - exiting");
1794            exit(res);
1795            break;
1796        default:
1797            log_msg(3,
1798                    "feed_into_partimage() called in background --- pid=%ld",
1799                    (long int) (pid));
1800        }
1801    } else {
1802        if (!strncmp(orig_bf_fname, "/dev/", 5))    // non-NTFS partition
1803        {
1804            strcpy(outfile_fname, orig_bf_fname);
1805        } else                  // biggiefile
1806        {
1807            sprintf(outfile_fname, "%s/%s", bkpinfo->restore_path,
1808                    orig_bf_fname);
1809        }
1810        use_partimage_hack = FALSE;
1811        partimagehack_fifo[0] = '\0';
1812        file_to_openout = outfile_fname;
1813        if (!does_file_exist(outfile_fname))    // yes, it looks weird with the '!' but it's correct that way
1814        {
1815            make_hole_for_file(outfile_fname);
1816        }
1817        sprintf(tmp, "Reassembling big file %ld (%s)",
1818                biggiefile_number + 1, orig_bf_fname);
1819        log_msg(2, tmp);
1820    }
1821
1822    if (dummy_restore) {
1823        sprintf(outfile_fname, "/dev/null");
1824    }
1825
1826    if (!bkpinfo->zip_exe[0]) {
1827        sprintf(command, "cat > \"%s\"", file_to_openout);
1828    } else {
1829        sprintf(command, "%s -dc > \"%s\" 2>> %s", bkpinfo->zip_exe,
1830                file_to_openout, MONDO_LOGFILE);
1831    }
1832    sprintf(tmp, "Pipe command = '%s'", command);
1833    log_msg(3, tmp);
1834
1835    /* restore biggiefile, one slice at a time */
1836    if (!(pout = popen(command, "w"))) {
1837        fatal_error("Cannot pipe out");
1838    }
1839    for (res = read_header_block_from_stream(&slice_siz, tmp, &ctrl_chr);
1840         ctrl_chr != BLK_STOP_A_BIGGIE;
1841         res = read_header_block_from_stream(&slice_siz, tmp, &ctrl_chr)) {
1842        if (ctrl_chr != BLK_START_AN_AFIO_OR_SLICE) {
1843            wrong_marker(BLK_START_AN_AFIO_OR_SLICE, ctrl_chr);
1844        }
1845        sprintf(tmp, "Working on file #%ld, slice #%ld    ",
1846                biggiefile_number + 1, current_slice_number);
1847        log_msg(2, tmp);
1848        if (!g_text_mode) {
1849            newtDrawRootText(0, g_noof_rows - 2, tmp);
1850            newtRefresh();
1851        }
1852        strip_spaces(tmp);
1853        update_progress_form(tmp);
1854        if (current_slice_number == 0) {
1855            res =
1856                read_file_from_stream_to_file(bkpinfo,
1857                                              "/tmp/biggie-blah.txt",
1858                                              slice_siz);
1859            if (!(fin = fopen("/tmp/biggie-blah.txt", "r"))) {
1860                log_OS_error("blah blah");
1861            } else {
1862                if (fread
1863                    ((void *) &biggiestruct, 1, sizeof(biggiestruct),
1864                     fin) < sizeof(biggiestruct)) {
1865                    log_msg(2,
1866                            "Warning - unable to get biggiestruct of bigfile #%d",
1867                            biggiefile_number + 1);
1868                }
1869                paranoid_fclose(fin);
1870            }
1871        } else {
1872            res =
1873                read_file_from_stream_to_stream(bkpinfo, pout, slice_siz);
1874        }
1875        retval += res;
1876        res = read_header_block_from_stream(&slice_siz, tmp, &ctrl_chr);
1877        if (ctrl_chr != BLK_STOP_AN_AFIO_OR_SLICE) {
1878            wrong_marker(BLK_STOP_AN_AFIO_OR_SLICE, ctrl_chr);
1879        }
1880        current_slice_number++;
1881        g_current_progress++;
1882    }
1883    paranoid_pclose(pout);
1884
1885    log_msg(1, "pathname_of_last_file_restored is now %s",
1886            pathname_of_last_file_restored);
1887
1888    if (use_partimage_hack) {
1889        log_msg(3, "Waiting for partimage to finish");
1890        sprintf(tmp,
1891                " ps ax | grep \" partimagehack \" | grep -v grep > /dev/null 2> /dev/null");
1892        while (system(tmp) == 0) {
1893            sleep(1);
1894        }
1895        log_msg(3, "OK, partimage has really finished");
1896    }
1897
1898    log_msg(3, "biggiestruct.filename = %s", biggiestruct.filename);
1899    log_msg(3, "biggiestruct.checksum = %s", biggiestruct.checksum);
1900    if (strcmp(outfile_fname, "/dev/null")) {
1901        chmod(outfile_fname, biggiestruct.properties.st_mode);
1902        chown(outfile_fname, biggiestruct.properties.st_uid,
1903              biggiestruct.properties.st_gid);
1904        ubuf->actime = biggiestruct.properties.st_atime;
1905        ubuf->modtime = biggiestruct.properties.st_mtime;
1906        utime(outfile_fname, ubuf);
1907    }
1908
1909    paranoid_free(tmp);
1910    paranoid_free(outfile_fname);
1911    paranoid_free(command);
1912    paranoid_free(partimagehack_command);
1913    paranoid_free(sz_devfile);
1914    paranoid_free(partimagehack_fifo);
1915    g_loglevel = old_loglevel;
1916    return (retval);
1917}
1918
1919/**************************************************************************
1920 *END_RESTORE_A_BIGGIEFILE_FROM_STREAM                                    *
1921 **************************************************************************/
1922
1923
1924
1925/**
1926 * Restore @p tarball_fname from CD.
1927 * @param tarball_fname The filename of the tarball to restore (in /mnt/cdrom).
1928 * This will be used unmodified.
1929 * @param current_tarball_number The number (starting from 0) of the fileset
1930 * we're restoring now.
1931 * @param filelist The node structure containing the list of files to be
1932 * restored. If no file in the afioball is in this list, afio will still be
1933 * called, but nothing will be written.
1934 * @return 0 for success, nonzero for failure.
1935 */
1936int
1937restore_a_tarball_from_CD(char *tarball_fname,
1938                          long current_tarball_number,
1939                          struct s_node *filelist)
1940{
1941    int retval = 0;
1942    int res;
1943    char *p;
1944
1945  /** malloc **/
1946    char *command;
1947    char *tmp;
1948    char *filelist_name;
1949    char *filelist_subset_fname;
1950    char *executable;
1951    char *temp_log;
1952    char screen_message[100];
1953    long matches = 0;
1954    bool use_star;
1955    char *xattr_fname;
1956    char *acl_fname;
1957//  char files_to_restore_this_time_fname[MAX_STR_LEN];
1958
1959    assert_string_is_neither_NULL_nor_zerolength(tarball_fname);
1960    malloc_string(command);
1961    malloc_string(tmp);
1962    malloc_string(filelist_name);
1963    malloc_string(filelist_subset_fname);
1964    malloc_string(executable);
1965    malloc_string(temp_log);
1966    malloc_string(xattr_fname);
1967    malloc_string(acl_fname);
1968
1969    log_msg(5, "Entering");
1970    filelist_subset_fname[0] = '\0';
1971    use_star = (strstr(tarball_fname, ".star")) ? TRUE : FALSE;
1972//  sprintf(files_to_restore_this_time_fname, "/tmp/ftrttf.%d.%d", (int)getpid(), (int)random());
1973    sprintf(command, "mkdir -p %s/tmp", MNT_RESTORING);
1974    run_program_and_log_output(command, 9);
1975    sprintf(temp_log, "/tmp/%d.%d", (int) (random() % 32768),
1976            (int) (random() % 32768));
1977
1978    sprintf(filelist_name, MNT_CDROM "/archives/filelist.%ld",
1979            current_tarball_number);
1980    if (length_of_file(filelist_name) <= 2) {
1981        log_msg(2, "There are _zero_ files in filelist '%s'",
1982                filelist_name);
1983        log_msg(2,
1984                "This is a bit silly (ask Hugo to fix mondo-makefilelist, please)");
1985        log_msg(2,
1986                "but it's non-critical. It's cosmetic. Don't worry about it.");
1987        retval = 0;
1988        goto leave_sub;
1989    }
1990    if (count_lines_in_file(filelist_name) <= 0
1991        || length_of_file(tarball_fname) <= 0) {
1992        log_msg(3, "length_of_file(%s) = %ld", tarball_fname,
1993                length_of_file(tarball_fname));
1994        sprintf(tmp, "Unable to restore fileset #%ld (CD I/O error)",
1995                current_tarball_number);
1996        log_to_screen(tmp);
1997        retval = 1;
1998        goto leave_sub;
1999    }
2000
2001    if (filelist) {
2002        sprintf(filelist_subset_fname, "/tmp/filelist-subset-%ld.tmp",
2003                current_tarball_number);
2004        if ((matches =
2005             save_filelist_entries_in_common(filelist_name, filelist,
2006                                             filelist_subset_fname,
2007                                             use_star))
2008            <= 0) {
2009            sprintf(tmp, "Skipping fileset %ld", current_tarball_number);
2010            log_msg(1, tmp);
2011        } else {
2012            log_msg(3, "Saved fileset %ld's subset to %s",
2013                    current_tarball_number, filelist_subset_fname);
2014        }
2015        sprintf(screen_message, "Tarball #%ld --- %ld matches",
2016                current_tarball_number, matches);
2017        log_to_screen(screen_message);
2018    } else {
2019        filelist_subset_fname[0] = '\0';
2020    }
2021
2022    if (filelist == NULL || matches > 0) {
2023        sprintf(xattr_fname, XATTR_LIST_FNAME_RAW_SZ,
2024                MNT_CDROM "/archives", current_tarball_number);
2025        sprintf(acl_fname, ACL_LIST_FNAME_RAW_SZ, MNT_CDROM "/archives",
2026                current_tarball_number);
2027        if (strstr(tarball_fname, ".bz2")) {
2028            strcpy(executable, "bzip2");
2029        } else if (strstr(tarball_fname, ".lzo")) {
2030            strcpy(executable, "lzop");
2031        } else {
2032            executable[0] = '\0';
2033        }
2034        if (executable[0]) {
2035            sprintf(tmp, "which %s > /dev/null 2> /dev/null", executable);
2036            if (run_program_and_log_output(tmp, FALSE)) {
2037                log_to_screen
2038                    ("(compare_a_tarball) Compression program not found - oh no!");
2039                paranoid_MR_finish(1);
2040            }
2041            strcpy(tmp, executable);
2042            sprintf(executable, "-P %s -Z", tmp);
2043        }
2044#ifdef __FreeBSD__
2045#define BUFSIZE 512
2046#else
2047#define BUFSIZE (1024L*1024L)/TAPE_BLOCK_SIZE
2048#endif
2049
2050//      if (strstr(tarball_fname, ".star."))
2051        if (use_star) {
2052            sprintf(command,
2053                    "star -x -force-remove -U " STAR_ACL_SZ
2054                    " errctl= file=%s", tarball_fname);
2055            if (strstr(tarball_fname, ".bz2")) {
2056                strcat(command, " -bz");
2057            }
2058        } else {
2059            if (filelist_subset_fname[0] != '\0') {
2060                sprintf(command,
2061                        "afio -i -M 8m -b %ld -c %ld %s -w %s %s",
2062                        TAPE_BLOCK_SIZE,
2063                        BUFSIZE, executable, filelist_subset_fname,
2064//             files_to_restore_this_time_fname,
2065                        tarball_fname);
2066            } else {
2067                sprintf(command,
2068                        "afio -i -b %ld -c %ld -M 8m %s %s",
2069                        TAPE_BLOCK_SIZE,
2070                        BUFSIZE, executable, tarball_fname);
2071            }
2072        }
2073#undef BUFSIZE
2074        sprintf(command + strlen(command), " 2>> %s >> %s", temp_log,
2075                temp_log);
2076        log_msg(1, "command = '%s'", command);
2077        unlink(temp_log);
2078        res = system(command);
2079        if (res) {
2080            p = strstr(command, "-acl ");
2081            if (p) {
2082                p[0] = p[1] = p[2] = p[3] = ' ';
2083                log_msg(1, "new command = '%s'", command);
2084                res = system(command);
2085            }
2086        }
2087        if (res && length_of_file(temp_log) < 5) {
2088            res = 0;
2089        }
2090
2091        log_msg(1, "Setting fattr list %s", xattr_fname);
2092        if (length_of_file(xattr_fname) > 0) {
2093            res = set_fattr_list(filelist_subset_fname, xattr_fname);
2094            if (res) {
2095                log_to_screen
2096                    ("Errors occurred while setting extended attributes");
2097            } else {
2098                log_msg(1, "I set xattr OK");
2099            }
2100            retval += res;
2101        }
2102        if (length_of_file(acl_fname) > 0) {
2103            log_msg(1, "Setting acl list %s", acl_fname);
2104            res = set_acl_list(filelist_subset_fname, acl_fname);
2105            if (res) {
2106                log_to_screen
2107                    ("Errors occurred while setting access control lists");
2108            } else {
2109                log_msg(1, "I set ACL OK");
2110            }
2111            retval += res;
2112        }
2113        if (retval) {
2114            sprintf(command, "cat %s >> %s", temp_log, MONDO_LOGFILE);
2115            system(command);
2116            log_msg(2, "Errors occurred while processing fileset #%d",
2117                    current_tarball_number);
2118        } else {
2119            log_msg(2, "Fileset #%d processed OK", current_tarball_number);
2120        }
2121    }
2122    if (does_file_exist("/PAUSE")) {
2123        popup_and_OK
2124            ("Press ENTER to go on. Delete /PAUSE to stop these pauses.");
2125    }
2126    unlink(filelist_subset_fname);
2127    unlink(xattr_fname);
2128    unlink(acl_fname);
2129    unlink(temp_log);
2130
2131  leave_sub:
2132    paranoid_free(command);
2133    paranoid_free(tmp);
2134    paranoid_free(filelist_name);
2135    paranoid_free(filelist_subset_fname);
2136    paranoid_free(executable);
2137    paranoid_free(temp_log);
2138    paranoid_free(xattr_fname);
2139    paranoid_free(acl_fname);
2140    log_msg(5, "Leaving");
2141    return (retval);
2142}
2143
2144/**************************************************************************
2145 *END_RESTORE_A_TARBALL_FROM_CD                                           *
2146 **************************************************************************/
2147
2148
2149/**
2150 * Restore a tarball from the currently opened stream.
2151 * @param bkpinfo The backup information structure. Fields used:
2152 * - @c bkpinfo->backup_media_type
2153 * - @c bkpinfo->media_device
2154 * - @c bkpinfo->zip_exe
2155 * @param tarball_fname The filename of the afioball to restore.
2156 * @param current_tarball_number The number (starting from 0) of the fileset
2157 * we're restoring now.
2158 * @param filelist The node structure containing the list of files to be
2159 * restored. If no file in the afioball is in this list, afio will still be
2160 * called, but nothing will be written.
2161 * @param size The size (in @b bytes) of the afioball.
2162 * @return 0 for success, nonzero for failure.
2163 */
2164int
2165restore_a_tarball_from_stream(struct s_bkpinfo *bkpinfo,
2166                              char *tarball_fname,
2167                              long current_tarball_number,
2168                              struct s_node *filelist,
2169                              long long size, char *xattr_fname,
2170                              char *acl_fname)
2171{
2172    int retval = 0;
2173    int res = 0;
2174
2175  /** malloc add ***/
2176    char *tmp;
2177    char *command;
2178    char *afio_fname;
2179    char *filelist_fname;
2180    char *filelist_subset_fname;
2181    char *executable;
2182    long matches = 0;
2183    bool restore_this_fileset = FALSE;
2184    bool use_star;
2185
2186    assert(bkpinfo != NULL);
2187    assert_string_is_neither_NULL_nor_zerolength(tarball_fname);
2188    malloc_string(filelist_subset_fname);
2189    malloc_string(filelist_fname);
2190    malloc_string(afio_fname);
2191    malloc_string(executable);
2192    malloc_string(command);
2193    malloc_string(tmp);
2194    filelist_subset_fname[0] = '\0';
2195    /* to do it with a file... */
2196    use_star = (strstr(tarball_fname, ".star")) ? TRUE : FALSE;
2197    sprintf(tmp,
2198            "Restoring from fileset #%ld (%ld KB) on %s #%d",
2199            current_tarball_number, (long) size >> 10,
2200            media_descriptor_string(bkpinfo->backup_media_type),
2201            g_current_media_number);
2202    log_msg(2, tmp);
2203    run_program_and_log_output("mkdir -p " MNT_RESTORING "/tmp", FALSE);
2204
2205  /****************************************************************************
2206   * Use RAMDISK's /tmp; saves time; oh wait, it's too small                  *
2207   * Well, pipe from tape to afio, then; oh wait, can't do that either: bug   *
2208   * in afio or someting; oh darn.. OK, use tmpfs :-)                         *
2209   ****************************************************************************/
2210    filelist_fname[0] = filelist_subset_fname[0] = '\0';
2211    sprintf(afio_fname, "/tmp/tmpfs/archive.tmp.%ld",
2212            current_tarball_number);
2213    sprintf(filelist_fname, "%s/filelist.%ld", bkpinfo->tmpdir,
2214            current_tarball_number);
2215    sprintf(filelist_subset_fname, "%s/filelist-subset-%ld.tmp",
2216            bkpinfo->tmpdir, current_tarball_number);
2217//  sprintf(filelist_fname, "/tmp/tmpfs/temp-filelist.%ld", current_tarball_number);
2218    res = read_file_from_stream_to_file(bkpinfo, afio_fname, size);
2219    if (strstr(tarball_fname, ".star")) {
2220        bkpinfo->use_star = TRUE;
2221    }
2222    if (res) {
2223        log_msg(1, "Warning - error reading afioball from tape");
2224    }
2225    if (bkpinfo->compression_level == 0) {
2226        executable[0] = '\0';
2227    } else {
2228        if (bkpinfo->use_star) {
2229            strcpy(executable, " -bz");
2230        } else {
2231            sprintf(executable, "-P %s -Z", bkpinfo->zip_exe);
2232        }
2233    }
2234
2235    if (!filelist)              // if unconditional restore then restore entire fileset
2236    {
2237        restore_this_fileset = TRUE;
2238    } else                      // If restoring selectively then get TOC from tarball
2239    {
2240        if (strstr(tarball_fname, ".star.")) {
2241            use_star = TRUE;
2242            sprintf(command, "star -t file=%s %s", afio_fname, executable);
2243        } else {
2244            use_star = FALSE;
2245            sprintf(command, "afio -t -M 8m -b %ld %s %s", TAPE_BLOCK_SIZE,
2246                    executable, afio_fname);
2247        }
2248        sprintf(command + strlen(command), " > %s 2>> %s", filelist_fname,
2249                MONDO_LOGFILE);
2250        log_msg(1, "command = %s", command);
2251        if (system(command)) {
2252            log_msg(4, "Warning - error occurred while retrieving TOC");
2253        }
2254        if ((matches =
2255             save_filelist_entries_in_common(filelist_fname, filelist,
2256                                             filelist_subset_fname,
2257                                             use_star))
2258            <= 0 || length_of_file(filelist_subset_fname) < 2) {
2259            if (length_of_file(filelist_subset_fname) < 2) {
2260                log_msg(1, "No matches found in fileset %ld",
2261                        current_tarball_number);
2262            }
2263            sprintf(tmp, "Skipping fileset %ld", current_tarball_number);
2264            log_msg(2, tmp);
2265            restore_this_fileset = FALSE;
2266        } else {
2267            log_msg(5, "%ld matches. Saved fileset %ld's subset to %s",
2268                    matches, current_tarball_number,
2269                    filelist_subset_fname);
2270            restore_this_fileset = TRUE;
2271        }
2272    }
2273
2274// Concoct the call to star/afio to restore files
2275    if (strstr(tarball_fname, ".star."))    // star
2276    {
2277        sprintf(command, "star -x file=%s %s", afio_fname, executable);
2278        if (filelist) {
2279            sprintf(command + strlen(command), " list=%s",
2280                    filelist_subset_fname);
2281        }
2282    } else                      // afio
2283    {
2284        sprintf(command, "afio -i -M 8m -b %ld %s", TAPE_BLOCK_SIZE,
2285                executable);
2286        if (filelist) {
2287            sprintf(command + strlen(command), " -w %s",
2288                    filelist_subset_fname);
2289        }
2290        sprintf(command + strlen(command), " %s", afio_fname);
2291    }
2292    sprintf(command + strlen(command), " 2>> %s", MONDO_LOGFILE);
2293
2294// Call if IF there are files to restore (selectively/unconditionally)
2295    if (restore_this_fileset) {
2296        log_msg(1, "Calling command='%s'", command);
2297        paranoid_system(command);
2298
2299        iamhere("Restoring xattr, acl stuff");
2300        res = set_fattr_list(filelist_subset_fname, xattr_fname);
2301        if (res) {
2302            log_msg(1, "Errors occurred while setting xattr");
2303        } else {
2304            log_msg(1, "I set xattr OK");
2305        }
2306        retval += res;
2307
2308        res = set_acl_list(filelist_subset_fname, acl_fname);
2309        if (res) {
2310            log_msg(1, "Errors occurred while setting ACL");
2311        } else {
2312            log_msg(1, "I set ACL OK");
2313        }
2314        retval += res;
2315
2316    } else {
2317        log_msg(1, "NOT CALLING '%s'", command);
2318    }
2319
2320    if (does_file_exist("/PAUSE") && current_tarball_number >= 50) {
2321        log_to_screen("Paused after set %ld", current_tarball_number);
2322        popup_and_OK("Pausing. Press ENTER to continue.");
2323    }
2324
2325    unlink(filelist_subset_fname);
2326    unlink(filelist_fname);
2327    unlink(afio_fname);
2328
2329    paranoid_free(filelist_subset_fname);
2330    paranoid_free(filelist_fname);
2331    paranoid_free(afio_fname);
2332    paranoid_free(command);
2333    paranoid_free(tmp);
2334    return (retval);
2335}
2336
2337/**************************************************************************
2338 *END_RESTORE_A_TARBALL_FROM_STREAM                                       *
2339 **************************************************************************/
2340
2341
2342
2343
2344/**
2345 * Restore all biggiefiles from all media in this CD backup.
2346 * The CD with the last afioball should be currently mounted.
2347 * @param bkpinfo The backup information structure. @c backup_media_type is the
2348 * only field used in this function.
2349 * @param filelist The node structure containing the list of files to be
2350 * restored. If a prospective biggiefile is not in this list, it will be ignored.
2351 * @return 0 for success, nonzero for failure.
2352 */
2353int
2354restore_all_biggiefiles_from_CD(struct s_bkpinfo *bkpinfo,
2355                                struct s_node *filelist)
2356{
2357    int retval = 0;
2358    int res;
2359    long noof_biggiefiles, bigfileno = 0, total_slices;
2360  /** malloc **/
2361    char *tmp;
2362    bool just_changed_cds = FALSE, finished;
2363    char *xattr_fname;
2364    char *acl_fname;
2365    char *biggies_whose_EXATs_we_should_set;    // EXtended ATtributes
2366    char *pathname_of_last_biggie_restored;
2367    FILE *fbw = NULL;
2368
2369    malloc_string(xattr_fname);
2370    malloc_string(acl_fname);
2371    malloc_string(tmp);
2372    malloc_string(biggies_whose_EXATs_we_should_set);
2373    malloc_string(pathname_of_last_biggie_restored);
2374    assert(bkpinfo != NULL);
2375
2376    sprintf(biggies_whose_EXATs_we_should_set,
2377            "%s/biggies-whose-EXATs-we-should-set", bkpinfo->tmpdir);
2378    if (!(fbw = fopen(biggies_whose_EXATs_we_should_set, "w"))) {
2379        log_msg(1, "Warning - cannot openout %s",
2380                biggies_whose_EXATs_we_should_set);
2381    }
2382
2383    read_cfg_var(g_mondo_cfg_file, "total-slices", tmp);
2384    total_slices = atol(tmp);
2385    sprintf(tmp, "Reassembling large files      ");
2386    mvaddstr_and_log_it(g_currentY, 0, tmp);
2387    if (length_of_file(BIGGIELIST) < 6) {
2388        log_msg(1, "OK, no biggielist; not restoring biggiefiles");
2389        return (0);
2390    }
2391    noof_biggiefiles = count_lines_in_file(BIGGIELIST);
2392    if (noof_biggiefiles <= 0) {
2393        log_msg(2,
2394                "OK, no biggiefiles in biggielist; not restoring biggiefiles");
2395        return (0);
2396    }
2397    sprintf(tmp, "OK, there are %ld biggiefiles in the archives",
2398            noof_biggiefiles);
2399    log_msg(2, tmp);
2400
2401    open_progress_form("Reassembling large files",
2402                       "I am now reassembling all the large files.",
2403                       "Please wait. This may take some time.",
2404                       "", total_slices);
2405    for (bigfileno = 0, finished = FALSE; !finished;) {
2406        log_msg(2, "Thinking about restoring bigfile %ld", bigfileno + 1);
2407        if (!does_file_exist(slice_fname(bigfileno, 0, ARCHIVES_PATH, ""))) {
2408            log_msg(3,
2409                    "...but its first slice isn't on this CD. Perhaps this was a selective restore?");
2410            log_msg(3, "Cannot find bigfile #%ld 's first slice on %s #%d",
2411                    bigfileno + 1,
2412                    media_descriptor_string(bkpinfo->backup_media_type),
2413                    g_current_media_number);
2414            log_msg(3, "Slicename would have been %s",
2415                    slice_fname(bigfileno + 1, 0, ARCHIVES_PATH, ""));
2416            // I'm not positive 'just_changed_cds' is even necessary...
2417            if (just_changed_cds) {
2418                just_changed_cds = FALSE;
2419                log_msg(3,
2420                        "I'll continue to scan this CD for bigfiles to be restored.");
2421            } else if (does_file_exist(MNT_CDROM "/archives/NOT-THE-LAST")) {
2422                insist_on_this_cd_number(bkpinfo,
2423                                         ++g_current_media_number);
2424                sprintf(tmp, "Restoring from %s #%d",
2425                        media_descriptor_string(bkpinfo->
2426                                                backup_media_type),
2427                        g_current_media_number);
2428                log_to_screen(tmp);
2429                just_changed_cds = TRUE;
2430            } else {
2431                log_msg(2, "There was no bigfile #%ld. That's OK.",
2432                        bigfileno + 1);
2433                log_msg(2, "I'm going to stop restoring bigfiles now.");
2434                finished = TRUE;
2435            }
2436        } else {
2437            just_changed_cds = FALSE;
2438            sprintf(tmp, "Restoring big file %ld", bigfileno + 1);
2439            update_progress_form(tmp);
2440            res =
2441                restore_a_biggiefile_from_CD(bkpinfo, bigfileno, filelist,
2442                                             pathname_of_last_biggie_restored);
2443            iamhere(pathname_of_last_biggie_restored);
2444            if (fbw && pathname_of_last_biggie_restored[0]) {
2445                fprintf(fbw, "%s\n", pathname_of_last_biggie_restored);
2446            }
2447            retval += res;
2448            bigfileno++;
2449
2450        }
2451    }
2452
2453    if (fbw) {
2454        fclose(fbw);
2455        sprintf(acl_fname, ACL_BIGGLST_FNAME_RAW_SZ, ARCHIVES_PATH);
2456        sprintf(xattr_fname, XATTR_BIGGLST_FNAME_RAW_SZ, ARCHIVES_PATH);
2457        if (length_of_file(acl_fname) > 0 && find_home_of_exe("setfacl")) {
2458            set_acl_list(biggies_whose_EXATs_we_should_set, acl_fname);
2459        }
2460        if (length_of_file(xattr_fname) > 0
2461            && find_home_of_exe("setfattr")) {
2462            set_fattr_list(biggies_whose_EXATs_we_should_set, xattr_fname);
2463        }
2464    }
2465    if (does_file_exist("/PAUSE")) {
2466        popup_and_OK
2467            ("Press ENTER to go on. Delete /PAUSE to stop these pauses.");
2468    }
2469    close_progress_form();
2470    if (retval) {
2471        mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
2472    } else {
2473        mvaddstr_and_log_it(g_currentY++, 74, "Done.");
2474    }
2475    paranoid_free(xattr_fname);
2476    paranoid_free(acl_fname);
2477    paranoid_free(tmp);
2478    paranoid_free(biggies_whose_EXATs_we_should_set);
2479    paranoid_free(pathname_of_last_biggie_restored);
2480    return (retval);
2481}
2482
2483/**************************************************************************
2484 *END_RESTORE_ALL_BIGGIFILES_FROM_CD                                      *
2485 **************************************************************************/
2486
2487
2488
2489/**
2490 * Restore all afioballs from all CDs in the backup.
2491 * The first CD should be inserted (if not, it will be asked for).
2492 * @param bkpinfo The backup information structure. @c backup_media_type is the
2493 * only field used in @e this function.
2494 * @param filelist The node structure containing the list of files to be
2495 * restored. If no file in some particular afioball is in this list, afio will
2496 * still be called for that fileset, but nothing will be written.
2497 * @return 0 for success, or the number of filesets that failed.
2498 */
2499int
2500restore_all_tarballs_from_CD(struct s_bkpinfo *bkpinfo,
2501                             struct s_node *filelist)
2502{
2503    int retval = 0;
2504    int res;
2505    int attempts;
2506    long current_tarball_number = 0;
2507    long max_val;
2508  /**malloc ***/
2509    char *tmp;
2510    char *tarball_fname;
2511    char *progress_str;
2512    char *comment;
2513
2514    malloc_string(tmp);
2515    malloc_string(tarball_fname);
2516    malloc_string(progress_str);
2517    malloc_string(comment);
2518
2519    assert(bkpinfo != NULL);
2520
2521    mvaddstr_and_log_it(g_currentY, 0, "Restoring from archives");
2522    log_msg(2,
2523            "Insisting on 1st CD, so that I can have a look at LAST-FILELIST-NUMBER");
2524    if (g_current_media_number != 1) {
2525        log_msg(3, "OK, that's jacked up.");
2526        g_current_media_number = 1;
2527    }
2528    insist_on_this_cd_number(bkpinfo, g_current_media_number);
2529    read_cfg_var(g_mondo_cfg_file, "last-filelist-number", tmp);
2530    max_val = atol(tmp) + 1;
2531    sprintf(progress_str, "Restoring from %s #%d",
2532            media_descriptor_string(bkpinfo->backup_media_type),
2533            g_current_media_number);
2534    log_to_screen(progress_str);
2535    open_progress_form("Restoring from archives",
2536                       "Restoring data from the archives.",
2537                       "Please wait. This may take some time.",
2538                       progress_str, max_val);
2539    for (;;) {
2540        insist_on_this_cd_number(bkpinfo, g_current_media_number);
2541        update_progress_form(progress_str);
2542        sprintf(tarball_fname, MNT_CDROM "/archives/%ld.afio.bz2",
2543                current_tarball_number);
2544        if (!does_file_exist(tarball_fname)) {
2545            sprintf(tarball_fname, MNT_CDROM "/archives/%ld.afio.lzo",
2546                    current_tarball_number);
2547        }
2548        if (!does_file_exist(tarball_fname)) {
2549            sprintf(tarball_fname, MNT_CDROM "/archives/%ld.afio.",
2550                    current_tarball_number);
2551        }
2552        if (!does_file_exist(tarball_fname)) {
2553            sprintf(tarball_fname, MNT_CDROM "/archives/%ld.star.bz2",
2554                    current_tarball_number);
2555        }
2556        if (!does_file_exist(tarball_fname)) {
2557            sprintf(tarball_fname, MNT_CDROM "/archives/%ld.star.",
2558                    current_tarball_number);
2559        }
2560        if (!does_file_exist(tarball_fname)) {
2561            if (current_tarball_number == 0) {
2562                log_to_screen
2563                    ("No tarballs. Strange. Maybe you only backed up freakin' big files?");
2564                return (0);
2565            }
2566            if (!does_file_exist(MNT_CDROM "/archives/NOT-THE-LAST")
2567                || system("find " MNT_CDROM
2568                          "/archives/slice* > /dev/null 2> /dev/null") ==
2569                0) {
2570                break;
2571            }
2572            g_current_media_number++;
2573            sprintf(progress_str, "Restoring from %s #%d",
2574                    media_descriptor_string(bkpinfo->backup_media_type),
2575                    g_current_media_number);
2576            log_to_screen(progress_str);
2577        } else {
2578            sprintf(progress_str, "Restoring from fileset #%ld on %s #%d",
2579                    current_tarball_number,
2580                    media_descriptor_string(bkpinfo->backup_media_type),
2581                    g_current_media_number);
2582//    log_msg(3, "progress_str = %s", progress_str);
2583            for (res = 999, attempts = 0; attempts < 3 && res != 0;
2584                 attempts++) {
2585                res =
2586                    restore_a_tarball_from_CD(tarball_fname,
2587                                              current_tarball_number,
2588                                              filelist);
2589            }
2590            sprintf(tmp, "%s #%d, fileset #%ld - restore ",
2591                    media_descriptor_string(bkpinfo->backup_media_type),
2592                    g_current_media_number, current_tarball_number);
2593            if (res) {
2594                strcat(tmp, "reported errors");
2595            } else if (attempts > 1) {
2596                strcat(tmp, "succeeded");
2597            } else {
2598                strcat(tmp, "succeeded");
2599            }
2600            if (attempts > 1) {
2601                sprintf(tmp + strlen(tmp), " (%d attempts) - review logs",
2602                        attempts);
2603            }
2604            strcpy(comment, tmp);
2605            if (attempts > 1) {
2606                log_to_screen(comment);
2607            }
2608
2609            retval += res;
2610            current_tarball_number++;
2611            g_current_progress++;
2612        }
2613    }
2614    close_progress_form();
2615    if (retval) {
2616        mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
2617    } else {
2618        mvaddstr_and_log_it(g_currentY++, 74, "Done.");
2619    }
2620    paranoid_free(tmp);
2621    paranoid_free(tarball_fname);
2622    paranoid_free(progress_str);
2623    paranoid_free(comment);
2624
2625    return (retval);
2626}
2627
2628/**************************************************************************
2629 *END_RESTORE_ALL_TARBALLS_FROM_CD                                        *
2630 **************************************************************************/
2631
2632
2633
2634/**
2635 * Restore all biggiefiles from the currently opened stream.
2636 * @param bkpinfo The backup information structure. Passed to other functions.
2637 * @param filelist The node structure containing the list of files to be
2638 * restored. If a prospective biggiefile is not in the list, it will be ignored.
2639 * @return 0 for success, or the number of biggiefiles that failed.
2640 */
2641int
2642restore_all_biggiefiles_from_stream(struct s_bkpinfo *bkpinfo,
2643                                    struct s_node *filelist)
2644{
2645    long noof_biggiefiles;
2646    long current_bigfile_number = 0;
2647    long total_slices;
2648
2649    int retval = 0;
2650    int res = 0;
2651    int ctrl_chr;
2652
2653  /** malloc add ****/
2654    char *tmp;
2655    char *biggie_fname;
2656    char *biggie_cksum;
2657    char *xattr_fname;
2658    char *acl_fname;
2659    char *p;
2660    char *pathname_of_last_biggie_restored;
2661    char *biggies_whose_EXATs_we_should_set;    // EXtended ATtributes
2662    long long biggie_size;
2663    FILE *fbw = NULL;
2664
2665    malloc_string(tmp);
2666    malloc_string(biggie_fname);
2667    malloc_string(biggie_cksum);
2668    malloc_string(xattr_fname);
2669    malloc_string(acl_fname);
2670    malloc_string(biggies_whose_EXATs_we_should_set);
2671    malloc_string(pathname_of_last_biggie_restored);
2672    assert(bkpinfo != NULL);
2673
2674    read_cfg_var(g_mondo_cfg_file, "total-slices", tmp);
2675
2676    total_slices = atol(tmp);
2677    sprintf(tmp, "Reassembling large files      ");
2678    sprintf(xattr_fname, XATTR_BIGGLST_FNAME_RAW_SZ, bkpinfo->tmpdir);
2679    sprintf(acl_fname, ACL_BIGGLST_FNAME_RAW_SZ, bkpinfo->tmpdir);
2680    mvaddstr_and_log_it(g_currentY, 0, tmp);
2681    sprintf(biggies_whose_EXATs_we_should_set,
2682            "%s/biggies-whose-EXATs-we-should-set", bkpinfo->tmpdir);
2683    if (!(fbw = fopen(biggies_whose_EXATs_we_should_set, "w"))) {
2684        log_msg(1, "Warning - cannot openout %s",
2685                biggies_whose_EXATs_we_should_set);
2686    }
2687// get xattr and acl files if they're there
2688    res =
2689        read_header_block_from_stream(&biggie_size, biggie_fname,
2690                                      &ctrl_chr);
2691    if (ctrl_chr == BLK_START_EXTENDED_ATTRIBUTES) {
2692        res =
2693            read_EXAT_files_from_tape(bkpinfo, &biggie_size, biggie_fname,
2694                                      &ctrl_chr, xattr_fname, acl_fname);
2695    }
2696
2697    noof_biggiefiles = atol(biggie_fname);
2698    sprintf(tmp, "OK, there are %ld biggiefiles in the archives",
2699            noof_biggiefiles);
2700    log_msg(2, tmp);
2701    open_progress_form("Reassembling large files",
2702                       "I am now reassembling all the large files.",
2703                       "Please wait. This may take some time.",
2704                       "", total_slices);
2705
2706    for (res =
2707         read_header_block_from_stream(&biggie_size, biggie_fname,
2708                                       &ctrl_chr);
2709         ctrl_chr != BLK_STOP_BIGGIEFILES;
2710         res =
2711         read_header_block_from_stream(&biggie_size, biggie_fname,
2712                                       &ctrl_chr)) {
2713        if (ctrl_chr != BLK_START_A_NORMBIGGIE
2714            && ctrl_chr != BLK_START_A_PIHBIGGIE) {
2715            wrong_marker(BLK_START_A_NORMBIGGIE, ctrl_chr);
2716        }
2717        p = strrchr(biggie_fname, '/');
2718        if (!p) {
2719            p = biggie_fname;
2720        } else {
2721            p++;
2722        }
2723        sprintf(tmp, "Restoring big file %ld (%lld K)",
2724                current_bigfile_number + 1, biggie_size / 1024);
2725        update_progress_form(tmp);
2726        res = restore_a_biggiefile_from_stream(bkpinfo, biggie_fname,
2727                                               current_bigfile_number,
2728                                               biggie_cksum,
2729                                               biggie_size,
2730                                               filelist, ctrl_chr,
2731                                               pathname_of_last_biggie_restored);
2732        log_msg(1, "I believe I have restored %s",
2733                pathname_of_last_biggie_restored);
2734        if (fbw && pathname_of_last_biggie_restored[0]) {
2735            fprintf(fbw, "%s\n", pathname_of_last_biggie_restored);
2736        }
2737        retval += res;
2738        current_bigfile_number++;
2739
2740    }
2741    if (current_bigfile_number != noof_biggiefiles
2742        && noof_biggiefiles != 0) {
2743        sprintf(tmp, "Warning - bigfileno=%ld but noof_biggiefiles=%ld\n",
2744                current_bigfile_number, noof_biggiefiles);
2745    } else {
2746        sprintf(tmp,
2747                "%ld biggiefiles in biggielist.txt; %ld biggiefiles processed today.",
2748                noof_biggiefiles, current_bigfile_number);
2749    }
2750    log_msg(1, tmp);
2751
2752    if (fbw) {
2753        fclose(fbw);
2754        if (length_of_file(biggies_whose_EXATs_we_should_set) > 2) {
2755            iamhere("Setting biggie-EXATs");
2756            if (length_of_file(acl_fname) > 0) {
2757                log_msg(1, "set_acl_list(%s,%s)",
2758                        biggies_whose_EXATs_we_should_set, acl_fname);
2759                set_acl_list(biggies_whose_EXATs_we_should_set, acl_fname);
2760            }
2761            if (length_of_file(xattr_fname) > 0) {
2762                log_msg(1, "set_fattr_List(%s,%s)",
2763                        biggies_whose_EXATs_we_should_set, xattr_fname);
2764                set_fattr_list(biggies_whose_EXATs_we_should_set,
2765                               xattr_fname);
2766            }
2767        } else {
2768            iamhere
2769                ("No biggiefiles selected. So, no biggie-EXATs to set.");
2770        }
2771    }
2772    if (does_file_exist("/PAUSE")) {
2773        popup_and_OK
2774            ("Press ENTER to go on. Delete /PAUSE to stop these pauses.");
2775    }
2776
2777    close_progress_form();
2778    if (retval) {
2779        mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
2780    } else {
2781        mvaddstr_and_log_it(g_currentY++, 74, "Done.");
2782    }
2783    paranoid_free(biggies_whose_EXATs_we_should_set);
2784    paranoid_free(pathname_of_last_biggie_restored);
2785    paranoid_free(biggie_fname);
2786    paranoid_free(biggie_cksum);
2787    paranoid_free(xattr_fname);
2788    paranoid_free(acl_fname);
2789    paranoid_free(tmp);
2790    return (retval);
2791}
2792
2793/**************************************************************************
2794 *END_RESTORE_ALL_BIGGIEFILES_FROM_STREAM                                 *
2795 **************************************************************************/
2796
2797
2798
2799
2800
2801
2802/**
2803 * Restore all afioballs from the currently opened tape stream.
2804 * @param bkpinfo The backup information structure. Fields used:
2805 * - @c bkpinfo->backup_media_type
2806 * - @c bkpinfo->restore_path
2807 * @param filelist The node structure containing the list of files to be
2808 * restored. If no file in an afioball is in this list, afio will still be
2809 * called for that fileset, but nothing will be written.
2810 * @return 0 for success, or the number of filesets that failed.
2811 */
2812int
2813restore_all_tarballs_from_stream(struct s_bkpinfo *bkpinfo,
2814                                 struct s_node *filelist)
2815{
2816    int retval = 0;
2817    int res;
2818    long current_afioball_number = 0;
2819    int ctrl_chr;
2820    long max_val /*, total_noof_files */ ;
2821
2822  /** malloc **/
2823    char *tmp;
2824    char *progress_str;
2825    char *tmp_fname;
2826    char *xattr_fname;
2827    char *acl_fname;
2828
2829    long long tmp_size;
2830
2831    malloc_string(tmp);
2832    malloc_string(progress_str);
2833    malloc_string(tmp_fname);
2834    assert(bkpinfo != NULL);
2835    malloc_string(xattr_fname);
2836    malloc_string(acl_fname);
2837    mvaddstr_and_log_it(g_currentY, 0, "Restoring from archives");
2838    read_cfg_var(g_mondo_cfg_file, "last-filelist-number", tmp);
2839    max_val = atol(tmp) + 1;
2840
2841    chdir(bkpinfo->restore_path);   /* I don't know why this is needed _here_ but it seems to be. -HR, 02/04/2002 */
2842
2843    run_program_and_log_output("pwd", 5);
2844
2845    sprintf(progress_str, "Restoring from media #%d",
2846            g_current_media_number);
2847    log_to_screen(progress_str);
2848    open_progress_form("Restoring from archives",
2849                       "Restoring data from the archives.",
2850                       "Please wait. This may take some time.",
2851                       progress_str, max_val);
2852
2853    log_msg(3, "hey");
2854
2855    res = read_header_block_from_stream(&tmp_size, tmp_fname, &ctrl_chr);
2856    if (res) {
2857        log_msg(2, "Warning - error reading afioball from tape");
2858    }
2859    retval += res;
2860    if (ctrl_chr != BLK_START_AFIOBALLS) {
2861        wrong_marker(BLK_START_AFIOBALLS, ctrl_chr);
2862    }
2863    log_msg(2, "ho");
2864    res = read_header_block_from_stream(&tmp_size, tmp_fname, &ctrl_chr);
2865    while (ctrl_chr != BLK_STOP_AFIOBALLS) {
2866        update_progress_form(progress_str);
2867        sprintf(xattr_fname, "%s/xattr-subset-%ld.tmp", bkpinfo->tmpdir,
2868                current_afioball_number);
2869        sprintf(acl_fname, "%s/acl-subset-%ld.tmp", bkpinfo->tmpdir,
2870                current_afioball_number);
2871        unlink(xattr_fname);
2872        unlink(acl_fname);
2873        if (ctrl_chr == BLK_START_EXTENDED_ATTRIBUTES) {
2874            iamhere("Reading EXAT files from tape");
2875            res =
2876                read_EXAT_files_from_tape(bkpinfo, &tmp_size, tmp_fname,
2877                                          &ctrl_chr, xattr_fname,
2878                                          acl_fname);
2879        }
2880        if (ctrl_chr != BLK_START_AN_AFIO_OR_SLICE) {
2881            wrong_marker(BLK_START_AN_AFIO_OR_SLICE, ctrl_chr);
2882        }
2883        sprintf(tmp,
2884                "Restoring from fileset #%ld (name=%s, size=%ld K)",
2885                current_afioball_number, tmp_fname, (long) tmp_size >> 10);
2886        res =
2887            restore_a_tarball_from_stream(bkpinfo, tmp_fname,
2888                                          current_afioball_number,
2889                                          filelist, tmp_size, xattr_fname,
2890                                          acl_fname);
2891        retval += res;
2892        if (res) {
2893            sprintf(tmp, "Fileset %ld - errors occurred",
2894                    current_afioball_number);
2895            log_to_screen(tmp);
2896        }
2897        res =
2898            read_header_block_from_stream(&tmp_size, tmp_fname, &ctrl_chr);
2899        if (ctrl_chr != BLK_STOP_AN_AFIO_OR_SLICE) {
2900            wrong_marker(BLK_STOP_AN_AFIO_OR_SLICE, ctrl_chr);
2901        }
2902
2903        current_afioball_number++;
2904        g_current_progress++;
2905        sprintf(progress_str, "Restoring from fileset #%ld on %s #%d",
2906                current_afioball_number,
2907                media_descriptor_string(bkpinfo->backup_media_type),
2908                g_current_media_number);
2909        res =
2910            read_header_block_from_stream(&tmp_size, tmp_fname, &ctrl_chr);
2911        unlink(xattr_fname);
2912        unlink(acl_fname);
2913    }                           // next
2914    log_msg(1, "All done with afioballs");
2915    close_progress_form();
2916    if (retval) {
2917        mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
2918    } else {
2919        mvaddstr_and_log_it(g_currentY++, 74, "Done.");
2920    }
2921    paranoid_free(tmp);
2922    paranoid_free(progress_str);
2923    paranoid_free(tmp_fname);
2924    paranoid_free(xattr_fname);
2925    paranoid_free(acl_fname);
2926    return (retval);
2927}
2928
2929/**************************************************************************
2930 *END_ RESTORE_ALL_TARBALLS_FROM_STREAM                                   *
2931 **************************************************************************/
2932
2933/* @} - end of LLrestoreGroup */
2934
2935
2936/**
2937 * Restore all files in @p filelist.
2938 * @param bkpinfo The backup information structure. Most fields are used.
2939 * @param filelist The node structure containing the list of files to be
2940 * restored.
2941 * @return 0 for success, or the number of afioballs and biggiefiles that failed.
2942 * @ingroup restoreGroup
2943 */
2944int restore_everything(struct s_bkpinfo *bkpinfo, struct s_node *filelist)
2945{
2946    int resA;
2947    int resB;
2948
2949  /** mallco ***/
2950    char *cwd;
2951    char *newpath;
2952    char *tmp;
2953    assert(bkpinfo != NULL);
2954
2955    malloc_string(cwd);
2956    malloc_string(newpath);
2957    malloc_string(tmp);
2958    log_msg(2, "restore_everything() --- starting");
2959    g_current_media_number = 1;
2960    getcwd(cwd, MAX_STR_LEN - 1);
2961    sprintf(tmp, "mkdir -p %s", bkpinfo->restore_path);
2962    run_program_and_log_output(tmp, FALSE);
2963    log_msg(1, "Changing dir to %s", bkpinfo->restore_path);
2964    chdir(bkpinfo->restore_path);
2965    getcwd(newpath, MAX_STR_LEN - 1);
2966    log_msg(1, "path is now %s", newpath);
2967    log_msg(1, "restoring everything");
2968    if (!find_home_of_exe("petris") && !g_text_mode) {
2969        newtDrawRootText(0, g_noof_rows - 2,
2970                         "Press ALT-<left cursor> twice to play Petris :-) ");
2971        newtRefresh();
2972    }
2973    mvaddstr_and_log_it(g_currentY, 0, "Preparing to read your archives");
2974    if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
2975        mount_cdrom(bkpinfo);
2976        mvaddstr_and_log_it(g_currentY++, 0,
2977                            "Restoring OS and data from streaming media");
2978        if (bkpinfo->backup_media_type == cdstream) {
2979            openin_cdstream(bkpinfo);
2980        } else {
2981            assert_string_is_neither_NULL_nor_zerolength(bkpinfo->
2982                                                         media_device);
2983            openin_tape(bkpinfo);
2984        }
2985        resA = restore_all_tarballs_from_stream(bkpinfo, filelist);
2986        resB = restore_all_biggiefiles_from_stream(bkpinfo, filelist);
2987        if (bkpinfo->backup_media_type == cdstream) {
2988            closein_cdstream(bkpinfo);
2989        } else {
2990            closein_tape(bkpinfo);
2991        }
2992    } else {
2993        mvaddstr_and_log_it(g_currentY++, 0,
2994                            "Restoring OS and data from CD       ");
2995        mount_cdrom(bkpinfo);
2996        resA = restore_all_tarballs_from_CD(bkpinfo, filelist);
2997        resB = restore_all_biggiefiles_from_CD(bkpinfo, filelist);
2998    }
2999    chdir(cwd);
3000    if (resA + resB) {
3001        log_to_screen("Errors occurred while data was being restored.");
3002    }
3003    if (length_of_file("/etc/raidtab") > 0) {
3004        log_msg(2, "Copying local raidtab to restored filesystem");
3005        run_program_and_log_output("cp -f /etc/raidtab " MNT_RESTORING
3006                                   "/etc/raidtab", FALSE);
3007    }
3008    kill_petris();
3009    log_msg(2, "restore_everything() --- leaving");
3010    paranoid_free(cwd);
3011    paranoid_free(newpath);
3012    paranoid_free(tmp);
3013    return (resA + resB);
3014}
3015
3016/**************************************************************************
3017 *END_RESTORE_EVERYTHING                                                  *
3018 **************************************************************************/
3019
3020
3021
3022/**
3023 * @brief Haha. You wish! (This function is not implemented :-)
3024 */
3025int
3026restore_live_from_monitas_server(struct s_bkpinfo *bkpinfo,
3027                                 char *monitas_device,
3028                                 char *restore_this_directory,
3029                                 char *restore_here)
3030     /* NB: bkpinfo hasn't been populated yet, except for ->tmp which is "/tmp" */
3031{
3032    FILE *fout;
3033    int retval = 0;
3034    int i;
3035    int j;
3036    struct mountlist_itself the_mountlist;
3037    static struct raidlist_itself the_raidlist;
3038  /** malloc **/
3039    char tmp[MAX_STR_LEN + 1];
3040    char command[MAX_STR_LEN + 1];
3041    char datablock[256 * 1024];
3042    char datadisks_fname[MAX_STR_LEN + 1];
3043    long k;
3044    long length;
3045    long long llt;
3046    struct s_node *filelist = NULL;
3047    assert(bkpinfo != NULL);
3048    assert_string_is_neither_NULL_nor_zerolength(monitas_device);
3049    assert(restore_this_directory != NULL);
3050    assert(restore_here != NULL);
3051
3052    sprintf(tmp, "restore_here = '%s'", restore_here);
3053
3054    log_msg(2, tmp);
3055
3056    log_msg(2, "restore_live_from_monitas_server() - starting");
3057    unlink("/tmp/mountlist.txt");
3058    unlink("/tmp/filelist.full");
3059    unlink("/tmp/biggielist.txt");
3060    if (restore_here[0] == '\0') {
3061        strcpy(bkpinfo->restore_path, MNT_RESTORING);
3062    } else {
3063        strcpy(bkpinfo->restore_path, restore_here);
3064    }
3065    log_msg(3, "FYI FYI FYI FYI FYI FYI FYI FYI FYI FYI FYI");
3066    sprintf(tmp, "FYI - data will be restored to %s",
3067            bkpinfo->restore_path);
3068    log_msg(3, tmp);
3069    log_msg(3, "FYI FYI FYI FYI FYI FYI FYI FYI FYI FYI FYI");
3070    sprintf(datadisks_fname, "/tmp/mondorestore.datadisks.%d",
3071            (int) (random() % 32768));
3072    chdir(bkpinfo->tmpdir);
3073
3074    sprintf(command, "cat %s", monitas_device);
3075    g_tape_stream = popen(command, "r");    // for compatibility with openin_tape()
3076    if (!(fout = fopen(datadisks_fname, "w"))) {
3077        log_OS_error(datadisks_fname);
3078        return (1);
3079    }
3080    for (i = 0; i < 32; i++) {
3081        for (j = 0; j < 4; j++) {
3082            for (length = k = 0; length < 256 * 1024; length += k) {
3083                k = fread(datablock + length, 1, 256 * 1024 - length,
3084                          g_tape_stream);
3085            }
3086            fwrite(datablock, 1, length, fout);
3087            g_tape_posK += length;
3088        }
3089    }
3090    paranoid_fclose(fout);
3091    sprintf(command,
3092            "tar -zxvf %s tmp/mondo-restore.cfg tmp/mountlist.txt tmp/filelist.full tmp/biggielist.txt",
3093            datadisks_fname);
3094    run_program_and_log_output(command, 4);
3095    read_header_block_from_stream(&llt, tmp, &i);
3096    read_header_block_from_stream(&llt, tmp, &i);
3097
3098    unlink(datadisks_fname);
3099    read_cfg_file_into_bkpinfo(g_mondo_cfg_file, bkpinfo);
3100    retval = load_mountlist(&the_mountlist, g_mountlist_fname); // in case read_cfg_file_into_bkpinfo   strcpy(bkpinfo->media_device, monitas_device);
3101
3102
3103    load_raidtab_into_raidlist(&the_raidlist, RAIDTAB_FNAME);
3104    iamhere("FIXME");
3105    fatal_error("This will fail");
3106    sprintf(command,
3107            "cat %s | grep -x \"%s.*\" > %s",
3108            g_filelist_full, restore_this_directory, g_filelist_full);
3109    if (system(command)) {
3110        retval++;
3111        log_to_screen
3112            ("Error(s) occurred while processing filelist and wildcard");
3113    }
3114    iamhere("FIXME");
3115    fatal_error("This will fail");
3116    sprintf(command,
3117            "cat %s | grep -x \"%s.*\" > %s",
3118            g_biggielist_txt, restore_this_directory, g_biggielist_txt);
3119    if (system(command)) {
3120        log_msg(1,
3121                "Error(s) occurred while processing biggielist and wildcard");
3122    }
3123    sprintf(command, "touch %s", g_biggielist_txt);
3124    run_program_and_log_output(command, FALSE);
3125//  filelist = load_filelist(g_filelist_restthese);  // FIXME --- this probably doesn't work because it doesn't include the biggiefiles
3126    retval += restore_everything(bkpinfo, filelist);
3127    free_filelist(filelist);
3128    log_msg(2, "--------End of restore_live_from_monitas_server--------");
3129    return (retval);
3130}
3131
3132/**************************************************************************
3133 *END_RESTORE_LIVE_FROM_MONITAS_SERVER                                    *
3134 **************************************************************************/
3135
3136
3137
3138
3139extern void wait_until_software_raids_are_prepped(char *, int);
3140
3141
3142char which_restore_mode(void);
3143
3144
3145/**
3146 * Log a "don't panic" message to the logfile.
3147 */
3148void welcome_to_mondorestore()
3149{
3150    log_msg(0, "-------------- Mondo Restore v%s -------------", VERSION);
3151    log_msg(0,
3152            "DON'T PANIC! Mondorestore logs almost everything, so please ");
3153    log_msg(0,
3154            "don't break out in a cold sweat just because you see a few  ");
3155    log_msg(0,
3156            "error messages in the log. Read them; analyze them; see if  ");
3157    log_msg(0,
3158            "they are significant; above all, verify your backups! Please");
3159    log_msg(0,
3160            "attach a compressed copy of this log to any e-mail you send ");
3161    log_msg(0,
3162            "to the Mondo mailing list when you are seeking technical    ");
3163    log_msg(0,
3164            "support. Without it, we can't help you.               - Hugo");
3165    log_msg(0,
3166            "------------------------------------------------------------");
3167    log_msg(0,
3168            "BTW, despite (or perhaps because of) the wealth of messages,");
3169    log_msg(0,
3170            "some users are inclined to stop reading this log.  If Mondo ");
3171    log_msg(0,
3172            "stopped for some reason, chances are it's detailed here.    ");
3173    log_msg(0,
3174            "More than likely there's a message at the very end of this  ");
3175    log_msg(0,
3176            "log that will tell you what is wrong.  Please read it!      ");
3177    log_msg(0,
3178            "------------------------------------------------------------");
3179}
3180
3181
3182
3183/**
3184 * Restore the user's data.
3185 * What did you think it did, anyway? :-)
3186 */
3187int main(int argc, char *argv[])
3188{
3189    FILE *fin;
3190    FILE *fout;
3191    int retval = 0;
3192    int res;
3193//  int c;
3194    char *tmp;
3195
3196#ifndef VERSION
3197#define VERSION "1.7x_cvs"
3198#endif
3199
3200    struct mountlist_itself *mountlist;
3201    struct raidlist_itself *raidlist;
3202    struct s_bkpinfo *bkpinfo;
3203    struct s_node *filelist;
3204    char *a, *b;
3205
3206  /**************************************************************************
3207   * hugo-                                                                  *
3208   * busy stuff here - it needs some comments -stan                           *
3209   *                                                                        *
3210   **************************************************************************/
3211    if (getuid() != 0) {
3212        fprintf(stderr, "Please run as root.\r\n");
3213        exit(127);
3214    }
3215
3216    g_loglevel = DEFAULT_MR_LOGLEVEL;
3217    malloc_string(tmp);
3218
3219/* Configure global variables */
3220#ifdef __FreeBSD__
3221    if (strstr
3222        (call_program_and_get_last_line_of_output("cat /tmp/cmdline"),
3223         "textonly"))
3224#else
3225    if (strstr
3226        (call_program_and_get_last_line_of_output("cat /proc/cmdline"),
3227         "textonly"))
3228#endif
3229    {
3230        g_text_mode = TRUE;
3231        log_msg(1, "TEXTONLY MODE");
3232    } else {
3233        g_text_mode = FALSE;
3234    }                           // newt :-)
3235    if (!
3236        (bkpinfo = g_bkpinfo_DONTUSETHIS =
3237         malloc(sizeof(struct s_bkpinfo)))) {
3238        fatal_error("Cannot malloc bkpinfo");
3239    }
3240    if (!(mountlist = malloc(sizeof(struct mountlist_itself)))) {
3241        fatal_error("Cannot malloc mountlist");
3242    }
3243    if (!(raidlist = malloc(sizeof(struct raidlist_itself)))) {
3244        fatal_error("Cannot malloc raidlist");
3245    }
3246
3247    malloc_libmondo_global_strings();
3248
3249    strcpy(g_mondo_home,
3250           call_program_and_get_last_line_of_output("which mondorestore"));
3251    sprintf(g_tmpfs_mountpt, "/tmp/tmpfs");
3252    make_hole_for_dir(g_tmpfs_mountpt);
3253    g_current_media_number = 1; // precaution
3254
3255    run_program_and_log_output("mkdir -p " MNT_CDROM, FALSE);
3256    run_program_and_log_output("mkdir -p /mnt/floppy", FALSE);
3257
3258    malloc_string(tmp);
3259    malloc_string(a);
3260    malloc_string(b);
3261    setup_MR_global_filenames(bkpinfo); // malloc() and set globals, using bkpinfo->tmpdir etc.
3262    reset_bkpinfo(bkpinfo);
3263    bkpinfo->backup_media_type = none;  // in case boot disk was made for one backup type but user wants to restore from another backup type
3264    bkpinfo->restore_data = TRUE;   // Well, yeah :-)
3265    if (am_I_in_disaster_recovery_mode()) {
3266        run_program_and_log_output("mount / -o remount,rw", 2);
3267    }                           // for b0rken distros
3268    g_main_pid = getpid();
3269    srandom((int) (time(NULL)));
3270    register_pid(getpid(), "mondo");
3271    set_signals(TRUE);
3272    g_kernel_version = get_kernel_version();
3273
3274    log_msg(1, "FYI - g_mountlist_fname = %s", g_mountlist_fname);
3275    if (strlen(g_mountlist_fname) < 3) {
3276        fatal_error
3277            ("Serious error in malloc()'ing. Could be a bug in your glibc.");
3278    }
3279    mkdir(MNT_CDROM, 0x770);
3280
3281/* Backup original mountlist.txt */
3282    sprintf(tmp, "%s.orig", g_mountlist_fname);
3283    if (!does_file_exist(g_mountlist_fname)) {
3284        log_msg(2,
3285                "%ld: Warning - g_mountlist_fname (%s) does not exist yet",
3286                __LINE__, g_mountlist_fname);
3287    } else if (!does_file_exist(tmp)) {
3288        sprintf(tmp, "cp -f %s %s.orig", g_mountlist_fname,
3289                g_mountlist_fname);
3290        run_program_and_log_output(tmp, FALSE);
3291    }
3292
3293/* Init directories */
3294    make_hole_for_dir(bkpinfo->tmpdir);
3295    sprintf(tmp, "mkdir -p %s", bkpinfo->tmpdir);
3296    run_program_and_log_output(tmp, FALSE);
3297    make_hole_for_dir("/var/log");
3298    make_hole_for_dir("/tmp/tmpfs");    /* just in case... */
3299    run_program_and_log_output("umount " MNT_CDROM, FALSE);
3300    run_program_and_log_output
3301        ("ln -sf /var/log/mondo-archive.log /tmp/mondo-restore.log",
3302         FALSE);
3303
3304    run_program_and_log_output("rm -Rf /tmp/tmpfs/mondo.tmp.*", FALSE);
3305
3306/* Init GUI */
3307    malloc_libmondo_global_strings();
3308    setup_newt_stuff();         /* call newtInit and setup screen log */
3309    welcome_to_mondorestore();
3310    if (bkpinfo->disaster_recovery) {
3311        log_msg(1, "I am in disaster recovery mode");
3312    } else {
3313        log_msg(1, "I am in normal, live mode");
3314    }
3315
3316    iamhere("what time is it");
3317
3318/* Process command-line parameters */
3319    if (argc == 2 && strcmp(argv[1], "--edit-mountlist") == 0) {
3320#ifdef __FreeBSD__
3321        system("mv -f /tmp/raidconf.txt /etc/raidtab");
3322        if (!does_file_exist("/etc/raidtab"))
3323            system("vinum printconfig > /etc/raidtab");
3324#endif
3325        load_raidtab_into_raidlist(raidlist, RAIDTAB_FNAME);
3326        if (!does_file_exist(g_mountlist_fname)) {
3327            strcpy(g_mountlist_fname, "/tmp/mountlist.txt");
3328        }
3329        res = let_user_edit_the_mountlist(bkpinfo, mountlist, raidlist);
3330#ifdef __FreeBSD__
3331        system("mv -f /etc/raidtab /tmp/raidconf.txt");
3332#endif
3333        paranoid_MR_finish(res);
3334    }
3335
3336    g_loglevel = DEFAULT_MR_LOGLEVEL;
3337    if (argc == 3 && strcmp(argv[1], "--echo-to-screen") == 0) {
3338        fout = fopen("/tmp/out.txt", "w");
3339        fput_string_one_char_at_a_time(stderr, argv[2]);
3340        finish(0);
3341    }
3342
3343    if (argc == 3 && strcmp(argv[1], "--gendf") == 0) {
3344        make_grub_install_scriptlet(argv[2]);
3345        finish(0);
3346    }
3347
3348    if (argc >= 2 && strcmp(argv[1], "--pih") == 0) {
3349        if (system("mount | grep cdrom 2> /dev/null > /dev/null")) {
3350            system("mount " MNT_CDROM);
3351        }
3352        bkpinfo->compression_level = 1;
3353        g_current_media_number = 2;
3354        strcpy(bkpinfo->restore_path, "/tmp/TESTING");
3355        bkpinfo->backup_media_type = dvd;
3356        open_progress_form("Reassembling /dev/hda1",
3357                           "Shark is a bit of a silly person.",
3358                           "Please wait. This may take some time.",
3359                           "", 1999);
3360        system("rm -Rf /tmp/*pih*");
3361
3362        restore_a_biggiefile_from_CD(bkpinfo, 42, NULL, tmp);
3363    }
3364
3365    if (argc == 5 && strcmp(argv[1], "--common") == 0) {
3366        g_loglevel = 6;
3367        filelist = load_filelist(argv[2]);
3368        if (!filelist) {
3369            fatal_error("Failed to load filelist");
3370        }
3371        toggle_node_selection(filelist, FALSE);
3372        toggle_all_root_dirs_on(filelist);
3373        toggle_path_selection(filelist, "/usr/share", TRUE);
3374//      show_filelist(filelist);
3375        save_filelist(filelist, "/tmp/out.txt");
3376//      finish(0);
3377//      toggle_path_selection (filelist, "/root/stuff", TRUE);
3378        strcpy(a, argv[3]);
3379        strcpy(b, argv[4]);
3380
3381        res = save_filelist_entries_in_common(a, filelist, b, FALSE);
3382        free_filelist(filelist);
3383        printf("res = %d", res);
3384        finish(0);
3385    }
3386
3387    if (argc == 3 && strcmp(argv[1], "--popuplist") == 0) {
3388        popup_changelist_from_file(argv[2]);
3389        paranoid_MR_finish(0);
3390    }
3391
3392    if (argc == 5 && strcmp(argv[1], "--copy") == 0) {
3393        log_msg(1, "SCORE");
3394        g_loglevel = 10;
3395        if (strstr(argv[2], "save")) {
3396            log_msg(1, "Saving from %s to %s", argv[3], argv[4]);
3397            fin = fopen(argv[3], "r");
3398            fout = fopen(argv[4], "w");
3399            copy_from_src_to_dest(fin, fout, 'w');
3400            fclose(fin);
3401            fin = fopen(argv[3], "r");
3402            copy_from_src_to_dest(fin, fout, 'w');
3403            fclose(fout);
3404            fclose(fin);
3405        } else if (strstr(argv[2], "restore")) {
3406            fout = fopen(argv[3], "w");
3407            fin = fopen(argv[4], "r");
3408            copy_from_src_to_dest(fout, fin, 'r');
3409            fclose(fin);
3410            fin = fopen(argv[4], "r");
3411            copy_from_src_to_dest(fout, fin, 'r');
3412            fclose(fout);
3413            fclose(fin);
3414        } else {
3415            fatal_error("Unknown additional param");
3416        }
3417        finish(0);
3418    }
3419
3420    if (argc == 3 && strcmp(argv[1], "--mdstat") == 0) {
3421        wait_until_software_raids_are_prepped(argv[2], 100);
3422        finish(0);
3423    }
3424
3425    if (argc == 4 && strcmp(argv[1], "--mdconv") == 0) {
3426        finish(create_raidtab_from_mdstat(argv[2], argv[3]));
3427    }
3428
3429
3430    if (argc == 2 && strcmp(argv[1], "--live-grub") == 0) {
3431        retval = run_grub(FALSE, "/dev/hda");
3432        if (retval) {
3433            log_to_screen("Failed to write Master Boot Record");
3434        }
3435        paranoid_MR_finish(0);
3436    }
3437    if (argc == 3 && strcmp(argv[1], "--paa") == 0) {
3438        g_current_media_number = atoi(argv[2]);
3439        pause_and_ask_for_cdr(5, NULL);
3440        paranoid_MR_finish(0);
3441    } else if (!bkpinfo->disaster_recovery) {   // live!
3442        if (argc != 1) {
3443            popup_and_OK
3444                ("Live mode doesn't support command-line parameters yet.");
3445            paranoid_MR_finish(1);
3446//    return(1);
3447        }
3448        log_msg(1, "I am in normal, live mode.");
3449        log_msg(2, "FYI, MOUNTLIST_FNAME = %s", g_mountlist_fname);
3450        mount_boot_if_necessary();  /* for Gentoo users */
3451        log_msg(2, "Still here.");
3452        if (argc > 1 && strcmp(argv[argc - 1], "--live-from-cd") == 0) {
3453            g_restoring_live_from_cd = TRUE;
3454        }
3455        if (argc == 5 && strcmp(argv[1], "--monitas-live") == 0) {
3456            retval =
3457                restore_live_from_monitas_server(bkpinfo,
3458                                                 argv[2],
3459                                                 argv[3], argv[4]);
3460        } else {
3461            log_msg(2, "Calling restore_to_live_filesystem()");
3462            retval = restore_to_live_filesystem(bkpinfo);
3463        }
3464        log_msg(2, "Still here. Yay.");
3465        if (strlen(bkpinfo->tmpdir) > 0) {
3466            sprintf(tmp, "rm -Rf %s/*", bkpinfo->tmpdir);
3467            run_program_and_log_output(tmp, FALSE);
3468        }
3469        unmount_boot_if_necessary();    /* for Gentoo users */
3470        paranoid_MR_finish(retval);
3471    } else {
3472/* Disaster recovery mode (must be) */
3473        log_msg(1, "I must be in disaster recovery mode.");
3474        log_msg(2, "FYI, MOUNTLIST_FNAME = %s ", g_mountlist_fname);
3475        if (argc == 3 && strcmp(argv[1], "--monitas-memorex") == 0) {
3476            log_to_screen("Uh, that hasn't been implemented yet.");
3477            paranoid_MR_finish(1);
3478        }
3479
3480        iamhere("About to call load_mountlist and load_raidtab");
3481        strcpy(bkpinfo->restore_path, MNT_RESTORING);
3482        read_cfg_file_into_bkpinfo(g_mondo_cfg_file, bkpinfo);
3483        retval = load_mountlist(mountlist, g_mountlist_fname);
3484        retval += load_raidtab_into_raidlist(raidlist, RAIDTAB_FNAME);
3485        iamhere
3486            ("Returned from calling load_mountlist and load_raidtab successfully");
3487
3488        if (argc > 1
3489            && (strcmp(argv[1], "--compare") == 0
3490                || strcmp(argv[1], "--nuke") == 0)) {
3491            if (bkpinfo->backup_media_type == nfs
3492                && !is_this_device_mounted(bkpinfo->nfs_mount)) {
3493                log_msg(1, "Mounting nfs dir");
3494                sprintf(bkpinfo->isodir, "/tmp/isodir");
3495                run_program_and_log_output("mkdir -p /tmp/isodir", 5);
3496                sprintf(tmp, "mount %s -t nfs -o nolock /tmp/isodir",
3497                        bkpinfo->nfs_mount);
3498                run_program_and_log_output(tmp, 1);
3499            }
3500        }
3501
3502
3503        if (retval) {
3504            log_to_screen
3505                ("Warning - load_raidtab_into_raidlist returned an error");
3506        }
3507
3508
3509        log_msg(1, "Send in the clowns.");
3510
3511        if (argc == 2 && strcmp(argv[1], "--partition-only") == 0) {
3512            log_msg(0, "Partitioning only.");
3513            load_raidtab_into_raidlist(raidlist, RAIDTAB_FNAME);
3514            strcpy(g_mountlist_fname, "/tmp/mountlist.txt");
3515            load_mountlist(mountlist, g_mountlist_fname);
3516            res = partition_everything(mountlist);
3517            finish(res);
3518        }
3519
3520        if (argc == 2 && strcmp(argv[1], "--format-only") == 0) {
3521            log_msg(0, "Formatting only.");
3522            load_raidtab_into_raidlist(raidlist, RAIDTAB_FNAME);
3523            strcpy(g_mountlist_fname, "/tmp/mountlist.txt");
3524            load_mountlist(mountlist, g_mountlist_fname);
3525            res = format_everything(mountlist, FALSE);
3526            finish(res);
3527        }
3528
3529        if (argc == 2 && strcmp(argv[1], "--stop-lvm-and-raid") == 0) {
3530            log_msg(0, "Stopping LVM and RAID");
3531            load_raidtab_into_raidlist(raidlist, RAIDTAB_FNAME);
3532            strcpy(g_mountlist_fname, "/tmp/mountlist.txt");
3533            load_mountlist(mountlist, g_mountlist_fname);
3534            res = do_my_funky_lvm_stuff(TRUE, FALSE);
3535            res += stop_all_raid_devices(mountlist);
3536            finish(res);
3537        }
3538
3539        if (argc == 2 && strcmp(argv[1], "--nuke") == 0) {
3540            iamhere("nuking");
3541            retval += nuke_mode(bkpinfo, mountlist, raidlist);
3542        } else if (argc == 2 && strcmp(argv[1], "--interactive") == 0) {
3543            iamhere("catchall");
3544            retval += catchall_mode(bkpinfo, mountlist, raidlist);
3545        } else if (argc == 2 && strcmp(argv[1], "--compare") == 0) {
3546            iamhere("compare");
3547            retval += compare_mode(bkpinfo, mountlist, raidlist);
3548        } else if (argc == 2 && strcmp(argv[1], "--iso") == 0) {
3549            iamhere("iso");
3550            retval = iso_mode(bkpinfo, mountlist, raidlist, FALSE);
3551        } else if (argc == 2 && strcmp(argv[1], "--mbr") == 0) {
3552            iamhere("mbr");
3553            retval = mount_all_devices(mountlist, TRUE);
3554            if (!retval) {
3555                retval += run_boot_loader(FALSE);
3556                retval += unmount_all_devices(mountlist);
3557            }
3558            if (retval) {
3559                log_to_screen("Failed to write Master Boot Record");
3560            }
3561        } else if (argc == 2 && strcmp(argv[1], "--isonuke") == 0) {
3562            iamhere("isonuke");
3563            retval = iso_mode(bkpinfo, mountlist, raidlist, TRUE);
3564        } else if (argc != 1) {
3565            log_to_screen("Invalid paremeters");
3566            paranoid_MR_finish(1);
3567        } else {
3568            iamhere("catchall (no mode specified in command-line call");
3569            retval += catchall_mode(bkpinfo, mountlist, raidlist);
3570        }
3571    }
3572
3573    /* clean up at the end */
3574    if (retval) {
3575        if (does_file_exist("/tmp/changed.files")) {
3576            log_to_screen
3577                ("See /tmp/changed.files for list of files that have changed.");
3578        }
3579        mvaddstr_and_log_it(g_currentY++,
3580                            0,
3581                            "Run complete. Errors were reported. Please review the logfile.");
3582    } else {
3583        if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
3584            mvaddstr_and_log_it(g_currentY++,
3585                                0,
3586                                "Run complete. Please remove floppy/CD/media and reboot.");
3587        } else {
3588            run_program_and_log_output("sync", FALSE);
3589            if (is_this_device_mounted(MNT_CDROM)) {
3590                res =
3591                    run_program_and_log_output("umount " MNT_CDROM, FALSE);
3592            } else {
3593                res = 0;
3594            }
3595
3596            if (!bkpinfo->please_dont_eject) {
3597                res = eject_device("/dev/cdrom");
3598/*
3599              if (res)
3600        {
3601          log_to_screen( "WARNING - failed to eject CD-ROM disk" );
3602        }
3603*/
3604            }
3605            mvaddstr_and_log_it(g_currentY++,
3606                                0,
3607                                "Run complete. Please remove media and reboot.");
3608        }
3609    }
3610
3611// g_I_have_just_nuked is set true by nuke_mode() just before it returns
3612    if (g_I_have_just_nuked || does_file_exist("/POST-NUKE-ANYWAY")) {
3613        if (!system("which post-nuke > /dev/null 2> /dev/null")) {
3614            log_msg(1, "post-nuke found; running...");
3615            if (mount_all_devices(mountlist, TRUE)) {
3616                log_to_screen
3617                    ("Unable to re-mount partitions for post-nuke stuff");
3618            } else {
3619                log_msg(1, "Re-mounted partitions for post-nuke stuff");
3620                sprintf(tmp, "post-nuke %s %d", bkpinfo->restore_path,
3621                        retval);
3622                if (!g_text_mode) {
3623                    newtSuspend();
3624                }
3625                log_msg(2, "Calling '%s'", tmp);
3626                if ((res = system(tmp))) {
3627                    log_OS_error(tmp);
3628                }
3629                if (!g_text_mode) {
3630                    newtResume();
3631                }
3632//              newtCls();
3633                log_msg(1, "post-nuke returned w/ res=%d", res);
3634            }
3635            unmount_all_devices(mountlist);
3636            log_msg(1, "I've finished post-nuking.");
3637        }
3638    }
3639/* 
3640  log_to_screen("If you are REALLY in a hurry, hit Ctrl-Alt-Del now.");
3641  log_to_screen("Otherwise, please wait until the RAID disks are done.");
3642  wait_until_software_raids_are_prepped("/proc/mdstat", 100);
3643  log_to_screen("Thank you.");
3644*/
3645    unlink("/tmp/mondo-run-prog.tmp");
3646    set_signals(FALSE);
3647    sprintf(tmp, "rm -Rf %s", bkpinfo->tmpdir);
3648    run_program_and_log_output(tmp, FALSE);
3649    log_to_screen
3650        ("Restore log copied to /tmp/mondo-restore.log on your hard disk");
3651    sprintf(tmp,
3652            "Mondo-restore is exiting (retval=%d)                                      ",
3653            retval);
3654    log_to_screen(tmp);
3655    sprintf(tmp, "umount %s", bkpinfo->isodir);
3656    run_program_and_log_output(tmp, 5);
3657    paranoid_free(mountlist);
3658    paranoid_free(raidlist);
3659    if (am_I_in_disaster_recovery_mode()) {
3660        run_program_and_log_output("mount / -o remount,rw", 2);
3661    }                           // for b0rken distros
3662    paranoid_MR_finish(retval); // frees global stuff plus bkpinfo
3663    free_libmondo_global_strings(); // it's fine to have this here :) really :)
3664    paranoid_free(a);
3665    paranoid_free(b);
3666    paranoid_free(tmp);
3667
3668    unlink("/tmp/filelist.full");
3669    unlink("/tmp/filelist.full.gz");
3670
3671    exit(retval);
3672}
3673
3674/**************************************************************************
3675 *END_MAIN                                                                *
3676 **************************************************************************/
3677
3678
3679
3680
3681
3682/**************************************************************************
3683 *END_MONDO-RESTORE.C                                                     *
3684 **************************************************************************/
Note: See TracBrowser for help on using the repository browser.