summaryrefslogtreecommitdiffstats
path: root/mdkupdate
blob: 865f3631176042f1bdc92e8a3b61c7006e3b769d (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
#!/usr/bin/perl
################################################################################
# Mdkupdate                                                                    # 
#                                                                              #
# Copyright (C) 2002 MandrakeSoft                                              #
#
# Daouda Lo <daouda@mandrakesoft.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.   #
################################################################################

use POSIX;
use Digest::MD5  qw(md5 md5_hex md5_base64);
use HTTP::Request;
use HTTP::Request::Common;
use LWP::UserAgent;
use Net::HTTPS; #for https connections 
use MIME::Base64 qw(encode_base64);
use lib qw(/usr/lib/libDrakX);
use common;
BEGIN { unshift @::textdomains, 'mdkupdate' }

require_root_capability();

my $logfile = "/var/log/mdkupdate.log";
my $conffile = "/root/.mdkupdate";

my $onlineUrl = "https://www.mandrakeonline.net/";
my %url;
foreach (qw(online_dif online_update online3_RemoteAction)) {
    $url->{$_} = $onlineUrl . $_ . '.php'
}
my $rpms_rep = "/root/tmp/";
my $VERSION = "0.17";
my $security = grep { /^-?-security$/ } @ARGV;
my $update = grep { /^-?-update$/ } @ARGV;

my ($scheduled, $noscheduled);

sub usage {
    print STDERR N("mdkupdate version %s
Copyright (C) 2002 MandrakeSoft.
This is free software and may be redistributed under the terms of the GNU GPL.

usage:
", $VERSION) . N("  --help         - print this help message.
") . N("  --auto         - Mdkupdate launched automatically.
") . N("  --applet       - launch MandrakeUpdate.
") . N("  --update       - Update keys
");
    exit(0);
}

my ($opt) = @ARGV;
@ARGV == 1 && ($opt eq '--auto' || $opt eq '--security' || $opt eq '--applet' || $opt eq '--help') or usage();

-s $conffile or die N("No $conffile file found. Run mdkonline wizard first");

my %o = getVarsFromSh($conffile);
if ($o{LOGIN} && $o{PASS} && $o{LOGIN} !~ /\s+/ && $o{PASS} !~ /\s+/) {
    my $u;
    my $MandrakeUpdateURL = $url->{online3_RemoteAction} . '?action=ScheduledRPM' . '&log=' . $o{LOGIN} . '&pass=' . $o{PASS} . '&host=' . $o{MACHINE} . '&key=' . $o{CURRENTKEY};
    my $resp = getFromURL($MandrakeUpdateURL);
    my $contents = $resp->content;
    if ($resp->is_success) {
	if ($contents =~ /TRUE/) { $u = 10 } elsif ($contents = m/(\d+)/) { $u = sprintf("%d", $1) } else { $u = 83 } ;
	my $action = {
		      10 => sub {
			  my $c2h = splitContents($contents);
			  #printf("\nCONTENTS = $contents \n torf = %s\n OLDKEY = %s = %s \n NEWKEY = %s \n FTP = %s\n", $c2h->{torf}, $c2h->{OLDKEY}, $o{CURRENTKEY}, $c2h->{NEWKEY}, $c2h->{FTP} );
			  if ($c2h->{torf} eq "TRUE" && $c2h->{OLDKEY} && $c2h->{NEWKEY}) { updateConf($c2h->{OLDKEY}, $c2h->{NEWKEY}) }
			  if ($c2h->{FTP}) { 
			      # for debugging purpose
			      $c2h->{FTP} = 'ftp://ftp.lip6.fr/pub/linux/distributions/mandrake/updates';
			      addMedia($c2h->{FTP})
			  }
			  $scheduled = join(',',@{$c2h->{sched}});
			  $noscheduled = join(',',@{$c2h->{nosched}}); $noscheduled =~ s/\.rpm//g;
			  printf "SCHEDULED = $scheduled\nNOSCHEDULED = $noscheduled\n";
			  if ($opt eq '--applet') {
			      print "MandrakeUpdate --media=mdkupdate --pkg-sel=$scheduled --pkg-nosel=$noscheduled";
			      system "MandrakeUpdate","--media=mdkupdate","--pkg-sel=$scheduled","--pkg-nosel=$noscheduled";
			  } elsif ($opt eq '--auto') {
			      $o{AUTO} eq 'TRUE' and autoInstallRpms($c2h->{sched});
			  }
			  rpm_qa("/root/rpm_qa_installed_after");
			  my %new = getVarsFromSh($conffile);
			  if (! -s "/root/.mdkupdate.rpms" || $update) {
			      #- send configuration and get back key to use...
			      $new{CURRENTKEY} = send_config($new{LOGIN},$new{PASS},$new{MACHINE});
			      delete $new{OLDKEY};
			      #- save back keys.
			      setVarsInSh($conffile, \%new);
			  } else {
			      #- this can safely be ignored if new configuration is sent.
			      send_rpm_dif($new{LOGIN},$new{PASS},$new{MACHINE},$new{OLDKEY});
			  }
			  clean_dir();
		      },
		      80 => sub { 
			  log::l("[mdkupdate] Client password does not match in database")
		      },
		      81 => sub {
			  log::l("[mdkupdate] Bad Authentification key. Please rerun mdkonline wizard")
		      },
		      82 => sub {
			  log::l("[mdkupdate] No active Online service found for this host.")
		      },
		      83 => sub {
			  log::l("[mdkupdate] Unknown problem, better relaunch mdkonline wizard or check connexion")
		      }
		     };
	$action->{$u}->();
    } else {
	log::l(N("Connection problem")."\n" . N("MandrakeUpdate could not contact the site, we will try again."));
    }
} else {
    $ret = -1; 
}
sub splitContents {
    my $cont = shift;
    my ($elem, $s);
    $s = [ split /\n/, $cont ];
    $elem->{torf} = $s->[0];
    if ($elem->{torf} eq 'TRUE') {
	($elem->{torf},$elem->{NEWKEY},$elem->{OLDKEY},$elem->{FTP}) = splice(@$s,0,4);
	($elem->{sched},$elem->{nosched}) = partition { $_ =~/i586$/ } @$s;
    }
    $elem
}

################################################################################
# Taken from mdkonline to perform complete update of rpm list (by diff), it has
# been decided to do exactly what mdkonline does the first time to update the db.
################################################################################
sub report_config {
    my ($file) = @_;
sub header { "
********************************************************************************
* $_[0]
********************************************************************************";
	 }
open (FILE,"> $file") || die "Couldn't open $file : $!";
map { chomp; print FILE "$_\n" }
    header("scsi"), cat_("/proc/scsi/scsi"),
    header("lsmod"), cat_("/proc/modules"),
    header("cmdline"), cat_("/proc/cmdline"),
    header("pcmcia: stab"), cat_("$prefix/var/lib/pcmcia/stab") || cat_("$prefix/var/run/stab"),
    header("usb"), cat_("/proc/bus/usb/devices"),
    header("partitions"), cat_("/proc/partitions"),
    header("cpuinfo"), cat_("/proc/cpuinfo"),
    header("install.log"), cat_("$prefix/root/drakx/install.log"),
    header("fstab"), cat_("$prefix/etc/fstab"),
    header("lilo.conf"), cat_("$prefix/etc/lilo.conf"),
    header("menu.lst"), cat_("$prefix/boot/grub/menu.lst"),
    header("/etc/modules.conf"), cat_("$prefix/etc/modules.conf"),
    header("rpm -qa"), join ('', sort `rpm -qa`),
    header("mandrake version"), cat_('/etc/redhat-release');
close(FILE);
}
sub getFromURL {
    my ($link) = @_;
    my $ua = LWP::UserAgent->new;
    $ua->agent("MdkUpdateAgent/$VERSION" . $ua->agent);
    $ua->env_proxy;
    my $request = HTTP::Request->new(GET => $link);
    my $response = $ua->request($request);
    $response
}
sub send_config {
    # When we arrive here, we're sure the login/passwd is correct
    my ($login, $passwd, $box_name) = @_;
#    print STDERR "Sending config\n";
    my $result = -1;
    
    report_config("/root/$login.$passwd.$box_name.online.log");
    `/usr/bin/bzip2 \\\-9 \\\-f /root/$login.$passwd.$box_name.online.log`;

    # Turn the binary file into a uuencoded ascii file
    open (FILE, "/root/$login.$passwd.$box_name.online.log.bz2") or die "$!";
    my ($chunk, $buffer);
    while (read(FILE, $chunk, 60*57)) {
	$buffer .= $chunk;
    }
    close (FILE);
    open (FILEOUT, "> /root/$login.$passwd.$box_name.online.log.bz2.uue") or die "$!";
	print FILEOUT encode_base64($buffer);
    close (FILEOUT);

    my $ua = LWP::UserAgent->new;
    $ua->agent("MdkOnlineAgent/$VERSION" . $ua->agent);
    $ua->env_proxy;
    my $response = $ua->request(POST 'https://www.mandrakeonline.net/wizard.php',

				Content_Type => 'form-data',
				Content => [submit => "upload_wizard",
					    wizard => ["/root/$login.$passwd.$box_name.online.log.bz2.uue"]
					    ]);
    # Check the outcome of the response
    #print "REPONSE: ".$response->content."\n";
    if ($response->is_success) {
	$result = ($response->content =~ /TRUE(.*)/) ? 0 : -1;
	#print("key is $1\n");
	$key = $1; 
	#- update local copy now.
	unlink "/root/.mdkupdate.rpms";
	rename "/root/rpm_qa_installed_after", "/root/.mdkupdate.rpms";
    } else {
	# pb with the connection ?
	$result = -1;
    }

    unlink "/root/$login.$passwd.$box_name.online.log.bz2";
    unlink "/root/$login.$passwd.$box_name.online.log.bz2.uue";

    $result == 0 && $key;
}
################################################################################

sub autoInstallRpms {
    my ($pkgs) = shift;
    my @pkg;
    push(@pkg, $_ . '.rpm') foreach @{$pkgs};
    updatePkgs(@pkg);
}
sub updateConf {
    my ($oldkey, $newkey) = @_;
    my %l = getVarsFromSh $conffile;
    setVarsInSh($conffile, {
		OLDKEY => $oldkey,
		CURRENTKEY => $newkey,
		VER => $l{VER},
       	        MACHINE => $l{MACHINE},
		PASS => $l{PASS},
		LOGIN => $l{LOGIN},
		AUTO => $l{AUTO}
	      });
}
sub addMedia {
    my $mirror = shift;
    my ($r) = getRelease();
    my $fullpath2mir = "$mirror". "/$r" . "/RPMS" . "/" ;
    eval {
	system "/usr/sbin/urpmi.removemedia", "mdkupdate";
	system "/usr/sbin/urpmi.addmedia", "--update", "mdkupdate", $fullpath2mir, "with ../base/hdlist.cz";
    };
    $@ and die "Problem adding Update Media with urpmi";
}
sub getRelease() {
    my ($release) = cat_('/etc/mandrake-release') =~ /release\s+(\S+)/;
    ($release)
}
sub updatePkgs {
    my (@str) = @_;
    @str or return;
    eval {
	system "/usr/sbin/urpmi", "--auto", "--media", "mdkupdate", map { /^(.*)\.rpm$/ && $1 } @str;
	$? == 0 or die N("Unable to update packages from mdkupdate medium.\n");
    };
    $@ and die "Problem upgrading with urpmi";
}
sub send_rpm_dif {
    my ($login,$password,$box_name,$oldkey) =@_;
    #`sdiff -s /root/rpm_qa_installed_after /root/rpm_qa_installed_before >/root/$login.$password.$box_name.$oldkey.dif`;
    `sdiff -s /root/rpm_qa_installed_after /root/.mdkupdate.rpms >/root/$login.$password.$box_name.$oldkey.dif`;
    -s "/root/$login.$password.$box_name.$oldkey.dif" or die N("System is up to date");
    my $ua = LWP::UserAgent->new;
    $ua->agent("MdkOnlineAgent/$VERSION" . $ua->agent);
    $ua->env_proxy;
    my $response = $ua->request(POST "https://www.mandrakeonline.net/online_dif.php",

				Content_Type => 'form-data',
				Content => [submit => "upload_dif",
					    dif_file => ["/root/$login.$password.$box_name.$oldkey.dif"]
					    ]);
    #- update .mdkupdate.rpms with newer version just sent.
    if ($response->content =~ /TRUE/) {
	unlink "/root/.mdkupdate.rpms";
	rename "/root/rpm_qa_installed_after", "/root/.mdkupdate.rpms";
    } else { print "REPONSE: " . $response->content . "\n"; } 
}

sub clean_dir() {
    system("rm -f /root/*.dif /root/rpm_qa_installed_before /root/rpm_qa_installed_after");    
}

sub rpm_qa {
    my ($file) = @_;
    open (FILE,"> $file") || die "Couldn't open $file : $!"; 
    map { chomp; print FILE "$_" } join('', sort `rpm -qa`);
    close FILE;
}

sub log_i {
    local *LOG;
    open LOG, ">>/var/log/mdkupdate.log" or die "can't output to log file\n";
    print LOG @_;
    close LOG;
}

sub fatal {
    my ($comment)=@_;
    printf STDERR "%s\n", $comment; exit($_[0]);
}