summaryrefslogtreecommitdiffstats
path: root/urpm/download.pm
blob: c6800f73bd354045f1dedb833b2fb38a1d9083d3 (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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
package urpm::download;


use strict;
use urpm::msg;
use urpm::util qw(cat_ basename dirname file_size max member output_safe reduce_pathname);
use bytes ();
use Cwd;
use Exporter;
# perl_checker: require urpm

our @ISA = 'Exporter';
our @EXPORT = qw(get_proxy
	propagate_sync_callback
	sync_file sync_rsync sync_ssh
	set_proxy_config dump_proxy_config
);

#- proxy config file.
our $PROXY_CFG = '/etc/urpmi/proxy.cfg';
my $proxy_config;

#- Timeout for curl connection and wget operations
our $CONNECT_TIMEOUT = 60; #-  (in seconds)


=head1 NAME

urpm::download - download routines for the urpm* tools

=head1 SYNOPSIS

=head1 DESCRIPTION

=over

=cut


sub ftp_http_downloaders() { qw(curl wget prozilla aria2) }

sub available_ftp_http_downloaders() {
    my %binaries = (
	curl => 'curl', 
	wget => 'wget', 
	prozilla => 'proz',
	aria2 => 'aria2c',
    );
    grep { -x "/usr/bin/$binaries{$_}" || -x "/bin/$binaries{$_}" } ftp_http_downloaders();
}

sub metalink_downloaders() { qw(aria2) }

sub available_metalink_downloaders() {
    my %binaries = (
	aria2 => 'aria2c',
    );
    grep { -x "/usr/bin/$binaries{$_}" || -x "/bin/$binaries{$_}" } metalink_downloaders();
}

sub use_metalink {
    my ($urpm, $medium) = @_;

    $medium->{allow_metalink} //= do {
	my $use_metalink = 1;
	preferred_downloader($urpm, $medium, \$use_metalink);
	$use_metalink;
    };
}

my %warned;
sub preferred_downloader {
    my ($urpm, $medium, $use_metalink) = @_;

    my @available = urpm::download::available_ftp_http_downloaders();
    my @metalink_downloaders = urpm::download::available_metalink_downloaders();
    my $metalink_disabled = !$$use_metalink && $medium->{disable_metalink};

    if ($$use_metalink && !$metalink_disabled) {
	#- If metalink is used, only aria2 is available as other downloaders doesn't support metalink
	unshift @available, @metalink_downloaders;
    }
	    
    #- first downloader of @available is the default one
    my $preferred = $available[0];
    my $requested_downloader = requested_ftp_http_downloader($urpm, $medium);
    if ($requested_downloader) {
	if (member($requested_downloader, @available)) {
	    #- use user default downloader if provided and available
	    $preferred = $requested_downloader;
	} elsif ($warned{webfetch_not_available}++ == 0) {
	    $urpm->{log}(N("%s is not available, falling back on %s", $requested_downloader, $preferred));
	}
    }

    if ($$use_metalink && !member($preferred, @metalink_downloaders)) {
	$warned{not_using_metalink}++ or 
	  $urpm->{log}($requested_downloader eq $preferred ? 
		       "not using metalink since requested downloader does not handle it" :
		       "not using metalink since no downloaders handling metalink are available");
	$$use_metalink = 0;
    }
    $preferred;
}

sub parse_http_proxy {
    $_[0] =~ m!^(?:http://)?([^:/]+(:\d+)?)/*$!;
}

#- parses proxy.cfg (private)
sub load_proxy_config () {
    return if defined $proxy_config;
    $proxy_config = {};
    foreach (cat_($PROXY_CFG)) {
	chomp; s/#.*$//; s/^\s*//; s/\s*$//;
	if (/^(?:(.*):\s*)?(ftp_proxy|http_proxy)\s*=\s*(.*)$/) {
	    $proxy_config->{$1 || ''}{$2} = $3;
	    next;
	}
	if (/^(?:(.*):\s*)?proxy_user\s*=\s*([^:]*)(?::(.*))?$/) {
	    $proxy_config->{$1 || ''}{user} = $2;
	    $proxy_config->{$1 || ''}{pwd} = $3 if defined $3;
	    next;
	}
	if (/^(?:(.*):\s*)?proxy_user_ask/) {
	    $proxy_config->{$1 || ''}{ask} = 1;
	    next;
	}
    }
}

#- writes proxy.cfg
sub dump_proxy_config () {
    $proxy_config or return 0; #- hasn't been read yet

    my $has_password;

    open my $f, '>', $PROXY_CFG or return 0;
    foreach ('', sort grep { !/^(|cmd_line)$/ } keys %$proxy_config) {
	my $m = $_ eq '' ? '' : "$_:";
	my $p = $proxy_config->{$_};
	foreach (qw(http_proxy ftp_proxy)) {
	    if (defined $p->{$_} && $p->{$_} ne '') {
		print $f "$m$_=$p->{$_}\n";
		$has_password ||= hide_password($p->{$_}) ne $p->{$_};
	    }
	}
	if ($p->{ask}) {
	    print $f "${m}proxy_user_ask\n";
	} elsif (defined $p->{user} && $p->{user} ne '') {
	    print $f "${m}proxy_user=$p->{user}:$p->{pwd}\n";
	    $has_password ||= $p->{pwd};
	}
    }
    close $f;
    chmod 0600, $PROXY_CFG if $has_password;
    return 1;
}

#- deletes the proxy configuration for the specified media
sub remove_proxy_media {
    defined $proxy_config and delete $proxy_config->{$_[0] || ''};
}

sub get_proxy_ {
    my ($urpm) = @_;

    -e $PROXY_CFG && !-r $PROXY_CFG and $urpm->{error}(N("can not read proxy settings (not enough rights to read %s)", $PROXY_CFG));

    get_proxy($urpm);
}

=item get_proxy($media)

Reads and loads the proxy.cfg file ;
Returns the global proxy settings (without arguments) or the
proxy settings for the specified media (with a media name as argument)

=cut

sub get_proxy (;$) {
    my ($o_media) = @_; $o_media ||= '';
    load_proxy_config();
    my $p = $proxy_config->{cmd_line}
	|| $proxy_config->{$o_media}
	|| $proxy_config->{''}
	|| {
	    http_proxy => undef,
	    ftp_proxy => undef,
	    user => undef,
	    pwd => undef,
	};
    if ($p->{ask} && ($p->{http_proxy} || $p->{ftp_proxy}) && !$p->{user}) {
	our $PROMPT_PROXY;
	unless (defined $PROMPT_PROXY) {
	    require urpm::prompt;
	    $PROMPT_PROXY = new urpm::prompt(
		N("Please enter your credentials for accessing proxy\n"),
		[ N("User name:"), N("Password:") ],
		undef,
		[ 0, 1 ],
	    );
	}
	($p->{user}, $p->{pwd}) = $PROMPT_PROXY->prompt;
    }
    $p;
}

#- copies the settings for proxies from the command line to media named $media
#- and writes the proxy.cfg file (used when adding new media)
sub copy_cmd_line_proxy {
    my ($media) = @_;
    return unless $media;
    load_proxy_config();
    if (defined $proxy_config->{cmd_line}) {
	$proxy_config->{$media} = $proxy_config->{cmd_line};
	dump_proxy_config();
    } else {
	#- use default if available
	$proxy_config->{$media} = $proxy_config->{''};
    }
}

=item set_cmdline_proxy(%h)

Overrides the config file proxy settings with values passed via command-line

=cut

sub set_cmdline_proxy {
    my (%h) = @_;
    load_proxy_config();
    $proxy_config->{cmd_line} ||= {
	http_proxy => undef,
	ftp_proxy => undef,
	user => undef,
	pwd => undef,
    };
    $proxy_config->{cmd_line}{$_} = $h{$_} foreach keys %h;
}

=item set_proxy_config($key, $value, $o_media)

Changes permanently the proxy settings

=cut

sub set_proxy_config {
    my ($key, $value, $o_media) = @_;
    $proxy_config->{$o_media || ''}{$key} = $value;
}

#- set up the environment for proxy usage for the appropriate tool.
#- returns an array of command-line arguments for wget or curl.
sub set_proxy {
    my ($proxy) = @_;

    my $p = $proxy->{proxy};
    defined $p->{http_proxy} || defined $p->{ftp_proxy} or return;

    my @res;
    if ($proxy->{type} =~ /\bwget\b/) {
	if (defined $p->{http_proxy}) {
	    $ENV{http_proxy} = $p->{http_proxy} =~ /^http:/
	      ? $p->{http_proxy} : "http://$p->{http_proxy}";
	}
	$ENV{ftp_proxy} = $p->{ftp_proxy} if defined $p->{ftp_proxy};
	@res = ("--proxy-user=$p->{user}", "--proxy-passwd=$p->{pwd}")
	  if defined $p->{user} && defined $p->{pwd};
    } elsif ($proxy->{type} =~ /\bcurl\b/) {
	push @res, ('-x', $p->{http_proxy}) if defined $p->{http_proxy};
	push @res, ('-x', $p->{ftp_proxy}) if defined $p->{ftp_proxy};
	push @res, ('-U', "$p->{user}:$p->{pwd}")
	  if defined $p->{user} && defined $p->{pwd};
	push @res, '-H', 'Pragma:' if @res;
    } elsif ($proxy->{type} =~ /\baria2\b/) {
	if (my ($http_proxy) = $p->{http_proxy} && parse_http_proxy($p->{http_proxy})) {
	    my $allproxy = $p->{user}; 
	    $allproxy .= ":" . $p->{pwd} if $p->{pwd}; 
	    $allproxy .= "@" if $p->{user};
	    $allproxy .= $http_proxy;
	    @res = ("--all-proxy=http://$allproxy");
	}
    } else { 
	die N("Unknown webfetch `%s' !!!\n", $proxy->{type});
    }
    @res;
}

sub _error_msg {
    my ($name) = @_;

    my $msg = $? & 127 ? N("%s failed: exited with signal %d", $name, $? & 127) :
                         N("%s failed: exited with %d", $name, $? >> 8);
    "$msg\n";
}

sub _error {
    my ($name) = @_;
    die _error_msg($name);
}

sub hide_password {
    my ($url) = @_;
    $url =~ s|([^:]*://[^/:\@]*:)[^/:\@]*(\@.*)|$1xxxx$2|; #- if needed...
    $url;
}

sub propagate_sync_callback {
    my $options = shift;
    if (ref($options) && $options->{callback}) {
	my $mode = shift;
	if ($mode =~ /^(?:start|progress|end)$/) {
	    my $file = shift;
	    return $options->{callback}($mode, hide_password($file), @_);
	} else {
	    return $options->{callback}($mode, @_);
	}
    }
}

sub sync_file {
    my $options = shift;
    foreach (@_) {
	propagate_sync_callback($options, 'start', $_);
	require urpm::util;
	urpm::util::copy($_, ref($options) ? $options->{dir} : $options)
	    or die N("copy failed");
	propagate_sync_callback($options, 'end', $_);
    }
}

sub sync_wget {
    -x "/usr/bin/wget" or die N("wget is missing\n");
    my $options = shift;
    $options = { dir => $options } if !ref $options;
    #- force download to be done in cachedir to avoid polluting cwd.
    (my $cwd) = getcwd() =~ /(.*)/;
    chdir $options->{dir};
    my ($buf, $total, $file) = ('', undef, undef);
    my $wget_command = join(" ", map { "'$_'" }
	#- construction of the wget command-line
	"/usr/bin/wget",
	($options->{'limit-rate'} ? "--limit-rate=$options->{'limit-rate'}" : @{[]}),
	($options->{resume} ? "--continue" : "--force-clobber"),
	($options->{proxy} ? set_proxy({ type => "wget", proxy => $options->{proxy} }) : @{[]}),
	($options->{retry} ? ('-t', $options->{retry}) : @{[]}),
	($options->{callback} ? ("--progress=bar:force", "-o", "-") :
	    $options->{quiet} ? "-q" : @{[]}),
	"--retr-symlinks",
	($options->{"no-certificate-check"} ? "--no-check-certificate" : @{[]}),
	"--timeout=$CONNECT_TIMEOUT",
	(defined $options->{'wget-options'} ? split /\s+/, $options->{'wget-options'} : @{[]}),
	'-P', $options->{dir},
	@_
    ) . " |";
    $options->{debug} and $options->{debug}($wget_command);
    local $ENV{LC_ALL} = 'C';
    my $wget_pid = open(my $wget, $wget_command);
    local $/ = \1; #- read input by only one char, this is slow but very nice (and it works!).
    local $_;
    while (<$wget>) {
	$buf .= $_;
	if ($_ eq "\r" || $_ eq "\n") {
	    if ($options->{callback}) {
		if ($buf =~ /^--(\d\d\d\d-\d\d-\d\d )?\d\d:\d\d:\d\d--\s+(\S.*)\n/ms) {
		    my $file_ = $2;
		    if ($file && $file ne $file_) {
			propagate_sync_callback($options, 'end', $file);
			undef $file;
		    }
		    ! defined $file and propagate_sync_callback($options, 'start', $file = $file_);
		} elsif (defined $file && ! defined $total && ($buf =~ /==>\s+RETR/ || $buf =~ /200 OK$/)) {
		    $total = '';
		} elsif ($buf =~ /^Length:\s*(\d\S*)/) {
		    $total = $1;
		} elsif (defined $total && $buf =~ m!^\s*(\d+)%.*\s+(\S+/s)\s+((ETA|eta)\s+(.*?)\s*)?[\r\n]$!ms) {
		    my ($percent, $speed, $eta) = ($1, $2, $5);
		    if (propagate_sync_callback($options, 'progress', $file, $percent, $total, $eta, $speed) eq 'canceled') {
			kill 15, $wget_pid;
			close $wget;
			return;
		    }
		    if ($_ eq "\n") {
			propagate_sync_callback($options, 'end', $file);
			($total, $file) = (undef, undef);
		    }
		}
	    } else {
		$options->{quiet} or print STDERR $buf;
	    }
	    $buf = '';
	}
    }
    $file and propagate_sync_callback($options, 'end', $file);
    chdir $cwd;
    close $wget or _error('wget');
}

sub sync_curl {
    -x "/usr/bin/curl" or die N("curl is missing\n");
    my $options = shift;
    $options = { dir => $options } if !ref $options;
    if (defined $options->{'limit-rate'} && $options->{'limit-rate'} =~ /\d$/) {
	#- use bytes by default
	$options->{'limit-rate'} .= 'B';
    }
    #- force download to be done in cachedir to avoid polluting cwd,
    #- however for curl, this is mandatory.
    (my $cwd) = getcwd() =~ /(.*)/;
    chdir($options->{dir});
    my (@ftp_files, @other_files);
    foreach (@_) {
	my ($proto, $nick, $rest) = m,^(http|ftp)://([^:/]+):(.*),,;
	if ($nick) { #- escape @ in user names
	    $nick =~ s/@/%40/;
	    $_ = "$proto://$nick:$rest";
	}
	if (m|^ftp://.*/([^/]*)$| && file_size($1) > 8192) { #- manage time stamp for large file only
	    push @ftp_files, $_;
	} else {
	    push @other_files, $_;
	}
    }
    if (@ftp_files) {
	my ($cur_ftp_file, %ftp_files_info);
	local $_;

	eval { require Date::Manip };

	#- prepare to get back size and time stamp of each file.
	my $cmd = join(" ", map { "'$_'" } "/usr/bin/curl",
	    "-q", # don't read .curlrc; some toggle options might interfer
	    ($options->{'limit-rate'} ? ("--limit-rate", $options->{'limit-rate'}) : @{[]}),
	    ($options->{proxy} ? set_proxy({ type => "curl", proxy => $options->{proxy} }) : @{[]}),
	    ($options->{retry} ? ('--retry', $options->{retry}) : @{[]}),
	    "--stderr", "-", # redirect everything to stdout
	    "--disable-epsv",
	    "--connect-timeout", $CONNECT_TIMEOUT,
	    "-s", "-I",
	    "--anyauth",
	    (defined $options->{'curl-options'} ? split /\s+/, $options->{'curl-options'} : @{[]}),
	    @ftp_files);
	$options->{debug} and $options->{debug}($cmd);
	open my $curl, "$cmd |";
	while (<$curl>) {
	    if (/Content-Length:\s*(\d+)/) {
		!$cur_ftp_file || exists($ftp_files_info{$cur_ftp_file}{size})
		    and $cur_ftp_file = shift @ftp_files;
		$ftp_files_info{$cur_ftp_file}{size} = $1;
	    }
	    if (/Last-Modified:\s*(.*)/) {
		!$cur_ftp_file || exists($ftp_files_info{$cur_ftp_file}{time})
		    and $cur_ftp_file = shift @ftp_files;
		eval {
		    $ftp_files_info{$cur_ftp_file}{time} = Date::Manip::ParseDate($1);
		};
	    }
	}
	close $curl or _error('curl');

	#- now analyse size and time stamp according to what already exists here.
	if (@ftp_files) {
	    #- re-insert back shifted element of ftp_files, because curl output above
	    #- has not been parsed correctly, so in doubt download them all.
	    push @ftp_files, keys %ftp_files_info;
	} else {
	    #- for that, it should be clear ftp_files is empty...
	    #- elsewhere, the above work was useless.
	    foreach (keys %ftp_files_info) {
		my ($lfile) = m|/([^/]*)$| or next; #- strange if we can't parse it correctly.
		my $ltime = eval { Date::Manip::ParseDate(scalar gmtime((stat $1)[9])) };
		$ltime && -s $lfile == $ftp_files_info{$_}{size} && $ftp_files_info{$_}{time} eq $ltime
		    or push @ftp_files, $_;
	    }
	}
    }
    # Indicates whether this option is available in our curl
    our $location_trusted;
    if (!defined $location_trusted) {
	$location_trusted = `/usr/bin/curl -h` =~ /location-trusted/ ? 1 : 0;
    }
    #- http files (and other files) are correctly managed by curl wrt conditional download.
    #- options for ftp files, -R (-O <file>)*
    #- options for http files, -R (-O <file>)*
    my $result;
    if (my @all_files = (
	    (map { ("-O", $_) } @ftp_files),
	    (map { m|/| ? ("-O", $_) : @{[]} } @other_files)))
    {
	my @l = (@ftp_files, @other_files);
	my $cmd = join(" ", map { "'$_'" } "/usr/bin/curl",
	    "-q", # don't read .curlrc; some toggle options might interfer
	    ($options->{'limit-rate'} ? ("--limit-rate", $options->{'limit-rate'}) : @{[]}),
	    ($options->{resume} ? ("--continue-at", "-") : @{[]}),
	    ($options->{proxy} ? set_proxy({ type => "curl", proxy => $options->{proxy} }) : @{[]}),
	    ($options->{retry} ? ('--retry', $options->{retry}) : @{[]}),
	    ($options->{quiet} ? "-s" : @{[]}),
	    ($options->{"no-certificate-check"} ? "-k" : @{[]}),
	    $location_trusted ? "--location-trusted" : @{[]},
	    "-R",
	    "-f",
	    "--disable-epsv",
	    "--connect-timeout", $CONNECT_TIMEOUT,
	    "--anyauth",
	    (defined $options->{'curl-options'} ? split /\s+/, $options->{'curl-options'} : @{[]}),
	    "--stderr", "-", # redirect everything to stdout
	    @all_files);
	$options->{debug} and $options->{debug}($cmd);
	$result = _curl_action($cmd, $options, @l);
    }
    chdir $cwd;
    $result;
}

sub _curl_action {
    my ($cmd, $options, @l) = @_;
    
	my ($buf, $file); $buf = '';
	my $curl_pid = open(my $curl, "$cmd |");
	local $/ = \1; #- read input by only one char, this is slow but very nice (and it works!).
	local $_;
	while (<$curl>) {
	    $buf .= $_;
	    if ($_ eq "\r" || $_ eq "\n") {
		if ($options->{callback}) {
		    unless (defined $file) {
			$file = shift @l;
			propagate_sync_callback($options, 'start', $file);
		    }
		    if (my ($percent, $total, $eta, $speed) = $buf =~ /^\s*(\d+)\s+(\S+)[^\r\n]*\s+(\S+)\s+(\S+)\s*[\r\n]$/ms) {
			$speed =~ s/^-//;
			if (propagate_sync_callback($options, 'progress', $file, $percent, $total, $eta, $speed) eq 'canceled') {
			    kill 15, $curl_pid;
			    close $curl;
			    die N("curl failed: download canceled\n");
			}
			#- this checks that download has actually started
			if ($_ eq "\n"
			    && !($speed eq 0 && $percent == 100 && index($eta, '--') >= 0) #- work around bug 13685
			) {
			    propagate_sync_callback($options, 'end', $file);
			    $file = undef;
			}
		    } elsif ($buf =~ /^curl:/) { #- likely to be an error reported by curl
			local $/ = "\n";
			chomp $buf;
			propagate_sync_callback($options, 'error', $file, $buf);
		    }
		} else {
		    $options->{quiet} or print STDERR $buf;
		}
		$buf = '';
	    }
	}
	close $curl or _error('curl');
}

sub _calc_limit_rate {
    my $limit_rate = $_[0];
    for ($limit_rate) {
	/^(\d+)$/     and $limit_rate = int $1/1024, last;
	/^(\d+)[kK]$/ and $limit_rate = $1, last;
	/^(\d+)[mM]$/ and $limit_rate = 1024*$1, last;
	/^(\d+)[gG]$/ and $limit_rate = 1024*1024*$1, last;
    }
    $limit_rate;
}

sub sync_rsync {
    -x "/usr/bin/rsync" or die N("rsync is missing\n");
    my $options = shift;
    $options = { dir => $options } if !ref $options;
    #- force download to be done in cachedir to avoid polluting cwd.
    (my $cwd) = getcwd() =~ /(.*)/;
    chdir($options->{dir});
    my $limit_rate = _calc_limit_rate($options->{'limit-rate'});
    foreach (@_) {
	my $count = 10; #- retry count on error (if file exists).
	my $basename = basename($_);
	my $file =  m!^rsync://([^/]*::.*)! ? $1 : $_;
	propagate_sync_callback($options, 'start', $file);
	do {
	    local $_;
	    my $buf = '';
	    my $cmd = join(" ", "/usr/bin/rsync",
		($limit_rate ? "--bwlimit=$limit_rate" : @{[]}),
		($options->{quiet} ? qw(-q) : qw(--progress -v --no-human-readable)),
		($options->{compress} ? qw(-z) : @{[]}),
		($options->{ssh} ? qq(-e $options->{ssh}) : 
		   ("--timeout=$CONNECT_TIMEOUT",
		    "--contimeout=$CONNECT_TIMEOUT")),
		qw(--partial --no-whole-file --no-motd --copy-links),
		(defined $options->{'rsync-options'} ? split /\s+/, $options->{'rsync-options'} : @{[]}),
		"'$file' '$options->{dir}' 2>&1");
	    $options->{debug} and $options->{debug}($cmd);
	    open(my $rsync, "$cmd |");
	    local $/ = \1; #- read input by only one char, this is slow but very nice (and it works!).
	    local $_;
	    while (<$rsync>) {
		$buf .= $_;
		if ($_ eq "\r" || $_ eq "\n") {
		    if ($options->{callback}) {
			if (my ($percent, $speed) = $buf =~ /^\s*\d+\s+(\d+)%\s+(\S+)\s+/) {
			    propagate_sync_callback($options, 'progress', $file, $percent, undef, undef, $speed);
			} else {
			    $options->{debug} and $options->{debug}($buf);
			}
		    } else {
			$options->{quiet} or print STDERR $buf;
			$options->{debug} and $options->{debug}($buf);
		    }
		    $buf = '';
		}
	    }
	    close $rsync;
	} while ($? != 0 && --$count > 0 && -e $options->{dir} . "/$basename");
	propagate_sync_callback($options, 'end', $file);
    }
    chdir $cwd;
    $? == 0 or _error('rsync');
}

our $SSH_PATH;
sub _init_ssh_path() {
    foreach (qw(/usr/bin/ssh /bin/ssh)) {
	-x $_ and $SSH_PATH = $_;
	next;
    }
}

#- Don't generate a tmp dir name, so when we restart urpmi, the old ssh
#- connection can be reused
our $SSH_CONTROL_DIR = $ENV{TMP} || $ENV{TMPDIR} || '/tmp';
our $SSH_CONTROL_OPTION;

sub sync_ssh {
    $SSH_PATH or _init_ssh_path();
    $SSH_PATH or die N("ssh is missing\n");
    my $options = shift;
    $options = { dir => $options } if !ref $options;
    unless ($options->{'rsync-options'} =~ /(?:-e|--rsh)\b/) {
	my ($server, $user) = ('', getpwuid($<));
	$_[0] =~ /((?:\w|\.)*):/ and $server = $1;
	$_[0] =~ /((?:\w|-)*)@/ and $user = $1;
	$SSH_CONTROL_OPTION = "-o 'ControlPath $SSH_CONTROL_DIR/ssh-urpmi-$$-%h_%p_%r' -o 'ControlMaster auto'";
	if (start_ssh_master($server, $user)) {
	    $options->{ssh} = qq("$SSH_PATH $SSH_CONTROL_OPTION");
	} else {
	    #- can't start master, use single connection
	    $options->{ssh} = $SSH_PATH;
	}
    }
    sync_rsync($options, @_);
}

sub sync_prozilla {
    -x "/usr/bin/proz" or die N("prozilla is missing\n");
    my $options = shift;
    $options = { dir => $options } if !ref $options;
    #- force download to be done in cachedir to avoid polluting cwd.
    (my $cwd) = getcwd() =~ /(.*)/;
    chdir $options->{dir};
    my $proz_command = join(" ", map { "'$_'" }
	"/usr/bin/proz",
	"--no-curses",
	(defined $options->{'prozilla-options'} ? split /\s+/, $options->{'prozilla-options'} : @{[]}),
	@_
    );
    my $ret = system($proz_command);
    chdir $cwd;
    if ($ret) {
	if ($? == -1) {
	    die N("Couldn't execute prozilla\n");
	} else {
	    _error('prozilla');
	}
    }
}

sub sync_aria2 {
    my ($urpm, $medium, $rel_files, $options) = @_;

    -x "/usr/bin/aria2c" or die N("aria2 is missing\n");

    #- force download to be done in cachedir to avoid polluting cwd.
    (my $cwd) = getcwd() =~ /(.*)/;
    chdir $options->{dir};

    my $stat_file = ($< ? $ENV{HOME} : '/root') . '/.aria2-adaptive-stats';

    my $aria2c_command = join(" ", map { "'$_'" }
	"/usr/bin/aria2c", $options->{debug} ? ('--log', "$options->{dir}/.aria2.log") : @{[]},
	'--auto-file-renaming=false',
	'--ftp-pasv',
	'--summary-interval=0',
	'--follow-metalink=mem',
      $medium->{mirrorlist} ? (
	'--metalink-enable-unique-protocol=true', # do not try to connect to the same server using the same protocol
	 '--metalink-preferred-protocol=http', # try http as first protocol as they're stateless and
	                                       # will put less strain on ie. the ftp servers which connections
	                                       # are statefull for, causing unhappy mirror admins complaining
	                                       # about increase of connections, increasing resource usage.
	'--max-tries=5', # nb: not using $options->{retry}
	'--lowest-speed-limit=20K', "--timeout", 3,
        '--split=3', # maximum number of servers to use for one download
        '--uri-selector=adaptive', "--server-stat-if=$stat_file", "--server-stat-of=$stat_file",
        $options->{is_versioned} ? @{[]} : '--max-file-not-found=9', # number of not found errors on different servers before aborting file download
        '--connect-timeout=6', # $CONNECT_TIMEOUT,
      ) : @{[]},
	'-Z', '-j1',
	($options->{'limit-rate'} ? "--max-download-limit=" . $options->{'limit-rate'} : @{[]}),
	($options->{resume} ? "--continue" : "--allow-overwrite=true"),
	($options->{proxy} ? set_proxy({ type => "aria2", proxy => $options->{proxy} }) : @{[]}),
	($options->{"no-certificate-check"} ? "--check-certificate=false" : @{[]}),
	(defined $options->{'aria2-options'} ? split /\s+/, $options->{'aria2-options'} : @{[]}),
        _create_metalink_($urpm, $medium, $rel_files, $options));

    $options->{debug} and $options->{debug}($aria2c_command);

    local $ENV{LC_ALL} = 'C';
    my $aria2_pid = open(my $aria2, "$aria2c_command |");

    _parse_aria2_output($options, $aria2, $aria2_pid, $medium, $rel_files);

    chdir $cwd;
    if (!close $aria2) {
	my $raw_msg = _error_msg('aria2');
	my $want_retry;
	if (!$options->{is_retry} & $options->{is_versioned}) {
	    $want_retry = 1;
	} else {
	    my $msg = N("Failed to download %s", $rel_files->[0]);
	    $want_retry = $options->{ask_retry} && $options->{ask_retry}($raw_msg, $msg);
	}
	if ($want_retry) {
	    $options->{is_retry}++;
	    $options->{debug} and $options->{debug}("retrying ($options->{is_retry})");
	    goto &sync_aria2;
	}
	die $raw_msg;
    }
}

sub _parse_aria2_output {
    my ($options, $aria2, $aria2_pid, $medium, $rel_files) = @_;

    my ($buf, $_total, $file) = ('', undef, undef);

    local $/ = \1; #- read input by only one char, this is slow but very nice (and it works!).
    local $_;    

    while (<$aria2>) {
	if ($_ eq "\r" || $_ eq "\n") {
	    $options->{debug}("aria2c: $buf") if $options->{debug};
		if ($options->{callback}) {
			if (!defined($file) && @$rel_files) {
				$file = $medium->{mirrorlist} ? 
				  $medium->{mirrorlist} . ': ' . $medium->{'with-dir'} . "/$rel_files->[0]" :
				  "$medium->{url}/$rel_files->[0]";
				propagate_sync_callback($options, 'start', $file)
				  if !$options->{is_retry};
			}
			#parses aria2c: [#1 SIZE:176.0KiB/2.5MiB(6%) CN:3 SPD:256.22KiBs ETA:09s]
    		    if ($buf =~ m!^\[#\d*\s+\S+:([\d\.]+\w*).([\d\.]+\w*)\S([\d]+)\S+\s+\S+\s*([\d\.]+)\s\w*:([\d\.]+\w*)\s\w*:(\d+\w*)\]$!) {
			    my ($total, $percent, $speed, $eta) = ($2, $3, $5, $6);
			    #- $1 = current downloaded size, $4 = connections
		    if (propagate_sync_callback($options, 'progress', $file, $percent, $total, $eta, $speed) eq 'canceled') {
			kill 15, $aria2_pid;
			close $aria2;
			return;
			}
		    }
		    if ($buf =~ m!Download\scomplete:\s/!) {
			propagate_sync_callback($options, 'end', $file);
			shift @$rel_files;
			delete $options->{is_retry};
			$file = undef;			
		    } elsif ($buf =~ /ERR\|(.*)/) {
			propagate_sync_callback($options, 'error', $file, $1);
		    }
	    } else {
		$options->{quiet} or print STDERR "$buf\n";
	    }
	    $buf = '';
	} else {
	    $buf .= $_;
	}
    }
}

sub start_ssh_master {
    my ($server, $user) = @_;
    $server or return 0;
    if (!check_ssh_master($server, $user)) {
	system(qq($SSH_PATH -f -N $SSH_CONTROL_OPTION -M $user\@$server));
	return ! $?;
    }
    return 1;
}

sub check_ssh_master {
    my ($server, $user) = @_;
    system(qq($SSH_PATH -q -f -N $SSH_CONTROL_OPTION $user\@$server -O check));
    return ! $?;
}

END {
    #- remove ssh persistent connections
    foreach my $socket (glob "$SSH_CONTROL_DIR/ssh-urpmi-$$-*") {
	my ($server, $login) = $socket =~ /ssh-urpmi-\d+-([^_]+)_\d+_(.*)$/ or next;
	system($SSH_PATH, '-q', '-f', '-N', '-o', "ControlPath $socket", '-O', 'exit', "$login\@$server");
    }
}

#- get the width of the terminal
my $wchar = 79;
eval {
    require Term::ReadKey;
    ($wchar) = Term::ReadKey::GetTerminalSize();
    --$wchar;
};

sub progress_text {
    my ($mode, $percent, $total, $eta, $speed) = @_;
    $mode eq 'progress' ?
      (defined $total && defined $eta ?
	 N("        %s%% of %s completed, ETA = %s, speed = %s", $percent, $total, $eta, $speed) :
	 N("        %s%% completed, speed = %s", $percent, $speed)) : '';
}

=item sync_logger($mode, $file, $percent, $_total, $_eta, $_speed)

Default logger (callback) suitable for sync operation on STDERR only.

=cut

sub sync_logger {
    my ($mode, $file, $percent, $total, $eta, $speed) = @_;
    if ($mode eq 'start') {
	print STDERR "    $file\n";
    } elsif ($mode eq 'progress') {
	my $text = progress_text($mode, $percent, $total, $eta, $speed);
	if (length($text) > $wchar) { $text = substr($text, 0, $wchar) }
	if (bytes::length($text) < $wchar) {
	    # clearing more than needed in case the terminal is not handling utf8 and we have a utf8 string
	    print STDERR $text, " " x ($wchar - bytes::length($text)), "\r";
	} else {
	    # clearing all the line first since we can't really know the "length" of the string
	    print STDERR " " x $wchar, "\r", $text, "\r";
	}
    } elsif ($mode eq 'end') {
	print STDERR " " x $wchar, "\r";
    } elsif ($mode eq 'error') {
	#- error is 3rd argument, saved in $percent
	print STDERR N("...retrieving failed: %s", $percent), "\n";
    }
}

=item requested_ftp_http_downloader($urpm, $medium)

Return the downloader program to use (whether it pas provided on the
command line or in the config file).

=cut

sub requested_ftp_http_downloader {
    my ($urpm, $medium) = @_;

    $urpm->{options}{downloader} || #- cmd-line switch
      $medium && $medium->{downloader} || 
	$urpm->{global_config}{downloader} || "";
}

sub parse_url_with_login {
    my ($url) = @_;
    $url =~ m!([^:]*)://([^/:]*)(:([^/:\@]*))?\@([^/]*)(.*)! && $1 ne 'ssh' &&
      { proto => $1, login => $2, password => $4, machine => $5, dir => $6 };
}
sub url_obscuring_password {
    my ($url) = @_;
    my $u = parse_url_with_login($url);
    if ($u && $u->{password}) {
	sprintf('%s://xxx:xxx@%s%s', $u->{proto}, $u->{machine}, $u->{dir});
    } else {
	$url;
    }
}

#- $medium can be undef
sub _all_options {
    my ($urpm, $medium, $options) = @_;

    my %all_options = ( 
	dir => "$urpm->{cachedir}/partial",
	proxy => get_proxy_($urpm),
	metalink => $medium->{mirrorlist},
	$medium->{"disable-certificate-check"} ? "no-certificate-check" : @{[]},
	$urpm->{debug} ? (debug => $urpm->{debug}) : @{[]},
	%$options,
    );
    foreach my $cpt (qw(compress limit-rate retry wget-options curl-options rsync-options prozilla-options aria2-options metalink)) {
	$all_options{$cpt} = $urpm->{options}{$cpt} if defined $urpm->{options}{$cpt};
    }
    \%all_options;
}

sub sync_rel {
    my ($urpm, $medium, $rel_files, %options) = @_;

    my @files = map { reduce_pathname("$medium->{url}/$_") } @$rel_files;

    my $files_text = join(' ', (use_metalink($urpm, $medium) ? ($medium->{mirrorlist}, $medium->{'with-dir'}) : url_obscuring_password($medium->{url})), @$rel_files);
    $urpm->{debug} and $urpm->{debug}(N("retrieving %s", $files_text));

    my $all_options = _all_options($urpm, $medium, \%options);
    my @result_files = map { $all_options->{dir} . '/' . basename($_) } @$rel_files;
    unlink @result_files if $all_options->{preclean};

    (my $cwd) = getcwd() =~ /(.*)/;
    eval { _sync_webfetch_raw($urpm, $medium, $rel_files, \@files, $all_options) };
    my $err = $@;
    chdir $cwd;
    if (!$err) {
	$urpm->{log}(N("retrieved %s", $files_text));
	\@result_files;
    } else {
	$urpm->{log}("error: $err");
	# don't leave partial download
	unlink @result_files;
	undef;
    }
}

sub sync_rel_one {
    my ($urpm, $medium, $rel_file, %options) = @_;

    my $files = sync_rel($urpm, $medium, [$rel_file], %options) or return;
    $files->[0];
}

=item sync_url($urpm, $url, %options)

Retrieve a file from the network and return the local cached file path.

=cut

sub sync_url {
    my ($urpm, $url, %options) = @_;
    sync_rel_one($urpm, { url => dirname($url), disable_metalink => $options{disable_metalink} }, basename($url), %options);
}

sub sync_rel_to {
    my ($urpm, $medium, $rel_file, $dest_file, %options) = @_;

    my $files = sync_rel($urpm, $medium, [$rel_file], %options) or return undef;
    my $result_file = $files->[0];
    $result_file ne $dest_file or rename($result_file, $dest_file) or return;
    $result_file;
}

=item get_content($urpm, $url, %o_options)

Retrieve a file and return its content.

=cut

sub get_content {
    my ($urpm, $url, %o_options) = @_;

    my $file = sync_url($urpm, $url, %o_options, quiet => 1, preclean => 1) or return;

    my @l = cat_($file);
    unlink $file;

    wantarray() ? @l : join('', @l);
}
    

#- syncing algorithms.
#-
#- nb: $files is constructed from $rel_files using $medium
sub _sync_webfetch_raw {    
    my ($urpm, $medium, $rel_files, $files, $options) = @_;

    #- currently ftp and http protocols are managed by curl or wget,
    #- ssh and rsync protocols are managed by rsync *AND* ssh.
    my $proto = urpm::protocol_from_url($medium->{url}) or die N("unknown protocol defined for %s", $medium->{url});

    if ($proto eq 'file') {
	my @l = map { urpm::file_from_local_url($_) } @$files;
	eval { sync_file($options, @l) };
	$urpm->{fatal}(10, $@) if $@;
    } elsif ($proto eq 'rsync') {
	sync_rsync($options, @$files);
    } elsif (member($proto, 'ftp', 'http', 'https') || $options->{metalink}) {

	my $preferred = preferred_downloader($urpm, $medium, \$options->{metalink});
	if ($preferred eq 'aria2') {
	    sync_aria2($urpm, $medium, $rel_files, $options);
	} else {
	  my $sync = $urpm::download::{"sync_$preferred"} or die N("no webfetch found, supported webfetch are: %s\n", join(", ", urpm::download::ftp_http_downloaders()));

	  my @l = @$files;
	  while (@l) {
	    my $half_MAX_ARG = 131072 / 2;
	    # restrict the number of elements so that it fits on cmdline of curl/wget/proz/aria2c
	    my $n = 0;
	    for (my $len = 0; $n < @l && $len < $half_MAX_ARG; $len += length($l[$n++])) {}	    
	    $sync->($options, splice(@l, 0, $n));
	  }
	}
    } elsif ($proto eq 'ssh') {
	my @ssh_files = map { m!^ssh://([^/]*)(.*)! ? "$1:$2" : @{[]} } @$files;
	sync_ssh($options, @ssh_files);
    } else {
	die N("unable to handle protocol: %s", $proto);
    }
}

sub _take_n_elem {
    my ($n, @l) = @_;
    @l < $n ? @l : @l[0 .. $n-1];
}

sub _create_one_metalink_line {
    my ($medium, $mirror, $rel_file, $counter) = @_;

    my $type = urpm::protocol_from_url($mirror->{url});

    # If more than 100 mirrors, give all the remaining mirrors a priority of 0
    my $preference = max(0, 100 - $counter);

    my @options = (qq(type="$type"), qq(preference="$preference"));
    # Not supported in metalinks
    #if (@$list[$i]->{bw}) {
    #    push @options, 'bandwidth="' . @$list[$i]->{bw} . '"';
    #       }
    # Supported in metalinks, but no longer used in mirror list..?
    if ($mirror->{connections}) {
	push @options, qq(maxconnections="$mirror->{connections}");
    }
    push @options, 'location="' . lc($mirror->{zone}) . '"';
    my $base = urpm::mirrors::_add__with_dir($mirror->{url}, $medium->{'with-dir'});
    sprintf('<url %s>%s/%s</url>', join(' ', @options), $base, $rel_file);
}

sub _create_metalink_ {
    my ($urpm, $medium, $rel_files, $options) = @_;
    # Don't create a metalink when downloading mirror list
    $medium or return;

    # only use the 8 best mirrors, then we let aria2 choose
    require urpm::mirrors;
    my @mirrors = $medium->{mirrorlist} ? (map {
	# aria2 doesn't handle rsync
	my @l = grep { urpm::protocol_from_url($_->{url}) ne 'rsync' } @$_;
	_take_n_elem(8, @l);
    } urpm::mirrors::list_urls($urpm, $medium, '')) : { url => $medium->{url} };
    
    my $metalinkfile = "$urpm->{cachedir}/$options->{media}.metalink";
    # Even if not required by metalink spec, this line is needed at top of
    # metalink file, otherwise aria2 won't be able to autodetect it..
    my @metalink = (
      '<?xml version="1.0" encoding="utf-8"?>',
      '<metalink version="3.0" generator="URPMI" xmlns="http://www.metalinker.org/">',
      '<files>',
    );

    foreach my $rel_file (@$rel_files) {
	my $i = 0; 
	my @lines = map {
	    $i++;
	    _create_one_metalink_line($medium, $_, $rel_file, $i);
	} @mirrors;

	push @metalink, map { "\t$_" }
	  sprintf('<file name="%s"><resources>', basename($rel_file)),
	  (map { "\t$_" } @lines),
	  '</resources></file>';
    }
    push @metalink, '</files>', '</metalink>';
    
    output_safe($metalinkfile, join('', map { "$_\n" } @metalink));
    $metalinkfile;
}

1;

__END__

=back

=head1 COPYRIGHT

Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005 MandrakeSoft SA

Copyright (C) 2005-2010 Mandriva SA

=cut
n>sec = NULL; /* Add an empty archdata section to the module if necessary */ for (i = 0; i < f->header.e_shnum; ++i) { if (strcmp(f->sections[i]->name, ARCHDATA_SEC_NAME) == 0) { *sec = f->sections[i]; break; } } if (!*sec) *sec = obj_create_alloced_section(f, ARCHDATA_SEC_NAME, 16, 0, 0); /* Size and populate archdata */ if (arch_archdata(f, *sec)) return(1); return 0; } static int init_module(const char *m_name, struct obj_file *f, unsigned long m_size, const char *blob_name, unsigned int noload, unsigned int flag_load_map) { struct module *module; struct obj_section *sec; void *image; int ret = 0; tgt_long m_addr; sec = obj_find_section(f, ".this"); module = (struct module *) sec->contents; m_addr = sec->header.sh_addr; module->size_of_struct = sizeof(*module); module->size = m_size; module->flags = flag_autoclean ? NEW_MOD_AUTOCLEAN : 0; sec = obj_find_section(f, "__ksymtab"); if (sec && sec->header.sh_size) { module->syms = sec->header.sh_addr; module->nsyms = sec->header.sh_size / (2 * tgt_sizeof_char_p); } if (n_ext_modules_used) { sec = obj_find_section(f, ".kmodtab"); module->deps = sec->header.sh_addr; module->ndeps = n_ext_modules_used; } module->init = obj_symbol_final_value(f, obj_find_symbol(f, "init_module")); module->cleanup = obj_symbol_final_value(f, obj_find_symbol(f, "cleanup_module")); sec = obj_find_section(f, "__ex_table"); if (sec) { module->ex_table_start = sec->header.sh_addr; module->ex_table_end = sec->header.sh_addr + sec->header.sh_size; } sec = obj_find_section(f, ".text.init"); if (sec) { module->runsize = sec->header.sh_addr - m_addr; } sec = obj_find_section(f, ".data.init"); if (sec) { if (!module->runsize || module->runsize > sec->header.sh_addr - m_addr) module->runsize = sec->header.sh_addr - m_addr; } sec = obj_find_section(f, ARCHDATA_SEC_NAME); if (sec && sec->header.sh_size) { module->archdata_start = sec->header.sh_addr; module->archdata_end = module->archdata_start + sec->header.sh_size; } sec = obj_find_section(f, KALLSYMS_SEC_NAME); if (sec && sec->header.sh_size) { module->kallsyms_start = sec->header.sh_addr; module->kallsyms_end = module->kallsyms_start + sec->header.sh_size; } if (!arch_init_module(f, module)) return 0; /* * Whew! All of the initialization is complete. * Collect the final module image and give it to the kernel. */ image = xmalloc(m_size); obj_create_image(f, image); if (flag_load_map) print_load_map(f); if (blob_name) { int fd, l; fd = open(blob_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (fd < 0) { error("open %s failed %m", blob_name); ret = -1; } else { if ((l = write(fd, image, m_size)) != m_size) { error("write %s failed %m", blob_name); ret = -1; } close(fd); } } if (ret == 0 && !noload) { fflush(stdout); /* Flush any debugging output */ ret = sys_init_module(m_name, (struct module *) image); if (ret) { error("init_module: %m"); lprintf("Hint: insmod errors can be caused by incorrect module parameters, " "including invalid IO or IRQ parameters.\n" " You may find more information in syslog or the output from dmesg"); } } free(image); return ret == 0; } #ifdef COMPAT_2_0 static int old_init_module(const char *m_name, struct obj_file *f, unsigned long m_size) { char *image; struct old_mod_routines routines; struct old_symbol_table *symtab; int ret; int nsyms = 0, strsize = 0, total; /* Create the symbol table */ /* Size things first... */ if (flag_export) { int i; for (i = 0; i < HASH_BUCKETS; ++i) { struct obj_symbol *sym; for (sym = f->symtab[i]; sym; sym = sym->next) if (ELFW(ST_BIND) (sym->info) != STB_LOCAL && sym->secidx <= SHN_HIRESERVE) { sym->ksymidx = nsyms++; strsize += strlen(sym->name) + 1; } } } total = (sizeof(struct old_symbol_table) + nsyms * sizeof(struct old_module_symbol) + n_ext_modules_used * sizeof(struct old_module_ref) + strsize); symtab = xmalloc(total); symtab->size = total; symtab->n_symbols = nsyms; symtab->n_refs = n_ext_modules_used; if (flag_export && nsyms) { struct old_module_symbol *ksym; char *str; int i; ksym = symtab->symbol; str = ((char *) ksym + nsyms * sizeof(struct old_module_symbol) + n_ext_modules_used * sizeof(struct old_module_ref)); for (i = 0; i < HASH_BUCKETS; ++i) { struct obj_symbol *sym; for (sym = f->symtab[i]; sym; sym = sym->next) if (sym->ksymidx >= 0) { ksym->addr = obj_symbol_final_value(f, sym); ksym->name = (unsigned long) str - (unsigned long) symtab; str = stpcpy(str, sym->name) + 1; ksym++; } } } if (n_ext_modules_used) { struct old_module_ref *ref; int i; ref = (struct old_module_ref *) ((char *) symtab->symbol + nsyms * sizeof(struct old_module_symbol)); for (i = 0; i < n_module_stat; ++i) { if (module_stat[i].status /* used */) { ref++->module = module_stat[i].modstruct; } } } /* Fill in routines. */ routines.init = obj_symbol_final_value(f, obj_find_symbol(f, "init_module")); routines.cleanup = obj_symbol_final_value(f, obj_find_symbol(f, "cleanup_module")); /* * Whew! All of the initialization is complete. * Collect the final module image and give it to the kernel. */ image = xmalloc(m_size); obj_create_image(f, image); /* * image holds the complete relocated module, * accounting correctly for mod_use_count. * However the old module kernel support assume that it * is receiving something which does not contain mod_use_count. */ ret = old_sys_init_module(m_name, image + sizeof(long), (m_size - sizeof(long)) | (flag_autoclean ? OLD_MOD_AUTOCLEAN : 0), &routines, symtab); if (ret) error("init_module: %m"); free(image); free(symtab); return ret == 0; } #endif /* end compat */ /************************************************************************/ /* Check that a module parameter has a reasonable definition */ static int check_module_parameter(struct obj_file *f, char *key, char *value, int *persist_flag) { struct obj_symbol *sym; int min, max; char *p = value; sym = obj_find_symbol(f, key); if (sym == NULL) { /* FIXME: For 2.2 kernel compatibility, only issue warnings for * most error conditions. Make these all errors in 2.5. */ lprintf("Warning: %s symbol for parameter %s not found", error_file, key); ++warnings; return(1); } if (isdigit(*p)) { min = strtoul(p, &p, 10); if (*p == '-') max = strtoul(p + 1, &p, 10); else max = min; } else min = max = 1; if (max < min) { lprintf("Warning: %s parameter %s has max < min!", error_file, key); ++warnings; return(1); } switch (*p) { case 'c': if (!isdigit(p[1])) { lprintf("%s parameter %s has no size after 'c'!", error_file, key); ++warnings; return(1); } while (isdigit(p[1])) ++p; /* swallow c array size */ break; case 'b': /* drop through */ case 'h': /* drop through */ case 'i': /* drop through */ case 'l': /* drop through */ case 's': break; case '\0': lprintf("%s parameter %s has no format character!", error_file, key); ++warnings; return(1); default: lprintf("%s parameter %s has unknown format character '%c'", error_file, key, *p); ++warnings; return(1); } switch (*++p) { case 'p': if (*(p-1) == 's') { error("parameter %s is invalid persistent string", key); return(1); } *persist_flag = 1; break; case '\0': break; default: lprintf("%s parameter %s has unknown format modifier '%c'", error_file, key, *p); ++warnings; return(1); } return(0); } /* Check that all module parameters have reasonable definitions */ static void check_module_parameters(struct obj_file *f, int *persist_flag) { struct obj_section *sec; char *ptr, *value, *n, *endptr; int namelen, err = 0; sec = obj_find_section(f, ".modinfo"); if (sec == NULL) { /* module does not support typed parameters */ return; } ptr = sec->contents; endptr = ptr + sec->header.sh_size; while (ptr < endptr && !err) { value = strchr(ptr, '='); n = strchr(ptr, '\0'); if (value) { namelen = value - ptr; if (namelen >= 5 && strncmp(ptr, "parm_", 5) == 0 && !(namelen > 10 && strncmp(ptr, "parm_desc_", 10) == 0)) { char *pname = xmalloc(namelen + 1); strncpy(pname, ptr + 5, namelen - 5); pname[namelen - 5] = '\0'; err = check_module_parameter(f, pname, value+1, persist_flag); free(pname); } } else { if (n - ptr >= 5 && strncmp(ptr, "parm_", 5) == 0) { error("parameter %s found with no value", ptr); err = 1; } } ptr = n + 1; } if (err) *persist_flag = 0; return; } static void set_tainted(struct obj_file *f, int fd, int kernel_has_tainted, int noload, int taint, const char *text1, const char *text2) { char buf[80]; int oldval; static int first = 1; if (fd < 0 && !kernel_has_tainted) return; /* New modutils on old kernel */ lprintf("Warning: loading %s will taint the kernel: %s%s", f->filename, text1, text2); ++warnings; if (first) { lprintf(" See %s for information about tainted modules", TAINT_URL); first = 0; } if (fd >= 0 && !noload) { read(fd, buf, sizeof(buf)-1); buf[sizeof(buf)-1] = '\0'; oldval = strtoul(buf, NULL, 10); sprintf(buf, "%d\n", oldval | taint); write(fd, buf, strlen(buf)); } } /* Check if loading this module will taint the kernel. */ static void check_tainted_module(struct obj_file *f, int noload) { static const char tainted_file[] = TAINT_FILENAME; int fd, kernel_has_tainted; const char *ptr; if ((fd = open(tainted_file, O_RDWR)) < 0) { if (errno == ENOENT) kernel_has_tainted = 0; else if (errno == EACCES) kernel_has_tainted = 1; else { perror(tainted_file); kernel_has_tainted = 0; } } else kernel_has_tainted = 1; switch (obj_gpl_license(f, &ptr)) { case 0: break; case 1: set_tainted(f, fd, kernel_has_tainted, noload, TAINT_PROPRIETORY_MODULE, "no license", ""); break; case 2: /* The module has a non-GPL license so we pretend that the * kernel always has a taint flag to get a warning even on * kernels without the proc flag. */ set_tainted(f, fd, 1, noload, TAINT_PROPRIETORY_MODULE, "non-GPL license - ", ptr); break; default: set_tainted(f, fd, 1, noload, TAINT_PROPRIETORY_MODULE, "Unexpected return from obj_gpl_license", ""); break; } if (flag_force_load) set_tainted(f, fd, 1, noload, TAINT_FORCED_MODULE, "forced load", ""); if (fd >= 0) close(fd); } /* For common 3264 code, only compile the usage message once, in the 64 bit version */ #if defined(COMMON_3264) && defined(ONLY_32) extern void insmod_usage(void); /* Use the copy in the 64 bit version */ #else /* Common 64 bit version or any non common code - compile usage routine */ void insmod_usage(void) { fputs("Usage:\n" "insmod [-fhkLmnpqrsSvVxXyYN] [-e persist_name] [-o module_name] [-O blob_name] [-P prefix] module [ symbol=value ... ]\n" "\n" " module Name of a loadable kernel module ('.o' can be omitted)\n" " -f, --force Force loading under wrong kernel version\n" " -h, --help Print this message\n" " -k, --autoclean Make module autoclean-able\n" " -L, --lock Prevent simultaneous loads of the same module\n" " -m, --map Generate load map (so crashes can be traced)\n" " -n, --noload Don't load, just show\n" " -p, --probe Probe mode; check if the module matches the kernel\n" " -q, --quiet Don't print unresolved symbols\n" " -r, --root Allow root to load modules not owned by root\n" " -s, --syslog Report errors via syslog\n" " -S, --kallsyms Force kallsyms on module\n" " -v, --verbose Verbose output\n" " -V, --version Show version\n" " -x, --noexport Do not export externs\n" " -X, --export Do export externs (default)\n" " -y, --noksymoops Do not add ksymoops symbols\n" " -Y, --ksymoops Do add ksymoops symbols (default)\n" " -N, --numeric-only Only check the numeric part of the kernel version\n" " -e persist_name\n" " --persist=persist_name Filename to hold any persistent data from the module\n" " -o NAME, --name=NAME Set internal module name to NAME\n" " -O NAME, --blob=NAME Save the object as a binary blob in NAME\n" " -P PREFIX\n" " --prefix=PREFIX Prefix for kernel or module symbols\n" ,stderr); exit(1); } #endif /* defined(COMMON_3264) && defined(ONLY_32) */ #if defined(COMMON_3264) && defined(ONLY_32) #define INSMOD_MAIN insmod_main_32 /* 32 bit version */ #elif defined(COMMON_3264) && defined(ONLY_64) #define INSMOD_MAIN insmod_main_64 /* 64 bit version */ #else #define INSMOD_MAIN insmod_main /* Not common code */ #endif int INSMOD_MAIN(int argc, char **argv) { int k_version; int k_crcs; char k_strversion[STRVERSIONLEN]; struct option long_opts[] = { {"force", 0, 0, 'f'}, {"help", 0, 0, 'h'}, {"autoclean", 0, 0, 'k'}, {"lock", 0, 0, 'L'}, {"map", 0, 0, 'm'}, {"noload", 0, 0, 'n'}, {"probe", 0, 0, 'p'}, {"poll", 0, 0, 'p'}, /* poll is deprecated, remove in 2.5 */ {"quiet", 0, 0, 'q'}, {"root", 0, 0, 'r'}, {"syslog", 0, 0, 's'}, {"kallsyms", 0, 0, 'S'}, {"verbose", 0, 0, 'v'}, {"version", 0, 0, 'V'}, {"noexport", 0, 0, 'x'}, {"export", 0, 0, 'X'}, {"noksymoops", 0, 0, 'y'}, {"ksymoops", 0, 0, 'Y'}, {"persist", 1, 0, 'e'}, {"numeric-only", 1, 0, 'N'}, {"name", 1, 0, 'o'}, {"blob", 1, 0, 'O'}, {"prefix", 1, 0, 'P'}, {0, 0, 0, 0} }; char *m_name = NULL; char *blob_name = NULL; /* Save object as binary blob */ int m_version; ElfW(Addr) m_addr; unsigned long m_size; int m_crcs; char m_strversion[STRVERSIONLEN]; char *filename; char *persist_name = NULL; /* filename to hold any persistent data */ int fp; struct obj_file *f; struct obj_section *kallsyms = NULL, *archdata = NULL; int o; int noload = 0; int dolock = 1; /*Note: was: 0; */ int quiet = 0; int exit_status = 1; int force_kallsyms = 0; int persist_parms = 0; /* does module have persistent parms? */ int i; int gpl; error_file = "insmod"; /* To handle repeated calls from combined modprobe */ errors = optind = 0; /* Process the command line. */ while ((o = getopt_long(argc, argv, "fhkLmnpqrsSvVxXyYNe:o:O:P:R:", &long_opts[0], NULL)) != EOF) switch (o) { case 'f': /* force loading */ flag_force_load = 1; break; case 'h': /* Print the usage message. */ insmod_usage(); break; case 'k': /* module loaded by kerneld, auto-cleanable */ flag_autoclean = 1; break; case 'L': /* protect against recursion. */ dolock = 1; break; case 'm': /* generate load map */ flag_load_map = 1; break; case 'n': /* don't load, just check */ noload = 1; break; case 'p': /* silent probe mode */ flag_silent_probe = 1; break; case 'q': /* Don't print unresolved symbols */ quiet = 1; break; case 'r': /* allow root to load non-root modules */ root_check_off = !root_check_off; break; case 's': /* start syslog */ setsyslog("insmod"); break; case 'S': /* Force kallsyms */ force_kallsyms = 1; break; case 'v': /* verbose output */ flag_verbose = 1; break; case 'V': fputs("insmod version " MODUTILS_VERSION "\n", stderr); break; case 'x': /* do not export externs */ flag_export = 0; break; case 'X': /* do export externs */ flag_export = 1; break; case 'y': /* do not define ksymoops symbols */ flag_ksymoops = 0; break; case 'Y': /* do define ksymoops symbols */ flag_ksymoops = 1; break; case 'N': /* only check numeric part of kernel version */ flag_numeric_only = 1; break; case 'e': /* persistent data filename */ free(persist_name); persist_name = xstrdup(optarg); break; case 'o': /* name the output module */ m_name = optarg; break; case 'O': /* save the output module object */ blob_name = optarg; break; case 'P': /* use prefix on crc */ set_ncv_prefix(optarg); break; default: insmod_usage(); break; } if (optind >= argc) { insmod_usage(); } filename = argv[optind++]; if (config_read(0, NULL, "", NULL) < 0) { error("Failed handle configuration"); } if (persist_name && !*persist_name && (!persistdir || !*persistdir)) { free(persist_name); persist_name = NULL; if (flag_verbose) { lprintf("insmod: -e \"\" ignored, no persistdir"); ++warnings; } } if (m_name == NULL) { size_t len; char *p; if ((p = strrchr(filename, '/')) != NULL) p++; else p = filename; len = strlen(p); if (len > 2 && p[len - 2] == '.' && p[len - 1] == 'o') len -= 2; else if (len > 4 && p[len - 4] == '.' && p[len - 3] == 'm' && p[len - 2] == 'o' && p[len - 1] == 'd') len -= 4; #ifdef CONFIG_USE_ZLIB else if (len > 5 && !strcmp(p + len - 5, ".o.gz")) len -= 5; #endif m_name = xmalloc(len + 1); memcpy(m_name, p, len); m_name[len] = '\0'; } /* Locate the file to be loaded. */ if (!strchr(filename, '/') && !strchr(filename, '.')) { char *tmp = search_module_path(filename); if (tmp == NULL) { error("%s: no module by that name found", filename); return 1; } filename = tmp; lprintf("Using %s", filename); } else if (flag_verbose) lprintf("Using %s", filename); /* And open it. */ if ((fp = gzf_open(filename, O_RDONLY)) == -1) { error("%s: %m", filename); return 1; } /* Try to prevent multiple simultaneous loads. */ if (dolock) flock(fp, LOCK_EX); if (!get_kernel_info(K_SYMBOLS)) goto out; /* * Set the genksyms prefix if this is a versioned kernel * and it's not already set. */ set_ncv_prefix(NULL); for (i = 0; !noload && i < n_module_stat; ++i) { if (strcmp(module_stat[i].name, m_name) == 0) { error("a module named %s already exists", m_name); goto out; } } error_file = filename; if ((f = obj_load(fp, ET_REL, filename)) == NULL) goto out; /* Version correspondence? */ k_version = get_kernel_version(k_strversion); m_version = get_module_version(f, m_strversion); if (m_version == -1) { error("couldn't find the kernel version the module was compiled for"); goto out; } k_crcs = is_kernel_checksummed(); m_crcs = is_module_checksummed(f); if ((m_crcs == 0 || k_crcs == 0) && strncmp(k_strversion, m_strversion, STRVERSIONLEN) != 0) { if (flag_force_load) { lprintf("Warning: kernel-module version mismatch\n" "\t%s was compiled for kernel version %s\n" "\twhile this kernel is version %s", filename, m_strversion, k_strversion); ++warnings; } else { if (!quiet) error("kernel-module version mismatch\n" "\t%s was compiled for kernel version %s\n" "\twhile this kernel is version %s.", filename, m_strversion, k_strversion); goto out; } } if (m_crcs != k_crcs) obj_set_symbol_compare(f, ncv_strcmp, ncv_symbol_hash); /* Let the module know about the kernel symbols. */ gpl = obj_gpl_license(f, NULL) == 0; add_kernel_symbols(f, gpl); #ifdef ARCH_ppc64 if (!ppc64_process_syms (f)) goto out; #endif /* Allocate common symbols, symbol tables, and string tables. * * The calls marked DEPMOD indicate the bits of code that depmod * uses to do a pseudo relocation, ignoring undefined symbols. * Any changes made to the relocation sequence here should be * checked against depmod. */ #ifdef COMPAT_2_0 if (k_new_syscalls ? !create_this_module(f, m_name) : !old_create_mod_use_count(f)) goto out; #else if (!create_this_module(f, m_name)) goto out; #endif arch_create_got(f); /* DEPMOD */ if (!obj_check_undefineds(f, quiet)) { /* DEPMOD, obj_clear_undefineds */ if (!gpl && !quiet) { if (gplonly_seen) error("\n" "Hint: You are trying to load a module without a GPL compatible license\n" " and it has unresolved symbols. The module may be trying to access\n" " GPLONLY symbols but the problem is more likely to be a coding or\n" " user error. Contact the module supplier for assistance, only they\n" " can help you.\n"); else error("\n" "Hint: You are trying to load a module without a GPL compatible license\n" " and it has unresolved symbols. Contact the module supplier for\n" " assistance, only they can help you.\n"); } goto out; } obj_allocate_commons(f); /* DEPMOD */ check_module_parameters(f, &persist_parms); check_tainted_module(f, noload); if (optind < argc) { if (!process_module_arguments(f, argc - optind, argv + optind, 1)) goto out; } hide_special_symbols(f); if (persist_parms && persist_name && *persist_name) { f->persist = persist_name; persist_name = NULL; } if (persist_parms && persist_name && !*persist_name) { /* -e "". This is ugly. Take the filename, compare it against * each of the module paths until we find a match on the start * of the filename, assume the rest is the relative path. Have * to do it this way because modprobe uses absolute filenames * for module names in modules.dep and the format of modules.dep * does not allow for any backwards compatible changes, so there * is nowhere to store the relative filename. The only way this * should fail to calculate a relative path is "insmod ./xxx", for * that case the user has to specify -e filename. */ int j, l = strlen(filename); char *relative = NULL; char *p; for (i = 0; i < nmodpath; ++i) { p = modpath[i].path; j = strlen(p); while (j && p[j] == '/') --j; if (j < l && strncmp(filename, p, j) == 0 && filename[j] == '/') { while (filename[j] == '/') ++j; relative = xstrdup(filename+j); break; } } if (relative) { i = strlen(relative); if (i > 3 && strcmp(relative+i-3, ".gz") == 0) relative[i -= 3] = '\0'; if (i > 2 && strcmp(relative+i-2, ".o") == 0) relative[i -= 2] = '\0'; else if (i > 4 && strcmp(relative+i-4, ".mod") == 0) relative[i -= 4] = '\0'; f->persist = xmalloc(strlen(persistdir) + 1 + i + 1); strcpy(f->persist, persistdir); /* safe, xmalloc */ strcat(f->persist, "/"); /* safe, xmalloc */ strcat(f->persist, relative); /* safe, xmalloc */ free(relative); } else error("Cannot calculate persistent filename"); } if (f->persist && *(f->persist) != '/') { error("Persistent filenames must be absolute, ignoring '%s'", f->persist); free(f->persist); f->persist = NULL; } if (f->persist && !flag_ksymoops) { error("has persistent data but ksymoops symbols are not available"); free(f->persist); f->persist = NULL; } if (f->persist && !k_new_syscalls) { error("has persistent data but the kernel is too old to support it"); free(f->persist); f->persist = NULL; } if (persist_parms && flag_verbose) { if (f->persist) lprintf("Persist filename '%s'", f->persist); else lprintf("No persistent filename available"); } if (f->persist) { FILE *fp = fopen(f->persist, "r"); if (!fp) { if (flag_verbose) lprintf("Cannot open persist file '%s' %m", f->persist); } else { int pargc = 0; char *pargv[1000]; /* hard coded but big enough */ char line[3000]; /* hard coded but big enough */ char *p; while (fgets(line, sizeof(line), fp)) { p = strchr(line, '\n'); if (!p) { error("Persistent data line is too long\n%s", line); break; } *p = '\0'; p = line; while (isspace(*p)) ++p; if (!*p || *p == '#') continue; if (pargc == sizeof(pargv)/sizeof(pargv[0])) { error("More than %d persistent parameters", pargc); break; } pargv[pargc++] = xstrdup(p); } fclose(fp); if (!process_module_arguments(f, pargc, pargv, 0)) goto out; while (pargc--) free(pargv[pargc]); } } if (flag_ksymoops) add_ksymoops_symbols(f, filename, m_name); if (k_new_syscalls) create_module_ksymtab(f); /* archdata based on relocatable addresses */ if (add_archdata(f, &archdata)) goto out; /* kallsyms based on relocatable addresses */ if (add_kallsyms(f, &kallsyms, force_kallsyms)) goto out; /**** No symbols or sections to be changed after kallsyms above ***/ if (errors) goto out; /* If we were just checking, we made it. */ if (flag_silent_probe) { exit_status = 0; goto out; } /* Module has now finished growing; find its size and install it. */ m_size = obj_load_size(f); /* DEPMOD */ if (noload) { /* Don't bother actually touching the kernel. */ m_addr = 0x12340000; } else { errno = 0; m_addr = create_module(m_name, m_size); #ifdef ARCH_ppc64 m_addr |= ppc64_module_base (f); #endif switch (errno) { case 0: break; case EEXIST: if (dolock) { /* * Assume that we were just invoked * simultaneous with another insmod * and return success. */ exit_status = 0; goto out; } error("a module named %s already exists", m_name); goto out; case ENOMEM: error("can't allocate kernel memory for module; needed %lu bytes", m_size); goto out; default: error("create_module: %m"); goto out; } } /* module is already built, complete with ksymoops symbols for the * persistent filename. If the kernel does not support persistent data * then give an error but continue. It is too difficult to clean up at * this stage and this error will only occur on backported modules. * rmmod will also get an error so warn the user now. */ if (f->persist && !noload) { struct { struct module m; int data; } test_read; memset(&test_read, 0, sizeof(test_read)); test_read.m.size_of_struct = -sizeof(test_read.m); /* -ve size => read, not write */ test_read.m.read_start = m_addr + sizeof(struct module); test_read.m.read_end = test_read.m.read_start + sizeof(test_read.data); if (sys_init_module(m_name, (struct module *) &test_read)) { int old_errors = errors; error("has persistent data but the kernel is too old to support it." " Expect errors during rmmod as well"); errors = old_errors; } } if (!obj_relocate(f, m_addr)) { /* DEPMOD */ if (!noload) delete_module(m_name); goto out; } /* Do archdata again, this time we have the final addresses */ if (add_archdata(f, &archdata)) goto out; /* Do kallsyms again, this time we have the final addresses */ if (add_kallsyms(f, &kallsyms, force_kallsyms)) goto out; #ifdef COMPAT_2_0 if (k_new_syscalls) init_module(m_name, f, m_size, blob_name, noload, flag_load_map); else if (!noload) old_init_module(m_name, f, m_size); #else init_module(m_name, f, m_size, blob_name, noload, flag_load_map); #endif if (errors) { if (!noload) delete_module(m_name); goto out; } if (warnings && !noload) lprintf("Module %s loaded, with warnings", m_name); exit_status = 0; out: if (dolock) flock(fp, LOCK_UN); close(fp); if (!noload) snap_shot(NULL, 0); return exit_status; } /* For common 3264 code, add an overall insmod_main, in the 64 bit version. */ #if defined(COMMON_3264) && defined(ONLY_64) int insmod_main(int argc, char **argv) { if (arch64()) return insmod_main_64(argc, argv); else return insmod_main_32(argc, argv); } #endif /* defined(COMMON_3264) && defined(ONLY_64) */ int insmod_call(char * full_filename, char * params) { int argc = 2; char *argv[50]; char * ptr = params; argv[0] = "stage1"; argv[1] = full_filename; while (ptr != NULL) { argv[argc] = ptr; argc++; ptr = strchr(ptr, ' '); if (ptr) { ptr[0] = '\0'; ptr++; } } return insmod_main(argc, argv); }