summaryrefslogtreecommitdiffstats
path: root/mdk-stage1/tools.c
blob: cd1b40fe89fc810580fdf87a153244a3b669c6b1 (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
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
/*
 * Guillaume Cottenceau (gc@mandrakesoft.com)
 *
 * Copyright 2000 MandrakeSoft
 *
 * This software may be freely redistributed under the terms of the GNU
 * public license.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

/*
 * Portions from Erik Troan (ewt@redhat.com)
 *
 * Copyright 1996 Red Hat Software 
 *
 */

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <bzlib.h>
#include <sys/mount.h>
#include "stage1.h"
#include "log.h"
#include "mount.h"
#include "frontend.h"
#include "automatic.h"

#include "tools.h"


static struct param_elem params[50];
static int param_number = 0;

void process_cmdline(void)
{
	char buf[512];
	int fd, size, i;
	
	log_message("opening /proc/cmdline... ");
	
	if ((fd = open("/proc/cmdline", O_RDONLY)) == -1)
		fatal_error("could not open /proc/cmdline");
	
	size = read(fd, buf, sizeof(buf));
	buf[size-1] = '\0'; // -1 to eat the \n
	close(fd);

	log_message("\t%s", buf);

	i = 0;
	while (buf[i] != '\0') {
		char *name, *value = NULL;
		int j = i;
		while (buf[i] != ' ' && buf[i] != '=' && buf[i] != '\0')
			i++;
		if (i == j) {
			i++;
			continue;
		}
		name = memdup(&buf[j], i-j + 1);
		name[i-j] = '\0';

		if (buf[i] == '=') {
			int k = i+1;
			i++;
			while (buf[i] != ' ' && buf[i] != '\0')
				i++;
			value = memdup(&buf[k], i-k + 1);
			value[i-k] = '\0';
		}

		params[param_number].name = name;
		params[param_number].value = value;
		param_number++;
		if (!strcmp(name, "expert")) set_param(MODE_EXPERT);
		if (!strcmp(name, "rescue")) set_param(MODE_RESCUE);
		if (!strcmp(name, "special_stage2")) set_param(MODE_SPECIAL_STAGE2);
		if (!strcmp(name, "automatic")) {
			set_param(MODE_AUTOMATIC);
			grab_automatic_params(value);
		}
		if (buf[i] == '\0')
			break;
		i++;
	}
	
	log_message("\tgot %d args", param_number);
}


int stage1_mode = 0;

int get_param(int i)
{
#ifdef SPAWN_INTERACTIVE
	static int fd = 0;
	char buf[5000];
	char * ptr;
	int nb;

	if (fd <= 0) {
		fd = open(interactive_fifo, O_RDONLY);
		if (fd == -1)
			return (stage1_mode & i);
		fcntl(fd, F_SETFL, O_NONBLOCK);
	}

	if (fd > 0) {
		if ((nb = read(fd, buf, sizeof(buf))) > 0) {
			buf[nb] = '\0';
			ptr = buf;
			while ((ptr = strstr(ptr, "+ "))) {
				if (!strncmp(ptr+2, "expert", 6)) set_param(MODE_EXPERT);
				if (!strncmp(ptr+2, "rescue", 6)) set_param(MODE_RESCUE);
				ptr++;
			}
			ptr = buf;
			while ((ptr = strstr(ptr, "- "))) {
				if (!strncmp(ptr+2, "expert", 6)) unset_param(MODE_EXPERT);
				if (!strncmp(ptr+2, "rescue", 6)) unset_param(MODE_RESCUE);
				ptr++;
			}
		}
	}
#endif

	return (stage1_mode & i);
}

char * get_param_valued(char *param_name)
{
	int i;
	for (i = 0; i < param_number ; i++)
		if (!strcmp(params[i].name, param_name))
			return params[i].value;

	return NULL;
}

void set_param_valued(char *param_name, char *param_value)
{
	params[param_number].name = param_name;
	params[param_number].value = param_value;
	param_number++;
}

void set_param(int i)
{
	stage1_mode |= i;
	if (i == MODE_RESCUE) {
		set_param_valued("special_stage2", "rescue");
		set_param(MODE_SPECIAL_STAGE2);
	}
}

void unset_param(int i)
{
	stage1_mode &= ~i;
}

int charstar_to_int(char * s)
{
	int number = 0;
	while (*s && isdigit(*s)) {
		number = (number * 10) + (*s - '0');
		s++;
	}
	return number;
}

int total_memory(void)
{
	int value;
	struct stat statr;
	if (stat("/proc/kcore", &statr))
		return 0;

	/* drakx powered: use /proc/kcore and rounds every 4 Mbytes */
	value = 4 * ((int)((float)statr.st_size / 1024 / 1024 / 4 + 0.5));
	log_message("Total Memory: %d Mbytes", value);

	return value;
}


int ramdisk_possible(void)
{
	if (total_memory() > MEM_LIMIT_RAMDISK)
		return 1;
	else {
		log_message("warning, ramdisk is not possible due to low mem!");
		return 0;
	}
}


static void save_stuff_for_rescue(void)
{
	void save_this_file(char * file) {
		char buf[5000];
		int fd_r, fd_w, i;
		char location[100];

		if ((fd_r = open(file, O_RDONLY)) < 0) {
			log_message("can't open %s for read", file);
			return;
		}
		strcpy(location, STAGE2_LOCATION);
		strcat(location, file);
		if ((fd_w = open(location, O_WRONLY)) < 0) {
			log_message("can't open %s for write", location);
			close(fd_r);
			return;
		}
		if ((i = read(fd_r, buf, sizeof(buf))) <= 0) {
			log_message("can't read from %s", file);
			close(fd_r); close(fd_w);
			return;
		}
		if (write(fd_w, buf, i) != i)
			log_message("can't write %d bytes to %s", i, location);
		close(fd_r); close(fd_w);
		log_message("saved file %s for rescue (%d bytes)", file, i);
	}
	save_this_file("/etc/resolv.conf");
}


enum return_type load_ramdisk_fd(int ramdisk_fd, int size)
{
	BZFILE * st2;
	char * ramdisk = "/dev/ram3"; /* warning, verify that this file exists in the initrd (and actually is a ramdisk device file) */
	int ram_fd;
	char buffer[4096];
	int z_errnum;
	char * wait_msg = "Loading program into memory...";
	int bytes_read = 0;
	int actually;
	int seems_ok = 0;

	st2 = BZ2_bzdopen(ramdisk_fd, "r");

	if (!st2) {
		log_message("Opening compressed ramdisk: %s", BZ2_bzerror(st2, &z_errnum));
		error_message("Could not open compressed ramdisk file.");
		return RETURN_ERROR;
	}

	ram_fd = open(ramdisk, O_WRONLY);
	if (ram_fd == -1) {
		log_perror(ramdisk);
		error_message("Could not open ramdisk device file.");
		return RETURN_ERROR;
	}
	
	init_progression(wait_msg, size);

	while ((actually = BZ2_bzread(st2, buffer, sizeof(buffer))) > 0) {
		seems_ok = 1;
		if (write(ram_fd, buffer, actually) != actually) {
			log_perror("writing ramdisk");
			remove_wait_message();
			return RETURN_ERROR;
		}
		update_progression((int)((bytes_read += actually) / RAMDISK_COMPRESSION_RATIO));
	}

	if (!seems_ok) {
		log_message("reading compressed ramdisk: %s", BZ2_bzerror(st2, &z_errnum));
		remove_wait_message();
		error_message("Could not uncompress second stage ramdisk.");
		return RETURN_ERROR;
	}

	end_progression();

	BZ2_bzclose(st2); /* opened by gzdopen, but also closes the associated fd */
	close(ram_fd);

	if (my_mount(ramdisk, STAGE2_LOCATION, "ext2"))
		return RETURN_ERROR;

	set_param(MODE_RAMDISK);

	if (IS_RESCUE) {
		save_stuff_for_rescue();
		if (umount(STAGE2_LOCATION)) {
			log_perror(ramdisk);
			return RETURN_ERROR;
		}
		return RETURN_OK; /* fucksike, I lost several hours wondering why the kernel won't see the rescue if it is alreay mounted */
	}

	return RETURN_OK;
}


char * get_ramdisk_realname(void)
{
	char img_name[500];
	char * stg2_name = get_param_valued("special_stage2");
	char * begin_img = RAMDISK_LOCATION;
	char * end_img = "_stage2.bz2";

	if (!stg2_name)
		stg2_name = "mdkinst";

	if (IS_RESCUE)
		stg2_name = "rescue";
	
	strcpy(img_name, begin_img);
	strcat(img_name, stg2_name);
	strcat(img_name, end_img);

	return strdup(img_name);
}


enum return_type load_ramdisk(void)
{
	int st2_fd;
	struct stat statr;
	char img_name[500];

	strcpy(img_name, IMAGE_LOCATION);
	strcat(img_name, get_ramdisk_realname());

	log_message("trying to load %s as a ramdisk", img_name);

	st2_fd = open(img_name, O_RDONLY); /* to be able to see the progression */

	if (st2_fd == -1) {
		log_message("open ramdisk file (%s) failed", img_name);
		error_message("Could not open compressed ramdisk file (%s).", img_name);
		return RETURN_ERROR;
	}

	if (stat(img_name, &statr))
		return RETURN_ERROR;
	else
		return load_ramdisk_fd(st2_fd, statr.st_size);
}

/* pixel's */
void * memdup(void *src, size_t size)
{
	void * r;
	r = malloc(size);
	memcpy(r, src, size);
	return r;
}


static char ** my_env = NULL;
static int env_size = 0;

void handle_env(char ** env)
{
	char ** ptr = env;
	while (ptr && *ptr) {
		ptr++;
		env_size++;
	}
	my_env = malloc(sizeof(char *) * 100);
	memcpy(my_env, env, sizeof(char *) * (env_size+1));
}

char ** grab_env(void) {
	return my_env;
}

void add_to_env(char * name, char * value)
{
	char tmp[500];
	sprintf(tmp, "%s=%s", name, value);
	my_env[env_size] = strdup(tmp);
	env_size++;
	my_env[env_size] = NULL;
}


char ** list_directory(char * direct)
{
	char * tmp[50000]; /* in /dev there can be many many files.. */
	int i = 0;
	struct dirent *ep;
	DIR *dp = opendir(direct);
	while (dp && (ep = readdir(dp))) {
		if (strcmp(ep->d_name, ".") && strcmp(ep->d_name, "..")) {
			tmp[i] = strdup(ep->d_name);
			i++;
		}
	}
	if (dp)
		closedir(dp);
	tmp[i] = NULL;
	return memdup(tmp, sizeof(char*) * (i+1));
}


int string_array_length(char ** a)
{
	int i = 0;
	if (!a)
		return -1;
	while (a && *a) {
		a++;
		i++;
	}
	return i;
}
pan> "alpha" ? "bsd" : arch() =~ /^sparc/ ? "sun" : arch() eq "ppc" && detect_devices::get_mac_model() !~ /^IBM/ ? "mac" : $hd->{totalsectors} > 4 * 1024 * 1024 * 2048 ? 'lvm' : "dos"; #- default to LVM on full disk when >4TB } sub initialize { my ($hd, $o_type) = @_; my $type = $o_type || _default_type($hd); require "partition_table/$type.pm"; "partition_table::$type"->initialize($hd); delete $hd->{extended}; if (detect_devices::is_xbox()) { my $part = { start => 1, size => 15632048, pt_type => 0x0bf, isFormatted => 1 }; partition_table::dos::compute_CHS($hd, $part); $hd->{primary}{raw}[0] = $part; } } sub read_primary { my ($hd) = @_; #- it can be safely considered that the first sector is used to probe the partition table #- but other sectors (typically for extended partition ones) have to match this type! my @parttype = ( if_(arch() =~ /^ia64/, 'gpt'), # gpt must be tried before dos as it presents a fake compatibility mbr arch() =~ /^sparc/ ? ('sun', 'bsd') : ('gpt', 'lvm', 'dmcrypt', 'dos', 'bsd', 'sun', 'mac'), ); foreach ('empty', @parttype, 'unknown') { /unknown/ and die "unknown partition table format on disk " . $hd->{file}; # perl_checker: require partition_table::bsd # perl_checker: require partition_table::dos # perl_checker: require partition_table::empty # perl_checker: require partition_table::dmcrypt # perl_checker: require partition_table::lvm # perl_checker: require partition_table::gpt # perl_checker: require partition_table::mac # perl_checker: require partition_table::sun require "partition_table/$_.pm"; bless $hd, "partition_table::$_"; if ($hd->read_primary) { log::l("found a $_ partition table on $hd->{file} at sector 0"); return 1; } } 0; } sub read { my ($hd) = @_; read_primary($hd) or return 0; eval { my $need_removing_empty_extended; if ($hd->{primary}{extended}) { read_extended($hd, $hd->{primary}{extended}, \$need_removing_empty_extended) or return 0; } if ($need_removing_empty_extended) { #- special case when hda5 is empty, it must be skipped #- (windows XP generates such partition tables) remove_empty_extended($hd); #- includes adjust_main_extended } }; die "extended partition: $@" if $@; assign_device_numbers($hd); remove_empty_extended($hd); $hd->set_best_geometry_for_the_partition_table; 1; } sub read_extended { my ($hd, $extended, $need_removing_empty_extended) = @_; my $pt = do { my ($pt, $info) = $hd->read_one($extended->{start}) or return 0; partition_table::raw::pt_info_to_primary($hd, $pt, $info); }; $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!)"; if (@{$pt->{normal}} == 0) { $$need_removing_empty_extended = 1; delete $pt->{normal}; print "need_removing_empty_extended\n"; } elsif (@{$pt->{normal}} > 1) { die "more than one normal partition in extended partition"; } else { $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}; return read_extended($hd, $pt->{extended}, $need_removing_empty_extended); } else { 1; } } sub will_tell_kernel { my ($hd, $action, $o_part, $o_delay) = @_; if ($action eq 'resize') { will_tell_kernel($hd, del => $o_part); will_tell_kernel($hd, add => $o_part); } else { my $part_number; if ($o_part) { ($part_number) = $o_part->{device} =~ /(\d+)$/ or #- do not die, it occurs when we zero_MBR_and_dirty a raw_lvm_PV log::l("ERROR: will_tell_kernel bad device " . description($o_part)), return; } my @para = $action eq 'force_reboot' ? () : $action eq 'add' ? ($part_number, $o_part->{start}, $o_part->{size}) : $action eq 'del' ? $part_number : internal_error("unknown action $action"); push @{$hd->{'will_tell_kernel' . ($o_delay || '')} ||= []}, [ $action, @para ]; } if (!$o_delay) { foreach my $delay ('delay_del', 'delay_add') { my $l = delete $hd->{"will_tell_kernel$delay"} or next; push @{$hd->{will_tell_kernel} ||= []}, @$l; } } $hd->{isDirty} = 1; } sub tell_kernel { my ($hd, $tell_kernel) = @_; my $F = partition_table::raw::openit($hd); my $force_reboot = any { $_->[0] eq 'force_reboot' } @$tell_kernel; if (!$force_reboot) { # only keep the last action on the partition number # that way we do not del/add the same partition, and this helps udev :) foreach (reverse(uniq_ { $_->[1] } reverse @$tell_kernel)) { my ($action, $part_number, $o_start, $o_size) = @$_; if ($action eq 'add') { $force_reboot ||= !c::add_partition(fileno $F, $part_number, $o_start, $o_size); } elsif ($action eq 'del') { $force_reboot ||= !c::del_partition(fileno $F, $part_number); } log::l("tell kernel $action ($hd->{device} $part_number $o_start $o_size) force_reboot=$force_reboot rebootNeeded=$hd->{rebootNeeded}"); } } if ($force_reboot) { my @magic_parts = grep { $_->{isMounted} && $_->{real_mntpoint} } get_normal_parts($hd); foreach (@magic_parts) { syscall_('umount', $_->{real_mntpoint}) or log::l(N("error unmounting %s: %s", $_->{real_mntpoint}, $!)); } $hd->{rebootNeeded} = !ioctl($F, c::BLKRRPART(), 0); log::l("tell kernel force_reboot ($hd->{device}), rebootNeeded=$hd->{rebootNeeded}"); foreach (@magic_parts) { syscall_('mount', $_->{real_mntpoint}, $_->{fs_type}, c::MS_MGC_VAL()) or log::l(N("mount failed: ") . $!); } } } # write the partition table sub write { my ($hd) = @_; $hd->{isDirty} or return; $hd->{readonly} and internal_error("a read-only partition table should not be dirty ($hd->{device})!"); #- set first primary partition active if no primary partitions are marked as active. if (my @l = @{$hd->{primary}{raw}}) { foreach (@l) { $_->{local_start} = $_->{start}; $_->{active} ||= 0; } $l[0]{active} = 0x80 if !any { $_->{active} } @l; } #- 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! if (arch() !~ /^sparc/) { 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; if (my $tell_kernel = delete $hd->{will_tell_kernel}) { if (fs::type::is_dmraid($hd)) { fs::dmraid::call_dmraid('-an'); fs::dmraid::call_dmraid('-ay'); } else { tell_kernel($hd, $tell_kernel); } } # get major/minor again after writing the partition table so that we got them for dynamic devices # (eg: for SCSI like devices with kernel-2.6.28+): fs::get_major_minor([ get_normal_parts($hd) ]); } sub active { my ($hd, $part) = @_; $_->{active} = 0 foreach @{$hd->{primary}{normal}}; $part->{active} = 0x80; $hd->{isDirty} = 1; } # 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) { will_tell_kernel($hd, del => $_); splice(@{$hd->{primary}{normal}}, $i, 1); %$_ = (); #- blank it $hd->raw_removed($hd->{primary}{raw}); return 1; } $i++; } my ($first, $second, $third) = map { $_->{normal} } @{$hd->{extended} || []}; if ($third && $first eq $part) { die "Can not 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); assign_device_numbers($hd); will_tell_kernel($hd, del => $part); return 1; } 0; } # create of partition at starting at `start', of size `size' and of type `pt_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 $hd->raw_add($hd->{primary}{raw}, $part); } push @{$hd->{primary}{normal}}, $part; #- really do it } sub add_extended { arch() =~ /^sparc|ppc/ and die N("Extended partition not supported on this platform"); my ($hd, $part, $extended_type) = @_; $extended_type =~ s/Extended_?//; my $e = $hd->{primary}{extended}; if ($e && !verifyInside($part, $e)) { #-die "sorry, can not 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 N("You have a hole in your partition table but I can not 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}}, { pt_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});