summaryrefslogtreecommitdiffstats
path: root/perl-install/services.pm
blob: 851202694d7cae7c95e08547f553edb402ee4ecd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
package services; # $Id$

use diagnostics;
use strict;

#-######################################################################################
#- misc imports
#-######################################################################################
use common qw(:common :functional :system :file);
use commands;
use run_program;
use my_gtk qw(:helpers :wrappers);

sub description {
    my %services = (
alsa => __("Launch the ALSA (Advanced Linux Sound Architecture) sound system"),
anacron => __("Anacron a periodic command scheduler."),
apmd => __("apmd is used for monitoring batery status and logging it via syslog.
It can also be used for shutting down the machine when the battery is low."),
atd => __("Runs commands scheduled by the at command at the time specified when
at was run, and runs batch commands when the load average is low enough."),
crond => __("cron is a standard UNIX program that runs user-specified programs
at periodic scheduled times. vixie cron adds a number of features to the basic
UNIX cron, including better security and more powerful configuration options."),
gpm => __("GPM adds mouse support to text-based Linux applications such the
Midnight Commander. It also allows mouse-based console cut-and-paste operations,
and includes support for pop-up menus on the console."),
harddrake => __("HardDrake runs a hardware probe, and optionally configures
new/changed hardware."),
httpd => __("Apache is a World Wide Web server.  It is used to serve HTML files
and CGI."),
inet => __("The internet superserver daemon (commonly called inetd) starts a
variety of other internet services as needed. It is responsible for starting
many services, including telnet, ftp, rsh, and rlogin. Disabling inetd disables
all of the services it is responsible for."),
ipchains => __("Launch packet filtering for Linux kernel 2.2 series, to set
up a firewall to protect your machine from network attacks."),
keytable => __("This package loads the selected keyboard map as set in
/etc/sysconfig/keyboard.  This can be selected using the kbdconfig utility.
You should leave this enabled for most machines."),
kheader => __("Automatic regeneration of kernel header in /boot for
/usr/include/linux/{autoconf,version}.h"),
kudzu => __("Automatic detection and configuration of hardware at boot."),
linuxconf => __("Linuxconf will sometimes arrange to perform various tasks
at boot-time to maintain the system configuration."),
lpd => __("lpd is the print daemon required for lpr to work properly. It is
basically a server that arbitrates print jobs to printer(s)."),
lvs => __("Linux Virtual Server, used to build a high-performance and highly
available server."),
named => __("named (BIND) is a Domain Name Server (DNS) that is used to resolve
host names to IP addresses."),
netfs => __("Mounts and unmounts all Network File System (NFS), SMB (Lan
Manager/Windows), and NCP (NetWare) mount points."),
network => __("Activates/Deactivates all network interfaces configured to start
at boot time."),
nfs => __("NFS is a popular protocol for file sharing across TCP/IP networks.
This service provides NFS server functionality, which is configured via the
/etc/exports file."),
nfslock => __("NFS is a popular protocol for file sharing across TCP/IP
networks. This service provides NFS file locking functionality."),
numlock => __("Automatically switch on numlock key locker under console
and XFree at boot."),
oki4daemon => __("Support the OKI 4w and compatible winprinters."),
pcmcia => __("PCMCIA support is usually to support things like ethernet and
modems in laptops.  It won't get started unless configured so it is safe to have
it installed on machines that don't need it."),
portmap => __("The portmapper manages RPC connections, which are used by
protocols such as NFS and NIS. The portmap server must be running on machines
which act as servers for protocols which make use of the RPC mechanism."),
postfix => __("Postfix is a Mail Transport Agent, which is the program that
moves mail from one machine to another."),
random => __("Saves and restores system entropy pool for higher quality random
number generation."),
rawdevices => __("Assign raw devices to block devices (such as hard drive
partitions), for the use of applications such as Oracle"),
routed => __("The routed daemon allows for automatic IP router table updated via
the RIP protocol. While RIP is widely used on small networks, more complex
routing protocols are needed for complex networks."),
rstatd => __("The rstat protocol allows users on a network to retrieve
performance metrics for any machine on that network."),
rusersd => __("The rusers protocol allows users on a network to identify who is
logged in on other responding machines."),
rwhod => __("The rwho protocol lets remote users get a list of all of the users
logged into a machine running the rwho daemon (similiar to finger)."),
sound => __("Launch the sound system on your machine"),
syslog => __("Syslog is the facility by which many daemons use to log messages
to various system log files.  It is a good idea to always run syslog."),
usb => __("Load the drivers for your usb devices."),
xfs => __("Starts the X Font Server (this is mandatory for XFree to run)."),
    );
    my ($name, $prefix) = @_;
    my $s = $services{$name};
    if ($s) {
	$s = translate($s);
    } else {
	($s = cat_("$prefix/etc/rc.d/init.d/$_")) =~ s/\\\s*\n#\s*//mg;
	($s) = $s =~ /^# description:\s+(.*?)^(?:[^#]|# {0,2}\S)/sm;
	$s =~ s/^#\s*//m;
    }
    $s =~ s/\n/ /gm; $s =~ s/\s+$//;
    $s;
}

#- returns: 
#--- the listref of installed services
#--- the listref of "on" services
sub services {
    my ($prefix) = @_;
    my $cmd = $prefix ? "chroot $prefix" : "";
    my @l = map { [ /([^\s:]+)/, /\bon\b/ ] } grep { !/:$/ } sort `LANGUAGE=C $cmd chkconfig --list`;
    [ map { $_->[0] } @l ], [ mapgrep { $_->[1], $_->[0] } @l ];
}

sub ask {
    my ($in, $prefix) = @_;
    my ($l, $on_services) = services($prefix);
    ref($in) !~ /gtk/ || $::isInstall and return $in->ask_many_from_list("drakxservices",
			    _("Choose which services should be automatically started at boot time"),
			    {
			     list => $l,
			     help => sub { description($_, $prefix) },
			     values => $on_services,
			     sort => 1,
			    });
    my $W = my_gtk->new(_("Services"));
    my ($x, $y, $w_popup);
    my $nopop = sub { $w_popup and $w_popup->destroy };
    my $display = sub { $nopop->(); $_[0] and gtkmove(gtkshow(gtkadd($w_popup=new Gtk::Window (-popup),
        				       gtksignal_connect(gtkadd(new Gtk::EventBox(),
        				           gtkadd(gtkset_shadow_type(new Gtk::Frame, 'etched_out'),
        					   gtkset_justify(new Gtk::Label($_[0]), 0))),
        					   button_press_event => sub { $nopop->() }
		      ))), $x, $y) };
    my $update_service = sub {
		my $started = -e "/var/lock/subsys/$_[0]";
                my $action = $started ? "stop" : "start";
                $_[1]->set($started ? _("running") : _("stopped"));
                $started, $action;
    };
    my $strip = sub {
                my $infos_old = $_[0];
                my $infos;
		while ($infos_old =~ s/(.{40})//) {
                    $1 =~ /(.*) ([^ ]*)/;
		    $infos .= "$1\n$2";
                }
                $infos .= $infos_old;
    };
    my $b = new Gtk::EventBox();
    $b->set_events(["pointer_motion_mask"]);
    gtkadd($W->{window}, gtkadd($b, gtkpack_($W->create_box_with_title(_("Services and deamons")),
	1, gtkset_usize(createScrolledWindow(create_packtable({ col_spacings => 10, row_spacings => 3 },
	    map {
                my $service = $_;
        	my $infos = $strip->(description($_, $prefix));
                $infos ||= _("No additionnal information\nabout this service, sorry.");
		my $l = new Gtk::Label();
                my ($started, $action) = $update_service->($service, gtkset_justify($l, 0));
		[ gtkpack__(new Gtk::HBox(0,0), $_),
		  gtkpack__(new Gtk::HBox(0,0), $l),
		  gtkpack__(new Gtk::HBox(0,0), gtksignal_connect(new Gtk::Button("Infos"), clicked => sub { $display->($infos) })),
                  gtkpack__(new Gtk::HBox(0,0), gtkset_active(gtksignal_connect(
                          new Gtk::CheckButton(_("On boot")),
                          clicked => sub { if ($_[0]->active) {
                                               "@$on_services" =~ /$service/ or push(@$on_services,$service)
                                           } else {
                                               @$on_services = grep(!/$service/, @$on_services)
                                        }}), "@$on_services" =~ /$service/ )),
		  map { my $a = $_;
                      gtkpack__(new Gtk::HBox(0,0), gtksignal_connect(new Gtk::Button(_($a)),
                          clicked => sub { my $c = "service $service " . (lc($a) eq "start" ? "restart" : lc($a)) . " 2>&1"; local $_=`$c`; s/\033\[[^mG]*[mG]//g;
                                           ($started, $action) = $update_service->($service, $l);
                                           $display->($_);
                                         }
                      )) } ("Start", "Stop")
		]
	    }
            @$l)), 500, 400),
            0, gtkpack(gtkset_border_width(new Gtk::HBox(0,0),5), $W->create_okcancel)
            ))
	  );
    $b->signal_connect( motion_notify_event => sub { my ($w, $e) = @_;
                                                               my ($ox, $oy) = $w->window->get_deskrelative_origin;
                                                               $x = $e->{'x'}+$ox; $y = $e->{'y'}+$oy; });
    $b->signal_connect( button_press_event => sub { $nopop->()});
    $::isEmbedded and Gtk->main_iteration while Gtk->events_pending;
    $::isEmbedded and kill (12, $::CCPID);
    $W->main or return;
    ($l, $on_services);
}

sub doit {
    my ($in, $on_services, $prefix) = @_;
    my ($l, $was_on_services) = services($prefix);

    foreach (@$l) {
	my $before = member($_, @$was_on_services);
	my $after = member($_, @$on_services);
	if ($before != $after) {
	    my $script = "/etc/rc.d/init.d/$_";
	    run_program::rooted($prefix, "chkconfig", $after ? "--add" : "--del", $_);
	    if ($after && cat_("$prefix$script") =~ /^#\s+chkconfig:\s+-/m) {
		run_program::rooted($prefix, "chkconfig", "--level", "35", $_, "on");
	    }
	    if (!$after && $::isStandalone) {
		run_program::rooted($prefix, $script, "stop");
	    }
	}
    }
}


1;
S -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', 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 = ( arch() =~ /^ppc/ ? ( 0x07 => 'hpfs', ) : ( 0x07 => 'ntfs', ), arch() !~ /^sparc/ ? ( 0x01 => 'vfat', 0x04 => 'vfat', 0x05 => 'ignore', 0x06 => 'vfat', ) : (), 0x0b => 'vfat', 0x0c => 'vfat', 0x0e => 'vfat', 0x1b => 'vfat', 0x1c => 'vfat', 0x1e => 'vfat', 0x82 => 'swap', 0x83 => 'ext2', 0x183=> 'reiserfs', 0x402 => 'hfs', nfs => 'nfs', #- hack ); my %types_rev = reverse %types; my %fs2type = reverse %type2fs; 1; sub important_types { $::expert and return sort values %types; @important_types, $::beginner ? () : @important_types2; } sub type2name($) { $types{$_[0]} || $_[0] } sub type2fs($) { $type2fs{$_[0]} } sub fs2type($) { $fs2type{$_[0]} } sub name2type($) { local ($_) = @_; /0x(.*)/ ? hex $1 : $types_rev{$_} || $_; } sub isWholedisk($) { arch() =~ /^sparc/ && $_[0]{type} == 5 } sub isExtended($) { (arch() !~ /^sparc/ && $_[0]{type} == 5) || $_[0]{type} == 0xf || $_[0]{type} == 0x85 } sub isRAID($) { $_[0]{type} == 0xfd } sub isSwap($) { $type2fs{$_[0]{type}} eq 'swap' } sub isExt2($) { $type2fs{$_[0]{type}} eq 'ext2' } sub isReiserfs($) { $type2fs{$_[0]{type}} eq 'reiserfs' } sub isDos($) { $ {{ 1=>1, 4=>1, 6=>1 }}{$_[0]{type}} } sub isWin($) { $ {{ 0xb=>1, 0xc=>1, 0xe=>1, 0x1b=>1, 0x1c=>1, 0x1e=>1 }}{$_[0]{type}} } sub isFat($) { isDos($_[0]) || isWin($_[0]) } sub isNfs($) { $_[0]{type} eq 'nfs' } #- small hack sub isNT($) { $_[0]{type} == 0x7 } sub isSupermount($) { $_[0]{type} eq 'supermount' } sub isHFS($) { $type2fs{$_[0]{type}} eq 'hfs' } sub isApplePartMap { defined $_[0]{isMap} } sub isLoopback { defined $_[0]{loopback_file} } sub isTrueFS { isExt2($_[0]) || isReiserfs($_[0]) } sub isMountableRW { isTrueFS($_[0]) || isFat($_[0]) } sub isPrimary($$) { my ($part, $hd) = @_; foreach (@{$hd->{primary}{raw}}) { $part eq $_ and return 1; } 0; } sub adjustStartAndEnd($$) { my ($hd, $part) = @_; $hd->adjustStart($part); $hd->adjustEnd($part); } 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 (@_) { next if !$i || !$_ || $i == $_ || isWholedisk($i); #- avoid testing twice on whole disk for simplicity :-) isWholedisk($_) ? verifyInside($i, $_) || cdie sprintf("partitions sector #$i->{start} (%dMB) is not inside whole disk (%dMB)!", $i->{size} >> 11, $_->{size} >> 11) : verifyNotOverlap($i, $_) || cdie sprintf("partitions sector #$i->{start} (%dMB) and sector #$_->{start} (%dMB) are overlapping!", $i->{size} >> 11, $_->{size} >> 11); } } } sub verifyParts($) { my ($hd) = @_; verifyParts_(get_normal_parts($hd)); } sub verifyPrimary($) { my ($pt) = @_; $_->{start} > 0 || arch() =~ /^sparc/ || die "partition must NOT start at sector 0" foreach @{$pt->{normal}}; 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}; my $only_linux = 1; foreach (map $_->{normal}, @l) { $start = min($start, $_->{start}); $end = max($end, $_->{start} + $_->{size}); $only_linux &&= isTrueFS($_) || isSwap($_); } $l->{start} = $hd->{primary}{extended}{start} = $start; $l->{size} = $hd->{primary}{extended}{size} = $end - $start; $hd->{primary}{extended}{type} = $only_linux ? 0x85 : 0x5 if !$::expert; } 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 adjust_local_extended($$) { my ($hd, $part) = @_; foreach (@{$hd->{extended} || []}) { $_->{normal} == $part or next; $_->{size} = $part->{size} + $part->{start} - $_->{start}; last; } } sub get_normal_parts($) { my ($hd) = @_; #- HACK !! $hd->{raid} and return grep {$_} @{$hd->{raid}}; $hd->{loopback} and return grep {$_} @{$hd->{loopback}}; @{$hd->{primary}{normal} || []}, map { $_->{normal} } @{$hd->{extended} || []} } sub get_holes($) { my ($hd) = @_; my $start = 1; map { my $current = $start; $start = $_->{start} + $_->{size}; { start => $current, size => $_->{start} - $current } } sort { $a->{start} <=> $b->{start} } get_normal_parts($hd), { start => $hd->{totalsectors}, size => 0 }; } sub read_one($$) { my ($hd, $sector) = @_; my ($pt, $info); foreach ('dos', 'bsd', 'sun', 'mac', 'unknown') { /unknown/ and die "unknown partition table format"; eval { bless $hd, "partition_table_$_"; ($pt, $info) = $hd->read($sector); }; $@ or last; } my @extended = $hd->hasExtended ? 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, info => $info }; } sub read($;$) { my ($hd, $clearall) = @_; if ($clearall) { partition_table_raw::zero_MBR($hd); return 1; } my $pt = read_one($hd, 0) or return 0; $hd->{primary} = $pt; undef $hd->{extended}; 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}; #- the following verification can broke an existing partition table that is #- correctly read by fdisk or cfdisk. maybe the extended partition can be #- recomputed to get correct size. if (!verifyInside($pt->{normal}, $extended)) { $extended->{size} = $pt->{normal}{start} + $pt->{normal}{size}; 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; } #- last chance for verification, this make sure if an error is detected, #- it will never be writed back on partition table. verifyParts($hd); $hd->write(0, $hd->{primary}{raw}, $hd->{primary}{info}) or die "writing of partition table failed"; #- should be fixed but a extended exist with no real extended partition, that blanks mbr! 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}; $hd->write($_->{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(); $hd->kernel_read; $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++; } my ($first, $second, $third) = map { $_->{normal} } @{$hd->{extended} || []}; if ($third && $first eq $part) { die "Can't handle removing hda5 when hda6 is not the second partition" if $second->{start} > $third->{start}; } #- 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, $extended_type) = @_; $extended_type =~ s/Extended_?//; 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, $hd->cylinder_size()); $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 => $extended_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) = @_; get_normal_parts($hd) >= ($hd->{device} =~ /^sd/ ? 15 : 63) and cdie "maximum number of partitions handled by linux reached"; $part->{notFormatted} = 1; $part->{isFormatted} = 0; $part->{rootDevice} = $hd->{device}; $hd->{isDirty} = $hd->{needKernelReread} = 1; $part->{start} ||= 1 if arch() !~ /^sparc/; #- starting at sector 0 is not allowed adjustStartAndEnd($hd, $part) unless $forceNoAdjust; my $e = $hd->{primary}{extended}; if ($primaryOrExtended eq 'Primary' || $primaryOrExtended !~ /Extended/ && is_empty_array_ref($hd->{primary}{normal})) { eval { add_primary($hd, $part) }; return unless $@; } eval { add_extended($hd, $part, $primaryOrExtended) } if $hd->hasExtended; #- try adding extended if ($@ || !$hd->hasExtended) { 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; delete @$_{qw(isMounted isFormatted notFormatted toFormat toFormatUnsure)} foreach get_normal_parts($hd); $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); }