source: branches/stable/mondo/src/common/libmondo-files.c @ 1594

Last change on this file since 1594 was 1594, checked in by bruno, 12 years ago

Use of conf file entries (iso_burning_*, media_device, media_size)
and adapatation of the rest of the code to that (including bkpinfo)

  • Property svn:keywords set to Id
File size: 34.0 KB
Line 
1/* libmondo-files.c                                  file manipulation
2   $Id: libmondo-files.c 1594 2007-08-26 10:26:06Z bruno $
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
21#include "mr_mem.h"
22#include "mr_msg.h"
23#include "mr_file.h"
24#include "mr_gettext.h"
25
26/*@unused@*/
27//static char cvsid[] = "$Id: libmondo-files.c 1594 2007-08-26 10:26:06Z bruno $";
28
29extern char err_log_lines[NOOF_ERR_LINES][MAX_STR_LEN];
30
31extern int g_currentY;
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[MAX_STR_LEN];
47
48    char *command = NULL;
49    char *tmp = NULL;
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            (void) fgets(output, MAX_STR_LEN, 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 = NULL;
97    char *incoming = NULL;
98    char *tmp = NULL;
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 = NULL;
178    char *outfname = NULL;
179    char *tmp = NULL;
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(infname);
210        mr_free(outfname);
211        return;
212    }
213    mr_free(outfname);
214
215    for (mr_getline(&incoming, &n, fin); !feof(fin);
216         mr_getline(&incoming, &n, fin)) {
217        i = strlen(incoming) - 1;
218        if (i >= 0 && incoming[i] < 32) {
219            incoming[i] = '\0';
220        }
221        if (does_file_exist(incoming)) {
222            fprintf(fout, "%s\n", incoming);
223        } else {
224            mr_asprintf(&tmp, "Excluding '%s'-nonexistent\n", incoming);
225            log_it(tmp);
226            mr_free(tmp);
227        }
228    }
229    mr_free(incoming);
230    paranoid_fclose(fout);
231    paranoid_fclose(fin);
232    unlink(infname);
233    mr_free(infname);
234}
235
236
237/**
238 * Attempt to find the user's kernel by calling Mindi.
239 * If Mindi can't find the kernel, ask user. If @p kernel is not empty,
240 * don't do anything.
241 * @param kernel Where to put the found kernel.
242 * @return 0 for success, 1 for failure.
243 */
244int figure_out_kernel_path_interactively_if_necessary(char *kernel)
245{
246    char *tmp = NULL;
247    char *command = NULL;
248
249    malloc_string(tmp);
250    if (!kernel[0]) {
251        strcpy(kernel,
252               call_program_and_get_last_line_of_output
253               ("mindi --findkernel 2> /dev/null"));
254    }
255    // If we didn't get anything back, check whether mindi raised a fatal error
256    if (!kernel[0]) {
257        mr_asprintf(&command, "grep 'Fatal error' /var/log/mindi.log");
258        strcpy(tmp, call_program_and_get_last_line_of_output(command));
259        if (strlen(tmp) > 1) {
260            popup_and_OK(tmp);
261            fatal_error("Mindi gave a fatal error. Please check '/var/log/mindi.log'.");
262        }
263        mr_free(command);
264    }
265    log_it("Calling Mindi with kernel path of '%s'", kernel);
266    while (!kernel[0]) {
267        if (!ask_me_yes_or_no
268            ("Kernel not found or invalid. Choose another?")) {
269            return (1);
270        }
271        if (!popup_and_get_string
272            ("Kernel path",
273             "What is the full path and filename of your kernel, please?",
274             kernel, MAX_STR_LEN / 4)) {
275            fatal_error
276                ("Kernel not found. Please specify with the '-k' flag.");
277        }
278        log_it("User says kernel is at %s", kernel);
279    }
280    return (0);
281}
282
283
284/**
285 * Find location of specified executable in user's PATH.
286 * @param fname The basename of the executable to search for (e.g. @c afio).
287 * @return The full path to the executable, or "" if it does not exist, or NULL if @c file could not be found.
288 * @note The returned string points to static storage that will be overwritten with each call.
289 * @bug The checks with @c file and @c dirname seem pointless. If @c incoming is "", then you're calling
290 * <tt>dirname 2\>/dev/null</tt> or <tt>file 2\>/dev/null | cut -d':' -f1 2\>/dev/null</tt>, which basically amounts
291 * to nothing.
292 */
293char *find_home_of_exe(char *fname)
294{
295    /*@ buffers ********************* */
296    static char output[MAX_STR_LEN];
297    char *incoming;
298    char *command = NULL;
299
300    malloc_string(incoming);
301    incoming[0] = '\0';
302    /*@******************************* */
303
304    assert_string_is_neither_NULL_nor_zerolength(fname);
305
306    mr_asprintf(&command, "which %s 2> /dev/null", fname);
307    strcpy(incoming, call_program_and_get_last_line_of_output(command));
308    mr_free(command);
309
310    if (incoming[0] == '\0') {
311        if (system("which file > /dev/null 2> /dev/null")) {
312            mr_free(incoming);
313            mr_free(command);
314            output[0] = '\0';
315            return (NULL);      // forget it :)
316        }
317        mr_asprintf(&command,
318                "file %s 2> /dev/null | cut -d':' -f1 2> /dev/null",
319                incoming);
320        strcpy(incoming,
321               call_program_and_get_last_line_of_output(command));
322        mr_free(command);
323    }
324    if (incoming[0] == '\0')    // yes, it is == '\0' twice, not once :)
325    {
326        mr_asprintf(&command, "dirname %s 2> /dev/null", incoming);
327        strcpy(incoming,
328               call_program_and_get_last_line_of_output(command));
329        mr_free(command);
330    }
331    strcpy(output, incoming);
332    if (output[0] != '\0' && does_file_exist(output)) {
333        mr_msg(4, "find_home_of_exe () --- Found %s at %s", fname,
334                incoming);
335    } else {
336        output[0] = '\0';
337        mr_msg(4, "find_home_of_exe() --- Could not find %s", fname);
338    }
339    mr_free(incoming);
340    if (!output[0]) {
341        return (NULL);
342    } else {
343        return (output);
344    }
345}
346
347
348/**
349 * Get the last sequence of digits surrounded by non-digits in the first 32k of
350 * a file.
351 * @param logfile The file to look in.
352 * @return The number found, or 0 if none.
353 */
354int get_trackno_from_logfile(char *logfile)
355{
356
357    /*@ pointers ********************************************************* */
358    FILE *fin;
359
360    /*@ int ************************************************************** */
361    int trackno = 0;
362    size_t len = 0;
363
364    /*@ buffer ************************************************************ */
365    char datablock[32701];
366
367    assert_string_is_neither_NULL_nor_zerolength(logfile);
368
369    if (!(fin = fopen(logfile, "r"))) {
370        log_OS_error("Unable to open logfile");
371        fatal_error("Unable to open logfile to read trackno");
372    }
373    len = fread(datablock, 1, 32700, fin);
374    paranoid_fclose(fin);
375    if (len <= 0) {
376        return (0);
377    }
378    for (; len > 0 && !isdigit(datablock[len - 1]); len--);
379    datablock[len--] = '\0';
380    for (; len > 0 && isdigit(datablock[len - 1]); len--);
381    trackno = atoi(datablock + len);
382    return (trackno);
383}
384
385
386/**
387 * Get a percentage from the last line of @p filename. We look for the string
388 * "% done" on the last line and, if we find it, grab the number before the last % sign.
389 * @param filename The file to get the percentage from.
390 * @return The percentage found, or 0 for error.
391 */
392int grab_percentage_from_last_line_of_file(char *filename)
393{
394
395    char *lastline = NULL;
396    char *command = NULL;
397    char *p = NULL;
398    int i;
399
400    malloc_string(lastline);
401    for (i = NOOF_ERR_LINES - 1;
402         i >= 0 && !strstr(err_log_lines[i], "% Done")
403         && !strstr(err_log_lines[i], "% done"); i--);
404    if (i < 0) {
405        mr_asprintf(&command,
406                "tail -n3 %s | grep -Fi \"%c\" | tail -n1 | awk '{print $0;}'",
407                filename, '%');
408        strcpy(lastline,
409               call_program_and_get_last_line_of_output(command));
410        mr_free(command);
411        if (!lastline[0]) {
412            return (0);
413        }
414    } else {
415        strcpy(lastline, err_log_lines[i]);
416    }
417
418    p = strrchr(lastline, '%');
419    if (p) {
420        *p = '\0';
421    }
422    if (!p) {
423        return (0);
424    }
425    *p = '\0';
426    for (p--; *p != ' ' && p != lastline; p--);
427    if (p != lastline) {
428        p++;
429    }
430    i = atoi(p);
431
432    return (i);
433}
434
435
436/**
437 * Return the last line of @p filename.
438 * @param filename The file to get the last line of.
439 * @return The last line of the file.
440 * @note The returned string points to static storage that will be overwritten with each call.
441 */
442char *last_line_of_file(char *filename)
443{
444    /*@ buffers ***************************************************** */
445    static char output[MAX_STR_LEN];
446    char *command = NULL;
447    char *tmp = NULL;
448
449    /*@ pointers **************************************************** */
450    FILE *fin;
451
452    /*@ end vars **************************************************** */
453
454    if (!does_file_exist(filename)) {
455        mr_asprintf(&tmp, _("Tring to get last line of nonexistent file (%s)"),
456                filename);
457        log_it(tmp);
458        mr_free(tmp);
459        output[0] = '\0';
460        return (output);
461    }
462    mr_asprintf(&command, "tail -n1 %s", filename);
463    fin = popen(command, "r");
464    mr_free(command);
465
466    (void) fgets(output, MAX_STR_LEN, fin);
467    paranoid_pclose(fin);
468    while (strlen(output) > 0 && output[strlen(output) - 1] < 32) {
469        output[strlen(output) - 1] = '\0';
470    }
471    return (output);
472}
473
474
475/**
476 * Get the length of @p filename in bytes.
477 * @param filename The file to get the length of.
478 * @return The length of the file, or -1 for error.
479 */
480off_t length_of_file(char *filename)
481{
482    /*@ pointers *************************************************** */
483    FILE *fin;
484
485    /*@ long long ************************************************* */
486    off_t length;
487
488    fin = fopen(filename, "r");
489    if (!fin) {
490        log_it("filename=%s", filename);
491        log_OS_error("Unable to openin filename");
492        return (-1);
493    }
494    fseeko(fin, 0, SEEK_END);
495    length = ftello(fin);
496    paranoid_fclose(fin);
497    return (length);
498}
499
500
501/**
502 * Create the directory @p outdir_fname and all parent directories. Equivalent to <tt>mkdir -p</tt>.
503 * @param outdir_fname The directory to create.
504 * @return The return value of @c mkdir.
505 */
506/* BERLIOS: This function shouldn't call system at all */
507int make_hole_for_dir(char *outdir_fname)
508{
509    char *tmp;
510    int res = 0;
511
512    assert_string_is_neither_NULL_nor_zerolength(outdir_fname);
513    mr_asprintf(&tmp, "mkdir -p %s", outdir_fname);
514    res = system(tmp);
515    mr_free(tmp);
516    return (res);
517}
518
519
520/**
521 * Create the parent directories of @p outfile_fname.
522 * @param outfile_fname The file to make a "hole" for.
523 * @return 0, always.
524 * @bug Return value unnecessary.
525 */
526/* BERLIOS: This function shouldn't call system at all */
527int make_hole_for_file(char *outfile_fname)
528{
529    /*@ buffer ****************************************************** */
530    char *command;
531
532    /*@ int  ******************************************************** */
533    int res = 0;
534
535    /*@ end vars *************************************************** */
536
537    assert_string_is_neither_NULL_nor_zerolength(outfile_fname);
538    assert(!strstr(outfile_fname, MNT_CDROM));
539    assert(!strstr(outfile_fname, "/dev/cdrom"));
540
541    mr_asprintf(&command, "mkdir -p \"%s\" 2> /dev/null", outfile_fname);
542    res += system(command);
543    mr_free(command);
544
545    mr_asprintf(&command, "rmdir \"%s\" 2> /dev/null", outfile_fname);
546    res += system(command);
547    mr_free(command);
548
549    mr_asprintf(&command, "rm -f \"%s\" 2> /dev/null", outfile_fname);
550    res += system(command);
551    mr_free(command);
552    unlink(outfile_fname);
553    return (0);
554}
555
556
557/**
558 * Get the number of lines in @p filelist_fname that contain the string @p wildcard.
559 * @param filelist_fname The file to search through.
560 * @param wildcard The string to search for. This is @e not a shell glob or a regular expression.
561 * @return The number of lines matched.
562 */
563long noof_lines_that_match_wildcard(char *filelist_fname, char *wildcard)
564{
565    /*@ long ******************************************************* */
566    long matches = 0;
567
568    /*@ pointers *************************************************** */
569    FILE *fin;
570
571    /*@ buffers **************************************************** */
572    char *incoming = NULL;
573
574    size_t n = 0;
575    /*@ end vars *************************************************** */
576
577
578    fin = fopen(filelist_fname, "r");
579
580    if (!fin) {
581        log_OS_error("Unable to openin filelist_fname");
582        return (0);
583    }
584    mr_getline(&incoming, &n, fin);
585    while (!feof(fin)) {
586        if (strstr(incoming, wildcard)) {
587            matches++;
588        }
589        mr_getline(&incoming, &n, fin);
590    }
591    paranoid_fclose(fin);
592    mr_free(incoming);
593    return (matches);
594}
595
596
597/**
598 * Register our PID in a file in /var/run.
599 * The PID will be put in /var/run/monitas-<tt>name_str</tt>.pid.
600 * @param pid 0 to remove file, anything else to create it.
601 * @param name_str The basename of the PID file (e.g. "mondo" or "server")
602 * @note This function does not provide support against multiple instances, unless you check for that yourself.
603 */
604void register_pid(pid_t pid, char *name_str)
605{
606    char *tmp = NULL;
607    char *lockfile_fname = NULL;
608    int res;
609    size_t n = 0;
610    FILE *fin;
611
612    mr_asprintf(&lockfile_fname, "/var/run/monitas-%s.pid", name_str);
613    if (!pid) {
614        log_it("Unregistering PID");
615        if (unlink(lockfile_fname)) {
616            log_it("Error unregistering PID");
617        }
618        mr_free(lockfile_fname);
619        return;
620    }
621    if (does_file_exist(lockfile_fname)) {
622        if ((fin = fopen(lockfile_fname, "r"))) {
623            mr_getline(&tmp, &n, fin);
624            paranoid_fclose(fin);
625        } else {
626            log_OS_error("Unable to openin lockfile_fname");
627        }
628        pid = (pid_t) atol(tmp);
629        mr_free(tmp);
630
631        mr_asprintf(&tmp, "ps %ld > /dev/null 2> /dev/null", (long int) pid);
632        res = system(tmp);
633        mr_free(tmp);
634        if (!res) {
635            log_it
636                ("I believe the daemon is already running. If it isn't, please delete %s and try again.",
637                 lockfile_fname);
638        }
639    }
640    mr_asprintf(&tmp, "echo %ld > %s 2> /dev/null", (long int) getpid(),
641            lockfile_fname);
642    mr_free(lockfile_fname);
643
644    if (system(tmp)) {
645        fatal_error("Cannot register PID");
646    }
647    mr_free(tmp);
648    return;
649}
650
651
652/**
653 * Determine the size (in KB) of @p dev in the mountlist in <tt>tmpdir</tt>/mountlist.txt.
654 * @param tmpdir The tempdir where the mountlist is stored.
655 * @param dev The device to search for.
656 * @return The size of the partition in KB.
657 */
658long size_of_partition_in_mountlist_K(char *tmpdir, char *dev)
659{
660    char *command = NULL;
661    char *sz_res = NULL;
662    long file_len_K = 0L;
663
664    mr_asprintf(&command,
665            "grep '%s ' %s/mountlist.txt | head -n1 | awk '{print $4;}'",
666            dev, tmpdir);
667    log_it(command);
668    mr_asprintf(&sz_res, call_program_and_get_last_line_of_output(command));
669    file_len_K = atol(sz_res);
670    mr_msg(4, "%s --> %s --> %ld", command, sz_res, file_len_K);
671    mr_free(command);
672    mr_free(sz_res);
673    return (file_len_K);
674}
675
676
677/**
678 * Calculate the total size (in KB) of all the biggiefiles in this backup.
679 * @param bkpinfo The backup information structure. Only the @c bkpinfo->tmpdir field is used.
680 * @return The total size of all biggiefiles in KB.
681 */
682long size_of_all_biggiefiles_K(struct s_bkpinfo *bkpinfo)
683{
684    char *fname = NULL;
685    char *biggielist = NULL;
686    char *comment = NULL;
687    char *tmp = NULL;
688    char *command = NULL;
689
690    /*@ long ******************************************************** */
691    long scratchL = 0L;
692    long file_len_K = 0L;
693
694    /*@ pointers *************************************************** */
695    FILE *fin = NULL;
696    size_t n = 0;
697
698    /*@ end vars *************************************************** */
699
700    malloc_string(tmp);
701    log_it("Calculating size of all biggiefiles (in total)");
702    mr_asprintf(&biggielist, "%s/biggielist.txt", bkpinfo->tmpdir);
703    log_it("biggielist = %s", biggielist);
704    if (!(fin = fopen(biggielist, "r"))) {
705        log_OS_error
706            ("Cannot open biggielist. OK, so estimate is based on filesets only.");
707    } else {
708        mr_msg(4, "Reading it...");
709        for (mr_getline(&fname, &n, fin); !feof(fin);
710             mr_getline(&fname, &n, fin)) {
711            if (fname[strlen(fname) - 1] <= 32) {
712                fname[strlen(fname) - 1] = '\0';
713            }
714            if (0 == strncmp(fname, "/dev/", 5)) {
715                if (is_dev_an_NTFS_dev(fname)) {
716                    if ( !find_home_of_exe("ntfsresize")) {
717                        fatal_error("ntfsresize not found");
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                    strcpy (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                } else {
727                    file_len_K = get_phys_size_of_drive(fname) * 1024L;
728                }
729            } else {
730                /* BERLIOS: more than long here ??? */
731                file_len_K = (long) (length_of_file(fname) / 1024);
732            }
733            if (file_len_K > 0) {
734                scratchL += file_len_K;
735                mr_msg(4, "%s --> %ld K", fname, file_len_K);
736            }
737            mr_asprintf(&comment,
738                    "After adding %s, scratchL+%ld now equals %ld", fname,
739                    file_len_K, scratchL);
740            mr_msg(4, comment);
741            mr_free(comment);
742
743            if (feof(fin)) {
744                break;
745            }
746        }
747        mr_free(fname);
748    }
749    mr_free(biggielist);
750
751    log_it("Closing...");
752    paranoid_fclose(fin);
753    log_it("Finished calculating total size of all biggiefiles");
754    mr_free(tmp);
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 = NULL;
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_asprintf(&command, CP_BIN " --parents -pRdf %s %s", MONDO_SHARE,
954            bkpinfo->scratchdir);
955
956    mr_msg(4, "command = %s", command);
957    if (run_program_and_log_output(command, 1)) {
958        fatal_error("Failed to copy Mondo's stuff to scratchdir");
959    }
960    mr_free(command);
961
962    /* i18n */
963    mr_asprintf(&command, CP_BIN " --parents /usr/share/locale/*/LC_MESSAGES/mondo.mo %s",bkpinfo->scratchdir);
964    mr_msg(4, "command = %s", command);
965    run_program_and_log_output(command, 1);
966    mr_free(command);
967
968    mr_asprintf(&tmp, "%s/payload.tgz", MONDO_SHARE);
969    if (does_file_exist(tmp)) {
970        log_it("Untarring payload %s to scratchdir %s", tmp,
971               bkpinfo->scratchdir);
972        (void) getcwd(old_pwd, MAX_STR_LEN - 1);
973        chdir(bkpinfo->scratchdir);
974        mr_asprintf(&command, "tar -zxvf %s", tmp);
975        if (run_program_and_log_output(command, FALSE)) {
976            fatal_error("Failed to untar payload");
977        }
978        mr_free(command);
979        chdir(old_pwd);
980    }
981    mr_free(tmp);
982
983    mr_asprintf(&command, "cp -f %s/LAST-FILELIST-NUMBER %s", bkpinfo->tmpdir,
984            bkpinfo->scratchdir);
985    if (run_program_and_log_output(command, FALSE)) {
986        fatal_error("Failed to copy LAST-FILELIST-NUMBER to scratchdir");
987    }
988    mr_free(command);
989
990    mr_asprintf(&tmp,call_program_and_get_last_line_of_output("which mondorestore"));
991    if (!tmp) {
992        fatal_error
993            ("'which mondorestore' returned null. Where's your mondorestore? `which` can't find it. That's odd. Did you install mondorestore?");
994    }
995    mr_asprintf(&command, "cp -f %s %s", tmp, bkpinfo->tmpdir);
996    mr_free(tmp);
997
998    if (run_program_and_log_output(command, FALSE)) {
999        fatal_error("Failed to copy mondorestore to tmpdir");
1000    }
1001    mr_free(command);
1002
1003    mr_asprintf(&command, "hostname > %s/HOSTNAME", bkpinfo->scratchdir);
1004    paranoid_system(command);
1005    mr_free(command);
1006
1007    if (bkpinfo->postnuke_tarball[0]) {
1008        mr_asprintf(&command, "cp -f %s %s/post-nuke.tgz",
1009                bkpinfo->postnuke_tarball, bkpinfo->tmpdir);
1010        if (run_program_and_log_output(command, FALSE)) {
1011            fatal_error("Unable to copy post-nuke tarball to tmpdir");
1012        }
1013        mr_free(command);
1014    }
1015
1016    mvaddstr_and_log_it(g_currentY++, 74, "Done.");
1017}
1018
1019
1020/**
1021 * Store the client's NFS configuration in files to be restored at restore-time.
1022 * Assumes that @c bkpinfo->media_type = nfs, but does not check for this.
1023 * @param bkpinfo The backup information structure. Fields used:
1024 * - @c nfs_mount
1025 * - @c nfs_remote_dir
1026 * - @c tmpdir
1027 */
1028void store_nfs_config(struct s_bkpinfo *bkpinfo)
1029{
1030
1031    /*@ buffers ******** */
1032    char nfs_dev[MAX_STR_LEN];
1033    char mac_addr[MAX_STR_LEN];
1034    char nfs_mount[MAX_STR_LEN];
1035    char nfs_client_ipaddr[MAX_STR_LEN];
1036    char nfs_client_netmask[MAX_STR_LEN];
1037    char nfs_client_broadcast[MAX_STR_LEN];
1038    char nfs_client_defgw[MAX_STR_LEN];
1039    char nfs_server_ipaddr[MAX_STR_LEN];
1040    char *tmp = NULL;
1041    char *command = NULL;
1042
1043    FILE *fd1 = NULL;
1044
1045    /*@ pointers ***** */
1046    char *p;
1047
1048    log_it("Storing NFS configuration");
1049    mr_asprintf(&tmp, bkpinfo->nfs_mount);
1050    p = strchr(tmp, ':');
1051    if (!p) {
1052        fatal_error
1053            ("NFS mount doesn't have a colon in it, e.g. 192.168.1.4:/home/nfs");
1054    }
1055    *p = '\0';
1056    p++;
1057    strcpy(nfs_server_ipaddr, tmp);
1058    strcpy(nfs_mount, p);
1059    mr_free(tmp);
1060
1061    /* BERLIOS : there is a bug #67 here as it only considers the first NIC */
1062    mr_asprintf(&command,
1063            "ifconfig | tr '\n' '#' | sed s/##// | tr '#' ' ' | tr '' '\n' | head -n1 | cut -d' ' -f1");
1064    strcpy(nfs_dev, call_program_and_get_last_line_of_output(command));
1065    mr_free(command);
1066
1067    mr_asprintf(&command,
1068            "ifconfig | tr '\n' '#' | sed s/##// | tr '#' ' ' | tr '' '\\n' | head -n1 | tr -s '\t' ' ' | cut -d' ' -f7 | cut -d':' -f2");
1069    strcpy(nfs_client_ipaddr,
1070           call_program_and_get_last_line_of_output(command));
1071    mr_free(command);
1072
1073    mr_asprintf(&command,
1074            "ifconfig | tr '\n' '#' | sed s/##// | tr '#' ' ' | tr '' '\\n' | head -n1 | tr -s '\t' ' ' | cut -d' ' -f9 | cut -d':' -f2");
1075    strcpy(nfs_client_netmask,
1076           call_program_and_get_last_line_of_output(command));
1077    mr_free(command);
1078
1079    mr_asprintf(&command,
1080            "ifconfig | tr '\n' '#' | sed s/##// | tr '#' ' ' | tr '' '\\n' | head -n1 | tr -s '\t' ' ' | cut -d' ' -f8 | cut -d':' -f2");
1081    strcpy(nfs_client_broadcast,
1082           call_program_and_get_last_line_of_output(command));
1083    mr_free(command);
1084
1085    mr_asprintf(&command,
1086            "route -n | grep '^0.0.0.0' | awk '{print $2}'");
1087    strcpy(nfs_client_defgw,
1088           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    log_it(tmp);
1095    mr_free(tmp);
1096
1097    if (strlen(nfs_dev) < 2) {
1098        fatal_error
1099            ("Unable to find ethN (eth0, eth1, ...) adapter via NFS mount you specified.");
1100    }
1101    /********
1102    * If the NFS device that found above is a bonded device,
1103    * we need to replace it with an ethN device or the
1104    * networking will not start during an NFS restore.
1105    *
1106    * If the NFS device in nfs_dev begins with the word "bond",
1107    * look for the corresponding slave ethN device and copy it to nfs_dev.
1108    * Using the common MAC address
1109    ********/
1110    if (!strncmp(nfs_dev, "bond", 4)) {
1111        log_to_screen("Found bonding device %s; looking for corresponding ethN slave device\n", nfs_dev);
1112        mr_asprintf(&command,
1113                "ifconfig %s | awk '{print $5}' | head -n1", nfs_dev);
1114        strcpy(mac_addr, call_program_and_get_last_line_of_output(command));
1115        mr_free(command);
1116
1117        mr_asprintf(&command,
1118                "ifconfig | grep -E '%s' | grep -v '%s' | head -n1 | cut -d' ' -f1", mac_addr,nfs_dev);
1119        strcpy(nfs_dev, call_program_and_get_last_line_of_output(command));
1120        mr_free(command);
1121
1122        log_to_screen("Replacing it with %s\n", nfs_dev);
1123    }
1124
1125    fd1 = mr_fopen(MONDORESTORECFG, "a");
1126    mr_fprintf(fd1, "nfs-dev=%s\n", nfs_dev);
1127    mr_fprintf(fd1, "nfs-client-ipaddr=%s\n", nfs_client_ipaddr);
1128    mr_fprintf(fd1, "nfs-client-netmask=%s\n", nfs_client_netmask);
1129    mr_fprintf(fd1, "nfs-client-broadcast=%s\n", nfs_client_broadcast);
1130    mr_fprintf(fd1, "nfs-client-defgw=%s\n", nfs_client_defgw);
1131    mr_fprintf(fd1, "nfs-server-ipaddr=%s\n", nfs_server_ipaddr);
1132    mr_fprintf(fd1, "nfs-server-mount=%s\n", bkpinfo->nfs_mount);
1133    mr_fprintf(fd1, "nfs-server-path=%s\n", bkpinfo->nfs_remote_dir);
1134    mr_fprintf(fd1, "iso-prefix=%s\n", bkpinfo->prefix);
1135    mr_fclose(fd1);
1136
1137    log_it("Finished storing NFS configuration");
1138}
1139
1140
1141/**
1142 * Determine the approximate number of media that the backup will take up,
1143 * and tell the user. The uncompressed size is estimated as size_of_all_biggiefiles_K()
1144 * plus (noof_sets x bkpinfo->optimal_set_size). The compression factor is estimated as
1145 * 2/3 for LZO and 1/2 for bzip2. The data is not saved anywhere. If there are any
1146 * "imagedevs", the estimate is not shown as it will be wildly inaccurate.
1147 * If there are more than 50 media estimated, the estimate will not be shown.
1148 * @param bkpinfo The backup information structure. Fields used:
1149 * - @c bkpinfo->backup_media_type
1150 * - @c bkpinfo->image_devs
1151 * - @c bkpinfo->media_size
1152 * - @c bkpinfo->optimal_set_size
1153 * - @c bkpinfo->use_lzo
1154 * @param noof_sets The number of filesets created.
1155 * @ingroup archiveGroup
1156 */
1157void
1158estimate_noof_media_required(struct s_bkpinfo *bkpinfo, long noof_sets)
1159{
1160    /*@ buffers *************** */
1161    char *tmp = NULL;
1162
1163    /*@ long long ************* */
1164    long long scratchLL;
1165
1166    if (bkpinfo->media_size <= 0L) {
1167        log_to_screen("Number of media required: UNKNOWN");
1168        return;
1169    }
1170
1171    log_it("Estimating number of media required...");
1172    scratchLL =
1173        (long long) (noof_sets) * (long long) (bkpinfo->optimal_set_size)
1174        + (long long) (size_of_all_biggiefiles_K(bkpinfo));
1175    scratchLL = (scratchLL / 1024) / bkpinfo->media_size;
1176    scratchLL++;
1177    if (bkpinfo->use_lzo) {
1178        scratchLL = (scratchLL * 2) / 3;
1179    } else if (bkpinfo->use_gzip) {
1180        scratchLL = (scratchLL * 2) / 3;
1181    } else {
1182        scratchLL = scratchLL / 2;
1183    }
1184    if (!scratchLL) {
1185        scratchLL++;
1186    }
1187    if (scratchLL <= 1) {
1188        mr_asprintf(&tmp,
1189                _("Your backup will probably occupy a single %s. Maybe two."),
1190                bkpinfo->backup_media_string);
1191    } else {
1192        mr_asprintf(&tmp, _("Your backup will occupy approximately %s media."),
1193                number_to_text((int) (scratchLL + 1)));
1194    }
1195    if (!bkpinfo->image_devs[0] && (scratchLL < 50)) {
1196        log_to_screen(tmp);
1197    }
1198    mr_free(tmp);
1199    return;
1200}
1201
1202
1203/**
1204 * Determine whether a file is compressed. This is done
1205 * by reading through the "do-not-compress-these" file distributed with Mondo.
1206 * @param filename The file to check.
1207 * @return TRUE if it's compressed, FALSE if not.
1208 */
1209bool is_this_file_compressed(char *filename)
1210{
1211    char *do_not_compress_these = NULL;
1212    char *tmp = NULL;
1213    char *p = NULL;
1214    char *q = NULL;
1215
1216    q = strrchr(filename, '.');
1217    if (q == NULL) {
1218        return (FALSE);
1219    }
1220
1221    mr_asprintf(&tmp, "%s/do-not-compress-these", MONDO_SHARE);
1222    if (!does_file_exist(tmp)) {
1223        mr_free(tmp);
1224        return (FALSE);
1225    }
1226    malloc_string(do_not_compress_these);
1227    /* BERLIOS: This is just plain WRONG !! */
1228    strcpy(do_not_compress_these,last_line_of_file(tmp));
1229    mr_free(tmp);
1230
1231    for (p = do_not_compress_these; p != NULL; p++) {
1232        mr_asprintf(&tmp, p);
1233        if (strchr(tmp, ' ')) {
1234            *(strchr(tmp, ' ')) = '\0';
1235        }
1236        if (!strcmp(q, tmp)) {
1237            mr_free(do_not_compress_these);
1238            mr_free(tmp);
1239            return (TRUE);
1240        }
1241        mr_free(tmp);
1242
1243        if (!(p = strchr(p, ' '))) {
1244            break;
1245        }
1246    }
1247    mr_free(do_not_compress_these);
1248    return (FALSE);
1249}
1250
1251
1252int mode_of_file(char *fname)
1253{
1254    struct stat buf;
1255
1256    if (lstat(fname, &buf)) {
1257        return (-1);
1258    }                           // error
1259    else {
1260        return (buf.st_mode);
1261    }
1262}
1263
1264
1265/**
1266 * Create a small script that mounts /boot, calls @c grub-install, and syncs the disks.
1267 * @param outfile Where to put the script.
1268 * @return 0 for success, 1 for failure.
1269 */
1270int make_grub_install_scriptlet(char *outfile)
1271{
1272    FILE *fout = NULL;
1273    int retval = 0;
1274
1275    if ((fout = fopen(outfile, "w"))) {
1276        fprintf(fout,
1277                "#!/bin/sh\n\nmount /boot > /dev/null 2> /dev/null\ngrub-install $@\nres=$?\nsync;sync;sync\nexit $res\n");
1278        paranoid_fclose(fout);
1279        mr_msg(2, "Created %s", outfile);
1280        chmod(outfile,0755);
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.