source: branches/stable/mondo/src/common/libmondo-tools.c @ 1116

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

Suppress lib-common-externs.h useless

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