summaryrefslogtreecommitdiffstats
path: root/perl-install/printer/detect.pm
blob: 065ac23e1a5b34af1b86640e1eca231e3ec1a3eb (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
package printer::detect;

use strict;
use common;
use modules;
use detect_devices;
use printer::data;

sub local_detect() {
    modules::any_conf->read->get_probeall("usb-interface") and eval { modules::load($usbprintermodule) };
    # Reload parallel port modules only when we were not called from the
    # hotplug script, to avoid the hotplug script running recursively
    if (!$::noX) {
	eval { modules::unload(qw(lp parport_pc parport)) }; #- on kernel 2.4 parport has to be unloaded to probe again
	eval { modules::load(qw(parport_pc lp)) }; #- take care as not available on 2.4 kernel (silent error).
    }
    whatPrinter();
}

sub net_detect { whatNetPrinter(1, 0, @_) }

sub net_smb_detect { whatNetPrinter(0, 1, @_) }

sub detect {
    local_detect(), whatNetPrinter(1, 1, @_);
}


#-CLASS:PRINTER;
#-MODEL:HP LaserJet 1100;
#-MANUFACTURER:Hewlett-Packard;
#-DESCRIPTION:HP LaserJet 1100 Printer;
#-COMMAND SET:MLC,PCL,PJL;
sub whatPrinter() {
    my @res = (whatParport(), whatUsbport());
    grep { $_->{val}{CLASS} eq "PRINTER" } @res;
}

sub whatParport() {
    my @res;
    foreach (0..3) {
	my $elem = {};
	my $F;
	open $F, "/proc/parport/$_/autoprobe" or open $F, "/proc/sys/dev/parport/parport$_/autoprobe" or next;
	{
	    local $_;
	    my $itemfound = 0;
	    while (<$F>) { 
		if (/(.*):(.*);/) { #-#
		    $elem->{$1} = $2;
		    $elem->{$1} =~ s/Hewlett[-\s_]Packard/HP/;
		    $elem->{$1} =~ s/HEWLETT[-\s_]PACKARD/HP/;
		    $itemfound = 1;
		}
	    }
	    # Some parallel printers miss the "CLASS" field
	    $elem->{CLASS} = 'PRINTER' 
		if $itemfound && !defined($elem->{CLASS});
	}
	push @res, { port => "/dev/lp$_", val => $elem };
    }
    @res;
}

sub whatPrinterPort() {
    grep { detect_devices::tryWrite($_) } qw(/dev/lp0 /dev/lp1 /dev/lp2 /dev/usb/lp0 /dev/usb/lp1 /dev/usb/lp2 /dev/usb/lp3 /dev/usb/lp4 /dev/usb/lp5 /dev/usb/lp6 /dev/usb/lp7 /dev/usb/lp8 /dev/usb/lp9);
}

sub whatUsbport() {
    # The printer manufacturer and model names obtained with the usb_probe()
    # function were very messy, once there was a lot of noise around the
    # manufacturers name ("Inc.", "SA", "International", ...) and second,
    # all Epson inkjets answered with the name "Epson Stylus Color 760" which
    # lead many newbies to install their Epson Stylus Photo XXX as an Epson
    # Stylus Color 760 ...
    #
    # This routine based on an ioctl request gives very clean and correct
    # manufacturer and model names, so that they are easily matched to the
    # printer entries in the Foomatic database
    my @res;
    foreach my $i (0..15) {
	my $port = "/dev/usb/lp$i";
	my $realport = devices::make($port);
	next if !$realport;
	next if ! -r $realport;
	foreach my $j (1..3) {
	    open(my $PORT, $realport) or next;
	    my $idstr = "";
	    # Calculation of IOCTL function 0x84005001 (to get device ID
	    # string):
	    # len = 1024
	    # IOCNR_GET_DEVICE_ID = 1
	    # LPIOC_GET_DEVICE_ID(len) =
	    #     _IOC(_IOC_READ, 'P', IOCNR_GET_DEVICE_ID, len)
	    # _IOC(), _IOC_READ as defined in /usr/include/asm/ioctl.h
	    # Use "eval" so that program does not stop when IOCTL fails
	    eval { 
		my $output = "\0" x 1024; 
		ioctl($PORT, 0x84005001, $output);
		$idstr = $output;
	    } or do {
		close $PORT;
		next;
	    };
	    close $PORT;
	    # Remove non-printable characters
	    $idstr =~ tr/[\x00-\x1f]/./;
	    # If we do not find any item in the ID string, we try to read
	    # it again
	    my $itemfound = 0;
	    # Extract the printer data from the ID string
	    my ($manufacturer, $model, $serialnumber, $description, $commandset) =
		    ("", "", "", "", "");
	    my ($sku);
	    if ($idstr =~ /CLS:([^;]+);/ || $idstr =~ /CLASS:([^;]+);/) {
		$itemfound = 1;
	    }
	    if ($idstr =~ /MFG:([^;]+);/ || $idstr =~ /MANUFACTURER:([^;]+);/) {
		$manufacturer = $1;
		$manufacturer =~ s/Hewlett[-\s_]Packard/HP/;
		$manufacturer =~ s/HEWLETT[-\s_]PACKARD/HP/;
		$itemfound = 1;
	    }
	    # For HP's multi-function devices the real model name is in the "SKU"
	    # field. So use this field with priority for $model when it exists.
	    if ($idstr =~ /MDL:([^;]+);/ || $idstr =~ /MODEL:([^;]+);/) {
		$model ||= $1;
		$itemfound = 1;
	    }
	    if ($idstr =~ /SKU:([^;]+);/) {
		$sku = $1;
		$itemfound = 1;
	    }
	    if ($idstr =~ /DES:([^;]+);/ || $idstr =~ /DESCRIPTION:([^;]+);/) {
		$description = $1;
		$description =~ s/Hewlett[-\s_]Packard/HP/;
		$description =~ s/HEWLETT[-\s_]PACKARD/HP/;
		$itemfound = 1;
	    }
	    if (($idstr =~ /SE*R*N:([^;]+);/) ||
		($idstr =~ /SN:([^;]+);/)) {
		$serialnumber = $1;
		$itemfound = 1;
	    }
	    if ($idstr =~ /CMD:([^;]+);/ || 
		$idstr =~ /COMMAND\s*SET:([^;]+);/) {
		$commandset ||= $1;
		$itemfound = 1;
	    }
	    # Nothing found? Try again if not in the third attempt,
	    # after the third attempt give up
	    next if !$itemfound;
	    # Was there a manufacturer and a model in the string?
	    if ($manufacturer eq "" || $model eq "") {
		$manufacturer = "";
		$model = N("Unknown Model");
	    }
	    # No description field? Make one out of manufacturer and model.
	    if ($description eq "") {
		$description = "$manufacturer $model";
	    }
	    # Store this auto-detection result in the data structure
	    push @res, { port => $port, val => 
			 { CLASS => 'PRINTER',
			   MODEL => $model,
			   MANUFACTURER => $manufacturer,
			   DESCRIPTION => $description,
			   SERIALNUMBER => $serialnumber,
			   'COMMAND SET' => $commandset,
			   SKU => $sku
			   } };
	    last;
	}
    }
    @res;
}

sub whatNetPrinter {
    my ($network, $smb, $timeout) = @_;

    my (@res);

    # Set timeouts for "nmap"
    $timeout = 4000 if !$timeout;
    my $irtimeout = $timeout / 2;

    # Which ports should be scanned?
    my @portstoscan;
    push @portstoscan, "139" if $smb;
    push @portstoscan, "4010", "4020", "4030", "5503", "9100-9104" if $network;
    
    return () if $#portstoscan < 0;
    my $portlist = join ",", @portstoscan;
    
    # Which hosts should be scanned?
    # (Applying nmap to a whole network is very time-consuming, because nmap
    #  waits for a certain timeout period on non-existing hosts, so we get a 
    #  lists of existing hosts by pinging the broadcast addresses for existing
    #  hosts and then scanning only them, which is much faster)
    my @hostips = getIPsInLocalNetworks();
    return () if $#hostips < 0;
    my $hostlist = join " ", @hostips;

    # Scan network for printers, the timeout settings are there to avoid
    # delays caused by machines blocking their ports with a firewall
    local *F;
    open F, ($::testing ? "" : "chroot $::prefix/ ") .
	qq(/bin/sh -c "export LC_ALL=C; nmap -r -P0 --host_timeout $timeout --initial_rtt_timeout $irtimeout -p $portlist $hostlist" 2> /dev/null |)
	or return @res;
    my ($host, $ip, $port, $modelinfo) = ("", "", "", "");
    while (my $line = <F>) {
	chomp $line;

	# head line of the report of a host with the ports in question open
	if (($line =~ m/^\s*Interesting\s+ports\s+on\s+(\S*)\s*\((\S+)\)\s*:\s*$/i) ||
	    ($line =~ m/^\s*Interesting\s+ports\s+on\s+(\S+)\s*:\s*$/i)) {
	    ($host, $ip) = ($1, $2);
	    $ip = $host if !$ip;
	    $host = $ip if $host eq "";
	    $port = "";

	    undef $modelinfo;

	} elsif ($line =~ m!^\s*(\d+)/\S+\s+open\s+!i) {
	    next if $ip eq "";
	    $port = $1;
	    
	    # Now we have all info for one printer
	    # Store this auto-detection result in the data structure

	    # Determine the protocol by the port number

	    # SMB/Windows
	    if ($port eq "139") {
		my @shares = getSMBPrinterShares($ip);
		foreach my $share (@shares) {
		    push @res, { port => "smb://$host/$share->{name}",
				 val => { CLASS => 'PRINTER',
					  MODEL => N("Unknown Model"),
					  MANUFACTURER => "",
					  DESCRIPTION => $share->{description},
					  SERIALNUMBER => ""
				      }
			     };
		}
	    } else {
		if (!defined($modelinfo)) {
		    # SNMP request to auto-detect model
		    $modelinfo = getSNMPModel($ip);
		}
		if (defined($modelinfo)) {
		    push @res, { port => "socket://$host:$port",
				 val => $modelinfo
				 };
		}
	    }
	}
    }
    close F;
    @res;
}

sub getNetworkInterfaces() {

    # subroutine determines the list of all network interfaces reported
    # by "ifconfig", except "lo".
    
    # Return an empty list if no network is running
    return () unless network_running();
    
    my @interfaces;
	
    local *IFCONFIG_OUT;
    open IFCONFIG_OUT, ($::testing ? "" : "chroot $::prefix/ ") .
	'/bin/sh -c "export LC_ALL=C; ifconfig" 2> /dev/null |' or return ();
    while (my $readline = <IFCONFIG_OUT>) {
	# New entry ...
	if ($readline =~ /^(\S+)\s/) {
	    my $dev = $1;
	    if ($dev ne "lo") {
		push @interfaces, $dev;
	    }
	}
    }
    close(IFCONFIG_OUT);

    @interfaces;
}

sub getIPsOfLocalMachine() {

    # subroutine determines all IPs which point to the local machine,
    # except 127.0.0.1 (localhost).

    # Return an empty list if no network is running
    return () unless network_running();
    
    # Read the output of "ifconfig" to determine the broadcast addresses of
    # the local networks
    my $dev_is_realnet = 0;
    my @local_ips;
    my $current_ip = "";
	
    local *IFCONFIG_OUT;
    open IFCONFIG_OUT, ($::testing ? "" : "chroot $::prefix/ ") .
	'/bin/sh -c "export LC_ALL=C; ifconfig" 2> /dev/null |' or return ();
    while (my $readline = <IFCONFIG_OUT>) {
	# New entry ...
	if ($readline =~ /^(\S+)\s/) {
	    my $dev = $1;
	    # ... for a real network (not lo = localhost)
	    $dev_is_realnet = $dev ne 'lo';
	    # delete previous address
	    $current_ip = "";
	}
	# Are we in the important line now?
	if ($readline =~ /\sinet addr:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\s/) {
	    # Rip out the IP address
	    $current_ip = $1;
	    
	    # Are we in an entry for a real network?
	    if ($dev_is_realnet) {
		# Store current IP address
		push @local_ips, $current_ip;
	    }
	}
    }
    close(IFCONFIG_OUT);
    @local_ips;
}

sub getIPsInLocalNetworks() {

    # subroutine determines the list of all hosts reachable in the local
    # networks by means of pinging the broadcast addresses.
    
    # Return an empty list if no network is running
    return () unless network_running();
    
    # Read the output of "ifconfig" to determine the broadcast addresses of
    # the local networks
    my $dev_is_localnet = 0;
    my @local_bcasts;
    my $current_bcast = "";
	
    local *IFCONFIG_OUT;
    open IFCONFIG_OUT, ($::testing ? "" : "chroot $::prefix/ ") .
	'/bin/sh -c "export LC_ALL=C; ifconfig" 2> /dev/null |' or return ();
    while (my $readline = <IFCONFIG_OUT>) {
	# New entry ...
	if ($readline =~ /^(\S+)\s/) {
	    my $dev = $1;
	    # ... for a local network (eth = ethernet, 
	    #     vmnet = VMWare,
	    #     ethernet card connected to ISP excluded)?
	    $dev_is_localnet = $dev =~ /^eth/ || $dev =~ /^vmnet/;
	    # delete previous address
	    $current_bcast = "";
	}
	# Are we in the important line now?
	if ($readline =~ /\sBcast:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\s/) {
	    # Rip out the broadcast IP address
	    $current_bcast = $1;
	    
	    # Are we in an entry for a local network?
	    if ($dev_is_localnet == 1) {
		# Store current IP address
		push @local_bcasts, $current_bcast;
	    }
	}
    }
    close(IFCONFIG_OUT);

    my @addresses;
    # Now ping all broadcast addresses and additionally "nmblookup" the
    # networks (to find Windows servers which do not answer to ping)
    foreach my $bcast (@local_bcasts) {
	local *F;
	open F, ($::testing ? "" : "chroot $::prefix/ ") . 
	    qq(/bin/sh -c "export LC_ALL=C; ping -w 1 -b -n $bcast 2> /dev/null | cut -f 4 -d ' ' | sed s/:// | egrep '^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+' | uniq | sort" |) 
	    or next;
	local $_;
	while (<F>) { chomp; push @addresses, $_ }
	close F;
	if (-x "/usr/bin/nmblookup") {
	    local *F;
	    open F, ($::testing ? "" : "chroot $::prefix/ ") . 
		qq(/bin/sh -c "export LC_ALL=C; nmblookup -B $bcast \\* 2> /dev/null | cut -f 1 -d ' ' | egrep '^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+' | uniq | sort" |)
		or next;
	    local $_;
	    while (<F>) { 
		chomp;
		push @addresses, $_ if !(member($_,@addresses));
	    }
	}
    }

    @addresses;
}

sub getSMBPrinterShares {
    my ($host) = @_;
    
    # SMB request to auto-detect shares
    local *F;
    open F, ($::testing ? "" : "chroot $::prefix/ ") .
	qq(/bin/sh -c "export LC_ALL=C; smbclient -N -L $host" 2> /dev/null |) or return ();
    my $insharelist = 0;
    my @shares;
    while (my $l = <F>) {
	chomp $l;
	if ($l =~ /^\s*Sharename\s+Type\s+Comment\s*$/i) {
	    $insharelist = 1;
	} elsif ($l =~ /^\s*Server\s+Comment\s*$/i) {
	    $insharelist = 0;
	} elsif ($l =~ /^\s*(\S+)\s+Printer\s*(.*)$/i &&
		 $insharelist) {
	    my $name = $1;
	    my $description = $2;
	    $description =~ s/^(\s*)//;
	    push @shares, { name => $name, description => $description };
	}
    }
    close F;

    return @shares;
}

sub getSNMPModel {
    my ($host) = @_;
    my $manufacturer = "";
    my $model = "";
    my $description = "";
    my $serialnumber = "";
    
    # SNMP request to auto-detect model
    local *F;
    open F, ($::testing ? $::prefix : "chroot $::prefix/ ") .
	qq(/bin/sh -c "scli -v 1 -c 'show printer info' $host" 2> /dev/null |) or
	return { CLASS => 'PRINTER',
		 MODEL => N("Unknown Model"),
		 MANUFACTURER => "",
		 DESCRIPTION => "",
		 SERIALNUMBER => ""
		 };
    while (my $l = <F>) {
	chomp $l;
	if ($l =~ /^\s*Manufacturer:\s*(\S.*)$/i &&
	    $l =~ /^\s*Vendor:\s*(\S.*)$/i) {
	    $manufacturer = $1;
	    $manufacturer =~ s/Hewlett[-\s_]Packard/HP/;
	    $manufacturer =~ s/HEWLETT[-\s_]PACKARD/HP/;
	} elsif ($l =~ /^\s*Model:\s*(\S.*)$/i) {
	    $model = $1;
	} elsif ($l =~ /^\s*Description:\s*(\S.*)$/i) {
	    $description = $1;
	    $description =~ s/Hewlett[-\s_]Packard/HP/;
	    $description =~ s/HEWLETT[-\s_]PACKARD/HP/;
	} elsif ($l =~ /^\s*Serial\s*Number:\s*(\S.*)$/i) {
	    $serialnumber = $1;
	}
    }
    close F;

    # Was there a manufacturer and a model in the output?
    # If not, get them from the description
    if ($manufacturer eq "" || $model eq "") {
	if ($description =~ /^\s*(\S*)\s+(\S.*)$/) {
	    $manufacturer = $1 if $manufacturer eq "";
	    $model = $2 if $model eq "";
	}
	# No description field? Make one out of manufacturer and model.
    } elsif ($description eq "") {
	$description = "$manufacturer $model";
    }
    
    # We couldn't determine a model
    $model = N("Unknown Model") if $model eq "";
    
    # Remove trailing spaces
    $manufacturer =~ s/(\S+)\s+$/$1/;
    $model        =~ s/(\S+)\s+$/$1/;
    $description  =~ s/(\S+)\s+$/$1/;
    $serialnumber =~ s/(\S+)\s+$/$1/;

    # Now we have all info for one printer
    # Store this auto-detection result in the data structure
    return  { CLASS => 'PRINTER',
	      MODEL => $model,
	      MANUFACTURER => $manufacturer,
	      DESCRIPTION => $description,
	      SERIALNUMBER => $serialnumber
	      };
}

sub network_running() {
    # If the network is not running return 0, otherwise 1.
    local *F; 
    open F, ($::testing ? $::prefix : "chroot $::prefix/ ") . 
	'/bin/sh -c "export LC_ALL=C; /sbin/ifconfig" 2> /dev/null |' or
	    die 'Could not run "ifconfig"!';
    while (my $line = <F>) {
	if ($line !~ /^lo\s+/ && # The loopback device can have been 
                                   # started by the spooler's startup script
	    $line =~ /^(\S+)\s+/) { # In this line starts an entry for a
	                              # running network
	    close F;
	    return 1;
	}
    }
    close F;
    return 0;
}

sub parport_addr {
    # auto-detect the parallel port addresses
    my ($device) = @_;
    $device =~ m!^/dev/lp(\d+)$! or
	$device =~ m!^/dev/printers/(\d+)$!;
    my $portnumber = $1;
    my $parport_addresses = 
	`cat /proc/sys/dev/parport/parport$portnumber/base-addr`;
    my $address_arg;
    if ($parport_addresses =~ /^\s*(\d+)\s+(\d+)\s*$/) {
	$address_arg = sprintf(" -base 0x%x -basehigh 0x%x", $1, $2);
    } elsif ($parport_addresses =~ /^\s*(\d+)\s*$/) {
	$address_arg = sprintf(" -base 0x%x", $1);
    } else {
	$address_arg = "";
    }
    return $address_arg;
}

1;
class="hl opt">->{prefix}) }) if $o->{isUpgrade}; $o->{timezone}{timezone} ||= timezone::bestTimezone(lang::lang2text($o->{lang})); my $utc = $::expert && !grep { isFat($_) || isNT($_) } @{$o->{fstab}}; my $ntp = timezone::ntp_server($o->{prefix}); add2hash_($o->{timezone}, { UTC => $utc, ntp => $ntp }); } sub setPackages { my ($o) = @_; require pkgs; if (!$o->{packages} || is_empty_hash_ref($o->{packages}{names})) { $o->{packages} = pkgs::psUsingHdlists($o->{prefix}, $o->{method}); pkgs::getDeps($o->{prefix}, $o->{packages}); pkgs::selectPackage($o->{packages}, pkgs::packageByName($o->{packages}, 'basesystem') || die("missing basesystem package"), 1); #- must be done after selecting base packages (to save memory) pkgs::getProvides($o->{packages}); #- must be done after getProvides pkgs::read_rpmsrate($o->{packages}, getFile("Mandrake/base/rpmsrate")); ($o->{compssUsers}, $o->{compssUsersSorted}) = pkgs::readCompssUsers($o->{meta_class}); #- preselect default_packages and compssUsersChoices. setDefaultPackages($o); } else { #- this has to be done to make sure necessary files for urpmi are #- present. pkgs::psUpdateHdlistsDeps($o->{prefix}, $o->{method}, $o->{packages}); } } sub setDefaultPackages { my ($o, $clean) = @_; if ($clean) { delete $o->{$_} foreach qw(default_packages compssUsersChoice); #- clean modified variables. } push @{$o->{default_packages}}, "nfs-utils-clients" if $o->{method} eq "nfs"; push @{$o->{default_packages}}, "numlock" if $o->{miscellaneous}{numlock}; push @{$o->{default_packages}}, "kernel22" if !$::oem && c::kernel_version() =~ /^\Q2.2/; push @{$o->{default_packages}}, "raidtools" if !is_empty_array_ref($o->{all_hds}{raids}); push @{$o->{default_packages}}, "lvm" if !is_empty_array_ref($o->{all_hds}{lvms}); push @{$o->{default_packages}}, "reiserfsprogs" if grep { isThisFs("reiserfs", $_) } @{$o->{fstab}}; push @{$o->{default_packages}}, "xfsprogs" if grep { isThisFs("xfs", $_) } @{$o->{fstab}}; push @{$o->{default_packages}}, "jfsprogs" if grep { isThisFs("jfs", $_) } @{$o->{fstab}}; push @{$o->{default_packages}}, "alsa", "alsa-utils" if modules::get_alias("sound-slot-0") =~ /^snd-card-/; #- if no cleaning needed, populate by default, clean is used for second or more call to this function. unless ($clean) { if ($::auto_install && ($o->{compssUsersChoice} || {})->{ALL}) { $o->{compssUsersChoice}{$_} = 1 foreach map { @{$o->{compssUsers}{$_}{flags}} } @{$o->{compssUsersSorted}}; } if (!$o->{compssUsersChoice} && !$o->{isUpgrade}) { #- by default, choose: if ($o->{meta_class} eq 'server') { $o->{compssUsersChoice}{$_} = 1 foreach 'X', 'MONITORING', 'NETWORKING_REMOTE_ACCESS_SERVER'; } else { $o->{compssUsersChoice}{$_} = 1 foreach 'GNOME', 'KDE', 'CONFIG', 'X'; $o->{lang} eq 'eu_ES' and $o->{compssUsersChoice}{KDE} = 0; $o->{compssUsersChoice}{$_} = 1 foreach map { @{$o->{compssUsers}{$_}{flags}} } 'Workstation|Office Workstation', 'Workstation|Internet station'; } } } $o->{compssUsersChoice}{uc($_)} = 1 foreach grep { modules::get_that_type($_) } ('tv', 'scanner', 'photo', 'sound'); $o->{compssUsersChoice}{uc($_)} = 1 foreach map { $_->{driver} =~ /Flag:(.*)/ } detect_devices::probeall(); $o->{compssUsersChoice}{SYSTEM} = 1; $o->{compssUsersChoice}{DOCS} = !$o->{excludedocs}; $o->{compssUsersChoice}{BURNER} = 1 if detect_devices::burners(); $o->{compssUsersChoice}{DVD} = 1 if detect_devices::dvdroms(); $o->{compssUsersChoice}{USB} = 1 if modules::get_alias("usb-interface"); $o->{compssUsersChoice}{PCMCIA} = 1 if detect_devices::hasPCMCIA(); $o->{compssUsersChoice}{HIGH_SECURITY} = 1 if $o->{security} > 3; $o->{compssUsersChoice}{BIGMEM} = 1 if !$::oem && (availableRamMB() > 800) && (arch() !~ /ia64/); $o->{compssUsersChoice}{SMP} = 1 if detect_devices::hasSMP(); $o->{compssUsersChoice}{'3D'} = 1 if detect_devices::matching_desc('Matrox.* G[245][05]0') || detect_devices::matching_desc('Rage X[CL]') || detect_devices::matching_desc('3D Rage (?:LT|Pro)') || detect_devices::matching_desc('Voodoo [35]') || detect_devices::matching_desc('Voodoo Banshee') || detect_devices::matching_desc('8281[05].* CGC') || detect_devices::matching_desc('Rage 128') || detect_devices::matching_desc('Radeon ') && !detect_devices::matching_desc('Radeon 8500') || detect_devices::matching_desc('[nN]Vidia.*T[nN]T2') || #- TNT2 cards detect_devices::matching_desc('[nN]Vidia.*NV[56]') || detect_devices::matching_desc('[nN]Vidia.*Vanta') || detect_devices::matching_desc('[nN]Vidia.*GeForce') || #- GeForce cards detect_devices::matching_desc('[nN]Vidia.*NV1[15]') || detect_devices::matching_desc('[nN]Vidia.*Quadro'); foreach (map { substr($_, 0, 2) } lang::langs($o->{langs})) { pkgs::packageByName($o->{packages}, "locales-$_") or next; push @{$o->{default_packages}}, "locales-$_"; $o->{compssUsersChoice}{qq(LOCALES"$_")} = 1; #- mainly for zh in case of zh_TW.Big5 } foreach (lang::langsLANGUAGE($o->{langs})) { $o->{compssUsersChoice}{qq(LOCALES"$_")} = 1; } $o->{compssUsersChoice}{'CHARSET"' . lang::lang2charset($o->{lang}) . '"'} = 1; } sub unselectMostPackages { my ($o) = @_; pkgs::unselectAllPackages($o->{packages}); pkgs::selectPackage($o->{packages}, pkgs::packageByName($o->{packages}, $_) || next) foreach @{$o->{default_packages}}; } sub warnAboutNaughtyServers { my ($o) = @_; my @naughtyServers = pkgs::naughtyServers($o->{packages}) or return 1; if (!$o->ask_yesorno('', formatAlaTeX(_("You have selected the following server(s): %s These servers are activated by default. They don't have any known security issues, but some new could be found. In that case, you must make sure to upgrade as soon as possible. Do you really want to install these servers? ", join(", ", @naughtyServers))), 1)) { pkgs::unselectPackage($o->{packages}, pkgs::packageByName($o->{packages}, $_)) foreach @naughtyServers; } } sub addToBeDone(&$) { my ($f, $step) = @_; return &$f() if $::o->{steps}{$step}{done}; push @{$::o->{steps}{$step}{toBeDone}}, $f; } sub setAuthentication { my ($o) = @_; my ($shadow, $md5, $ldap, $nis) = @{$o->{authentication} || {}}{qw(shadow md5 LDAP NIS)}; my $p = $o->{prefix}; #- obsoleted always enabled (in /etc/pam.d/system-auth furthermore) #any::enableMD5Shadow($p, $shadow, $md5); any::enableShadow($p) if $shadow; if ($ldap) { $o->pkg_install(qw(chkauth openldap-clients nss_ldap pam_ldap)); run_program::rooted($o->{prefix}, "/usr/sbin/chkauth", "ldap", "-D", $o->{netc}{LDAPDOMAIN}, "-s", $ldap); } elsif ($nis) { #$o->pkg_install(qw(chkauth ypbind yp-tools net-tools)); #run_program::rooted($o->{prefix}, "/usr/sbin/chkauth", "yp", $domain, "-s", $nis); $o->pkg_install("ypbind"); my $domain = $o->{netc}{NISDOMAIN}; $domain || $nis ne "broadcast" or die _("Can't use broadcast with no NIS domain"); my $t = $domain ? "domain $domain" . ($nis ne "broadcast" && " server") : "ypserver"; substInFile { $_ = "#~$_" unless /^#/; $_ .= "$t $nis\n" if eof; } "$p/etc/yp.conf"; require network; network::write_conf("$p/etc/sysconfig/network", $o->{netc}); } } sub killCardServices { my $pid = chomp_(cat_("/tmp/cardmgr.pid")); $pid and kill(15, $pid); #- send SIGTERM } sub unlockCdrom(;$) { my ($cdrom) = @_; $cdrom or cat_("/proc/mounts") =~ m,(/(?:dev|tmp)/\S+)\s+(?:/mnt/cdrom|/tmp/image), and $cdrom = $1; eval { $cdrom and ioctl detect_devices::tryOpen($1), c::CDROM_LOCKDOOR(), 0 }; } sub ejectCdrom(;$) { my ($cdrom) = @_; getFile("XXX"); #- close still opened filehandle $cdrom ||= $1 if cat_("/proc/mounts") =~ m,(/(?:dev|tmp)/\S+)\s+(?:/mnt/cdrom|/tmp/image),; if ($cdrom) { #- umount BEFORE opening the cdrom device otherwise the umount will #- D state if the cdrom is already removed eval { fs::umount("/tmp/image") }; if ($@) { log::l("files still open: ", readlink($_)) foreach map { glob_("$_/fd/*") } glob_("/proc/*") } eval { ioctl detect_devices::tryOpen($cdrom), c::CDROMEJECT(), 1 }; } } sub setupFB { my ($o, $vga) = @_; $vga ||= 785; #- assume at least 640x480x16. require bootloader; #- update bootloader entries with vga, all kernel are now framebuffer. foreach (qw(vmlinuz vmlinuz-secure vmlinuz-smp vmlinuz-hack)) { if (my $e = bootloader::get("/boot/$_", $o->{bootloader})) { $e->{vga} = $vga; } } bootloader::install($o->{prefix}, $o->{bootloader}, $o->{fstab}, $o->{all_hds}{hds}); 1; } sub hdInstallPath() { my $tail = first(readlink("/tmp/image") =~ m|^/tmp/hdimage/(.*)|); my $head = first(readlink("/tmp/hdimage") =~ m|$::o->{prefix}(.*)|); $tail && ($head ? "$head/$tail" : "/mnt/hd/$tail"); } sub install_urpmi { my ($prefix, $method, $mediums) = @_; #- rare case where urpmi cannot be installed (no hd install path). $method eq 'disk' && !hdInstallPath() and return; my @cfg = map { my $name = $_->{fakemedium}; local *LIST; my $mask = umask 077; open LIST, ">$prefix/var/lib/urpmi/list.$name" or log::l("failed to write list.$name"); umask $mask; my $dir = ($_->{prefix} || ${{ nfs => "file://mnt/nfs", disk => "file:/" . hdInstallPath(), ftp => $ENV{URLPREFIX}, http => $ENV{URLPREFIX}, cdrom => "removable://mnt/cdrom" }}{$method}) . "/$_->{rpmsdir}"; local *FILES; open FILES, "$ENV{LD_LOADER} parsehdlist /tmp/$_->{hdlist} |"; print LIST "$dir/$_\n" foreach chomp_(<FILES>); close FILES or log::l("parsehdlist failed"), return; close LIST; #- build synthesis file if there are still not existing (ie not copied from mirror). if (-s "$prefix/var/lib/urpmi/synthesis.hdlist.$name.cz" <= 32) { unlink "$prefix/var/lib/urpmi/synthesis.hdlist.$name.cz"; run_program::rooted($prefix, "parsehdlist", ">", "/var/lib/urpmi/synthesis.hdlist.$name", "--synthesis", "/var/lib/urpmi/hdlist.$name.cz"); run_program::rooted($prefix, "gzip", "-S", ".cz", "/var/lib/urpmi/synthesis.hdlist.$name"); } my ($qname, $qdir) = ($name, $dir); $qname =~ s/(\s)/\\$1/g; $qdir =~ s/(\s)/\\$1/g; #- output new urpmi.cfg format here. "$qname " . ($dir !~ /^(ftp|http)/ && $qdir) . " { hdlist: hdlist.$name.cz with_hdlist: ../base/" . ($_->{update} ? "hdlist.cz" : $_->{hdlist}) . " list: list.$name" . ($dir =~ /removable:/ && " removable: /dev/cdrom") . ($_->{update} && " update") . " } "; } sort { $a->{medium} <=> $b->{medium} } values %$mediums; eval { output "$prefix/etc/urpmi/urpmi.cfg", @cfg }; } #-############################################################################### #- kde stuff #-############################################################################### sub kderc_largedisplay { my ($prefix) = @_; update_gnomekderc($_, 'KDE', Contrast => 7, kfmIconStyle => "Large", kpanelIconStyle => "Normal", #- to change to Large when icons looks better KDEIconStyle => "Large") foreach list_skels($prefix, '.kderc'); substInFile { s/^(GridWidth)=85/$1=100/; s/^(GridHeight)=70/$1=75/; } $_ foreach list_skels($prefix, '.kde/share/config/kfmrc'); } sub kdeicons_postinstall { my ($prefix) = @_; #- parse etc/fstab file to search for dos/win, floppy, zip, cdroms icons. #- handle both supermount and fsdev usage. my %l = ( 'cdrom' => [ 'cdrom', 'Cd-Rom' ], 'zip' => [ 'zip', 'Zip' ], 'floppy-ls' => [ 'floppy', 'LS-120' ], 'floppy' => [ 'floppy', 'Floppy' ], ); foreach (fs::read_fstab($prefix, "/etc/fstab")) { my ($name_, $nb) = $_->{mntpoint} =~ m|.*/(\S+?)(\d*)$/|; my ($name, $text) = @{$l{$name_} || []}; my $f = ${{ supermount => sub { $name .= '.fsdev' if $name }, vfat => sub { $name = 'Dos_'; $text = $name_ }, }}{$_->{type}}; &$f if $f; template2userfile($prefix, "$ENV{SHARE_PATH}/$name.kdelnk.in", "Desktop/$text" . ($nb && " $nb"). ".kdelnk", 1, %$_) if $name; } # rename the .kdelnk to the name found in the .kdelnk as kde doesn't use it # for displaying foreach my $dir (grep { -d $_ } list_skels($prefix, 'Desktop')) { foreach (grep { /\.kdelnk$/ } all($dir)) { cat_("$dir/$_") =~ /^Name\[\Q$ENV{LANG}\E\]=(.{2,14})$/m and rename "$dir/$_", "$dir/$1.kdelnk"; } } } sub kdemove_desktop_file { my ($prefix) = @_; my @toMove = qw(doc.kdelnk news.kdelnk updates.kdelnk home.kdelnk printer.kdelnk floppy.kdelnk cdrom.kdelnk FLOPPY.kdelnk CDROM.kdelnk); #- remove any existing save in Trash of each user and #- move appropriate file there after an upgrade. foreach my $dir (grep { -d $_ } list_skels($prefix, 'Desktop')) { renamef("$dir/$_", "$dir/Trash/$_") foreach grep { -e "$dir/$_" } @toMove, grep { /\.rpmorig$/ } all($dir) } } #-############################################################################### #- auto_install stuff #-############################################################################### sub auto_inst_file() { ($::g_auto_install ? "/tmp" : "$::o->{prefix}/root/drakx") . "/auto_inst.cfg.pl" } sub report_bug { my ($prefix) = @_; any::report_bug($prefix, 'auto_inst' => g_auto_install('', 1)); } sub g_auto_install { my ($replay, $respect_privacy) = @_; my $o = {}; require pkgs; $o->{default_packages} = pkgs::selected_leaves($::o->{packages}); my @fields = qw(mntpoint type size); $o->{partitions} = [ map { my %l; @l{@fields} = @$_{@fields}; \%l } grep { $_->{mntpoint} } @{$::o->{fstab}} ]; exists $::o->{$_} and $o->{$_} = $::o->{$_} foreach qw(lang authentication mouse wacom netc timezone superuser intf keyboard users partitioning isUpgrade manualFstab nomouseprobe crypto security netcnx useSupermount autoExitInstall mkbootdisk); #- TODO modules bootloader if (my $printer = $::o->{printer}) { $o->{printer}{$_} = $::o->{printer}{$_} foreach qw(SPOOLER DEFAULT BROWSEPOLLADDR BROWSEPOLLPORT MANUALCUPSCONFIG); $o->{printer}{configured} = {}; foreach my $queue (keys %{$::o->{printer}{configured}}) { my $val = $::o->{printer}{configured}{$queue}{queuedata}; exists $val->{$_} and $o->{printer}{configured}{$queue}{queuedata}{$_} = $val->{$_} foreach keys %{$val || {}}; } } if (my $card = $::o->{X}{card}) { $o->{X}{$_} = $::o->{X}{$_} foreach qw(default_depth resolution_wanted); if ($o->{X}{default_depth} and my $depth = $card->{depth}{$o->{X}{default_depth}}) { $depth ||= []; $o->{X}{resolution_wanted} ||= join "x", @{$depth->[0]} unless is_empty_array_ref($depth->[0]); $o->{X}{monitor} = $::o->{X}{monitor} if $::o->{X}{monitor}{manual}; } } local $o->{partitioning}{auto_allocate} = !$replay; $o->{autoExitInstall} = !$replay; $o->{interactiveSteps} = [ 'doPartitionDisks', 'formatPartitions'] if $replay; #- deep copy because we're modifying it below $o->{users} = [ @{$o->{users} || []} ]; my @user_info_to_remove = ( if_($respect_privacy, qw(name realname home pw)), qw(oldu oldg password password2), ); $_ = { %{$_ || {}} }, delete @$_{@user_info_to_remove} foreach $o->{superuser}, @{$o->{users} || []}; if ($respect_privacy && $o->{netcnx}) { if (my $type = $o->{netcnx}{type}) { my @netcnx_type_to_remove = qw(passwd passwd2 login phone_in phone_out); $_ = { %{$_ || {}} }, delete @$_{@netcnx_type_to_remove} foreach $o->{netcnx}{$type}; } } require Data::Dumper; my $str = join('', "#!/usr/bin/perl -cw # # You should check the syntax of this file before using it in an auto-install. # You can do this with 'perl -cw auto_inst.cfg.pl' or by executing this file # (note the '#!/usr/bin/perl -cw' on the first line). ", Data::Dumper->Dump([$o], ['$o']), "\0"); $str =~ s/ {8}/\t/g; #- replace all 8 space char by only one tabulation, this reduces file size so much :-) $str; } sub getAndSaveInstallFloppy { my ($o, $where) = @_; if ($postinstall_rpms && -d $postinstall_rpms && -r "$postinstall_rpms/auto_install.img") { log::l("getAndSaveInstallFloppy: using file saved as $postinstall_rpms/auto_install.img"); cp_af("$postinstall_rpms/auto_install.img", $where); } else { my $image = cat_("/proc/cmdline") =~ /pcmcia/ ? "pcmcia" : ${{ disk => 'hd', cdrom => 'cdrom', ftp => 'network', nfs => 'network', http => 'network' }}{$o->{method}}; $image .= arch() =~ /sparc64/ && "64"; #- for sparc64 there are a specific set of image. getAndSaveFile("images/$image.img", $where) or log::l("failed to write Install Floppy ($image.img) to $where"), return; } 1; } sub getAndSaveAutoInstallFloppy { my ($o, $replay, $where) = @_; eval { modules::load('loop') }; if (arch() =~ /sparc/) { my $imagefile = "$o->{prefix}/tmp/autoinst.img"; my $mountdir = "$o->{prefix}/tmp/mount"; -d $mountdir or mkdir $mountdir, 0755; my $workdir = "$o->{prefix}/tmp/work"; -d $workdir or rmdir $workdir; getAndSaveInstallFloppy($o, $imagefile) or return; devices::make($_) foreach qw(/dev/loop6 /dev/ram); run_program::run("losetup", "/dev/loop6", $imagefile); fs::mount("/dev/loop6", $mountdir, "romfs", 'readonly'); cp_af($mountdir, $workdir); fs::umount($mountdir); run_program::run("losetup", "-d", "/dev/loop6"); substInFile { s/timeout.*//; s/^(\s*append\s*=\s*\".*)\"/$1 kickstart=floppy\"/ } "$workdir/silo.conf"; #" for po #-TODO output "$workdir/ks.cfg", generate_ks_cfg($o); output "$workdir/boot.msg", "\n7m", "!! If you press enter, an auto-install is going to start. ALL data on this computer is going to be lost, including any Windows partitions !! ", "7m\n"; local $o->{partitioning}{clearall} = 1;