summaryrefslogtreecommitdiffstats
path: root/perl-install/authentication.pm
blob: f82a05cb846013224704382f0946303842c770c3 (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
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
package authentication; # $Id$

use common;
use any;

sub kinds { 
    my $no_para = @_ == 0;
    my ($do_pkgs, $meta_class) = @_;
    my $allow_SmartCard = $no_para || $do_pkgs->is_available('castella-pam');
    my $allow_AD = $no_para || $meta_class =~ /corporate/;
    (
	'local', 
	'LDAP',
	'NIS', 
	if_($allow_SmartCard, 'SmartCard'), 
	'winbind', 
	if_($allow_AD, 'AD', 'SMBKRB'),
    );
}

sub kind2name {
    my ($kind) = @_;
    # Keep the following strings in sync with kind2description ones!!!
    ${{ local => N("Local file"), 
    LDAP => N("LDAP"), 
    NIS => N("NIS"),
    SmartCard => N("Smart Card"),
    winbind => N("Windows Domain"), 
    AD => N("Active Directory with SFU"),
    SMBKRB => N("Active Directory with Winbind") }}{$kind};
}

my %kind2pam_kind = (
    local     => [],
    SmartCard => ['castella'],
    LDAP      => ['ldap'], 
    NIS       => [],
    AD        => ['krb5'],
    winbind   => ['winbind'], 
    SMBKRB    => ['winbind'],
);

my %kind2nsswitch = (
    local     => [],
    SmartCard => [],
    LDAP      => ['ldap'], 
    NIS       => ['nis'],
    AD        => ['ldap'],
    winbind   => ['winbind'], 
    SMBKRB    => ['winbind'],
);

sub kind2description() {
    join('', 
         map {
             qq($_->[0]\n$_->[1]\n\n);
         }
         (
          [ N("Local file:"), N("Use local for all authentication and information user tell in local file"), ],
          [ N("LDAP:"), N("Tells your computer to use LDAP for some or all authentication. LDAP consolidates certain types of information within your organization."), ],
          [ N("NIS:"), N("Allows you to run a group of computers in the same Network Information Service domain with a common password and group file."), ],
          [ N("Windows Domain:"), N("Winbind allows the system to retrieve information and authenticate users in a Windows domain."), ],
          [ N("Active Directory with SFU:"), N("Kerberos is a secure system for providing network authentication services."), ],
          [ N("Active Directory with Winbind:"), N("Kerberos is a secure system for providing network authentication services.")  ],
         )
        );
}
sub to_kind {
    my ($authentication) = @_;
    (find { exists $authentication->{$_} } kinds()) || 'local';
}

sub domain_to_ldap_domain {
    my ($domain) = @_;
    join(',', map { "dc=$_" } split /\./, $domain);
}

sub ask_parameters {
    my ($in, $netc, $authentication, $kind) = @_;

    #- keep only this authentication kind
    foreach (kinds()) {
	delete $authentication->{$_} if $_ ne $kind;
    }

    if ($kind eq 'LDAP') {
	$netc->{LDAPDOMAIN} ||= domain_to_ldap_domain($netc->{DOMAINNAME});
	$in->ask_from('',
		     N("Authentication LDAP"),
		     [ { label => N("LDAP Base dn"), val => \$netc->{LDAPDOMAIN} },
		       { label => N("LDAP Server"), val => \$authentication->{LDAP_server} },
		     ]) or return;
    } elsif ($kind eq 'AD') {
	
	$authentication->{AD_domain} ||= $netc->{DOMAINNAME};
	$authentication->{AD_users_db} ||= 'cn=users,' . domain_to_ldap_domain($authentication->{AD_domain});

	$in->do_pkgs->install(qw(perl-Net-DNS));

	my @srvs = query_srv_names($authentication->{AD_domain});
	$authentication->{AD_server} ||= $srvs[0] if @srvs;

	my %sub_kinds = my @sub_kinds = (
	    simple => N("simple"), 
	    tls => N("TLS"),
	    ssl => N("SSL"),
	    kerberos => N("security layout (SASL/Kerberos)"),
	);

	my $AD_user = $authentication->{AD_user} =~ /(.*)\@\Q$authentication->{AD_domain}\E$/ ? $1 : $authentication->{AD_user};
	my $anonymous = $AD_user;

	$in->ask_from('',
		     N("Authentication Active Directory"),
		     [ { label => N("Domain"), val => \$authentication->{AD_domain} },
		     #{ label => N("Server"), val => \$authentication->{AD_server} },
		       { label => N("Server"), type => 'combo', val => \$authentication->{AD_server}, list => \@srvs , not_edit => 0 },
		       { label => N("LDAP users database"), val => \$authentication->{AD_users_db} },
		       { label => N("Use Anonymous BIND "), val => \$anonymous, type => 'bool' },
		       { label => N("LDAP user allowed to browse the Active Directory"), val => \$AD_user, disabled => sub { $anonymous } },
		       { label => N("Password for user"), val => \$authentication->{AD_password}, disabled => sub { $anonymous } },
		       { label => N("Encryption"), val => \$authentication->{sub_kind}, list => [ map { $_->[0] } group_by2(@sub_kinds) ], format => sub { $sub_kinds{$_[0]} } },
		     ]) or return;
	$authentication->{AD_user} = !$AD_user || $authentication->{sub_kind} eq 'anonymous' ? '' : 
	                             $AD_user =~ /@/ ? $AD_user : "$AD_user\@$authentication->{AD_domain}";
	$authentication->{AD_password} = '' if !$authentication->{AD_user};


    } elsif ($kind eq 'NIS') { 
	$authentication->{NIS_server} ||= 'broadcast';
	$netc->{NISDOMAIN} ||= $netc->{DOMAINNAME};
	$in->ask_from('',
		     N("Authentication NIS"),
		     [ { label => N("NIS Domain"), val => \$netc->{NISDOMAIN} },
		       { label => N("NIS Server"), val => \$authentication->{NIS_server}, list => ["broadcast"], not_edit => 0 },
		     ]) or return;
    } elsif ($kind eq 'winbind' || $kind eq 'SMBKRB') {
	#- maybe we should browse the network like diskdrake --smb and get the 'doze server names in a list 
	#- but networking is not setup yet necessarily
	$in->ask_warn('', N("For this to work for a W2K PDC, you will probably need to have the admin run: C:\\>net localgroup \"Pre-Windows 2000 Compatible Access\" everyone /add and reboot the server.
You will also need the username/password of a Domain Admin to join the machine to the Windows(TM) domain.
If networking is not yet enabled, Drakx will attempt to join the domain after the network setup step.
Should this setup fail for some reason and domain authentication is not working, run 'smbpasswd -j DOMAIN -U USER%%PASSWORD' using your Windows(tm) Domain, and Admin Username/Password, after system boot.
The command 'wbinfo -t' will test whether your authentication secrets are good."))
	  if $kind eq 'winbind';

	$authentication->{AD_domain} ||= $netc->{DOMAINNAME} if $kind eq 'SMBKRB';
	 $authentication->{AD_users_idmap} ||= 'ou=idmap,' . domain_to_ldap_domain($authentication->{AD_domain}) if $kind eq 'SMBKRB';
	$netc->{WINDOMAIN} ||= $netc->{DOMAINNAME};
	my $anonymous;
	$in->ask_from('',
		      $kind eq 'SMBKRB' ? N("Authentication Active Directory") : N("Authentication Windows Domain"),
		        [ if_($kind eq 'SMBKRB', 
			  { label => N("Domain"), val => \$authentication->{AD_domain} }
			     ),
			  { label => N("Windows Domain"), val => \$netc->{WINDOMAIN} },
			  { label => N("Domain Admin User Name"), val => \$authentication->{winuser} },
			  { label => N("Domain Admin Password"), val => \$authentication->{winpass}, hidden => 1 },
			  { label => N("Use Idmap for store UID/SID "), val => \$anonymous, type => 'bool' },
			  { label => N("Default Idmap "), val => \$authentication->{AD_users_idmap}, disabled => sub { $anonymous } },
			]) or return;
    }
    $authentication->{$kind} ||= 1;
    1;
}

sub ask_root_password_and_authentication {
    my ($in, $netc, $superuser, $authentication, $meta_class, $security) = @_;

    my $kind = to_kind($authentication);

    $in->ask_from_({
	 title => N("Set administrator (root) password and network authentication methods"), 
	 messages => N("Set administrator (root) password"),
	 advanced_label => N("Authentication method"),
	 advanced_messages => kind2description(),
	 interactive_help_id => "setRootPassword",
	 cancel => ($security <= 2 ? 
		    #-PO: keep this short or else the buttons will not fit in the window
		    N("No password") : ''),
	 focus_first => 1,
	 callbacks => { 
	     complete => sub {
		 $superuser->{password} eq $superuser->{password2} or $in->ask_warn('', [ N("The passwords do not match"), N("Please try again") ]), return 1,0;
		 length $superuser->{password} < 2 * $security
		   and $in->ask_warn('', N("This password is too short (it must be at least %d characters long)", 2 * $security)), return 1,0;
		 return 0;
        } } }, [
{ label => N("Password"), val => \$superuser->{password},  hidden => 1 },
{ label => N("Password (again)"), val => \$superuser->{password2}, hidden => 1 },
{ label => N("Authentication"), val => \$kind, type => 'list', list => [ authentication::kinds($in->do_pkgs, $meta_class) ], format => \&authentication::kind2name, advanced => 1 },
        ]) or delete $superuser->{password};

    ask_parameters($in, $netc, $authentication, $kind) or goto &ask_root_password_and_authentication;
}


sub get() {
    my $system_auth = cat_("/etc/pam.d/system-auth");
    { md5 => $system_auth =~ /md5/, shadow => $system_auth =~ /shadow/ };
}

sub set {
    my ($in, $netc, $authentication, $o_when_network_is_up) = @_;

    my $when_network_is_up = $o_when_network_is_up || sub { my ($f) = @_; $f->() };

    enable_shadow() if $authentication->{shadow};    

    my $kind = authentication::to_kind($authentication);

    log::l("authentication::set $kind");

    my $pam_modules = $kind2pam_kind{$kind} or log::l("kind2pam_kind does not know $kind");
    $pam_modules ||= [];
    sshd_config_UsePAM(@$pam_modules > 0);
    set_pam_authentication(@$pam_modules);

    my $nsswitch = $kind2nsswitch{$kind} or log::l("kind2nsswitch does not know $kind");
    $nsswitch ||= [];
    set_nsswitch_priority(@$nsswitch);

    if ($kind eq 'local') {
    } elsif ($kind eq 'SmartCard') {
	$in->do_pkgs->install('castella-pam');
    } elsif ($kind eq 'LDAP') {
	$in->do_pkgs->install(qw(openldap-clients nss_ldap pam_ldap autofs));

	my $domain = $netc->{LDAPDOMAIN} || do {
	    my $s = run_program::rooted_get_stdout($::prefix, 'ldapsearch', '-x', '-h', $authentication->{LDAP_server}, '-b', '', '-s', 'base', '+');
	    first($s =~ /namingContexts: (.+)/);
	} or log::l("no ldap domain found on server $authentication->{LDAP_server}"), return;

	update_ldap_conf(
			 host => $authentication->{LDAP_server},
			 base => $domain,
			 nss_base_shadow => $domain . "?sub",
			 nss_base_passwd => $domain . "?sub",
			 nss_base_group => $domain . "?sub",
			);
    } elsif ($kind eq 'AD') {
	$in->do_pkgs->install(qw(nss_ldap pam_krb5 libsasl2-plug-gssapi));
	my $port = "389";
	
	my $ssl = { 
		   anonymous => 'off', 
		   simple => 'off', 
		   tls => 'start_tls',
		   ssl => 'on',
		   kerberos => 'off',
		  }->{$authentication->{sub_kind}};

	if ($ssl eq 'on') {
		$port = '636';
	}
	
	
	
	update_ldap_conf(
			 host => $authentication->{AD_server},
			 base => domain_to_ldap_domain($authentication->{AD_domain}),
			 nss_base_shadow => "$authentication->{AD_users_db}?sub",
			 nss_base_passwd => "$authentication->{AD_users_db}?sub",
			 nss_base_group => "$authentication->{AD_users_db}?sub",

			 ssl => $ssl,
			 sasl_mech => $authentication->{sub_kind} eq 'kerberos' ? 'GSSAPI' : '',
			 port => $port,

			 binddn => $authentication->{AD_user},
			 bindpw => $authentication->{AD_password},

			 (map_each { "nss_map_objectclass_$::a" => $::b }
			  posixAccount => 'User',
			  shadowAccount => 'User',
			  posixGroup => 'Group',
			 ),


			 scope => 'sub',
			 pam_login_attribute => 'sAMAccountName',
			 pam_filter => 'objectclass=User',
			 pam_password => 'ad',

			 
			 (map_each { "nss_map_attribute_$::a" => $::b }
			  uid => 'sAMAccountName',
			  uidNumber => 'msSFU30UidNumber',
			  gidNumber => 'msSFU30GidNumber',
			  cn => 'sAMAccountName',
			  uniqueMember => 'member',
			  userPassword => 'msSFU30Password',
			  homeDirectory => 'msSFU30HomeDirectory',
			  loginShell => 'msSFU30LoginShell',
			  gecos => 'name',
			 ),
			);

	configure_krb5_for_AD($authentication);

    } elsif ($kind eq 'NIS') {
	$in->do_pkgs->install(qw(ypbind autofs));
	my $domain = $netc->{NISDOMAIN};
	$domain || $authentication->{NIS_server} ne "broadcast" or die N("Can not use broadcast with no NIS domain");
	my $t = $domain ? "domain $domain" . ($authentication->{NIS_server} ne "broadcast" && " server") : "ypserver";
	substInFile {
	    $_ = "#~$_" unless /^#/;
	    $_ .= "$t $authentication->{NIS_server}\n" if eof;
	} "$::prefix/etc/yp.conf";

	#- no need to modify system-auth for nis

	$when_network_is_up->(sub {
	    run_program::rooted($::prefix, 'nisdomainname', $domain);
	    run_program::rooted($::prefix, 'service', 'ypbind', 'restart');
	}) if !$::isInstall; #- TODO: also do it during install since nis can be useful to resolve domain names. Not done because 9.2-RC
#    } elsif ($kind eq 'winbind' || $kind eq 'AD' && $authentication->{subkind} eq 'winbind') {

#	}) if !$::isInstall; 
#- TODO: also do it during install since nis can be useful to resolve domain names. Not done because 9.2-RC
    } elsif ($kind eq 'winbind') {

	my $domain = uc $netc->{WINDOMAIN};
	
	$in->do_pkgs->install('samba-winbind');

	require network::smb;
	network::smb::write_smb_conf($domain);
	run_program::rooted($::prefix, "chkconfig", "--level", "35", "winbind", "on");
	mkdir_p("$::prefix/home/$domain");
	run_program::rooted($::prefix, 'service', 'smb', 'restart');
	run_program::rooted($::prefix, 'service', 'winbind', 'restart');
	
	#- defer running smbpassword until the network is up

	$when_network_is_up->(sub {
	    run_program::rooted($::prefix, 'net', 'join', $domain, '-U', $authentication->{winuser} . '%' . $authentication->{winpass});
	});
    } elsif ($kind eq 'SMBKRB') {
	 $authentication->{AD_server} ||= 'ads.' . $authentication->{AD_domain};
	my $domain = uc $netc->{WINDOMAIN};
	my $realm = $authentication->{AD_domain};

	configure_krb5_for_AD($authentication);
	$in->do_pkgs->install('samba-winbind', 'pam_krb5', 'samba-server', 'samba-client');
		
	require network::smb;
	network::smb::write_smb_ads_conf($domain,$realm);
	run_program::rooted($::prefix, "chkconfig", "--level", "35", "winbind", "on");
	mkdir_p("$::prefix/home/$domain");
	run_program::rooted($::prefix, 'net', 'time', 'set', '-S', $authentication->{AD_server});
	run_program::rooted($::prefix, 'service', 'smb', 'restart');
	run_program::rooted($::prefix, 'service', 'winbind', 'restart');
	
	$when_network_is_up->(sub {
	    run_program::rooted($::prefix, 'net', 'ads', 'join', '-U', $authentication->{winuser} . '%' . $authentication->{winpass});
	});
    }
}


sub pam_modules() {
    'pam_ldap', 'pam_castella', 'pam_winbind', 'pam_krb5', 'pam_mkhomedir';
}
sub pam_module_from_path { 
    $_[0] && $_[0] =~ m|(/lib/security/)?(pam_.*)\.so| && $2;
}
sub pam_module_to_path { 
    "$_[0].so";
}
sub pam_format_line {
    my ($type, $control, $module, @para) = @_;
    sprintf("%-11s %-13s %s\n", $type, $control, join(' ', pam_module_to_path($module), @para));
}

sub get_raw_pam_authentication() {
    my %before_deny;
    foreach (cat_("$::prefix/etc/pam.d/system-auth")) {
	my ($type, $control, $module, @para) = split;
	if ($module = pam_module_from_path($module)) {
	    $before_deny{$type}{$module} = \@para if $control eq 'sufficient' && member($module, pam_modules());
	}
    }
    \%before_deny;
}

sub set_pam_authentication {
    my (@authentication_kinds) = @_;
    
    my %special = (
	auth => \@authentication_kinds,
	account => [ difference2(\@authentication_kinds, [ 'castella' ]) ],
	password => [ intersection(\@authentication_kinds, [ 'ldap', 'krb5' ]) ],
    );
    my %before_first = (
	session => 
	  intersection(\@authentication_kinds, [ 'winbind', 'krb5', 'ldap' ]) 
	    ? pam_format_line('session', 'optional', 'pam_mkhomedir', 'skel=/etc/skel/', 'umask=0022') :
	  member('castella', @authentication_kinds)
	    ? pam_format_line('session', 'optional', 'pam_castella') : '',
    );
    my %after_deny = (
	session => member('krb5', @authentication_kinds) ? pam_format_line('session', 'optional', 'pam_krb5') : '',
    );

    substInFile {
	my ($type, $control, $module, @para) = split;
	if ($module = pam_module_from_path($module)) {
	    if (member($module, pam_modules())) {
		#- first removing previous config
		$_ = '';
	    }
	    if ($module eq 'pam_unix' && $special{$type}) {
		my @para_for_last = 
		    $type eq 'auth' ? qw(likeauth nullok use_first_pass) :
		    $type eq 'account' ? qw(use_first_pass) : @{[]};
		@para = difference2(\@para, \@para_for_last);

		my ($before_noask, $ask) = partition { $_ eq 'castella' } @{$special{$type}};
		my ($before, $after) = partition { $_ eq 'krb5' } @$ask;

		if (!@$ask) {
		    @para_for_last = grep { $_ ne 'use_first_pass' } @para_for_last;
		}

		my @l = ((map { [ "pam_$_" ] } @$before_noask, @$before),
			 [ 'pam_unix', @para ],
			 (map { [ "pam_$_" ] } @$after),
			 );
		push @{$l[-1]}, @para_for_last;
		$_ = join('', map { pam_format_line($type, 'sufficient', @$_) } @l);

		if ($control eq 'required') {
		    #- ensure a pam_deny line is there
		    ($control, $module, @para) = ('required', 'pam_deny');
		    $_ .= pam_format_line($type, $control, $module);
		}
	    }
	    if (my $s = delete $before_first{$type}) {
		$_ = $s . $_;
	    }
	    if ($control eq 'required' && member($module, 'pam_deny', 'pam_unix')) {
		if (my $s = delete $after_deny{$type}) {
		    $_ .= $s;
		}
	    }
	}
    } "$::prefix/etc/pam.d/system-auth";
}

sub get_pam_authentication_kinds() {
    my $before_deny = get_raw_pam_authentication();
    map { s/pam_//; $_ } keys %{$before_deny->{auth}};
}

sub set_nsswitch_priority {
    my (@kinds) = @_;
    my @known = qw(nis ldap winbind);
    substInFile {
	if (my ($database, $l) = /^(\s*(?:passwd|shadow|group|automount):\s*)(.*)/) {
	    my @l = difference2([ split(' ', $l) ], \@known);
	    $_ = $database . join(' ', uniq('files', @kinds, @l)) . "\n";
	}	
    } "$::prefix/etc/nsswitch.conf";
}

my $special_ldap_cmds = join('|', 'nss_map_attribute', 'nss_map_objectclass');
sub _after_read_ldap_line {
    my ($s) = @_;
    $s =~ s/\b($special_ldap_cmds)\s*/$1 . '_'/e;
    $s;
}
sub _pre_write_ldap_line {
    my ($s) = @_;
    $s =~ s/\b($special_ldap_cmds)_/$1 . ' '/e;
    $s;
}

sub read_ldap_conf() {
    my %conf = map { 
	s/^\s*#.*//; 
	if_(_after_read_ldap_line($_) =~ /(\S+)\s+(.*)/, $1 => $2);
    } cat_("$::prefix/etc/ldap.conf");
    \%conf;
}

sub update_ldap_conf {    
    my (%conf) = @_;

    substInFile {
	my ($cmd) = _after_read_ldap_line($_) =~ /^\s*#?\s*(\w+)\s/;
	if ($cmd && exists $conf{$cmd}) {
	    my $val = $conf{$cmd};
	    $conf{$cmd} = '';
	    $_ = $val ? _pre_write_ldap_line("$cmd $val\n") : /^\s*#/ ? $_ : "#$_";
        }
	if (eof) {
	    foreach my $cmd (keys %conf) {
		my $val = $conf{$cmd} or next;
		$_ .= _pre_write_ldap_line("$cmd $val\n");
	    }
	}
    } "$::prefix/etc/ldap.conf";
}

sub configure_krb5_for_AD {
    my ($authentication) = @_;

    my $uc_domain = uc $authentication->{AD_domain};
    my $krb5_conf_file = "$::prefix/etc/krb5.conf";

    krb5_conf_update($krb5_conf_file,
		     libdefaults => (
				     default_realm => $uc_domain,
				     dns_lookup_realm => $authentication->{AD_server} ? 'false' : 'true',
				     dns_lookup_kdc => $authentication->{AD_server} ? 'false' : 'true',
				    ));

    my @sections = (
		    realms => <<EOF,
 $uc_domain = {
  kdc = $authentication->{AD_server}:88
  admin_server = $authentication->{AD_server}:749
  default_domain = $authentication->{AD_domain}
 }
EOF
		    domain_realm => <<EOF,
 .$authentication->{AD_domain} = $uc_domain
EOF
		    kdc => <<'EOF',
 profile = /etc/kerberos/krb5kdc/kdc.conf
EOF
		    pam => <<'EOF',
 debug = false
 ticket_lifetime = 36000
 renew_lifetime = 36000
 forwardable = true
 krb4_convert = false
EOF
		    login => <<'EOF',
 krb4_convert = false
 krb4_get_tickets = false
EOF
		       );
    foreach (group_by2(@sections)) {
	my ($section, $txt) = @$_;
	krb5_conf_overwrite_category($krb5_conf_file, $section => $authentication->{AD_server} ? $txt : '');
    }
}

sub krb5_conf_overwrite_category {
    my ($file, $category, $new_val) = @_;

    my $done;
    substInFile {
	if (my $i = /^\s*\[\Q$category\E\]/i ... /^\[/) {
	    if ($new_val) {
		if ($i == 1) {
		    $_ .= $new_val;
		    $done = 1;
		} elsif ($i =~ /E/) {
		    $_ = "\n$_";
		} else {
		    $_ = '';
		}
	    } else {
		$_ = '' if $i !~ /E/;
	    }
	}
	#- if category has not been found above.
	if (eof && $new_val && !$done) {
	    $_ .= "\n[$category]\n$new_val";
	}
    } $file;
}

sub krb5_conf_update {
    my ($file, $category, %subst_) = @_;

    my %subst = map { lc($_) => [ $_, $subst_{$_} ] } keys %subst_;

    my $s;
    foreach (MDK::Common::File::cat_($file), "[NOCATEGORY]\n") {
	if (my $i = /^\s*\[\Q$category\E\]/i ... /^\[/) {
	    if ($i =~ /E/) { #- for last line of category
		chomp $s; $s .= "\n";
		$s .= " $_->[0] = $_->[1]\n" foreach values %subst;
		%subst = ();
	    } elsif (/^\s*([^=]*?)\s*=/) {
		if (my $e = delete $subst{lc($1)}) {
		    $_ = " $1 = $e->[1]\n";
		}
	      }
	}
	$s .= $_ if !/^\Q[NOCATEGORY]/;
    }

    #- if category has not been found above.
    if (keys %subst) {
	chomp $s;
	$s .= "\n[$category]\n";
	$s .= " $_->[0] = $_->[1]\n" foreach values %subst;
    }

    MDK::Common::File::output($file, $s);

}

sub sshd_config_UsePAM {
    my ($UsePAM) = @_;
    my $sshd = "$::prefix/etc/ssh/sshd_config";
    -e $sshd or return;

    my $val = "UsePAM " . bool2yesno($UsePAM);
    substInFile {
	$val = '' if s/^#?UsePAM.*/$val/;
	$_ .= "$val\n" if eof && $val;
    } $sshd;
}

sub query_srv_names {
    my ($domain) = @_;

    eval { require Net::DNS; 1 } or return;
    my $res = Net::DNS::Resolver->new;
    my $query = $res->query("_ldap._tcp.$domain", 'srv') or return;
    map { $_->target } $query->answer;
}

sub enable_shadow() {
    run_program::rooted($::prefix, "pwconv")  or log::l("pwconv failed");
    run_program::rooted($::prefix, "grpconv") or log::l("grpconv failed");
}

sub user_crypted_passwd {
    my ($u, $isMD5) = @_;
    if ($u->{password}) {
	crypt($u->{password}, $isMD5 ? '$1$' . salt(8) : salt(2));
    } else {
	$u->{pw} || '';
    }
}

sub set_root_passwd {
    my ($superuser, $authentication) = @_;
    $superuser->{name} = 'root';
    write_passwd_user($superuser, $authentication->{md5});    
    delete $superuser->{name};
}

sub write_passwd_user {
    my ($u, $isMD5) = @_;

    $u->{pw} = user_crypted_passwd($u, $isMD5);      
    $u->{shell} ||= '/bin/bash';

    substInFile {
	my $l = unpack_passwd($_);
	if ($l->{name} eq $u->{name}) {
	    add2hash_($u, $l);
	    $_ = pack_passwd($u);
	    $u = {};
	}
	if (eof && $u->{name}) {
	    $_ .= pack_passwd($u);
	}
    } "$::prefix/etc/passwd";
}

my @etc_pass_fields = qw(name pw uid gid realname home shell);
sub unpack_passwd {
    my ($l) = @_;
    my %l; @l{@etc_pass_fields} = split ':', chomp_($l);
    \%l;
}
sub pack_passwd {
    my ($l) = @_;
    join(':', @$l{@etc_pass_fields}) . "\n";
}

1;

hl kwb">$bootloader, { memsize => $1 }) if cat_("/proc/cmdline") =~ /\bmem=(\d+[KkMm]?)(?:\s.*)?$/; if (my ($s, $port, $speed) = cat_("/proc/cmdline") =~ /console=(ttyS(\d),(\d+)\S*)/) { log::l("serial console $s $port $speed"); set_append($bootloader, 'console' => $s); any::set_login_serial_console($port, $speed); } #- add a restore entry if installation is done from disk, in order to allow redoing it. if (my $hd_install_path = any::hdInstallPath()) { my ($cmdline, $vga); if ($::restore && -e "/tmp/image/boot/vmlinuz" && -e "/tmp/image/boot/all.rdz" && ($cmdline = cat_("/tmp/image/boot/grub/menu.lst") =~ m|kernel \S+/boot/vmlinuz (.*)$|m)) { #- cmdline should'n have any reference to vga=... $cmdline =~ s/vga=(\S+)//g and $vga = $1; log::l("copying kernel and stage1 install to $::prefix/boot/restore"); eval { mkdir "$::prefix/boot/restore"; cp_af("/tmp/image/boot/vmlinuz", "$::prefix/boot/restore/vmlinuz"); cp_af("/tmp/image/boot/all.rdz", "$::prefix/boot/restore/all.rdz") }; unless ($@) { log::l("adding a restore bootloader entry on $hd_install_path (remapped to $::prefix/boot/restore)"); add_entry($bootloader, { type => 'image', label => 'restore', kernel_or_dev => "/boot/restore/vmlinuz", initrd => "/boot/restore/all.rdz", append => "$cmdline recovery", #- the restore entry is a recovery entry if_($vga, vga => $vga), }); } } else { log::l("no restore bootloader need to be used on $hd_install_path"); } } my %labels = get_kernels_and_labels(); $labels{''} or die "no kernel installed"; while (my ($ext, $version) = each %labels) { my $entry = add_kernel($bootloader, $version, $ext, $root, { if_($options{vga_fb} && $ext eq '', vga => $options{vga_fb}), #- using framebuffer }); $entry->{append} .= " splash=silent" if $options{vga_fb} && $options{quiet}; if ($options{vga_fb} && $ext eq '') { add_kernel($bootloader, $version, $ext, $root, { label => 'linux-nonfb' }); } } #- remove existing libsafe, don't care if the previous one was modified by the user? @{$bootloader->{entries}} = grep { $_->{label} ne 'failsafe' } @{$bootloader->{entries}}; my $failsafe = add_kernel($bootloader, $labels{''}, '', $root, { label => 'failsafe' }); $failsafe->{append} =~ s/devfs=mount/devfs=nomount/; $failsafe->{append} .= " failsafe"; if (arch() =~ /sparc/) { #- search for SunOS, it could be a really better approach to take into account #- partition type for mounting point. my $sunos = 0; foreach (@$hds) { foreach (@{$_->{primary}{normal}}) { my $path = $_->{device} =~ m|^/| && $_->{device} !~ m|^/dev/| ? $_->{device} : dev2prompath($_->{device}); add_entry($bootloader, { type => 'other', kernel_or_dev => $path, label => "sunos" . ($sunos++ ? $sunos : ''), }) if $path && isSunOS($_) && type2name($_->{type}) =~ /root/i; } } } elsif (arch() =~ /ppc/) { #- if we identified a MacOS partition earlier - add it if (defined $partition_table::mac::macos_part) { add_entry($bootloader, { label => "macos", kernel_or_dev => $partition_table::mac::macos_part }); } } elsif (arch() !~ /ia64/) { #- search for dos (or windows) boot partition. Don't look in extended partitions! my %nbs; foreach (@$hds) { foreach (@{$_->{primary}{normal}}) { isFat_or_NTFS($_) or next; my $from_magic = { type => fsedit::typeOfPart($_->{device}) }; isFat_or_NTFS($from_magic) or next; my $label = 'windows'; add_entry($bootloader, { type => 'other', kernel_or_dev => "/dev/$_->{device}", label => $label . ($nbs{$label}++ ? $nbs{$label} : ''), $_->{device} =~ /[1-4]$/ ? ( table => "/dev/$_->{rootDevice}" ) : ( unsafe => 1 ), }) } } } foreach ('secure', 'enterprise', 'smp') { if (get_label("linux-$_", $bootloader)) { $bootloader->{default} ||= "linux-$_"; last; } } $bootloader->{default} ||= "linux"; $bootloader->{method} ||= first(method_choices($fstab, $bootloader)); } sub detect_bootloader() { chomp_(run_program::rooted_get_stdout($::prefix, 'detectloader')); } sub method_choices { my ($fstab, $bootloader) = @_; my %choices = ( if_(arch() =~ /sparc/, 'silo' => N("SILO"), ), if_(arch() !~ /sparc|ppc/ && !isLoopback(fsedit::get_root($fstab)), if_(!detect_devices::matching_desc('ProSavageDDR'), 'lilo-graphic' => N("LILO with graphical menu")), 'lilo-menu' => N("LILO with text menu"), ), if_(arch() !~ /sparc|ppc/ && !isRAID(fsedit::get_root($fstab)), 'grub' => N("Grub"), ), if_(arch() =~ /ppc/, 'yaboot' => N("Yaboot"), ), ); my $prefered; $prefered ||= 'grub' if $::isStandalone && detect_bootloader() =~ /GRUB/; $prefered ||= 'lilo-' . (member($bootloader->{install}, 'text', 'menu', 'graphic') ? $bootloader->{install} : 'graphic'); my $default = exists $choices{$prefered} ? $prefered : first(keys %choices); $default, \%choices; } sub suggest_floppy { my ($bootloader) = @_; my $floppy = detect_devices::floppy() or return; $floppy eq 'fd0' or log::l("suggest_floppy: not adding $floppy"), return; add_entry($bootloader, { type => 'other', kernel_or_dev => '/dev/fd0', label => 'floppy', unsafe => 1 }); } sub keytable { my ($f) = @_; $f or return; if ($f !~ /\.klt$/) { my $file = "/boot/$f.klt"; run_program::rooted($::prefix, "keytab-lilo.pl", ">", $file, $f) or return; $f = $file; } -r "$::prefix/$f" && $f; } sub has_profiles { my ($b) = @_; to_bool(get_label("office", $b)) } sub set_profiles { my ($b, $want_profiles) = @_; my $office = get_label("office", $b); if ($want_profiles xor $office) { my $e = get_label("linux", $b); if ($want_profiles) { push @{$b->{entries}}, { %$e, label => "office", append => "$e->{append} prof=Office" }; $e->{append} .= " prof=Home"; } else { # remove profiles $e->{append} =~ s/\s*prof=\w+//; @{$b->{entries}} = grep { $_ != $office } @{$b->{entries}}; } } } sub get_of_dev { my ($unix_dev) = @_; my $of_dev; run_program::rooted_or_die($::prefix, "/usr/sbin/ofpath", ">", \$of_dev, $unix_dev); chomp($of_dev); log::l("OF Device: $of_dev"); $of_dev; } sub install_yaboot { my ($bootloader, $_fstab, $_hds) = @_; $bootloader->{prompt} = $bootloader->{timeout}; if ($bootloader->{message}) { eval { output("$::prefix/boot/message", $bootloader->{message}) } or $bootloader->{message} = 0; } { local $\ = "\n"; my $f = "$::prefix/etc/yaboot.conf"; local *F; open F, ">$f" or die "cannot create yaboot config file: $f"; log::l("writing yaboot config to $f"); print F "#yaboot.conf - generated by DrakX"; print F "init-message=\"\\n$bootloader->{'init-message'}\\n\"" if $bootloader->{'init-message'}; if ($bootloader->{boot}) { print F "boot=$bootloader->{boot}"; my $of_dev = get_of_dev($bootloader->{boot}); print F "ofboot=$of_dev"; } else { die "no bootstrap partition defined." } $bootloader->{$_} and print F "$_=$bootloader->{$_}" foreach qw(delay timeout); print F "install=/usr/lib/yaboot/yaboot"; print F "magicboot=/usr/lib/yaboot/ofboot"; $bootloader->{$_} and print F $_ foreach qw(enablecdboot enableofboot); $bootloader->{$_} and print F "$_=$bootloader->{$_}" foreach qw(defaultos default); #- print F "nonvram"; my $boot = "/dev/" . $bootloader->{useboot} if $bootloader->{useboot}; foreach (@{$bootloader->{entries}}) { if ($_->{type} eq "image") { my $of_dev = ''; if ($boot !~ /$_->{root}/ && $boot) { $of_dev = get_of_dev($boot); print F "$_->{type}=$of_dev," . substr($_->{kernel_or_dev}, 5); } else { $of_dev = get_of_dev($_->{root}); print F "$_->{type}=$of_dev,$_->{kernel_or_dev}"; } print F "\tlabel=", make_label_lilo_compatible($_->{label}); print F "\troot=$_->{root}"; if ($boot !~ /$_->{root}/ && $boot) { print F "\tinitrd=$of_dev," . substr($_->{initrd}, 5) if $_->{initrd}; } else { print F "\tinitrd=$of_dev,$_->{initrd}" if $_->{initrd}; } #- xfs module on PPC requires larger initrd - say 6MB? print F "\tinitrd-size=6144" if $bootloader->{xfsroot}; print F "\tappend=\" $_->{append}\"" if $_->{append}; print F "\tread-write" if $_->{'read-write'}; print F "\tread-only" if !$_->{'read-write'}; } else { my $of_dev = get_of_dev($_->{kernel_or_dev}); print F "$_->{label}=$of_dev"; } } } log::l("Installing boot loader..."); my $f = "$::prefix/tmp/of_boot_dev"; my $of_dev = get_of_dev($bootloader->{boot}); output($f, "$of_dev\n"); $::testing and return; if (defined $install_steps_interactive::new_bootstrap) { run_program::run("hformat", $bootloader->{boot}) or die "hformat failed"; } my $error; run_program::rooted($::prefix, "/usr/sbin/ybin", "2>", \$error) or die "ybin failed: $error"; } sub install_silo { my ($silo, $fstab) = @_; my $boot = fsedit::get_root($fstab, 'boot')->{device}; my ($wd, $_num) = $boot =~ /^(.*\D)(\d*)$/; #- setup boot promvars for. require c; if ($boot =~ /^md/) { #- get all mbr devices according to /boot are listed, #- then join all zero based partition translated to prom with ';'. #- keep bootdev with the first of above. log::l("/boot is present on raid partition which is not currently supported for promvars"); } else { if (!$silo->{use_partition}) { foreach (@$fstab) { if (!$_->{start} && $_->{device} =~ /$wd/) { $boot = $_->{device}; log::l("found a zero based partition in $wd as $boot"); last; } } } $silo->{bootalias} = c::disk2PromPath($boot); $silo->{bootdev} = $silo->{bootalias}; log::l("preparing promvars for device=$boot"); } c::hasAliases() or log::l("clearing promvars alias as non supported"), $silo->{bootalias} = ''; if ($silo->{message}) { eval { output("$::prefix/boot/message", $silo->{message}) } or $silo->{message} = 0; } { local $\ = "\n"; my $f = "$::prefix/boot/silo.conf"; #- always write the silo.conf file in /boot ... symlinkf "../boot/silo.conf", "$::prefix/etc/silo.conf"; #- ... and make a symlink from /etc. local *F; open F, ">$f" or die "cannot create silo config file: $f"; log::l("writing silo config to $f"); $silo->{$_} and print F "$_=$silo->{$_}" foreach qw(partition root default append); $silo->{$_} and print F $_ foreach qw(restricted); print F "password=", $silo->{password} if $silo->{restricted} && $silo->{password}; #- also done by msec print F "timeout=", round(10 * $silo->{timeout}) if $silo->{timeout}; print F "message=$silo->{boot}/message" if $silo->{message}; foreach (@{$silo->{entries}}) { #-my ($v, $e) = each %{$silo->{entries}}) { my $type = "$_->{type}=$_->{kernel_or_dev}"; $type =~ s|/boot|$silo->{boot}|; print F $type; print F "\tlabel=$_->{label}"; if ($_->{type} eq "image") { my $initrd = $_->{initrd}; $initrd =~ s|/boot|$silo->{boot}|; print F "\tpartition=$_->{partition}" if $_->{partition}; print F "\troot=$_->{root}" if $_->{root}; print F "\tinitrd=$initrd" if $_->{initrd}; print F "\tappend=\"$1\"" if $_->{append} =~ /^\s*"?(.*?)"?\s*$/; print F "\tread-write" if $_->{'read-write'}; print F "\tread-only" if !$_->{'read-write'}; } } } log::l("Installing boot loader..."); if (!$::testing) { my $error; run_program::rooted($::prefix, "silo", \$error, if_($silo->{use_partition}, "-t")) or run_program::rooted($::prefix, "silo", "-p", "2", if_($silo->{use_partition}, "-t")) or die "silo failed: $error"; #- try writing in the prom. log::l("setting promvars alias=$silo->{bootalias} bootdev=$silo->{bootdev}"); require c; c::setPromVars($silo->{bootalias}, $silo->{bootdev}); } } sub make_label_lilo_compatible { my ($label) = @_; $label = substr($label, 0, 15); #- lilo doesn't handle more than 15 char long labels $label =~ s/ /_/g; #- lilo does not support blank character in image names, labels or aliases qq("$label"); } sub write_lilo_conf { my ($bootloader, $fstab, $hds) = @_; $bootloader->{prompt} = $bootloader->{timeout}; my $file2fullname = sub { my ($file) = @_; if (arch() =~ /ia64/) { (my $part, $file) = fsedit::file2part($fstab, $file); my %hds = map_index { $_ => "hd$::i" } map { $_->{device} } sort { isFat($b) <=> isFat($a) || $a->{device} cmp $b->{device} } fsedit::get_fstab(@$hds); $hds{$part->{device}} . ":" . $file; } else { $file } }; my %bios2dev = map_index { $::i => $_ } dev2bios($hds, $bootloader->{first_hd_device} || $bootloader->{boot}); my %dev2bios = reverse %bios2dev; if (is_empty_hash_ref($bootloader->{bios} ||= {})) { my $dev = $hds->[0]{device}; if ($dev2bios{$dev}) { log::l("Since we're booting on $bios2dev{0}, make it bios=0x80, whereas $dev is now " . (0x80 + $dev2bios{$dev})); $bootloader->{bios}{"/dev/$bios2dev{0}"} = '0x80'; $bootloader->{bios}{"/dev/$dev"} = sprintf("0x%x", 0x80 + $dev2bios{$dev}); } foreach (0 .. 3) { my ($letter) = $bios2dev{$_} =~ /hd([^ac])/; #- at least hda and hdc are handled correctly :-/ next if $bootloader->{bios}{"/dev/$bios2dev{$_}"} || !$letter; next if $_ > 0 #- always print if first disk is hdb, hdd, hde... && $bios2dev{$_ - 1} eq "hd" . chr(ord($letter) - 1); #- no need to help lilo with hdb (resp. hdd, hdf...) log::l("Helping lilo: $bios2dev{$_} must be " . (0x80 + $_)); $bootloader->{bios}{"/dev/$bios2dev{$_}"} = sprintf("0x%x", 0x80 + $_); } } { local $\ = "\n"; my $f = arch() =~ /ia64/ ? "$::prefix/boot/efi/elilo.conf" : "$::prefix/etc/lilo.conf"; local *F; open F, ">$f" or die "cannot create lilo config file: $f"; log::l("writing lilo config to $f"); chmod 0600, $f if $bootloader->{password}; #- normalize: RESTRICTED is only valid if PASSWORD is set delete $bootloader->{restricted} if !$bootloader->{password}; local $bootloader->{default} = make_label_lilo_compatible($bootloader->{default}); $bootloader->{$_} and print F "$_=$bootloader->{$_}" foreach qw(boot map install vga default keytable); $bootloader->{$_} and print F $_ foreach qw(linear geometric compact prompt nowarn restricted); print F "append=\"$bootloader->{append}\"" if $bootloader->{append}; print F "password=", $bootloader->{password} if $bootloader->{password}; #- also done by msec print F "timeout=", round(10 * $bootloader->{timeout}) if $bootloader->{timeout}; print F "serial=", $1 if get_append($bootloader, 'console') =~ /ttyS(.*)/; print F "message=/boot/message" if arch() !~ /ia64/; print F "menu-scheme=wb:bw:wb:bw" if arch() !~ /ia64/; print F "ignore-table" if any { $_->{unsafe} && $_->{table} } @{$bootloader->{entries}}; while (my ($dev, $bios) = each %{$bootloader->{bios}}) { print F "disk=$dev bios=$bios"; } foreach (@{$bootloader->{entries}}) { print F "$_->{type}=", $file2fullname->($_->{kernel_or_dev}); print F "\tlabel=", make_label_lilo_compatible($_->{label}); if ($_->{type} eq "image") { print F "\troot=$_->{root}" if $_->{root}; print F "\tinitrd=", $file2fullname->($_->{initrd}) if $_->{initrd}; print F "\tappend=\"$_->{append}\"" if $_->{append}; print F "\tvga=$_->{vga}" if $_->{vga}; print F "\tread-write" if $_->{'read-write'}; print F "\tread-only" if !$_->{'read-write'}; } else { print F "\ttable=$_->{table}" if $_->{table}; print F "\tunsafe" if $_->{unsafe} && !$_->{table}; if (my ($dev) = $_->{table} =~ m|/dev/(.*)|) { if ($dev2bios{$dev}) { #- boot off the nth drive, so reverse the BIOS maps my $nb = sprintf("0x%x", 0x80 + $dev2bios{$dev}); $_->{mapdrive} ||= { '0x80' => $nb, $nb => '0x80' }; } } while (my ($from, $to) = each %{$_->{mapdrive} || {}}) { print F "\tmap-drive=$from"; print F "\t to=$to"; } } } } } sub install_lilo { my ($bootloader, $fstab, $hds, $method) = @_; if (my ($install) = $method =~ /lilo-(text|menu)/) { $bootloader->{install} = $install; } else { delete $bootloader->{install}; } output("$::prefix/boot/message-text", $bootloader->{message}) if $bootloader->{message}; symlinkf "message-" . ($method ne 'lilo-graphic' ? 'text' : 'graphic'), "$::prefix/boot/message"; write_lilo_conf($bootloader, $fstab, $hds); if (!$::testing && arch() !~ /ia64/ && $bootloader->{method} =~ /lilo/) { log::l("Installing boot loader..."); my $error; run_program::rooted($::prefix, "lilo", "2>", \$error) or die "lilo failed: $error"; } } sub dev2bios { my ($hds, $where) = @_; $where =~ s|/dev/||; my @dev = map { $_->{device} } @$hds; member($where, @dev) or ($where) = @dev; #- if not on mbr, s/h(d[e-g])/x$1/ foreach $where, @dev; #- emulates ultra66 as xd_ my $start = substr($where, 0, 2); my $translate = sub { my ($dev) = @_; $dev eq $where ? "aaa" : #- if exact match, value it first $dev =~ /^$start(.*)/ ? "ad$1" : #- if same class (ide/scsi/ultra66), value it before other classes $dev; }; @dev = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, $translate->($_) ] } @dev; s/x(d.)/h$1/ foreach @dev; #- switch back; @dev; } sub dev2grub { my ($dev, $dev2bios) = @_; $dev =~ m|^(/dev/)?(...)(.*)$| or die "dev2grub (bad device $dev), caller is " . join(":", caller()); my $grub = $dev2bios->{$2} or die "dev2grub ($2)"; "($grub" . ($3 && "," . ($3 - 1)) . ")"; } sub grub2dev { my ($device, $o_block_device) = @_; my ($dev, $part) = ($1 . ")", $2) if $device =~ s/(\([^,]*?)(?:,(.*))?\)//; undef $part if $o_block_device; $part++ if defined $part; # grub wants "(hdX,Y)" where lilo just want "hdY+1" $dev =~ s/,[^)]*//; my $new_dev = +{ map { chomp; s/()//g; split(/\s+/, $_, 2) } cat_("$::prefix/boot/grub/device.map") }->{$dev} . $part; wantarray() ? ($device, $new_dev) : $new_dev; } # replace dummy "(hdX,Y)" in "(hdX,Y)/boot/vmlinuz..." by appropriate path if needed sub ungrubify { my ($device) = @_; my $dev; ($device, $dev) = grub2dev($device); my %mnt_pts = ("/dev/" . devices::from_devfs(readlink('/dev/root')) => "/", map { (split)[0..1] } cat_("/proc/mounts")); (my $v = join($mnt_pts{$dev} || $dev, $device)) =~ s!//!/!g; $v; } sub write_grub_config { my ($bootloader, $fstab, $hds) = @_; my %dev2bios = ( (map_index { $_ => "fd$::i" } detect_devices::floppies_dev()), (map_index { $_ => "hd$::i" } dev2bios($hds, $bootloader->{first_hd_device} || $bootloader->{boot})), ); { my %bios2dev = reverse %dev2bios; output "$::prefix/boot/grub/device.map", join '', map { "($_) /dev/$bios2dev{$_}\n" } sort keys %bios2dev; } my $bootIsReiser = isThisFs("reiserfs", fsedit::get_root($fstab, 'boot')); my $file2grub = sub { my ($part, $file) = fsedit::file2part($fstab, $_[0], 'keep_simple_symlinks'); dev2grub($part->{device}, \%dev2bios) . $file; }; { local $\ = "\n"; my $f = "$::prefix/boot/grub/menu.lst"; local *F; open F, ">$f" or die "cannot create grub config file: $f"; log::l("writing grub config to $f"); $bootloader->{$_} and print F "$_ $bootloader->{$_}" foreach qw(timeout); print F "color black/cyan yellow/cyan"; print F "i18n ", $file2grub->("/boot/grub/messages"); print F "keytable ", $file2grub->($bootloader->{keytable}) if $bootloader->{keytable}; print F "serial --unit=$1 --speed=$2\nterminal --timeout=" . ($bootloader->{timeout} || 0) . " console serial" if get_append($bootloader, 'console') =~ /ttyS(\d),(\d+)/; #- since we use notail in reiserfs, altconfigfile is broken :-( unless ($bootIsReiser) { print F "altconfigfile ", $file2grub->(my $once = "/boot/grub/menu.once"); output "$::prefix$once", " " x 100; } each_index { print F "default $::i" if $_->{label} eq $bootloader->{default}; } @{$bootloader->{entries}}; foreach (@{$bootloader->{entries}}) { print F "\ntitle $_->{label}"; if ($_->{type} eq "image") { my $vga = $_->{vga} || $bootloader->{vga}; printf F "kernel %s root=%s %s%s%s\n", $file2grub->($_->{kernel_or_dev}), $_->{root} =~ /loop7/ ? "707" : $_->{root}, #- special to workaround bug in kernel (see #ifdef CONFIG_BLK_DEV_LOOP) $_->{append}, $_->{'read-write'} && " rw", $vga && $vga ne "normal" && " vga=$vga"; print F "initrd ", $file2grub->($_->{initrd}) if $_->{initrd}; } else { print F "root ", dev2grub($_->{kernel_or_dev}, \%dev2bios); if (my ($dev) = $_->{table} =~ m|/dev/(.*)|) { if ($dev2bios{$dev} =~ /hd([1-9])/) { #- boot off the nth drive, so reverse the BIOS maps my $nb = sprintf("0x%x", 0x80 + $1); $_->{mapdrive} ||= { '0x80' => $nb, $nb => '0x80' }; } } if ($_->{mapdrive}) { map_each { print F "map ($::b) ($::a)" } %{$_->{mapdrive}}; print F "makeactive"; } print F "chainloader +1"; } } } my $dev = dev2grub($bootloader->{boot}, \%dev2bios); my ($s1, $s2, $m) = map { $file2grub->("/boot/grub/$_") } qw(stage1 stage2 menu.lst); my $f = "/boot/grub/install.sh"; output "$::prefix$f", "grub --device-map=/boot/grub/device.map --batch <<EOF install $s1 d $dev $s2 p $m quit EOF "; output "$::prefix/boot/grub/messages", map { substr(translate($_) . "\n", 0, 78) } ( #- ensure the translated messages are not too big the hard way #-PO: these messages will be displayed at boot time in the BIOS, use only ASCII (7bit) #-PO: and keep them smaller than 79 chars long N_("Welcome to GRUB the operating system chooser!"), #-PO: these messages will be displayed at boot time in the BIOS, use only ASCII (7bit) #-PO: and keep them smaller than 79 chars long N_("Use the %c and %c keys for selecting which entry is highlighted."), #-PO: these messages will be displayed at boot time in the BIOS, use only ASCII (7bit) #-PO: and keep them smaller than 79 chars long N_("Press enter to boot the selected OS, 'e' to edit the"), #-PO: these messages will be displayed at boot time in the BIOS, use only ASCII (7bit) #-PO: and keep them smaller than 79 chars long N_("commands before booting, or 'c' for a command-line."), #-PO: these messages will be displayed at boot time in the BIOS, use only ASCII (7bit) #-PO: and keep them smaller than 79 chars long N_("The highlighted entry will be booted automatically in %d seconds."), ); my $e = "$::prefix/boot/.enough_space"; output $e, 1; -s $e or die \N("not enough room in /boot"); unlink $e; $f; } sub install_grub { my ($bootloader, $fstab, $hds) = @_; my $f = write_grub_config($bootloader, $fstab, $hds); if (!$::testing) { log::l("Installing boot loader..."); symlink "$::prefix/boot", "/boot"; my $error; run_program::run("sh", $f, "2>", \$error) or die "grub failed: $error"; unlink "/boot"; } } sub lnx4win_file { my $bootloader = shift; map { local $_ = $_; s,/,\\,g; "$bootloader->{boot_drive}:\\lnx4win$_" } @_; } sub install { my ($bootloader, $fstab, $hds) = @_; if (my $p = find { $bootloader->{boot} eq "/dev/$_->{device}" } @$fstab) { die \N("You can't install the bootloader on a %s partition\n", partition_table::type2fs($p)) if isThisFs('xfs', $p); } $bootloader->{keytable} = keytable($bootloader->{keytable}); my @methods = $bootloader->{method} eq 'grub' ? ('lilo-graphic', 'grub') : $bootloader->{method}; my @rcs = map { my ($main_method) = /(\w+)/; my $f = $bootloader::{"install_$main_method"} or die "unknown bootloader method $_"; eval { $f->($bootloader, $fstab, $hds, $_) }; $@; } @methods; die $rcs[0] if every { $_ } @rcs; } 1;