source: branches/3.2/mondo/src/common/libmondo-tools.c @ 3507

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