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

Last change on this file since 507 was 507, checked in by bcornec, 13 years ago

merge -r489:506 $SVN_M/branches/stable

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