source: MondoRescue/branches/2.2.9/mondo/src/common/libmondo-tools.c @ 2211

Last change on this file since 2211 was 2211, checked in by Bruno Cornec, 11 years ago

r3089@localhost: bruno | 2009-05-18 06:41:05 +0200

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