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

Last change on this file since 149 was 149, checked in by bcornec, 15 years ago

merge -r144:148 $SVN_M/branches/2.05

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