source: trunk/mondo/mondo/common/libmondo-devices.c @ 1

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

Initial import from latest mondo-2.04_cvs_20050503/mindi-1.04_cvs_20050503 on http://www.mondorescue.org

File size: 78.8 KB
Line 
1/* libmondo-devices.c                 Subroutines for handling devices
2   $Id: libmondo-devices.c,v 1.26 2004/06/21 20:20:36 hugo Exp $
3.
4
5
601/07/2005
7- sensibly_set_tmpdir_and_scratchdir() --- exclude smb and smbfs and (new) cifs
8
910/23
10- if root mounted at '/dev/rd/' then say FALSE, not mounted on ramdisk
11  just to please Fred Beondo :-p
12
1307/25
14- updated get_phys_size_of_drive() to support newer, larger drives
15
1607/18
17- better support of users who boot from LVM CD and nuke-restore non-LVM backups
18
1907/08
20- BLKGETSIZE64 instead of BLKGETIO..whatever (Joshua)
21- amended to use BLKGETSIZE if BLKGETSIZE64 missing (Hugo)
22- resort to HDIO_GETGEO if BLKGETSIZE and BLKGETSIZE63 fail
23
24
2506/25
26- added Mandrake 9.2 support to which_boot_loader()
27- cleaned up find_cdrom_device()
28
2906/23
30- rewrote resolve_softlinks_to_get_to_actual_device_file() in C
31
3206/17
33- don't use star automatically if SELINUX detected; let user do that
34
3505/07
36- usage of parted2fdisk instead of fdisk alone (ia32/ia64 compatibility)
37  BCO
38
3904/17
40- replaced INTERNAL_TAPE_BLK_SIZE with bkpinfo->internal_tape_block_size
41
4204/13
43- if kernel >= 2.6 then ask for /dev entry, not SCSI node
44
4504/12
46- in mount_CDROM_...whatever, don't use bkpinfo_DONTUSETHIS to see if
47  mounting a real CD device; look for /dev/ at start of $device instead
48
4904/04
50- when testing for tape drive, use INTERNAL_TAPE_BLK_SIZE, not TAPE_BLOCK_SIZE
51
5204/03
53- don't eject/retract drive if ISO
54
5502/23/2004
56- changed strstr() to strncmp() in a few places
57
5812/11/2003
59- if we can't find the DVD using dvdrecord then try it w/cdrecord
60
6111/15
62- changed a few []s to char*s
63- better support of multiple CD-ROM drives
64
6511/14
66- better find_cdrom_device(), to cope w/ multiple CD writers
67
6810/26
69- call 'mt -f %s offline' to eject tape drive in eject_device()
70
7110/25
72- ask user to confirm which NFS share to mount
73- improved which_boot_loader()
74
7510/22
76- tweaked find_cdrom_device() and find_cdrw_device()
77- created find_dvd_device()
78
7910/21
80- changed "/mnt/cdrom" to MNT_CDROM
81
8209/28
83- interactive gui no longer asks dvd's speed
84
8509/26
86- interactive gui now supports dvd
87
8809/23
89- malloc/free global strings in new subroutines - malloc_libmondo_global_strings()
90  and free_libmondo_global_strings() - which are in libmondo-tools.c
91
9209/21
93- ask for CD size when backing up interactively
94- offer to exclude NFS shares if they're present
95
9609/20
97- exclude /dev/shm from sensibly_*()
98
9909/18
100- less verbose logging when insisting on CD #n
101
10209/09
103- added resolve_softlinks_to_get_to_actual_device_file()
104
10509/05
106- rewrote inisist_on_this_cd_number() and what_number_cd_is_this()
107
10809/02
109- is_this_a_valid_disk_format() -- treat ntfs (a.k.a. type 7) as recognized format
110  just in case user's backup includes a partimagehack-imaged drive
111
11208/01 - 08/31
113- better boot-time tape detection
114- remove backup-time, erroneous, "remove floppy" msg
115- working on am_I_in_disaster_recovery_mode()
116- interactively_obtain_...() - pause & ask user to remove CD/floppy
117
11806/01 - 07/31
119- in which_boot_loader(), also search /dev/cciss for boot loader
120- fixed calls to popup_and_get_string()
121- fixed bug in get_phys_size_of_drive()
122- fixed bug in where_is_root_mounted()
123- commented out a spurious assert()
124
12505/01 - 05/31
126- superior get_phys_size_of_drive() (Joshua Oreman)
127- fixed call to inject_device() --- Andree L.
128- find_cdrom_device() now may, if asked to, mount drive if possible,
129  to test that it has a CD in it; it then unmounts
130- mount_CDROM_here() now calls retract_cd_and_defeat_autorun() as well
131- fixed support for subdir-within-NFS-mount
132- cleaned up some FreeBSD-specific stuff
133- added Joshua Oreman's FreeBSD patches
134- mount_CDROM_here() --- mkdir -p mountpt
135- add older drive support to get_phys_size_of_drive()
136
13704/01 - 04/30
138- made which_boot_loader() more friendly towards Red Hat 9
139- find_and_mount_actual_cd() retracts all CD trays
140- added lots of log_OS_error()'s and assert()'s
141- fix ISO support in interactively_restore_...()
142- made find_cdrom_device() skip dmesg if second-stage string is empty
143- in find_cdrw_device(), find cdrecord before dvdrecord
144- fixed am_i_in_disaster_recovery_mode()
145- fixed insist_on_this_cd_number()
146
14703/01 - 03/31
148- more work on find_cdrom_device()
149- find_cdrom_device() --- if nonexistent/not found then
150  make sure to return '' as dev str and 1 as res
151- cleaner find_cdrom_device(), to find DVD instead of CD-ROM
152  as last resort
153- fix insist_on_this_cd_number()
154- add user the speed of CD writer, if writing
155- if root is /dev/root then assume not a ramdisk
156
15701/07 - 02/28
158- fixed find_cdrom_device (Stan Benoit)
159- if root is at /dev/root/root then LVM (not ramdisk)
160- fix am_I_in_disaster_recovery_mode() to recognize that /dev/rd/cp*
161  entries are not ramdisks but RAID disks
162- find_cdrw_device() no longer complains to stderr if no cdrecord
163
16401/02/2003
165- sensibly_set_tmpdir_and_scratchdir() --- exclude smb and smbfs
166
16712/01/2002
168- don't ask for isodir path if in disaster recovery mode
169
17011/01 - 11/30
171- added g_restoring_live_from_cd;
172- handle_incoming_parameters() will sensibly set tmpdir and scratchdir
173- properly wipe spurious scratchdir and tmpdir
174- modified sensibly_...() to use tmp.mondo.* and mondo.scratch.*
175  instead of mondo.tmpdir.* and mondo.scratchdir.*
176- line 861,912: set media_size[0] to 1999 as well as 1 thru N
177- chmod 700, not 770, in make_fifo()
178- sensibly_set_tmpdir_and_scratchdir() will now prefix a '/' to the
179  strings if it is missing
180
18110/01 - 10/31
182- changed find_cdrom_device() to ignore DVD drives in the hd[a-d] search;
183  consequently, the subroutine will try scd0, sr0, etc. afterwards
184- commented code
185- fixed obscure bug in find_and_mount_actual_cd()
186- code which sensibly configures tmpdir,scratchdir is now sep. sub.
187- changed sort -s to sort -n <-- sensibly...()
188
18909/01 - 09/30
190- added list_of_NFS_devices_and_mounts()
191- try /dev/st0 if no tape specified at all
192- change '64k' to TAPE_BLOCK_SIZE
193- improved find_cdrom_device()
194- if cdrecord not found then find_cdrom_device() returns 1
195- if disaster recovery mode then don't ask for CD-ROM's /dev entry;
196  assume /dev/cdrom
197- if restoring data then ask for CD-ROM's /dev entry (not its SCSI node)
198- run_program_and_log_output() now takes boolean operator to specify
199  whether it will log its activities in the event of _success_
200- changed sort -n +4 to sort -s +4 (Troff)
201- ask if user's kernel is sane; if 'no' then use FAILSAFE
202- ask user to confirm the tape/CD device name
203- if restoring (not archiving) then don't try to find CD-ROM's SCSI
204  node; try to find its /dev entry instead
205- better detection of biggest partition
206
20708/01 - 08/31
208- fixed verify bug --- CD#1 was being verified again & again & ...
209- detect boot loader + device; if not detectible then _ask_
210- if run interactively, assume tape size is irrelevant & don't ask
211  for it; Mondo should handle end-of-tape gracefully now
212- worked on handling unknowng media size
213- added interactively_obtain_media_parameters_from_user()
214- when trying to mount CD-ROM, find_and_mount_actual_cd() will
215  now call find_cdrom_device() to try to find the /dev entry first
216- fixed serious bug in zero_out_a_device()
217- cleaned up some log_it() calls
218- fixed minor bug in find_cdrom_device()
219- better at distinguishing between live filesystem and ramdisk
220
22107/24/2002
222- created
223*/
224
225/**
226 * @file
227 * Functions to handle interactions with backup devices.
228 */
229
230#include "my-stuff.h"
231#include "mondostructures.h"
232#include "libmondo-files-EXT.h"
233#include "libmondo-devices.h"
234#include "lib-common-externs.h"
235#include "libmondo-string-EXT.h"
236#include "libmondo-tools-EXT.h"
237#include "libmondo-gui-EXT.h"
238#include "libmondo-fork-EXT.h"
239#include "libmondo-stream-EXT.h"
240
241#include <sys/types.h>
242#ifdef __FreeBSD__
243#define DKTYPENAMES
244#define FSTYPENAMES
245#include <sys/disklabel.h>
246#include <sys/disk.h>
247#elif linux
248#define u64 unsigned long long
249#include <linux/fs.h> /* for BLKGETSIZE64 */
250#include <linux/hdreg.h>
251#endif
252
253/*@unused@*/
254//static char cvsid[] = "$Id: libmondo-devices.c,v 1.26 2004/06/21 20:20:36 hugo Exp $";
255
256extern int g_current_media_number;
257extern double g_kernel_version;
258
259extern bool g_ISO_restore_mode;
260extern struct s_bkpinfo *g_bkpinfo_DONTUSETHIS;
261extern char *g_erase_tmpdir_and_scratchdir;
262
263static char g_cdrw_drive_is_here[MAX_STR_LEN/4]="";
264static char g_cdrom_drive_is_here[MAX_STR_LEN/4]="";
265static char g_dvd_drive_is_here[MAX_STR_LEN/4]="";
266
267
268/**
269 * ????? @bug ?????
270 * @ingroup globalGroup
271 */
272bool g_restoring_live_from_cd=FALSE;
273
274extern t_bkptype g_backup_media_type; // set by main()
275
276
277
278
279void set_g_cdrom_and_g_dvd_to_bkpinfo_value(struct s_bkpinfo *bkpinfo)
280{
281  strcpy(g_cdrom_drive_is_here, bkpinfo->media_device); // just in case
282  strcpy(g_dvd_drive_is_here, bkpinfo->media_device); // just in case
283}
284
285
286
287/**
288 * Retract all CD trays and wait for autorun to complete.
289 * @ingroup deviceGroup
290 */
291void retract_CD_tray_and_defeat_autorun(void)
292{
293//  log_it("rctada: Retracting all CD trays", __LINE__);
294  if (strlen(g_cdrom_drive_is_here)>0)
295    { inject_device(g_cdrom_drive_is_here); }
296  if (strlen(g_dvd_drive_is_here)>0)
297    { inject_device(g_dvd_drive_is_here); }
298  if (strlen(g_cdrw_drive_is_here)>0)
299    { inject_device(g_cdrw_drive_is_here); }
300//  log_it("rctada: killing autorun");
301//  run_program_and_log_output("killall autorun", TRUE);
302  if (!run_program_and_log_output("ps | grep autorun | grep -v grep", 5))
303    {
304      log_it("autorun detected; sleeping for 2 seconds");
305      sleep(2);
306    }
307  log_it("rctada: Unmounting all CD drives", __LINE__);
308  run_program_and_log_output("umount /dev/cdr* /dev/dvd*", 5);
309}
310
311
312
313/**
314 * Determine whether we're booted off a ramdisk.
315 * @return @c TRUE (we are) or @c FALSE (we aren't).
316 * @ingroup utilityGroup
317 */
318bool
319am_I_in_disaster_recovery_mode (void)
320{
321  char *tmp, *comment;
322  bool is_this_a_ramdisk = FALSE;
323
324  malloc_string(tmp);
325  malloc_string(comment);
326  strcpy(tmp, where_is_root_mounted());
327  sprintf(comment, "root is mounted at %s\n", tmp);
328  log_msg(0, comment);
329  log_msg(0, "No, Schlomo, that doesn't mean %s is the root partition. It's just a debugging message. Relax. It's part of am_I_in_disaster_recovery_mode().", tmp);
330
331#ifdef __FreeBSD__
332  if (strstr(tmp, "/dev/md"))
333    {
334      is_this_a_ramdisk = TRUE;
335    }
336#else
337  if (!strncmp(tmp, "/dev/ram", 8) || (!strncmp(tmp, "/dev/rd", 7) && !strcmp(tmp, "/dev/rd/") && strncmp(tmp, "/dev/rd/cd", 10)) || strstr(tmp, "rootfs")
338    || !strcmp(tmp, "/dev/root"))
339    { is_this_a_ramdisk = TRUE; }
340  else
341    { is_this_a_ramdisk = FALSE; }
342#endif
343
344  if (is_this_a_ramdisk)
345    {
346      if (!does_file_exist("/THIS-IS-A-RAMDISK") && !does_file_exist("/tmp/mountlist.txt.sample"))
347        {
348          log_to_screen("Using /dev/root is stupid of you but I'll forgive you.");
349          is_this_a_ramdisk = FALSE;
350        }
351    }
352  if (does_file_exist("/THIS-IS-A-RAMDISK"))
353    {
354      is_this_a_ramdisk = TRUE;
355    }
356  paranoid_free(tmp);
357  paranoid_free(comment);
358  log_msg(1, "Is this a ramdisk? result = %d", is_this_a_ramdisk);
359  return(is_this_a_ramdisk);
360}
361
362
363
364
365
366/**
367 * Turn @c bkpinfo->backup_media_type into a human-readable string.
368 * @return The human readable string (e.g. @c cdr becomes <tt>"cdr"</tt>).
369 * @note The returned string points to static storage that will be overwritten with each call.
370 * @ingroup stringGroup
371 */
372static char *bkptype_to_string(t_bkptype bt)
373{
374  static char output[MAX_STR_LEN/4];
375  switch(bt)
376    {
377    case none: strcpy(output, "none");
378        break;
379    case iso:  strcpy(output, "iso");
380        break;
381    case cdr:  strcpy(output, "cdr");
382        break;
383    case cdrw: strcpy(output, "cdrw");
384        break;
385    case cdstream: strcpy(output, "cdstream");
386        break;
387    case nfs:  strcpy(output, "nfs");
388        break;
389    case tape: strcpy(output, "tape");
390        break;
391    case udev: strcpy(output, "udev");
392        break;
393    default: strcpy(output, "default");
394    }
395  return(output);
396}
397
398
399
400/**
401 * @addtogroup deviceGroup
402 * @{
403 */
404/**
405 * Eject the tray of the specified CD device.
406 * @param dev The device to eject.
407 * @return the return value of the @c eject command. (0=success, nonzero=failure)
408 */
409int eject_device(char*dev)
410{
411  char *command;
412  int res1=0, res2=0;
413
414  malloc_string(command);
415
416  if (IS_THIS_A_STREAMING_BACKUP(g_backup_media_type) && g_backup_media_type!=udev)
417    {
418      sprintf(command, "mt -f %s offline", dev);
419      res1 = run_program_and_log_output(command, 1);
420    }
421  else
422    {
423      res1 = 0;
424    }
425
426#ifdef __FreeBSD__
427  if (strstr (dev, "acd")) {
428      sprintf (command, "cdcontrol -f %s eject", dev);
429  } else {
430      sprintf (command, "camcontrol eject `echo %s | sed 's|/dev/||'`", dev);
431  }
432#else
433  sprintf(command, "eject %s", dev);
434#endif
435
436  log_msg(3, "Ejecting %s", dev);
437  res2 = run_program_and_log_output(command, 1);
438  paranoid_free(command);
439  if (res1 && res2) { return(1); }
440  else { return(0); }
441}
442
443/**
444 * Load (inject) the tray of the specified CD device.
445 * @param dev The device to load/inject.
446 * @return 0 for success, nonzero for failure.
447 */
448int inject_device(char*dev)
449{
450  char *command;
451  int i;
452
453  malloc_string(command);
454
455
456#ifdef __FreeBSD__
457  if (strstr (dev, "acd")) {
458      sprintf (command, "cdcontrol -f %s close", dev);
459  } else {
460      sprintf (command, "camcontrol load `echo %s | sed 's|/dev/||'`", dev);
461  }
462#else
463  sprintf(command, "eject -t %s", dev);
464#endif
465  i = run_program_and_log_output(command, FALSE);
466  paranoid_free(command);
467  return(i);
468}
469
470
471/**
472 * Determine whether the specified @p device (really, you can use any file)
473 * exists.
474 * @return TRUE if it exists, FALSE if it doesn't.
475 */
476bool
477does_device_exist (char *device)
478{
479
480    /*@ buffers ************************************************************/
481  char *tmp;
482
483  malloc_string(tmp);
484  assert_string_is_neither_NULL_nor_zerolength(device);
485
486  sprintf (tmp, "ls %s > /dev/null 2> /dev/null", device);
487 
488  paranoid_free(tmp);
489  if (system (tmp))
490    {
491      return (FALSE);
492    }
493  else
494    {
495      return (TRUE);
496    }
497}
498
499
500/**
501 * Determine whether a non-Microsoft partition exists on any connected hard drive.
502 * @return TRUE (there's a Linux/FreeBSD partition) or FALSE (Microsoft has taken over yet another innocent PC).
503 */
504bool
505does_nonMS_partition_exist (void)
506{
507#if __FreeBSD__
508    return !system ("for drive in /dev/ad? /dev/da?; do fdisk $drive | grep -q FreeBSD && exit 0; done; false");
509#else
510    return !system ("parted2fdisk -l 2>/dev/null | grep '^/dev/' | egrep -qv '(MS|DOS|FAT|NTFS)'");
511#endif
512}
513
514/**
515 * Determine whether the specified @p partno exists on the specified @p drive.
516 * @param drive The drive to search for the partition in.
517 * @param partno The partition number to look for.
518 * @return 0 if it exists, nonzero otherwise.
519 */
520int
521does_partition_exist (const char *drive, int partno)
522{
523    /*@ buffers *****************************************************/
524  char *program;
525  char *incoming;
526  char *searchstr;
527  char *tmp;
528
529    /*@ ints ********************************************************/
530  int res = 0;
531
532    /*@ pointers ****************************************************/
533  FILE *fin;
534
535
536    /*@ end vars ****************************************************/
537  assert_string_is_neither_NULL_nor_zerolength(drive);
538  assert(partno>=0 && partno<999);
539
540  malloc_string(program);
541  malloc_string(incoming);
542  malloc_string(searchstr);
543  malloc_string(tmp);
544
545#ifdef __FreeBSD__
546  // We assume here that this is running from mondorestore. (It is.)
547  sprintf (program, "ls %s >/dev/null 2>&1", drive, build_partition_name (tmp, drive, partno));
548  return system (program);
549#else
550  tmp[0] = '\0';
551#endif
552
553  sprintf (program, "parted2fdisk -l %s 2> /dev/null", drive);
554  fin = popen (program, "r");
555  if (!fin)
556    {
557      log_it("program=%s", program);
558      log_OS_error("Cannot popen-in program");
559      return (0);
560    }
561  (void) build_partition_name (searchstr, drive, partno);
562  strcat(searchstr, " ");
563  for (res = 0; !res && fgets (incoming, MAX_STR_LEN - 1, fin); )
564    {
565      if (strstr (incoming, searchstr))
566    {
567      res = 1;
568    }
569    }
570  if (pclose (fin)) { log_OS_error("Cannot pclose fin"); }
571  paranoid_free(program);
572  paranoid_free(incoming);
573  paranoid_free(searchstr);
574  paranoid_free(tmp);
575  return (res);
576}
577
578
579
580
581
582/**
583 * Determine whether given NULL-terminated @p str exists in the MBR of @p dev.
584 * @param dev The device to look in.
585 * @param str The string to look for.
586 * @return TRUE if it exists, FALSE if it doesn't.
587 */
588bool
589does_string_exist_in_boot_block (char *dev, char *str)
590{
591    /*@ buffers *****************************************************/
592  char *command;
593
594    /*@ end vars ****************************************************/
595  int i;
596
597  assert_string_is_neither_NULL_nor_zerolength(dev);
598  assert_string_is_neither_NULL_nor_zerolength(str);
599
600  malloc_string(command);
601  sprintf (command,
602       "dd if=%s bs=446 count=1 2> /dev/null | strings | grep \"%s\" > /dev/null 2> /dev/null",
603       dev, str);
604  i = system(command);
605  paranoid_free(command);
606  if (i)
607    {
608      return (FALSE);
609    }
610  else
611    {
612      return (TRUE);
613    }
614}
615
616/**
617 * Determine whether specified @p str exists in the first @p n sectors of
618 * @p dev.
619 * @param dev The device to look in.
620 * @param str The string to look for.
621 * @param n The number of 512-byte sectors to search.
622 */
623bool
624does_string_exist_in_first_N_blocks (char *dev, char *str, int n)
625{
626      /*@ buffers *****************************************************/
627  char *command;
628      /*@ end vars ****************************************************/ 
629  int i;
630
631  malloc_string(command);
632  sprintf (command,
633         "dd if=%s bs=512 count=%i 2> /dev/null | strings | grep \"%s\" > /dev/null 2> /dev/null",
634         dev, n, str);
635  i = system(command);
636  paranoid_free(command);
637  if (i)
638    {
639      return (FALSE);
640    }
641  else
642    {
643      return (TRUE);
644    }
645}
646
647
648
649/**
650 * Try to mount CD-ROM at @p mountpoint. If the CD-ROM is not found or has
651 * not been specified, call find_cdrom_device() to find it.
652 * @param bkpinfo The backup information structure. The only field used is @c bkpinfo->media_device.
653 * @param mountpoint Where to mount the CD-ROM.
654 * @return 0 for success, nonzero for failure.
655 * @see mount_CDROM_here
656 */
657int
658find_and_mount_actual_cd (struct s_bkpinfo *bkpinfo, char *mountpoint)
659{
660    /*@ buffers ******************************************************/
661
662    /*@ int's  *******************************************************/
663  int res;
664  char *dev;
665
666    /*@ end vars *****************************************************/
667
668  malloc_string(dev);
669  assert(bkpinfo!=NULL);
670  assert_string_is_neither_NULL_nor_zerolength(mountpoint);
671
672  if (g_backup_media_type == dvd)
673    {
674      strcpy(dev, g_dvd_drive_is_here);
675      if (!dev[0])
676        { find_dvd_device(dev,FALSE); }
677    }
678  else
679    {
680      strcpy(dev, g_cdrom_drive_is_here);
681      if (!dev[0])
682        { find_cdrom_device(dev,FALSE); }
683    }
684
685  if (bkpinfo->backup_media_type != iso)
686    { retract_CD_tray_and_defeat_autorun(); }
687
688  if (!dev[0] || (res=mount_CDROM_here (dev, mountpoint)))
689    {
690      if (!popup_and_get_string
691            ("CD-ROM device", "Please enter your CD-ROM's /dev device",
692            dev, MAX_STR_LEN/4))
693    { res = 1; }
694      else
695    { res=mount_CDROM_here (dev, mountpoint); }
696    }
697  if (res) { log_msg(1, "mount failed"); }
698  else { log_msg(1, "mount succeeded with %s", dev); }
699  paranoid_free(dev);
700  return (res);
701}
702
703
704
705
706
707/**
708 * Locate a CD-R/W writer's SCSI node.
709 * @param cdrw_device SCSI node will be placed here.
710 * @return 0 for success, nonzero for failure.
711 */
712
713
714/**
715 * Locate a CD-R/W writer's SCSI node.
716 * @param cdrw_device SCSI node will be placed here.
717 * @return 0 for success, nonzero for failure.
718 */
719int
720find_cdrw_device (char *cdrw_device)
721{
722    /*@ buffers *************************/
723  char *comment;
724  char *tmp;
725  char *cdr_exe;
726  char *command;
727
728  malloc_string(comment);
729  malloc_string(tmp);
730  malloc_string(cdr_exe);
731  malloc_string(command);
732  if (g_cdrw_drive_is_here[0])
733    {
734      strcpy(cdrw_device, g_cdrw_drive_is_here);
735      log_msg(3, "Been there, done that. Returning %s", cdrw_device);
736  paranoid_free(comment);
737  paranoid_free(tmp);
738  paranoid_free(cdr_exe);
739  paranoid_free(command);
740      return(0);
741    }
742  if (g_backup_media_type == dvd)
743    {
744      log_msg(1, "This is dumb. You're calling find_cdrw_device() but you're backing up to DVD. WTF?");
745  paranoid_free(comment);
746  paranoid_free(tmp);
747  paranoid_free(cdr_exe);
748  paranoid_free(command);
749      return(1);
750    }
751  run_program_and_log_output("insmod ide-scsi", -1);
752  if (find_home_of_exe("cdrecord"))
753    { strcpy(cdr_exe, "cdrecord"); }
754  else
755    { strcpy(cdr_exe, "dvdrecord"); }
756  tmp[0]='\0';
757  if (find_home_of_exe(cdr_exe))
758    {
759      sprintf(command, "%s -scanbus 2> /dev/null | tr -s '\t' ' ' | grep \"[0-9]*,[0-9]*,[0-9]*\" | grep -v \"[0-9]*) \\*\" | grep CD | cut -d' ' -f2 | head -n1", cdr_exe);
760      strcpy (tmp, call_program_and_get_last_line_of_output(command));
761    }
762  if (strlen (tmp) < 2)
763    {
764  paranoid_free(comment);
765  paranoid_free(tmp);
766  paranoid_free(cdr_exe);
767  paranoid_free(command);
768      return 1;
769    }
770  else
771    {
772      strcpy (cdrw_device, tmp);
773      sprintf (comment, "Found CDRW device - %s", cdrw_device);
774      log_it (comment);
775      strcpy (g_cdrw_drive_is_here, cdrw_device);
776      paranoid_free(comment);
777      paranoid_free(tmp);
778      paranoid_free(cdr_exe);
779      paranoid_free(command);
780      return (0);
781    }
782}
783
784
785
786
787/**
788 * Attempt to locate a CD-ROM device's /dev entry.
789 * Several different methods may be used to find the device, including
790 * calling @c cdrecord, searching @c dmesg, and trial-and-error.
791 * @param output Where to put the located /dev entry.
792 * @param try_to_mount Whether to mount the CD as part of the test; if mount
793 * fails then return failure.
794 * @return 0 for success, nonzero for failure.
795 */
796int
797find_cdrom_device (char *output, bool try_to_mount)
798{
799    /*@ pointers *****************************************************/
800  FILE *fin;
801  char *p;
802  char *q;
803  char *r;
804  int retval=0;
805
806    /*@ bool's *******************************************************/
807  bool found_it = FALSE;
808
809    /*@ buffers ******************************************************/
810  char *tmp;
811  char *cdr_exe;
812  char *phrase_one;
813  char *phrase_two;
814  char *command;
815  char *dvd_last_resort;
816  char *mountpoint;
817  static char the_last_place_i_found_it[MAX_STR_LEN] = "";
818
819    /*@ intialize ****************************************************/
820  malloc_string(tmp);
821  malloc_string(cdr_exe);
822  malloc_string(phrase_one);
823  malloc_string(phrase_two);
824  malloc_string(command);
825  malloc_string(dvd_last_resort);
826  malloc_string(mountpoint);
827 
828  output[0] = '\0';
829  phrase_one[0] = '\0';
830  phrase_two[0] = '\0';
831  dvd_last_resort[0] = '\0';
832
833    /*@ end vars *****************************************************/
834
835  if (g_cdrom_drive_is_here[0] && !isdigit(g_cdrom_drive_is_here[0]))
836    {
837      strcpy(output, g_cdrom_drive_is_here);
838      log_msg(3, "Been there, done that. Returning %s", output);
839      retval=0;
840      goto end_of_find_cdrom_device;
841    }
842  if (the_last_place_i_found_it[0]!='\0' && !try_to_mount)
843    {
844        strcpy(output, the_last_place_i_found_it);
845        log_msg(3, "find_cdrom_device() --- returning last found location - '%s'", output);
846        retval=0;
847    goto end_of_find_cdrom_device;
848    }
849
850  sprintf(mountpoint,"/tmp/cd.%d", (int)(random()%32767));
851  make_hole_for_dir(mountpoint);
852
853  if (find_home_of_exe("cdrecord"))
854    { strcpy(cdr_exe, "cdrecord"); }
855  else
856    { strcpy(cdr_exe, "dvdrecord"); }
857  tmp[0]='\0';
858  if (!find_home_of_exe(cdr_exe))
859    {
860      strcpy(output, "/dev/cdrom");
861      log_msg(4, "Can't find cdrecord; assuming %s", output);
862      if (!does_device_exist(output))
863        {
864          log_msg(4, "That didn't work. Sorry.");
865          retval=1;
866          goto end_of_find_cdrom_device;
867        }
868      else
869        {
870          retval=0;
871          goto end_of_find_cdrom_device;
872        }
873    }
874
875  sprintf(command, "%s -scanbus 2> /dev/null", cdr_exe);
876  fin = popen (command, "r");
877  if (!fin) { log_msg(4, "command=%s", command); log_OS_error("Cannot popen command"); return (1); }
878  for (fgets (tmp, MAX_STR_LEN, fin); !feof (fin);
879       fgets (tmp, MAX_STR_LEN, fin))
880    {
881      p = strchr (tmp, '\'');
882      if (p)
883    {
884      q = strchr (++p, '\'');
885      if (q)
886        {
887          for (r = q; *(r - 1) == ' '; r--);
888          *r = '\0';
889          strcpy (phrase_one, p);
890          p = strchr (++q, '\'');
891          if (p)
892        {
893          q = strchr (++p, '\'');
894          if (q)
895            {
896              while (*(q - 1) == ' ')
897            {
898              q--;
899            }
900              *q = '\0';
901              strcpy (phrase_two, p);
902            }
903        }
904        }
905    }
906    }
907  paranoid_pclose(fin);
908
909#ifndef __FreeBSD__
910  if (strlen(phrase_two)==0)
911    { log_msg(4, "Not running phase two. String is empty."); }
912  else
913    {
914      sprintf (command, "dmesg | grep \"%s\" 2> /dev/null", phrase_two);
915      fin = popen (command, "r");
916      if (!fin)
917        {
918          log_msg(4, "Cannot run 2nd command - non-fatal, fortunately");
919        }
920      else
921        {
922          for (fgets (tmp, MAX_STR_LEN, fin); !feof (fin); fgets (tmp, MAX_STR_LEN, fin))
923        {
924              log_msg(5, "--> '%s'", tmp);
925              if (tmp[0] != ' ' && tmp[1] != ' ')
926            {
927              p = strchr (tmp, ':');
928              if (p)
929            {
930              *p = '\0';
931              if (strstr(tmp, "DVD"))
932                {
933                  sprintf(dvd_last_resort, "/dev/%s", tmp);
934                  log_msg(4, "Ignoring '%s' because it's a DVD drive", tmp);
935                }
936              else
937                {
938                  sprintf (output, "/dev/%s", tmp);
939                  found_it = TRUE;
940                }
941            }
942                }
943            }
944          paranoid_pclose(fin);
945        }
946    }
947
948#endif
949#ifdef __FreeBSD__
950  if (!found_it)
951      { log_msg(4, "OK, approach 2"); if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/cdrom")))
952        { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/cdrom1")))
953          { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/dvd")))
954            { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/acd0")))
955              { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/cd01")))
956                { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/acd1")))
957                  { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/cd1")))
958              { retval=1; goto end_of_find_cdrom_device; }
959          } } } } } } }
960#else
961  if (!found_it && strlen(dvd_last_resort)>0)
962    {
963      log_msg(4, "Well, I'll use the DVD - %s - as a last resort", dvd_last_resort);
964      strcpy(output, dvd_last_resort);
965      found_it = TRUE;
966    }
967  if (found_it)
968    {
969      sprintf(tmp, "grep \"%s=ide-scsi\" /proc/cmdline &> /dev/null", strrchr(output,'/')+1);
970      if (system(tmp) == 0)
971    {
972      log_msg(4, "%s is not right. It's being SCSI-emulated. Continuing.", output);
973      found_it = FALSE;
974      output[0] = '\0';
975    }
976    }
977
978  if (found_it)
979    {
980      log_msg(4, "(find_cdrom_device) --> '%s'", output);
981      if (!does_device_exist(output)) { found_it=FALSE; log_msg(4, "OK, I was wrong, I haven't found it... yet."); }
982    }
983
984  if (!found_it)
985      { log_msg(4, "OK, approach 2"); if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/scd0")))
986        { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/sr0" )))
987          { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/cdrom")))
988            { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/cdrom0")))
989              { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/cdrom1")))
990        { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/sr1")))
991                  { if (!(found_it = set_dev_to_this_if_rx_OK(output, "/dev/dvd")))
992            { if (!(found_it = set_dev_to_this_if_rx_OK(output, g_cdrw_drive_is_here)))
993              { retval=1; goto end_of_find_cdrom_device; }
994            } } } } } } } }
995#endif
996
997  if (found_it && try_to_mount)
998    {
999      if (mount_CDROM_here (output, mountpoint))
1000        {
1001          log_msg(4, "[Cardigans] I've changed my mind");
1002          found_it = FALSE;
1003        }
1004      else
1005        {
1006          sprintf(tmp, "%s/archives", mountpoint);
1007          if (!does_file_exist(tmp))
1008            {
1009              log_msg(4, "[Cardigans] I'll take it back");
1010              found_it = FALSE;
1011            }
1012          else
1013            {
1014              sprintf(command, "umount %s", output);
1015              paranoid_system(command);
1016              log_msg(4, "I'm confident the Mondo CD is in %s", output);
1017        }
1018        }
1019    }
1020  unlink(mountpoint);
1021
1022  if (found_it)
1023    {
1024      if (!does_file_exist(output)) { log_msg(3, "I still haven't found it."); return(1); }
1025      log_msg(3, "(find_cdrom_device) --> '%s'", output);
1026      strcpy(the_last_place_i_found_it, output);
1027      strcpy(g_cdrom_drive_is_here, output);
1028      retval=0;
1029      goto end_of_find_cdrom_device;
1030    }
1031
1032  sprintf(command, "%s -scanbus | grep \"[0-9],[0-9],[0-9]\" | grep \"[D|C][V|D]\" | grep -n \"\" | grep \"%s\" | cut -d':' -f2", cdr_exe, g_cdrw_drive_is_here);
1033  log_msg(1, "command=%s", command);
1034  strcpy(tmp, call_program_and_get_last_line_of_output(command));
1035  if (tmp[0])
1036    { 
1037      strcpy(output, tmp); 
1038      log_msg(4, "Finally found it at %s", output);
1039      retval=0;
1040      goto end_of_find_cdrom_device;
1041    }
1042  else
1043    {
1044      log_msg(4, "Still couldn't find it."); 
1045      retval=1;
1046      goto end_of_find_cdrom_device;
1047    }
1048end_of_find_cdrom_device:
1049  paranoid_free(tmp);
1050  paranoid_free(cdr_exe);
1051  paranoid_free(phrase_one);
1052  paranoid_free(phrase_two);
1053  paranoid_free(command);
1054  paranoid_free(dvd_last_resort);
1055  paranoid_free(mountpoint);
1056  return(retval);
1057}
1058
1059
1060
1061
1062
1063int find_dvd_device(char*output, bool try_to_mount)
1064{
1065  char *command;
1066  char *tmp;
1067  int retval=0, devno=-1;
1068
1069  malloc_string(command);
1070  malloc_string(tmp);
1071
1072    if (g_dvd_drive_is_here[0])
1073    {
1074      strcpy(output, g_dvd_drive_is_here);
1075      log_msg(3, "Been there, done that. Returning %s", output);
1076      return(0);
1077    }
1078
1079  sprintf(tmp, call_program_and_get_last_line_of_output
1080            (
1081"dvdrecord -scanbus 2> /dev/null | grep \") '\" | grep -n \"\" | grep DVD | cut -d':' -f1"
1082            )
1083        );
1084  log_msg(5, "tmp = '%s'", tmp);
1085  if (!tmp[0]) sprintf (tmp, call_program_and_get_last_line_of_output
1086                 (
1087"cdrecord -scanbus 2> /dev/null | grep \") '\" | grep -n \"\" | grep DVD | cut -d':' -f1"
1088                             )
1089                       );
1090  if (tmp[0])
1091    {
1092      devno=atoi(tmp) - 1;
1093    }
1094  if (devno>=0)
1095    {
1096      retval=0;
1097      sprintf(output, "/dev/scd%d", devno);
1098      strcpy(g_dvd_drive_is_here, output);
1099      log_msg(2, "I think DVD is at %s", output);
1100    }
1101  else
1102    {
1103      log_msg(2,"I cannot find DVD");
1104      retval=1;
1105    }
1106
1107  if (try_to_mount)
1108    {
1109      log_msg(1, "Ignoring the fact that try_to_mount==TRUE");
1110    }
1111  return(retval);
1112}
1113
1114
1115
1116
1117
1118#include <sys/ioctl.h>
1119
1120/**
1121 * Find the size of the specified @p drive, in megabytes. Uses @c ioctl calls
1122 * and @c dmesg.
1123 * @param drive The device to find the size of.
1124 * @return size in megabytes.
1125 */
1126long
1127get_phys_size_of_drive (char *drive)
1128{
1129    int fd;
1130#if linux
1131    unsigned long long s=0;
1132    int fileid, cylinders=0, cylindersleft=0;
1133    int cylindersize=0;
1134    int gotgeo = 0;
1135
1136   
1137  struct hd_geometry hdgeo;
1138#elif __FreeBSD__
1139    off_t s;
1140#endif
1141
1142    long outvalA=-1;
1143    long outvalB=-1;
1144    long outvalC=-1;
1145
1146    if ((fd = open (drive, O_RDONLY)) != -1) {
1147    if (ioctl (fd,
1148#if linux
1149    #ifdef BLKGETSIZE64
1150            BLKGETSIZE64,
1151    #else
1152            BLKGETSIZE,
1153   #endif
1154#elif __FreeBSD__
1155           DIOCGMEDIASIZE,
1156#endif
1157           &s) != -1) {
1158        close (fd);
1159                    // s>>11 works for older disks but not for newer ones
1160        outvalB =
1161#if linux
1162    #ifdef BLKGETSIZE64 
1163          s >> 20
1164    #else
1165              s >> 11
1166    #endif
1167#else
1168              s >> 20
1169#endif
1170;
1171    }
1172    }
1173
1174    if (outvalB<=0)
1175      { log_msg (1, "Error getting size of %s: %s", drive, strerror (errno)); }
1176#if linux
1177    fileid = open (drive, O_RDONLY);
1178    if (fileid) {
1179        if (ioctl (fileid, HDIO_GETGEO, &hdgeo) != -1) {
1180            if (hdgeo.cylinders && hdgeo.heads && hdgeo.sectors) {
1181                cylindersleft = cylinders = hdgeo.cylinders;
1182                cylindersize = hdgeo.heads * hdgeo.sectors / 2;
1183                outvalA = cylindersize * cylinders / 1024;
1184                log_msg (2, "Got Harddisk geometry, C:%d, H:%d, S:%d", hdgeo.cylinders, hdgeo.heads, hdgeo.sectors);
1185                gotgeo = 1;
1186            } else {
1187                log_msg (1, "Harddisk geometry wrong");
1188            }
1189        } else {
1190            log_msg (1, "Error in ioctl() getting new hard disk geometry (%s), resizing in unsafe mode", strerror(errno));
1191        }
1192        close(fileid);
1193    } else {
1194        log_msg (1, "Failed to open %s for reading: %s", drive, strerror(errno));
1195    }
1196    if (!gotgeo) {
1197        log_msg (1, "Failed to get harddisk geometry, using old mode");
1198    }
1199/* 
1200  if ((fd = open (drive, O_RDONLY)) != -1) {
1201      if (ioctl (fd, HDIO_GETGEO, &hdgeo) != -1)  {
1202      close (fd);
1203      log_msg (2, "Geometry of drive %s is C:%d, H:%d, S%d, its size is %d MB", drive, hdgeo.cylinders, hdgeo.heads, hdgeo.sectors, (hdgeo.cylinders * hdgeo.heads * hdgeo.sectors / 2 / 1024));
1204      if ( hdgeo.cylinders && hdgeo.heads && hdgeo.sectors ) {
1205          outvalB = ((long) (hdgeo.cylinders * hdgeo.heads * hdgeo.sectors / 2 / 1024));
1206      }
1207      }
1208      close (fd);
1209 */
1210#endif
1211
1212// OLDER DISKS will give ridiculously low value for outvalB (so outvalA is returned) :)
1213// NEWER DISKS will give sane value for outvalB (close to outvalA, in other words) :)
1214
1215  outvalC = (outvalA > outvalB) ? outvalA : outvalB;
1216 
1217//  log_msg (5, "drive = %s, error = %s", drive, strerror (errno));
1218//  fatal_error ("GPSOD: Unable to get size of drive");
1219  log_msg(1, "%s --> %ld or %ld --> %ld", drive, outvalA, outvalB, outvalC);
1220 
1221  return(outvalC);
1222}
1223   
1224/* The old version */
1225#if 0 
1226long
1227get_phys_size_of_drive (char *drive)
1228{
1229    /*@ pointers *****************************************************/
1230#if linux
1231  FILE *fin;
1232  char *p;
1233  char *q;
1234  char *r;
1235    /*@ buffers ******************************************************/
1236  char *tmp;
1237  char *command;
1238
1239    /*@ long *********************************************************/
1240  long outL;
1241  long tempLa;
1242  long tempLb;
1243  long tempLc;
1244
1245#endif
1246
1247  struct hd_geometry hdgeo;
1248  int fd;
1249
1250#ifdef __FreeBSD__
1251  off_t o;
1252
1253  if ((fd = open (drive, O_RDONLY)) != -1) {
1254      if (ioctl (fd, DIOCGMEDIASIZE, &o) != -1) {
1255      close (fd);
1256      return (long) (o / (off_t) (1024 * 1024));
1257      }
1258      close (fd);
1259  }
1260  log_msg (4, "drive = %s, error = %s", drive, strerror (errno));
1261  fatal_error ("GPSOD: Unable to get size of drive");
1262#else
1263
1264  malloc_string(tmp);
1265  malloc_string(command);
1266
1267  if ((fd = open (drive, O_RDONLY)) != -1) {
1268      if (ioctl (fd, HDIO_GETGEO, &hdgeo) != -1)  {
1269      close (fd);
1270      log_msg (2, "Geometry of drive %s is C:%d, H:%d, S%d, its size is %d MB", drive, hdgeo.cylinders, hdgeo.heads, hdgeo.sectors, (hdgeo.cylinders * hdgeo.heads * hdgeo.sectors / 2 / 1024));
1271      if ( hdgeo.cylinders && hdgeo.heads && hdgeo.sectors ) {
1272          return ((long) (hdgeo.cylinders * hdgeo.heads * hdgeo.sectors / 2 / 1024));
1273      }
1274      }
1275      close (fd);
1276  }
1277
1278  assert_string_is_neither_NULL_nor_zerolength(drive);
1279
1280  sprintf (command,
1281       "parted2fdisk -l %s | head -n4 | tr -s '\n' '\t' | tr -s ' ' '\t' | cut -f8,14,16",
1282       drive);
1283  strcpy (tmp, call_program_and_get_last_line_of_output (command));
1284  if (tmp[0])
1285    {
1286      p = tmp;
1287      q = strchr (p, ' ');
1288      if (q)
1289    {
1290      *(q++) = '\0';
1291      r = strchr (q, ' ');
1292      if (r)
1293        {
1294          *(r++) = '\0';
1295          tempLa = atol (p);
1296          tempLb = atol (q);
1297          tempLc = atol (r);
1298          outL = tempLa * tempLb / 1024 * tempLc / 1024;
1299          if (outL > 100)
1300        {
1301      paranoid_free(tmp);
1302      paranoid_free(command);
1303          return (outL);
1304        }
1305        }
1306    }
1307    }
1308
1309  /* try to grep for 'Drive xxxx: yyy MB' */
1310  sprintf(command, "parted2fdisk -l %s | grep MB | tr -s ' ' '\t' | cut -f3", drive);
1311  strcpy(tmp, call_program_and_get_last_line_of_output(command));
1312  if (atol(tmp) > 0)
1313    {
1314      paranoid_free(tmp);
1315      paranoid_free(command);
1316      return (atol(tmp));
1317    }
1318
1319  /* else, do it the old-fashioned way */
1320  p = strrchr (drive, (int) '/');
1321  if (p)
1322    {
1323      strcpy (tmp, p + 1);
1324    }
1325  else
1326    {
1327      paranoid_free(tmp);
1328      paranoid_free(command);
1329      return (-1);
1330    }
1331  sprintf (command, "dmesg | grep %s 2> /dev/null", tmp);
1332  if (!(fin = popen (command, "r")))
1333    { log_OS_error("Cannot popen dmesg command"); }
1334  else
1335    {
1336      fgets (tmp, MAX_STR_LEN - 1, fin);
1337      while (!feof (fin) && !strstr (tmp, "GB") && !strstr (tmp, "MB"))
1338        {
1339          fgets (tmp, MAX_STR_LEN - 1, fin);
1340        }
1341      if (pclose (fin)) { log_OS_error("Cannot pclose dmesg fin"); }
1342    }
1343  if (!(p = strstr (tmp, "GB")) && !(p = strstr (tmp, "MB")))
1344    {
1345      log_msg (3, "Cannot find %s's size: dmesg isn't helping either.",
1346           drive);
1347      paranoid_free(tmp);
1348      paranoid_free(command);
1349      return (-1);
1350    }
1351  for (; !isdigit (*(p - 1)); p--);
1352  *p = '\0';
1353  for (p--; isdigit (*(p - 1)); p--);
1354  outL = atol (p);
1355  if (outL <= 0)
1356    {
1357      paranoid_free(tmp);
1358      paranoid_free(command);
1359      return (-1);
1360    }
1361  if (strstr (tmp, "GB"))
1362    {
1363      outL = outL * 1024;
1364    }
1365      paranoid_free(tmp);
1366      paranoid_free(command);
1367  return (outL * 19 / 20);
1368#endif
1369}
1370#endif /* 0 */
1371
1372
1373
1374
1375
1376/**
1377 * Determine whether @p format is supported by the kernel. Uses /proc/filesystems
1378 * under Linux and @c lsvfs under FreeBSD.
1379 * @param format The format to test.
1380 * @return TRUE if the format is supported, FALSE if not.
1381 */
1382bool
1383is_this_a_valid_disk_format (char *format)
1384{
1385  char *good_formats;
1386    char *command;
1387    char *format_sz;
1388
1389  FILE *pin;
1390  int retval;
1391  malloc_string(good_formats);
1392  malloc_string(command);
1393  malloc_string(format_sz);
1394
1395  assert_string_is_neither_NULL_nor_zerolength(format);
1396
1397  sprintf (format_sz, "%s ", format);
1398
1399#ifdef __FreeBSD__
1400  sprintf (command,
1401           "lsvfs | tr -s '\t' ' ' | grep -v Filesys | grep -v -- -- | cut -d' ' -f1 | tr -s '\n' ' '");
1402#else
1403  sprintf (command,
1404       "cat /proc/filesystems | grep -v nodev | tr -s '\t' ' ' | cut -d' ' -f2 | tr -s '\n' ' '");
1405#endif
1406
1407  pin = popen (command, "r");
1408  if (!pin)
1409    {
1410      log_OS_error ("Unable to read good formats");
1411      retval=0;
1412    }
1413  else
1414    {
1415      strcpy (good_formats, " ");
1416      (void) fgets (good_formats + 1, MAX_STR_LEN, pin);
1417      if (pclose (pin))
1418        { log_OS_error("Cannot pclose good formats"); }
1419      strip_spaces (good_formats);
1420      strcat (good_formats, " swap lvm raid ntfs 7 "); // " ntfs 7 " -- um, cheating much? :)
1421      if (strstr (good_formats, format_sz))
1422        {
1423      retval=1;
1424        }
1425      else
1426        {
1427      retval=0;
1428        }
1429    }
1430  paranoid_free(good_formats);
1431  paranoid_free(command);
1432  paranoid_free(format_sz);
1433  return (retval);
1434}
1435
1436
1437/** @def SWAPLIST_COMMAND The command to list the swap files/partitions in use. */
1438
1439/**
1440 * Determine whether @p device_raw is currently mounted.
1441 * @param device_raw The device to check.
1442 * @return TRUE if it's mounted, FALSE if not.
1443 */
1444bool is_this_device_mounted (char *device_raw)
1445{
1446
1447    /*@ pointers *****************************************************/
1448  FILE *fin;
1449
1450    /*@ buffers ******************************************************/
1451  char *incoming;
1452  char *device_with_tab;
1453  char *device_with_space;
1454  char *tmp;
1455  int retval=0;
1456 
1457#ifdef __FreeBSD__
1458  #define SWAPLIST_COMMAND "swapinfo"
1459#else
1460  #define SWAPLIST_COMMAND "cat /proc/swaps"
1461#endif
1462
1463    /*@ end vars *****************************************************/
1464
1465  malloc_string(incoming);
1466  malloc_string(device_with_tab);
1467  malloc_string(device_with_space);
1468  malloc_string(tmp);
1469  assert(device_raw!=NULL);
1470//  assert_string_is_neither_NULL_nor_zerolength(device_raw);
1471  if (device_raw[0] != '/' && !strstr(device_raw, ":/"))
1472    {
1473      log_msg(1, "%s needs to have a '/' prefixed - I'll do it", device_raw);
1474      sprintf(tmp, "/%s", device_raw);
1475    }
1476  else
1477    {
1478      strcpy(tmp, device_raw);
1479    }
1480  log_msg(1, "Is %s mounted?", tmp);
1481  if (!strcmp(tmp, "/proc") || !strcmp(tmp, "proc"))
1482    {
1483      log_msg(1, "I don't know how the heck /proc made it into the mountlist. I'll ignore it.");
1484      return(0);
1485    }
1486  sprintf (device_with_tab, "%s\t", tmp);
1487  sprintf (device_with_space, "%s ", tmp);
1488
1489  if (!(fin = popen ("mount", "r"))) { log_OS_error("Cannot popen 'mount'"); return(FALSE); }
1490  for (fgets (incoming, MAX_STR_LEN - 1, fin); !feof (fin);
1491       fgets (incoming, MAX_STR_LEN - 1, fin))
1492    {
1493      if ( strstr (incoming, device_with_space) //> incoming
1494      || strstr (incoming, device_with_tab) ) // > incoming)
1495    {
1496      paranoid_pclose (fin);
1497      retval=1;
1498      goto end_of_func;
1499    }
1500    }
1501  paranoid_pclose(fin);
1502  sprintf (tmp, "%s | grep -w \"%s\" > /dev/null 2> /dev/null",
1503       SWAPLIST_COMMAND, device_with_space);
1504  log_msg(4, "tmp (command) = '%s'", tmp);
1505  if (!system (tmp))
1506    {
1507      retval=1;
1508      goto end_of_func;
1509    }
1510end_of_func:
1511  paranoid_free(incoming);
1512  paranoid_free(device_with_tab);
1513  paranoid_free(device_with_space);
1514  paranoid_free(tmp);
1515  return (retval);
1516}
1517
1518#ifdef __FreeBSD__
1519//                       CODE IS FREEBSD-SPECIFIC
1520/**
1521 * Create a loopback device for specified @p fname.
1522 * @param fname The file to associate with a device.
1523 * @return /dev entry for the device, or NULL if it couldn't be allocated.
1524 */
1525char *
1526make_vn (char *fname)
1527{
1528    char *device   = (char*) malloc (MAX_STR_LEN);
1529    char *mddevice = (char*) malloc (32);
1530    char command[MAX_STR_LEN];
1531    int vndev = 2;
1532    if (atoi (call_program_and_get_last_line_of_output ("/sbin/sysctl -n kern.osreldate")) <
1533        500000) {
1534        do {
1535            sprintf (mddevice, "vn%ic", vndev++);
1536            sprintf (command, "vnconfig %s %s", mddevice, fname);
1537            if (vndev > 10) {
1538                return NULL;
1539            }
1540        }
1541       while (system (command));
1542    } else {
1543        sprintf (command, "mdconfig -a -t vnode -f %s", fname);
1544        mddevice = call_program_and_get_last_line_of_output (command);
1545        if (!strstr (mddevice, "md")) {
1546            return NULL;
1547        }
1548    }
1549    sprintf (device, "/dev/%s", mddevice);
1550    return device;
1551}
1552
1553
1554
1555//                       CODE IS FREEBSD-SPECIFIC
1556/**
1557 * Deallocate specified @p dname.
1558 * This should be called when you are done with the device created by make_vn(),
1559 * so the system does not run out of @c vn devices.
1560 * @param dname The device to deallocate.
1561 * @return 0 for success, nonzero for failure.
1562 */
1563int
1564kick_vn (char *dname)
1565{
1566    char command[MAX_STR_LEN];
1567
1568    if (strncmp (dname, "/dev/", 5) == 0) {
1569        dname += 5;
1570    }
1571
1572    if (atoi (call_program_and_get_last_line_of_output ("/sbin/sysctl -n kern.osreldate")) <
1573        500000) {
1574        sprintf (command, "vnconfig -d %s", dname);
1575        return system (command);
1576    } else {
1577        sprintf (command, "mdconfig -d -u %s", dname);
1578        return system (command);
1579    }
1580    /*NOTREACHED*/
1581    return 255;
1582}
1583#endif
1584
1585
1586/**
1587 * Mount the CD-ROM at @p mountpoint.
1588 * @param device The device (or file if g_ISO_restore_mode) to mount.
1589 * @param mountpoint The place to mount it.
1590 * @return 0 for success, nonzero for failure.
1591 */
1592int
1593mount_CDROM_here (char *device, char *mountpoint)
1594{
1595    /*@ buffer *******************************************************/
1596  char *command;
1597  char *dev;
1598  char *options;
1599  int retval;
1600
1601  malloc_string(command);
1602  malloc_string(dev);
1603  malloc_string(options);
1604  assert_string_is_neither_NULL_nor_zerolength(device);
1605  assert_string_is_neither_NULL_nor_zerolength(mountpoint);
1606
1607  make_hole_for_dir(mountpoint);
1608  strcpy(options, "ro");
1609  if (isdigit(device[0]))
1610    { find_cdrom_device(device, FALSE); }
1611  else
1612    { strcpy(dev, device); }
1613  if (g_ISO_restore_mode)
1614    {
1615
1616#ifdef __FreeBSD__
1617      strcpy (dev, make_vn (device));
1618      if (!dev) {
1619          sprintf (command, "Unable to mount ISO (make_vn(%s) failed)", device);
1620          fatal_error (command);
1621        }
1622      strcpy (device, dev);
1623#else
1624      strcat(options,",loop");
1625#endif
1626
1627    }
1628  log_msg(4, "(mount_CDROM_here --- device=%s, mountpoint=%s", device, mountpoint);
1629    /*@ end vars ****************************************************/
1630
1631#ifdef __FreeBSD__
1632  sprintf (command, "mount_cd9660 -r %s %s 2>> %s",
1633           device, mountpoint, MONDO_LOGFILE);
1634
1635#else
1636  sprintf (command, "mount %s -o %s -t iso9660 %s 2>> %s",
1637           device, options, mountpoint, MONDO_LOGFILE);
1638#endif
1639
1640  log_msg (4, command);
1641  if (strncmp(device, "/dev/", 5) == 0)
1642    {
1643      retract_CD_tray_and_defeat_autorun(); 
1644    }
1645  retval = system (command);
1646  log_msg(1, "system(%s) returned %d", command, retval);
1647
1648  paranoid_free(command);
1649  paranoid_free(dev);
1650  paranoid_free(options);
1651  return(retval);
1652}
1653
1654
1655
1656
1657
1658
1659/**
1660 * Ask the user for CD number @p cd_number_i_want.
1661 * Sets g_current_media_number once the correct CD is inserted.
1662 * @param bkpinfo The backup information structure. Fields used:
1663 * - @c bkpinfo->backup_media_type
1664 * - @c bkpinfo->isodir
1665 * - @c bkpinfo->media_device
1666 * - @c bkpinfo->please_dont_eject_when_restoring
1667 * @param cd_number_i_want The CD number to ask for.
1668 */
1669void
1670insist_on_this_cd_number (struct s_bkpinfo* bkpinfo, int cd_number_i_want)
1671{
1672
1673    /*@ int **************************************************************/
1674  int res = 0;
1675
1676
1677    /*@ buffers **********************************************************/
1678  char *tmp;
1679  char *request;
1680
1681  assert(bkpinfo!=NULL);
1682  assert(cd_number_i_want > 0);
1683
1684//  log_msg(3, "Insisting on CD number %d", cd_number_i_want);
1685
1686  if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type))
1687    {
1688      log_msg(3, "No need to insist_on_this_cd_number when the backup type isn't CD-R(W) or NFS or ISO");
1689      return;
1690    }
1691  malloc_string(tmp);
1692  malloc_string(request);
1693  sprintf(tmp, "mkdir -p "MNT_CDROM);
1694  run_program_and_log_output(tmp, 5);
1695  if (g_ISO_restore_mode || bkpinfo->backup_media_type == iso || bkpinfo->backup_media_type == nfs)
1696    {
1697      log_msg(3, "Remounting CD");
1698      g_ISO_restore_mode = TRUE;
1699// FIXME --- I'm tempted to do something about this...
1700// Why unmount and remount again and again?
1701      if (is_this_device_mounted(MNT_CDROM)) { run_program_and_log_output("umount "MNT_CDROM, 5); }
1702      system("mkdir -p /tmp/isodir &> /dev/null");
1703      sprintf(tmp, "%s/%s/%d.iso", bkpinfo->isodir, bkpinfo->nfs_remote_dir, cd_number_i_want);
1704      if (!does_file_exist(tmp))
1705        {
1706      sprintf(tmp, "/tmp/isodir/%s/%d.iso", bkpinfo->nfs_remote_dir, cd_number_i_want);
1707      if (does_file_exist(tmp))
1708        {
1709          log_msg(1, "FIXME - hacking bkpinfo->isodir from '%s' to /tmp/isodir", bkpinfo->isodir);
1710          strcpy(bkpinfo->isodir, "/tmp/isodir");
1711        }
1712        }
1713      log_msg(3, "Mounting %s at %s", tmp, MNT_CDROM);
1714      if (mount_CDROM_here(tmp, MNT_CDROM)) { fatal_error("Mommy!"); }
1715//    g_current_media_number = cd_number_i_want;
1716//    return;
1717    }
1718  if ((res=what_number_cd_is_this (bkpinfo)) != cd_number_i_want)
1719    {
1720      log_msg(3, "Currently, we hold %d but we want %d", res, cd_number_i_want);
1721      sprintf (tmp, "Insisting on %s #%d", media_descriptor_string(bkpinfo->backup_media_type), cd_number_i_want);
1722      sprintf (request, "Please insert %s #%d and press Enter.",
1723               media_descriptor_string(bkpinfo->backup_media_type),
1724           cd_number_i_want);
1725      log_msg (3, tmp);
1726      while (what_number_cd_is_this (bkpinfo) != cd_number_i_want)
1727    {
1728      paranoid_system ("sync");
1729      if (is_this_device_mounted (MNT_CDROM))
1730        {
1731          res = run_program_and_log_output ("umount "MNT_CDROM, FALSE);
1732        }
1733      else
1734        {
1735          res = 0;
1736        }
1737      if (res)
1738        {
1739          log_to_screen ("WARNING - failed to unmount CD-ROM drive");
1740        }
1741          if (!bkpinfo->please_dont_eject)
1742            { res = eject_device(bkpinfo->media_device); }
1743          else
1744            { res = 0; }
1745      if (res)
1746        {
1747              log_to_screen ("WARNING - failed to eject CD-ROM disk");
1748        }
1749          popup_and_OK (request);
1750          if (!bkpinfo->please_dont_eject)
1751            {
1752              inject_device(bkpinfo->media_device);
1753            }
1754      paranoid_system ("sync");
1755    }
1756      log_msg (1, "Thankyou. Proceeding...");
1757      g_current_media_number = cd_number_i_want;
1758    }
1759  paranoid_free(tmp);
1760  paranoid_free(request);
1761}
1762
1763/* @} - end of deviceGroup */
1764
1765
1766
1767
1768
1769
1770/**
1771 * Ask user for details of backup/restore information.
1772 * Called when @c mondoarchive doesn't get any parameters.
1773 * @param bkpinfo The backup information structure to fill out with the user's data.
1774 * @param archiving_to_media TRUE if archiving, FALSE if restoring.
1775 * @return 0, always.
1776 * @bug No point of `int' return value.
1777 * @ingroup archiveGroup
1778 */
1779int interactively_obtain_media_parameters_from_user(struct s_bkpinfo *bkpinfo, bool archiving_to_media)
1780// archiving_to_media is TRUE if I'm being called by mondoarchive
1781// archiving_to_media is FALSE if I'm being called by mondorestore
1782{
1783  char *tmp;
1784  char *sz_size;
1785  char *command;
1786  char *comment;
1787  int i;
1788  FILE*fin;
1789
1790  malloc_string(tmp);
1791  malloc_string(sz_size);
1792  malloc_string(command);
1793  malloc_string(comment);
1794  assert(bkpinfo!=NULL);
1795  sz_size[0] = '\0';
1796  bkpinfo->nonbootable_backup = FALSE;
1797
1798// Tape, CD, NFS, ...?
1799  srandom(getpid());
1800  bkpinfo->backup_media_type = (g_restoring_live_from_cd) ? cdr : which_backup_media_type(bkpinfo->restore_data);
1801  if (bkpinfo->backup_media_type == none)
1802    { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1803  if (bkpinfo->backup_media_type == tape && bkpinfo->restore_data)
1804    { popup_and_OK("Please remove CD/floppy from drive(s)"); }
1805  log_msg(3, "media type = %s", bkptype_to_string(bkpinfo->backup_media_type));
1806  if (archiving_to_media)
1807    {
1808      sensibly_set_tmpdir_and_scratchdir(bkpinfo);
1809    }
1810  bkpinfo->cdrw_speed = (bkpinfo->backup_media_type == cdstream) ? 2 : 4;
1811  bkpinfo->compression_level = (bkpinfo->backup_media_type == cdstream) ? 1:5;
1812  bkpinfo->use_lzo =  (bkpinfo->backup_media_type == cdstream) ? TRUE : FALSE;
1813
1814/*
1815  if (find_home_of_exe("star") && (!find_home_of_exe("afio") || find_home_of_exe("selinuxenabled")))
1816    {
1817      bkpinfo->use_star = FALSE;   
1818      bkpinfo->use_lzo = FALSE;
1819      log_to_screen("Using star, not afio");
1820      if (!find_home_of_exe("afio"))
1821    { log_to_screen("...because afio not found"); }
1822      if (find_home_of_exe("selinuxenabled"))
1823    { log_to_screen("...because SELINUX found"); }
1824    }
1825*/
1826
1827  mvaddstr_and_log_it(2, 0, " ");
1828
1829// Find device's /dev (or SCSI) entry
1830  switch(bkpinfo->backup_media_type)
1831    {
1832      case cdr:
1833      case cdrw:
1834      case dvd:
1835    if (archiving_to_media)
1836          {
1837            if (ask_me_yes_or_no("Is your computer a laptop, or does the CD writer incorporate BurnProof technology?"))
1838              { bkpinfo->manual_cd_tray = TRUE; }
1839            if ((bkpinfo->compression_level = which_compression_level()) == -1)
1840              { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1841        sprintf(comment, "What speed is your %s (re)writer?", media_descriptor_string(bkpinfo->backup_media_type));
1842        if (bkpinfo->backup_media_type==dvd)
1843          {
1844        find_dvd_device(bkpinfo->media_device, FALSE);
1845            strcpy(tmp, "1");
1846        sprintf(sz_size, "%d", DEFAULT_DVD_DISK_SIZE); // 4.7 salesman's GB = 4.482 real GB = 4582 MB
1847        log_msg(1, "Setting to DVD defaults");
1848          }
1849        else
1850          {
1851                strcpy(bkpinfo->media_device, VANILLA_SCSI_CDROM);
1852            strcpy(tmp, "4");
1853        strcpy(sz_size, "650");
1854        log_msg(1, "Setting to CD defaults");
1855          }
1856        if (bkpinfo->backup_media_type != dvd)
1857          {
1858            if (!popup_and_get_string("Speed", comment, tmp, 4))
1859              { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1860          }
1861            bkpinfo->cdrw_speed = atoi(tmp); // if DVD then this shouldn't ever be used anyway :)
1862        sprintf(comment, "How much data (in Megabytes) will each %s store?", media_descriptor_string(bkpinfo->backup_media_type));
1863        if (!popup_and_get_string("Size", comment, sz_size, 5))
1864          { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1865        for(i=0; i<=MAX_NOOF_MEDIA; i++) { bkpinfo->media_size[i] = atoi(sz_size); }
1866        if (bkpinfo->media_size[0] <=0)
1867              { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1868          }
1869      case cdstream:
1870    if (bkpinfo->disaster_recovery)
1871      {
1872            strcpy(bkpinfo->media_device, "/dev/cdrom");
1873        log_msg(2, "CD-ROM device assumed to be at %s", bkpinfo->media_device);
1874      }
1875    else if (bkpinfo->restore_data
1876        || bkpinfo->backup_media_type == dvd)
1877      {
1878            if (!bkpinfo->media_device[0])
1879              { strcpy(bkpinfo->media_device, "/dev/cdrom"); } // just for the heck of it :)
1880        log_msg(1, "bkpinfo->media_device = %s", bkpinfo->media_device);
1881        if (bkpinfo->backup_media_type == dvd || find_cdrom_device (bkpinfo->media_device, FALSE))
1882          {
1883        log_msg(1, "bkpinfo->media_device = %s", bkpinfo->media_device);
1884            sprintf(comment, "Please specify your %s drive's /dev entry", media_descriptor_string(bkpinfo->backup_media_type));
1885            if (!popup_and_get_string("Device?", comment, bkpinfo->media_device, MAX_STR_LEN/4))
1886              { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1887          }
1888        log_msg(2, "%s device found at %s", media_descriptor_string(bkpinfo->backup_media_type), bkpinfo->media_device);
1889      }
1890    else
1891      {
1892        if (find_cdrw_device(bkpinfo->media_device)) { bkpinfo->media_device[0]='\0'; }
1893        if (bkpinfo->media_device[0])
1894          {
1895            sprintf(tmp, "I think I've found your %s burner at SCSI node %s; am I right on the money?", media_descriptor_string(bkpinfo->backup_media_type), bkpinfo->media_device);
1896            if (!ask_me_yes_or_no(tmp)) { bkpinfo->media_device[0]='\0'; }
1897          }
1898           if (!bkpinfo->media_device[0])
1899          {
1900        if (g_kernel_version < 2.6)
1901          {
1902            i=popup_and_get_string("Device node?", "What is the SCSI node of your CD (re)writer, please?", bkpinfo->media_device, MAX_STR_LEN/4);
1903          }
1904        else
1905          {
1906            i=popup_and_get_string("/dev entry?", "What is the /dev entry of your CD (re)writer, please?", bkpinfo->media_device, MAX_STR_LEN/4);
1907          }
1908        if (!i)
1909              { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1910          }
1911      }
1912    if (bkpinfo->backup_media_type == cdstream)
1913      {
1914        for(i=0; i<=MAX_NOOF_MEDIA; i++) { bkpinfo->media_size[i] = 650; }
1915      }
1916    break;
1917      case udev:
1918    if (!ask_me_yes_or_no("This option is for advanced users only. Are you sure?"))
1919      { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1920      case tape:
1921
1922    if (find_tape_device_and_size(bkpinfo->media_device, sz_size))
1923      {
1924        log_msg(3, "Ok, using vanilla scsi tape.");
1925        strcpy(bkpinfo->media_device, VANILLA_SCSI_TAPE);
1926        if ((fin=fopen(bkpinfo->media_device, "r")))
1927          { paranoid_fclose(fin); }
1928        else
1929          { strcpy(bkpinfo->media_device, "/dev/osst0"); }
1930      }
1931    if (bkpinfo->media_device[0])
1932      {
1933        if ((fin=fopen(bkpinfo->media_device, "r")))
1934          { paranoid_fclose(fin); }
1935        else
1936          {
1937        if (does_file_exist("/tmp/mondo-restore.cfg"))
1938          {
1939            read_cfg_var("/tmp/mondo-restore.cfg", "media-dev", bkpinfo->media_device);
1940          }
1941          }
1942        sprintf(tmp, "I think I've found your tape streamer at %s; am I right on the money?", bkpinfo->media_device);
1943      }
1944    if (bkpinfo->media_device[0])
1945      {
1946        sprintf(tmp, "I think I've found your tape streamer at %s; am I right on the money?", bkpinfo->media_device);
1947        if (!ask_me_yes_or_no(tmp)) { bkpinfo->media_device[0]='\0'; }
1948      }
1949        if (!bkpinfo->media_device[0])
1950      {
1951        if (!popup_and_get_string("Device name?", "What is the /dev entry of your tape streamer?", bkpinfo->media_device, MAX_STR_LEN/4))
1952          { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1953      }
1954    sprintf(tmp, "ls -l %s", bkpinfo->media_device);
1955    if (run_program_and_log_output(tmp, FALSE))
1956          { log_to_screen("User has not specified a valid /dev entry"); finish(1); }
1957    log_msg(4, "sz_size = %s", sz_size);
1958        sz_size[0] = '\0';
1959/*
1960    if ((size_sz[0]=='\0' || atol(size_sz)==0) && archiving_to_media)
1961      {
1962        if (!popup_and_get_string("Tape size", "How much COMPRESSED data will one of your tape cartridges hold? (e.g. 4GB for 4 gigabytes)", size_sz, 16))
1963          { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1964      }
1965*/
1966    if (sz_size[0]=='\0')
1967      { bkpinfo->media_size[0] = 0; }
1968        else
1969      { bkpinfo->media_size[0] = friendly_sizestr_to_sizelong (sz_size)/2 - 50; }
1970    log_msg(4, "media_size[0] = %ld", bkpinfo->media_size[0]);
1971        if (bkpinfo->media_size[0] <= 0) { bkpinfo->media_size[0] = 0; }
1972    for(i=1; i<=MAX_NOOF_MEDIA; i++) { bkpinfo->media_size[i] = bkpinfo->media_size[0]; }
1973        if (archiving_to_media)
1974          {
1975            if ((bkpinfo->compression_level = which_compression_level()) == -1)
1976              { log_to_screen("User has chosen not to backup the PC"); finish(1); }
1977          }
1978        break;
1979
1980
1981
1982      case nfs:
1983    if (!bkpinfo->nfs_mount[0]) { strcpy(bkpinfo->nfs_mount, call_program_and_get_last_line_of_output("mount | grep \":\" | cut -d' ' -f1 | head -n1")); }
1984#ifdef __FreeBSD__
1985        if (TRUE)
1986#else
1987    if (!bkpinfo->disaster_recovery )
1988#endif
1989      {
1990        if (!popup_and_get_string("NFS dir.", "Please enter path and directory where archives are stored remotely. (Mondo has taken a guess at the correct value. If it is incorrect, delete it and type the correct one.)", bkpinfo->nfs_mount, MAX_STR_LEN/4))
1991          {
1992        log_to_screen("User has chosen not to backup the PC");
1993        finish(1);
1994          }
1995            if (!bkpinfo->restore_data)
1996              {
1997                if ((bkpinfo->compression_level = which_compression_level()) == -1)
1998                  {
1999                    log_to_screen("User has chosen not to backup the PC");
2000                    finish(1);
2001                  }
2002              }
2003            sprintf(command, "mount | grep %s | cut -d' ' -f3", bkpinfo->nfs_mount);
2004            strcpy(bkpinfo->isodir, call_program_and_get_last_line_of_output(command));
2005      }
2006    if (bkpinfo->disaster_recovery)
2007          {
2008        system("umount /tmp/isodir 2> /dev/null");
2009        if (!popup_and_get_string("NFS share", "Which remote NFS share should I mount?", bkpinfo->nfs_mount, MAX_STR_LEN))
2010          {
2011                log_to_screen("User has chosen not to backup the PC");
2012                finish(1);
2013          }
2014          }
2015        if (!is_this_device_mounted(bkpinfo->nfs_mount))
2016          {
2017            sprintf(bkpinfo->isodir, "/tmp/isodir");
2018        run_program_and_log_output("mkdir -p /tmp/isodir", 5);
2019        sprintf(tmp, "mount %s -t nfs /tmp/isodir", bkpinfo->nfs_mount);
2020        run_program_and_log_output(tmp, 5);
2021          }
2022    if (!is_this_device_mounted(bkpinfo->nfs_mount))
2023      {
2024        popup_and_OK("Please mount that partition before you try to backup to or restore from it.");
2025        finish(1);
2026      }
2027        strcpy(tmp, bkpinfo->nfs_remote_dir);
2028        if (!popup_and_get_string("Directory", "Which directory within that mountpoint?", tmp, MAX_STR_LEN))
2029          {
2030            log_to_screen("User has chosen not to backup the PC");
2031             finish(1);
2032          }
2033        strcpy(bkpinfo->nfs_remote_dir, tmp);
2034    for(i=0; i<=MAX_NOOF_MEDIA; i++) { bkpinfo->media_size[i] = 650; }
2035        log_msg(3, "Just set nfs_remote_dir to %s", bkpinfo->nfs_remote_dir);
2036    log_msg(3, "isodir is still %s", bkpinfo->isodir);
2037    break;
2038
2039      case iso:
2040        if (!bkpinfo->disaster_recovery)
2041          {
2042             if (!popup_and_get_string("Storage dir.", "Please enter the full path that contains your ISO images.  Example: /mnt/raid0_0", bkpinfo->isodir, MAX_STR_LEN/4))
2043          { log_to_screen("User has chosen not to backup the PC"); finish(1); }
2044             if (archiving_to_media) {
2045                 if ((bkpinfo->compression_level = which_compression_level()) == -1)
2046                     { log_to_screen("User has chosen not to backup the PC"); finish(1); }
2047                 if (!popup_and_get_string ("ISO size.", "Please enter how big you want each ISO image to be (in megabytes). This should be less than or equal to the size of the CD-R[W]'s you plan to backup to.", sz_size, 16))
2048                     { log_to_screen ("User has chosen not to backup the PC"); finish(1); }
2049                 for(i=0; i<=MAX_NOOF_MEDIA; i++) { bkpinfo->media_size[i] = atoi (sz_size); }
2050             } else {
2051                 for (i=0;i<=MAX_NOOF_MEDIA; i++) { bkpinfo->media_size[i] = 650;}
2052             }
2053          }
2054    break;
2055      default:
2056    fatal_error("I, Mojo Jojo, shall defeat those pesky Powerpuff Girls!");
2057    }
2058
2059  if (archiving_to_media)
2060    {
2061
2062#ifdef __FreeBSD__
2063    strcpy (bkpinfo->boot_device, call_program_and_get_last_line_of_output
2064        ("mount | grep ' / ' | head -1 | cut -d' ' -f1 | sed 's/\\([0-9]\\).*/\\1/'"));
2065#else
2066    strcpy (bkpinfo->boot_device, call_program_and_get_last_line_of_output
2067            ("mount | grep ' / ' | head -1 | cut -d' ' -f1 | sed 's/[0-9].*//'"));
2068#endif
2069      i = which_boot_loader(bkpinfo->boot_device);
2070      if (i=='U') // unknown
2071        {
2072
2073#ifdef __FreeBSD__
2074          if (!popup_and_get_string("Boot device", "What is your boot device? (e.g. /dev/ad0)", bkpinfo->boot_device, MAX_STR_LEN/4))
2075            { log_to_screen("User has chosen not to backup the PC"); finish(1); }
2076          i = which_boot_loader (bkpinfo->boot_device);
2077#else
2078          if (!popup_and_get_string("Boot device", "What is your boot device? (e.g. /dev/hda)", bkpinfo->boot_device, MAX_STR_LEN/4))
2079            { log_to_screen("User has chosen not to backup the PC"); finish(1); }
2080          if (does_string_exist_in_boot_block(bkpinfo->boot_device, "LILO")) { i='L'; }
2081          else if (does_string_exist_in_boot_block(bkpinfo->boot_device, "ELILO")) { i='E'; }
2082          else if (does_string_exist_in_boot_block(bkpinfo->boot_device, "GRUB")) { i='G'; }
2083          else { i = 'U'; }
2084#endif
2085          if (i == 'U')
2086            {
2087          if (ask_me_yes_or_no("Unidentified boot loader. Shall I restore it byte-for-byte at restore time and hope for the best?"))
2088        {
2089          i = 'R'; // raw
2090        }
2091          else
2092        {
2093          log_to_screen("I cannot find your boot loader. Please run mondoarchive with parameters."); finish(1);
2094        }
2095        }
2096    }
2097      bkpinfo->boot_loader = i;
2098      strcpy(bkpinfo->include_paths, "/");
2099      if (!popup_and_get_string("Backup paths", "Please enter paths which you want me to backup. The default is '/' (i.e. everything).", bkpinfo->include_paths, MAX_STR_LEN))
2100        { log_to_screen("User has chosen not to backup the PC"); finish(1); }
2101      strcpy(tmp, list_of_NFS_mounts_only());
2102      if (strlen(tmp)>2)
2103        {
2104          if (bkpinfo->exclude_paths[0]) { strcat(bkpinfo->exclude_paths, " "); }
2105          strncpy(bkpinfo->exclude_paths, tmp, MAX_STR_LEN);
2106    }
2107
2108// NTFS
2109      strcpy(tmp, call_program_and_get_last_line_of_output("parted2fdisk -l | grep -i ntfs | awk '{ print $1};' | tr -s '\\n' ' ' | awk '{ print $0};'"));
2110      if (strlen(tmp) > 2)
2111        {
2112      if (!popup_and_get_string("NTFS partitions", "Please enter/confirm the NTFS partitions you wish to backup as well.", tmp, MAX_STR_LEN/4))
2113            { log_to_screen ("User has chosen not to backup the PC"); finish(1); }
2114          strncpy (bkpinfo->image_devs, tmp, MAX_STR_LEN/4);
2115    }
2116
2117
2118      if (!popup_and_get_string("Exclude paths", "Please enter paths which you do NOT want to backup. Separate them with spaces. NB: /tmp and /proc are always excluded. :-) Just hit 'Enter' if you want to do a full system backup.", bkpinfo->exclude_paths, MAX_STR_LEN))
2119        { log_to_screen("User has chosen not to backup the PC"); finish(1); }
2120      bkpinfo->make_cd_use_lilo = FALSE;
2121      bkpinfo->backup_data = TRUE;
2122      bkpinfo->verify_data = ask_me_yes_or_no("Will you want to verify your backups after Mondo has created them?");
2123
2124#ifndef __FreeBSD__
2125      if (!ask_me_yes_or_no("Are you confident that your kernel is a sane, sensible, standard Linux kernel? Say 'no' if you are using a Gentoo <1.4 or Debian <3.0, please."))
2126#endif
2127        { strcpy(bkpinfo->kernel_path, "FAILSAFE"); }
2128
2129      if (!ask_me_yes_or_no("Are you sure you want to proceed? Hit 'no' to abort."))
2130        { log_to_screen("User has chosen not to backup the PC"); finish(1); }
2131    }
2132  else
2133    {
2134      bkpinfo->restore_data = TRUE; // probably...
2135    }
2136
2137  if (bkpinfo->backup_media_type == iso || bkpinfo->backup_media_type == nfs)
2138    {
2139      g_ISO_restore_mode = TRUE;
2140    }
2141
2142#ifdef __FreeSD__
2143// skip
2144#else
2145  if (bkpinfo->backup_media_type == nfs)
2146    {
2147      sprintf(tmp, "mount | grep \"%s\" | cut -d' ' -f3", bkpinfo->nfs_mount);
2148//      strcpy(bkpinfo->isodir, call_program_and_get_last_line_of_output(tmp));
2149      log_msg(3, "I think the NFS mount is mounted at %s", bkpinfo->isodir);
2150    }
2151  log_it("isodir = %s", bkpinfo->isodir);
2152  log_it("nfs_mount = '%s'", bkpinfo->nfs_mount);
2153#endif
2154
2155  log_it("media device = %s", bkpinfo->media_device);
2156  log_it("media size = %ld", bkpinfo->media_size[1]);
2157  log_it("media type = %s", bkptype_to_string(bkpinfo->backup_media_type));
2158  log_it("compression = %ld", bkpinfo->compression_level);
2159  log_it("include_paths = '%s'", bkpinfo->include_paths);
2160  log_it("exclude_paths = '%s'", bkpinfo->exclude_paths);
2161  log_it("scratchdir = '%s'", bkpinfo->scratchdir);
2162  log_it("tmpdir = '%s'", bkpinfo->tmpdir);
2163  log_it("boot_device = '%s' (loader=%c)", bkpinfo->boot_device, bkpinfo->boot_loader);
2164  if (bkpinfo->media_size[0] < 0) 
2165    {
2166      if (archiving_to_media)
2167        {
2168          fatal_error("Media size is less than zero.");
2169        }
2170      else
2171        {
2172      log_msg(2, "Warning - media size is less than zero.");
2173      bkpinfo->media_size[0] = 0;
2174    }
2175    }
2176  paranoid_free(tmp);
2177  paranoid_free(sz_size);
2178  paranoid_free(command);
2179  paranoid_free(comment);
2180  return(0);
2181}
2182
2183
2184
2185
2186/**
2187 * @addtogroup utilityGroup
2188 * @{
2189 */
2190/**
2191 * Get a space-separated list of NFS devices and mounts.
2192 * @return The list created.
2193 * @note The return value points to static data that will be overwritten with each call.
2194 */
2195char *list_of_NFS_devices_and_mounts(void)
2196{
2197  char *exclude_these_devices;
2198  char *exclude_these_directories;
2199  static char result_sz[512];
2200
2201  malloc_string(exclude_these_devices);
2202  malloc_string(exclude_these_directories);
2203  strcpy(exclude_these_directories, call_program_and_get_last_line_of_output("mount -t coda,ncpfs,nfs,smbfs | tr -s '\t' ' ' | cut -d' ' -f3 | tr -s '\n' ' ' | awk '{print $0;}'"));
2204  strcpy(exclude_these_devices, call_program_and_get_last_line_of_output("cat /etc/fstab | tr -s '\t' ' ' | grep -E '( (coda|ncpfs|nfs|smbfs) )' | cut -d' ' -f1 | tr -s '\n' ' ' | awk '{print $0;}'"));
2205  sprintf(result_sz, "%s %s", exclude_these_directories, exclude_these_devices);
2206  paranoid_free(exclude_these_devices);
2207  paranoid_free(exclude_these_directories);
2208  return(result_sz);
2209}
2210
2211
2212
2213
2214/**
2215 * Get a space-separated list of NFS mounts.
2216 * @return The list created.
2217 * @note The return value points to static data that will be overwritten with each call.
2218 * @bug Even though we only want the mounts, the devices are still checked.
2219 */
2220char *list_of_NFS_mounts_only(void)
2221{
2222  char *exclude_these_devices;
2223  char *exclude_these_directories;
2224  static char result_sz[512];
2225
2226  malloc_string(exclude_these_devices);
2227  malloc_string(exclude_these_directories);
2228  strcpy(exclude_these_directories, call_program_and_get_last_line_of_output("mount -t coda,ncpfs,nfs,smbfs | tr -s '\t' ' ' | cut -d' ' -f3 | tr -s '\n' ' ' | awk '{print $0;}'"));
2229  strcpy(exclude_these_devices, call_program_and_get_last_line_of_output("cat /etc/fstab | tr -s '\t' ' ' | grep -E '( (coda|ncpfs|nfs|smbfs) )' | cut -d' ' -f1 | tr -s '\n' ' ' | awk '{print $0;}'"));
2230  sprintf(result_sz, "%s", exclude_these_directories);
2231  paranoid_free(exclude_these_devices);
2232  paranoid_free(exclude_these_directories);
2233  return(result_sz);
2234}
2235
2236/* @} - end of utilityGroup */
2237
2238
2239
2240
2241
2242/**
2243 * Create a randomly-named FIFO. The format is @p stub "." [random] [random] where
2244 * [random] is a random number between 1 and 32767.
2245 * @param store_name_here Where to store the new filename.
2246 * @param stub A random number will be appended to this to make the FIFO's name.
2247 * @ingroup deviceGroup
2248 */
2249void make_fifo(char*store_name_here, char*stub)
2250{
2251  char *tmp;
2252
2253  malloc_string(tmp);
2254  assert_string_is_neither_NULL_nor_zerolength(stub);
2255
2256  sprintf(store_name_here, "%s%d%d", stub, (int)(random()%32768), (int)(random()%32768));
2257  make_hole_for_file(store_name_here);
2258  mkfifo(store_name_here, S_IRWXU|S_IRWXG);
2259  sprintf(tmp, "chmod 770 %s", store_name_here);
2260  paranoid_system(tmp);
2261  paranoid_free(tmp);
2262}
2263
2264
2265
2266
2267
2268
2269/**
2270 * Set the tmpdir and scratchdir to reside on the partition with the most free space.
2271 * Automatically excludes DOS, NTFS, SMB, and NFS filesystems.
2272 * @param bkpinfo The backup information structure. @c bkpinfo->tmpdir and @c bkpinfo->scratchdir will be set.
2273 * @ingroup utilityGroup
2274 */
2275void sensibly_set_tmpdir_and_scratchdir(struct s_bkpinfo *bkpinfo)
2276{
2277  char *tmp, *command, *sz;
2278
2279  malloc_string(tmp);
2280  malloc_string(command);
2281  malloc_string(sz);
2282  assert(bkpinfo!=NULL);
2283
2284#ifdef __FreeBSD__
2285      strcpy(tmp, call_program_and_get_last_line_of_output("df -m -t nonfs,msdosfs,ntfs,smbfs,smb,cifs | tr -s '\t' ' ' | grep -v none | grep -v Filesystem | awk '{printf \"%s %s\\n\", $4, $6;}' | sort -n | tail -n1 | awk '{print $NF;}'"));
2286#else
2287      strcpy(tmp, call_program_and_get_last_line_of_output("df -m -x nfs -x vfat -x ntfs -x smbfs -x smb -x cifs | sed 's/                  /devdev/' | tr -s '\t' ' ' | grep -v none | grep -v Filesystem | grep -v /dev/shm | awk '{printf \"%s %s\\n\", $4, $6;}' | sort -n | tail -n1 | awk '{print $NF;}'"));
2288#endif
2289
2290      if (tmp[0]!='/') { strcpy(sz, tmp); strcpy(tmp, "/"); strcat(tmp, sz); }
2291      if (!tmp[0]) {
2292      fatal_error ("I couldn't figure out the tempdir!");
2293      }
2294      sprintf(bkpinfo->tmpdir, "%s/tmp.mondo.%d", tmp, (int)(random()%32768));
2295      log_it("bkpinfo->tmpdir is being set to %s", bkpinfo->tmpdir);
2296
2297      sprintf(bkpinfo->scratchdir, "%s/mondo.scratch.%d", tmp, (int)(random()%32768));
2298      log_it("bkpinfo->scratchdir is being set to %s", bkpinfo->scratchdir);
2299
2300      sprintf(g_erase_tmpdir_and_scratchdir, "rm -Rf %s %s", bkpinfo->tmpdir, bkpinfo->scratchdir);
2301     
2302      sprintf(command, "rm -Rf %s/tmp.mondo.* %s/mondo.scratch.*", tmp, tmp);
2303      paranoid_system(command);
2304  paranoid_free(tmp);
2305  paranoid_free(command);
2306  paranoid_free(sz);
2307}
2308
2309
2310
2311
2312
2313
2314/**
2315 * @addtogroup deviceGroup
2316 * @{
2317 */
2318/**
2319 * If we can read @p dev, set @p output to it.
2320 * If @p dev cannot be read, set @p output to "".
2321 * @param dev The device to check for.
2322 * @param output Set to @p dev if @p dev exists, "" otherwise.
2323 * @return TRUE if @p dev exists, FALSE if it doesn't.
2324 */
2325bool set_dev_to_this_if_rx_OK(char *output, char*dev)
2326{
2327  char *command;
2328
2329  malloc_string(command);
2330  if (!dev || dev[0]=='\0') { output[0]='\0'; return(FALSE); }
2331//  assert_string_is_neither_NULL_nor_zerolength(dev);
2332  log_msg(10, "Injecting %s", dev);
2333  inject_device(dev);
2334  if (!does_file_exist(dev)) { log_msg(10, "%s doesn't exist. Returning FALSE.", dev); return(FALSE); }
2335  sprintf(command, "dd bs=%ld count=1 if=%s of=/dev/null &> /dev/null", 512L, dev);
2336  if (!run_program_and_log_output(command, FALSE) && !run_program_and_log_output(command, FALSE))
2337    { strcpy(output, dev); log_msg(4, "Found it - %s", dev); return(TRUE); }
2338  else
2339    { output[0]='\0'; log_msg(4, "It's not %s",dev); return(FALSE); }
2340}
2341
2342
2343
2344
2345
2346/**
2347 * Find out what number CD is in the drive.
2348 * @param bkpinfo The backup information structure. The @c bkpinfo->media_device field is the only one used.
2349 * @return The current CD number, or -1 if it could not be found.
2350 * @note If the CD is not mounted, it will be mounted
2351 * (and remain mounted after this function returns).
2352 */
2353int what_number_cd_is_this(struct s_bkpinfo *bkpinfo)
2354{
2355  int cd_number=-1;
2356  char *mountdev;
2357  char *tmp;
2358
2359  malloc_string(mountdev);
2360  malloc_string(tmp);
2361  assert(bkpinfo!=NULL);
2362//  log_it("Asking what_number_cd_is_this");
2363  if (g_ISO_restore_mode)
2364    {
2365      sprintf(tmp, "mount | grep iso9660 | awk '{print $3;}'");
2366//      log_it("tmp = %s", tmp);
2367
2368      strcpy(mountdev, call_program_and_get_last_line_of_output(tmp));
2369      strcat(mountdev, "/archives/THIS-CD-NUMBER");
2370//      log_it("mountdev = %s", mountdev);
2371      cd_number = atoi(last_line_of_file(mountdev));
2372//      log_it("cd_number = %d", cd_number);
2373paranoid_free(mountdev);
2374paranoid_free(tmp);
2375      return(cd_number);
2376    }
2377
2378  strcpy(mountdev, bkpinfo->media_device);
2379  if (!mountdev[0])
2380    {
2381      log_it("(what_number_cd_is_this) Warning - media_device unknown. Finding out...");
2382      find_cdrom_device(bkpinfo->media_device, FALSE);
2383    }
2384  if (! is_this_device_mounted(MNT_CDROM))
2385    { mount_CDROM_here(mountdev, MNT_CDROM); }
2386  cd_number = atoi(last_line_of_file(MNT_CDROM"/archives/THIS-CD-NUMBER"));
2387//  log_it("cd_number..later.. = %d", cd_number);
2388paranoid_free(mountdev);
2389paranoid_free(tmp);
2390  return(cd_number);
2391}
2392
2393
2394
2395
2396
2397
2398
2399/**
2400 * Find out what device is mounted as root (/).
2401 * @return Root device.
2402 * @note The returned string points to static storage and will be overwritten with every call.
2403 * @bug A bit of a misnomer; it's actually finding out the root device.
2404 * The mountpoint (where it's mounted) will obviously be '/'.
2405 */
2406char *
2407where_is_root_mounted ()
2408{
2409    /*@ buffers *****************/
2410  static char tmp[MAX_STR_LEN];
2411
2412
2413#ifdef __FreeBSD__
2414  strcpy (tmp, call_program_and_get_last_line_of_output
2415          ("mount | grep \" on / \" | cut -d' ' -f1"));
2416#else
2417  strcpy (tmp, call_program_and_get_last_line_of_output
2418      ("mount | grep \" on / \" | cut -d' ' -f1 | sed s/[0-9]// | sed s/[0-9]//"));
2419  if (strstr(tmp, "/dev/cciss/")) {
2420      strcpy (tmp, call_program_and_get_last_line_of_output
2421              ("mount | grep \" on / \" | cut -d' ' -f1 | cut -dp -f1"));
2422  }
2423  if (strstr(tmp, "/dev/md"))
2424    {
2425      strcpy(tmp,
2426         call_program_and_get_last_line_of_output
2427         ("mount | grep \" on / \" | cut -d' ' -f1"));
2428    }
2429#endif
2430
2431  return (tmp);
2432}
2433
2434
2435/**
2436 * Find out which boot loader is in use.
2437 * @param which_device Device to look for the boot loader on.
2438 * @return 'L' for LILO, 'E'for ELILO, 'G' for GRUB, 'B' or 'D' for FreeBSD boot loaders, or 'U' for Unknown.
2439 * @note Under Linux, all drives are examined, not just @p which_device.
2440 */
2441#ifdef __FreeBSD__
2442char which_boot_loader (char *which_device)
2443{
2444  int count_lilos = 0;
2445  int count_grubs = 0;
2446  int count_boot0s = 0;
2447  int count_dangerouslydedicated = 0;
2448
2449  log_it ("looking at drive %s's MBR", which_device);
2450  if (does_string_exist_in_boot_block (which_device, "GRUB"))
2451      { count_grubs++; }
2452  if (does_string_exist_in_boot_block (which_device, "LILO"))
2453      { count_lilos++; }
2454  if (does_string_exist_in_boot_block (which_device, "Drive"))
2455      { count_boot0s++; }
2456  if (does_string_exist_in_first_N_blocks (which_device, "FreeBSD/i386", 17))
2457      { count_dangerouslydedicated++; }
2458  log_it ("%d grubs and %d lilos and %d elilos and %d boot0s and %d DD\n", count_grubs, count_lilos, count_elilos, count_boot0s, count_dangerouslydedicated);
2459
2460  if (count_grubs && !count_lilos)
2461    { return ('G'); }
2462  else if (count_lilos && !count_grubs)
2463    { return ('L'); }
2464 else if (count_grubs == 1 && count_lilos == 1)
2465    {
2466      log_it ("I'll bet you used to use LILO but switched to GRUB...");
2467      return ('G');
2468    }
2469  else if (count_boot0s == 1)
2470      { return ('B'); }
2471  else if (count_dangerouslydedicated)
2472      { return ('D'); }
2473  else
2474    {
2475      log_it ("Unknown boot loader");
2476      return ('U');
2477    }
2478}
2479
2480#else
2481
2482char which_boot_loader (char *which_device)
2483{
2484    /*@ buffer ******************************************************/
2485  char *list_drives_cmd;
2486  char *current_drive;
2487
2488    /*@ pointers ****************************************************/
2489  FILE *pdrives;
2490
2491    /*@ int *********************************************************/
2492  int count_lilos = 0;
2493  int count_grubs = 0;
2494
2495    /*@ end vars ****************************************************/
2496
2497  malloc_string(list_drives_cmd);
2498  malloc_string(current_drive);
2499
2500#ifdef __IA64__
2501  /* No choice for it */
2502  return ('E');
2503#endif
2504  assert(which_device!=NULL);
2505  //  sprintf (list_drives_cmd,
2506  //       "fdisk -l | grep /dev | grep cyl | tr ':' ' ' | cut -d' ' -f2");
2507
2508  sprintf (list_drives_cmd,
2509  // "parted2fdisk
2510       "fdisk -l 2>/dev/null | grep \"/dev/.*:\" | tr -s ':' ' ' | tr -s ' ' '\n' | grep /dev/; echo %s", where_is_root_mounted());
2511  log_it("list_drives_cmd = %s", list_drives_cmd);
2512
2513  if (!(pdrives = popen (list_drives_cmd, "r")))
2514    {
2515      log_OS_error ("Unable to open list of drives");
2516      paranoid_free(list_drives_cmd);
2517      paranoid_free(current_drive);
2518      return ('\0');
2519    }
2520  for (fgets (current_drive, MAX_STR_LEN, pdrives); !feof (pdrives);
2521       fgets (current_drive, MAX_STR_LEN, pdrives))
2522    {
2523      strip_spaces (current_drive);
2524      log_it ("looking at drive %s's MBR", current_drive);
2525      if (does_string_exist_in_boot_block (current_drive, "GRUB"))
2526    {
2527      count_grubs++;
2528      strcpy (which_device, current_drive);
2529      break;
2530    }
2531      if (does_string_exist_in_boot_block (current_drive, "LILO"))
2532    {
2533      count_lilos++;
2534      strcpy (which_device, current_drive);
2535      break;
2536    }
2537    }
2538  if (pclose (pdrives)) { log_OS_error("Cannot pclose pdrives"); }
2539  log_it ("%d grubs and %d lilos\n", count_grubs, count_lilos);
2540  paranoid_free(list_drives_cmd);
2541  paranoid_free(current_drive);
2542  if (count_grubs && !count_lilos)
2543    {
2544      return ('G');
2545    }
2546  else if (count_lilos && !count_grubs)
2547    {
2548      return ('L');
2549    }
2550  else if (count_grubs == 1 && count_lilos == 1)
2551    {
2552      log_it ("I'll bet you used to use LILO but switched to GRUB...");
2553      return ('G');
2554    }
2555  else
2556    {
2557      log_it ("Unknown boot loader");
2558      return ('U');
2559    }
2560}
2561#endif
2562
2563
2564
2565
2566/**
2567 * Write zeroes over the first 16K of @p device.
2568 * @param device The device to zero.
2569 * @return 0 for success, 1 for failure.
2570 */
2571int
2572zero_out_a_device (char *device)
2573{
2574  FILE *fout;
2575  int i;
2576
2577  assert_string_is_neither_NULL_nor_zerolength(device);
2578
2579  log_it ("Zeroing drive %s", device);
2580  if (!(fout=fopen (device, "w")))
2581    {
2582      log_OS_error ("Unable to open/write to device");
2583      return (1);
2584    }
2585  for (i = 0; i < 16384; i++)
2586    {
2587      fputc ('\0', fout);
2588    }
2589  paranoid_fclose(fout);
2590  log_it ("Device successfully zeroed.");
2591  return (0);
2592}
2593
2594/**
2595 * Return the device pointed to by @p incoming.
2596 * @param incoming The device to resolve symlinks for.
2597 * @return The path to the real device file.
2598 * @note The returned string points to static storage that will be overwritten with each call.
2599 * @bug Won't work with file v4.0; needs to be written in C.
2600 */
2601char *resolve_softlinks_to_get_to_actual_device_file(char*incoming)
2602{
2603  static char output[MAX_STR_LEN];
2604  char *command;
2605  char *curr_fname;
2606  char *scratch;
2607  char *tmp;
2608  char *p;
2609   
2610  struct stat statbuf; 
2611  command = malloc(1000);
2612  malloc_string(tmp);
2613  malloc_string(scratch);
2614  malloc_string(curr_fname);
2615  if (!does_file_exist(incoming))
2616    {
2617      log_it("resolve_softlinks_to_get_to_actual_device_file --- device not found");
2618      strcpy(output, incoming);
2619    }
2620  else
2621    {
2622      strcpy(curr_fname, incoming);
2623      lstat(curr_fname, &statbuf);
2624      while(S_ISLNK(statbuf.st_mode))
2625        {
2626      log_msg(1, "curr_fname = %s", curr_fname);
2627      sprintf(command, "file %s", curr_fname);
2628      strcpy(tmp, call_program_and_get_last_line_of_output(command));
2629      for(p=tmp + strlen(tmp); p != tmp && *p != '`' && *p != ' '; p--);
2630      p++;
2631      strcpy(scratch, p);
2632      for(p=scratch; *p != '\0' && *p != '\''; p++);
2633      *p = '\0';
2634      log_msg(0, "curr_fname %s --> '%s' --> %s", curr_fname, tmp, scratch);
2635      if (scratch[0] == '/')
2636        {
2637          strcpy(curr_fname, scratch); // copy whole thing because it's an absolute softlink
2638        }
2639      else
2640        { // copy over the basename cos it's a relative softlink
2641          p = curr_fname + strlen(curr_fname);
2642          while(p!=curr_fname && *p != '/') { p--;}
2643          if (*p == '/') { p++; }
2644          strcpy(p, scratch);
2645        }
2646          lstat(curr_fname, &statbuf);
2647    }
2648      strcpy(output, curr_fname);
2649      log_it("resolved %s to %s", incoming, output);
2650    }
2651  paranoid_free(command);
2652  paranoid_free(curr_fname);
2653  paranoid_free(tmp);
2654  return(output);
2655}
2656
2657/* @} - end of deviceGroup */
2658
2659
2660/**
2661 * Return the type of partition format (GPT or MBR)
2662 */
2663char *which_partition_format(const char *drive)
2664{
2665  static char output[4];
2666  char *tmp;
2667  char *command;
2668   
2669  malloc_string(tmp);
2670  malloc_string(command);
2671  log_msg(0, "Looking for partition table format type");
2672  sprintf(command, "fdisk -l %s | grep 'EFI GPT'", drive);
2673  strcpy(tmp, call_program_and_get_last_line_of_output(command));
2674  if (strstr(tmp,"GPT") == NULL) {
2675      strcpy(output,"MBR");
2676  } else {
2677      strcpy(output,"GPT");
2678  }
2679  log_msg(0, "Found %s partition table format type",output);
2680  paranoid_free(command);
2681  paranoid_free(tmp);
2682  return(output);
2683}
2684
2685/* @} - end of deviceGroup */
2686
Note: See TracBrowser for help on using the repository browser.