aboutsummaryrefslogtreecommitdiffstats
path: root/edit-urpm-sources.pl
blob: 7aa45f55b16a60cd3740d716d5eb16367e3791cf (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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
#!/usr/bin/perl
#*****************************************************************************
# 
#  Copyright (c) 2002 Guillaume Cottenceau (gc at mandrakesoft dot com)
# 
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2, as
#  published by the Free Software Foundation.
# 
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
# 
#  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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# 
#*****************************************************************************
#
# $Id$


use strict;
use lib qw(/usr/lib/libDrakX);
use common;
use rpmdrake;
use URPM::Signature;

BEGIN {
    eval { require ugtk2; ugtk2->import(qw(:all)) };
    if ($@) {
	print "This program cannot be run in console mode.\n";
	c::_exit(0);  #- skip ugtk2::END
    }
}

$::isStandalone = 1;

require_root_capability();

my $urpm;
my ($mainw, $remove, $edit, $list_tv);

sub selrow {
    my ($o_list_tv) = @_;
    defined $o_list_tv or $o_list_tv = $list_tv;
    my ($model, $iter) = $o_list_tv->get_selection->get_selected;
    $model && $iter or return -1;
    my $path = $model->get_path($iter);
    my $row = $path->to_string;
    return $row;
}

sub remove_row {
    my ($model, $path_str) = @_;
    my $iter = $model->get_iter_from_string($path_str);
    $iter or return;
    $model->remove($iter);
}

sub add_callback {
    my $w = ugtk2->new(N("Add a medium"), grab => 1, center => 1, transient => $mainw->{rwindow});
    my %radios_infos = (local => { name => N("Local files"), url => N("Path:"), dirsel => 1 },
			ftp => { name => N("FTP server"), url => N("URL:"), loginpass => 1 },
			http => { name => N("HTTP server"), url => N("URL:") },
			removable => { name => N("Removable device"), url => N("Path or mount point:"), dirsel => 1 },
			security => { name => N("Security updates"), url => N("URL:"), securitysel => 1 },
		       );
    my @radios_names_ordered = qw(local ftp http removable security);
    my @modes_buttons = gtkradio($radios_infos{local}{name}, map { $radios_infos{$_}{name} } @radios_names_ordered);
    my $notebook = Gtk2::Notebook->new;
    $notebook->set_show_tabs(0); $notebook->set_show_border(0);
    my $count_nbs;
    mapn {
	my $info = $radios_infos{$_[0]};
	my $url_entry = sub {
	    gtkpack_(Gtk2::HBox->new(0, 0),
		     1, $info->{url_entry} = gtkentry(),
		     if_($info->{dirsel}, 0, gtksignal_connect(Gtk2::Button->new(but(N("Browse..."))),
							       clicked => sub { $info->{url_entry}->set_text(ask_dir()) })),
		     if_($info->{securitysel}, 0, gtksignal_connect(Gtk2::Button->new(but(N("Choose a mirror..."))),
								    clicked => sub { my $m = choose_mirror(transient => $w->{rwindow});
										     if ($m) {
											 $info->{url_entry}->set_text(make_url_mirror($m));
											 $info->{hdlist_entry}->set_text('../base/synthesis.hdlist.cz');
                                                                                         $info->{hdlist_entry}->set_sensitive(1);
                                                                                         $info->{hdlist_check}->set_active(1);
										     }
										 })));
	};
        my $tips = Gtk2::Tooltips->new;
        my $checkbut_entry = sub {
            my ($name, $label, $visibility, $callback, $tip) = @_;
            [ gtkpack_(Gtk2::HBox->new(0, 0),
                       1, Gtk2::Label->new,
                       0, gtksignal_connect($info->{$name.'_check'} = gtkset_tip($tips, Gtk2::CheckButton->new($label), $tip),
                                            clicked => sub { $info->{$name.'_entry'}->set_sensitive($_[0]->get_active);
                                                             $callback and $callback->(@_);
                                                         })),
              gtkset_visibility(gtkset_sensitive($info->{$name.'_entry'} = gtkentry(), 0), $visibility) ];
        };
	my $loginpass_entries = sub {
	    map { 
                  $checkbut_entry->(@$_, sub {
                                        $info->{pass_check}->set_active($_[0]->get_active);
                                        $info->{login_check}->set_active($_[0]->get_active);
                                    })
              } ([ 'login', N("Login:"), 1 ], [ 'pass', N("Password:"), 0 ])
	};
	my $nb = $count_nbs++;
	gtksignal_connect($_[1], 'clicked' => sub { $_[0]->get_active and $notebook->set_current_page($nb) });
	$notebook->append_page(my $book = create_packtable({},
		      [ gtkset_alignment(Gtk2::Label->new(N("Name:")), 1, 0.5),
                        $info->{name_entry} = gtkentry($_[0] eq 'security' and 'update_source') ],
		      [ gtkset_alignment(Gtk2::Label->new($info->{url}), 1, 0.5),
                        $url_entry->() ],
		      $checkbut_entry->('hdlist', N("Relative path to synthesis/hdlist:"), 1, undef,
                                        N("If left blank, synthesis/hdlist will be automatically probed")),
		      if_($info->{loginpass}, $loginpass_entries->())));
	$book->show;
    } \@radios_names_ordered, \@modes_buttons;

    my $checkok = sub {
	my $info = $radios_infos{$radios_names_ordered[$notebook->get_current_page]};
	my ($name, $url) = map { $info->{$_.'_entry'}->get_text } qw(name url);
	$name eq '' || $url eq '' and interactive_msg('rpmdrake', N("You need to fill up at least the two first entries.")), return 0;
	if (member($name, map { $_->{name} } @{$urpm->{media}})) {
	    $info->{name_entry}->select_region(0, -1);
	    interactive_msg('rpmdrake', 
N("There is already a medium by that name, do you
really want to replace it?"), yesno => 1) or return 0;
	}
	1;
    };

    my ($type, $probe, %i, %make_url);
    gtkadd($w->{window},
	   gtkpack(Gtk2::VBox->new(0,5),
		   Gtk2::Label->new(N("Adding a medium:")),
		   gtkpack__(Gtk2::HBox->new(0, 0), Gtk2::Label->new(but(N("Type of medium:"))), @modes_buttons),
		   $notebook,
		   Gtk2::HSeparator->new,
		   gtkpack(create_hbox(),
			   gtksignal_connect(Gtk2::Button->new(N("Ok")), clicked => sub {
						 if ($checkok->()) {
	$w->{retval} = { nb => $notebook->get_current_page };
	$type = $radios_names_ordered[$w->{retval}{nb}];
	my $info = $radios_infos{$type};
	%i = (name => $info->{name_entry}->get_text, url => $info->{url_entry}->get_text, hdlist => $info->{hdlist_entry}->get_text);
	%make_url = (local => "file:/$i{url}", http => $i{url}, security => $i{url}, removable => "removable:/$i{url}");
	$i{url} =~ s|^ftp://||;
	$make_url{ftp} = sprintf "ftp://%s%s", $info->{login_check}->get_active
	                                           ? ($info->{login_entry}->get_text.':'.$info->{pass_entry}->get_text.'@')
						   : '',
					       $i{url};
        $probe = $info->{hdlist_check}->get_active == 0 || $i{hdlist} eq '';
	Gtk2->main_quit;
    }
					     }),
			   gtksignal_connect(Gtk2::Button->new(N("Cancel")), clicked => sub { $w->{retval} = 0; Gtk2->main_quit }))));
    if ($w->main) {
	if (member($i{name}, map { $_->{name} } @{$urpm->{media}})) {
	    standalone::explanations("Removing medium $i{name}");
	    $urpm->select_media($i{name});
	    $urpm->remove_selected_media;
	}
	add_medium_and_check($urpm,
			     { probe_with => $probe, nolock => 1 },
			     $i{name}, $make_url{$type}, $i{hdlist}, update => $type eq 'security');
	return 1;
    }
    return 0;
}

sub remove_callback {
    my $row = selrow();
    $row == -1 and return;
    my $wait = wait_msg(N("Please wait, removing medium..."));
    my $name = $urpm->{media}[$row]{name};
    standalone::explanations("Removing medium $name");
    $urpm->select_media($name);
    $urpm->remove_selected_media;
    $urpm->update_media(noclean => 1, nolock => 1);
    remove_wait_msg($wait);
}

sub edit_callback {
    my $row = selrow();
    $row == -1 and return;
    my $medium = $urpm->{media}[$row];
    my $w = ugtk2->new(N("Edit a medium"), grab => 1, center => 1, transient => $mainw->{rwindow});
    my ($url_entry, $hdlist_entry, $url, $with_hdlist);
    gtkadd(
	$w->{window},
	gtkpack_(
	    Gtk2::VBox->new(0,5),
	    0, Gtk2::Label->new(N("Editing medium \"%s\":", $medium->{name})),
	    0, create_packtable(
		{},
		[ N("URL:"), $url_entry = gtkentry($medium->{url}) ],
		[ N("Relative path to synthesis/hdlist:"), $hdlist_entry = gtkentry($medium->{with_hdlist}) ],
	    ),
	    0, Gtk2::HSeparator->new,
	    0, gtkpack(
		create_hbox(),
		gtksignal_connect(
		    Gtk2::Button->new(N("Save changes")),
		    clicked => sub {
			$w->{retval} = 1;
			($url, $with_hdlist) = ($url_entry->get_text, $hdlist_entry->get_text);
			Gtk2->main_quit;
		    },
		),
		gtksignal_connect(
		    Gtk2::Button->new(N("Cancel")),
		    clicked => sub { $w->{retval} = 0; Gtk2->main_quit },
		),
		gtksignal_connect(
		    Gtk2::Button->new(N("Proxy...")),
		    clicked => sub { proxy_callback($medium) },
		),
	    )
	)
    );
    $w->{rwindow}->set_size_request(600, -1);
    if ($w->main) {
	my ($name, $update) = map { $medium->{$_} } qw(name update);
	$url =~ m|^removable://| and (
	    interactive_msg(
		N("You need to insert the medium to continue"),
		N("In order to save the changes, you need to insert the medium in the drive."),
		yesno => 1, text => { yes => N("Ok"), no => N("Cancel") }
	    ) or return 0
	);
	standalone::explanations("Removing medium $name");
	$urpm->select_media($name);
	$urpm->remove_selected_media;
	add_medium_and_check($urpm, { nolock => 1 }, $name, $url, $with_hdlist, update => $update);
	return 1;
    }
    return 0;
}

sub update_callback {
    update_sources_interactive($urpm, transient => $mainw->{rwindow}, nolock => 1);
}

sub proxy_callback {
    my ($medium) = @_;
    my $medium_name = $medium ? $medium->{name} : '';
    my $w = ugtk2->new(N("Configure proxies"), grab => 1, center => 1, transient => $mainw->{rwindow});
    my ($proxy, $proxy_user) = curl_download::readproxy($medium_name);
    my ($user, $pass) = $proxy_user =~ /^([^:]*):(.*)$/;
    my ($proxybutton, $proxyentry, $proxyuserbutton, $proxyuserentry, $proxypasswordentry);
    gtkadd(
	$w->{window},
	gtkpack__(
	    Gtk2::VBox->new(0, 5),
	    gtkset_justify(Gtk2::Label->new(
		$medium_name
		    ? N("Proxy settings for media \"%s\"", $medium_name)
		    : N("Global proxy settings")
	    ), 'center'),
	    gtkset_justify(Gtk2::Label->new(N("If you need a proxy, enter the hostname and an optional port (syntax: <proxyhost[:port]>):")), 'center'),
	    gtkpack_(
		Gtk2::HBox->new(0, 10),
		0, gtkset_active($proxybutton = Gtk2::CheckButton->new(N("Proxy hostname:")), to_bool($proxy)),
		1, gtkset_sensitive($proxyentry = gtkentry($proxy), to_bool($proxy)),
	    ),
	    gtkset_justify(Gtk2::Label->new(N("You may specify a user/password for the proxy authentication:")), 'center'),
	    gtkpack_(
		Gtk2::HBox->new(0, 10),
		0, gtkset_active($proxyuserbutton = Gtk2::CheckButton->new(N("User:")), to_bool($proxy_user)),
		1, gtkset_sensitive($proxyuserentry = gtkentry($user), to_bool($proxy_user)),
		0, Gtk2::Label->new(N("Password:")),
		1, gtkset_visibility(gtkset_sensitive($proxypasswordentry = gtkentry($pass), to_bool($proxy_user)), 0),
	    ),
	    Gtk2::HSeparator->new,
	    gtkpack(
		create_hbox(),
		gtksignal_connect(
		    Gtk2::Button->new(N("Ok")),
		    clicked => sub {
			$w->{retval} = 1;
			$proxy = $proxybutton->get_active ? $proxyentry->get_text : '';
			$proxy_user = $proxyuserbutton->get_active
			    ? ($proxyuserentry->get_text.':'.$proxypasswordentry->get_text) : '';
			Gtk2->main_quit;
		    },
		),
		gtksignal_connect(
		    Gtk2::Button->new(N("Cancel")),
		    clicked => sub { $w->{retval} = 0; Gtk2->main_quit },
		)
	    )
	)
    );
    $proxybutton->signal_connect(
	clicked => sub {
	    $proxyentry->set_sensitive($_[0]->get_active);
	    $_[0]->get_active and return;
	    $proxyuserbutton->set_active(0);
	    $proxyuserentry->set_sensitive(0);
	    $proxypasswordentry->set_sensitive(0);
	}
    );
    $proxyuserbutton->signal_connect(clicked => sub { $proxyuserentry->set_sensitive($_[0]->get_active);
    $proxypasswordentry->set_sensitive($_[0]->get_active) });

    $w->main and curl_download::writeproxy($proxy, $proxy_user, $medium_name);
}

sub parallel_read_sysconf {
    my @conf;
    foreach (cat_('/etc/urpmi/parallel.cfg')) {
        my ($name, $protocol, $command) = /([^:]+):([^:]+):(.*)/ or print STDERR "Warning, unrecognized line in /etc/urpmi/parallel.cfg:\n$_";
        my $medias = $protocol =~ s/\(([^\)]+)\)$// ? [ split /,/, $1 ] : [];
        push @conf, { name => $name, protocol => $protocol, medias => $medias, command => $command };
    }
    \@conf;
}

sub parallel_write_sysconf {
    my ($conf) = @_;
    output '/etc/urpmi/parallel.cfg',
           map { my $m = @{$_->{medias}} ? '('.join(',', @{$_->{medias}}).')' : '';
                 "$_->{name}:$_->{protocol}$m:$_->{command}\n" } @$conf;
}

sub remove_parallel {
    my ($num, $conf) = @_;
    if ($num != -1) {
        splice @$conf, $num, 1;
        parallel_write_sysconf($conf);
    }
}

sub edit_parallel {
    my ($num, $conf) = @_;
    my $edited = $num == -1 ? {} : $conf->[$num];

    my $w = ugtk2->new($num == -1 ? N("Add a parallel group") : N("Edit a parallel group"), grab => 1);
    my $name_entry;

    my $medias_ls = Gtk2::ListStore->new("Glib::String");
    my $medias = Gtk2::TreeView->new_with_model($medias_ls);
    $medias->append_column(Gtk2::TreeViewColumn->new_with_attributes(undef, Gtk2::CellRendererText->new, 'text' => 0));
    $medias->set_headers_visible(0);
    $medias->get_selection->set_mode('browse');
    $medias_ls->append_set([ 0 => $_ ]) foreach @{$edited->{medias}};

    my $add_media = sub {
        my $w = ugtk2->new(N("Add a medium limit"), grab => 1);
        my $medias_list_ls = Gtk2::ListStore->new("Glib::String");
        my $medias_list = Gtk2::TreeView->new_with_model($medias_list_ls);
        $medias_list->append_column(Gtk2::TreeViewColumn->new_with_attributes(undef, Gtk2::CellRendererText->new, 'text' => 0));
        $medias_list->set_headers_visible(0);
        $medias_list->get_selection->set_mode('browse');
        $medias_list_ls->append_set([ 0 => $_->{name} ]) foreach @{$urpm->{media}};
        my $sel;
        gtkadd($w->{window},
               gtkpack__(Gtk2::VBox->new(0, 5),
                         Gtk2::Label->new(N("Choose a medium for adding in the media limit:")),
                         $medias_list,
                         Gtk2::HSeparator->new,
                         gtkpack(create_hbox(),
           gtksignal_connect(Gtk2::Button->new(N("Ok")), clicked => sub {
                                 $w->{retval} = 1;
                                 $sel = selrow($medias_list);
                                 Gtk2->main_quit
                             }),
           gtksignal_connect(Gtk2::Button->new(N("Cancel")), clicked => sub { $w->{retval} = 0; Gtk2->main_quit }))));
        if ($w->main && $sel != -1) {
            my $media = ${$urpm->{media}}[$sel]{name};
            $medias_ls->append_set([ 0 => $media ]);
            push @{$edited->{medias}}, $media;
        }
    };
    my $remove_media = sub {
        my $row = selrow($medias);
        if ($row != -1) {
            splice @{$edited->{medias}}, $row, 1;
            remove_row($medias_ls, $row);
        }
    };

    my $hosts_ls = Gtk2::ListStore->new("Glib::String");
    my $hosts = Gtk2::TreeView->new_with_model($hosts_ls);
    $hosts->append_column(Gtk2::TreeViewColumn->new_with_attributes(undef, Gtk2::CellRendererText->new, 'text' => 0));
    $hosts->set_headers_visible(0);
    $hosts->get_selection->set_mode('browse');
    my $hosts_list;
    if ($edited->{protocol} eq 'ssh')    { $hosts_list = [ split /:/, $edited->{command} ] };
    if ($edited->{protocol} eq 'ka-run') { push @$hosts_list, $1 while $edited->{command} =~ /-m (\S+)/g };
    $hosts_ls->append_set([ 0 => $_ ]) foreach @$hosts_list;
    my $add_host = sub {
        my $w = ugtk2->new(N("Add a host"), grab => 1);
        my ($entry, $value);
        gtkadd($w->{window},
               gtkpack__(Gtk2::VBox->new(0, 5),
                         Gtk2::Label->new(N("Type in the hostname or IP address of the host to add:")),
                         $entry = gtkentry(),
                         Gtk2::HSeparator->new,
                         gtkpack(create_hbox(),
           gtksignal_connect(Gtk2::Button->new(N("Ok")), clicked => sub { $w->{retval} = 1; $value = $entry->get_text; Gtk2->main_quit }),
           gtksignal_connect(Gtk2::Button->new(N("Cancel")), clicked => sub { $w->{retval} = 0; Gtk2->main_quit }))));
        if ($w->main) {
            $hosts_ls->append_set([ 0 => $value ]);
            push @$hosts_list, $value;
        }
    };
    my $remove_host = sub {
        my $row = selrow($hosts);
        if ($row != -1) {
            splice @$hosts_list, $row, 1;
            remove_row($hosts_ls, $row);
        }
    };

    my @protocols_names = qw(ka-run ssh);
    my @protocols;
    gtkadd($w->{window},
	   gtkpack_(Gtk2::VBox->new(0, 5),
                    if_($num != -1,
                        0, Gtk2::Label->new(N("Editing parallel group \"%s\":", $edited->{name}))),
		    1, create_packtable({},
					[ N("Group name:"), $name_entry = gtkentry($edited->{name}) ],
                                        [ N("Protocol:"), gtkpack__(Gtk2::HBox->new(0, 0),
                                                                    @protocols = gtkradio($edited->{protocol}, @protocols_names)) ],
                                        [ N("Media limit:"),
                                          gtkpack_(Gtk2::HBox->new(0, 5),
                                                   1, gtkadd(gtkset_shadow_type(Gtk2::Frame->new, 'in'),
                                                             create_scrolled_window($medias, [ 'never', 'automatic' ])),
                                                   0, gtkpack__(Gtk2::VBox->new(0, 0),
                                             gtksignal_connect(Gtk2::Button->new(but(N("Add"))),    clicked => sub { $add_media->() }),
                                             gtksignal_connect(Gtk2::Button->new(but(N("Remove"))), clicked => sub { $remove_media->() }))) ],
                                        [ N("Hosts:"),
                                          gtkpack_(Gtk2::HBox->new(0, 5),
                                                   1, gtkadd(gtkset_shadow_type(Gtk2::Frame->new, 'in'),
                                                             create_scrolled_window($hosts, [ 'never', 'automatic' ])),
                                                   0, gtkpack__(Gtk2::VBox->new(0, 0),
                                             gtksignal_connect(Gtk2::Button->new(but(N("Add"))),    clicked => sub { $add_host->() }),
                                             gtksignal_connect(Gtk2::Button->new(but(N("Remove"))), clicked => sub { $remove_host->() }))) ]),
		    0, Gtk2::HSeparator->new,
		    0, gtkpack(create_hbox(),
			       gtksignal_connect(Gtk2::Button->new(N("Ok")), clicked => sub {
                                                     $w->{retval} = 1;
                                                     $edited->{name} = $name_entry->get_text;
                                                     mapn {
                                                         $_[0]->get_active and $edited->{protocol} = $_[1];
                                                     } \@protocols, \@protocols_names;
                                                     Gtk2->main_quit }),
			       gtksignal_connect(Gtk2::Button->new(N("Cancel")), clicked => sub { $w->{retval} = 0; Gtk2->main_quit }))));
    $w->{rwindow}->set_position('center');
    $w->{rwindow}->set_size_request(600, -1);
    if ($w->main) {
        $num == -1 and push @$conf, $edited;
        if ($edited->{protocol} eq 'ssh')    { $edited->{command} = join(':', @$hosts_list) }
        if ($edited->{protocol} eq 'ka-run') { $edited->{command} = "-c ssh ".join(' ', map { "-m $_" } @$hosts_list) }
        parallel_write_sysconf($conf);
	return 1;
    }        
    return 0;
}

sub parallel_callback {
    my $w = ugtk2->new(N("Configure parallel urpmi (distributed execution of urpmi)"), grab => 1, transient => $mainw->{rwindow});
    my $list_ls = Gtk2::ListStore->new("Glib::String", "Glib::String", "Glib::String", "Glib::String");
    my $list = Gtk2::TreeView->new_with_model($list_ls);
    each_index { $list->append_column(Gtk2::TreeViewColumn->new_with_attributes($_, Gtk2::CellRendererText->new, 'text' => $::i)) } N("Group"), N("Protocol"), N("Media limit");
    $list->append_column(my $commandcol = Gtk2::TreeViewColumn->new_with_attributes(N("Command"), Gtk2::CellRendererText->new, 'text' => 3));
    $commandcol->set_max_width(200);

    my $conf;
    my $reread = sub {
	$list_ls->clear;
        $conf = parallel_read_sysconf();
	foreach (@$conf) {
            $list_ls->append_set([ 0 => $_->{name},
                                   1 => $_->{protocol},
                                   2 => @{$_->{medias}} ? join(', ', @{$_->{medias}}) : N("(none)"),
                                   3 => $_->{command} ]);
	}
    };
    $reread->();

    gtkadd($w->{window},
	   gtkpack_(Gtk2::VBox->new(0,5),
		    1, gtkpack_(Gtk2::HBox->new(0, 10),
				1, $list,
				0, gtkpack__(Gtk2::VBox->new(0, 5),
					     gtksignal_connect($remove = Gtk2::Button->new(but(N("Remove"))),
                                                               clicked => sub { remove_parallel(selrow($list), $conf); $reread->() }),
					     gtksignal_connect($edit = Gtk2::Button->new(but(N("Edit"))),
                                                               clicked => sub {
                                                                   my $row = selrow($list);
                                                                   $row != -1 and edit_parallel($row, $conf);
                                                                   $reread->() }),
					     gtksignal_connect(Gtk2::Button->new(but(N("Add..."))), 
							       clicked => sub { edit_parallel(-1, $conf) and $reread->() }))),
		    0, Gtk2::HSeparator->new,
		    0, gtkpack(create_hbox(),
			       gtksignal_connect(Gtk2::Button->new(N("Ok")), clicked => sub { Gtk2->main_quit }))));
    $w->{rwindow}->set_position('center');

    $w->main;
}


sub keys_callback {
    my $w = ugtk2->new(N("Manage keys for digital signatures of packages"), grab => 1, transient => $mainw->{rwindow});

    my $media_list_ls = Gtk2::ListStore->new("Glib::String");
    my $media_list = Gtk2::TreeView->new_with_model($media_list_ls);
    $media_list->append_column(Gtk2::TreeViewColumn->new_with_attributes(N("Medium"), Gtk2::CellRendererText->new, 'text' => 0));
    $media_list->get_selection->set_mode('browse');

    my $keys_list_ls = Gtk2::ListStore->new("Glib::String", "Glib::String");
    my $keys_list = Gtk2::TreeView->new_with_model($keys_list_ls);
    $keys_list->append_column(Gtk2::TreeViewColumn->new_with_attributes(N("Keys"), Gtk2::CellRendererText->new, 'text' => 0));
    $keys_list->get_selection->set_mode('browse');

    my ($current_medium, $current_medium_nb, @keys);

    my $read_conf = sub {
        $urpm->parse_pubkeys(root => $urpm->{root});
        @keys = map { [ split /[,\s]+/, $_->{'key-ids'} ] } @{$urpm->{media}};
    };
    my $write = sub {
        $urpm->write_config;
        $urpm = urpm->new;
        $urpm->read_config; 
        $read_conf->();
        $media_list->get_selection->signal_emit('changed');
    };
    $read_conf->();
    my $key_name = sub {
        exists $urpm->{keys}{$_[0]} ? $urpm->{keys}{$_[0]}{name}
                                    : N("no name found, key doesn't exist in rpm keyring!");
    };
    
    $media_list_ls->append_set([ 0 => $_->{name} ]) foreach @{$urpm->{media}};
    $media_list->get_selection->signal_connect(changed => sub {
        my ($model, $iter) = $_[0]->get_selected;
        $model && $iter or return;
        $current_medium = $model->get($iter, 0);
        $current_medium_nb = $model->get_path($iter)->to_string;
        $keys_list_ls->clear;
        $keys_list_ls->append_set([ 0 => sprintf("%s (%s)", $_, $key_name->($_)), 1 => $_ ]) foreach @{$keys[$current_medium_nb]};
    });

    my $add_key = sub {
        my $w_add = ugtk2->new(N("Add a key"), grab => 1, transient => $w->{rwindow});
        my $available_keyz_ls = Gtk2::ListStore->new("Glib::String", "Glib::String");
        my $available_keyz = Gtk2::TreeView->new_with_model($available_keyz_ls);
        $available_keyz->append_column(Gtk2::TreeViewColumn->new_with_attributes(undef, Gtk2::CellRendererText->new, 'text' => 0));
        $available_keyz->set_headers_visible(0);
        $available_keyz->get_selection->set_mode('browse');
        $available_keyz_ls->append_set([ 0 => sprintf("%s (%s)", $_, $key_name->($_)), 1 => $_ ]) foreach keys %{$urpm->{keys}};
        my $key;
        gtkadd($w_add->{window},
               gtkpack__(Gtk2::VBox->new(0, 5),
                         Gtk2::Label->new(N("Choose a key for adding to the medium %s", $current_medium)),
                         $available_keyz,
                         Gtk2::HSeparator->new,
                         gtkpack(create_hbox(),
                                 gtksignal_connect(Gtk2::Button->new(N("Ok")), clicked => sub {
                                                       my ($model, $iter) = $available_keyz->get_selection->get_selected;
                                                       $model && $iter and $key = $model->get($iter, 1);
                                                       Gtk2->main_quit;
                                                   }),
                                 gtksignal_connect(Gtk2::Button->new(N("Cancel")), clicked => sub { Gtk2->main_quit }))));
        $w_add->main;
        if (defined $key) {
            $urpm->{media}[$current_medium_nb]{'key-ids'} = join(',', sort(uniq(@{$keys[$current_medium_nb]}, $key)));
            $write->();
        }
    };

    my $remove_key = sub {
        my ($model, $iter) = $keys_list->get_selection->get_selected;
        $model && $iter or return;
        my $key = $model->get($iter, 1);
	interactive_msg(N("Remove a key"),
                        N("Are you sure you want to remove the key %s from medium %s?\n(name of the key: %s)",
                          $key, $current_medium, $key_name->($key)),
                        yesno => 1, transient => $w->{rwindow}) or return;
        $urpm->{media}[$current_medium_nb]{'key-ids'} = join(',', difference2(\@{$keys[$current_medium_nb]}, [ $key ]));
        $write->();
    };

    gtkadd($w->{window},
	   gtkpack_(Gtk2::VBox->new(0,5),
		    1, gtkpack_(Gtk2::HBox->new(0, 10),
				1, $media_list,
				1, $keys_list,
				0, gtkpack__(Gtk2::VBox->new(0, 5),
					     gtksignal_connect($remove = Gtk2::Button->new(but(N("Add a key..."))),
                                                               clicked => \&$add_key),
					     gtksignal_connect($remove = Gtk2::Button->new(but(N("Remove key"))),
                                                               clicked => \&$remove_key))),
		    0, Gtk2::HSeparator->new,
		    0, gtkpack(create_hbox(),
			       gtksignal_connect(Gtk2::Button->new(N("Ok")), clicked => sub { Gtk2->main_quit }))));
    $w->{rwindow}->set_position('center');

    $w->main;
}


sub mainwindow {
    $mainw = ugtk2->new(N("Configure media"), center => 1);

    my $list = Gtk2::ListStore->new("Glib::Boolean", "Glib::String");
    $list_tv = Gtk2::TreeView->new_with_model($list);
    $list_tv->get_selection->set_mode('browse');
    $list_tv->set_rules_hint(1);
    $list_tv->set_reorderable(1);

    my $reorder_ok = 1;
    $list->signal_connect(row_deleted => sub {
                              my ($model) = @_;
                              $reorder_ok or return;
                              my @media;
                              $model->foreach(sub {
                                              my (undef, undef, $iter) = @_;
                                              my $name = $model->get($iter, 1);
                                              push @media, find { $_->{name} eq $name } @{$urpm->{media}};
                                              0;
                                          }, undef);
                              @{$urpm->{media}} = @media;
                          });

    $list_tv->append_column(Gtk2::TreeViewColumn->new_with_attributes(N("Enabled?"), my $tr = Gtk2::CellRendererToggle->new, 'active' => 0));
    $list_tv->append_column(Gtk2::TreeViewColumn->new_with_attributes(N("Medium"), Gtk2::CellRendererText->new, 'text' => 1));

    $tr->signal_connect(toggled => sub {
			    my (undef, $path) = @_;
			    my $iter = $list->get_iter_from_string($path);
			    $urpm->{media}[$path]{ignore} = !$urpm->{media}[$path]{ignore} || undef;
			    $list->set($iter, 0, !$urpm->{media}[$path]{ignore});
			});

    my $menu = Gtk2::Menu->new;
    my @menu_actions = ([ 'update_source', N("Update medium") ], [ 'generate_hdlist', N("Regenerate hdlist") ]);
    foreach (@menu_actions) {
	my ($action, $text) = @$_;
        my $row;
        my $select_media = sub {
            $urpm->select_media($urpm->{media}[$row]{name});
            foreach (@{$urpm->{media}}) {  #- force ignored media to be returned alive
                $_->{modified} and delete $_->{ignore};
            }
        };
	my %action2fun; %action2fun = (
			  update_source => sub {
                              slow_func(N("Please wait, updating media..."),
                                        sub { $urpm->update_media(noclean => 1, nolock => 1) });
                          },
			  generate_hdlist => sub {
                              slow_func(N("Please wait, generating hdlist..."),
                                        sub { $urpm->update_media(noclean => 1, force => 1, nolock => 1) });
                          });
	$menu->append(gtksignal_connect(gtkshow(Gtk2::MenuItem->new_with_label($text)),
                                        activate => sub {
                                            $row = selrow();
                                            $row == -1 and return;
                                            $select_media->();
                                            $action2fun{$action}->()
                                        }));
    }
    $list_tv->signal_connect(button_press_event => sub {
                                 $_[1]->button == 3 or return 0;
                                 $menu->popup(undef, undef, undef, undef, $_[1]->button, $_[1]->time);
                                 1;
                             });

    my $reread_media = sub {
        $reorder_ok = 0;
	$urpm = urpm->new;
	$urpm->read_config; 
	$list->clear;
	$list->append_set([ 0 => !$_->{ignore}, 1 => $_->{name} ]) foreach @{$urpm->{media}};
        $reorder_ok = 1;
    };
    $reread_media->();

    gtkadd($mainw->{window},
	   gtkpack_(Gtk2::VBox->new(0,5),
		    1, gtkpack_(Gtk2::HBox->new(0, 10),
				1, $list_tv,
				0, gtkpack__(Gtk2::VBox->new(0, 5),
					     gtksignal_connect($remove = Gtk2::Button->new(but(N("Remove"))),
										clicked => sub { remove_callback(); $reread_media->(); }),
					     gtksignal_connect($edit = Gtk2::Button->new(but(N("Edit"))),
										clicked => sub { edit_callback() and $reread_media->() }),
					     gtksignal_connect(Gtk2::Button->new(but(N("Add..."))), 
							       clicked => sub { add_callback() and $reread_media->(); }),
					     gtksignal_connect(
						 Gtk2::Button->new(but(N("Update..."))),
						 clicked => sub {
						     update_callback() and $reread_media->();
						 },
					     ),
					     gtksignal_connect(Gtk2::Button->new(but(N("Manage keys..."))), clicked => \&keys_callback),
					     gtksignal_connect(Gtk2::Button->new(but(N("Proxy..."))), clicked => \&proxy_callback),
					     gtksignal_connect(Gtk2::Button->new(but(N("Parallel..."))), clicked => \&parallel_callback))),
		    0, Gtk2::HSeparator->new,
		    0, gtkpack(create_hbox(),
			       gtksignal_connect(Gtk2::Button->new(but(N("Help"))), clicked => sub {
                                                           system("drakhelp --id software-management-sources &");
                                                           interactive_msg(N("Help launched in background"),
                                                                           N("The help window has been started, it should appear shortly on your desktop."));
                                                                        }),
			       gtksignal_connect(Gtk2::Button->new(but(N("Ok"))), clicked => sub { Gtk2->main_quit }))));
    $mainw->main;
}


readconf();

if (!member(basename($0), @$already_splashed)) {
    interactive_msg('rpmdrake',
N("%s

Is it ok to continue?",
N("Welcome to the Software Media Manager!

This tool will help you configure the packages media you wish to use on
your computer. They will then be available to install new software package
or to perform updates.")), yesno => 1) or myexit -1;
    push @$already_splashed, basename($0);
}

{
    $urpm = urpm->new;
    local $urpm->{fatal} = sub {
        interactive_msg('rpmdrake',
N("Packages database is locked. Please close other applications
working with packages database (do you have another media
manager on another desktop, or are you currently installing
packages as well?)."));
        myexit -1;
    };
    $urpm->exlock_urpmi_db;
}

mainwindow();
$urpm->write_config;

writeconf();

myexit 0;
l ipl">$printer->{SPOOLER} -r |") or die "Could not run foomatic-configure"; eval join('', <$F>); close $F; } else { my ($_daemonless_cups, $remote_cups_server) = printer::main::read_client_conf(); $printer->{remote_cups_server} = $remote_cups_server; } } $printer->{configured} = {}; my $i; my $N = $#QUEUES + 1; for ($i = 0; $i < $N; $i++) { # Set the default printer $printer->{DEFAULT} = $QUEUES[$i]{queuedata}{queue} if $QUEUES[$i]{queuedata}{default}; # Advance to the next entry if the current is a remotely defined # printer next if $QUEUES[$i]{queuedata}{remote}; # Add an entry for a locally defined queue $printer->{configured}{$QUEUES[$i]{queuedata}{queue}} = $QUEUES[$i]; if (!$QUEUES[$i]{make} || !$QUEUES[$i]{model}) { if ($printer->{SPOOLER} eq "cups") { $printer->{OLD_QUEUE} = $QUEUES[$i]{queuedata}{queue}; my $descr = get_descr_from_ppd($printer); if ($descr =~ m/^([^\|]*)\|([^\|]*)(\|.*|)$/) { $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{make} ||= $1; $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{model} ||= $2; } # Read out which PPD file was originally used to set up this # queue if (open(my $F, "< $::prefix/etc/cups/ppd/$QUEUES[$i]{queuedata}{queue}.ppd")) { while (my $line = <$F>) { if ($line =~ /^\*%MDKMODELCHOICE:(.+)$/) { $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{ppd} = $1; } } close $F; } # Mark that we have a CUPS queue but do not know the name # the PPD file in /usr/share/cups/model if (!$printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{ppd}) { $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{ppd} = '1'; } $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{driver} = 'PPD'; $printer->{OLD_QUEUE} = ""; } $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{make} ||= ""; $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{model} ||= N("Unknown model"); } else { $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{make} = $QUEUES[$i]{make}; $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{model} = $QUEUES[$i]{model}; } # Fill in "options" field if (my $args = $printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{args}) { my @options; foreach my $arg (@$args) { push(@options, "-o"); my $optstr = $arg->{name} . "=" . $arg->{default}; push(@options, $optstr); } @{$printer->{configured}{$QUEUES[$i]{queuedata}{queue}}{queuedata}{options}} = @options; } # Construct an entry line for tree view in main window of # printerdrake make_menuentry($printer, $QUEUES[$i]{queuedata}{queue}); } } sub make_menuentry { my ($printer, $queue) = @_; my $spooler = $spoolers{$printer->{SPOOLER}}{short_name}; my $connect = $printer->{configured}{$queue}{queuedata}{connect}; my $localremote = N("Configured on this machine"); my $make = $printer->{configured}{$queue}{queuedata}{make}; my $model = $printer->{configured}{$queue}{queuedata}{model}; my $connection; if ($connect =~ m!^(file|parallel):/dev/lp(\d+)$!) { my $number = $2; $connection = N(" on parallel port #%s", $number); } elsif ($connect =~ m!^(file|usb):/dev/usb/lp(\d+)$!) { my $number = $2; $connection = N(", USB printer #%s", $number); } elsif ($connect =~ m!^usb://!) { $connection = N(", USB printer"); } elsif ($connect =~ m!^hp:/(.+?)$!) { my $hplipdevice = $1; if ($hplipdevice =~ m!^par/!) { $connection = N(", HP printer on a parallel port"); } elsif ($hplipdevice =~ m!^usb/!) { $connection = N(", HP printer on USB"); } elsif ($hplipdevice =~ m!^net/!) { $connection = N(", HP printer on HP JetDirect"); } else { $connection = N(", HP printer"); } } elsif ($connect =~ m!^ptal://?(.+?)$!) { my $ptaldevice = $1; if ($ptaldevice =~ /^mlc:par:(\d+)$/) { my $number = $1; $connection = N(", multi-function device on parallel port #%s", $number); } elsif ($ptaldevice =~ /^mlc:par:/) { $connection = N(", multi-function device on a parallel port"); } elsif ($ptaldevice =~ /^mlc:usb:/) { $connection = N(", multi-function device on USB"); } elsif ($ptaldevice =~ /^hpjd:/) { $connection = N(", multi-function device on HP JetDirect"); } else { $connection = N(", multi-function device"); } } elsif ($connect =~ m!^file:(.+)$!) { my $file = $1; $connection = N(", printing to %s", $file); } elsif ($connect =~ m!^lpd://([^/]+)/([^/]+)/?$!) { my ($server, $printer) = ($1, $2); $connection = N(" on LPD server \"%s\", printer \"%s\"", $server, $printer); } elsif ($connect =~ m!^socket://([^/:]+):([^/:]+)/?$!) { my ($host, $port) = ($1, $2); $connection = N(", TCP/IP host \"%s\", port %s", $host, $port); } elsif ($connect =~ m!^smb://([^/\@]+)/([^/\@]+)/?$! || $connect =~ m!^smb://.*/([^/\@]+)/([^/\@]+)/?$! || $connect =~ m!^smb://.*\@([^/\@]+)/([^/\@]+)/?$!) { my ($server, $share) = ($1, $2); $connection = N(" on SMB/Windows server \"%s\", share \"%s\"", $server, $share); } elsif ($connect =~ m!^ncp://([^/\@]+)/([^/\@]+)/?$! || $connect =~ m!^ncp://.*/([^/\@]+)/([^/\@]+)/?$! || $connect =~ m!^ncp://.*\@([^/\@]+)/([^/\@]+)/?$!) { my ($server, $printer) = ($1, $2); $connection = N(" on Novell server \"%s\", printer \"%s\"", $server, $printer); } elsif ($connect =~ m!^postpipe:(.+)$!) { my $command = $1; $connection = N(", using command %s", $command); } else { $connection = ($printer->{expert} ? ", URI: $connect" : ""); } my $sep = "!"; $printer->{configured}{$queue}{queuedata}{menuentry} = ($printer->{expert} ? "$spooler$sep" : "") . "$localremote$sep$queue: $make $model$connection"; } sub connectionstr { my ($connect) = @_; my $connection; if ($connect =~ m!^(file|parallel):/dev/lp(\d+)$!) { my $number = $2; $connection = N("Parallel port #%s", $number); } elsif ($connect =~ m!^(file|usb):/dev/usb/lp(\d+)$!) { my $number = $2; $connection = N("USB printer #%s", $number); } elsif ($connect =~ m!^usb://!) { $connection = N("USB printer"); } elsif ($connect =~ m!^hp:/(.+?)$!) { my $hplipdevice = $1; if ($hplipdevice =~ m!^par/!) { $connection = N("HP printer on a parallel port"); } elsif ($hplipdevice =~ m!^usb/!) { $connection = N("HP printer on USB"); } elsif ($hplipdevice =~ m!^net/!) { $connection = N("HP printer on HP JetDirect"); } else { $connection = N("HP printer"); } } elsif ($connect =~ m!^ptal://?(.+?)$!) { my $ptaldevice = $1; if ($ptaldevice =~ /^mlc:par:(\d+)$/) { my $number = $1; $connection = N("Multi-function device on parallel port #%s", $number); } elsif ($ptaldevice =~ /^mlc:par:/) { $connection = N("Multi-function device on a parallel port"); } elsif ($ptaldevice =~ /^mlc:usb:/) { $connection = N("Multi-function device on USB"); } elsif ($ptaldevice =~ /^hpjd:/) { $connection = N("Multi-function device on HP JetDirect"); } else { $connection = N("Multi-function device"); } } elsif ($connect =~ m!^file:(.+)$!) { my $file = $1; $connection = N("Prints into %s", $file); } elsif ($connect =~ m!^lpd://([^/]+)/([^/]+)/?$!) { my ($server, $port) = ($1, $2); $connection = N("LPD server \"%s\", printer \"%s\"", $server, $port); } elsif ($connect =~ m!^socket://([^/:]+):([^/:]+)/?$!) { my ($host, $port) = ($1, $2); $connection = N("TCP/IP host \"%s\", port %s", $host, $port); } elsif ($connect =~ m!^smb://([^/\@]+)/([^/\@]+)/?$! || $connect =~ m!^smb://.*/([^/\@]+)/([^/\@]+)/?$! || $connect =~ m!^smb://.*\@([^/\@]+)/([^/\@]+)/?$!) { my ($server, $share) = ($1, $2); $connection = N("SMB/Windows server \"%s\", share \"%s\"", $server, $share); } elsif ($connect =~ m!^ncp://([^/\@]+)/([^/\@]+)/?$! || $connect =~ m!^ncp://.*/([^/\@]+)/([^/\@]+)/?$! || $connect =~ m!^ncp://.*\@([^/\@]+)/([^/\@]+)/?$!) { my ($server, $share) = ($1, $2); $connection = N("Novell server \"%s\", printer \"%s\"", $server, $share); } elsif ($connect =~ m!^postpipe:(.+)$!) { my $command = $1; $connection = N("Uses command %s", $command); } else { $connection = N("URI: %s", $connect); } return $connection; } sub read_printer_db { my ($printer, $spooler) = @_; # No local queues available in daemon-less CUPS mode return 1 if $spooler eq "rcups"; my $DBPATH; #- do not have to do close ... and do not modify globals at least # Generate the Foomatic printer/driver overview, read it from the # appropriate file when it is already generated open($DBPATH, ($::testing ? $::prefix : "chroot $::prefix/ ") . #-# "foomatic-configure -O -q |") or die "Could not run foomatic-configure"; my $entry = {}; my $inentry = 0; my $indrivers = 0; my $inautodetect = 0; my $autodetecttype = ""; local $_; while (<$DBPATH>) { chomp; if ($inentry) { # We are inside a printer entry if ($indrivers) { # We are inside the drivers block of a printers entry if (m!^\s*</drivers>\s*$!) { # End of drivers block $indrivers = 0; } elsif (m!^\s*<driver>(.+)</driver>\s*$!) { push @{$entry->{drivers}}, $1; } } elsif ($inautodetect) { # We are inside the autodetect block of a printers entry # All entries inside this block will be ignored if ($autodetecttype) { if (m!^.*</$autodetecttype>\s*$!) { # End of general, parallel, USB, or SNMP section $autodetecttype = ""; } elsif (m!^\s*<manufacturer>\s*([^<>]+)\s*</manufacturer>\s*$!) { # Manufacturer $entry->{devidmake} = $1; } elsif (m!^\s*<model>\s*([^<>]+)\s*</model>\s*$!) { # Model $entry->{devidmodel} = $1; } elsif (m!^\s*<description>\s*([^<>]+)\s*</description>\s*$!) { # Description $entry->{deviddesc} = $1; } elsif (m!^\s*<commandset>\s*([^<>]+)\s*</commandset>\s*$!) { # Command set $entry->{devidcmdset} = $1; } elsif (m!^\s*<ieee1284>\s*([^<>]+)\s*</ieee1284>\s*$!) { # Full ID string my $idstr = $1; $idstr =~ m!(MFG|MANUFACTURER):([^;]+);!i and $entry->{devidmake} = $2; $idstr =~ m!(MDL|MODEL):([^;]+);!i and $entry->{devidmodel} = $2; $idstr =~ m!(DES|DESCRIPTION):([^;]+);!i and $entry->{deviddesc} = $2; $idstr =~ m!(CMD|COMMAND\s*SET):([^;]+);!i and $entry->{devidcmdset} = $2; } } else { if (m!^.*</autodetect>\s*$!) { # End of autodetect block $inautodetect = 0; } elsif (m!^\s*<(general|parallel|usb|snmp)>\s*$!) { # Beginning of parallel, USB, or SNMP section $autodetecttype = $1; } } } else { if (m!^\s*</printer>\s*$!) { # entry completed $inentry = 0; # Expert mode: # Make one database entry per driver with the entry name # manufacturer|model|driver if ($printer->{expert}) { foreach my $driver (@{$entry->{drivers}}) { my $driverstr; if ($driver eq "Postscript") { $driverstr = "PostScript"; } else { $driverstr = "GhostScript + $driver"; } if ($driver eq $entry->{defaultdriver}) { $driverstr .= " (recommended)"; } $entry->{ENTRY} = "$entry->{make}|$entry->{model}|$driverstr"; $entry->{ENTRY} =~ s/^CITOH/C.ITOH/i; $entry->{ENTRY} =~ s/^KYOCERA[\s\-]*MITA/KYOCERA/i; $entry->{driver} = $driver; # Duplicate contents of $entry because it is multiply entered to the database map { $thedb{$entry->{ENTRY}}{$_} = $entry->{$_} } keys %$entry; } } else { # Recommended mode # Make one entry per printer, with the recommended # driver (manufacturerer|model) $entry->{ENTRY} = "$entry->{make}|$entry->{model}"; $entry->{ENTRY} =~ s/^CITOH/C.ITOH/i; $entry->{ENTRY} =~ s/^KYOCERA[\s\-]*MITA/KYOCERA/i; if ($entry->{defaultdriver}) { $entry->{driver} = $entry->{defaultdriver}; map { $thedb{$entry->{ENTRY}}{$_} = $entry->{$_} } keys %$entry; } } $entry = {}; } elsif (m!^\s*<id>\s*([^\s<>]+)\s*</id>\s*$!) { # Foomatic printer ID $entry->{printer} = $1; } elsif (m!^\s*<make>(.+)</make>\s*$!) { # Printer manufacturer $entry->{make} = uc($1); } elsif (m!^\s*<model>(.+)</model>\s*$!) { # Printer model $entry->{model} = $1; } elsif (m!<driver>(.+)</driver>!) { # Printer default driver $entry->{defaultdriver} = $1; } elsif (m!^\s*<drivers>\s*$!) { # Drivers block $indrivers = 1; @{$entry->{drivers}} = (); } elsif (m!^\s*<autodetect>\s*$!) { # Autodetect block $inautodetect = 1; } } } else { if (m!^\s*<printer>\s*$!) { # new entry $inentry = 1; } } } close $DBPATH; # Add raw queue $entry->{ENTRY} = N("Raw printer (No driver)"); $entry->{driver} = "raw"; $entry->{make} = ""; $entry->{model} = N("Unknown model"); $thedb{$entry->{ENTRY}}{$_} = $entry->{$_} foreach keys %$entry; #- Load CUPS driver database if CUPS is used as spooler if ($spooler && $spooler eq "cups") { poll_ppd_base($printer); } #my @entries_db_short = sort keys %printer::thedb; #%descr_to_db = map { $printer::thedb{$_}{DESCR}, $_ } @entries_db_short; #%descr_to_help = map { $printer::thedb{$_}{DESCR}, $printer::thedb{$_}{ABOUT} } @entries_db_short; #@entry_db_description = keys %descr_to_db; #db_to_descr = reverse %descr_to_db; } sub read_foomatic_options ($) { my ($printer) = @_; # Generate the option data for the chosen printer/driver combo my $COMBODATA; open(my $F, ($::testing ? $::prefix : "chroot $::prefix/ ") . "foomatic-configure -P -q -p $printer->{currentqueue}{printer}" . " -d $printer->{currentqueue}{driver}" . ($printer->{OLD_QUEUE} ? " -s $printer->{SPOOLER} -n $printer->{OLD_QUEUE}" : "") . ($printer->{SPECIAL_OPTIONS} ? " $printer->{SPECIAL_OPTIONS}" : "") . " |") or die "Could not run foomatic-configure"; eval join('', (<$F>)); close $F; # Return the arguments field return $COMBODATA->{args}; } sub read_ppd_options ($) { my ($printer) = @_; # Generate the option data for a given PPD file my $COMBODATA; open(my $F, ($::testing ? $::prefix : "chroot $::prefix/ ") . "foomatic-configure -P -q" . " --ppd /usr/share/cups/model/$printer->{currentqueue}{ppd}" . ($printer->{OLD_QUEUE} ? " -s $printer->{SPOOLER} -n $printer->{OLD_QUEUE}" : "") . ($printer->{SPECIAL_OPTIONS} ? " $printer->{SPECIAL_OPTIONS}" : "") . " |") or die "Could not run foomatic-configure"; eval join('', (<$F>)); close $F; # Return the arguments field return $COMBODATA->{args}; } my %sysconfig = getVarsFromSh("$::prefix/etc/sysconfig/printing"); sub set_cups_special_options { my ($queue) = @_; # Set some special CUPS options my @lpoptions = chomp_(cat_("$::prefix/etc/cups/lpoptions")); # If nothing is already configured, set text file borders of half an inch # and decrease the font size a little bit, so nothing of the text gets # cut off by unprintable borders. if (!any { /$queue.*\s(page-(top|bottom|left|right)|lpi|cpi)=/ } @lpoptions) { run_program::rooted($::prefix, "lpoptions", "-p", $queue, "-o", "page-top=36", "-o", "page-bottom=36", "-o", "page-left=36", "-o page-right=36", "-o", "cpi=12", "-o", "lpi=7", "-o", "wrap"); } # Let images fill the whole page by default if (!any { /$queue.*\s(scaling|natural-scaling|ppi)=/ } @lpoptions) { run_program::rooted($::prefix, "lpoptions", "-p", $queue, "-o", "scaling=100"); } return 1; } sub set_cups_autoconf { my ($autoconf) = @_; $sysconfig{CUPS_CONFIG} = $autoconf ? "automatic" : "manual"; setVarsInSh("$::prefix/etc/sysconfig/printing", \%sysconfig); # Restart CUPS printer::services::restart("cups") if $autoconf; return 1; } sub get_cups_autoconf() { $sysconfig{CUPS_CONFIG} ne 'manual' ? 1 : 0 } sub set_usermode { my ($usermode) = @_; $sysconfig{USER_MODE} = $usermode ? "expert" : "recommended"; setVarsInSh("$::prefix/etc/sysconfig/printing", \%sysconfig) if !$::testing; return $usermode; } sub get_usermode() { $sysconfig{USER_MODE} eq 'expert' ? 1 : 0 } sub set_jap_textmode { my $textmode = ($_[0] ? 'cjk' : ''); # Do not write mime.convs if the file does not exist, as then # CUPS is not installed and the created mime.convs will be broken. # When installing CUPS later it will not work. return 1 if (! -r "$::prefix/etc/cups/mime.convs"); substInFile { s!^(\s*text/plain\s+\S+\s+\d+\s+)\S+(\s*$)!$1${textmode}texttops$2! } "$::prefix/etc/cups/mime.convs"; return 1; } sub get_jap_textmode() { my @mimeconvs = cat_("$::prefix/etc/cups/mime.convs"); (m!^\s*text/plain\s+\S+\s+\d+\s+(\S+)\s*$!m and $1 eq 'cjktexttops' and return 1) foreach @mimeconvs; return 0; } #---------------------------------------------------------------------- # Handling of /etc/cups/cupsd.conf sub read_cupsd_conf() { # If /etc/cups/cupsd.conf a default cupsd.conf will be put out to avoid # writing of a broken cupsd.conf file when we write it back later. my @cupsd_conf = cat_("$::prefix/etc/cups/cupsd.conf"); if (!@cupsd_conf) { @cupsd_conf = map { /\n$/s or "$_\n" } split('\n', 'LogLevel info TempDir /var/spool/cups/tmp Port 631 Browsing On BrowseAddress @LOCAL BrowseDeny All BrowseAllow 127.0.0.1 BrowseAllow @LOCAL BrowseOrder deny,allow <Location /> Order Deny,Allow Deny From All Allow From 127.0.0.1 Allow From @LOCAL </Location> <Location /admin> AuthType Basic AuthClass System Order Deny,Allow Deny From All Allow From 127.0.0.1 </Location> '); } return @cupsd_conf; } sub write_cupsd_conf { my (@cupsd_conf) = @_; # Do not write cupsd.conf if the file does not exist, as then # CUPS is not installed and the created cupsd.conf will be broken. # When installing CUPS later it will not start. return 1 if (! -r "$::prefix/etc/cups/cupsd.conf"); output("$::prefix/etc/cups/cupsd.conf", @cupsd_conf); } sub read_location { # Return the lines inside the [path] location block # # <Location [path]> # ... # </Location> my ($cupsd_conf_ptr, $path) = @_; my @result; if (any { m!^\s*<Location\s+$path\s*>! } @$cupsd_conf_ptr) { my $location_start = -1; my $location_end = -1; # Go through all the lines, bail out when start and end line found for (my $i = 0; $i <= $#{$cupsd_conf_ptr} && $location_end == -1; $i++) { if ($cupsd_conf_ptr->[$i] =~ m!^\s*<\s*Location\s+$path\s*>!) { # Start line of block $location_start = $i; } elsif ($cupsd_conf_ptr->[$i] =~ m!^\s*<\s*/Location\s*>! && $location_start != -1) { # End line of block $location_end = $i; last; } elsif ($location_start >= 0 && $location_end < 0) { # Inside the location block push(@result, $cupsd_conf_ptr->[$i]); } } } else { # If there is no root location block, set the result array to # "undef" @result = undef; } return @result; } sub rip_location { # Cut out the [path] location block # # <Location [path]> # ... # </Location> # # so that it can be treated seperately without affecting the # rest of the file my ($cupsd_conf_ptr, $path) = @_; my @location; my $location_start = -1; my $location_end = -1; if (any { m!^\s*<Location\s+$path\s*>! } @$cupsd_conf_ptr) { # Go through all the lines, bail out when start and end line found for (my $i = 0; $i <= $#{$cupsd_conf_ptr} && $location_end == -1; $i++) { if ($cupsd_conf_ptr->[$i] =~ m!^\s*<\s*Location\s+$path\s*>!) { # Start line of block $location_start = $i; } elsif ($cupsd_conf_ptr->[$i] =~ m!^\s*<\s*/Location\s*>! && $location_start != -1) { # End line of block $location_end = $i; last; } } # Rip out the block and store it seperately @location = splice(@$cupsd_conf_ptr, $location_start, $location_end - $location_start + 1); } else { # If there is no location block, create one $location_start = $#{$cupsd_conf_ptr} + 1; @location = ("<Location $path>\n", "</Location>\n"); } return $location_start, @location; } sub insert_location { # Re-insert a location block ripped with "rip_location" my ($cupsd_conf_ptr, $location_start, @location) = @_; splice(@$cupsd_conf_ptr, $location_start,0,@location); } sub add_to_location { # Add a directive to a given location (only if it is not already there) my ($cupsd_conf_ptr, $path, $directive) = @_; my ($location_start, @location) = rip_location($cupsd_conf_ptr, $path); my $success = handle_configs::insert_directive(\@location, $directive); insert_location($cupsd_conf_ptr, $location_start, @location); return $success; } sub remove_from_location { # Remove a directive from a given location my ($cupsd_conf_ptr, $path, $directive) = @_; my ($location_start, @location) = rip_location($cupsd_conf_ptr, $path); my $success = handle_configs::remove_directive(\@location, $directive); insert_location($cupsd_conf_ptr, $location_start, @location); return $success; } sub replace_in_location { # Replace a directive in a given location my ($cupsd_conf_ptr, $path, $olddirective, $newdirective) = @_; my ($location_start, @location) = rip_location($cupsd_conf_ptr, $path); my $success = handle_configs::replace_directive(\@location, $olddirective, $newdirective); insert_location($cupsd_conf_ptr, $location_start, @location); return $success; } sub add_allowed_host { # Add a host or network which should get access to the local printer(s) my ($cupsd_conf_ptr, $host) = @_; return (handle_configs::insert_directive($cupsd_conf_ptr, "BrowseAddress $host") and add_to_location($cupsd_conf_ptr, "/", "Allow From $host")); } sub remove_allowed_host { # Remove a host or network which should get access to the local # printer(s) my ($cupsd_conf_ptr, $host) = @_; return (handle_configs::remove_directive($cupsd_conf_ptr, "BrowseAddress $host") and remove_from_location($cupsd_conf_ptr, "/", "Allow From $host")); } sub replace_allowed_host { # Remove a host or network which should get access to the local # printer(s) my ($cupsd_conf_ptr, $oldhost, $newhost) = @_; return (handle_configs::replace_directive($cupsd_conf_ptr, "BrowseAddress $oldhost", "BrowseAddress $newhost") and replace_in_location($cupsd_conf_ptr, "/", "Allow From $newhost", "Allow From $newhost")); } sub broadcastaddress { # Determines the broadcast address (for "BrowseAddress" line) for # a given network IP my ($address) = @_; if ($address =~ /^\d+\.\*$/) { $address =~ s/\*$/255.255.255/; } elsif ($address =~ /^\d+\.\d+\.\*$/) { $address =~ s/\*$/255.255/; } elsif ($address =~ /^\d+\.\d+\.\d+\.\*$/) { $address =~ s/\*$/255/; } elsif ($address =~ m!^(\d+)\.(\d+)\.(\d+)\.(\d+)/(\d+)$!) { my $numadr = ($1 << 24) + ($2 << 16) + ($3 << 8) + $4; my $mask = ((1 << $5) - 1) << (32 - $5); my $broadcast = $numadr | (~$mask); $address = (($broadcast & (255 << 24)) >> 24) . '.' . (($broadcast & (255 << 16)) >> 16) . '.' . (($broadcast & (255 << 8)) >> 8) . '.' . ($broadcast & 255); } elsif ($address =~ m!^(\d+)\.(\d+)\.(\d+)\.(\d+)/(\d+)\.(\d+)\.(\d+)\.(\d+)$!) { my $numadr = ($1 << 24) + ($2 << 16) + ($3 << 8) + $4; my $mask = ($5 << 24) + ($6 << 16) + ($7 << 8) + $8; my $broadcast = $numadr | (~$mask); $address = (($broadcast & (255 << 24)) >> 24) . '.' . (($broadcast & (255 << 16)) >> 16) . '.' . (($broadcast & (255 << 8)) >> 8) . '.' . ($broadcast & 255); } return $address; } sub networkaddress { # Guesses a network address for a given broadcast address my ($address) = @_; if ($address =~ /\.255$/) { while ($address =~ s/\.255$//) {}; $address .= ".*"; } return $address; } sub localprintersshared { # Do we broadcast our local printers my ($printer) = @_; return ($printer->{cupsconfig}{keys}{Browsing} !~ /off/i && $printer->{cupsconfig}{keys}{BrowseInterval} != 0 && $#{$printer->{cupsconfig}{keys}{BrowseAddress}} >= 0); } sub remotebroadcastsaccepted { # Do we accept broadcasts from remote CUPS servers? my ($printer) = @_; # Is browsing not turned on at all? if ($printer->{cupsconfig}{keys}{Browsing} =~ /off/i) { return 0; } # No "BrowseDeny" lines at all if ($#{$printer->{cupsconfig}{keys}{BrowseDeny}} < 0) { return 1; } my $havedenyall = join('', @{$printer->{cupsconfig}{keys}{BrowseDeny}}) =~ /All/im; my $havedenylocal = join('', @{$printer->{cupsconfig}{keys}{BrowseDeny}}) =~ /\@LOCAL/im; my $orderallowdeny = $printer->{cupsconfig}{keys}{BrowseOrder} =~ /allow\s*,\s*deny/i; my $haveallowremote = 0; foreach my $allowline (@{$printer->{cupsconfig}{keys}{BrowseAllow}}) { next if $allowline =~ /^\s*(localhost|0*127\.0+\.0+\.0*1|none)\s*$/i; $haveallowremote = 1; } # A line denying all (or at least the all LANs) together with the order # "allow,deny" or without "BrowseAllow" lines (which allow the # broadcasts of at least one remote resource). if (($havedenyall || $havedenylocal) && ($orderallowdeny || !$haveallowremote)) { return 0; } return 1; } sub clientnetworks { # Determine the client networks to which the printers will be # shared If the configuration is supported by our simplified # interface ("Deny From All", "Order Deny,Allow", "Allow From ..." # lines in "<location /> ... </location>", a "BrowseAddress ..." # line for each "Allow From ..." line), return the list of allowed # client networks ("Allow"/"BrowseAddress" lines), if not, return # the list of all items which are at least one of the # "BrowseAddresse"s or one of the "Allow From" addresses together # with a flag that the setup is not supported. my ($printer) = @_; # Check for a "Deny From All" line my $havedenyfromall = (join('', @{$printer->{cupsconfig}{root}{DenyFrom}}) =~ /All/im ? 1 : 0); # Check for "Deny From XXX" with XXX != All my $havedenyfromnotall = ($#{$printer->{cupsconfig}{root}{DenyFrom}} - $havedenyfromall < 0 ? 0 : 1); # Check for a "BrowseDeny All" line my $havebrowsedenyall = (join('', @{$printer->{cupsconfig}{keys}{BrowseDeny}}) =~ /All/im ? 1 : 0); # Check for "BrowseDeny XXX" with XXX != All my $havebrowsedenynotall = ($#{$printer->{cupsconfig}{keys}{BrowseDeny}} - $havebrowsedenyall < 0 ? 0 : 1); my @sharehosts; my $haveallowfromlocalhost = 0; my $haveallowedhostwithoutbrowseaddress = 0; my $haveallowedhostwithoutbrowseallow = 0; # Go through all "Allow From" lines foreach my $line (@{$printer->{cupsconfig}{root}{AllowFrom}}) { if ($line =~ /^\s*(localhost|0*127\.0+\.0+\.0*1)\s*$/i) { # Line pointing to localhost $haveallowfromlocalhost = 1; } elsif ($line =~ /^\s*(none)\s*$/i) { # Skip "Allow From None" lines } elsif (!member($line, @sharehosts)) { # Line pointing to remote server push(@sharehosts, $line); if (!member(broadcastaddress($line), @{$printer->{cupsconfig}{keys}{BrowseAddress}})) { $haveallowedhostwithoutbrowseaddress = 1; } if (!member($line, @{$printer->{cupsconfig}{keys}{BrowseAllow}})) { $haveallowedhostwithoutbrowseallow = 1; } } } my $havebrowseaddresswithoutallowedhost = 0; # Go through all "BrowseAdress" lines foreach my $line (@{$printer->{cupsconfig}{keys}{BrowseAddress}}) { if ($line =~ /^\s*(localhost|0*127\.0+\.0+\.0*1)\s*$/i) { # Skip lines pointing to localhost } elsif ($line =~ /^\s*(none)\s*$/i) { # Skip "Allow From None" lines } elsif (!member($line, map { broadcastaddress($_) } @sharehosts)) { # Line pointing to remote server push(@sharehosts, networkaddress($line)); if ($printer->{cupsconfig}{localprintersshared}) { $havebrowseaddresswithoutallowedhost = 1; } } } my $havebrowseallowwithoutallowedhost = 0; # Go through all "BrowseAllow" lines foreach my $line (@{$printer->{cupsconfig}{keys}{BrowseAllow}}) { if ($line =~ /^\s*(localhost|0*127\.0+\.0+\.0*1)\s*$/i) { # Skip lines pointing to localhost } elsif ($line =~ /^\s*(none)\s*$/i) { # Skip "BrowseAllow None" lines } elsif (!member($line, @sharehosts)) { # Line pointing to remote server push(@sharehosts, $line); #$havebrowseallowwithoutallowedhost = 1; } } my $configunsupported = (!$havedenyfromall || $havedenyfromnotall || !$havebrowsedenyall || $havebrowsedenynotall || !$haveallowfromlocalhost || $haveallowedhostwithoutbrowseaddress || $havebrowseaddresswithoutallowedhost || $haveallowedhostwithoutbrowseallow || $havebrowseallowwithoutallowedhost); return $configunsupported, @sharehosts; } sub makesharehostlist { # Human-readable strings for hosts onto which the local printers # are shared my ($printer) = @_; my @sharehostlist; my %sharehosthash; foreach my $host (@{$printer->{cupsconfig}{clientnetworks}}) { if ($host =~ /\@LOCAL/i) { $sharehosthash{$host} = N("Local network(s)"); } elsif ($host =~ /\@IF\((.*)\)/i) { $sharehosthash{$host} = N("Interface \"%s\"", $1); } elsif ($host =~ m!(/|^\*|\*$|^\.)!) { $sharehosthash{$host} = N("Network %s", $host); } else { $sharehosthash{$host} = N("Host %s", $host); } push(@sharehostlist, $sharehosthash{$host}); } my %sharehosthash_inv = reverse %sharehosthash; return { list => \@sharehostlist, hash => \%sharehosthash, invhash => \%sharehosthash_inv }; } sub makebrowsepolllist { # Human-readable strings for hosts from which the print queues are # polled my ($printer) = @_; my @browsepolllist; my %browsepollhash; foreach my $host (@{$printer->{cupsconfig}{BrowsePoll}}) { my ($ip, $port); if ($host =~ /^([^:]+):([^:]+)$/) { $ip = $1; $port = $2; } else { $ip = $host; $port = '631'; } $browsepollhash{$host} = N("%s (Port %s)", $ip, $port); push(@browsepolllist, $browsepollhash{$host}); } my %browsepollhash_inv = reverse %browsepollhash; return { list => \@browsepolllist, hash => \%browsepollhash, invhash => \%browsepollhash_inv }; } sub is_network_ip { # Determine whwther the given string is a valid network IP my ($address) = @_; $address =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ || $address =~ /^(\d+\.){1,3}\*$/ || $address =~ m!^(\d+)\.(\d+)\.(\d+)\.(\d+)/(\d+)$! || $address =~ m!^(\d+)\.(\d+)\.(\d+)\.(\d+)/(\d+)\.(\d+)\.(\d+)\.(\d+)$!; } sub read_cups_config { # Read the information relevant to the printer sharing dialog from # the CUPS configuration my ($printer) = @_; # From /etc/cups/cupsd.conf # Keyword "Browsing" $printer->{cupsconfig}{keys}{Browsing} = handle_configs::read_unique_directive($printer->{cupsconfig}{cupsd_conf}, 'Browsing', 'On'); # Keyword "BrowseInterval" $printer->{cupsconfig}{keys}{BrowseInterval} = handle_configs::read_unique_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseInterval', '30'); # Keyword "BrowseAddress" @{$printer->{cupsconfig}{keys}{BrowseAddress}} = handle_configs::read_directives($printer->{cupsconfig}{cupsd_conf}, 'BrowseAddress'); # Keyword "BrowseAllow" @{$printer->{cupsconfig}{keys}{BrowseAllow}} = handle_configs::read_directives($printer->{cupsconfig}{cupsd_conf}, 'BrowseAllow'); # Keyword "BrowseDeny" @{$printer->{cupsconfig}{keys}{BrowseDeny}} = handle_configs::read_directives($printer->{cupsconfig}{cupsd_conf}, 'BrowseDeny'); # Keyword "BrowseOrder" $printer->{cupsconfig}{keys}{BrowseOrder} = handle_configs::read_unique_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseOrder', 'deny,allow'); # Keyword "BrowsePoll" (needs "Browsing On") if ($printer->{cupsconfig}{keys}{Browsing} !~ /off/i) { @{$printer->{cupsconfig}{BrowsePoll}} = handle_configs::read_directives($printer->{cupsconfig}{cupsd_conf}, 'BrowsePoll'); } # Root location @{$printer->{cupsconfig}{rootlocation}} = read_location($printer->{cupsconfig}{cupsd_conf}, '/'); # Keyword "Allow from" @{$printer->{cupsconfig}{root}{AllowFrom}} = handle_configs::read_directives($printer->{cupsconfig}{rootlocation}, 'Allow From'); # Remove the IPs pointing to the local machine my @localips = printer::detect::getIPsOfLocalMachine(); @{$printer->{cupsconfig}{root}{AllowFrom}} = grep { !member($_, @localips) } @{$printer->{cupsconfig}{root}{AllowFrom}}; # Keyword "Deny from" @{$printer->{cupsconfig}{root}{DenyFrom}} = handle_configs::read_directives($printer->{cupsconfig}{rootlocation}, 'Deny From'); # Keyword "Order" $printer->{cupsconfig}{root}{Order} = handle_configs::read_unique_directive($printer->{cupsconfig}{rootlocation}, 'Order', 'Deny,Allow'); # Widget settings # Local printers available to other machines? $printer->{cupsconfig}{localprintersshared} = localprintersshared($printer); # This machine is accepting printers shared by remote machines? $printer->{cupsconfig}{remotebroadcastsaccepted} = remotebroadcastsaccepted($printer); # To which machines are the local printers available? ($printer->{cupsconfig}{customsharingsetup}, @{$printer->{cupsconfig}{clientnetworks}}) = clientnetworks($printer); } sub write_cups_config { # Write the information edited via the printer sharing dialog into # the CUPS configuration my ($printer) = @_; # Local printers available to other machines? if ($printer->{cupsconfig}{localprintersshared}) { handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'Browsing On'); if ($printer->{cupsconfig}{keys}{BrowseInterval} == 0) { handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseInterval 30'); } } else { handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseInterval 0'); } # This machine is accepting printers shared by remote machines? if ($printer->{cupsconfig}{remotebroadcastsaccepted}) { handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'Browsing On'); if (!$printer->{cupsconfig}{customsharingsetup}) { # If we broadcast our printers, let's accept the broadcasts # from the machines to which we broadcast handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseDeny All'); handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseOrder Deny,Allow'); } } else { if ($printer->{cupsconfig}{localprintersshared} || $#{$printer->{cupsconfig}{BrowsePoll}} >= 0) { # Deny all broadcasts, but leave all "BrowseAllow" lines # untouched handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseDeny All'); handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseOrder Allow,Deny'); } else { # We also do not share printers, if we also do not # "BrowsePoll", we turn browsing off to do not need to deal # with any addresses handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'Browsing Off'); } } # To which machines are the local printers available? if (!$printer->{cupsconfig}{customsharingsetup}) { my @localips = printer::detect::getIPsOfLocalMachine(); # root location block @{$printer->{cupsconfig}{rootlocation}} = "<Location />\n" . "Order Deny,Allow\n" . "Deny From All\n" . "Allow From 127.0.0.1\n" . (@localips ? "Allow From " . join("\nAllow From ", @localips) . "\n" : "") . ($printer->{cupsconfig}{localprintersshared} && $#{$printer->{cupsconfig}{clientnetworks}} >= 0 ? "Allow From " . join("\nAllow From ", grep { !member($_, @localips) } @{$printer->{cupsconfig}{clientnetworks}}) . "\n" : "") . "</Location>\n"; my ($location_start, @_location) = rip_location($printer->{cupsconfig}{cupsd_conf}, "/"); insert_location($printer->{cupsconfig}{cupsd_conf}, $location_start, @{$printer->{cupsconfig}{rootlocation}}); # "BrowseAddress" lines if ($#{$printer->{cupsconfig}{clientnetworks}} >= 0) { handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseAddress ' . join("\nBrowseAddress ", map { broadcastaddress($_) } @{$printer->{cupsconfig}{clientnetworks}})); } else { handle_configs::comment_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseAddress') } # Set "BrowseAllow" lines if ($#{$printer->{cupsconfig}{clientnetworks}} >= 0) { handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseAllow ' . join("\nBrowseAllow ", @{$printer->{cupsconfig}{clientnetworks}})); } else { handle_configs::comment_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowseAllow'); } } # Set "BrowsePoll" lines if ($#{$printer->{cupsconfig}{BrowsePoll}} >= 0) { handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowsePoll ' . join("\nBrowsePoll ", @{$printer->{cupsconfig}{BrowsePoll}})); # "Browsing" must be on for "BrowsePoll" to work handle_configs::set_directive($printer->{cupsconfig}{cupsd_conf}, 'Browsing On'); } else { handle_configs::comment_directive($printer->{cupsconfig}{cupsd_conf}, 'BrowsePoll'); } } sub clean_cups_config { # Clean $printer data structure from all settings not related to # the CUPS printer sharing dialog my ($printer) = @_; delete $printer->{cupsconfig}{keys}; delete $printer->{cupsconfig}{root}; delete $printer->{cupsconfig}{cupsd_conf}; delete $printer->{cupsconfig}{rootlocation}; } #---------------------------------------------------------------------- # Handling of /etc/cups/client.conf sub read_client_conf() { return (0, undef) if (! -r "$::prefix/etc/cups/client.conf"); my @client_conf = cat_("$::prefix/etc/cups/client.conf"); my @servers = handle_configs::read_directives(\@client_conf, "ServerName"); return (@servers > 0, $servers[0]); # If there is more than one entry in client.conf, # the first one counts. } sub write_client_conf { my ($daemonless_cups, $remote_cups_server) = @_; # Create the directory for client.conf if needed (-d "$::prefix/etc/cups/" ) || mkdir("$::prefix/etc/cups/") || return 1; my (@client_conf) = cat_("$::prefix/etc/cups/client.conf"); if ($daemonless_cups) { handle_configs::set_directive(\@client_conf, "ServerName $remote_cups_server"); } else { handle_configs::comment_directive(\@client_conf, "ServerName"); } output("$::prefix/etc/cups/client.conf", @client_conf); } #---------------------------------------------------------------------- sub read_printers_conf { my ($printer) = @_; my $current; #- read /etc/cups/printers.conf file. #- according to this code, we are now using the following keys for each queues. #- DeviceURI > lpd://printer6/lp #- Info > Info Text #- Location > Location Text #- State > Idle|Stopped #- Accepting > Yes|No open(my $PRINTERS, "$::prefix/etc/cups/printers.conf") or return; local $_; while (<$PRINTERS>) { chomp; /^\s*#/ and next; if (/^\s*<(?:DefaultPrinter|Printer)\s+([^>]*)>/) { $current = { mode => 'cups', QUEUE => $1, } } elsif (m!\s*</Printer>!) { $current->{QUEUE} && $current->{DeviceURI} or next; #- minimal check of synthax. add2hash($printer->{configured}{$current->{QUEUE}} ||= {}, $current); $current = undef } elsif (/\s*(\S*)\s+(.*)/) { $current->{$1} = $2 } } close $PRINTERS; #- assume this printing system. $printer->{SPOOLER} ||= 'cups'; } sub get_direct_uri() { #- get the local printer to access via a Device URI. my @direct_uri; open(my $F, ($::testing ? $::prefix : "chroot $::prefix/ ") . "/usr/sbin/lpinfo -v |"); local $_; while (<$F>) { /^(direct|usb|serial)\s+(\S*)/ and push @direct_uri, $2; } close $F; @direct_uri; } sub checkppd { # Check whether the PPD file is valid my ($printer, $ppdfile) = @_; return 1 if $printer->{SPOOLER} ne "cups"; return run_program::rooted($::prefix, "cupstestppd", "-q", $ppdfile); } sub installppd { # Install the PPD file in /usr/share/cups/model/printerdrake/ my ($printer, $ppdfile) = @_; return "" if !$ppdfile; # Install PPD file mkdir_p("$::prefix/usr/share/cups/model/printerdrake"); # "cp_f()" is broken, it hangs infinitely # cp_f($ppdfile, "$::prefix/usr/share/cups/model/printerdrake"); run_program::rooted($::prefix, "cp", "-f", $ppdfile, "$::prefix/usr/share/cups/model/printerdrake"); $ppdfile =~ s!^(.*)(/[^/]+)$!/usr/share/cups/model/printerdrake$2!; chmod 0644, "$::prefix$ppdfile"; # Restart CUPS to register new PPD file printer::services::restart("cups") if $printer->{SPOOLER} eq "cups"; # Re-read printer database %thedb = (); read_printer_db($printer, $printer->{SPOOLER}); # Return description string of the PPD file my $ppdentry = get_descr_from_ppdfile($printer, $ppdfile); return $ppdentry; } sub clean_manufacturer_name { my ($make) = @_; # Clean some manufacturer's names so that every manufacturer has only # one entry in the tree list $make =~ s/^CANON\W.*$/CANON/i; $make =~ s/^LEXMARK.*$/LEXMARK/i; $make =~ s/^HEWLETT?[\s\-]*PACKARD/HP/i; $make =~ s/^SEIKO[\s\-]*EPSON/EPSON/i; $make =~ s/^KYOCERA[\s\-]*MITA/KYOCERA/i; $make =~ s/^CITOH/C.ITOH/i; $make =~ s/^OKI(|[\s\-]*DATA)\s*$/OKIDATA/i; $make =~ s/^(SILENTWRITER2?|COLORMATE)/NEC/i; $make =~ s/^(XPRINT|MAJESTIX)/XEROX/i; $make =~ s/^QMS-PS/QMS/i; $make =~ s/^(PERSONAL|LASERWRITER)/APPLE/i; $make =~ s/^DIGITAL/DEC/i; $make =~ s/\s+Inc\.//i; $make =~ s/\s+Corp\.//i; $make =~ s/\s+SA\.//i; $make =~ s/\s+S\.\s*A\.//i; $make =~ s/\s+Ltd\.//i; $make =~ s/\s+International//i; $make =~ s/\s+Int\.//i; return uc($make); } sub ppd_entry_str { my ($mf, $descr, $lang) = @_; my ($model, $driver); if ($descr) { # Apply the beautifying rules of poll_ppd_base if ($descr =~ /Foomatic \+ Postscript/) { $descr =~ s/Foomatic \+ Postscript/PostScript/; } elsif ($descr =~ /Foomatic/i) { $descr =~ s/Foomatic/GhostScript/i; } elsif ($descr =~ /CUPS\+Gimp-Print/i) { $descr =~ s/CUPS\+Gimp-Print/CUPS + Gimp-Print/i; } elsif ($descr =~ /Series CUPS/i) { $descr =~ s/Series CUPS/Series, CUPS/i; } elsif ($descr !~ /(PostScript|GhostScript|CUPS|Foomatic)/i) { $descr .= ", PostScript"; } # Split model and driver $descr =~ s/\s*Series//i; $descr =~ s/\((.*?(PostScript|PS.*).*?)\)/$1/i; if ($descr =~ /^\s*(Generic\s*PostScript\s*Printer)\s*,?\s*(.*)$/i || $descr =~ /^\s*(PostScript\s*Printer)\s*,?\s*(.*)$/i || $descr =~ /^([^,]+[^,\s])\s*,?\s*(Foomatic.*)$/i || $descr =~ /^([^,]+[^,\s])\s*,?\s*(GhostScript.*)$/i || $descr =~ /^([^,]+[^,\s])\s*,?\s*(CUPS.*)$/i || $descr =~ /^([^,]+[^,\s])\s*,?\s+(PS.*)$/i || $descr =~ /^([^,]+[^,\s])\s*,?\s*(\(v?\.?\s*\d\d\d\d\.\d\d\d\).*)$/i || $descr =~ /^([^,]+[^,\s])\s*,?\s*(v\d+\.\d+.*)$/i || $descr =~ /^([^,]+[^,\s])\s*,?\s*(PostScript.*)$/i || $descr =~ /^([^,]+)\s*,?\s*(.+)$/) { $model = $1; $driver = $2; $model =~ s/[\-\s,]+$//; $driver =~ s/\b(PS|PostScript\b)/PostScript/gi; $driver =~ s/(PostScript)(.*)(PostScript)/$1$2/i; $driver =~ s/^\s*(\(?v?\.?\s*\d\d\d\d\.\d\d\d\)?|v\d+\.\d+)([,\s]*)(.*?)\s*$/$3$2$1/i; $driver =~ s/,\s*\(/ (/g; $driver =~ s/[\-\s,]+$//; $driver =~ s/^[\-\s,]+//; $driver =~ s/\s+/ /g; if ($driver !~ /[a-z]/i) { $driver = "PostScript " . $driver; $driver =~ s/ $//; } } else { # Some PPDs do not have the ", <driver>" part. $model = $descr; $driver = "PostScript"; } } # Remove manufacturer's name from the beginning of the model # name (do not do this with manufacturer names which contain # odd characters) $model =~ s/^$mf[\s\-]+//i if $mf && $mf !~ m![\\/\(\)\[\]\|\.\$\@\%\*\?]!; # Clean some manufacturer's names $mf = clean_manufacturer_name($mf); # Rename Canon "BJC XXXX" models into "BJC-XXXX" so that the # models do not appear twice if ($mf eq "CANON") { $model =~ s/BJC\s+/BJC-/; } # New MF devices from Epson have mis-spelled name in PPD files for # native CUPS drivers of Gimp-Print if ($mf eq "EPSON") { $model =~ s/Stylus CX\-/Stylus CX/; } # Remove the "Oki" from the beginning of the model names of Okidata # printers if ($mf eq "OKIDATA") { $model =~ s/Oki\s+//i; } # Try again to remove manufacturer's name from the beginning of the # model name, this with the cleaned manufacturer name $model =~ s/^$mf[\s\-]+//i if $mf && $mf !~ m![\\/\(\)\[\]\|\.\$\@\%\*\?]!; # Put out the resulting description string uc($mf) . '|' . $model . '|' . $driver . ($lang && " (" . lang::locale_to_main_locale($lang) . ")"); } sub get_descr_from_ppd { my ($printer) = @_; #- if there is no ppd, this means this is a raw queue. if (! -r "$::prefix/etc/cups/ppd/$printer->{OLD_QUEUE}.ppd") { return "|" . N("Unknown model"); } return get_descr_from_ppdfile($printer, "/etc/cups/ppd/$printer->{OLD_QUEUE}.ppd"); } sub get_descr_from_ppdfile { my ($printer, $ppdfile) = @_; my %ppd; # Remove ".gz" from end of file name, so that "catMaybeCompressed" works $ppdfile =~ s/\.gz$//; eval { local $_; foreach (catMaybeCompressed("$::prefix$ppdfile")) { # "OTHERS|Generic PostScript printer|PostScript (en)"; /^\*([^\s:]*)\s*:\s*"([^"]*)"/ and do { $ppd{$1} = $2; next }; /^\*([^\s:]*)\s*:\s*([^\s"]*)/ and do { $ppd{$1} = $2; next }; } }; my $descr = ($ppd{NickName} || $ppd{ShortNickName} || $ppd{ModelName}); my $make = $ppd{Manufacturer}; my $lang = $ppd{LanguageVersion}; my $entry = ppd_entry_str($make, $descr, $lang); if (!$printer->{expert}) { # Remove driver from printer list entry when in recommended mode $entry =~ s/^([^\|]+\|[^\|]+)\|.*$/$1/; } return $entry; } sub ppd_devid_data { my ($ppd) = @_; $ppd = "$::prefix/usr/share/cups/model/$ppd"; my @content; if ($ppd =~ /\.gz$/i) { @content = cat_("$::prefix/bin/zcat $ppd |") or return "", ""; } else { @content = cat_($ppd) or return "", ""; } my ($devidmake, $devidmodel); /^\*Manufacturer:\s*"(.*)"\s*$/ and $devidmake = $1 foreach @content; /^\*Product:\s*"\(?(.*?)\)?"\s*$/ and $devidmodel = $1 foreach @content; return $devidmake, $devidmodel; }