package tinyfirewall; use diagnostics; use strict; use common qw(:common :functional :system :file); use commands; use run_program; use netconnect; use network; use POSIX qw(tmpnam); my @messages = (_("tinyfirewall configurator This configures a personal firewall for this Linux Mandrake machine. For a powerful dedicated firewall solution, please look to the specialized MandrakeSecurity Firewall distribution."), _("We'll now ask you questions about which services you'd like to allow the Internet to connect to. Please think carefully about these questions, as your computer's security is important. Please, if you're not currently using one of these services, firewall it off. You can change this configuration anytime you like by re-running this application!"), _("Are you running a web server on this machine that you need the whole Internet to see? If you are running a webserver that only needs to be accessed by this machine, you can safely answer NO here. "), _("Are you running a name server on this machine? If you didn't set one up to give away IP and zone information to the whole Internet, please answer no. "), _("Do you want to allow incoming Secure Shell (ssh) connections? This is a telnet-replacement that you might use to login. If you're using telnet now, you should definitely switch to ssh. telnet is not encrypted -- so some attackers can steal your password if you use it. ssh is encrypted and doesn't allow for this eavesdropping."), _("Do you want to allow incoming telnet connections? This is horribly unsafe, as we explained in the previous screen. We strongly recommend answering No here and using ssh in place of telnet. "), _("Are you running an FTP server here that you need accessible to the Internet? If you are, we strongly recommend that you only use it for Anonymous transfers. Any passwords sent by FTP can be stolen by some attackers, since FTP also uses no encryption for transferring passwords. "), _("Are you running a mail server here? If you're sending you messages through pine, mutt or any other text-based mail client, you probably are. Otherwise, you should firewall this off. "), _("Are you running a POP or IMAP server here? This would be used to host non-web-based mail accounts for people via this machine. "), _("You appear to be running a 2.2 kernel. If your network IP is automatically set by a computer in your home or office (dynamically assigned), we need to allow for this. Is this the case? "), _("Is your computer getting time syncronized to another computer? Mostly, this is used by medium-large Unix/Linux organizations to synchronize time for logging and such. If you're not part of a larger office and haven't heard of this, you probably aren't."), _("Configuration complete. May we write these changes to disk? ") ); my %settings; my $config_file = "/etc/Bastille/bastille-firewall.cfg"; my $default_config_file = "/usr/share/Bastille/bastille-firewall.cfg"; # set this later sub ReadConfig { -e $config_file or commands::cp($default_config_file, $config_file); add2hash(\%settings, { getVarsFromSh("$config_file") }); } sub SaveConfig { my $tmp_file = tmpnam(); open CONFIGFILE, "$config_file" or die "Can't open $config_file: $!\n"; open TMPFILE, ">$tmp_file" or die "Can't open $tmp_file for writing: $!\n"; while (my $line = ) { if ($line =~ m/^(.+)\s*\=\s*\"(.*)\"/) { my ($variable, $value) = ($1, $2); my $newvalue = $settings{$variable}; $line =~ s/\".*\"/\"$newvalue\"/ if (exists $settings{$variable}); } print TMPFILE $line; } close CONFIGFILE; close TMPFILE; rename ($config_file, $config_file . ".orig"); system ("/bin/cp $tmp_file $config_file"); system ("/bin/rm $tmp_file"); } sub DoInterface { my ($in)=@_; $::isWizard=1; my $GetNetworkInfo = sub { $settings{DNS_SERVERS} = join(' ', uniq(split(' ', $settings{DNS_SERVERS}), @{network::read_resolv_conf("/etc/resolv.conf")}{'dnsServer', 'dnsServer2', 'dnsServer3'})); my (undef, undef, @netstat) = `/bin/netstat -in`; my @interfaces = map { /(\S+)/ } @netstat; my (@route, undef, undef) = `/sbin/route -n`; my $defaultgw; my $iface; foreach (@route) { my @parts = split /\s+/; $parts[0] eq "0.0.0.0" and $defaultgw = $parts[1], $iface = $parts[7] } my $fulliface = $iface; $fulliface =~ s/[0-9]+/\\\+/; $settings{PUBLIC_INTERFACES} = join(' ', uniq(split(' ', $settings{PUBLIC_INTERFACES}), $iface)); $settings{PUBLIC_INTERFACES} =~ $fulliface and $settings{PUBLIC_INTERFACES} =~ s/$iface *//; $settings{INTERNAL_IFACES} = join(' ', uniq(split(' ', $settings{INTERNAL_IFACES}), map { my $i=$_; my $f=$i; $f=~s/[0-9]+/\\\+/; if_(and_( map {$settings{$_} !~ /$i/ and $settings{$_} !~ /$f/ } ('TRUSTED_IFACES', 'PUBLIC_IFACES', 'INTERNAL_IFACES')), $i) } @interfaces )); }; # my $popimap = sub { $_[0] or return; $settings{FORCE_PASV_FTP} = 11; mapn {$settings{"$_[0]"} = "$_[1]"; } #[ qw(FORCE_PASV_FTP TCP_BLOCKED_SERVICES UDP_BLOCKED_SERVICES ICMP_ALLOWED_TYPES ENABLE_SRC_ADDR_VERIFY IP_MASQ_NETWORK IP_MASQ_MODULES REJECT_METHOD) ] , #[ "N", "6000:6020", "2049", "destination-unreachable echo-reply time-exceeded" , "Y", "", "", "DENY" ]; }; my $popimap = sub { $_[0] or return; $settings{'FORCE_PASV_FTP'} = "N"; $settings{TCP_BLOCKED_SERVICES}= "6000:6020"; $settings{UDP_BLOCKED_SERVICES}= "2049"; $settings{ICMP_ALLOWED_TYPES}= "destination-unreachable echo-reply time-exceeded"; $settings{ENABLE_SRC_ADDR_VEIFY}= "Y"; $settings{IP_MASQ_NETWORK}= ""; $settings{IP_MASQ_MODULES}= ""; $settings{REJECT_METHOD}= "DENY"; }; # my $ntp = sub { $_[0] or return; mapn { $settings{$_[0]} = $_[1] } ['ICMP_OUTBOUND_DISABLED_TYPES}', 'LOG_FAILURES'], [ "", "N"] }; my $ntp = sub { $_[0] or return; $settings{'ICMP_OUTBOUND_DISABLED_TYPES}'} = ""; $settings{'LOG_FAILURES'} = "N"; }; my $dhcp = sub { if ($_[0]) { $settings{DHCP_IFACES} and return; my (undef, undef, @netstat) = `/bin/netstat -in`; $settings{DHCP_IFACES} = join(' ', split(' ', $settings{DHCP_IFACES}), map { /(\S+)/ } @netstat ); } else { $settings{DHCP_IFACES} = "" } }; my $quit = sub { $_[0] or $in->exit(0); SaveConfig(); system($_) foreach ("/bin/cp /usr/share/Bastille/bastille-ipchains /usr/share/Bastille/bastille-netfilter /sbin", "/bin/cp /usr/share/Bastille/bastille-firewall /etc/rc.d/init.d/", "/bin/chmod 0700 /etc/rc.d/init.d/bastille-firewall", "/bin/chmod 0700 /sbin/bastille-ipchains", "/bin/chmod 0700 /sbin/bastille-netfilter", "/sbin/chkconfig bastille-firewall on", "/etc/rc.d/init.d/bastille-firewall stop", "/etc/rc.d/init.d/bastille-firewall start"); $in->exit(0); return; $_[0] or $in->exit(0); commands::cp("-f", $config_file, $config_file . ".orig"); substInFile { if(/^(.+)\s*\=/) { $a=$settings{$1}; s/\".*\"/\"$a\"/; } } $config_file; system($_) foreach ("/bin/cp /usr/share/Bastille/bastille-ipchains /usr/share/Bastille/bastille-netfilter /sbin", "/bin/cp /usr/share/Bastille/bastille-firewall /etc/rc.d/init.d/", "/bin/chmod 0700 /etc/rc.d/init.d/bastille-firewall", "/bin/chmod 0700 /sbin/bastille-ipchains", "/bin/chmod 0700 /sbin/bastille-netfilter", "/sbin/chkconfig bastille-firewall on", "/etc/rc.d/init.d/bastille-firewall stop", "/etc/rc.d/init.d/bastille-firewall start"); }; my @struct = ( [$GetNetworkInfo], [], [undef , undef, undef, undef, ["tcp", "80"], ["tcp", "443"]], [undef , undef, undef, undef, ["tcp", "53"], ["udp", "53"]], [undef , undef, undef, undef, ["tcp", "22"]], [undef , undef, undef, undef, ["tcp", "23"]], [undef , undef, undef, undef, ["tcp", "20"],["tcp", "21"]], [undef , undef, undef, undef, ["tcp", "25"]], [undef , undef, undef, $popimap, ["tcp", "109"], ["tcp", "110"], ["tcp", "143"]], [undef , "No I don't need DHCP", "Yes I need DHCP", $dhcp], [undef , "No I don't need NTP", "Yes I need NTP", $ntp ], [undef , "Don't Save", "Save & Quit", $quit ] ); if (!Kernel22()) { pop @struct; pop @struct; pop @struct; @struct = ( @struct, [undef , "Don't Save", "Save & Quit", $quit ] ); $messages[9]=$messages[11]; } if ( ! $in->standalone::pkgs_install(Kernel22() ? "ipchains" : "iptables", "Bastille")) { $in->ask_warn('', _("Failure installing the needed packages : %s and Bastille. Try to install them manually.", Kernel22() ? "ipchains" : "iptables") ); $in->exit(0); } for (my $i=0;$i<@struct;$i++) { $::Wizard_no_previous = $i == 0; $::Wizard_finished = $i == $#struct; my $l = $struct[$i]; @$l or goto ask; if (@$l == 1) { ($l->[0])->(); ask: $in->ask_okcancel(_("Firewall Configuration Wizard"), $messages[$i],1) ? next : goto prev; } my $no = $l->[1] ? $l->[1] : _("No (firewall this off from the internet)"); my $yes = $l->[2] ? $l->[2] : _("Yes (allow this through the firewall)"); if (my $e = $in->ask_from_list_(_("Firewall Configuration Wizard"), $messages[$i], [ $yes, $no ], or_( map { $_ && CheckService($_->[0], $_->[1]) } (@$l[4..6])) ? $yes : $no )) { map { $_ and Service($e=~/Yes/, $_->[0], $_->[1]) } (@{$struct[$i]}[4..6]); $struct[$i][3] and $struct[$i][3]->($e=~/Yes/ || $e eq "Save & Quit"); } else { prev: $i = $i-2 >= -1 ? $i-2 : -1; } } } sub unbox_service { split ' ', $settings{uc($_[0]) . "_PUBLIC_SERVICES"} } sub Service { my ($add, $protocol, $port) = @_; my @l = unbox_service($protocol); @l = uniq($add ? (@l, $port) : grep { $_ ne $port } @l); $settings{uc($protocol) . "_PUBLIC_SERVICES"} = join(' ', @l); } sub CheckService { member($_[1], unbox_service($_[0])); } sub Kernel22 { my ($major, $minor, $patchlevel) = (cat_("/proc/version"))[0] =~ m/^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/; $major eq "2" && $minor eq "2"; } sub main { my ($in)=@_; ReadConfig; DoInterface($in); } 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
package partition_table;

use diagnostics;
use strict;
use vars qw(@ISA %EXPORT_TAGS @EXPORT_OK @important_types @fields2save);

@ISA = qw(Exporter);
%EXPORT_TAGS = (
    types => [ qw(type2name type2fs name2type fs2type isExtended isExt2 isSwap isDos isWin isFat isPrimary isNfs) ],
);
@EXPORT_OK = map { @$_ } values %EXPORT_TAGS;


use common qw(:common :system :functional);
use partition_table_raw;
use Data::Dumper;


@important_types = ("Linux native", "Linux swap", "DOS FAT16", "Win98 FAT32");

@fields2save = qw(primary extended totalsectors);


my %types = (
  0x0 => 'Empty',
  0x1 => 'DOS 12-bit FAT',
  0x2 => 'XENIX root',
  0x3 => 'XENIX /usr',
  0x4 => 'DOS 16-bit FAT (up to 32M)',
  0x5 => 'DOS 3.3+ Extended Partition',
  0x6 => 'DOS FAT16',
  0x7 => 'OS/2 IFS (e.g., HPFS) / Windows NT NTFS / Advanced Unix / QNX2.x pre-1988 (see below under IDs 4d-4f)',
  0x8 => 'OS/2 (v1.0-1.3 only) / AIX boot partition / SplitDrive / Commodore DOS / DELL partition spanning multiple drives / QNX 1.x and 2.x ("qny")',
  0x9 => 'AIX data partition / Coherent filesystem / QNX 1.x and 2.x ("qnz")',
  0xa => 'OS/2 Boot Manager / Coherent swap partition / OPUS',
  0xb => 'Win98 FAT32',
  0xc => 'Win98 FAT32, LBA-mapped',
  0xe => 'Win95: DOS 16-bit FAT, LBA-mapped',
  0xf => 'Win95: Extended partition, LBA-mapped',
  0x10 => 'OPUS (?)',
  0x11 => 'Hidden DOS 12-bit FAT',
  0x12 => 'Compaq config partition',
  0x14 => 'Hidden DOS 16-bit FAT <32M',
  0x16 => 'Hidden DOS 16-bit FAT >=32M',
  0x17 => 'Hidden IFS (e.g., HPFS)',
  0x18 => 'AST Windows swapfile',
  0x1b => 'Hidden WIN95 OSR2 32-bit FAT',
  0x1c => 'Hidden WIN95 OSR2 32-bit FAT, LBA-mapped',
  0x1e => 'Hidden FAT95',
  0x22 => 'Used for Oxygen Extended Partition Table by ekstazya@sprint.ca.',
  0x24 => 'NEC DOS 3.x',
  0x38 => 'THEOS ver 3.2 2gb partition',
  0x39 => 'THEOS ver 4 spanned partition',
  0x3a => 'THEOS ver 4 4gb partition',
  0x3b => 'THEOS ver 4 extended partition',
  0x3c => 'PartitionMagic recovery partition',
  0x40 => 'Venix 80286',
  0x41 => 'Linux/MINIX (sharing disk with DRDOS) / Personal RISC Boot / PPC PReP (Power PC Reference Platform) Boot',
  0x42 => 'Linux swap (sharing disk with DRDOS) / SFS (Secure Filesystem) / W2K marker',
  0x43 => 'Linux native (sharing disk with DRDOS)',
  0x45 => 'EUMEL/Elan',
  0x46 => 'EUMEL/Elan 0x46',
  0x47 => 'EUMEL/Elan 0x47',
  0x48 => 'EUMEL/Elan 0x48',
  0x4d => 'QNX4.x',
  0x4e => 'QNX4.x 2nd part',
  0x4f => 'QNX4.x 3rd part / Oberon partition',
  0x50 => 'OnTrack Disk Manager (older versions) RO',
  0x51 => 'OnTrack Disk Manager RW (DM6 Aux1) / Novell',
  0x52 => 'CP/M / Microport SysV/AT',
  0x53 => 'Disk Manager 6.0 Aux3',
  0x54 => 'Disk Manager 6.0 Dynamic Drive Overlay',
  0x55 => 'EZ-Drive',
  0x56 => 'Golden Bow VFeature Partitioned Volume. / DM converted to EZ-BIOS',
  0x57 => 'DrivePro',
  0x5c => 'Priam EDisk',
  0x61 => 'SpeedStor',
  0x63 => 'Unix System V (SCO, ISC Unix, UnixWare, ...), Mach, GNU Hurd',
  0x64 => 'PC-ARMOUR protected partition / Novell Netware 2.xx',
  0x65 => 'Novell Netware 3.xx or 4.xx',
  0x67 => 'Novell',
  0x68 => 'Novell 0x68',
  0x69 => 'Novell 0x69',
  0x70 => 'DiskSecure Multi-Boot',
  0x75 => 'IBM PC/IX',
  0x80 => 'MINIX until 1.4a',
  0x81 => 'MINIX since 1.4b, early Linux / Mitac disk manager',
  0x82 => 'Linux swap',
  0x83 => 'Linux native',
  0x84 => 'OS/2 hidden C: drive / Hibernation partition',
  0x85 => 'Linux extended partition',
  0x86 => 'Old Linux RAID partition superblock / NTFS volume set',
  0x87 => 'NTFS volume set',
  0x8a => 'Linux Kernel Partition (used by AiR-BOOT)',
  0x8e => 'Linux Logical Volume Manager partition',
  0x93 => 'Amoeba',
  0x94 => 'Amoeba bad block table',
  0x99 => 'DCE376 logical drive',
  0xa0 => 'IBM Thinkpad hibernation partition / Phoenix NoteBIOS Power Management "Save-to-Disk" partition',
  0xa5 => 'BSD/386, 386BSD, NetBSD, FreeBSD',
  0xa6 => 'OpenBSD',
  0xa7 => 'NEXTSTEP',
  0xa9 => 'NetBSD',
  0xaa => 'Olivetti Fat 12 1.44Mb Service Partition',
  0xb7 => 'BSDI filesystem',
  0xb8 => 'BSDI swap partition',
  0xbe => 'Solaris boot partition',
  0xc0 => 'CTOS / REAL/32 secure small partition',
  0xc1 => 'DRDOS/secured (FAT-12)',
  0xc4 => 'DRDOS/secured (FAT-16, < 32M)',
  0xc6 => 'DRDOS/secured (FAT-16, >= 32M) / Windows NT corrupted FAT16 volume/stripe set',
  0xc7 => 'Windows NT corrupted NTFS volume/stripe set / Syrinx boot',
  0xcb => 'reserved for DRDOS/secured (FAT32)',
  0xcc => 'reserved for DRDOS/secured (FAT32, LBA)',
  0xcd => 'CTOS Memdump?',
  0xce => 'reserved for DRDOS/secured (FAT16, LBA)',
  0xd0 => 'REAL/32 secure big partition',
  0xd1 => 'Old Multiuser DOS secured FAT12',
  0xd4 => 'Old Multiuser DOS secured FAT16 <32M',
  0xd5 => 'Old Multiuser DOS secured extended partition',
  0xd6 => 'Old Multiuser DOS secured FAT16 >=32M',
  0xd8 => 'CP/M-86',
  0xdb => 'Digital Research CP/M, Concurrent CP/M, Concurrent DOS / CTOS (Convergent Technologies OS -Unisys) / KDG Telemetry SCPU boot',
  0xdd => 'Hidden CTOS Memdump?',
  0xe1 => 'DOS access or SpeedStor 12-bit FAT extended partition',
  0xe3 => 'DOS R/O or SpeedStor',
  0xe4 => 'SpeedStor 16-bit FAT extended partition < 1024 cyl.',
  0xeb => 'BeOS',
  0xee => 'Indication that this legacy MBR is followed by an EFI header',
  0xef => 'Partition that contains an EFI file system',
  0xf1 => 'SpeedStor',
  0xf2 => 'DOS 3.3+ secondary partition',
  0xf4 => 'SpeedStor large partition / Prologue single-volume partition',
  0xf5 => 'Prologue multi-volume partition',
  0xfd => 'Linux raid partition with autodetect using persistent superblock',
  0xfe => 'SpeedStor > 1024 cyl. or LANstep / IBM PS/2 IML (Initial Microcode Load) partition, located at the end of the disk. / Windows NT Disk Administrator hidden partition / Linux Logical Volume Manager partition (old)',
  0xff => 'Xenix Bad Block Table',
);

my %type2fs = (
  0x01 => 'vfat',
  0x04 => 'vfat',
  0x05 => 'ignore',
  0x06 => 'vfat',
  0x07 => 'hpfs',
  0x0b => 'vfat',
  0x0c => 'vfat',
  0x0e => 'vfat',
  0x82 => 'swap',
  0x83 => 'ext2',
  nfs  => 'nfs', #- hack
);
my %types_rev = reverse %types;
my %fs2type = reverse %type2fs;


1;

sub important_types { $_[0] and return sort values %types; @important_types }

sub type2name($) { $types{$_[0]} || $_[0] }
sub type2fs($) { $type2fs{$_[0]} }
sub fs2type($) { $fs2type{$_[0]} }
sub name2type($) { 
    local ($_) = @_;
    /0x(.*)/ ? hex $1 : $types_rev{$_} || $_;
}

sub isExtended($) { $_[0]{type} == 5 || $_[0]{type} == 0xf }
sub isSwap($) { $type2fs{$_[0]{type}} eq 'swap' }
sub isExt2($) { $type2fs{$_[0]{type}} eq 'ext2' }
sub isDos($) { $ {{ 1=>1, 4=>1, 6=>1 }}{$_[0]{type}} }
sub isWin($) { $ {{ 0xb=>1, 0xc=>1, 0xe=>1 }}{$_[0]{type}} }
sub isFat($) { isDos($_[0]) || isWin($_[0]) }
sub isNfs($) { $_[0]{type} eq 'nfs' } #- small hack

sub isPrimary($$) {
    my ($part, $hd) = @_;
    foreach (@{$hd->{primary}{raw}}) { $part eq $_ and return 1; }
    0;
}

sub cylinder_size($) {
    my ($hd) = @_;
    $hd->{geom}{sectors} * $hd->{geom}{heads};
}

sub adjustStart($$) {
    my ($hd, $part) = @_;
    my $end = $part->{start} + $part->{size};

    $part->{start} = round_up($part->{start},
			       $part->{start} % cylinder_size($hd) < 2 * $hd->{geom}{sectors} ?
			       $hd->{geom}{sectors} : cylinder_size($hd));
    $part->{size} = $end - $part->{start};
}
sub adjustEnd($$) {
    my ($hd, $part) = @_;
    my $end = $part->{start} + $part->{size};
    my $end2 = round_down($end, cylinder_size($hd));
    unless ($part->{start} < $end2) {
	$end2 = round_up($end, cylinder_size($hd));
    }
    $part->{size} = $end2 - $part->{start};
}
sub adjustStartAndEnd($$) {
    &adjustStart;
    &adjustEnd;
}

sub verifyNotOverlap($$) {
    my ($a, $b) = @_;
    $a->{start} + $a->{size} <= $b->{start} || $b->{start} + $b->{size} <= $a->{start};
}
sub verifyInside($$) {
    my ($a, $b) = @_;
    $b->{start} <= $a->{start} && $a->{start} + $a->{size} <= $b->{start} + $b->{size};
}

sub verifyParts_ {
    foreach my $i (@_) { foreach (@_) {
	$i != $_ and verifyNotOverlap($i, $_) || die "partitions $i->{start} $i->{size} and $_->{start} $_->{size} are overlapping!";
    }}
}
sub verifyParts($) {
    my ($hd) = @_;
    verifyParts_(get_normal_parts($hd));
}
sub verifyPrimary($) {
    my ($pt) = @_;
    verifyParts_(@{$pt->{normal}}, $pt->{extended});
}

sub assign_device_numbers($) {
    my ($hd) = @_;

    my $i = 1;
    $_->{device} = $hd->{prefix} . $i++ foreach @{$hd->{primary}{raw}},
                                                map { $_->{normal} } @{$hd->{extended} || []};

    #- try to figure what the windobe drive letter could be!
    #
    #- first verify there's at least one primary dos partition, otherwise it
    #- means it is a secondary disk and all will be false :(
    my ($c, @others) = grep { isFat($_) } @{$hd->{primary}{normal}};
    $c or return;

    $i = ord 'D';
    foreach (grep { isFat($_) } map { $_->{normal} } @{$hd->{extended}}) {
	$_->{device_windobe} = chr($i++);
    }
    $c->{device_windobe} = 'C';
    $_->{device_windobe} = chr($i++) foreach @others;
}

sub remove_empty_extended($) {
    my ($hd) = @_;
    my $last = $hd->{primary}{extended} or return;
    @{$hd->{extended}} = grep {
	if ($_->{normal}) {
	    $last = $_;
	} else {
	    %{$last->{extended}} = $_->{extended} ? %{$_->{extended}} : ();
	}
	$_->{normal};
    } @{$hd->{extended}};
    adjust_main_extended($hd);
}

sub adjust_main_extended($) {
    my ($hd) = @_;

    if (!is_empty_array_ref $hd->{extended}) {
	my ($l, @l) = @{$hd->{extended}};

	# the first is a special case, must recompute its real size
	my $start = round_down($l->{normal}{start} - 1, $hd->{geom}{sectors});
	my $end = $l->{normal}{start} + $l->{normal}{size};
	foreach (map $_->{normal}, @l) {
	    $start = min($start, $_->{start});
	    $end = max($end, $_->{start} + $_->{size});
	}
	$l->{start} = $hd->{primary}{extended}{start} = $start;
	$l->{size} = $hd->{primary}{extended}{size} = $end - $start;
    }
    unless (@{$hd->{extended} || []} || !$hd->{primary}{extended}) {
	%{$hd->{primary}{extended}} = (); #- modify the raw entry
	delete $hd->{primary}{extended};
    }
    verifyParts($hd); #- verify everything is all right
}


sub get_normal_parts($) {
    my ($hd) = @_;

    @{$hd->{primary}{normal} || []}, map { $_->{normal} } @{$hd->{extended} || []}
}


sub read_one($$) {
    my ($hd, $sector) = @_;

    my $pt = partition_table_raw::read($hd, $sector) or return;

    my @extended = grep { isExtended($_) } @$pt;
    my @normal = grep { $_->{size} && $_->{type} && !isExtended($_) } @$pt;

    @extended > 1 and die "more than one extended partition";

    $_->{rootDevice} = $hd->{device} foreach @normal, @extended;
    { raw => $pt, extended => $extended[0], normal => \@normal };
}

sub read($;$) {
    my ($hd, $clearall) = @_;
    my $pt = $clearall ?
      partition_table_raw::clear_raw() :
      read_one($hd, 0) || return 0;

    $hd->{primary} = $pt;
    $hd->{extended} = undef;
    $clearall and return $hd->{isDirty} = $hd->{needKernelReread} = 1;
    verifyPrimary($pt);

    eval {
	$pt->{extended} and read_extended($hd, $pt->{extended}) || return 0;
    }; die "extended partition: $@" if $@;
    assign_device_numbers($hd);
    remove_empty_extended($hd);
    1;
}

sub read_extended {
    my ($hd, $extended) = @_;

    my $pt = read_one($hd, $extended->{start}) or return 0;
    $pt = { %$extended, %$pt };

    push @{$hd->{extended}}, $pt;
    @{$hd->{extended}} > 100 and die "oops, seems like we're looping here :(  (or you have more than 100 extended partitions!)";

    @{$pt->{normal}} <= 1 or die "more than one normal partition in extended partition";
    @{$pt->{normal}} >= 1 or die "no normal partition in extended partition";
    $pt->{normal} = $pt->{normal}[0];
    #- in case of extended partitions, the start sector is local to the partition or to the first extended_part!
    $pt->{normal}{start} += $pt->{start};

    verifyInside($pt->{normal}, $extended) or die "partition $pt->{normal}{device} is not inside its extended partition";

    if ($pt->{extended}) {
	$pt->{extended}{start} += $hd->{primary}{extended}{start};
	read_extended($hd, $pt->{extended}) or return 0;
    }
    1;
}

# write the partition table
sub write($) {
    my ($hd) = @_;

    #- set first primary partition active if no primary partitions are marked as active.
    for ($hd->{primary}{raw}) {
	(grep { $_->{local_start} = $_->{start}; $_->{active} ||= 0 } @$_) or $_->[0]{active} = 0x80;
    }
    partition_table_raw::write($hd, 0, $hd->{primary}{raw}) or die "writing of partition table failed";

    foreach (@{$hd->{extended}}) {
	# in case of extended partitions, the start sector must be local to the partition
	$_->{normal}{local_start} = $_->{normal}{start} - $_->{start};
	$_->{extended} and $_->{extended}{local_start} = $_->{extended}{start} - $hd->{primary}{extended}{start};

	partition_table_raw::write($hd, $_->{start}, $_->{raw}) or die "writing of partition table failed";
    }
    $hd->{isDirty} = 0;

    #- now sync disk and re-read the partition table
    if ($hd->{needKernelReread}) {
	sync();
	partition_table_raw::kernel_read($hd);
	$hd->{needKernelReread} = 0;
    }
}

sub active($$) {
    my ($hd, $part) = @_;

    $_->{active} = 0 foreach @{$hd->{primary}{normal}};
    $part->{active} = 0x80;
}


# remove a normal partition from hard drive hd
sub remove($$) {
    my ($hd, $part) = @_;
    my $i;

    #- first search it in the primary partitions
    $i = 0; foreach (@{$hd->{primary}{normal}}) {
	if ($_ eq $part) {
	    splice(@{$hd->{primary}{normal}}, $i, 1);
	    %$_ = (); #- blank it

	    return $hd->{isDirty} = $hd->{needKernelReread} = 1;
	}
	$i++;
    }
    #- otherwise search it in extended partitions
    foreach (@{$hd->{extended}}) {
	$_->{normal} eq $part or next;

	delete $_->{normal}; #- remove it
	remove_empty_extended($hd);

	return $hd->{isDirty} = $hd->{needKernelReread} = 1;
    }
    0;
}

# create of partition at starting at `start', of size `size' and of type `type' (nice comment, uh?)
sub add_primary($$) {
    my ($hd, $part) = @_;

    {
	local $hd->{primary}{normal}; #- save it to fake an addition of $part, that way add_primary do not modify $hd if it fails
	push @{$hd->{primary}{normal}}, $part;
	adjust_main_extended($hd); #- verify
	raw_add($hd->{primary}{raw}, $part);
    }
    push @{$hd->{primary}{normal}}, $part; #- really do it
}

sub add_extended($$) {
    my ($hd, $part) = @_;

    my $e = $hd->{primary}{extended};

    if ($e && !verifyInside($part, $e)) {
	#-die "sorry, can't add outside the main extended partition" unless $::unsafe;
	my $end = $e->{start} + $e->{size};
	my $start = min($e->{start}, $part->{start});
	$end = max($end, $part->{start} + $part->{size}) - $start;

	{ #- faking a resizing of the main extended partition to test for problems
	    local $e->{start} = $start;
	    local $e->{size} = $end - $start;
	    eval { verifyPrimary($hd->{primary}) };
	    $@ and die
_("You have a hole in your partition table but I can't use it.
The only solution is to move your primary partitions to have the hole next to the extended partitions");
	}
    }

    if ($e && $part->{start} < $e->{start}) {
	my $l = first (@{$hd->{extended}});

	#- the first is a special case, must recompute its real size
	$l->{start} = round_down($l->{normal}{start} - 1, cylinder_size($hd));
	$l->{size} = $l->{normal}{start} + $l->{normal}{size} - $l->{start};
	my $ext = { %$l };
	unshift @{$hd->{extended}}, { type => 5, raw => [ $part, $ext, {}, {} ], normal => $part, extended => $ext };
	#- size will be autocalculated :)
    } else {
	my ($ext, $ext_size) = is_empty_array_ref($hd->{extended}) ?
	  ($hd->{primary}, -1) : #- -1 size will be computed by adjust_main_extended
	  (top(@{$hd->{extended}}), $part->{size});
	my %ext = ( type => 5, start => $part->{start}, size => $ext_size );

	raw_add($ext->{raw}, \%ext);
	$ext->{extended} = \%ext;
	push @{$hd->{extended}}, { %ext, raw => [ $part, {}, {}, {} ], normal => $part };
    }
    $part->{start}++; $part->{size}--; #- let it start after the extended partition sector
    adjustStartAndEnd($hd, $part);

    adjust_main_extended($hd);
}

sub add($$;$$) {
    my ($hd, $part, $primaryOrExtended, $forceNoAdjust) = @_;

    $part->{notFormatted} = 1;
    $part->{isFormatted} = 0;
    $part->{rootDevice} = $hd->{device};
    $hd->{isDirty} = $hd->{needKernelReread} = 1;
    $part->{start} ||= 1; #- starting at sector 0 is not allowed
    adjustStartAndEnd($hd, $part) unless $forceNoAdjust;

    my $e = $hd->{primary}{extended};

    if ($primaryOrExtended eq 'Primary' ||
	$primaryOrExtended ne 'Extended' && is_empty_array_ref($hd->{primary}{normal})) {
	eval { add_primary($hd, $part) };
	return unless $@;
    }
    eval { add_extended($hd, $part) }; #- try adding extended
    if (my $err = $@) {
	eval { add_primary($hd, $part) };
	die $@ if $@; #- send the add extended error which should be better
    }
}

# search for the next partition
sub next($$) {
    my ($hd, $part) = @_;

    first(
	  sort { $a->{start} <=> $b->{start} }
	  grep { $_->{start} >= $part->{start} + $part->{size} }
	  get_normal_parts($hd)
	 );
}
sub next_start($$) {
    my ($hd, $part) = @_;
    my $next = &next($hd, $part);
    $next ? $next->{start} : $hd->{totalsectors};
}


sub raw_add($$) {
    my ($raw, $part) = @_;

    foreach (@$raw) {
	$_->{size} || $_->{type} and next;
	$_ = $part;
	return;
    }
    die "raw_add: partition table already full";
}

sub load($$;$) {
    my ($hd, $file, $force) = @_;

    local *F;
    open F, $file or die _("Error reading file %s", $file);

    my $h;
    {
	local $/ = "\0";
	eval <F>;
    }
    $@ and die _("Restoring from file %s failed: %s", $file, $@);

    ref $h eq 'ARRAY' or die _("Bad backup file");

    my %h; @h{@fields2save} = @$h;

    $h{totalsectors} == $hd->{totalsectors} or $force or cdie("Bad totalsectors");

    #- unsure we don't modify totalsectors
    local $hd->{totalsectors};

    @{$hd}{@fields2save} = @$h;

    $hd->{isDirty} = $hd->{needKernelReread} = 1;
}

sub save($$) {
    my ($hd, $file) = @_;
    my @h = @{$hd}{@fields2save};
    local *F;
    open F, ">$file"
      and print F Data::Dumper->Dump([\@h], ['$h']), "\0"
      or die _("Error writing to file %s", $file);
}