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

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

x86_64 support (begining)
find_and_store_mondoarchives_home interface change
libmondo-tools.c modified with asprintf

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