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

Last change on this file since 2230 was 2230, checked in by bruno, 10 years ago
  • Simplify log_it calls when possible (with just a fixed string)
  • issue with truncate_to_drive_name reported by valgrind at restore time. Needs rewrite IMO
  • Property svn:keywords set to Id
File size: 39.6 KB
Line 
1/*
2   $Id: libmondo-tools.c 2230 2009-06-17 20:53:23Z 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 2230 2009-06-17 20:53:23Z 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_user = NULL;
860    bkpinfo->nfs_remote_dir[0] = '\0';
861    bkpinfo->postnuke_tarball[0] = '\0';
862    bkpinfo->wipe_media_first = FALSE;
863    bkpinfo->differential = 0;
864    bkpinfo->please_dont_eject = FALSE;
865    bkpinfo->cdrw_speed = 0;
866    bkpinfo->manual_cd_tray = FALSE;
867    bkpinfo->nonbootable_backup = FALSE;
868    bkpinfo->make_cd_use_lilo = FALSE;
869    bkpinfo->use_obdr = FALSE;
870    bkpinfo->restore_mode = interactive;
871}
872
873
874
875
876/**
877 * Get the remaining free space (in MB) on @p partition.
878 * @param partition The partition to check free space on (either a device or a mountpoint).
879 * @return The free space on @p partition, in MB.
880 */
881long free_space_on_given_partition(char *partition)
882{
883    char command[MAX_STR_LEN], out_sz[MAX_STR_LEN];
884    long res;
885
886    assert_string_is_neither_NULL_nor_zerolength(partition);
887
888    sprintf(command, "df -m -P %s 1> /dev/null 2> /dev/null", partition);
889    if (system(command)) {
890        return (-1);
891    }                           // partition does not exist
892    sprintf(command, "df -m -P %s | tail -n1 | tr -s ' ' '\t' | cut -f4",
893            partition);
894    strcpy(out_sz, call_program_and_get_last_line_of_output(command));
895    if (strlen(out_sz) == 0) {
896        return (-1);
897    }                           // error within df, probably
898    res = atol(out_sz);
899    return (res);
900}
901
902
903
904/**
905 * Check the user's system for sanity. Checks performed:
906 * - make sure user has enough RAM (32mb required, 64mb recommended)
907 * - make sure user has enough free space in @c /
908 * - check kernel for ramdisk support
909 * - make sure afio, cdrecord, mkisofs, bzip2, awk, md5sum, strings, mindi, and buffer exist
910 * - make sure CD-ROM is unmounted
911 * - make sure user's mountlist is OK by running <tt>mindi --makemountlist</tt>
912 *
913 * @return number of problems with the user's setup (0 for success)
914 */
915int some_basic_system_sanity_checks()
916{
917
918    /*@ buffers ************ */
919    char tmp[MAX_STR_LEN];
920    //  char command[MAX_STR_LEN];
921
922    /*@ int's *************** */
923    int retval = 0;
924
925    mvaddstr_and_log_it(g_currentY, 0,
926                        "Checking sanity of your Linux distribution");
927#ifndef __FreeBSD__
928    if (system("which mkfs.vfat 2> /dev/null 1> /dev/null")
929        && !system("which mkfs.msdos 2> /dev/null 1> /dev/null")) {
930        log_it
931            ("OK, you've got mkfs.msdos but not mkfs.vfat; time for the fairy to wave her magic wand...");
932        run_program_and_log_output
933            ("ln -sf `which mkfs.msdos` /sbin/mkfs.vfat", FALSE);
934    }
935    strcpy(tmp,
936           call_program_and_get_last_line_of_output
937           ("free | grep Mem | head -n1 | tr -s ' ' '\t' | cut -f2"));
938    if (atol(tmp) < 35000) {
939        retval++;
940        log_to_screen("You must have at least 32MB of RAM to use Mondo.");
941    }
942    if (atol(tmp) < 66000) {
943        log_to_screen
944            ("WARNING! You have very little RAM. Please upgrade to 64MB or more.");
945    }
946#endif
947
948    if (system("which " MKE2FS_OR_NEWFS " > /dev/null 2> /dev/null")) {
949        retval++;
950        log_to_screen
951            ("Unable to find " MKE2FS_OR_NEWFS " in system path.");
952        fatal_error
953            ("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. :)");
954    }
955#ifndef __FreeBSD__
956    if (run_program_and_log_output
957        ("grep ramdisk /proc/devices", FALSE)) {
958        /* Some SuSE have ramdisk as modules, so insert it first, then test again */
959        run_program_and_log_output("modprobe brd 2> /dev/null > /dev/null",FALSE);
960        if (run_program_and_log_output
961            ("grep ramdisk /proc/devices", FALSE)) {
962            if (!ask_me_yes_or_no
963                ("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?"))
964            {
965                //          retval++;
966                log_to_screen
967                    ("It looks as if your kernel lacks ramdisk and initrd support.");
968                log_to_screen
969                    ("I'll allow you to proceed but FYI, if I'm right, your kernel is broken.");
970            }
971        }
972    }
973#endif
974    retval += whine_if_not_found(MKE2FS_OR_NEWFS);
975    retval += whine_if_not_found("mkisofs");
976    if (system("which dvdrecord > /dev/null 2> /dev/null")) {
977        retval += whine_if_not_found("cdrecord");
978    }
979    retval += whine_if_not_found("bzip2");
980    retval += whine_if_not_found("gzip");
981    retval += whine_if_not_found("awk");
982    retval += whine_if_not_found("md5sum");
983    retval += whine_if_not_found("strings");
984    retval += whine_if_not_found("mindi");
985    retval += whine_if_not_found("buffer");
986
987    // abort if Windows partition but no ms-sys and parted
988    if (!run_program_and_log_output("mount | grep -Ew 'vfat|fat|dos' | grep -vE \"/dev/fd|nexdisk\"", 0)) {
989        log_to_screen("I think you have a Windows 9x partition.");
990        retval += whine_if_not_found("parted");
991    }
992
993    if (!find_home_of_exe("cmp")) {
994        if (!find_home_of_exe("true")) {
995            whine_if_not_found("cmp");
996        } else {
997            log_to_screen
998                ("Your system lacks the 'cmp' binary. I'll create a dummy cmp for you.");
999            if (run_program_and_log_output
1000                ("cp -f `which true` /usr/bin/cmp", 0)) {
1001                fatal_error("Failed to create dummy 'cmp' file.");
1002            }
1003        }
1004    }
1005    run_program_and_log_output
1006        ("umount `mount | grep cdr | cut -d' ' -f3 | tr '\n' ' '`", 5);
1007    strcpy(tmp,
1008           call_program_and_get_last_line_of_output
1009           ("mount | grep -E \"cdr(om|w)\""));
1010    if (strcmp("", tmp)) {
1011        if (strstr(tmp, "autofs")) {
1012            log_to_screen
1013                ("Your CD-ROM is mounted via autofs. I therefore cannot tell");
1014            log_to_screen
1015                ("if a CD actually is inserted. If a CD is inserted, please");
1016            log_to_screen("eject it. Thank you.");
1017            log_it
1018                ("Ignoring autofs CD-ROM 'mount' since we hope nothing's in it.");
1019        } else
1020            if (run_program_and_log_output("uname -a | grep Knoppix", 5)) {
1021            retval++;
1022            fatal_error
1023                ("Your CD-ROM drive is mounted. Please unmount it.");
1024        }
1025    }
1026
1027    run_program_and_log_output("cat /etc/fstab", 5);
1028#ifdef __FreeBSD__
1029    run_program_and_log_output("vinum printconfig", 5);
1030#else
1031    run_program_and_log_output("cat /etc/raidtab", 5);
1032#endif
1033
1034    if (run_program_and_log_output("mindi -V", 1)) {
1035        log_to_screen("Could not ascertain mindi's version number.");
1036        log_to_screen
1037            ("You have not installed Mondo and/or Mindi properly.");
1038        log_to_screen("Please uninstall and reinstall them both.");
1039        fatal_error("Please reinstall Mondo and Mindi.");
1040    }
1041    sprintf(tmp, "mindi --makemountlist %s/mountlist.txt.test", bkpinfo->tmpdir);
1042    if (run_program_and_log_output(tmp, 5)) {
1043        sprintf(tmp, "mindi --makemountlist %s/mountlist.txt.test failed for some reason.", bkpinfo->tmpdir);
1044        log_to_screen(tmp);
1045        log_to_screen
1046            ("Please run that command by hand and examine /var/log/mindi.log");
1047        log_to_screen
1048            ("for more information. Perhaps your /etc/fstab file is insane.");
1049        log_to_screen
1050            ("Perhaps Mindi's MakeMountlist() subroutine has a bug. We'll see.");
1051        retval++;
1052    }
1053
1054    if (!run_program_and_log_output("parted2fdisk -l | grep -i raid", 1)
1055        && !does_file_exist("/etc/raidtab")) {
1056        log_to_screen
1057            ("You have RAID partitions but no /etc/raidtab - creating one from /proc/mdstat");
1058        create_raidtab_from_mdstat("/etc/raidtab");
1059    }
1060
1061    if (retval) {
1062        mvaddstr_and_log_it(g_currentY++, 74, "Failed.");
1063    } else {
1064        mvaddstr_and_log_it(g_currentY++, 74, "Done.");
1065    }
1066    return (retval);
1067}
1068
1069/**
1070 * Retrieve the line containing @p label from the config file.
1071 * @param config_file The file to read from, usually @c /tmp/mondo-restore.cfg.
1072 * @param label What to read from the file.
1073 * @param value Where to put it.
1074 * @return 0 for success, 1 for failure.
1075 */
1076int read_cfg_var(char *config_file, char *label, char *value)
1077{
1078    /*@ buffer ****************************************************** */
1079    char command[MAX_STR_LEN * 2];
1080    char tmp[MAX_STR_LEN];
1081
1082    /*@ end vars *************************************************** */
1083
1084    assert_string_is_neither_NULL_nor_zerolength(config_file);
1085    assert_string_is_neither_NULL_nor_zerolength(label);
1086    if (!does_file_exist(config_file)) {
1087        sprintf(tmp, "(read_cfg_var) Cannot find %s config file",
1088                config_file);
1089        log_to_screen(tmp);
1090        value[0] = '\0';
1091        return (1);
1092    } else if ((value != NULL) && (strstr(value, "/dev/") && strstr(value, "t0") && !strcmp(label, "media-dev"))) {
1093        log_msg(2, "FYI, I can't read new value for %s - already got %s", label, value);
1094        return (0);
1095    } else {
1096        sprintf(command, "grep '%s .*' %s| cut -d' ' -f2,3,4,5",
1097                label, config_file);
1098        strcpy(value, call_program_and_get_last_line_of_output(command));
1099        if (strlen(value) == 0) {
1100            return (1);
1101        } else {
1102            return (0);
1103        }
1104    }
1105}
1106
1107
1108
1109/**
1110 * Remount @c supermount if it was unmounted earlier.
1111 */
1112void remount_supermounts_if_necessary()
1113{
1114    if (g_remount_cdrom_at_end) {
1115        run_program_and_log_output("mount " MNT_CDROM, FALSE);
1116    }
1117    if (g_remount_floppy_at_end) {
1118        run_program_and_log_output("mount " MNT_FLOPPY, FALSE);
1119    }
1120}
1121
1122/**
1123 * Unmount @c supermount if it's mounted.
1124 */
1125void unmount_supermounts_if_necessary()
1126{
1127    if (run_program_and_log_output
1128        ("mount | grep cdrom | grep super", FALSE) == 0) {
1129        g_remount_cdrom_at_end = TRUE;
1130        run_program_and_log_output("umount " MNT_CDROM, FALSE);
1131    }
1132    if (run_program_and_log_output
1133        ("mount | grep floppy | grep super", FALSE) == 0) {
1134        g_remount_floppy_at_end = TRUE;
1135        run_program_and_log_output("umount " MNT_FLOPPY, FALSE);
1136    }
1137}
1138
1139/**
1140 * Whether we had to stop autofs (if so, restart it at end).
1141 */
1142bool g_autofs_stopped = FALSE;
1143
1144/**
1145 * Path to the autofs initscript ("" if none exists).
1146 */
1147char g_autofs_exe[MAX_STR_LEN];
1148
1149/**
1150 * Autofs initscript in Xandros Linux distribution.
1151 */
1152#define XANDROS_AUTOFS_FNAME "/etc/init.d/xandros-autofs"
1153
1154/**
1155 * Autofs initscript in most Linux distributions.
1156 */
1157#define STOCK_AUTOFS_FNAME "/etc/rc.d/init.d/autofs"
1158
1159/**
1160 * If autofs is mounted, stop it (restart at end).
1161 */
1162void stop_autofs_if_necessary()
1163{
1164    char tmp[MAX_STR_LEN];
1165
1166    g_autofs_exe[0] = '\0';
1167    if (does_file_exist(XANDROS_AUTOFS_FNAME)) {
1168        strcpy(g_autofs_exe, XANDROS_AUTOFS_FNAME);
1169    } else if (does_file_exist(STOCK_AUTOFS_FNAME)) {
1170        strcpy(g_autofs_exe, STOCK_AUTOFS_FNAME);
1171    }
1172
1173    if (!g_autofs_exe[0]) {
1174        log_msg(3, "No autofs detected.");
1175    } else {
1176        log_msg(3, "%s --- autofs detected", g_autofs_exe);
1177// FIXME -- only disable it if it's running ---  sprintf(tmp, "%s status", autofs_exe);
1178        sprintf(tmp, "%s stop", g_autofs_exe);
1179        if (run_program_and_log_output(tmp, 2)) {
1180            log_it("Failed to stop autofs - I assume it wasn't running");
1181        } else {
1182            g_autofs_stopped = TRUE;
1183            log_it("Stopped autofs OK");
1184        }
1185    }
1186}
1187
1188/**
1189 * If autofs was stopped earlier, restart it.
1190 */
1191void restart_autofs_if_necessary()
1192{
1193    char tmp[MAX_STR_LEN];
1194
1195    if (!g_autofs_stopped || !g_autofs_exe[0]) {
1196        log_msg(3, "No autofs detected.");
1197        return;
1198    }
1199    sprintf(tmp, "%s start", g_autofs_exe);
1200    if (run_program_and_log_output(tmp, 2)) {
1201        log_it("Failed to start autofs");
1202    } else {
1203        g_autofs_stopped = FALSE;
1204        log_it("Started autofs OK");
1205    }
1206}
1207
1208
1209/**
1210 * If this is a distribution like Gentoo that doesn't keep /boot mounted, mount it.
1211 */
1212void mount_boot_if_necessary()
1213{
1214    char tmp[MAX_STR_LEN];
1215    char command[MAX_STR_LEN];
1216
1217    log_msg(1, "Started sub");
1218    log_msg(4, "About to set g_boot_mountpt[0] to '\\0'");
1219    g_boot_mountpt[0] = '\0';
1220    log_msg(4, "Done. Great. Seeting command to something");
1221    strcpy(command,
1222           "grep -v \":\" /etc/fstab | grep -vE '^#.*$' | grep -E \"[   ]/boot[     ]\" | tr -s ' ' '\t' | cut -f1 | head -n1");
1223    log_msg(4, "Cool. Command = '%s'", command);
1224    strcpy(tmp, call_program_and_get_last_line_of_output(command));
1225    log_msg(4, "tmp = '%s'", tmp);
1226    if (tmp[0]) {
1227        log_it("/boot is at %s according to /etc/fstab", tmp);
1228        strcpy(command, "mount | grep -Ew '/boot'");
1229        strcpy(tmp, call_program_and_get_last_line_of_output(command));
1230        if (!strcmp(tmp,"")) {
1231            if ((strstr(tmp, "LABEL=") || strstr(tmp,"UUID="))) {
1232                if (!run_program_and_log_output("mount /boot", 5)) {
1233                    strcpy(g_boot_mountpt, "/boot");
1234                    log_msg(1, "Mounted /boot");
1235                } else {
1236                    log_it("...ignored cos it's a label or uuid :-)");
1237                }
1238            } else {
1239                sprintf(command, "mount | grep -E '^%s'", tmp);
1240                log_msg(3, "command = %s", command);
1241                if (run_program_and_log_output(command, 5)) {
1242                    strcpy(g_boot_mountpt, tmp);
1243                    sprintf(tmp,
1244                            "%s (your /boot partition) is not mounted. I'll mount it before backing up",
1245                            g_boot_mountpt);
1246                    log_it(tmp);
1247                    sprintf(tmp, "mount %s", g_boot_mountpt);
1248                    if (run_program_and_log_output(tmp, 5)) {
1249                        g_boot_mountpt[0] = '\0';
1250                        log_msg(1, "Plan B");
1251                        if (!run_program_and_log_output("mount /boot", 5)) {
1252                            strcpy(g_boot_mountpt, "/boot");
1253                            log_msg(1, "Plan B worked");
1254                        } else {
1255                            log_msg(1,
1256                                "Plan B failed. Unable to mount /boot for backup purposes. This probably means /boot is mounted already, or doesn't have its own partition.");
1257                        }
1258                    }
1259                }
1260            }
1261        }
1262    }
1263    log_msg(1, "Ended sub");
1264}
1265
1266
1267/**
1268 * If we mounted /boot earlier, unmount it.
1269 */
1270void unmount_boot_if_necessary()
1271{
1272    char tmp[MAX_STR_LEN];
1273
1274    log_msg(3, "starting");
1275    if (g_boot_mountpt[0]) {
1276        sprintf(tmp, "umount %s", g_boot_mountpt);
1277        if (run_program_and_log_output(tmp, 5)) {
1278            log_it("WARNING - unable to unmount /boot");
1279        }
1280    }
1281    log_msg(3, "leaving");
1282}
1283
1284
1285
1286/**
1287 * Write a line to a configuration file. Writes a line of the form,
1288 * @c label @c value.
1289 * @param config_file The file to write to. Usually @c mondo-restore.cfg.
1290 * @param label What to call this bit of data you're writing.
1291 * @param value The bit of data you're writing.
1292 * @return 0 for success, 1 for failure.
1293 */
1294int write_cfg_var(char *config_file, char *label, char *value)
1295{
1296    /*@ buffers ***************************************************** */
1297    char command[MAX_STR_LEN * 2];
1298    char tempfile[MAX_STR_LEN];
1299    char tmp[MAX_STR_LEN];
1300
1301
1302    /*@ end vars *************************************************** */
1303    assert_string_is_neither_NULL_nor_zerolength(config_file);
1304    assert_string_is_neither_NULL_nor_zerolength(label);
1305    assert(value != NULL);
1306    if (!does_file_exist(config_file)) {
1307        sprintf(tmp, "(write_cfg_file) Cannot find %s config file",
1308                config_file);
1309        log_to_screen(tmp);
1310        return (1);
1311    }
1312    sprintf(tempfile, "%s/mojo-jojo.blah", bkpinfo->tmpdir);
1313    if (does_file_exist(config_file)) {
1314        sprintf(command, "grep -vE '^%s .*$' %s > %s",
1315                label, config_file, tempfile);
1316        paranoid_system(command);
1317    }
1318    sprintf(command, "echo \"%s %s\" >> %s", label, value, tempfile);
1319    paranoid_system(command);
1320    sprintf(command, "mv -f %s %s", tempfile, config_file);
1321    paranoid_system(command);
1322    unlink(tempfile);
1323    return (0);
1324}
1325
1326
1327/**
1328 * The standard log_debug_msg() (log_msg() also due to a macro). Writes some describing
1329 * information to the logfile.
1330 */
1331void standard_log_debug_msg(int debug_level, const char *szFile,
1332                            const char *szFunction, int nLine,
1333                            const char *fmt, ...)
1334{
1335    va_list args;
1336    int i;
1337    static int depth = 0;
1338    FILE *fout;
1339
1340    if (depth > 5) {
1341        depth--;
1342        return;
1343    }
1344    depth++;
1345
1346    if (debug_level <= g_loglevel) {
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        va_start(args, fmt);
1363        vfprintf(fout, fmt, args);
1364        va_end(args);
1365
1366        // do not slow down the progran if standard debug level
1367        // must be enabled: if no flush, the log won't be up-to-date if there
1368        // is a segfault
1369        //if (g_dwDebugLevel != 1)
1370
1371        fprintf(fout, "\n");
1372        paranoid_fclose(fout);
1373    }
1374    depth--;
1375}
1376
1377/**
1378 * Function pointer to the @c log_debug_msg function to use. Points to standard_log_debug_msg() by default.
1379 */
1380void (*log_debug_msg) (int, const char *, const char *, int, const char *,
1381                       ...) = standard_log_debug_msg;
1382
1383
1384/**
1385 * If @p y, malloc @p x, else free @p x.
1386 * @bug This function seems orphaned. Please remove.
1387 */
1388#define do_alloc_or_free_depending(x,y) { if(y) {x=malloc(MAX_STR_LEN);} else {paranoid_free(x);} }
1389
1390/**
1391 * Allocate or free important globals, depending on @p mal.
1392 * @param mal If TRUE, malloc; if FALSE, free.
1393 */
1394void do_libmondo_global_strings_thing(int mal)
1395{
1396    if (mal) {
1397        malloc_string(g_boot_mountpt);
1398        malloc_string(g_mondo_home);
1399        /*
1400        malloc_string(g_tmpfs_mountpt);
1401        */
1402        malloc_string(g_serial_string);
1403        malloc_string(g_magicdev_command);
1404    } else {
1405        paranoid_free(g_boot_mountpt);
1406        paranoid_free(g_mondo_home);
1407        /*
1408        paranoid_free(g_tmpfs_mountpt);
1409        */
1410        paranoid_free(g_serial_string);
1411        paranoid_free(g_magicdev_command);
1412
1413        mr_free(bkpinfo->nfs_user);
1414    }
1415
1416    /*
1417       char**list_of_arrays[] = {
1418       &g_boot_mountpt,
1419       &g_mondo_home,
1420       &g_tmpfs_mountpt,
1421       &g_serial_string,
1422       &g_magicdev_command,
1423       NULL};
1424
1425       char**ppcurr;
1426       int i;
1427
1428       for(i=0;list_of_arrays[i];i++)
1429       {
1430       log_msg(5, "Allocating %d", i);
1431       ppcurr = list_of_arrays[i];
1432       if (mal)
1433       { *ppcurr = malloc(MAX_STR_LEN); }
1434       else
1435       {
1436       if (*ppcurr)
1437       {
1438       free(*ppcurr);
1439       }
1440       }
1441       }
1442       log_msg(5, "Returning");
1443     */
1444}
1445
1446/**
1447 * Allocate important globals.
1448 * @see do_libmondo_global_strings_thing
1449 */
1450void malloc_libmondo_global_strings(void)
1451{
1452    do_libmondo_global_strings_thing(1);
1453}
1454
1455/**
1456 * Free important globals.
1457 * @see do_libmondo_global_strings_thing
1458 */
1459void free_libmondo_global_strings(void)
1460{
1461    do_libmondo_global_strings_thing(0);
1462}
1463
1464
1465
1466/**
1467 * Stop @c magicdev if it's running.
1468 * The command used to start it is saved in @p g_magicdev_command.
1469 */
1470void stop_magicdev_if_necessary()
1471{
1472    strcpy(g_magicdev_command,
1473           call_program_and_get_last_line_of_output
1474           ("ps ax | grep -w magicdev | grep -v grep | tr -s '\t' ' '| cut -d' ' -f6-99"));
1475    if (g_magicdev_command[0]) {
1476        log_msg(1, "g_magicdev_command = '%s'", g_magicdev_command);
1477        paranoid_system("killall magicdev");
1478    }
1479}
1480
1481
1482/**
1483 * Restart magicdev if it was stopped.
1484 */
1485void restart_magicdev_if_necessary()
1486{
1487    char *tmp;
1488
1489    malloc_string(tmp);
1490    if (g_magicdev_command && g_magicdev_command[0]) {
1491        sprintf(tmp, "%s &", g_magicdev_command);
1492        paranoid_system(tmp);
1493    }
1494    paranoid_free(tmp);
1495}
1496
1497/* @} - end of utilityGroup */
Note: See TracBrowser for help on using the repository browser.