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

Last change on this file since 226 was 226, checked in by bcornec, 14 years ago

merge -r218:225 $SVN_M/branches/2.05

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