source: branches/2.2.5/mondo/src/common/libmondo-tools.c @ 1656

Last change on this file since 1656 was 1656, checked in by Bruno Cornec, 12 years ago

Fixes missing extern function declaation for setup_tmpdir

  • Property svn:keywords set to Id
File size: 45.8 KB
Line 
1/* libmondo-tools.c                                  misc tools
2   $Id: libmondo-tools.c 1656 2007-09-24 23:12:19Z bruno $
3.
4
5
606/28
7- abort if RAID partitions found but /etc/raidtab not found
8
906/25
10- don't insist on ms-sys; recommend it
11- don't fatal_error if can't open log file
12
1306/14
14- call mindi -V before calling mindi --makemountlist
15
1604/09
17- lots of malloc'd char*'s instead of char[]'s in post_param_config'n
18
1904/02
20- better sanity-checking, re: /etc/modules.conf
21
2202/15
23- abort if Windows dir but no ms-sys or parted
24
2502/08
26- missing ramdisk/initrd support is nonfatal now (but stupid)
27
2801/16
29- added g_kernel_version and get_kernel_version()
30
3101/08/2004
32- fixed /boot mounter thingy
33
3411/14/2003
35- if <50MB free in /root, softlink /root/images/mindi to
36  /home/root/images/mindi as a workaround
37
3810/23
39- streaming backups now generate 4MB sets; CDs, 8MB sets
40
4110/21
42- better at finding your /boot in order to mount it, if nec.
43- link /etc/modules.conf to /etc/conf.modules if former
44  is missing but latter is not
45- changed "/mnt/cdrom" to MNT_CDROM
46- changed "/mnt/floppy" to MNT_FLOPPY
47
4810/13
49- added stop_magicdev_if_necessary()
50- added restart_magicdev_if_necessary()
51
5210/02
53- don't eject if bkpinfo->please_dont_eject is TRUE
54
5509/28
56- fixed segfault in mount_..._necessary
57
5809/26
59- ask for cmp (or create workaround if possible)
60
6109/25
62- add DVD support
63
6409/24
65- don't overwrite existing media-dev value in bkpinfo IF it's
66  a tape device AND it's already populated by /dev/{something}
67  ...This helps w/ weird tape drives
68
6909/23
70- malloc/free global strings in new subroutines - malloc_libmondo_global_strings()
71  and free_libmondo_global_strings() - which are in libmondo-tools.c
72
7309/18
74- added stop_autofs_if_necessary() and restart_autofs_if_necessary()
75
7609/13
77- added log_debug_msg()
78- turned log_it() into a macro
79
8009/10
81- reduced PPCFG_RAMDISK to 150m (was 200m)
82- max set size is now 8MB (was 6)
83- added 'buffer' to requisite tools
84
8508/29
86- typical set size is now 5MB
87   
8807/22
89- increased PPCFG* to 200m
90
9105/07
92- changed grep -m1 to grep | head -n1 for Debian users
93- pre_param_...() also mkdir -p /mnt/cdrom, just in case
94
9505/05
96- cleaner logging of call to dd if=<tape> of=/dev/null
97- added Joshua Oreman's FreeBSD patches
98
9905/04
100- added Herman Kuster's multi-level bkp patch
101
10205/02
103- log_it() --- "Message repeated N times" (if it was)
104
10504/24
106- added lots of assert()'s and log_OS_error()'s
107- reset_bkpinfop() --- reset all media_size[] array
108- increased tmpfs ramdisk to size=100m
109
11004/22
111- post_param_configuration() --- store iso-dev and isodir
112
11304/05
114- re-enable tmpfs ramdisk/mountpt _but_ make sure size=80m
115- in post_param_configuration(), use cdrecord in preference
116  to dvdrecord now
117
11803/27
119- disabled tmpfs ramdisk/mountpt
120
12101/02/2003
122- bkpinfo->makefilelist = TRUE
123
12412/10/2002
125- added g_loglevel
126- fixed minor bug in clean_up_KDE_desktop_if_necessary()
127- log versions of newt, slang, ncurses
128- isodir defaults to / if disaster recovery
129
13011/28
131- unmount all CD devices at start
132- added clean_up_KDE_desktop_if_necessary()
133
13411/20
135- don't use lilo.conf.anaconda; abort instead
136- mount/unmount /boot partition for Gentoo 1.2 users
137
13811/13
139- call mindi --makemountlist as part of testing sanity of distro
140
14111/08
142- added a couple of chmod 700's (one for scratchdir, one for tmpdir)
143  to post_param_configuration()
144
14510/01 - 10/31
146- added checking of / and /root's free space to some_basic_sanity_checks()
147- moved some subroutines here from common/libmondo-archive
148
14909/01 - 09/30
150- don't write log_it()'s string to stdout, even if text mode
151- tell user the kernel is bad if it has no ramdisk support but allow
152  it if they want to use the failsafe kernel for booting
153- run_program_and_log_output() now takes boolean operator to specify
154  whether it will log its activities in the event of _success_
155- if mkfs.vfat not found but mkfs.msdos found then create a softlink
156  from the former to the latter
157
15808/01 - 08/31
159- if /etc/lilo.conf not found not /etc/lilo.conf.anaconda found
160  then create a softlink from the former to the latter, to work
161  around RH7.3's b0rken LILO support
162- handle unknown media size
163
16407/27
165- created
166*/
167
168
169/**
170 * @file
171 * Miscellaneous tools that didn't really fit anywhere else.
172 */
173
174#include "my-stuff.h"
175#include "mondostructures.h"
176#include "lib-common-externs.h"
177#include "libmondo-tools.h"
178#include "libmondo-gui-EXT.h"
179#include "libmondo-files-EXT.h"
180#include "libmondo-fork-EXT.h"
181#include "libmondo-raid-EXT.h"
182#include <sys/socket.h>
183#include <netdb.h>
184#include <stdlib.h>
185#include <netinet/in.h>
186#include <arpa/inet.h>
187#include <sys/utsname.h>
188
189/*@unused@*/
190//static char cvsid[] = "$Id: libmondo-tools.c 1656 2007-09-24 23:12:19Z bruno $";
191
192extern int g_tape_buffer_size_MB;
193extern char *g_erase_tmpdir_and_scratchdir;
194extern char *g_serial_string;
195extern bool g_text_mode;
196extern int g_currentY;
197extern int g_current_media_number;
198extern char *MONDO_LOGFILE;
199
200/* Reference to global bkpinfo */
201extern struct s_bkpinfo *bkpinfo;
202
203/**
204 * @addtogroup globalGroup
205 * @{
206 */
207bool g_remount_cdrom_at_end,    ///< TRUE if we unmounted the CD-ROM and should remount it when done with the backup.
208 g_remount_floppy_at_end;       ///< TRUE if we unmounted the floppy and should remount it when done with the backup.
209bool g_cd_recovery;             ///< TRUE if we're making an "autonuke" backup.
210double g_kernel_version;
211
212/**
213 * The place where /boot is mounted.
214 */
215char *g_boot_mountpt = NULL;
216
217/**
218 * The location of Mondo's home directory.
219 */
220char *g_mondo_home = NULL;
221
222/**
223 * The serial string (used to differentiate between backups) of the current backup.
224 */
225char *g_serial_string = NULL;
226
227/**
228 * The location where tmpfs is mounted, or "" if it's not mounted.
229 */
230char *g_tmpfs_mountpt = NULL;
231char *g_magicdev_command = NULL;
232
233/**
234 * The default maximum level to log messages at or below.
235 */
236int g_loglevel = DEFAULT_DEBUG_LEVEL;
237
238/* @} - end of globalGroup */
239
240
241extern pid_t g_buffer_pid;
242extern pid_t g_main_pid;
243
244extern t_bkptype g_backup_media_type;
245
246extern bool am_I_in_disaster_recovery_mode(void);
247
248
249/**
250 * @addtogroup utilityGroup
251 * @{
252 */
253/**
254 * Assertion handler. Prints a friendly message to the user,
255 * offering to ignore all, dump core, break to debugger,
256 * exit, or ignore. Intended to be used with an assert() macro.
257 *
258 * @param file The file in which the assertion triggered.
259 * @param function The function (@c __FUNCTION__) in which the assertion triggered.
260 * @param line The line number of the assert() statement.
261 * @param exp The expression that failed (as a string).
262 */
263void _mondo_assert_fail(const char *file,
264                        const char *function, int line, const char *exp)
265{
266    static int ignoring_assertions = 0;
267    bool is_valid = TRUE;
268
269    log_it("ASSERTION FAILED: `%s' at %s:%d in %s", exp, file, line,
270           function);
271    if (ignoring_assertions) {
272        log_it("Well, the user doesn't care...");
273        return;
274    }
275#ifndef _XWIN
276    if (!g_text_mode)
277        newtSuspend();
278#endif
279    printf("ASSERTION FAILED: `%s'\n", exp);
280    printf("\tat %s:%d in %s\n\n", file, line, function);
281    printf("(I)gnore, ignore (A)ll, (D)ebug, a(B)ort, or (E)xit? ");
282    do {
283        is_valid = TRUE;
284        switch (toupper(getchar())) {
285        case 'A':               // ignore (A)ll
286            ignoring_assertions = 1;
287            break;
288        case 'B':               // a(B)ort
289            signal(SIGABRT, SIG_DFL);   /* prevent SIGABRT handler from running */
290            raise(SIGABRT);
291            break;              /* "can't get here" */
292        case 'D':               // (D)ebug, aka asm("int 3")
293#ifdef __IA32__
294            __asm__ __volatile__("int $3"); // break to debugger
295#endif
296            break;
297        case 'E':               // (E)xit
298            fatal_error("Failed assertion -- see above for details");
299            break;              /* "can't get here" */
300        case 'I':               // (I)gnore
301            break;
302            /* These next two work as follows:
303               the `default' catches the user's invalid choice and says so;
304               the '\n' catches the newline on the end and prints the prompt again.
305             */
306        case '\n':
307            printf
308                ("(I)gnore, ignore (A)ll, (D)ebug, a(B)ort, or (E)xit? ");
309            break;
310        default:
311            is_valid = FALSE;
312            printf("Invalid choice.\n");
313            break;
314        }
315    } while (!is_valid);
316
317    if (ignoring_assertions) {
318        log_it("Ignoring ALL assertions from now on.");
319    } else {
320        log_it("Ignoring assertion: %s", exp);
321    }
322
323    getchar();                  // skip \n
324
325#ifndef _XWIN
326    if (!g_text_mode)
327        newtResume();
328#endif
329}
330
331/**
332 * Clean's up users' KDE desktops.
333 * @bug Details about this function are unknown.
334 */
335void clean_up_KDE_desktop_if_necessary(void)
336{
337    char *tmp;
338
339    malloc_string(tmp);
340    strcpy(tmp,
341           "for i in `find /root /home -type d -name Desktop -maxdepth 2`; do \
342file=$i/.directory; if [ -f \"$file\" ] ; then mv -f $file $file.old ; \
343awk '{if (index($0, \"rootimagesmindi\")) { while (length($0)>2) { getline;} ; } \
344else { print $0;};}' $file.old  > $file ; fi ; done");
345    run_program_and_log_output(tmp, 5);
346    paranoid_free(tmp);
347}
348
349
350/**
351 * Locate mondoarchive's home directory. Searches in /usr/local/mondo, /usr/share/mondo,
352 * /usr/local/share/mondo, /opt, or if all else fails, search /usr.
353 *
354 * @param home_sz String to store the home directory ("" if it could not be found).
355 * @return 0 for success, nonzero for failure.
356 */
357int find_and_store_mondoarchives_home(char *home_sz)
358{
359    assert(home_sz != NULL);
360    strcpy(home_sz, MONDO_SHARE);
361    return (0);
362}
363
364
365char *get_architecture(void) {
366#ifdef __IA32__
367#   ifdef __X86_64__
368        return ("x86_64");
369#   else
370        return ("i386");
371#   endif
372#endif
373#ifdef __IA64__
374    return ("ia64");
375#endif
376    return ("unknown");
377}
378
379
380char *get_uname_m(void) {
381
382    struct utsname utsn;
383    char *tmp = NULL;
384
385    uname(&utsn);
386    asprintf(&tmp, utsn.machine);
387    return (tmp);
388}
389
390
391
392double get_kernel_version(void)
393{
394    char *p, tmp[200];
395    double d;
396#ifdef __FreeBSD__
397    // JOSH - FIXME :)
398    d = 5.2;                    // :-)
399#else
400    strcpy(tmp, call_program_and_get_last_line_of_output("uname -r"));
401    p = strchr(tmp, '.');
402    if (p) {
403        p = strchr(++p, '.');
404        if (p) {
405            while (*p) {
406                *p = *(p + 1);
407                p++;
408            }
409        }
410    }
411//  log_msg(1, "tmp = '%s'", tmp);
412    d = atof(tmp);
413#endif
414    log_msg(1, "g_kernel_version = %f", d);
415    return (d);
416}
417
418
419
420
421
422/**
423 * Get the current time.
424 * @return number of seconds since the epoch.
425 */
426long get_time()
427{
428    return (long) time((void *) 0);
429}
430
431
432
433
434
435
436
437/**
438 * Initialize a RAID volume structure, setting fields to zero. The
439 * actual hard drive is unaffected.
440 *
441 * @param raidrec The RAID volume structure to initialize.
442 * @note This function is system dependent.
443 */
444#ifdef __FreeBSD__
445void initialize_raidrec(struct vinum_volume *raidrec)
446{
447    int i, j;
448    raidrec->volname[0] = '\0';
449    raidrec->plexes = 0;
450    for (i = 0; i < 9; ++i) {
451        raidrec->plex[i].raidlevel = -1;
452        raidrec->plex[i].stripesize = 0;
453        raidrec->plex[i].subdisks = 0;
454        for (j = 0; j < 9; ++j) {
455            strcpy(raidrec->plex[i].sd[j].which_device, "");
456        }
457    }
458}
459#else
460void initialize_raidrec(struct raid_device_record *raidrec)
461{
462    assert(raidrec != NULL);
463    raidrec->raid_device[0] = '\0';
464    raidrec->raid_level = -9;
465    raidrec->persistent_superblock = 1;
466    raidrec->chunk_size = 64;
467    raidrec->parity = -1;
468    raidrec->data_disks.entries = 0;
469    raidrec->spare_disks.entries = 0;
470    raidrec->parity_disks.entries = 0;
471    raidrec->failed_disks.entries = 0;
472    raidrec->additional_vars.entries = 0;
473}
474#endif
475
476
477
478
479/**
480 * Insert modules that Mondo requires.
481 * Currently inserts @c msdos, @c vfat, and @c loop for Linux;
482 * @c msdosfs and @c ext2fs for FreeBSD.
483 */
484void insmod_crucial_modules(void)
485{
486#ifdef __FreeBSD__
487    system("kldstat | grep msdosfs || kldload msdosfs 2> /dev/null");
488    system("kldstat | grep ext2fs  || kldload ext2fs 2> /dev/null");
489#else
490    system("modprobe -a msdos vfat loop &> /dev/null");
491#endif
492}
493
494
495/**
496 * Log a trace message to the trace file.
497 * @bug This function seems orphaned. Please remove.
498 */
499void log_trace(char *o)
500{
501    /*@ pointers **************************************************** */
502    FILE *fout;
503
504    /*@ buffers ***************************************************** */
505    char output[MAX_STR_LEN];
506
507    /*@ int    ****************************************************** */
508    int i;
509
510    /*@ end vars *************************************************** */
511
512    if (o[0] == '\0') {
513        return;
514    }
515    strcpy(output, o);
516    i = (int) strlen(output);
517    if (i <= 0) {
518        return;
519    }
520    if (output[i - 1] < 32) {
521        output[i - 1] = '\0';
522    }
523    if (g_text_mode
524        /* && !strstr(last_line_of_file(MONDO_LOGFILE),output) */ ) {
525        printf("%s\n", output);
526    }
527
528    fout = fopen(MONDO_TRACEFILE, "a");
529    if (fout) {
530        fprintf(fout, "%s\n", output);
531        paranoid_fclose(fout);
532    } else {
533        log_OS_error("Cannot write to tracefile");
534    }
535}
536
537
538
539
540
541/**
542 * Finish configuring the backup information structure. Call this function
543 * to set the parameters that depend on those that can be given on the command
544 * line.
545 *
546 * @param bkpinfo The backup information structure. Fields modified/used:
547 * - Used: @c bkpinfo->backup_data
548 * - Used: @c bkpinfo->backup_media_type
549 * - Used: @c bkpinfo->cdrw_speed
550 * - Used: @c bkpinfo->compression_level
551 * - Used: @c bkpinfo->include_paths
552 * - Used: @c bkpinfo->prefix
553 * - Used: @c bkpinfo->isodir
554 * - Used: @c bkpinfo->manual_cd_tray
555 * - Used: @c bkpinfo->make_cd_use_lilo
556 * - Used: @c bkpinfo->media_device
557 * - Used: @c bkpinfo->nfs_mount
558 * - Used: @c bkpinfo->nonbootable_backup
559 * - Used: @c bkpinfo->scratchdir
560 * - Used: @c bkpinfo->tmpdir
561 * - Used: @c bkpinfo->use_lzo
562 * - Modified: @c bkpinfo->call_before_iso
563 * - Modified: @c bkpinfo->call_make_iso
564 * - Modified: @c bkpinfo->optimal_set_size
565 * - Modified: @c bkpinfo->zip_exe
566 * - Modified: @c bkpinfo->zip_suffix
567 *
568 * @return number of errors, or 0 for success.
569 * @note Also creates directories that are specified in the @c bkpinfo structure but
570 * do not exist.
571 */
572int post_param_configuration()
573{
574    char *extra_cdrom_params;
575    char *mondo_mkisofs_sz;
576    char *command;
577    char *mtpt;
578    char *hostname, *ip_address;
579    int retval = 0;
580    long avm = 0;
581    char *colon;
582    char *cdr_exe;
583    char *tmp;
584    char call_before_iso_user[MAX_STR_LEN] = "\0";
585    int rdsiz_MB;
586    char *iso_dev;
587    char *iso_mnt;
588    char *iso_tmp;
589    char *iso_path;
590
591    assert(bkpinfo != NULL);
592    malloc_string(extra_cdrom_params);
593    malloc_string(mondo_mkisofs_sz);
594    malloc_string(command);
595    malloc_string(mtpt);
596    malloc_string(hostname);
597    malloc_string(ip_address);
598    malloc_string(cdr_exe);
599    malloc_string(tmp);
600    malloc_string(iso_dev);
601    malloc_string(iso_mnt);
602    malloc_string(iso_tmp);
603    malloc_string(iso_path);
604    bkpinfo->optimal_set_size =
605        (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type) ? 16 : 16) *
606        1024;
607
608    log_msg(1, "Foo");
609    if (bkpinfo->backup_media_type == tape) {
610        log_msg(1, "Bar");
611        sprintf(tmp, "mt -f %s status", bkpinfo->media_device);
612        log_msg(1, "tmp = '%s'", tmp);
613        if (run_program_and_log_output(tmp, 3)) {
614            fatal_error
615                ("Unable to open tape device. If you haven't specified it with -d, do so. If you already have, check your parameter. I think it's wrong.");
616        }
617    }
618    make_hole_for_dir(bkpinfo->scratchdir);
619    if (bkpinfo->backup_media_type == iso)
620        make_hole_for_dir(bkpinfo->isodir);
621
622    run_program_and_log_output("uname -a", 5);
623    run_program_and_log_output("cat /etc/*-release", 5);
624    run_program_and_log_output("cat /etc/*issue*", 5);
625    sprintf(g_tmpfs_mountpt, "%s/tmpfs", bkpinfo->tmpdir);
626    sprintf(command, "mkdir -p %s", g_tmpfs_mountpt);
627    paranoid_system(command);
628    rdsiz_MB = PPCFG_RAMDISK_SIZE + g_tape_buffer_size_MB;
629#ifdef __FreeBSD__
630    strcpy(tmp,
631           call_program_and_get_last_line_of_output
632           ("vmstat | tail -1 | tr -s ' ' | cut -d' ' -f6"));
633    avm += atol(tmp);
634    strcpy(tmp,
635           call_program_and_get_last_line_of_output
636           ("swapinfo | grep -v Device | tr -s ' ' | cut -d' ' -f4 | tr '\n' '+' | sed 's/+$//' | bc"));
637    avm += atol(tmp);
638    sprintf(command, "mdmfs -s %d%c md9 %s", rdsiz_MB, 'm',
639            g_tmpfs_mountpt);
640#else
641    strcpy(tmp,
642           call_program_and_get_last_line_of_output
643           ("free | grep ':' | tr -s ' ' '\t' | cut -f2 | head -n1"));
644    avm += atol(tmp);
645    sprintf(command, "mount /dev/shm -t tmpfs %s -o size=%d%c",
646            g_tmpfs_mountpt, rdsiz_MB, 'm');
647    run_program_and_log_output("cat /proc/cpuinfo", 5);
648    run_program_and_log_output
649        ("rpm -q newt newt-devel slang slang-devel ncurses ncurses-devel gcc",
650         5);
651#endif
652    if (avm / 1024 > rdsiz_MB * 3) {
653        if (run_program_and_log_output(command, 5)) {
654            g_tmpfs_mountpt[0] = '\0';
655            log_it("Failed to mount tmpfs");
656        } else {
657            log_it("Tmpfs mounted OK - %d MB", rdsiz_MB);
658        }
659    } else {
660        g_tmpfs_mountpt[0] = '\0';
661        log_it("It doesn't seem you have enough swap to use tmpfs. Fine.");
662    }
663
664    if (bkpinfo->use_lzo) {
665        strcpy(bkpinfo->zip_exe, "lzop");
666        strcpy(bkpinfo->zip_suffix, "lzo");
667    } else if (bkpinfo->use_gzip) {
668        strcpy(bkpinfo->zip_exe, "gzip");
669        strcpy(bkpinfo->zip_suffix, "gz");
670    } else if (bkpinfo->compression_level != 0) {
671        strcpy(bkpinfo->zip_exe, "bzip2");
672        strcpy(bkpinfo->zip_suffix, "bz2");
673    } else {
674        bkpinfo->zip_exe[0] = bkpinfo->zip_suffix[0] = '\0';
675    }
676
677// DVD
678
679    if (bkpinfo->backup_media_type == dvd) {
680        extra_cdrom_params[0] = '\0';
681        mondo_mkisofs_sz[0] = '\0';
682        if (find_home_of_exe("growisofs")) {
683            strcpy(cdr_exe, "growisofs");
684        }                       // unlikely to be used
685        else {
686            fatal_error("Please install growisofs.");
687        }
688        if (bkpinfo->nonbootable_backup) {
689            strcat(mondo_mkisofs_sz, MONDO_GROWISOFS_NONBOOT);
690        } else if
691#ifdef __FreeBSD__
692            (TRUE)
693#else
694            (bkpinfo->make_cd_use_lilo)
695#endif
696#ifdef __IA64__
697    {
698        strcat(mondo_mkisofs_sz, MONDO_GROWISOFS_REGULAR_ELILO);
699    }
700#else
701    {
702        strcat(mondo_mkisofs_sz, MONDO_GROWISOFS_REGULAR_LILO);
703    }
704#endif
705        else
706        {
707            strcat(mondo_mkisofs_sz, MONDO_GROWISOFS_REGULAR_SYSLINUX);
708        }
709        if (bkpinfo->manual_cd_tray) {
710            fatal_error("Manual CD tray + DVD not supported yet.");
711            // -m isn't supported by growisofs, BTW...
712        } else {
713            sprintf(bkpinfo->call_make_iso,
714                    "%s %s -Z %s . 2>> _ERR_",
715                    mondo_mkisofs_sz,
716                    extra_cdrom_params, bkpinfo->media_device);
717        }
718        if (getenv ("SUDO_COMMAND")) {
719            sprintf(command, "strings `which growisofs` | grep -c SUDO_COMMAND");
720            if (!strcmp(call_program_and_get_last_line_of_output(command), "1")) {
721                popup_and_OK("Fatal Error: Can't write DVDs as sudo because growisofs doesn't support this - see the growisofs manpage for details.");
722                fatal_error("Can't write DVDs as sudo because growisofs doesn't support this - see the growisofs manpage for details.");
723            }       
724        }
725        log_msg(2, "call_make_iso (DVD res) is ... %s",
726                bkpinfo->call_make_iso);
727    }                           // end of DVD code
728
729// CD-R or CD-RW
730    if (bkpinfo->backup_media_type == cdrw
731        || bkpinfo->backup_media_type == cdr) {
732        extra_cdrom_params[0] = '\0';
733        if (!bkpinfo->manual_cd_tray) {
734            strcat(extra_cdrom_params, "-waiti ");
735        }
736        if (bkpinfo->backup_media_type == cdrw) {
737            strcat(extra_cdrom_params, "blank=fast ");
738        }
739        if (find_home_of_exe("cdrecord")) {
740            strcpy(cdr_exe, "cdrecord");
741        } else if (find_home_of_exe("dvdrecord")) {
742            strcpy(cdr_exe, "dvdrecord");
743        } else {
744            fatal_error("Please install either cdrecord or dvdrecord.");
745        }
746        if (bkpinfo->nonbootable_backup) {
747            strcpy(mondo_mkisofs_sz, MONDO_MKISOFS_NONBOOT);
748        } else if
749#ifdef __FreeBSD__
750            (TRUE)
751#else
752            (bkpinfo->make_cd_use_lilo)
753#endif
754#ifdef __IA64__
755    {
756        strcat(mondo_mkisofs_sz, MONDO_MKISOFS_REGULAR_ELILO);
757    }
758#else
759    {
760        strcpy(mondo_mkisofs_sz, MONDO_MKISOFS_REGULAR_LILO);
761    }
762#endif
763        else
764        {
765            strcpy(mondo_mkisofs_sz, MONDO_MKISOFS_REGULAR_SYSLINUX);
766        }
767        if (bkpinfo->manual_cd_tray) {
768            if (bkpinfo->call_before_iso[0] == '\0') {
769            sprintf(bkpinfo->call_before_iso,
770                        "%s -o %s/temporary.iso . 2>> _ERR_",
771                        mondo_mkisofs_sz, bkpinfo->tmpdir);
772                } else {
773                strncpy(call_before_iso_user, bkpinfo->call_before_iso, MAX_STR_LEN);
774                sprintf (bkpinfo->call_before_iso,
775                                    "( %s -o %s/temporary.iso . 2>> _ERR_ ; %s )",
776                        mondo_mkisofs_sz, bkpinfo->tmpdir, call_before_iso_user);
777            }
778            log_it("bkpinfo->call_before_iso = %s", bkpinfo->call_before_iso);
779            sprintf(bkpinfo->call_make_iso,
780                    "%s %s -v %s fs=4m dev=%s speed=%d %s/temporary.iso",
781                    cdr_exe, (bkpinfo->please_dont_eject) ? " " : "-eject",
782                    extra_cdrom_params, bkpinfo->media_device,
783                    bkpinfo->cdrw_speed, bkpinfo->tmpdir);
784        } else {
785            sprintf(bkpinfo->call_make_iso,
786                    "%s . 2>> _ERR_ | %s %s %s fs=4m dev=%s speed=%d -",
787                    mondo_mkisofs_sz, cdr_exe,
788                    (bkpinfo->please_dont_eject) ? " " : "-eject",
789                    extra_cdrom_params, bkpinfo->media_device,
790                    bkpinfo->cdrw_speed);
791        }
792    }                           // end of CD code
793
794    /*
795       if (bkpinfo->backup_data && bkpinfo->backup_media_type == tape)
796       {
797       sprintf (tmp,
798       "dd if=/dev/zero of=%s bs=%ld count=32 2> /dev/null",
799       bkpinfo->media_device, bkpinfo->internal_tape_block_size);
800       if (system(tmp))
801       {
802       retval++;
803       fprintf (stderr,
804       "Cannot write to tape device. Is the tape set read-only?\n");
805       }
806       } // end of tape code
807     */
808
809
810    if (bkpinfo->backup_media_type == iso) {
811
812/* Patch by Conor Daly <conor.daly@met.ie>
813 * 23-june-2004
814 * Break up isodir into iso_mnt and iso_path
815 * These will be used along with iso-dev at restore time
816 * to locate the ISOs where ever they're mounted
817 */
818
819        log_it("isodir = %s", bkpinfo->isodir);
820        sprintf(command, "df -P %s | tail -n1 | cut -d' ' -f1",
821                bkpinfo->isodir);
822        log_it("command = %s", command);
823        log_it("res of it = %s",
824               call_program_and_get_last_line_of_output(command));
825        sprintf(iso_dev, "%s",
826                call_program_and_get_last_line_of_output(command));
827        sprintf(tmp, "%s/ISO-DEV", bkpinfo->tmpdir);
828        write_one_liner_data_file(tmp,
829                                  call_program_and_get_last_line_of_output
830                                  (command));
831
832        sprintf(command, "mount | grep -w %s | tail -n1 | cut -d' ' -f3",
833                iso_dev);
834        log_it("command = %s", command);
835        log_it("res of it = %s",
836               call_program_and_get_last_line_of_output(command));
837        sprintf(iso_mnt, "%s",
838                call_program_and_get_last_line_of_output(command));
839        sprintf(tmp, "%s/ISO-MNT", bkpinfo->tmpdir);
840        write_one_liner_data_file(tmp,
841                                  call_program_and_get_last_line_of_output
842                                  (command));
843        log_it("isomnt: %s, %d", iso_mnt, strlen(iso_mnt));
844        sprintf(iso_tmp, "%s", bkpinfo->isodir);
845        if (strlen(iso_tmp) < strlen(iso_mnt)) {
846            iso_path[0] = '\0';
847        } else {
848            sprintf(iso_path, "%s", iso_tmp + strlen(iso_mnt));
849        }
850        sprintf(tmp, "%s/ISODIR", bkpinfo->tmpdir);
851        write_one_liner_data_file(tmp, iso_path);
852        log_it("isodir: %s", iso_path);
853        sprintf(tmp, "%s/ISO-PREFIX", bkpinfo->tmpdir);
854        write_one_liner_data_file(tmp, bkpinfo->prefix);
855        log_it("iso-prefix: %s",  bkpinfo->prefix);
856
857/* End patch */
858    }                           // end of iso code
859
860    if (bkpinfo->backup_media_type == nfs) {
861        strcpy(hostname, bkpinfo->nfs_mount);
862        colon = strchr(hostname, ':');
863        if (!colon) {
864            log_it("nfs mount doesn't have a colon in it");
865            retval++;
866        } else {
867            struct hostent *hent;
868
869            *colon = '\0';
870            hent = gethostbyname(hostname);
871            if (!hent) {
872                log_it("Can't resolve NFS mount (%s): %s", hostname,
873                       hstrerror(h_errno));
874                retval++;
875            } else {
876                strcpy(ip_address, inet_ntoa
877                       ((struct in_addr)
878                        *((struct in_addr *) hent->h_addr)));
879                strcat(ip_address, strchr(bkpinfo->nfs_mount, ':'));
880                strcpy(bkpinfo->nfs_mount, ip_address);
881            }
882        }
883        store_nfs_config();
884    }
885
886    log_it("Finished processing incoming params");
887    if (retval) {
888        fprintf(stderr, "Type 'man mondoarchive' for help.\n");
889    }
890    sprintf(tmp, "%s", MONDO_TMPISOS);  /* added #define 22 apr 2002 */
891    if (does_file_exist(tmp)) {
892        unlink(tmp);
893    }
894    if (strlen(bkpinfo->tmpdir) < 2 || strlen(bkpinfo->scratchdir) < 2) {
895        log_it("tmpdir or scratchdir are blank/missing");
896        retval++;
897    }
898    if (bkpinfo->include_paths[0] == '\0') {
899        //      fatal_error ("Why no backup path?");
900        strcpy(bkpinfo->include_paths, "/");
901    }
902    chmod(bkpinfo->scratchdir, 0700);
903    g_backup_media_type = bkpinfo->backup_media_type;
904    paranoid_free(mtpt);
905    paranoid_free(extra_cdrom_params);
906    paranoid_free(mondo_mkisofs_sz);
907    paranoid_free(command);
908    paranoid_free(hostname);
909    paranoid_free(ip_address);
910    paranoid_free(cdr_exe);
911    paranoid_free(tmp);
912    paranoid_free(iso_dev);
913    paranoid_free(iso_mnt);
914    paranoid_free(iso_tmp);
915    paranoid_free(iso_path);
916    return (retval);
917}
918
919
920
921/**
922 * Do some miscellaneous setup tasks to be performed before filling @c bkpinfo.
923 * Seeds the random-number generator, loads important modules, checks the sanity
924 * of the user's Linux distribution, and deletes logfile.
925 * @param bkpinfo The backup information structure. Will be initialized.
926 * @return number of errors (0 for success)
927 */
928int pre_param_configuration()
929{
930    int res = 0;
931    char *tmp = NULL;
932
933    make_hole_for_dir(MNT_CDROM);
934    assert(bkpinfo != NULL);
935    srandom((unsigned long) (time(NULL)));
936    insmod_crucial_modules();
937    if (bkpinfo->disaster_recovery) {
938        if (!does_nonMS_partition_exist()) {
939            fatal_error
940                ("I am in disaster recovery mode\nPlease don't run mondoarchive.");
941        }
942    }
943
944    unlink(MONDO_TRACEFILE);
945    asprintf(&tmp,"rm -Rf %s/changed.files*",MINDI_CACHE);
946    run_program_and_log_output(tmp, FALSE);
947    paranoid_free(tmp);
948    if (find_and_store_mondoarchives_home(g_mondo_home)) {
949        fprintf(stderr,
950                "Cannot find Mondo's homedir. I think you have >1 'mondo' directory on your hard disk. Please delete the superfluous 'mondo' directories and try again\n");
951        res++;
952        return (res);
953    }
954    res += some_basic_system_sanity_checks();
955    if (res) {
956        log_it("Your distribution did not pass Mondo's sanity test.");
957    }
958    g_current_media_number = 1;
959    bkpinfo->postnuke_tarball[0] = bkpinfo->nfs_mount[0] = '\0';
960    return (res);
961}
962
963void setup_tmpdir(char *path) {
964   
965    char *tmp = NULL;
966    char *p = NULL;
967
968    if (bkpinfo->tmpdir != NULL) {
969        /* purging a potential old tmpdir */
970        asprintf(&tmp,"rm -Rf %s",bkpinfo->tmpdir);
971        run_program_and_log_output(tmp, FALSE);
972        paranoid_free(tmp);
973    }
974       
975    if (getenv("TMPDIR")) {
976        asprintf(&tmp, "%s/mondo.tmp.XXXXXX", getenv("TMPDIR"));
977    } else if (getenv("TMP")) {
978        asprintf(&tmp, "%s/mondo.tmp.XXXXXX", getenv("TMP"));
979    } else if (path != NULL) {
980        asprintf(&tmp, "%s/mondo.tmp.XXXXXX", path);
981    } else {
982        asprintf(&tmp, "/tmp/mondo.tmp.XXXXXX");
983    }
984    p = mkdtemp(tmp);
985    if (p == NULL) {
986        log_it("Failed to create global tmp directory %s for Mondo.",tmp);
987        finish(-1);
988    }
989    strcpy(bkpinfo->tmpdir,p);
990    paranoid_free(tmp);
991    //sprintf(bkpinfo->tmpdir, "%s/tmpfs/mondo.tmp.%d", "/tmp", (int) (random() % 32768));  // for mondorestore
992}
993
994
995/**
996 * Reset all fields of the backup information structure to a sensible default.
997 * @param bkpinfo The @c bkpinfo to reset.
998 */
999void reset_bkpinfo()
1000{
1001    int i;
1002
1003    log_msg(1, "Hi");
1004    assert(bkpinfo != NULL);
1005    memset((void *) bkpinfo, 0, sizeof(struct s_bkpinfo));
1006
1007    /* special case for tmpdir as used eveywhere after */
1008    setup_tmpdir(NULL);
1009
1010    bkpinfo->manual_cd_tray = FALSE;
1011    bkpinfo->internal_tape_block_size = DEFAULT_INTERNAL_TAPE_BLOCK_SIZE;
1012    bkpinfo->media_device[0] = '\0';
1013    for (i = 0; i <= MAX_NOOF_MEDIA; i++) {
1014        bkpinfo->media_size[i] = -1;
1015    }
1016    bkpinfo->boot_loader = '\0';
1017    bkpinfo->boot_device[0] = '\0';
1018    bkpinfo->zip_exe[0] = '\0';
1019    bkpinfo->zip_suffix[0] = '\0';
1020    bkpinfo->restore_path[0] = '\0';
1021    bkpinfo->use_lzo = FALSE;
1022    bkpinfo->use_gzip = FALSE;
1023    bkpinfo->do_not_compress_these[0] = '\0';
1024    bkpinfo->verify_data = FALSE;
1025    bkpinfo->backup_data = FALSE;
1026    bkpinfo->restore_data = FALSE;
1027    bkpinfo->disaster_recovery =
1028        (am_I_in_disaster_recovery_mode()? TRUE : FALSE);
1029    if (bkpinfo->disaster_recovery) {
1030        strcpy(bkpinfo->isodir, "/");
1031    } else {
1032        strcpy(bkpinfo->isodir, "/root/images/mondo");
1033    }
1034    strcpy(bkpinfo->prefix, STD_PREFIX);
1035
1036    bkpinfo->scratchdir[0] = '\0';
1037    bkpinfo->make_filelist = TRUE;  // unless -J supplied to mondoarchive
1038    bkpinfo->optimal_set_size = 0;
1039    bkpinfo->backup_media_type = none;
1040    strcpy(bkpinfo->include_paths, "/");
1041    bkpinfo->exclude_paths[0] = '\0';
1042    bkpinfo->call_before_iso[0] = '\0';
1043    bkpinfo->call_make_iso[0] = '\0';
1044    bkpinfo->call_burn_iso[0] = '\0';
1045    bkpinfo->call_after_iso[0] = '\0';
1046    bkpinfo->image_devs[0] = '\0';
1047    bkpinfo->postnuke_tarball[0] = '\0';
1048    bkpinfo->kernel_path[0] = '\0';
1049    bkpinfo->nfs_mount[0] = '\0';
1050    bkpinfo->nfs_remote_dir[0] = '\0';
1051    bkpinfo->wipe_media_first = FALSE;
1052    bkpinfo->differential = FALSE;
1053    bkpinfo->cdrw_speed = 0;
1054// patch by Herman Kuster 
1055    bkpinfo->differential = 0;
1056// patch end
1057    bkpinfo->compression_level = 3;
1058}
1059
1060
1061
1062
1063/**
1064 * Get the remaining free space (in MB) on @p partition.
1065 * @param partition The partition to check free space on (either a device or a mountpoint).
1066 * @return The free space on @p partition, in MB.
1067 */
1068long free_space_on_given_partition(char *partition)
1069{
1070    char command[MAX_STR_LEN], out_sz[MAX_STR_LEN];
1071    long res;
1072
1073    assert_string_is_neither_NULL_nor_zerolength(partition);
1074
1075    sprintf(command, "df -m -P %s &> /dev/null", partition);
1076    if (system(command)) {
1077        return (-1);
1078    }                           // partition does not exist
1079    sprintf(command, "df -m -P %s | tail -n1 | tr -s ' ' '\t' | cut -f4",
1080            partition);
1081    strcpy(out_sz, call_program_and_get_last_line_of_output(command));
1082    if (strlen(out_sz) == 0) {
1083        return (-1);
1084    }                           // error within df, probably
1085    res = atol(out_sz);
1086    return (res);
1087}
1088
1089
1090
1091/**
1092 * Check the user's system for sanity. Checks performed:
1093 * - make sure user has enough RAM (32mb required, 64mb recommended)
1094 * - make sure user has enough free space in @c /
1095 * - check kernel for ramdisk support
1096 * - make sure afio, cdrecord, mkisofs, bzip2, awk, md5sum, strings, mindi, and buffer exist
1097 * - make sure CD-ROM is unmounted
1098 * - make sure /etc/modules.conf exists
1099 * - make sure user's mountlist is OK by running <tt>mindi --makemountlist</tt>
1100 *
1101 * @return number of problems with the user's setup (0 for success)
1102 */
1103int some_basic_system_sanity_checks()
1104{
1105
1106    /*@ buffers ************ */
1107    char tmp[MAX_STR_LEN];
1108    //  char command[MAX_STR_LEN];
1109
1110    /*@ int's *************** */
1111    int retval = 0;
1112    long Lres;
1113
1114
1115    mvaddstr_and_log_it(g_currentY, 0,
1116                        "Checking sanity of your Linux distribution");
1117#ifndef __FreeBSD__
1118    if (system("which mkfs.vfat &> /dev/null")
1119        && !system("which mkfs.msdos &> /dev/null")) {
1120        log_it
1121            ("OK, you've got mkfs.msdos but not mkfs.vfat; time for the fairy to wave her magic wand...");
1122        run_program_and_log_output
1123            ("ln -sf `which mkfs.msdos` /sbin/mkfs.vfat", FALSE);
1124    }
1125    strcpy(tmp,
1126           call_program_and_get_last_line_of_output
1127           ("free | grep Mem | head -n1 | tr -s ' ' '\t' | cut -f2"));
1128    if (atol(tmp) < 35000) {
1129        retval++;
1130        log_to_screen("You must have at least 32MB of RAM to use Mondo.");
1131    }
1132    if (atol(tmp) < 66000) {
1133        log_to_screen
1134            ("WARNING! You have very little RAM. Please upgrade to 64MB or more.");
1135    }
1136#endif
1137
1138    Lres = free_space_on_given_partition(MINDI_CACHE);
1139    log_it("Free space on partition of %s = %ld MB", MINDI_CACHE, Lres);
1140
1141    if (Lres < 50) {
1142        sprintf(tmp, "The partition of %s has <50MB free. Please free up space or enlarge the partition or make %s a symbolic link.", MINDI_CACHE, MINDI_CACHE); 
1143        fatal_error(tmp);
1144    }
1145
1146    if (system("which " MKE2FS_OR_NEWFS " > /dev/null 2> /dev/null")) {
1147        retval++;
1148        log_to_screen
1149            ("Unable to find " MKE2FS_OR_NEWFS " in system path.");
1150        fatal_error
1151            ("Please use \"su -\", not \"su\" to become root. OK? ...and please don't e-mail the mailing list or me about this. Just read the message. :)");
1152    }
1153#ifndef __FreeBSD__
1154    if (run_program_and_log_output
1155        ("grep ramdisk /proc/devices", FALSE)) {
1156        if (!ask_me_yes_or_no
1157            ("Your kernel has no ramdisk support. That's mind-numbingly stupid but I'll allow it if you're planning to use a failsafe kernel. Are you?"))
1158        {
1159            //          retval++;
1160            log_to_screen
1161                ("It looks as if your kernel lacks ramdisk and initrd support.");
1162            log_to_screen
1163                ("I'll allow you to proceed but FYI, if I'm right, your kernel is broken.");
1164        }
1165    }
1166#endif
1167    retval += whine_if_not_found(MKE2FS_OR_NEWFS);
1168    retval += whine_if_not_found("mkisofs");
1169    if (system("which dvdrecord > /dev/null 2> /dev/null")) {
1170        retval += whine_if_not_found("cdrecord");
1171    }
1172    retval += whine_if_not_found("bzip2");
1173    retval += whine_if_not_found("gzip");
1174    retval += whine_if_not_found("awk");
1175    retval += whine_if_not_found("md5sum");
1176    retval += whine_if_not_found("strings");
1177    retval += whine_if_not_found("mindi");
1178    retval += whine_if_not_found("buffer");
1179
1180    // abort if Windows partition but no ms-sys and parted
1181    if (!run_program_and_log_output
1182        ("mount | grep -w vfat | grep -vE \"/dev/fd|nexdisk\"", 0)
1183        ||
1184        !run_program_and_log_output
1185        ("mount | grep -w dos | grep -vE \"/dev/fd|nexdisk\"", 0)) {
1186        log_to_screen("I think you have a Windows 9x partition.");
1187        retval += whine_if_not_found("parted");
1188#ifndef __IA64__
1189        /* IA64 always has one vfat partition for EFI even without Windows */
1190        // retval +=
1191        if (!find_home_of_exe("ms-sys")) {
1192            log_to_screen("Please install ms-sys just in case.");
1193        }
1194#endif
1195    }
1196
1197    if (!find_home_of_exe("cmp")) {
1198        if (!find_home_of_exe("true")) {
1199            whine_if_not_found("cmp");
1200        } else {
1201            log_to_screen
1202                ("Your system lacks the 'cmp' binary. I'll create a dummy cmp for you.");
1203            if (run_program_and_log_output
1204                ("cp -f `which true` /usr/bin/cmp", 0)) {
1205                fatal_error("Failed to create dummy 'cmp' file.");
1206            }
1207        }
1208    }
1209    run_program_and_log_output
1210        ("umount `mount | grep cdr | cut -d' ' -f3 | tr '\n' ' '`", 5);
1211    strcpy(tmp,
1212           call_program_and_get_last_line_of_output
1213           ("mount | grep -E \"cdr(om|w)\""));
1214    if (strcmp("", tmp)) {
1215        if (strstr(tmp, "autofs")) {
1216            log_to_screen
1217                ("Your CD-ROM is mounted via autofs. I therefore cannot tell");
1218            log_to_screen
1219                ("if a CD actually is inserted. If a CD is inserted, please");
1220            log_to_screen("eject it. Thank you.");
1221            log_it
1222                ("Ignoring autofs CD-ROM 'mount' since we hope nothing's in it.");
1223        } else
1224            if (run_program_and_log_output("uname -a | grep Knoppix", 5)) {
1225            retval++;
1226            fatal_error
1227                ("Your CD-ROM drive is mounted. Please unmount it.");
1228        }
1229    }
1230#ifndef __FreeBSD__
1231    if (!does_file_exist("/etc/modules.conf")) {
1232        if (does_file_exist("/etc/conf.modules")) {
1233            log_it("Linking /etc/modules.conf to /etc/conf.modules");
1234            run_program_and_log_output
1235                ("ln -sf /etc/conf.modules /etc/modules.conf", 5);
1236        } else if (does_file_exist("/etc/modprobe.d")) {
1237            log_it
1238                ("Directory /etc/modprobe.d found. mindi will use its contents.");
1239        } else if (does_file_exist("/etc/modprobe.conf")) {
1240            log_it("Linking /etc/modules.conf to /etc/modprobe.conf");
1241            run_program_and_log_output
1242                ("ln -sf /etc/modprobe.conf /etc/modules.conf", 5);
1243        } else {
1244            retval++;
1245            log_to_screen
1246                ("Please find out what happened to /etc/modules.conf");
1247        }
1248    }
1249#endif
1250
1251    run_program_and_log_output("cat /etc/fstab", 5);
1252#ifdef __FreeBSD__
1253    run_program_and_log_output("vinum printconfig", 5);
1254#else
1255    run_program_and_log_output("cat /etc/raidtab", 5);
1256#endif
1257
1258    if (run_program_and_log_output("mindi -V", 1)) {
1259        log_to_screen("Could not ascertain mindi's version number.");
1260        log_to_screen
1261            ("You have not installed Mondo and/or Mindi properly.");
1262        log_to_screen("Please uninstall and reinstall them both.");
1263        fatal_error("Please reinstall Mondo and Mindi.");
1264    }
1265    sprintf(tmp, "mindi --makemountlist %s/mountlist.txt.test", bkpinfo->tmpdir);
1266    if (run_program_and_log_output(tmp, 5)) {
1267        sprintf(tmp, "mindi --makemountlist %s/mountlist.txt.test failed for some reason.", bkpinfo->tmpdir);
1268        log_to_screen(tmp);
1269        log_to_screen
1270            ("Please run that command by hand and examine /var/log/mindi.log");
1271        log_to_screen
1272            ("for more information. Perhaps your /etc/fstab file is insane.");
1273        log_to_screen
1274            ("Perhaps Mindi's MakeMountlist() subroutine has a bug. We'll see.");
1275        retval++;
1276    }
1277
1278    if (!run_program_and_log_output("parted2fdisk -l | grep -i raid", 1)
1279        && !does_file_exist("/etc/raidtab")) {
1280        log_to_screen
1281            ("You have RAID partitions but no /etc/raidtab - creating one from /proc/mdstat");
1282        create_raidtab_from_mdstat("/etc/raidtab");
1283    }
1284
1285    if (retval) {
1286        mvaddstr_and_log_it(g_currentY++, 74, "Failed.");
1287    } else {
1288        mvaddstr_and_log_it(g_currentY++, 74, "Done.");
1289    }
1290    return (retval);
1291}
1292
1293/**
1294 * Retrieve the line containing @p label from the config file.
1295 * @param config_file The file to read from, usually @c /tmp/mondo-restore.cfg.
1296 * @param label What to read from the file.
1297 * @param value Where to put it.
1298 * @return 0 for success, 1 for failure.
1299 */
1300int read_cfg_var(char *config_file, char *label, char *value)
1301{
1302    /*@ buffer ****************************************************** */
1303    char command[MAX_STR_LEN * 2];
1304    char tmp[MAX_STR_LEN];
1305
1306    /*@ end vars *************************************************** */
1307
1308    assert_string_is_neither_NULL_nor_zerolength(config_file);
1309    assert_string_is_neither_NULL_nor_zerolength(label);
1310    if (!does_file_exist(config_file)) {
1311        sprintf(tmp, "(read_cfg_var) Cannot find %s config file",
1312                config_file);
1313        log_to_screen(tmp);
1314        value[0] = '\0';
1315        return (1);
1316    } else if ((value != NULL) && (strstr(value, "/dev/") && strstr(value, "t0") && !strcmp(label, "media-dev"))) {
1317        log_msg(2, "FYI, I can't read new value for %s - already got %s", label, value);
1318        return (0);
1319    } else {
1320        sprintf(command, "grep '%s .*' %s| cut -d' ' -f2,3,4,5",
1321                label, config_file);
1322        strcpy(value, call_program_and_get_last_line_of_output(command));
1323        if (strlen(value) == 0) {
1324            return (1);
1325        } else {
1326            return (0);
1327        }
1328    }
1329}
1330
1331
1332
1333/**
1334 * Remount @c supermount if it was unmounted earlier.
1335 */
1336void remount_supermounts_if_necessary()
1337{
1338    if (g_remount_cdrom_at_end) {
1339        run_program_and_log_output("mount " MNT_CDROM, FALSE);
1340    }
1341    if (g_remount_floppy_at_end) {
1342        run_program_and_log_output("mount " MNT_FLOPPY, FALSE);
1343    }
1344}
1345
1346/**
1347 * Unmount @c supermount if it's mounted.
1348 */
1349void unmount_supermounts_if_necessary()
1350{
1351    if (run_program_and_log_output
1352        ("mount | grep cdrom | grep super", FALSE) == 0) {
1353        g_remount_cdrom_at_end = TRUE;
1354        run_program_and_log_output("umount " MNT_CDROM, FALSE);
1355    }
1356    if (run_program_and_log_output
1357        ("mount | grep floppy | grep super", FALSE) == 0) {
1358        g_remount_floppy_at_end = TRUE;
1359        run_program_and_log_output("umount " MNT_FLOPPY, FALSE);
1360    }
1361}
1362
1363/**
1364 * Whether we had to stop autofs (if so, restart it at end).
1365 */
1366bool g_autofs_stopped = FALSE;
1367
1368/**
1369 * Path to the autofs initscript ("" if none exists).
1370 */
1371char g_autofs_exe[MAX_STR_LEN];
1372
1373/**
1374 * Autofs initscript in Xandros Linux distribution.
1375 */
1376#define XANDROS_AUTOFS_FNAME "/etc/init.d/xandros-autofs"
1377
1378/**
1379 * Autofs initscript in most Linux distributions.
1380 */
1381#define STOCK_AUTOFS_FNAME "/etc/rc.d/init.d/autofs"
1382
1383/**
1384 * If autofs is mounted, stop it (restart at end).
1385 */
1386void stop_autofs_if_necessary()
1387{
1388    char tmp[MAX_STR_LEN];
1389
1390    g_autofs_exe[0] = '\0';
1391    if (does_file_exist(XANDROS_AUTOFS_FNAME)) {
1392        strcpy(g_autofs_exe, XANDROS_AUTOFS_FNAME);
1393    } else if (does_file_exist(STOCK_AUTOFS_FNAME)) {
1394        strcpy(g_autofs_exe, STOCK_AUTOFS_FNAME);
1395    }
1396
1397    if (!g_autofs_exe[0]) {
1398        log_msg(3, "No autofs detected.");
1399    } else {
1400        log_msg(3, "%s --- autofs detected", g_autofs_exe);
1401// FIXME -- only disable it if it's running ---  sprintf(tmp, "%s status", autofs_exe);
1402        sprintf(tmp, "%s stop", g_autofs_exe);
1403        if (run_program_and_log_output(tmp, 2)) {
1404            log_it("Failed to stop autofs - I assume it wasn't running");
1405        } else {
1406            g_autofs_stopped = TRUE;
1407            log_it("Stopped autofs OK");
1408        }
1409    }
1410}
1411
1412/**
1413 * If autofs was stopped earlier, restart it.
1414 */
1415void restart_autofs_if_necessary()
1416{
1417    char tmp[MAX_STR_LEN];
1418
1419    if (!g_autofs_stopped || !g_autofs_exe[0]) {
1420        log_msg(3, "No autofs detected.");
1421        return;
1422    }
1423    sprintf(tmp, "%s start", g_autofs_exe);
1424    if (run_program_and_log_output(tmp, 2)) {
1425        log_it("Failed to start autofs");
1426    } else {
1427        g_autofs_stopped = FALSE;
1428        log_it("Started autofs OK");
1429    }
1430}
1431
1432
1433/**
1434 * If this is a distribution like Gentoo that doesn't keep /boot mounted, mount it.
1435 */
1436void mount_boot_if_necessary()
1437{
1438    char tmp[MAX_STR_LEN];
1439    char command[MAX_STR_LEN];
1440
1441    log_msg(1, "Started sub");
1442    log_msg(4, "About to set g_boot_mountpt[0] to '\\0'");
1443    g_boot_mountpt[0] = '\0';
1444    log_msg(4, "Done. Great. Seeting command to something");
1445    strcpy(command,
1446           "grep -v \":\" /etc/fstab | grep -vE '^#.*$' | grep -E \"[   ]/boot[     ]\" | tr -s ' ' '\t' | cut -f1 | head -n1");
1447    log_msg(4, "Cool. Command = '%s'", command);
1448    strcpy(tmp, call_program_and_get_last_line_of_output(command));
1449    log_msg(4, "tmp = '%s'", tmp);
1450    if (tmp[0]) {
1451        log_it("/boot is at %s according to /etc/fstab", tmp);
1452        if ((strstr(tmp, "LABEL=") || strstr(tmp,"UUID="))) {
1453            if (!run_program_and_log_output("mount /boot", 5)) {
1454                strcpy(g_boot_mountpt, "/boot");
1455                log_msg(1, "Mounted /boot");
1456            } else {
1457                log_it("...ignored cos it's a label or uuid :-)");
1458            }
1459        } else {
1460            sprintf(command, "mount | grep -E '^%s'", tmp);
1461            log_msg(3, "command = %s", command);
1462            if (run_program_and_log_output(command, 5)) {
1463                strcpy(g_boot_mountpt, tmp);
1464                sprintf(tmp,
1465                        "%s (your /boot partition) is not mounted. I'll mount it before backing up",
1466                        g_boot_mountpt);
1467                log_it(tmp);
1468                sprintf(tmp, "mount %s", g_boot_mountpt);
1469                if (run_program_and_log_output(tmp, 5)) {
1470                    g_boot_mountpt[0] = '\0';
1471                    log_msg(1, "Plan B");
1472                    if (!run_program_and_log_output("mount /boot", 5)) {
1473                        strcpy(g_boot_mountpt, "/boot");
1474                        log_msg(1, "Plan B worked");
1475                    } else {
1476                        log_msg(1,
1477                                "Plan B failed. Unable to mount /boot for backup purposes. This probably means /boot is mounted already, or doesn't have its own partition.");
1478                    }
1479                }
1480            }
1481        }
1482    }
1483    log_msg(1, "Ended sub");
1484}
1485
1486
1487/**
1488 * If we mounted /boot earlier, unmount it.
1489 */
1490void unmount_boot_if_necessary()
1491{
1492    char tmp[MAX_STR_LEN];
1493
1494    log_msg(3, "starting");
1495    if (g_boot_mountpt[0]) {
1496        sprintf(tmp, "umount %s", g_boot_mountpt);
1497        if (run_program_and_log_output(tmp, 5)) {
1498            log_it("WARNING - unable to unmount /boot");
1499        }
1500    }
1501    log_msg(3, "leaving");
1502}
1503
1504
1505
1506/**
1507 * Write a line to a configuration file. Writes a line of the form,
1508 * @c label @c value.
1509 * @param config_file The file to write to. Usually @c mondo-restore.cfg.
1510 * @param label What to call this bit of data you're writing.
1511 * @param value The bit of data you're writing.
1512 * @return 0 for success, 1 for failure.
1513 */
1514int write_cfg_var(char *config_file, char *label, char *value)
1515{
1516    /*@ buffers ***************************************************** */
1517    char command[MAX_STR_LEN * 2];
1518    char tempfile[MAX_STR_LEN];
1519    char tmp[MAX_STR_LEN];
1520
1521
1522    /*@ end vars *************************************************** */
1523    assert_string_is_neither_NULL_nor_zerolength(config_file);
1524    assert_string_is_neither_NULL_nor_zerolength(label);
1525    assert(value != NULL);
1526    if (!does_file_exist(config_file)) {
1527        sprintf(tmp, "(write_cfg_file) Cannot find %s config file",
1528                config_file);
1529        log_to_screen(tmp);
1530        return (1);
1531    }
1532    sprintf(tempfile, "%s/mojo-jojo.blah", bkpinfo->tmpdir);
1533    if (does_file_exist(config_file)) {
1534        sprintf(command, "grep -vE '^%s .*$' %s > %s",
1535                label, config_file, tempfile);
1536        paranoid_system(command);
1537    }
1538    sprintf(command, "echo \"%s %s\" >> %s", label, value, tempfile);
1539    paranoid_system(command);
1540    sprintf(command, "mv -f %s %s", tempfile, config_file);
1541    paranoid_system(command);
1542    unlink(tempfile);
1543    return (0);
1544}
1545
1546
1547/**
1548 * The standard log_debug_msg() (log_msg() also due to a macro). Writes some describing
1549 * information to the logfile.
1550 */
1551void standard_log_debug_msg(int debug_level, const char *szFile,
1552                            const char *szFunction, int nLine,
1553                            const char *fmt, ...)
1554{
1555    va_list args;
1556    int i;
1557    static int depth = 0;
1558    char *tmp;
1559    FILE *fout;
1560
1561    if (depth > 5) {
1562        depth--;
1563        return;
1564    }
1565    depth++;
1566
1567    malloc_string(tmp);
1568
1569    if (debug_level <= g_loglevel) {
1570        va_start(args, fmt);
1571        if (!(fout = fopen(MONDO_LOGFILE, "a"))) {
1572            return;
1573        }                       // fatal_error("Failed to openout to logfile - sheesh..."); }
1574
1575        // add tabs to distinguish log levels
1576        if (debug_level > 0) {
1577            for (i = 1; i < debug_level; i++)
1578                fprintf(fout, "\t");
1579            if (getpid() == g_main_pid)
1580                fprintf(fout, "[Main] %s->%s#%d: ", szFile, szFunction,
1581                        nLine);
1582            else if (getpid() == g_buffer_pid && g_buffer_pid > 0)
1583                fprintf(fout, "[Buff] %s->%s#%d: ", szFile, szFunction,
1584                        nLine);
1585            else
1586                fprintf(fout, "[TH=%d] %s->%s#%d: ", getpid(), szFile,
1587                        szFunction, nLine);
1588        }
1589        vfprintf(fout, fmt, args);
1590
1591        // do not slow down the progran if standard debug level
1592        // must be enabled: if no flush, the log won't be up-to-date if there
1593        // is a segfault
1594        //if (g_dwDebugLevel != 1)
1595
1596        va_end(args);
1597        fprintf(fout, "\n");
1598        paranoid_fclose(fout);
1599    }
1600    depth--;
1601    paranoid_free(tmp);
1602}
1603
1604/**
1605 * Function pointer to the @c log_debug_msg function to use. Points to standard_log_debug_msg() by default.
1606 */
1607void (*log_debug_msg) (int, const char *, const char *, int, const char *,
1608                       ...) = standard_log_debug_msg;
1609
1610
1611/**
1612 * If @p y, malloc @p x, else free @p x.
1613 * @bug This function seems orphaned. Please remove.
1614 */
1615#define do_alloc_or_free_depending(x,y) { if(y) {x=malloc(MAX_STR_LEN);} else {paranoid_free(x);} }
1616
1617/**
1618 * Allocate or free important globals, depending on @p mal.
1619 * @param mal If TRUE, malloc; if FALSE, free.
1620 */
1621void do_libmondo_global_strings_thing(int mal)
1622{
1623    if (mal) {
1624        iamhere("Malloc'ing globals");
1625        malloc_string(g_boot_mountpt);
1626        malloc_string(g_mondo_home);
1627        malloc_string(g_tmpfs_mountpt);
1628        malloc_string(g_erase_tmpdir_and_scratchdir);
1629        malloc_string(g_serial_string);
1630        malloc_string(g_magicdev_command);
1631    } else {
1632        iamhere("Freeing globals");
1633        paranoid_free(g_boot_mountpt);
1634        paranoid_free(g_mondo_home);
1635        paranoid_free(g_tmpfs_mountpt);
1636        paranoid_free(g_erase_tmpdir_and_scratchdir);
1637        paranoid_free(g_serial_string);
1638        paranoid_free(g_magicdev_command);
1639    }
1640
1641    /*
1642       char**list_of_arrays[] = {
1643       &g_boot_mountpt,
1644       &g_mondo_home,
1645       &g_tmpfs_mountpt,
1646       &g_erase_tmpdir_and_scratchdir,
1647       &g_serial_string,
1648       &g_magicdev_command,
1649       NULL};
1650
1651       char**ppcurr;
1652       int i;
1653
1654       for(i=0;list_of_arrays[i];i++)
1655       {
1656       log_msg(5, "Allocating %d", i);
1657       ppcurr = list_of_arrays[i];
1658       if (mal)
1659       { *ppcurr = malloc(MAX_STR_LEN); }
1660       else
1661       {
1662       if (*ppcurr)
1663       {
1664       free(*ppcurr);
1665       }
1666       }
1667       }
1668       log_msg(5, "Returning");
1669     */
1670}
1671
1672/**
1673 * Allocate important globals.
1674 * @see do_libmondo_global_strings_thing
1675 */
1676void malloc_libmondo_global_strings(void)
1677{
1678    do_libmondo_global_strings_thing(1);
1679}
1680
1681/**
1682 * Free important globals.
1683 * @see do_libmondo_global_strings_thing
1684 */
1685void free_libmondo_global_strings(void)
1686{
1687    do_libmondo_global_strings_thing(0);
1688}
1689
1690
1691
1692/**
1693 * Stop @c magicdev if it's running.
1694 * The command used to start it is saved in @p g_magicdev_command.
1695 */
1696void stop_magicdev_if_necessary()
1697{
1698    strcpy(g_magicdev_command,
1699           call_program_and_get_last_line_of_output
1700           ("ps ax | grep -w magicdev | grep -v grep | tr -s '\t' ' '| cut -d' ' -f6-99"));
1701    if (g_magicdev_command[0]) {
1702        log_msg(1, "g_magicdev_command = '%s'", g_magicdev_command);
1703        paranoid_system("killall magicdev");
1704    }
1705}
1706
1707
1708/**
1709 * Restart magicdev if it was stopped.
1710 */
1711void restart_magicdev_if_necessary()
1712{
1713    char *tmp;
1714
1715    malloc_string(tmp);
1716    if (g_magicdev_command && g_magicdev_command[0]) {
1717        sprintf(tmp, "%s &", g_magicdev_command);
1718        paranoid_system(tmp);
1719    }
1720    paranoid_free(tmp);
1721}
1722
1723/* @} - end of utilityGroup */
Note: See TracBrowser for help on using the repository browser.