source: trunk/mondo/src/common/libmondo-files.c @ 1161

Last change on this file since 1161 was 1161, checked in by bruno, 13 years ago

Update trunk with the latest feedback from stable (obtained with meld) - First pass

  • Property svn:keywords set to Id
File size: 33.9 KB
Line 
1/*  $Id: libmondo-files.c 1161 2007-02-14 12:13:49Z bruno $
2 * file manipulation
3*/
4
5/**
6 * @file
7 * Functions to manipulate files.
8 */
9
10
11#include "my-stuff.h"
12#include "mondostructures.h"
13#include "libmondo-files.h"
14
15#include "libmondo-tools-EXT.h"
16#include "newt-specific-EXT.h"
17#include "libmondo-devices-EXT.h"
18#include "libmondo-fork-EXT.h"
19#include "libmondo-string-EXT.h"
20#include "mr_mem.h"
21
22#include "mr_file.h"
23
24/*@unused@*/
25//static char cvsid[] = "$Id: libmondo-files.c 1161 2007-02-14 12:13:49Z bruno $";
26
27extern char **err_log_lines;
28
29extern int g_currentY;
30extern int g_noof_log_lines;
31extern char *g_mondo_home;
32
33/**
34 * @addtogroup fileGroup
35 * @{
36 */
37/**
38 * Get an md5 checksum of the specified file.
39 * @param filename The file to checksum.
40 * @return The 32-character ASCII representation of the 128-bit checksum.
41 * @note The returned string points to static storage that will be overwritten with each call.
42 */
43char *calc_checksum_of_file(char *filename)
44{
45    /*@ buffers ***************************************************** */
46    static char *output = NULL;
47
48    char *command = NULL;
49    char *tmp = NULL;
50    size_t n = 0;
51
52    /*@ pointers **************************************************** */
53    char *p;
54    FILE *fin;
55
56    /*@ initialize pointers ***************************************** */
57
58    p = output;
59
60    /*@************************************************************** */
61
62    assert_string_is_neither_NULL_nor_zerolength(filename);
63
64    if (does_file_exist(filename)) {
65        mr_asprintf(&command, "md5sum \"%s\"", filename);
66        fin = popen(command, "r");
67        mr_free(command);
68
69        if (fin) {
70            mr_getline(&output, &n, fin);
71            p = strchr(output, ' ');
72            paranoid_pclose(fin);
73        }
74    } else {
75        mr_asprintf(&tmp, "File '%s' not found; cannot calc checksum",
76                filename);
77        log_it(tmp);
78        mr_free(tmp);
79    }
80    if (p) {
81        *p = '\0';
82    }
83    return (output);
84}
85
86
87/**
88 * Get the number of lines in @p filename.
89 * @param filename The file to count lines in.
90 * @return The number of lines in @p filename.
91 * @bug This function uses the shell and "wc -l"; it should probably be rewritten in C.
92 */
93long count_lines_in_file(char *filename)
94{
95
96    /*@ buffers ***************************************************** */
97    char *command = NULL;
98    char *incoming = NULL;
99    char *tmp = NULL;
100
101    /*@ long ******************************************************** */
102    long noof_lines = -1L;
103
104    /*@ int ******************************************************** */
105    size_t n = 0;
106
107    /*@ pointers **************************************************** */
108    FILE *fin;
109
110    assert_string_is_neither_NULL_nor_zerolength(filename);
111    if (!does_file_exist(filename)) {
112        mr_asprintf(&tmp,
113                "%s does not exist, so I cannot found the number of lines in it",
114                filename);
115        log_it(tmp);
116        mr_free(tmp);
117        return (0);
118    }
119    mr_asprintf(&command, "cat %s | wc -l", filename);
120    if (!does_file_exist(filename)) {
121        return (-1);
122    }
123    fin = popen(command, "r");
124    mr_free(command);
125
126    if (fin) {
127        if (feof(fin)) {
128            noof_lines = 0;
129        } else {
130            mr_getline(&incoming, &n, fin);
131            while (strlen(incoming) > 0
132                   && incoming[strlen(incoming) - 1] < 32) {
133                incoming[strlen(incoming) - 1] = '\0';
134            }
135            noof_lines = atol(incoming);
136            mr_free(incoming);
137        }
138        paranoid_pclose(fin);
139    }
140    return (noof_lines);
141}
142
143
144/**
145 * Check for existence of given @p filename.
146 * @param filename The file to check for.
147 * @return TRUE if it exists, FALSE otherwise.
148 */
149bool does_file_exist(char *filename)
150{
151
152    /*@ structures ************************************************** */
153    struct stat buf;
154
155    /*@************************************************************** */
156
157    assert(filename != NULL);
158
159    if (lstat(filename, &buf)) {
160        mr_msg(20, "%s does not exist", filename);
161        return (FALSE);
162    } else {
163        mr_msg(20, "%s exists", filename);
164        return (TRUE);
165    }
166}
167
168
169/**
170 * Modify @p inout (a file containing a list of files) to only contain files
171 * that exist.
172 * @param inout The filelist to operate on.
173 * @note The original file is renamed beforehand, so it will not be accessible
174 * while the modification is in progress.
175 */
176void exclude_nonexistent_files(char *inout)
177{
178    char *infname;
179    char *outfname;
180    char *tmp;
181    char *incoming = NULL;
182
183    /*@ int ********************************************************* */
184    int i;
185    size_t n = 0;
186
187    /*@ pointers **************************************************** */
188    FILE *fin, *fout;
189
190
191    /*@ end vars *********************************************************** */
192
193    assert_string_is_neither_NULL_nor_zerolength(inout);
194
195    mr_asprintf(&infname, "%s.in", inout);
196
197    mr_asprintf(&tmp, "cp -f %s %s", inout, infname);
198    run_program_and_log_output(tmp, FALSE);
199    mr_free(tmp);
200
201    if (!(fin = fopen(infname, "r"))) {
202        log_OS_error("Unable to openin infname");
203        mr_free(infname);
204        return;
205    }
206
207    mr_asprintf(&outfname, "%s", inout);
208    if (!(fout = fopen(outfname, "w"))) {
209        log_OS_error("Unable to openout outfname");
210        mr_free(infname);
211        mr_free(outfname);
212        return;
213    }
214    mr_free(outfname);
215
216    for (mr_getline(&incoming, &n, fin); !feof(fin);
217         mr_getline(&incoming, &n, fin)) {
218        i = strlen(incoming) - 1;
219        if (i >= 0 && incoming[i] < 32) {
220            incoming[i] = '\0';
221        }
222        if (does_file_exist(incoming)) {
223            fprintf(fout, "%s\n", incoming);
224        } else {
225            mr_asprintf(&tmp, "Excluding '%s'-nonexistent\n", incoming);
226            log_it(tmp);
227            mr_free(tmp);
228        }
229    }
230    mr_free(incoming);
231    paranoid_fclose(fout);
232    paranoid_fclose(fin);
233    unlink(infname);
234    mr_free(infname);
235}
236
237
238/**
239 * Attempt to find the user's kernel by calling Mindi.
240 * If Mindi can't find the kernel, ask user. If @p kernel is not empty,
241 * don't do anything.
242 * @param kernel Where to put the found kernel.
243 * @return 0 for success, 1 for failure.
244 */
245int figure_out_kernel_path_interactively_if_necessary(char *kernel)
246{
247    char *tmp = NULL;
248    char *command = NULL;
249
250    if (kernel == NULL) {
251        kernel = call_program_and_get_last_line_of_output
252               ("mindi --findkernel 2> /dev/null");
253    }
254    // If we didn't get anything back, check whether mindi raised a fatal error
255    if (kernel == NULL) {
256        mr_asprintf(&command, "grep 'Fatal error' /var/log/mindi.log");
257        tmp = call_program_and_get_last_line_of_output(command);
258        if (strlen(tmp) > 1) {
259            popup_and_OK(tmp);
260            fatal_error("Mindi gave a fatal error. Please check '/var/log/mindi.log'.");
261        }
262        mr_free(command);
263        mr_free(tmp);
264    }
265
266    if (kernel != NULL) {
267        log_it("Calling Mindi with kernel path of '%s'", kernel);
268    } else {
269        log_it("Calling Mindi without kernel, so asking one");
270    }
271
272    while (kernel == NULL) {
273        if (!ask_me_yes_or_no
274            (_("Kernel not found or invalid. Choose another?"))) {
275            return (1);
276        }
277        if (!popup_and_get_string
278            (_("Kernel path"),
279             _("What is the full path and filename of your kernel, please?"),
280             kernel)) {
281            fatal_error
282                ("Kernel not found. Please specify with the '-k' flag.");
283        }
284        log_it("User says kernel is at %s", kernel);
285    }
286    return (0);
287}
288
289
290/**
291 * Find location of specified executable in user's PATH.
292 * @param fname The basename of the executable to search for (e.g. @c afio).
293 * @return The full path to the executable, or "" if it does not exist, or NULL if @c file could not be found.
294 * @note The returned string points to static storage that will be overwritten with each call.
295 * @bug The checks with @c file and @c dirname seem pointless. If @c incoming is "", then you're calling
296 * <tt>dirname 2\>/dev/null</tt> or <tt>file 2\>/dev/null | cut -d':' -f1 2\>/dev/null</tt>, which basically amounts
297 * to nothing.
298 */
299char *find_home_of_exe(char *fname)
300{
301    /*@ buffers ********************* */
302    char *output = NULL;
303    char *incoming = NULL;
304    char *command = NULL;
305
306    /*@******************************* */
307
308    assert_string_is_neither_NULL_nor_zerolength(fname);
309
310    mr_asprintf(&command, "which %s 2> /dev/null", fname);
311    incoming = call_program_and_get_last_line_of_output(command);
312    mr_free(command);
313
314    if (incoming == NULL) {
315        if (system("which file > /dev/null 2> /dev/null")) {
316            return (NULL);      // forget it :)
317        }
318        mr_asprintf(&command,
319                "file %s 2> /dev/null | cut -d':' -f1 2> /dev/null",
320                incoming);
321        mr_free(incoming);
322
323        incoming = call_program_and_get_last_line_of_output(command);
324        mr_free(command);
325    }
326    if (incoming == NULL)   // yes, it is == '\0' twice, not once :)
327    {
328        mr_asprintf(&command, "dirname %s 2> /dev/null", incoming);
329        mr_free(incoming);
330
331        incoming = call_program_and_get_last_line_of_output(command);
332        mr_free(command);
333    }
334    output = incoming;
335
336    if (output != NULL && does_file_exist(output)) {
337        mr_msg(4, "find_home_of_exe () --- Found %s at %s", fname, output);
338    } else {
339        mr_free(output);
340        mr_msg(4, "find_home_of_exe() --- Could not find %s", fname);
341    }
342    return (output);
343}
344
345
346/**
347 * Get the last sequence of digits surrounded by non-digits in the first 32k of
348 * a file.
349 * @param logfile The file to look in.
350 * @return The number found, or 0 if none.
351 */
352int get_trackno_from_logfile(char *logfile)
353{
354
355    /*@ pointers ********************************************************* */
356    FILE *fin;
357
358    /*@ int ************************************************************** */
359    int trackno = 0;
360    size_t len = 0;
361
362    /*@ buffer ************************************************************ */
363    char datablock[32701];
364
365    assert_string_is_neither_NULL_nor_zerolength(logfile);
366
367    if (!(fin = fopen(logfile, "r"))) {
368        log_OS_error("Unable to open logfile");
369        fatal_error("Unable to open logfile to read trackno");
370    }
371    len = fread(datablock, 1, 32700, fin);
372    paranoid_fclose(fin);
373    if (len <= 0) {
374        return (0);
375    }
376    for (; len > 0 && !isdigit(datablock[len - 1]); len--);
377    datablock[len--] = '\0';
378    for (; len > 0 && isdigit(datablock[len - 1]); len--);
379    trackno = atoi(datablock + len);
380    return (trackno);
381}
382
383
384/**
385 * Get a percentage from the last line of @p filename. We look for the string
386 * "% done" on the last line and, if we find it, grab the number before the last % sign.
387 * @param filename The file to get the percentage from.
388 * @return The percentage found, or 0 for error.
389 */
390int grab_percentage_from_last_line_of_file(char *filename)
391{
392
393    char *lastline = NULL;
394    char *command = NULL;
395    char *p = NULL;
396    int i;
397
398    for (i = g_noof_log_lines - 1;
399         i >= 0 && !strstr(err_log_lines[i], "% Done")
400         && !strstr(err_log_lines[i], "% done"); i--);
401    if (i < 0) {
402        mr_asprintf(&command,
403                "tail -n3 %s | grep -Fi \"%c\" | tail -n1 | awk '{print $0;}'",
404                filename, '%');
405        lastline = call_program_and_get_last_line_of_output(command);
406        mr_free(command);
407        if (!lastline) {
408            return (0);
409        }
410    } else {
411        mr_asprintf(&lastline, err_log_lines[i]);
412    }
413
414    p = strrchr(lastline, '%');
415    if (p) {
416        *p = '\0';
417    }
418    if (!p) {
419        mr_free(lastline);
420        return (0);
421    }
422    *p = '\0';
423    for (p--; *p != ' ' && p != lastline; p--);
424    if (p != lastline) {
425        p++;
426    }
427    i = atoi(p);
428    mr_free(lastline);
429
430    return (i);
431}
432
433
434/**
435 * Return the last line of @p filename.
436 * @param filename The file to get the last line of.
437 * @return The last line of the file.
438 * @note The returned string points to static storage that will be overwritten with each call.
439 */
440char *last_line_of_file(char *filename)
441{
442    /*@ buffers ***************************************************** */
443    char *output = NULL;
444    char *command = NULL;
445    char *tmp = NULL;
446
447    /*@ pointers **************************************************** */
448    FILE *fin;
449    size_t n = 0;
450
451    /*@ end vars **************************************************** */
452
453    if (!does_file_exist(filename)) {
454        mr_asprintf(&tmp, _("Tring to get last line of nonexistent file (%s)"),
455                filename);
456        log_it(tmp);
457        mr_free(tmp);
458        return (NULL);
459    }
460    mr_asprintf(&command, "tail -n1 %s", filename);
461    fin = popen(command, "r");
462    mr_free(command);
463
464    mr_getline(&output, &n, fin);
465    paranoid_pclose(fin);
466    while (strlen(output) > 0 && output[strlen(output) - 1] < 32) {
467        output[strlen(output) - 1] = '\0';
468    }
469    return (output);
470}
471
472
473/**
474 * Get the length of @p filename in bytes.
475 * @param filename The file to get the length of.
476 * @return The length of the file, or -1 for error.
477 */
478off_t length_of_file(char *filename)
479{
480    /*@ pointers *************************************************** */
481    FILE *fin;
482
483    /*@ long long ************************************************* */
484    off_t length;
485
486    fin = fopen(filename, "r");
487    if (!fin) {
488        log_it("filename=%s", filename);
489        log_OS_error("Unable to openin filename");
490        return (-1);
491    }
492    fseeko(fin, 0, SEEK_END);
493    length = ftello(fin);
494    paranoid_fclose(fin);
495    return (length);
496}
497
498
499/**
500 * Create the directory @p outdir_fname and all parent directories. Equivalent to <tt>mkdir -p</tt>.
501 * @param outdir_fname The directory to create.
502 * @return The return value of @c mkdir.
503 */
504/* BERLIOS: This function shouldn't call system at all */
505int make_hole_for_dir(char *outdir_fname)
506{
507    char *tmp;
508    int res = 0;
509
510    assert_string_is_neither_NULL_nor_zerolength(outdir_fname);
511    mr_asprintf(&tmp, "mkdir -p %s", outdir_fname);
512    res = system(tmp);
513    mr_free(tmp);
514    return (res);
515}
516
517
518/**
519 * Create the parent directories of @p outfile_fname.
520 * @param outfile_fname The file to make a "hole" for.
521 * @return 0, always.
522 * @bug Return value unnecessary.
523 */
524/* BERLIOS: This function shouldn't call system at all */
525int make_hole_for_file(char *outfile_fname)
526{
527    /*@ buffer ****************************************************** */
528    char *command;
529
530    /*@ int  ******************************************************** */
531    int res = 0;
532
533    /*@ end vars *************************************************** */
534
535    assert_string_is_neither_NULL_nor_zerolength(outfile_fname);
536    assert(!strstr(outfile_fname, MNT_CDROM));
537    assert(!strstr(outfile_fname, "/dev/cdrom"));
538
539    mr_asprintf(&command, "mkdir -p \"%s\" 2> /dev/null", outfile_fname);
540    res += system(command);
541    mr_free(command);
542
543    mr_asprintf(&command, "rmdir \"%s\" 2> /dev/null", outfile_fname);
544    res += system(command);
545    mr_free(command);
546
547    mr_asprintf(&command, "rm -f \"%s\" 2> /dev/null", outfile_fname);
548    res += system(command);
549    mr_free(command);
550    unlink(outfile_fname);
551    return (0);
552}
553
554
555/**
556 * Get the number of lines in @p filelist_fname that contain the string @p wildcard.
557 * @param filelist_fname The file to search through.
558 * @param wildcard The string to search for. This is @e not a shell glob or a regular expression.
559 * @return The number of lines matched.
560 */
561long noof_lines_that_match_wildcard(char *filelist_fname, char *wildcard)
562{
563    /*@ long ******************************************************* */
564    long matches = 0;
565
566    /*@ pointers *************************************************** */
567    FILE *fin;
568
569    /*@ buffers **************************************************** */
570    char *incoming = NULL;
571
572    size_t n = 0;
573    /*@ end vars *************************************************** */
574
575
576    fin = fopen(filelist_fname, "r");
577
578    if (!fin) {
579        log_OS_error("Unable to openin filelist_fname");
580        return (0);
581    }
582    mr_getline(&incoming, &n, fin);
583    while (!feof(fin)) {
584        if (strstr(incoming, wildcard)) {
585            matches++;
586        }
587        mr_getline(&incoming, &n, fin);
588    }
589    paranoid_fclose(fin);
590    mr_free(incoming);
591    return (matches);
592}
593
594
595/**
596 * Register our PID in a file in /var/run.
597 * The PID will be put in /var/run/monitas-<tt>name_str</tt>.pid.
598 * @param pid 0 to remove file, anything else to create it.
599 * @param name_str The basename of the PID file (e.g. "mondo" or "server")
600 * @note This function does not provide support against multiple instances, unless you check for that yourself.
601 */
602void register_pid(pid_t pid, char *name_str)
603{
604    char *tmp = NULL;
605    char *lockfile_fname = NULL;
606    int res;
607    size_t n = 0;
608    FILE *fin;
609
610    mr_asprintf(&lockfile_fname, "/var/run/monitas-%s.pid", name_str);
611    if (!pid) {
612        log_it("Unregistering PID");
613        if (unlink(lockfile_fname)) {
614            log_it("Error unregistering PID");
615        }
616        mr_free(lockfile_fname);
617        return;
618    }
619    if (does_file_exist(lockfile_fname)) {
620        if ((fin = fopen(lockfile_fname, "r"))) {
621            mr_getline(&tmp, &n, fin);
622            paranoid_fclose(fin);
623        } else {
624            log_OS_error("Unable to openin lockfile_fname");
625        }
626        pid = (pid_t) atol(tmp);
627        mr_free(tmp);
628
629        mr_asprintf(&tmp, "ps %ld > /dev/null 2> /dev/null", (long int) pid);
630        res = system(tmp);
631        mr_free(tmp);
632        if (!res) {
633            log_it
634                ("I believe the daemon is already running. If it isn't, please delete %s and try again.",
635                 lockfile_fname);
636        }
637    }
638    mr_asprintf(&tmp, "echo %ld > %s 2> /dev/null", (long int) getpid(),
639            lockfile_fname);
640    mr_free(lockfile_fname);
641
642    if (system(tmp)) {
643        fatal_error("Cannot register PID");
644    }
645    mr_free(tmp);
646    return;
647}
648
649
650/**
651 * Determine the size (in KB) of @p dev in the mountlist in <tt>tmpdir</tt>/mountlist.txt.
652 * @param tmpdir The tempdir where the mountlist is stored.
653 * @param dev The device to search for.
654 * @return The size of the partition in KB.
655 */
656long size_of_partition_in_mountlist_K(char *tmpdir, char *dev)
657{
658    char *command = NULL;
659    char *sz_res = NULL;
660    long file_len_K = 0L;
661
662    mr_asprintf(&command,
663            "grep '%s ' %s/mountlist.txt | head -n1 | awk '{print $4;}'",
664            dev, tmpdir);
665    log_it(command);
666    sz_res = call_program_and_get_last_line_of_output(command);
667    file_len_K = atol(sz_res);
668    mr_msg(4, "%s --> %s --> %ld", command, sz_res, file_len_K);
669    mr_free(command);
670    mr_free(sz_res);
671    return (file_len_K);
672}
673
674
675/**
676 * Calculate the total size (in KB) of all the biggiefiles in this backup.
677 * @param bkpinfo The backup information structure. Only the @c bkpinfo->tmpdir field is used.
678 * @return The total size of all biggiefiles in KB.
679 */
680long size_of_all_biggiefiles_K(struct s_bkpinfo *bkpinfo)
681{
682    char *fname = NULL;
683    char *biggielist = NULL;
684    char *comment = NULL;
685    char *tmp = NULL;
686    char *command = NULL;
687
688    /*@ long ******************************************************** */
689    long scratchL = 0L;
690    long file_len_K = 0L;
691
692    /*@ pointers *************************************************** */
693    FILE *fin = NULL;
694    size_t n = 0;
695
696    /*@ end vars *************************************************** */
697
698    log_it("Calculating size of all biggiefiles (in total)");
699    mr_asprintf(&biggielist, "%s/biggielist.txt", bkpinfo->tmpdir);
700    log_it("biggielist = %s", biggielist);
701    if (!(fin = fopen(biggielist, "r"))) {
702        log_OS_error
703            ("Cannot open biggielist. OK, so estimate is based on filesets only.");
704    } else {
705        mr_msg(4, "Reading it...");
706        for (mr_getline(&fname, &n, fin); !feof(fin);
707             mr_getline(&fname, &n, fin)) {
708            if (fname[strlen(fname) - 1] <= 32) {
709                fname[strlen(fname) - 1] = '\0';
710            }
711            if (0 == strncmp(fname, "/dev/", 5)) {
712                if (is_dev_an_NTFS_dev(fname)) {
713                    tmp = find_home_of_exe("ntfsresize");
714                    if (!tmp) {
715                        fatal_error("ntfsresize not found");
716                    }
717                    mr_free(tmp);
718
719                    mr_asprintf(&command, "ntfsresize --force --info %s|grep '^You might resize at '|cut -d' ' -f5", fname);
720                    log_it("command = %s", command);
721                    tmp = call_program_and_get_last_line_of_output(command);
722                    mr_free(command);
723
724                    log_it("res of it = %s", tmp);
725                    file_len_K = atoll(tmp) / 1024L;
726                    mr_free(tmp);
727                } else {
728                    file_len_K = get_phys_size_of_drive(fname) * 1024L;
729                }
730            } else {
731                /* BERLIOS: more than long here ??? */
732                file_len_K = (long) (length_of_file(fname) / 1024);
733            }
734            if (file_len_K > 0) {
735                scratchL += file_len_K;
736                mr_msg(4, "%s --> %ld K", fname, file_len_K);
737            }
738            mr_asprintf(&comment,
739                    "After adding %s, scratchL+%ld now equals %ld", fname,
740                    file_len_K, scratchL);
741            mr_msg(4, comment);
742            mr_free(comment);
743
744            if (feof(fin)) {
745                break;
746            }
747        }
748        mr_free(fname);
749    }
750    mr_free(biggielist);
751
752    log_it("Closing...");
753    paranoid_fclose(fin);
754    log_it("Finished calculating total size of all biggiefiles");
755    return (scratchL);
756}
757
758/**
759 * Determine the amount of space (in KB) occupied by a mounted CD.
760 * This can also be used to find the space used for other directories.
761 * @param mountpt The mountpoint/directory to check.
762 * @return The amount of space occupied in KB.
763 */
764long long space_occupied_by_cd(char *mountpt)
765{
766    /*@ buffer ****************************************************** */
767    char *tmp = NULL;
768    char *command = NULL;
769    long long llres;
770    size_t n = 0;
771    /*@ pointers **************************************************** */
772    char *p = NULL;
773    FILE *fin = NULL;
774
775    /*@ end vars *************************************************** */
776
777    mr_asprintf(&command, "du -sk %s", mountpt);
778    errno = 0;
779    fin = popen(command, "r");
780    if (errno) {
781      log_it("popen() FAILED: command=%s, mountpt=%s, fin=%d, errno=%d, strerror=%s", command, mountpt, fin, errno, strerror(errno));
782      llres = 0;
783    } else {
784        mr_getline(&tmp, &n, fin);
785        paranoid_pclose(fin);
786        p = strchr(tmp, '\t');
787        if (p) {
788            *p = '\0';
789        }
790        for (p = tmp, llres = 0; *p != '\0'; p++) {
791            llres *= 10;
792            llres += (int) (*p - '0');
793        }
794    }
795
796    mr_free(command);
797    mr_free(tmp);
798    return (llres);
799}
800
801
802/**
803 * Update a CRC checksum to include another character.
804 * @param crc The original CRC checksum.
805 * @param c The character to add.
806 * @return The new CRC checksum.
807 * @ingroup utilityGroup
808 */
809unsigned int updcrc(unsigned int crc, unsigned int c)
810{
811    unsigned int tmp;
812    tmp = (crc >> 8) ^ c;
813    crc = (crc << 8) ^ crctttab[tmp & 255];
814    return crc;
815}
816
817
818/**
819 * Update a reverse CRC checksum to include another character.
820 * @param crc The original CRC checksum.
821 * @param c The character to add.
822 * @return The new CRC checksum.
823 * @ingroup utilityGroup
824 */
825unsigned int updcrcr(unsigned int crc, unsigned int c)
826{
827    unsigned int tmp;
828    tmp = crc ^ c;
829    crc = (crc >> 8) ^ crc16tab[tmp & 0xff];
830    return crc;
831}
832
833
834/**
835 * Check for an executable on the user's system; write a message to the
836 * screen and the log if we can't find it.
837 * @param fname The executable basename to look for.
838 * @return 0 if it's found, nonzero if not.
839 */
840int whine_if_not_found(char *fname)
841{
842    /*@ buffers *** */
843    char *command;
844    char *errorstr;
845    int res = 0;
846
847
848    mr_asprintf(&command, "which %s > /dev/null 2> /dev/null", fname);
849    res = system(command);
850    mr_free(command);
851
852    if (res) {
853        mr_asprintf(&errorstr,
854            _("Please install '%s'. I cannot find it on your system."),
855            fname);
856        log_to_screen(errorstr);
857        mr_free(errorstr);
858        log_to_screen
859            (_("There may be an hyperlink at http://www.mondorescue.org which"));
860        log_to_screen(_("will take you to the relevant (missing) package."));
861        return (1);
862    } else {
863        return (0);
864    }
865}
866
867
868/**
869 * Create a data file at @p fname containing @p contents.
870 * The data actually can be multiple lines, despite the name.
871 * @param fname The file to create.
872 * @param contents The data to put in it.
873 * @return 0 for success, 1 for failure.
874 */
875int write_one_liner_data_file(char *fname, char *contents)
876{
877    /*@ pointers *************************************************** */
878    FILE *fout;
879    int res = 0;
880
881    /*@ end vars *************************************************** */
882
883    assert_string_is_neither_NULL_nor_zerolength(fname);
884    if (!contents) {
885        log_it("%d: Warning - writing NULL to %s", __LINE__, fname);
886    }
887    if (!(fout = fopen(fname, "w"))) {
888        log_it("fname=%s");
889        log_OS_error("Unable to openout fname");
890        return (1);
891    }
892    fprintf(fout, "%s\n", contents);
893    paranoid_fclose(fout);
894    return (res);
895}
896
897
898/**
899 * Read @p fname into @p contents.
900 * @param fname The file to read.
901 * @param contents Where to put its contents.
902 * @return 0 for success, nonzero for failure.
903 */
904int read_one_liner_data_file(char *fname, char *contents)
905{
906    /*@ pointers *************************************************** */
907    FILE *fin;
908    int res = 0;
909    int i;
910
911    /*@ end vars *************************************************** */
912
913    assert_string_is_neither_NULL_nor_zerolength(fname);
914    if (!contents) {
915        log_it("%d: Warning - reading NULL from %s", __LINE__, fname);
916    }
917    if (!(fin = fopen(fname, "r"))) {
918        log_it("fname=%s", fname);
919        log_OS_error("Unable to openin fname");
920        return (1);
921    }
922    fscanf(fin, "%s\n", contents);
923    i = strlen(contents);
924    if (i > 0 && contents[i - 1] < 32) {
925        contents[i - 1] = '\0';
926    }
927    paranoid_fclose(fin);
928    return (res);
929}
930
931
932/**
933 * Copy the files that Mondo/Mindi need to run to the scratchdir or tempdir.
934 * Currently this includes: copy Mondo's home directory to scratchdir, untar "mondo_home/payload.tgz"
935 * if it exists, copy LAST-FILELIST-NUMBER to scratchdir, copy mondorestore
936 * and post-nuke.tgz (if it exists) to tmpdir, and run "hostname > scratchdir/HOSTNAME".
937 * @param bkpinfo The backup information structure. Fields used:
938 * - @c bkpinfo->postnuke_tarball
939 * - @c bkpinfo->scratchdir
940 * - @c bkpinfo->tmpdir
941 */
942void copy_mondo_and_mindi_stuff_to_scratchdir(struct s_bkpinfo *bkpinfo)
943{
944    /*@ Char buffers ** */
945    char *command = NULL;
946    char *tmp;
947    char old_pwd[MAX_STR_LEN];
948
949    mvaddstr_and_log_it(g_currentY, 0,
950                        "Copying Mondo's core files to the scratch directory");
951
952    /* BERLIOS: Why do we need to do it here as well ? */
953    mr_msg(4, "g_mondo_home='%s'", g_mondo_home);
954    if ((g_mondo_home == NULL) || strlen(g_mondo_home) < 2) {
955        mr_free(g_mondo_home);
956        g_mondo_home = find_and_store_mondoarchives_home();
957    }
958    mr_asprintf(&command, CP_BIN " --parents -pRdf %s %s", g_mondo_home,
959            bkpinfo->scratchdir);
960
961    mr_msg(4, "command = %s", command);
962    if (run_program_and_log_output(command, 1)) {
963        fatal_error("Failed to copy Mondo's stuff to scratchdir");
964    }
965    mr_free(command);
966
967    /* i18n */
968    mr_asprintf(&command, CP_BIN " --parents /usr/share/locale/*/LC_MESSAGES/mondo.mo %s",bkpinfo->scratchdir);
969    mr_msg(4, "command = %s", command);
970    run_program_and_log_output(command, 1);
971    mr_free(command);
972
973    mr_asprintf(&tmp, "%s/payload.tgz", g_mondo_home);
974    if (does_file_exist(tmp)) {
975        log_it("Untarring payload %s to scratchdir %s", tmp,
976               bkpinfo->scratchdir);
977        (void) getcwd(old_pwd, MAX_STR_LEN - 1);
978        chdir(bkpinfo->scratchdir);
979        mr_asprintf(&command, "tar -zxvf %s", tmp);
980        if (run_program_and_log_output(command, FALSE)) {
981            fatal_error("Failed to untar payload");
982        }
983        mr_free(command);
984        chdir(old_pwd);
985    }
986    mr_free(tmp);
987
988    mr_asprintf(&command, "cp -f %s/LAST-FILELIST-NUMBER %s", bkpinfo->tmpdir,
989            bkpinfo->scratchdir);
990    if (run_program_and_log_output(command, FALSE)) {
991        fatal_error("Failed to copy LAST-FILELIST-NUMBER to scratchdir");
992    }
993    mr_free(command);
994
995    tmp = call_program_and_get_last_line_of_output("which mondorestore");
996    if (!tmp) {
997        fatal_error
998            ("'which mondorestore' returned null. Where's your mondorestore? `which` can't find it. That's odd. Did you install mondorestore?");
999    }
1000    mr_asprintf(&command, "cp -f %s %s", tmp, bkpinfo->tmpdir);
1001    mr_free(tmp);
1002
1003    if (run_program_and_log_output(command, FALSE)) {
1004        fatal_error("Failed to copy mondorestore to tmpdir");
1005    }
1006    mr_free(command);
1007
1008    mr_asprintf(&command, "hostname > %s/HOSTNAME", bkpinfo->scratchdir);
1009    paranoid_system(command);
1010    mr_free(command);
1011
1012    if (bkpinfo->postnuke_tarball) {
1013        mr_asprintf(&command, "cp -f %s %s/post-nuke.tgz",
1014                bkpinfo->postnuke_tarball, bkpinfo->tmpdir);
1015        if (run_program_and_log_output(command, FALSE)) {
1016            fatal_error("Unable to copy post-nuke tarball to tmpdir");
1017        }
1018        mr_free(command);
1019    }
1020
1021    mvaddstr_and_log_it(g_currentY++, 74, "Done.");
1022}
1023
1024
1025/**
1026 * Store the client's NFS configuration in files to be restored at restore-time.
1027 * Assumes that @c bkpinfo->media_type = nfs, but does not check for this.
1028 * @param bkpinfo The backup information structure. Fields used:
1029 * - @c nfs_mount
1030 * - @c nfs_remote_dir
1031 * - @c tmpdir
1032 */
1033void store_nfs_config(struct s_bkpinfo *bkpinfo)
1034{
1035
1036    /*@ buffers ******** */
1037    char *nfs_dev = NULL;
1038    char *mac_addr = NULL;
1039    char *nfs_mount = NULL;
1040    char *nfs_client_ipaddr = NULL;
1041    char *nfs_client_netmask = NULL;
1042    char *nfs_client_broadcast = NULL;
1043    char *nfs_client_defgw = NULL;
1044    char *nfs_server_ipaddr = NULL;
1045    char *tmp = NULL;
1046    char *command = NULL;
1047
1048    FILE *fd1 = NULL;
1049
1050    /*@ pointers ***** */
1051    char *p;
1052
1053    log_it("Storing NFS configuration");
1054    mr_asprintf(&tmp, bkpinfo->nfs_mount);
1055    p = strchr(tmp, ':');
1056    if (!p) {
1057        fatal_error
1058            ("NFS mount doesn't have a colon in it, e.g. 192.168.1.4:/home/nfs");
1059    }
1060    *(p++) = '\0';
1061    mr_asprintf(&nfs_server_ipaddr, tmp);
1062    mr_free(tmp);
1063
1064    mr_asprintf(&nfs_mount, p);
1065    /* BERLIOS : there is a bug #67 here as it only considers the first NIC */
1066    mr_asprintf(&command,
1067            "ifconfig | tr '\n' '#' | sed s/##// | tr '#' ' ' | tr '' '\n' | head -n1 | cut -d' ' -f1");
1068    nfs_dev = call_program_and_get_last_line_of_output(command);
1069    mr_free(command);
1070
1071    mr_asprintf(&command,
1072            "ifconfig | tr '\n' '#' | sed s/##// | tr '#' ' ' | tr '' '\\n' | head -n1 | tr -s '\t' ' ' | cut -d' ' -f7 | cut -d':' -f2");
1073    nfs_client_ipaddr = call_program_and_get_last_line_of_output(command);
1074    mr_free(command);
1075
1076    mr_asprintf(&command,
1077            "ifconfig | tr '\n' '#' | sed s/##// | tr '#' ' ' | tr '' '\\n' | head -n1 | tr -s '\t' ' ' | cut -d' ' -f9 | cut -d':' -f2");
1078    nfs_client_netmask = call_program_and_get_last_line_of_output(command);
1079    mr_free(command);
1080
1081    mr_asprintf(&command,
1082            "ifconfig | tr '\n' '#' | sed s/##// | tr '#' ' ' | tr '' '\\n' | head -n1 | tr -s '\t' ' ' | cut -d' ' -f8 | cut -d':' -f2");
1083    nfs_client_broadcast = call_program_and_get_last_line_of_output(command);
1084    mr_free(command);
1085
1086    mr_asprintf(&command,
1087            "route -n | grep '^0.0.0.0' | awk '{print $2}'");
1088    nfs_client_defgw = call_program_and_get_last_line_of_output(command);
1089    mr_free(command);
1090
1091    mr_asprintf(&tmp,
1092            "nfs_client_ipaddr=%s; nfs_client_netmask=%s; nfs_server_ipaddr=%s; nfs_mount=%s; nfs_client_defgw=%s;  ",
1093            nfs_client_ipaddr, nfs_client_netmask, nfs_server_ipaddr, nfs_mount, nfs_client_defgw);
1094    mr_free(nfs_mount);
1095    log_it(tmp);
1096    mr_free(tmp);
1097
1098    if (strlen(nfs_dev) < 2) {
1099        fatal_error
1100            ("Unable to find ethN (eth0, eth1, ...) adapter via NFS mount you specified.");
1101    }
1102    /********
1103    * If the NFS device that found above is a bonded device,
1104    * we need to replace it with an ethN device or the
1105    * networking will not start during an NFS restore.
1106    *
1107    * If the NFS device in nfs_dev begins with the word "bond",
1108    * look for the corresponding slave ethN device and copy it to nfs_dev.
1109    * Using the common MAC address
1110    ********/
1111    if (!strncmp(nfs_dev, "bond", 4)) {
1112        log_to_screen("Found bonding device %s; looking for corresponding ethN slave device\n", nfs_dev);
1113        mr_asprintf(&command,
1114                "ifconfig %s | awk '{print $5}' | head -n1", nfs_dev);
1115        mac_addr = call_program_and_get_last_line_of_output(command);
1116        mr_free(command);
1117
1118        mr_asprintf(&command,
1119                "ifconfig | grep -E '%s' | grep -v '%s' | head -n1  | cut -d' ' -f1", mac_addr, nfs_dev);
1120        mr_free(nfs_dev);
1121        nfs_dev = call_program_and_get_last_line_of_output(command);
1122        mr_free(command);
1123        mr_free(mac_addr);
1124
1125        log_to_screen("Replacing it with %s\n", nfs_dev);
1126    }
1127
1128    mr_free(nfs_dev);
1129    fd1 = mr_fopen(MONDORESTORECFG, "a");
1130    mr_fprintf(fd1, "nfs-dev %s\n", nfs_dev);
1131    mr_fprintf(fd1, "nfs-client-ipaddr %s\n", nfs_client_ipaddr);
1132    mr_fprintf(fd1, "nfs-client-netmask %s\n", nfs_client_netmask);
1133    mr_fprintf(fd1, "nfs-client-broadcast %s\n", nfs_client_broadcast);
1134    mr_fprintf(fd1, "nfs-client-defgw %s\n", nfs_client_defgw);
1135    mr_fprintf(fd1, "nfs-server-ipaddr %s\n", nfs_server_ipaddr);
1136    mr_fprintf(fd1, "nfs-server-mount %s\n", bkpinfo->nfs_mount);
1137    mr_fprintf(fd1, "nfs-server-path %s\n", bkpinfo->nfs_remote_dir);
1138    mr_fprintf(fd1, "iso-prefix %s\n", bkpinfo->prefix);
1139    mr_fclose(fd1);
1140
1141    log_it("Finished storing NFS configuration");
1142}
1143
1144
1145/**
1146 * Determine the approximate number of media that the backup will take up,
1147 * and tell the user. The uncompressed size is estimated as size_of_all_biggiefiles_K()
1148 * plus (noof_sets x bkpinfo->optimal_set_size). The compression factor is estimated as
1149 * 2/3 for LZO and 1/2 for bzip2. The data is not saved anywhere. If there are any
1150 * "imagedevs", the estimate is not shown as it will be wildly inaccurate.
1151 * If there are more than 50 media estimated, the estimate will not be shown.
1152 * @param bkpinfo The backup information structure. Fields used:
1153 * - @c bkpinfo->backup_media_type
1154 * - @c bkpinfo->image_devs
1155 * - @c bkpinfo->media_size
1156 * - @c bkpinfo->optimal_set_size
1157 * - @c bkpinfo->use_lzo
1158 * @param noof_sets The number of filesets created.
1159 * @ingroup archiveGroup
1160 */
1161void
1162estimate_noof_media_required(struct s_bkpinfo *bkpinfo, long noof_sets)
1163{
1164    /*@ buffers *************** */
1165    char *tmp = NULL;
1166
1167    /*@ long long ************* */
1168    long long scratchLL;
1169
1170    if (bkpinfo->media_size[1] <= 0 || bkpinfo->backup_media_type == nfs) {
1171        log_to_screen("Number of media required: UNKNOWN");
1172        return;
1173    }
1174
1175    log_it("Estimating number of media required...");
1176    scratchLL =
1177        (long long) (noof_sets) * (long long) (bkpinfo->optimal_set_size)
1178        + (long long) (size_of_all_biggiefiles_K(bkpinfo));
1179    scratchLL = (scratchLL / 1024) / bkpinfo->media_size[1];
1180    scratchLL++;
1181    if (bkpinfo->use_lzo) {
1182        scratchLL = (scratchLL * 2) / 3;
1183    } else if (bkpinfo->use_gzip) {
1184        scratchLL = (scratchLL * 2) / 3;
1185    } else {
1186        scratchLL = scratchLL / 2;
1187    }
1188    if (!scratchLL) {
1189        scratchLL++;
1190    }
1191    if (scratchLL <= 1) {
1192        mr_asprintf(&tmp,
1193                _("Your backup will probably occupy a single %s. Maybe two."),
1194                bkpinfo->backup_media_string);
1195    } else {
1196        mr_asprintf(&tmp, _("Your backup will occupy approximately %s media."),
1197                number_to_text((int) (scratchLL + 1)));
1198    }
1199    if (!bkpinfo->image_devs && (scratchLL < 50)) {
1200        log_to_screen(tmp);
1201    }
1202    mr_free(tmp);
1203    return;
1204}
1205
1206
1207/**
1208 * Determine whether a file is compressed. This is done
1209 * by reading through the "do-not-compress-these" file distributed with Mondo.
1210 * @param filename The file to check.
1211 * @return TRUE if it's compressed, FALSE if not.
1212 */
1213bool is_this_file_compressed(char *filename)
1214{
1215    char *do_not_compress_these = NULL;
1216    char *tmp = NULL;
1217    char *p = NULL;
1218
1219    mr_asprintf(&tmp, "%s/do-not-compress-these", g_mondo_home);
1220    if (!does_file_exist(tmp)) {
1221        mr_free(tmp);
1222        return (FALSE);
1223    }
1224    mr_free(tmp);
1225
1226    do_not_compress_these = last_line_of_file(tmp);
1227    for (p = do_not_compress_these; p != NULL; p++) {
1228        mr_asprintf(&tmp, p);
1229        if (strchr(tmp, ' ')) {
1230            *(strchr(tmp, ' ')) = '\0';
1231        }
1232        if (!strcmp(strrchr(filename, '.'), tmp)) {
1233            mr_free(do_not_compress_these);
1234            mr_free(tmp);
1235            return (TRUE);
1236        }
1237        mr_free(tmp);
1238
1239        if (!(p = strchr(p, ' '))) {
1240            break;
1241        }
1242    }
1243    mr_free(do_not_compress_these);
1244    return (FALSE);
1245}
1246
1247
1248int mode_of_file(char *fname)
1249{
1250    struct stat buf;
1251
1252    if (lstat(fname, &buf)) {
1253        return (-1);
1254    }                           // error
1255    else {
1256        return (buf.st_mode);
1257    }
1258}
1259
1260
1261/**
1262 * Create a small script that mounts /boot, calls @c grub-install, and syncs the disks.
1263 * @param outfile Where to put the script.
1264 * @return 0 for success, 1 for failure.
1265 */
1266int make_grub_install_scriptlet(char *outfile)
1267{
1268    FILE *fout = NULL;
1269    char *tmp = NULL;
1270    int retval = 0;
1271
1272    if ((fout = fopen(outfile, "w"))) {
1273        fprintf(fout,
1274                "#!/bin/sh\n\nmount /boot > /dev/null 2> /dev/null\ngrub-install $@\nres=$?\nsync;sync;sync\nexit $res\n");
1275        paranoid_fclose(fout);
1276        mr_msg(2, "Created %s", outfile);
1277        mr_asprintf(&tmp, "chmod +x %s", outfile);
1278        paranoid_system(tmp);
1279        mr_free(tmp);
1280
1281        retval = 0;
1282    } else {
1283        retval = 1;
1284    }
1285    return (retval);
1286}
1287
1288/* @} - end fileGroup */
Note: See TracBrowser for help on using the repository browser.