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

Last change on this file since 1075 was 1075, checked in by Bruno Cornec, 17 years ago

Improvements for USB support in mindi when called from mondo
Changelogs in C files removed from common

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