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

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

Some merges from stable (synchro for mem. mngt)

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