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

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

merge -r1082:1105 $SVN_M/branches/stable

  • Property svn:keywords set to Id
File size: 33.8 KB
Line 
1/*  $Id: libmondo-files.c 1106 2007-02-07 22:55:11Z 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 1106 2007-02-07 22:55:11Z 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    char *command;
48    char *tmp;
49    size_t n = 0;
50
51    /*@ pointers **************************************************** */
52    char *p;
53    FILE *fin;
54
55    /*@ initialize pointers ***************************************** */
56
57    p = output;
58
59    /*@************************************************************** */
60
61    assert_string_is_neither_NULL_nor_zerolength(filename);
62
63    if (does_file_exist(filename)) {
64        mr_asprintf(&command, "md5sum \"%s\"", filename);
65        fin = popen(command, "r");
66        mr_free(command);
67
68        if (fin) {
69            mr_getline(&output, &n, fin);
70            p = strchr(output, ' ');
71            paranoid_pclose(fin);
72        }
73    } else {
74        mr_asprintf(&tmp, "File '%s' not found; cannot calc checksum",
75                filename);
76        log_it(tmp);
77        mr_free(tmp);
78    }
79    if (p) {
80        *p = '\0';
81    }
82    return (output);
83}
84
85
86/**
87 * Get the number of lines in @p filename.
88 * @param filename The file to count lines in.
89 * @return The number of lines in @p filename.
90 * @bug This function uses the shell and "wc -l"; it should probably be rewritten in C.
91 */
92long count_lines_in_file(char *filename)
93{
94
95    /*@ buffers ***************************************************** */
96    char *command;
97    char *incoming = NULL;
98    char *tmp;
99
100    /*@ long ******************************************************** */
101    long noof_lines = -1L;
102
103    /*@ int ******************************************************** */
104    size_t n = 0;
105
106    /*@ pointers **************************************************** */
107    FILE *fin;
108
109    assert_string_is_neither_NULL_nor_zerolength(filename);
110    if (!does_file_exist(filename)) {
111        mr_asprintf(&tmp,
112                "%s does not exist, so I cannot found the number of lines in it",
113                filename);
114        log_it(tmp);
115        mr_free(tmp);
116        return (0);
117    }
118    mr_asprintf(&command, "cat %s | wc -l", filename);
119    if (!does_file_exist(filename)) {
120        return (-1);
121    }
122    fin = popen(command, "r");
123    mr_free(command);
124
125    if (fin) {
126        if (feof(fin)) {
127            noof_lines = 0;
128        } else {
129            mr_getline(&incoming, &n, fin);
130            while (strlen(incoming) > 0
131                   && incoming[strlen(incoming) - 1] < 32) {
132                incoming[strlen(incoming) - 1] = '\0';
133            }
134            noof_lines = atol(incoming);
135            mr_free(incoming);
136        }
137        paranoid_pclose(fin);
138    }
139    return (noof_lines);
140}
141
142
143/**
144 * Check for existence of given @p filename.
145 * @param filename The file to check for.
146 * @return TRUE if it exists, FALSE otherwise.
147 */
148bool does_file_exist(char *filename)
149{
150
151    /*@ structures ************************************************** */
152    struct stat buf;
153
154    /*@************************************************************** */
155
156    assert(filename != NULL);
157
158    if (lstat(filename, &buf)) {
159        mr_msg(20, "%s does not exist", filename);
160        return (FALSE);
161    } else {
162        mr_msg(20, "%s exists", filename);
163        return (TRUE);
164    }
165}
166
167
168/**
169 * Modify @p inout (a file containing a list of files) to only contain files
170 * that exist.
171 * @param inout The filelist to operate on.
172 * @note The original file is renamed beforehand, so it will not be accessible
173 * while the modification is in progress.
174 */
175void exclude_nonexistent_files(char *inout)
176{
177    char *infname;
178    char *outfname;
179    char *tmp;
180    char *incoming = NULL;
181
182    /*@ int ********************************************************* */
183    int i;
184    size_t n = 0;
185
186    /*@ pointers **************************************************** */
187    FILE *fin, *fout;
188
189
190    /*@ end vars *********************************************************** */
191
192    assert_string_is_neither_NULL_nor_zerolength(inout);
193
194    mr_asprintf(&infname, "%s.in", inout);
195
196    mr_asprintf(&tmp, "cp -f %s %s", inout, infname);
197    run_program_and_log_output(tmp, FALSE);
198    mr_free(tmp);
199
200    if (!(fin = fopen(infname, "r"))) {
201        log_OS_error("Unable to openin infname");
202        mr_free(infname);
203        return;
204    }
205
206    mr_asprintf(&outfname, "%s", inout);
207    if (!(fout = fopen(outfname, "w"))) {
208        log_OS_error("Unable to openout outfname");
209        mr_free(outfname);
210        return;
211    }
212    mr_free(outfname);
213
214    for (mr_getline(&incoming, &n, fin); !feof(fin);
215         mr_getline(&incoming, &n, fin)) {
216        i = strlen(incoming) - 1;
217        if (i >= 0 && incoming[i] < 32) {
218            incoming[i] = '\0';
219        }
220        if (does_file_exist(incoming)) {
221            fprintf(fout, "%s\n", incoming);
222        } else {
223            mr_asprintf(&tmp, "Excluding '%s'-nonexistent\n", incoming);
224            log_it(tmp);
225            mr_free(tmp);
226        }
227    }
228    mr_free(incoming);
229    paranoid_fclose(fout);
230    paranoid_fclose(fin);
231    unlink(infname);
232    mr_free(infname);
233}
234
235
236/**
237 * Attempt to find the user's kernel by calling Mindi.
238 * If Mindi can't find the kernel, ask user. If @p kernel is not empty,
239 * don't do anything.
240 * @param kernel Where to put the found kernel.
241 * @return 0 for success, 1 for failure.
242 */
243int figure_out_kernel_path_interactively_if_necessary(char *kernel)
244{
245    char *tmp = NULL;
246    char *command = NULL;
247
248    if (kernel == NULL) {
249        kernel = call_program_and_get_last_line_of_output
250               ("mindi --findkernel 2> /dev/null");
251    }
252    // If we didn't get anything back, check whether mindi raised a fatal error
253    if (kernel == NULL) {
254        mr_asprintf(&command, "grep 'Fatal error' /var/log/mindi.log");
255        tmp = call_program_and_get_last_line_of_output(command);
256        if (strlen(tmp) > 1) {
257            popup_and_OK(tmp);
258            fatal_error("Mindi gave a fatal error. Please check '/var/log/mindi.log'.");
259        }
260        mr_free(command);
261        mr_free(tmp);
262    }
263
264    if (kernel != NULL) {
265        log_it("Calling Mindi with kernel path of '%s'", kernel);
266    } else {
267        log_it("Calling Mindi without kernel, so asking one");
268    }
269
270    while (kernel == NULL) {
271        if (!ask_me_yes_or_no
272            (_("Kernel not found or invalid. Choose another?"))) {
273            return (1);
274        }
275        if (!popup_and_get_string
276            (_("Kernel path"),
277             _("What is the full path and filename of your kernel, please?"),
278             kernel)) {
279            fatal_error
280                ("Kernel not found. Please specify with the '-k' flag.");
281        }
282        log_it("User says kernel is at %s", kernel);
283    }
284    return (0);
285}
286
287
288/**
289 * Find location of specified executable in user's PATH.
290 * @param fname The basename of the executable to search for (e.g. @c afio).
291 * @return The full path to the executable, or "" if it does not exist, or NULL if @c file could not be found.
292 * @note The returned string points to static storage that will be overwritten with each call.
293 * @bug The checks with @c file and @c dirname seem pointless. If @c incoming is "", then you're calling
294 * <tt>dirname 2\>/dev/null</tt> or <tt>file 2\>/dev/null | cut -d':' -f1 2\>/dev/null</tt>, which basically amounts
295 * to nothing.
296 */
297char *find_home_of_exe(char *fname)
298{
299    /*@ buffers ********************* */
300    char *output = NULL;
301    char *incoming = NULL;
302    char *command = NULL;
303
304    /*@******************************* */
305
306    assert_string_is_neither_NULL_nor_zerolength(fname);
307
308    mr_asprintf(&command, "which %s 2> /dev/null", fname);
309    incoming = call_program_and_get_last_line_of_output(command);
310    mr_free(command);
311
312    if (incoming == NULL) {
313        if (system("which file > /dev/null 2> /dev/null")) {
314            return (NULL);      // forget it :)
315        }
316        mr_asprintf(&command,
317                "file %s 2> /dev/null | cut -d':' -f1 2> /dev/null",
318                incoming);
319        mr_free(incoming);
320
321        incoming = call_program_and_get_last_line_of_output(command);
322        mr_free(command);
323    }
324    if (incoming == NULL)   // yes, it is == '\0' twice, not once :)
325    {
326        mr_asprintf(&command, "dirname %s 2> /dev/null", incoming);
327        mr_free(incoming);
328
329        incoming = call_program_and_get_last_line_of_output(command);
330        mr_free(command);
331    }
332    output = incoming;
333
334    if (output != NULL && does_file_exist(output)) {
335        mr_msg(4, "find_home_of_exe () --- Found %s at %s", fname, output);
336    } else {
337        mr_free(output);
338        mr_msg(4, "find_home_of_exe() --- Could not find %s", fname);
339    }
340    return (output);
341}
342
343
344/**
345 * Get the last sequence of digits surrounded by non-digits in the first 32k of
346 * a file.
347 * @param logfile The file to look in.
348 * @return The number found, or 0 if none.
349 */
350int get_trackno_from_logfile(char *logfile)
351{
352
353    /*@ pointers ********************************************************* */
354    FILE *fin;
355
356    /*@ int ************************************************************** */
357    int trackno = 0;
358    size_t len = 0;
359
360    /*@ buffer ************************************************************ */
361    char datablock[32701];
362
363    assert_string_is_neither_NULL_nor_zerolength(logfile);
364
365    if (!(fin = fopen(logfile, "r"))) {
366        log_OS_error("Unable to open logfile");
367        fatal_error("Unable to open logfile to read trackno");
368    }
369    len = fread(datablock, 1, 32700, fin);
370    paranoid_fclose(fin);
371    if (len <= 0) {
372        return (0);
373    }
374    for (; len > 0 && !isdigit(datablock[len - 1]); len--);
375    datablock[len--] = '\0';
376    for (; len > 0 && isdigit(datablock[len - 1]); len--);
377    trackno = atoi(datablock + len);
378    return (trackno);
379}
380
381
382/**
383 * Get a percentage from the last line of @p filename. We look for the string
384 * "% done" on the last line and, if we find it, grab the number before the last % sign.
385 * @param filename The file to get the percentage from.
386 * @return The percentage found, or 0 for error.
387 */
388int grab_percentage_from_last_line_of_file(char *filename)
389{
390
391    char *lastline = NULL;
392    char *command = NULL;
393    char *p = NULL;
394    int i;
395
396    for (i = g_noof_log_lines - 1;
397         i >= 0 && !strstr(err_log_lines[i], "% Done")
398         && !strstr(err_log_lines[i], "% done"); i--);
399    if (i < 0) {
400        mr_asprintf(&command,
401                "tail -n3 %s | grep -Fi \"%c\" | tail -n1 | awk '{print $0;}'",
402                filename, '%');
403        lastline = call_program_and_get_last_line_of_output(command);
404        mr_free(command);
405        if (!lastline) {
406            return (0);
407        }
408    } else {
409        mr_asprintf(&lastline, err_log_lines[i]);
410    }
411
412    p = strrchr(lastline, '%');
413    if (p) {
414        *p = '\0';
415    }
416    if (!p) {
417        mr_free(lastline);
418        return (0);
419    }
420    *p = '\0';
421    for (p--; *p != ' ' && p != lastline; p--);
422    if (p != lastline) {
423        p++;
424    }
425    i = atoi(p);
426    mr_free(lastline);
427
428    return (i);
429}
430
431
432/**
433 * Return the last line of @p filename.
434 * @param filename The file to get the last line of.
435 * @return The last line of the file.
436 * @note The returned string points to static storage that will be overwritten with each call.
437 */
438char *last_line_of_file(char *filename)
439{
440    /*@ buffers ***************************************************** */
441    char *output = NULL;
442    char *command = NULL;
443    char *tmp = NULL;
444
445    /*@ pointers **************************************************** */
446    FILE *fin;
447    size_t n = 0;
448
449    /*@ end vars **************************************************** */
450
451    if (!does_file_exist(filename)) {
452        mr_asprintf(&tmp, _("Tring to get last line of nonexistent file (%s)"),
453                filename);
454        log_it(tmp);
455        mr_free(tmp);
456        return (NULL);
457    }
458    mr_asprintf(&command, "tail -n1 %s", filename);
459    fin = popen(command, "r");
460    mr_free(command);
461
462    mr_getline(&output, &n, fin);
463    paranoid_pclose(fin);
464    while (strlen(output) > 0 && output[strlen(output) - 1] < 32) {
465        output[strlen(output) - 1] = '\0';
466    }
467    return (output);
468}
469
470
471/**
472 * Get the length of @p filename in bytes.
473 * @param filename The file to get the length of.
474 * @return The length of the file, or -1 for error.
475 */
476off_t length_of_file(char *filename)
477{
478    /*@ pointers *************************************************** */
479    FILE *fin;
480
481    /*@ long long ************************************************* */
482    off_t length;
483
484    fin = fopen(filename, "r");
485    if (!fin) {
486        log_it("filename=%s", filename);
487        log_OS_error("Unable to openin filename");
488        return (-1);
489    }
490    fseeko(fin, 0, SEEK_END);
491    length = ftello(fin);
492    paranoid_fclose(fin);
493    return (length);
494}
495
496
497/**
498 * Create the directory @p outdir_fname and all parent directories. Equivalent to <tt>mkdir -p</tt>.
499 * @param outdir_fname The directory to create.
500 * @return The return value of @c mkdir.
501 */
502/* BERLIOS: This function shouldn't call system at all */
503int make_hole_for_dir(char *outdir_fname)
504{
505    char *tmp;
506    int res = 0;
507
508    assert_string_is_neither_NULL_nor_zerolength(outdir_fname);
509    mr_asprintf(&tmp, "mkdir -p %s", outdir_fname);
510    res = system(tmp);
511    mr_free(tmp);
512    return (res);
513}
514
515
516/**
517 * Create the parent directories of @p outfile_fname.
518 * @param outfile_fname The file to make a "hole" for.
519 * @return 0, always.
520 * @bug Return value unnecessary.
521 */
522/* BERLIOS: This function shouldn't call system at all */
523int make_hole_for_file(char *outfile_fname)
524{
525    /*@ buffer ****************************************************** */
526    char *command;
527
528    /*@ int  ******************************************************** */
529    int res = 0;
530
531    /*@ end vars *************************************************** */
532
533    assert_string_is_neither_NULL_nor_zerolength(outfile_fname);
534    assert(!strstr(outfile_fname, MNT_CDROM));
535    assert(!strstr(outfile_fname, "/dev/cdrom"));
536
537    mr_asprintf(&command, "mkdir -p \"%s\" 2> /dev/null", outfile_fname);
538    res += system(command);
539    mr_free(command);
540
541    mr_asprintf(&command, "rmdir \"%s\" 2> /dev/null", outfile_fname);
542    res += system(command);
543    mr_free(command);
544
545    mr_asprintf(&command, "rm -f \"%s\" 2> /dev/null", outfile_fname);
546    res += system(command);
547    mr_free(command);
548    unlink(outfile_fname);
549    return (0);
550}
551
552
553/**
554 * Get the number of lines in @p filelist_fname that contain the string @p wildcard.
555 * @param filelist_fname The file to search through.
556 * @param wildcard The string to search for. This is @e not a shell glob or a regular expression.
557 * @return The number of lines matched.
558 */
559long noof_lines_that_match_wildcard(char *filelist_fname, char *wildcard)
560{
561    /*@ long ******************************************************* */
562    long matches = 0;
563
564    /*@ pointers *************************************************** */
565    FILE *fin;
566
567    /*@ buffers **************************************************** */
568    char *incoming = NULL;
569
570    size_t n = 0;
571    /*@ end vars *************************************************** */
572
573
574    fin = fopen(filelist_fname, "r");
575
576    if (!fin) {
577        log_OS_error("Unable to openin filelist_fname");
578        return (0);
579    }
580    mr_getline(&incoming, &n, fin);
581    while (!feof(fin)) {
582        if (strstr(incoming, wildcard)) {
583            matches++;
584        }
585        mr_getline(&incoming, &n, fin);
586    }
587    paranoid_fclose(fin);
588    mr_free(incoming);
589    return (matches);
590}
591
592
593/**
594 * Register our PID in a file in /var/run.
595 * The PID will be put in /var/run/monitas-<tt>name_str</tt>.pid.
596 * @param pid 0 to remove file, anything else to create it.
597 * @param name_str The basename of the PID file (e.g. "mondo" or "server")
598 * @note This function does not provide support against multiple instances, unless you check for that yourself.
599 */
600void register_pid(pid_t pid, char *name_str)
601{
602    char *tmp;
603    char *lockfile_fname;
604    int res;
605    size_t n = 0;
606    FILE *fin;
607
608    mr_asprintf(&lockfile_fname, "/var/run/monitas-%s.pid", name_str);
609    if (!pid) {
610        log_it("Unregistering PID");
611        if (unlink(lockfile_fname)) {
612            log_it("Error unregistering PID");
613        }
614        mr_free(lockfile_fname);
615        return;
616    }
617    if (does_file_exist(lockfile_fname)) {
618        if ((fin = fopen(lockfile_fname, "r"))) {
619            mr_getline(&tmp, &n, fin);
620            paranoid_fclose(fin);
621        } else {
622            log_OS_error("Unable to openin lockfile_fname");
623        }
624        pid = (pid_t) atol(tmp);
625        mr_free(tmp);
626
627        mr_asprintf(&tmp, "ps %ld > /dev/null 2> /dev/null", (long int) pid);
628        res = system(tmp);
629        mr_free(tmp);
630        if (!res) {
631            log_it
632                ("I believe the daemon is already running. If it isn't, please delete %s and try again.",
633                 lockfile_fname);
634        }
635    }
636    mr_asprintf(&tmp, "echo %ld > %s 2> /dev/null", (long int) getpid(),
637            lockfile_fname);
638    mr_free(lockfile_fname);
639
640    if (system(tmp)) {
641        fatal_error("Cannot register PID");
642    }
643    mr_free(tmp);
644    return;
645}
646
647
648/**
649 * Determine the size (in KB) of @p dev in the mountlist in <tt>tmpdir</tt>/mountlist.txt.
650 * @param tmpdir The tempdir where the mountlist is stored.
651 * @param dev The device to search for.
652 * @return The size of the partition in KB.
653 */
654long size_of_partition_in_mountlist_K(char *tmpdir, char *dev)
655{
656    char *command = NULL;
657    char *sz_res = NULL;
658    long file_len_K = 0L;
659
660    mr_asprintf(&command,
661            "grep '%s ' %s/mountlist.txt | head -n1 | awk '{print $4;}'",
662            dev, tmpdir);
663    log_it(command);
664    sz_res = call_program_and_get_last_line_of_output(command);
665    file_len_K = atol(sz_res);
666    mr_msg(4, "%s --> %s --> %ld", command, sz_res, file_len_K);
667    mr_free(command);
668    mr_free(sz_res);
669    return (file_len_K);
670}
671
672
673/**
674 * Calculate the total size (in KB) of all the biggiefiles in this backup.
675 * @param bkpinfo The backup information structure. Only the @c bkpinfo->tmpdir field is used.
676 * @return The total size of all biggiefiles in KB.
677 */
678long size_of_all_biggiefiles_K(struct s_bkpinfo *bkpinfo)
679{
680    char *fname = NULL;
681    char *biggielist = NULL;
682    char *comment = NULL;
683    char *tmp = NULL;
684    char *command = NULL;
685
686    /*@ long ******************************************************** */
687    long scratchL = 0L;
688    long file_len_K = 0L;
689
690    /*@ pointers *************************************************** */
691    FILE *fin = NULL;
692    size_t n = 0;
693
694    /*@ end vars *************************************************** */
695
696    log_it("Calculating size of all biggiefiles (in total)");
697    mr_asprintf(&biggielist, "%s/biggielist.txt", bkpinfo->tmpdir);
698    log_it("biggielist = %s", biggielist);
699    if (!(fin = fopen(biggielist, "r"))) {
700        log_OS_error
701            ("Cannot open biggielist. OK, so estimate is based on filesets only.");
702    } else {
703        mr_msg(4, "Reading it...");
704        for (mr_getline(&fname, &n, fin); !feof(fin);
705             mr_getline(&fname, &n, fin)) {
706            if (fname[strlen(fname) - 1] <= 32) {
707                fname[strlen(fname) - 1] = '\0';
708            }
709            if (0 == strncmp(fname, "/dev/", 5)) {
710                if (is_dev_an_NTFS_dev(fname)) {
711                    tmp = find_home_of_exe("ntfsresize");
712                    if (!tmp) {
713                        fatal_error("ntfsresize not found");
714                    }
715                    mr_free(tmp);
716
717                    mr_asprintf(&command, "ntfsresize --force --info %s|grep '^You might resize at '|cut -d' ' -f5", fname);
718                    log_it("command = %s", command);
719                    tmp = call_program_and_get_last_line_of_output(command);
720                    mr_free(command);
721
722                    log_it("res of it = %s", tmp);
723                    file_len_K = atoll(tmp) / 1024L;
724                    mr_free(tmp);
725                } else {
726                    file_len_K = get_phys_size_of_drive(fname) * 1024L;
727                }
728            } else {
729                /* BERLIOS: more than long here ??? */
730                file_len_K = (long) (length_of_file(fname) / 1024);
731            }
732            if (file_len_K > 0) {
733                scratchL += file_len_K;
734                mr_msg(4, "%s --> %ld K", fname, file_len_K);
735            }
736            mr_asprintf(&comment,
737                    "After adding %s, scratchL+%ld now equals %ld", fname,
738                    file_len_K, scratchL);
739            mr_msg(4, comment);
740            mr_free(comment);
741
742            if (feof(fin)) {
743                break;
744            }
745        }
746        mr_free(fname);
747    }
748    mr_free(biggielist);
749
750    log_it("Closing...");
751    paranoid_fclose(fin);
752    log_it("Finished calculating total size of all biggiefiles");
753    return (scratchL);
754}
755
756
757/**
758 * Determine the amount of space (in KB) occupied by a mounted CD.
759 * This can also be used to find the space used for other directories.
760 * @param mountpt The mountpoint/directory to check.
761 * @return The amount of space occupied in KB.
762 */
763long long space_occupied_by_cd(char *mountpt)
764{
765    /*@ buffer ****************************************************** */
766    char *tmp = NULL;
767    char *command = NULL;
768    long long llres;
769    size_t n = 0;
770    /*@ pointers **************************************************** */
771    char *p = NULL;
772    FILE *fin = NULL;
773
774    /*@ end vars *************************************************** */
775
776    mr_asprintf(&command, "du -sk %s", mountpt);
777    errno = 0;
778    fin = popen(command, "r");
779    if (errno) {
780      log_it("popen() FAILED: command=%s, mountpt=%s, fin=%d, errno=%d, strerror=%s", command, mountpt, fin, errno, strerror(errno));
781      llres = 0;
782    } else {
783        mr_getline(&tmp, &n, fin);
784        paranoid_pclose(fin);
785        p = strchr(tmp, '\t');
786        if (p) {
787            *p = '\0';
788        }
789        for (p = tmp, llres = 0; *p != '\0'; p++) {
790            llres *= 10;
791            llres += (int) (*p - '0');
792        }
793    }
794
795    mr_free(command);
796    mr_free(tmp);
797    return (llres);
798}
799
800
801/**
802 * Update a CRC checksum to include another character.
803 * @param crc The original CRC checksum.
804 * @param c The character to add.
805 * @return The new CRC checksum.
806 * @ingroup utilityGroup
807 */
808unsigned int updcrc(unsigned int crc, unsigned int c)
809{
810    unsigned int tmp;
811    tmp = (crc >> 8) ^ c;
812    crc = (crc << 8) ^ crctttab[tmp & 255];
813    return crc;
814}
815
816
817/**
818 * Update a reverse CRC checksum to include another character.
819 * @param crc The original CRC checksum.
820 * @param c The character to add.
821 * @return The new CRC checksum.
822 * @ingroup utilityGroup
823 */
824unsigned int updcrcr(unsigned int crc, unsigned int c)
825{
826    unsigned int tmp;
827    tmp = crc ^ c;
828    crc = (crc >> 8) ^ crc16tab[tmp & 0xff];
829    return crc;
830}
831
832
833/**
834 * Check for an executable on the user's system; write a message to the
835 * screen and the log if we can't find it.
836 * @param fname The executable basename to look for.
837 * @return 0 if it's found, nonzero if not.
838 */
839int whine_if_not_found(char *fname)
840{
841    /*@ buffers *** */
842    char *command;
843    char *errorstr;
844    int res = 0;
845
846
847    mr_asprintf(&command, "which %s > /dev/null 2> /dev/null", fname);
848    res = system(command);
849    mr_free(command);
850
851    if (res) {
852        mr_asprintf(&errorstr,
853            _("Please install '%s'. I cannot find it on your system."),
854            fname);
855        log_to_screen(errorstr);
856        mr_free(errorstr);
857        log_to_screen
858            (_("There may be an hyperlink at http://www.mondorescue.org which"));
859        log_to_screen(_("will take you to the relevant (missing) package."));
860        return (1);
861    } else {
862        return (0);
863    }
864}
865
866
867/**
868 * Create a data file at @p fname containing @p contents.
869 * The data actually can be multiple lines, despite the name.
870 * @param fname The file to create.
871 * @param contents The data to put in it.
872 * @return 0 for success, 1 for failure.
873 */
874int write_one_liner_data_file(char *fname, char *contents)
875{
876    /*@ pointers *************************************************** */
877    FILE *fout;
878    int res = 0;
879
880    /*@ end vars *************************************************** */
881
882    assert_string_is_neither_NULL_nor_zerolength(fname);
883    if (!contents) {
884        log_it("%d: Warning - writing NULL to %s", __LINE__, fname);
885    }
886    if (!(fout = fopen(fname, "w"))) {
887        log_it("fname=%s");
888        log_OS_error("Unable to openout fname");
889        return (1);
890    }
891    fprintf(fout, "%s\n", contents);
892    paranoid_fclose(fout);
893    return (res);
894}
895
896
897/**
898 * Read @p fname into @p contents.
899 * @param fname The file to read.
900 * @param contents Where to put its contents.
901 * @return 0 for success, nonzero for failure.
902 */
903int read_one_liner_data_file(char *fname, char *contents)
904{
905    /*@ pointers *************************************************** */
906    FILE *fin;
907    int res = 0;
908    int i;
909
910    /*@ end vars *************************************************** */
911
912    assert_string_is_neither_NULL_nor_zerolength(fname);
913    if (!contents) {
914        log_it("%d: Warning - reading NULL from %s", __LINE__, fname);
915    }
916    if (!(fin = fopen(fname, "r"))) {
917        log_it("fname=%s", fname);
918        log_OS_error("Unable to openin fname");
919        return (1);
920    }
921    fscanf(fin, "%s\n", contents);
922    i = strlen(contents);
923    if (i > 0 && contents[i - 1] < 32) {
924        contents[i - 1] = '\0';
925    }
926    paranoid_fclose(fin);
927    return (res);
928}
929
930
931/**
932 * Copy the files that Mondo/Mindi need to run to the scratchdir or tempdir.
933 * Currently this includes: copy Mondo's home directory to scratchdir, untar "mondo_home/payload.tgz"
934 * if it exists, copy LAST-FILELIST-NUMBER to scratchdir, copy mondorestore
935 * and post-nuke.tgz (if it exists) to tmpdir, and run "hostname > scratchdir/HOSTNAME".
936 * @param bkpinfo The backup information structure. Fields used:
937 * - @c bkpinfo->postnuke_tarball
938 * - @c bkpinfo->scratchdir
939 * - @c bkpinfo->tmpdir
940 */
941void copy_mondo_and_mindi_stuff_to_scratchdir(struct s_bkpinfo *bkpinfo)
942{
943    /*@ Char buffers ** */
944    char *command;
945    char *tmp;
946    char old_pwd[MAX_STR_LEN];
947
948    mvaddstr_and_log_it(g_currentY, 0,
949                        "Copying Mondo's core files to the scratch directory");
950
951    /* BERLIOS: Why do we need to do it here as well ? */
952    mr_msg(4, "g_mondo_home='%s'", g_mondo_home);
953    if ((g_mondo_home == NULL) || strlen(g_mondo_home) < 2) {
954        mr_free(g_mondo_home);
955        g_mondo_home = find_and_store_mondoarchives_home();
956    }
957    mr_asprintf(&command, CP_BIN " --parents -pRdf %s %s", g_mondo_home,
958            bkpinfo->scratchdir);
959
960    mr_msg(4, "command = %s", command);
961    if (run_program_and_log_output(command, 1)) {
962        fatal_error("Failed to copy Mondo's stuff to scratchdir");
963    }
964    mr_free(command);
965
966    mr_asprintf(&tmp, "%s/payload.tgz", g_mondo_home);
967
968    /* i18n */
969    mr_asprintf(&command, CP_BIN " --parents /usr/share/locale/*/LC_MESSAGES/mondo.mo %s",bkpinfo->scratchdir);
970    mr_msg(4, "command = %s", command);
971    run_program_and_log_output(command, 1);
972    mr_free(command);
973
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_asprintf(&command,
1117                "ifconfig | grep -E '%s' | grep -v '%s' | head -n1  | cut -d' ' -f1", mac_addr);
1118        mr_free(nfs_dev);
1119        nfs_dev = call_program_and_get_last_line_of_output(command);
1120        mr_free(command);
1121        mr_free(mac_addr);
1122
1123        log_to_screen("Replacing it with %s\n", nfs_dev);
1124    }
1125
1126    mr_free(nfs_dev);
1127    mr_free(tmp);
1128
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;
1269    char *tmp;
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.