source: trunk/mondo/mondo/common/libmondo-tools.c @ 59

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

Trunk: indent on all source files

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