source: branches/3.0/mondo/src/common/libmondo-tools.c @ 2907

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