3 # debianqueued -- daemon for managing Debian upload queues
5 # Copyright (C) 1997 Roman Hodek <Roman.Hodek@informatik.uni-erlangen.de>
6 # Copyright (C) 2001-2007 Ryan Murray <rmurray@debian.org>
7 # Copyright (C) 2008 Thomas Viehmann <tv@beamnet.de>
9 # This program is free software. You can redistribute it and/or
10 # modify it under the terms of the GNU General Public License as
11 # published by the Free Software Foundation: either version 2 or
12 # (at your option) any later version.
13 # This program comes with ABSOLUTELY NO WARRANTY!
20 use POSIX qw( strftime sys_stat_h sys_wait_h signal_h );
23 use Socket qw( PF_INET AF_INET SOCK_STREAM );
29 setlocale(&POSIX::LC_ALL, "C");
31 # ---------------------------------------------------------------------------
33 # ---------------------------------------------------------------------------
36 ( $conf::queued_dir = ( ( $0 !~ m,^/, ) ? POSIX::getcwd() . "/" : "" ) . $0 )
38 require "$conf::queued_dir/config";
39 my $junk = $conf::debug; # avoid spurious warnings about unused vars
40 $junk = $conf::ssh_key_file;
41 $junk = $conf::stray_remove_timeout;
42 $junk = $conf::problem_report_timeout;
43 $junk = $conf::queue_delay;
44 $junk = $conf::keep_files;
45 $junk = $conf::valid_files;
46 $junk = $conf::max_upload_retries;
47 $junk = $conf::upload_delay_1;
48 $junk = $conf::upload_delay_2;
49 $junk = $conf::check_md5sum;
52 $junk = $conf::ftpdebug;
53 $junk = $conf::ftptimeout;
54 $junk = @conf::nonus_packages;
55 $junk = @conf::test_binaries;
56 $junk = @conf::maintainer_mail;
57 $junk = @conf::targetdir_delayed;
58 $junk = $conf::mail ||= '/usr/sbin/sendmail';
59 $junk = $conf::overridemail;
60 $conf::target = "localhost" if $conf::upload_method eq "copy";
64 ( $main::progname = $0 ) =~ s,.*/,,;
66 ($main::hostname, undef, undef, undef, undef) = gethostbyname(hostname());
69 my $re_file_safe_prefix = qr/\A([a-zA-Z0-9][a-zA-Z0-9_.:~+-]*)/s;
70 my $re_file_safe = qr/$re_file_safe_prefix\z/s;
72 # extract -r and -k args
74 if ( @ARGV == 1 && $ARGV[0] =~ /^-[rk]$/ ) {
75 $main::arg = ( $ARGV[0] eq '-k' ) ? "kill" : "restart";
79 # test for another instance of the queued already running
80 my ( $pid, $delayed_dirs, $adelayedcore );
81 if ( open( PIDFILE, "<", $conf::pidfile ) ) {
82 chomp( $pid = <PIDFILE> );
86 # remove stale pid file
87 unlink($conf::pidfile);
88 } elsif ($main::arg) {
90 print "Killing running daemon (pid $pid) ...";
93 while ( kill( 0, $pid ) && $cnt-- > 0 ) {
97 if ( kill( 0, $pid ) ) {
98 print " failed!\nProcess $pid still running.\n";
102 if ( -e "$conf::incoming/core" ) {
103 unlink("$conf::incoming/core");
104 print "(Removed core file)\n";
106 for ( $delayed_dirs = 0 ;
107 $delayed_dirs <= $conf::max_delayed ;
111 sprintf( "$conf::incoming_delayed/core", $delayed_dirs );
112 if ( -e $adelayedcore ) {
113 unlink($adelayedcore);
114 print "(Removed core file)\n";
116 } ## end for ( $delayed_dirs = 0...
117 exit 0 if $main::arg eq "kill";
119 die "Another $main::progname is already running (pid $pid)\n"
120 if $pid && kill( 0, $pid );
122 } elsif ( $main::arg eq "kill" ) {
123 die "No daemon running\n";
124 } elsif ( $main::arg eq "restart" ) {
125 print "(No daemon running; starting anyway)\n";
128 # if started without arguments (initial invocation), then fork
131 # now go to background
132 die "$main::progname: fork failed: $!\n"
133 unless defined( $pid = fork );
136 # parent: wait for signal from child (SIGCHLD or SIGUSR1) and exit
137 my $sigset = POSIX::SigSet->new();
139 $SIG{"CHLD"} = sub { };
140 $SIG{"USR1"} = sub { };
141 POSIX::sigsuspend($sigset);
142 waitpid( $pid, WNOHANG );
143 if ( kill( 0, $pid ) ) {
144 print "Daemon (on $main::hostname) started in background (pid $pid)\n";
153 if ( $conf::upload_method eq "ssh" ) {
155 # exec an ssh-agent that starts us again
156 # force shell to be /bin/sh, ssh-agent may base its decision
157 # whether to use a fd or a Unix socket on the shell...
158 $ENV{"SHELL"} = "/bin/sh";
159 exec $conf::ssh_agent, $0, "startup", getppid();
160 die "$main::progname: Could not exec $conf::ssh_agent: $!\n";
163 # no need to exec, just set up @ARGV as expected below
164 @ARGV = ( "startup", getppid() );
166 } ## end else [ if ($pid)
167 } ## end if ( !@ARGV )
168 die "Please start without any arguments.\n"
169 if @ARGV != 2 || $ARGV[0] ne "startup";
170 my $parent_pid = $ARGV[1];
174 ( $version = 'Release: 0.95' ) =~ s/\$ ?//g;
175 print "debianqueued $version\n";
178 # check if all programs exist
180 foreach $prg ( $conf::gpg, $conf::ssh, $conf::scp, $conf::ssh_agent,
181 $conf::ssh_add, $conf::mail, $conf::mkfifo )
183 die "Required program $prg doesn't exist or isn't executable\n"
186 # check for correct upload method
187 die "Bad upload method '$conf::upload_method'.\n"
188 if $conf::upload_method ne "ssh"
189 && $conf::upload_method ne "ftp"
190 && $conf::upload_method ne "copy";
191 die "No keyrings\n" if !@conf::keyrings;
193 } ## end foreach $prg ( $conf::gpg, ...
194 die "statusfile path must be absolute."
195 if $conf::statusfile !~ m,^/,;
196 die "upload and target queue paths must be absolute."
197 if $conf::incoming !~ m,^/,
198 || $conf::incoming_delayed !~ m,^/,
199 || $conf::targetdir !~ m,^/,
200 || $conf::targetdir_delayed !~ m,^/,;
202 # ---------------------------------------------------------------------------
204 # ---------------------------------------------------------------------------
209 sub get_filelist_from_known_good_changes($);
210 sub age_delayed_queues();
211 sub process_changes($\@);
212 sub process_commands($);
213 sub age_delayed_queues();
214 sub is_on_target($\@);
215 sub copy_to_target(@);
218 sub check_incoming_writable();
220 sub write_status_file();
221 sub print_status($$$$$$);
222 sub format_status_num(\$$);
223 sub format_status_str(\$$);
234 sub check_incoming_writable();
242 sub try_to_get_mail_addr($$);
246 sub unblock_signals();
249 sub restart_statusd();
252 $ENV{"PATH"} = "/bin:/usr/bin";
253 $ENV{"IFS"} = "" if defined( $ENV{"IFS"} && $ENV{"IFS"} ne "" );
266 sub ST_CTIME() { 10 }
268 # fixed lengths of data items passed over status pipe
269 sub STATNUM_LEN() { 30 }
270 sub STATSTR_LEN() { 128 }
272 # init list of signals
273 defined $Config{sig_name}
274 or die "$main::progname: No signal list defined!\n";
277 foreach $name ( split( ' ', $Config{sig_name} ) ) {
278 $main::signo{$name} = $i++;
281 @main::fatal_signals = qw( INT QUIT ILL TRAP ABRT BUS FPE USR2 SEGV PIPE
282 TERM XCPU XFSZ PWR );
284 $main::block_sigset = POSIX::SigSet->new;
285 $main::block_sigset->addset( $main::signo{"INT"} );
286 $main::block_sigset->addset( $main::signo{"TERM"} );
288 # some constant net stuff
289 $main::tcp_proto = ( getprotobyname('tcp') )[2]
290 or die "Cannot get protocol number for 'tcp'\n";
291 my $used_service = ( $conf::upload_method eq "ssh" ) ? "ssh" : "ftp";
292 $main::echo_port = ( getservbyname( $used_service, 'tcp' ) )[2]
293 or die "Cannot get port number for service '$used_service'\n";
295 # clear queue of stored mails
296 @main::stored_mails = ();
298 # run ssh-add to bring the key into the agent (will use stdin/stdout)
299 if ( $conf::upload_method eq "ssh" ) {
300 system "$conf::ssh_add $conf::ssh_key_file"
301 and die "$main::progname: Running $conf::ssh_add failed "
302 . "(exit status ", $? >> 8, ")\n";
305 # change to queue dir
306 chdir($conf::incoming)
307 or die "$main::progname: cannot cd to $conf::incoming: $!\n";
309 # needed before /dev/null redirects, some system send a SIGHUP when loosing
310 # the controlling tty
311 $SIG{"HUP"} = "IGNORE";
313 # open logfile, make it unbuffered
314 open( LOG, ">>", $conf::logfile )
315 or die "Cannot open my logfile $conf::logfile: $!\n";
316 chmod( 0644, $conf::logfile )
317 or die "Cannot set modes of $conf::logfile: $!\n";
318 select( ( select(LOG), $| = 1 )[0] );
321 $SIG{"HUP"} = \&close_log;
323 # redirect stdin, ... to /dev/null
324 open( STDIN, "<", "/dev/null" )
325 or die "$main::progname: Can't redirect stdin to /dev/null: $!\n";
326 open( STDOUT, ">&", \*LOG )
327 or die "$main::progname: Can't redirect stdout to $conf::logfile: $!\n";
328 open( STDERR, ">&", \*LOG )
329 or die "$main::progname: Can't redirect stderr to $conf::logfile: $!\n";
331 # ok, from this point usually no "die" anymore, stderr is gone!
332 msg( "log", "daemon (pid $$) (on $main::hostname) started\n" );
334 # initialize variables used by send_status before launching the status daemon
336 format_status_num( $main::next_run, time + 10 );
337 format_status_str( $main::current_changes, "" );
339 $main::incoming_writable = 1; # assume this for now
341 # start the daemon watching the 'status' FIFO
342 if ( $conf::statusfile && $conf::statusdelay == 0 ) {
343 $main::statusd_pid = fork_statusd();
344 $SIG{"CHLD"} = \&kid_died; # watch out for dead status daemon
345 # SIGUSR1 triggers status info
346 $SIG{"USR1"} = \&send_status;
347 } ## end if ( $conf::statusfile...
348 $main::maind_pid = $$;
351 kill( $main::signo{"ABRT"}, $$ )
352 if defined $main::signo{"ABRT"};
356 open( PIDFILE, ">", $conf::pidfile )
357 or msg( "log", "Can't open $conf::pidfile: $!\n" );
358 printf PIDFILE "%5d\n", $$;
360 chmod( 0644, $conf::pidfile )
361 or die "Cannot set modes of $conf::pidfile: $!\n";
363 # other signals will just log an error and exit
364 foreach (@main::fatal_signals) {
365 $SIG{$_} = \&fatal_signal;
368 # send signal to user-started process that we're ready and it can exit
369 kill( $main::signo{"USR1"}, $parent_pid );
371 # ---------------------------------------------------------------------------
373 # ---------------------------------------------------------------------------
375 # default to classical incoming/target
376 $main::current_incoming = $conf::incoming;
377 $main::current_targetdir = $conf::targetdir;
380 write_status_file() if $conf::statusdelay;
383 # ping target only if there is the possibility that we'll contact it (but
384 # also don't wait too long).
385 my @have_changes = <*.changes *.commands *.dak-commands>;
386 for ( my $delayed_dirs = 0 ;
387 $delayed_dirs <= $conf::max_delayed ;
390 my $adelayeddir = sprintf( "$conf::incoming_delayed", $delayed_dirs );
391 push( @have_changes, <$adelayeddir/*.changes> );
392 } ## end for ( my $delayed_dirs ...
394 if @have_changes || ( time - $main::last_ping_time ) > 8 * 60 * 60;
396 if ( @have_changes && $main::target_up ) {
397 check_incoming_writable if !$main::incoming_writable;
398 check_dir() if $main::incoming_writable;
401 write_status_file() if $conf::statusdelay;
403 if ( $conf::upload_method eq "copy" ) {
404 age_delayed_queues();
407 # sleep() returns if we received a signal (SIGUSR1 for status FIFO), so
408 # calculate the end time once and wait for it being reached.
409 format_status_num( $main::next_run, time + $conf::queue_delay );
411 while ( ( $delta = calc_delta() ) > 0 ) {
412 debug("mainloop sleeping $delta secs");
415 # check if statusd died, if using status FIFO, or update status file
416 if ($conf::statusdelay) {
421 } ## end while ( ( $delta = calc_delta...
427 $delta = $main::next_run - time;
428 $delta = $conf::statusdelay
429 if $conf::statusdelay && $conf::statusdelay < $delta;
431 } ## end sub calc_delta()
433 # ---------------------------------------------------------------------------
434 # main working functions
435 # ---------------------------------------------------------------------------
438 # main function for checking the incoming dir
441 my ( @files, @changes, @keep_files, @this_keep_files, @stats, $file,
444 debug("starting checkdir");
446 write_status_file() if $conf::statusdelay;
448 # test if needed binaries are available; this is if they're on maybe
449 # slow-mounted NFS filesystems
450 foreach (@conf::test_binaries) {
453 # maybe the mount succeeds now
456 msg( "log", "binary test failed for $_; delaying queue run\n" );
458 } ## end foreach (@conf::test_binaries)
460 for ( $adelay = -1 ; $adelay <= $conf::max_delayed ; $adelay++ ) {
461 if ( $adelay == -1 ) {
462 $main::current_incoming = $conf::incoming;
463 $main::current_incoming_short = "";
464 $main::current_targetdir = $conf::targetdir;
466 $main::current_incoming = sprintf( $conf::incoming_delayed, $adelay );
467 $main::current_incoming_short = sprintf( "DELAYED/%d-day", $adelay );
468 $main::current_targetdir = sprintf( $conf::targetdir_delayed, $adelay );
471 # need to clear directory specific variables
473 undef(@this_keep_files);
475 chdir($main::current_incoming)
479 "Cannot change to dir "
480 . "${main::current_incoming_short}: $!\n"
485 # look for *.commands and *.dak-commands files but not in delayed queues
486 if ( $adelay == -1 ) {
487 foreach $file (<*.commands>) {
488 next unless $file =~ /$re_file_safe/;
491 process_commands($file);
494 write_status_file() if $conf::statusdelay;
496 } ## end foreach $file (<*.commands>)
497 foreach $file (<*.dak-commands>) {
498 next unless $file =~ /$re_file_safe/;
501 process_dak_commands($file);
504 write_status_file() if $conf::statusdelay;
507 } ## end if ( $adelay == -1 )
511 "log", "Cannot open dir ${main::current_incoming_short}: $!\n"
515 @files = readdir(INC);
518 # process all .changes files found
519 @changes = grep /\.changes$/, @files;
520 push( @keep_files, @changes ); # .changes files aren't stray
521 foreach $file (@changes) {
522 next unless $file =~ /$re_file_safe/;
525 # wrap in an eval to allow jumpbacks to here with die in case
528 eval { process_changes( $file, @this_keep_files ); };
530 msg( "log,mail", $@ ) if $@;
532 write_status_file() if $conf::statusdelay;
534 # files which are ok in conjunction with this .changes
535 debug("$file tells to keep @this_keep_files");
536 push( @keep_files, @this_keep_files );
539 # break out of this loop if the incoming dir has become unwritable
540 goto end_run if !$main::incoming_writable;
541 } ## end foreach $file (@changes)
542 ftp_close() if $conf::upload_method eq "ftp";
544 # find files which aren't related to any .changes
545 foreach $file (@files) {
547 # filter out files we never want to delete
548 next if !-f $file || # may have disappeared in the meantime
551 || ( grep { $_ eq $file } @keep_files )
552 || $file =~ /$conf::keep_files/;
554 # Delete such files if they're older than
555 # $stray_remove_timeout; they could be part of an
556 # yet-incomplete upload, with the .changes still missing.
557 # Cannot send any notification, since owner unknown.
558 next if !( @stats = stat($file) );
559 my $age = time - $stats[ST_MTIME];
560 my ( $maint, $pattern, @job_files );
561 if ( $file =~ /^junk-for-writable-test/
562 || $file !~ m,$conf::valid_files,
563 || $file !~ /$re_file_safe/
564 || $age >= $conf::stray_remove_timeout )
567 "Deleted stray file ${main::current_incoming_short}/$file\n" )
571 "found stray file ${main::current_incoming_short}/$file, deleting in ",
572 print_time( $conf::stray_remove_timeout - $age )
574 } ## end else [ if ( $file =~ /^junk-for-writable-test/...
575 } ## end foreach $file (@files)
576 } ## end for ( $adelay = -1 ; $adelay...
577 chdir($conf::incoming);
581 write_status_file() if $conf::statusdelay;
582 } ## end sub check_dir()
584 sub get_filelist_from_known_good_changes($) {
590 # parse the .changes file
591 open( CHANGES, "<", $changes )
592 or die "$changes: $!\n";
593 outer_loop: while (<CHANGES>) {
596 redo outer_loop if !/^\s/;
597 my @field = split(/\s+/);
600 # forbid shell meta chars in the name, we pass it to a
601 # subshell several times...
602 $field[5] =~ /$re_file_safe/;
603 if ( $1 ne $field[5] ) {
604 msg( "log", "found suspicious filename $field[5]\n" );
607 push( @filenames, $field[5] );
608 } ## end while (<CHANGES>)
609 } ## end if (/^Files:/i)
610 } ## end while (<CHANGES>)
613 } ## end sub get_filelist_from_known_good_changes($)
616 # process one .changes file
618 sub process_changes($\@) {
620 my $keep_list = shift;
622 $pgplines, @files, @filenames, @changes_stats,
623 $failure_file, $retries, $last_retry, $upload_time,
624 $file, $do_report, $ls_l, $problems_reported,
625 $errs, $pkgname, $signator, $extralines
630 format_status_str( $main::current_changes,
631 "$main::current_incoming_short/$changes" );
633 $main::mail_addr = "";
634 write_status_file() if $conf::statusdelay;
637 msg( "log", "processing ${main::current_incoming_short}/$changes\n" );
639 # run PGP on the file to check the signature
640 if ( !( $signator = pgp_check($changes) ) ) {
643 "$main::current_incoming_short/$changes has bad PGP/GnuPG signature!\n"
645 goto remove_only_changes;
646 } elsif ( $signator eq "LOCAL ERROR" ) {
648 # An error has appened when starting pgp... Don't process the file,
649 # but also don't delete it
651 "Can't PGP/GnuPG check $main::current_incoming_short/$changes -- don't process it for now"
654 } ## end elsif ( $signator eq "LOCAL ERROR")
656 # parse the .changes file
657 open( CHANGES, "<", $changes )
658 or die "Cannot open ${main::current_incoming_short}/$changes: $!\n";
662 outer_loop: while (<CHANGES>) {
663 if (/^---+(BEGIN|END) PGP .*---+$/) {
667 if ( $pgplines < 1 or $pgplines >= 3 ) {
668 $extralines++ if length $_ > 1;
671 if (/^Maintainer:\s*/i) {
672 chomp( $main::mail_addr = $' );
673 $main::mail_addr = $1 if $main::mail_addr =~ /<([^>]*)>/;
674 } elsif (/^Source:\s*/i) {
675 chomp( $pkgname = $' );
676 $pkgname =~ s/\s+$//;
677 $main::packages{$pkgname}++;
678 } elsif (/^Files:/i) {
680 redo outer_loop if !/^\s/;
681 my @field = split(/\s+/);
684 # forbid shell meta chars in the name, we pass it to a
685 # subshell several times...
686 $field[5] =~ /$re_file_safe/;
687 if ( $1 ne $field[5] ) {
688 msg( "log", "found suspicious filename $field[5]\n" );
691 "File '$field[5]' mentioned in $main::current_incoming_short/$changes\n",
692 "has bad characters in its name. Removed.\n"
696 } ## end if ( $1 ne $field[5] )
705 push( @filenames, $field[5] );
706 debug( "includes file $field[5], size $field[2], ", "md5 $field[1]" );
707 } ## end while (<CHANGES>)
708 } ## end elsif (/^Files:/i)
709 } ## end while (<CHANGES>)
712 # tell check_dir that the files mentioned in this .changes aren't stray,
713 # we know about them somehow
714 @$keep_list = @filenames;
716 # some consistency checks
719 "$main::current_incoming_short/$changes contained lines outside the pgp signed "
720 ."part, cannot process\n" );
721 goto remove_only_changes;
722 } ## end if ( $extralines )
723 if ( !$main::mail_addr ) {
725 "$main::current_incoming_short/$changes doesn't contain a Maintainer: field; "
726 . "cannot process\n" );
727 goto remove_only_changes;
728 } ## end if ( !$main::mail_addr)
729 if ( $main::mail_addr !~ /^(buildd_\S+-\S+|\S+\@\S+\.\S+)/ ) {
731 # doesn't look like a mail address, maybe only the name
732 my ( $new_addr, @addr_list );
733 if ( $new_addr = try_to_get_mail_addr( $main::mail_addr, \@addr_list ) ) {
735 # substitute (unique) found addr, but give a warning
738 "(The Maintainer: field didn't contain a proper "
743 "Looking for `$main::mail_addr' in the Debian "
744 . "keyring gave your address\n"
746 msg( "mail", "as unique result, so I used this.)\n" );
748 "Substituted $new_addr for malformed " . "$main::mail_addr\n" );
749 $main::mail_addr = $new_addr;
752 # not found or not unique: hold the job and inform queue maintainer
753 my $old_addr = $main::mail_addr;
754 $main::mail_addr = $conf::maintainer_mail;
757 "The job ${main::current_incoming_short}/$changes doesn't have a correct email\n"
759 msg( "mail", "address in the Maintainer: field:\n" );
760 msg( "mail", " $old_addr\n" );
761 msg( "mail", "A check for this in the Debian keyring gave:\n" );
764 ? " " . join( ", ", @addr_list ) . "\n"
766 msg( "mail", "Please fix this manually\n" );
769 "Bad Maintainer: field in ${main::current_incoming_short}/$changes: $old_addr\n"
771 goto remove_only_changes;
772 } ## end else [ if ( $new_addr = try_to_get_mail_addr...
773 } ## end if ( $main::mail_addr ...
774 if ( $pgplines < 3 ) {
777 "$main::current_incoming_short/$changes isn't signed with PGP/GnuPG\n"
779 msg( "log", "(uploader $main::mail_addr)\n" );
780 goto remove_only_changes;
781 } ## end if ( $pgplines < 3 )
784 "$main::current_incoming_short/$changes doesn't mention any files\n" );
785 msg( "log", "(uploader $main::mail_addr)\n" );
786 goto remove_only_changes;
787 } ## end if ( !@files )
789 # check for packages that shouldn't be processed
790 if ( grep( $_ eq $pkgname, @conf::nonus_packages ) ) {
793 "$pkgname is a package that must be uploaded "
794 . "to nonus.debian.org\n"
796 msg( "log,mail", "instead of target.\n" );
798 "Job rejected and removed all files belonging " . "to it:\n" );
799 msg( "log,mail", " ", join( ", ", @filenames ), "\n" );
800 rm( $changes, @filenames );
802 } ## end if ( grep( $_ eq $pkgname...
804 $failure_file = $changes . ".failures";
805 $retries = $last_retry = 0;
806 if ( -f $failure_file ) {
807 open( FAILS, "<", $failure_file )
808 or die "Cannot open $main::current_incoming_short/$failure_file: $!\n";
811 ( $retries, $last_retry ) = ( $1, $2 )
812 if $line =~ /^(\d+)\s+(\d+)$/;
813 push( @$keep_list, $failure_file );
814 } ## end if ( -f $failure_file )
816 die "Cannot stat ${main::current_incoming_short}/$changes (??): $!\n"
817 if !( @changes_stats = stat($changes) );
819 # Make $upload_time the maximum of all modification times of files
820 # related to this .changes (and the .changes it self). This is the
821 # last time something changes to these files.
822 $upload_time = $changes_stats[ST_MTIME];
825 next if !( @stats = stat( $file->{"name"} ) );
826 $file->{"stats"} = \@stats;
827 $upload_time = $stats[ST_MTIME] if $stats[ST_MTIME] > $upload_time;
828 } ## end for $file (@files)
830 $do_report = ( time - $upload_time ) > $conf::problem_report_timeout;
831 $problems_reported = $changes_stats[ST_MODE] & S_ISGID;
833 # if any of the files is newer than the .changes' ctime (the time
834 # we sent a report and set the sticky bit), send new problem reports
835 if ( $problems_reported && $changes_stats[ST_CTIME] < $upload_time ) {
836 $problems_reported = 0;
837 chmod +( $changes_stats[ST_MODE] &= ~S_ISGID ), $changes;
838 debug("upload_time>changes-ctime => resetting problems reported");
840 debug("do_report=$do_report problems_reported=$problems_reported");
842 # now check all files for correct size and md5 sum
844 my $filename = $file->{"name"};
845 if ( !defined( $file->{"stats"} ) ) {
847 # could be an upload that isn't complete yet, be quiet,
848 # but don't process the file;
849 msg( "log,mail", "$filename doesn't exist\n" )
850 if $do_report && !$problems_reported;
851 msg( "log", "$filename doesn't exist (ignored for now)\n" )
853 msg( "log", "$filename doesn't exist (already reported)\n" )
854 if $problems_reported;
856 } elsif ( $file->{"stats"}->[ST_SIZE] < $file->{"size"}
860 # could be an upload that isn't complete yet, be quiet,
861 # but don't process the file
862 msg( "log", "$filename is too small (ignored for now)\n" );
864 } elsif ( $file->{"stats"}->[ST_SIZE] != $file->{"size"} ) {
865 msg( "log,mail", "$filename has incorrect size; deleting it\n" );
868 } elsif ( md5sum($filename) ne $file->{"md5"} ) {
870 "$filename has incorrect md5 checksum; ",
874 } ## end elsif ( md5sum($filename)...
875 } ## end for $file (@files)
878 if ( ( time - $upload_time ) > $conf::bad_changes_timeout ) {
880 # if a .changes fails for a really long time (several days
881 # or so), remove it and all associated files
884 "$main::current_incoming_short/$changes couldn't be processed for ",
885 int( $conf::bad_changes_timeout / ( 60 * 60 ) ),
886 " hours and is now deleted\n"
888 msg( "log,mail", "All files it mentions are also removed:\n" );
889 msg( "log,mail", " ", join( ", ", @filenames ), "\n" );
890 rm( $changes, @filenames, $failure_file );
891 } elsif ( $do_report && !$problems_reported ) {
893 # otherwise, send a problem report, if not done already
896 "Due to the errors above, the .changes file couldn't ",
898 "Please fix the problems for the upload to happen.\n"
901 # remember we already have sent a mail regarding this file
902 debug("Sending problem report mail and setting SGID bit");
903 my $mode = $changes_stats[ST_MODE] |= S_ISGID;
904 msg( "log", "chmod failed: $!" )
905 if ( chmod( $mode, $changes ) != 1 );
906 } ## end elsif ( $do_report && !$problems_reported)
913 # if this upload already failed earlier, wait until the delay requirement
916 && ( time - $last_retry ) <
917 ( $retries == 1 ? $conf::upload_delay_1 : $conf::upload_delay_2 ) )
919 msg( "log", "delaying retry of upload\n" );
921 } ## end if ( $retries > 0 && (...
923 if ( $conf::upload_method eq "ftp" ) {
924 return if !ftp_open();
927 # check if the job is already present on target
928 # (moved to here, to avoid bothering target as long as there are errors in
930 if ( $ls_l = is_on_target( $changes, @filenames ) ) {
933 "$main::current_incoming_short/$changes is already present on target host:\n"
935 msg( "log,mail", "$ls_l\n" );
937 "Either you already uploaded it, or someone else ",
939 msg( "log,mail", "Job $changes removed.\n" );
940 rm( $changes, @filenames, $failure_file );
942 } ## end if ( $ls_l = is_on_target...
944 # clear sgid bit before upload, scp would copy it to target. We don't need
945 # it anymore, we know there are no problems if we come here. Also change
946 # mode of files to 644 if this should be done locally.
947 $changes_stats[ST_MODE] &= ~S_ISGID;
948 if ( !$conf::chmod_on_target ) {
949 $changes_stats[ST_MODE] &= ~0777;
950 $changes_stats[ST_MODE] |= 0644;
952 chmod +( $changes_stats[ST_MODE] ), $changes;
954 # try uploading to target
955 if ( !copy_to_target( $changes, @filenames ) ) {
957 # if the upload failed, increment the retry counter and remember the
958 # current time; both things are written to the .failures file. Don't
959 # increment the fail counter if the error was due to incoming
961 return if !$main::incoming_writable;
962 if ( ++$retries >= $conf::max_upload_retries ) {
964 "$changes couldn't be uploaded for $retries times now.\n" );
966 "Giving up and removing it and its associated files:\n" );
967 msg( "log,mail", " ", join( ", ", @filenames ), "\n" );
968 rm( $changes, @filenames, $failure_file );
971 if ( open( FAILS, ">", $failure_file ) ) {
972 print FAILS "$retries $last_retry\n";
974 chmod( 0600, $failure_file )
975 or die "Cannot set modes of $failure_file: $!\n";
976 } ## end if ( open( FAILS, ">$failure_file"...
977 push( @$keep_list, $failure_file );
978 debug("now $retries failed uploads");
981 "The upload will be retried in ",
984 ? $conf::upload_delay_1
985 : $conf::upload_delay_2
989 } ## end else [ if ( ++$retries >= $conf::max_upload_retries)
991 } ## end if ( !copy_to_target( ...
993 # If the files were uploaded ok, remove them
994 rm( $changes, @filenames, $failure_file );
996 msg( "mail", "$changes uploaded successfully to $conf::target\n" );
997 msg( "mail", "along with the files:\n ", join( "\n ", @filenames ),
1000 "$changes processed successfully (uploader $main::mail_addr)\n" );
1004 remove_only_changes:
1007 "Removing $main::current_incoming_short/$changes, but keeping its "
1008 . "associated files for now.\n"
1013 # Check for files that have the same stem as the .changes (and weren't
1014 # mentioned there) and delete them. It happens often enough that people
1015 # upload a .orig.tar.gz where it isn't needed and also not in the
1016 # .changes. Explicitly deleting it (and not waiting for the
1017 # $stray_remove_timeout) reduces clutter in the queue dir and maybe also
1018 # educates uploaders :-)
1020 # my $pattern = debian_file_stem( $changes );
1021 # my $spattern = substr( $pattern, 0, -1 ); # strip off '*' at end
1022 # my @other_files = glob($pattern);
1023 # filter out files that have a Debian revision at all and a different
1024 # revision. Those belong to a different upload.
1025 # if ($changes =~ /^\Q$spattern\E-([\d.+-]+)/) {
1026 # my $this_rev = $1;
1027 # @other_files = grep( !/^\Q$spattern\E-([\d.+-]+)/ || $1 eq $this_rev,
1030 # Also do not remove those files if a .changes is among them. Then there
1031 # is probably a second upload for another version or another architecture.
1032 # if (@other_files && !grep( /\.changes$/, @other_files )) {
1033 # rm( @other_files );
1034 # msg( "mail", "\nThe following file(s) seemed to belong to the same ".
1035 # "upload, but weren't listed\n" );
1036 # msg( "mail", "in the .changes file:\n " );
1037 # msg( "mail", join( "\n ", @other_files ), "\n" );
1038 # msg( "mail", "They have been deleted.\n" );
1039 # msg( "log", "Deleted files in upload not in $changes: @other_files\n" );
1041 } ## end sub process_changes($\@)
1044 # process one .dak-commands file
1046 sub process_dak_commands {
1047 my $commands = shift;
1049 msg("log", "processing ${main::current_incoming_short}/$commands\n");
1051 # TODO: get mail address from signed contents
1052 # and NOT implement a third parser for armored PGP...
1053 $main::mail_addr = undef;
1056 my $signator = pgp_check($commands);
1059 "$main::current_incoming_short/$commands has bad PGP/GnuPG signature!\n");
1061 "Removing $main::current_incoming_short/$commands\n");
1065 elsif ($signator eq 'LOCAL ERROR') {
1066 debug("Can't check signature for $main::current_incoming_short/$commands -- don't process it for now");
1069 msg("log,mail", "(PGP/GnuPG signature by $signator)\n");
1072 my @filenames = ($commands);
1073 if (my $ls_l = is_on_target($commands, @filenames)) {
1074 msg("log,mail", "$main::current_incoming_short/$commands is already present on target host:\n");
1075 msg("log,mail", "$ls_l\n");
1076 msg("log,mail", "Job $commands removed.\n");
1081 if (!copy_to_target($commands)) {
1082 msg("log,mail", "$commands couldn't be uploaded to target.\n");
1083 msg("log,mail", "Giving up and removing it.\n");
1089 msg("mail", "$commands uploaded successfully to $conf::target\n");
1093 # process one .commands file
1095 sub process_commands($) {
1096 my $commands = shift;
1097 my ( @cmds, $cmd, $pgplines, $signator );
1099 my ( @files, $file, @removed, $target_delay );
1101 format_status_str( $main::current_changes, $commands );
1103 $main::mail_addr = "";
1104 write_status_file() if $conf::statusdelay;
1106 msg( "log", "processing $main::current_incoming_short/$commands\n" );
1108 # run PGP on the file to check the signature
1109 if ( !( $signator = pgp_check($commands) ) ) {
1112 "$main::current_incoming_short/$commands has bad PGP/GnuPG signature!\n"
1115 } elsif ( $signator eq "LOCAL ERROR" ) {
1117 # An error has appened when starting pgp... Don't process the file,
1118 # but also don't delete it
1120 "Can't PGP/GnuPG check $main::current_incoming_short/$commands -- don't process it for now"
1123 } ## end elsif ( $signator eq "LOCAL ERROR")
1124 msg( "log", "(PGP/GnuPG signature by $signator)\n" );
1126 # parse the .commands file
1127 if ( !open( COMMANDS, "<", $commands ) ) {
1128 msg( "log", "Cannot open $main::current_incoming_short/$commands: $!\n" );
1133 outer_loop: while (<COMMANDS>) {
1134 if (/^---+(BEGIN|END) PGP .*---+$/) {
1136 } elsif (/^Uploader:\s*/i) {
1137 chomp( $main::mail_addr = $' );
1138 $main::mail_addr = $1 if $main::mail_addr =~ /<([^>]*)>/;
1139 } elsif (/^Commands:/i) {
1142 s/^\s*(.*)\s*$/$1/; # delete whitespace at both ends
1145 debug("includes cmd $_");
1147 last outer_loop if !defined( $_ = scalar(<COMMANDS>) );
1149 redo outer_loop if !/^\s/ || /^$/;
1150 } ## end for ( ; ; )
1151 } ## end elsif (/^Commands:/i)
1152 } ## end while (<COMMANDS>)
1155 # some consistency checks
1156 if ( !$main::mail_addr || $main::mail_addr !~ /^\S+\@\S+\.\S+/ ) {
1158 "$main::current_incoming_short/$commands contains no or bad Uploader: field: "
1159 . "$main::mail_addr\n" );
1161 "cannot process $main::current_incoming_short/$commands\n" );
1162 $main::mail_addr = "";
1164 } ## end if ( !$main::mail_addr...
1165 msg( "log", "(command uploader $main::mail_addr)\n" );
1167 if ( $pgplines < 3 ) {
1170 "$main::current_incoming_short/$commands isn't signed with PGP/GnuPG\n"
1174 "or the uploaded file is broken. Make sure to transfer in binary mode\n"
1176 msg( "mail", "or better yet - use dcut for commands files\n" );
1178 } ## end if ( $pgplines < 3 )
1180 # now process commands
1183 "Log of processing your commands file $main::current_incoming_short/$commands:\n\n"
1185 foreach $cmd (@cmds) {
1186 my @word = split( /\s+/, $cmd );
1187 msg( "mail,log", "> @word\n" );
1188 my $selecteddelayed = -1;
1191 if ( $word[0] eq "rm" ) {
1192 foreach ( @word[ 1 .. $#word ] ) {
1194 if (m,^DELAYED/([0-9]+)-day/,) {
1195 $selecteddelayed = $1;
1196 s,^DELAYED/[0-9]+-day/,,;
1199 msg("mail,log", "$_: filename component cannot start with a wildcard\n");
1200 } elsif ( $origword eq "--searchdirs" ) {
1201 $selecteddelayed = -2;
1205 "$_: filename may not contain slashes except for DELAYED/#-day/ prefixes\n"
1209 # process wildcards but also plain names
1211 my $pat = quotemeta($_);
1212 $pat =~ s/\\\*/.*/g;
1213 $pat =~ s/\\\?/.?/g;
1214 $pat =~ s/\\([][])/$1/g;
1216 if ( $selecteddelayed < 0 ) { # scanning or explicitly incoming
1217 opendir( DIR, "." );
1218 push( @thesefiles, grep /^$pat$/, readdir(DIR) );
1221 if ( $selecteddelayed >= 0 ) {
1222 my $dir = sprintf( $conf::incoming_delayed, $selecteddelayed );
1223 opendir( DIR, $dir );
1225 map ( "$dir/$_", grep /^$pat$/, readdir(DIR) ) );
1227 } elsif ( $selecteddelayed == -2 ) {
1228 for ( my ($adelay) = 0 ;
1229 ( !@thesefiles ) && $adelay <= $conf::max_delayed ;
1232 my $dir = sprintf( $conf::incoming_delayed, $adelay );
1233 opendir( DIR, $dir );
1235 map ( "$dir/$_", grep /^$pat$/, readdir(DIR) ) );
1237 } ## end for ( my ($adelay) = 0 ...
1238 } ## end elsif ( $selecteddelayed ...
1239 push( @files, @thesefiles );
1240 if ( !@thesefiles ) {
1241 msg( "mail,log", "$origword did not match anything\n" );
1243 } ## end else [ if ( $origword eq "--searchdirs")
1244 } ## end foreach ( @word[ 1 .. $#word...
1246 msg( "mail,log", "No files to delete\n" );
1249 foreach $file (@files) {
1251 msg( "mail,log", "$file: no such file\n" );
1252 } elsif ( $file =~ /$conf::keep_files/ ) {
1253 msg( "mail,log", "$file is protected, cannot " . "remove\n" );
1254 } elsif ( !unlink($file) ) {
1255 msg( "mail,log", "$file: rm: $!\n" );
1257 $file =~ s,$conf::incoming/?,,;
1258 push( @removed, $file );
1260 } ## end foreach $file (@files)
1261 msg( "mail,log", "Files removed: @removed\n" ) if @removed;
1262 } ## end else [ if ( !@files )
1263 } elsif ( $word[0] eq "reschedule" ) {
1265 msg( "mail,log", "Wrong number of arguments\n" );
1266 } elsif ( $conf::upload_method ne "copy" ) {
1267 msg( "mail,log", "reschedule not available\n" );
1268 } elsif ( $word[1] =~ m,/, || $word[1] !~ m/\.changes/ ) {
1271 "$word[1]: filename may not contain slashes and must be .changes\n"
1273 } elsif ( !( ($target_delay) = $word[2] =~ m,^([0-9]+)-day$, )
1274 || $target_delay > $conf::max_delayed )
1278 "$word[2]: rescheduling target must be #-day with # between 0 and $conf::max_delayed (in particular, no '/' allowed)\n"
1280 } elsif ( $word[1] =~ /$conf::keep_files/ ) {
1281 msg( "mail,log", "$word[1] is protected, cannot do stuff with it\n" );
1285 $adelay <= $conf::max_delayed
1287 sprintf( "$conf::targetdir_delayed", $adelay ) . "/$word[1]" ) ;
1290 } ## end for ( $adelay = 0 ; $adelay...
1291 if ( $adelay > $conf::max_delayed ) {
1292 msg( "mail,log", "$word[1] not found\n" );
1293 } elsif ( $adelay == $target_delay ) {
1294 msg( "mail,log", "$word[1] already is in $word[2]\n" );
1297 my ($dir) = sprintf( "$conf::targetdir_delayed", $adelay );
1299 sprintf( "$conf::targetdir_delayed", $target_delay );
1300 push( @thesefiles, $word[1] );
1302 get_filelist_from_known_good_changes("$dir/$word[1]") );
1303 for my $afile (@thesefiles) {
1304 if ( $afile =~ m/\.changes$/ ) {
1305 utime undef, undef, ("$dir/$afile");
1307 if ( !move("$dir/$afile", "$target_dir/$afile") ) {
1308 msg( "mail,log", "move: $!\n" );
1310 msg( "mail,log", "$afile moved to $target_delay-day\n" );
1312 } ## end for my $afile (@thesefiles)
1313 } ## end else [ if ( $adelay > $conf::max_delayed)
1314 } ## end else [ if ( @word != 3 )
1315 } elsif ( $word[0] eq "cancel" ) {
1317 msg( "mail,log", "Wrong number of arguments\n" );
1318 } elsif ( $conf::upload_method ne "copy" ) {
1319 msg( "mail,log", "cancel not available\n" );
1321 $word[1] !~ m,$re_file_safe_prefix\.changes\z, )
1324 "argument to cancel must be one .changes filename without path\n" );
1325 } ## end elsif ( $word[1] !~ ...
1327 for ( my ($adelay) = 0 ; $adelay <= $conf::max_delayed ; $adelay++ ) {
1328 my ($dir) = sprintf( "$conf::targetdir_delayed", $adelay );
1329 if ( -f "$dir/$word[1]" ) {
1331 push( @files, "$word[1]" );
1333 get_filelist_from_known_good_changes("$dir/$word[1]") );
1334 foreach $file (@files) {
1335 if ( !-f "$dir/$file" ) {
1336 msg( "mail,log", "$dir/$file: no such file\n" );
1337 } elsif ( "$dir/$file" =~ /$conf::keep_files/ ) {
1339 "$dir/$file is protected, cannot " . "remove\n" );
1340 } elsif ( !unlink("$dir/$file") ) {
1341 msg( "mail,log", "$dir/$file: rm: $!\n" );
1343 push( @removed, $file );
1345 } ## end foreach $file (@files)
1346 msg( "mail,log", "Files removed from $adelay-day: @removed\n" )
1348 } ## end if ( -f "$dir/$word[1]")
1349 } ## end for ( my ($adelay) = 0 ...
1351 msg( "mail,log", "No upload found: $word[1]\n" );
1354 msg( "mail,log", "unknown command $word[0]\n" );
1356 } ## end foreach $cmd (@cmds)
1359 "-- End of $main::current_incoming_short/$commands processing\n" );
1363 msg("log,mail", "Removing $main::current_incoming_short/$commands\n");
1366 } ## end sub process_commands($)
1368 sub age_delayed_queues() {
1369 for ( my ($adelay) = 0 ; $adelay <= $conf::max_delayed ; $adelay++ ) {
1370 my ($dir) = sprintf( "$conf::targetdir_delayed", $adelay );
1372 if ( $adelay == 0 ) {
1373 $target_dir = $conf::targetdir;
1375 $target_dir = sprintf( "$conf::targetdir_delayed", $adelay - 1 );
1377 for my $achanges (<$dir/*.changes>) {
1378 my $mtime = ( stat($achanges) )[9];
1379 if ( $mtime + 24 * 60 * 60 <= time || $adelay == 0 ) {
1380 utime undef, undef, ($achanges);
1381 my @thesefiles = ( $achanges =~ m,.*/([^/]*), );
1382 push( @thesefiles, get_filelist_from_known_good_changes($achanges) );
1383 for my $afile (@thesefiles) {
1384 if ( !move("$dir/$afile", "$target_dir/$afile") ) {
1385 msg( "log", "move: $!\n" );
1387 msg( "log", "$afile moved to $target_dir\n" );
1389 } ## end for my $afile (@thesefiles)
1390 } ## end if ( $mtime + 24 * 60 ...
1391 } ## end for my $achanges (<$dir/*.changes>)
1392 } ## end for ( my ($adelay) = 0 ...
1393 } ## end sub age_delayed_queues()
1396 # check if a file is already on target
1398 sub is_on_target($\@) {
1400 my $filelist = shift;
1404 if ( $conf::upload_method eq "ssh" ) {
1405 ( $msg, $stat ) = ssh_cmd("ls -l $file");
1406 } elsif ( $conf::upload_method eq "ftp" ) {
1408 ( $msg, $err ) = ftp_cmd( "dir", $file );
1414 $msg = "ls: no such file\n";
1417 $msg = join( "\n", @$msg );
1420 my @allfiles = ($file);
1421 push( @allfiles, @$filelist );
1423 $msg = "no such file";
1424 for my $afile (@allfiles) {
1425 if ( -f "$conf::targetdir/$afile" ) {
1429 } ## end for my $afile (@allfiles)
1430 for ( my ($adelay) = 0 ;
1431 $adelay <= $conf::max_delayed && $stat ;
1434 for my $afile (@allfiles) {
1436 -f ( sprintf( "$conf::targetdir_delayed", $adelay ) . "/$afile" ) )
1439 $msg = sprintf( "%d-day", $adelay ) . "/$afile";
1440 } ## end if ( -f ( sprintf( "$conf::targetdir_delayed"...
1441 } ## end for my $afile (@allfiles)
1442 } ## end for ( my ($adelay) = 0 ...
1443 } ## end else [ if ( $conf::upload_method...
1445 debug("exit status: $stat, output was: $msg");
1447 return "" if $stat && $msg =~ /no such file/i; # file not present
1448 msg( "log", "strange ls -l output on target:\n", $msg ), return ""
1449 if $stat || $@; # some other error, but still try to upload
1451 # ls -l returned 0 -> file already there
1452 $msg =~ s/\s\s+/ /g; # make multiple spaces into one, to save space
1454 } ## end sub is_on_target($\@)
1457 # copy a list of files to target
1459 sub copy_to_target(@) {
1461 my ( @md5sum, @expected_files, $sum, $name, $msgs, $stat );
1464 write_status_file() if $conf::statusdelay;
1467 if ( $conf::upload_method eq "ssh" ) {
1468 ( $msgs, $stat ) = scp_cmd(@files);
1470 } elsif ( $conf::upload_method eq "ftp" ) {
1472 if ( !$main::FTP_chan->cwd($main::current_targetdir) ) {
1474 "Can't cd to $main::current_targetdir on $conf::target\n" );
1477 foreach $file (@files) {
1478 ( $rv, $msgs ) = ftp_cmd( "put", $file );
1482 for my $file (@files) {
1483 eval { File::Copy::copy($file, $main::current_targetdir) };
1492 # check md5sums or sizes on target against our own
1493 my $have_md5sums = 1;
1494 if ($conf::check_md5sum) {
1495 if ( $conf::upload_method eq "ssh" ) {
1496 ( $msgs, $stat ) = ssh_cmd("md5sum @files");
1498 @md5sum = split( "\n", $msgs );
1499 } elsif ( $conf::upload_method eq "ftp" ) {
1500 my ( $rv, $err, $file );
1501 foreach $file (@files) {
1502 ( $rv, $err ) = ftp_cmd( "quot", "site", "md5sum", $file );
1504 next if ftp_code() == 550; # file not found
1505 if ( ftp_code() == 500 ) { # unimplemented
1507 goto get_sizes_instead;
1512 chomp( my $t = ftp_response() );
1513 push( @md5sum, $t );
1514 } ## end foreach $file (@files)
1515 if ( !$have_md5sums ) {
1517 foreach $file (@files) {
1518 ( $rv, $err ) = ftp_cmd( "size", $file );
1520 next if ftp_code() == 550; # file not found
1524 push( @md5sum, "$rv $file" );
1525 } ## end foreach $file (@files)
1526 } ## end if ( !$have_md5sums )
1528 for my $file (@files) {
1529 my $md5 = eval { md5sum("$main::current_targetdir/$file") };
1534 push @md5sum, "$md5 $file" if $md5;
1538 @expected_files = @files;
1541 ( $sum, $name ) = split;
1542 next if !grep { $_ eq $name } @files; # a file we didn't upload??
1543 next if $sum eq "md5sum:"; # looks like an error message
1544 if ( ( $have_md5sums && $sum ne md5sum($name) )
1545 || ( !$have_md5sums && $sum != ( -s $name ) ) )
1549 "Upload of $name to $conf::target failed ",
1550 "(" . ( $have_md5sums ? "md5sum" : "size" ) . " mismatch)\n"
1553 } ## end if ( ( $have_md5sums &&...
1555 # seen that file, remove it from expect list
1556 @expected_files = map { $_ eq $name ? () : $_ } @expected_files;
1557 } ## end foreach (@md5sum)
1558 if (@expected_files) {
1559 msg( "log,mail", "Failed to upload the files\n" );
1560 msg( "log,mail", " ", join( ", ", @expected_files ), "\n" );
1561 msg( "log,mail", "(Not present on target after upload)\n" );
1563 } ## end if (@expected_files)
1564 } ## end if ($conf::check_md5sum)
1566 if ($conf::chmod_on_target) {
1568 # change file's mode explicitly to 644 on target
1569 if ( $conf::upload_method eq "ssh" ) {
1570 ( $msgs, $stat ) = ssh_cmd("chmod 644 @files");
1572 } elsif ( $conf::upload_method eq "ftp" ) {
1574 foreach $file (@files) {
1575 ( $rv, $msgs ) = ftp_cmd( "quot", "site", "chmod", "644", $file );
1576 msg( "log", "Can't chmod $file on target:\n$msgs" )
1579 } ## end foreach $file (@files)
1581 for my $file (@files) {
1582 unless (chmod 0644, "$main::current_targetdir/$file") {
1583 $msgs = "Could not chmod $file: $!";
1588 } ## end if ($conf::chmod_on_target)
1591 write_status_file() if $conf::statusdelay;
1596 "Upload to $conf::target failed",
1597 $? ? ", last exit status " . sprintf( "%s", $? >> 8 ) : "", "\n" );
1598 msg( "log,mail", "Error messages:\n", $msgs )
1601 # If "permission denied" was among the errors, test if the incoming is
1603 if ( $msgs && $msgs =~ /(permission denied|read-?only file)/i ) {
1604 if ( !check_incoming_writable() ) {
1605 msg( "log,mail", "(The incoming directory seems to be ",
1608 } ## end if ( $msgs =~ /(permission denied|read-?only file)/i)
1610 # remove bad files or an incomplete upload on target
1611 if ( $conf::upload_method eq "ssh" ) {
1612 ssh_cmd("rm -f @files");
1613 } elsif ( $conf::upload_method eq "ftp" ) {
1615 foreach $file (@files) {
1617 ( $rv, $err ) = ftp_cmd( "delete", $file );
1618 msg( "log", "Can't delete $file on target:\n$err" )
1620 } ## end foreach $file (@files)
1622 my @tfiles = map { "$main::current_targetdir/$_" } @files;
1623 debug("executing unlink(@tfiles)");
1627 write_status_file() if $conf::statusdelay;
1629 } ## end sub copy_to_target(@)
1632 # check if a file is correctly signed with PGP
1643 if ($file =~ /$re_file_safe/) {
1646 msg( "log", "Tainted filename, skipping: $file\n" );
1647 return "LOCAL ERROR";
1650 # check the file has only one clear-signed section
1652 unless (open $fh, "<", $file) {
1653 msg("log,mail", "Could not open $file\n");
1656 unless (<$fh> eq "-----BEGIN PGP SIGNED MESSAGE-----\n") {
1657 msg("log,mail", "$file: does not start with a clearsigned message\n");
1663 msg("log,mail", "$file: dash-escaped messages are not accepted\n");
1666 elsif ($_ eq "-----BEGIN PGP SIGNATURE-----\n"
1667 || $_ eq "-----END PGP SIGNATURE-----\n") {
1671 msg("log,mail", "$file: unexpected OpenPGP armor\n");
1674 elsif ($pgplines > 3 && /\S/) {
1675 msg("log,mail", "$file: found text after end of signature\n");
1679 if ($pgplines != 3) {
1680 msg("log,mail", "$file: doesn't seem to be a valid clearsigned OpenPGP message\n");
1685 if ( -x $conf::gpg ) {
1686 my @command = ("$conf::gpg", "--no-options", "--batch", "--no-tty",
1687 "--trust-model", "always", "--no-default-keyring",
1688 (map +("--keyring" => $_), @conf::keyrings),
1690 debug( "executing " . join(" ", @command) );
1692 my $child = open(PIPE, "-|");
1693 if (!defined($child)) {
1694 msg("log", "Can't open pipe to $conf::gpg: $!\n");
1695 return "LOCAL ERROR";
1698 unless (open(STDERR, ">&", \*STDOUT)) {
1699 print "Could not redirect STDERR.";
1702 unless (open(STDIN, "<", $file)) {
1703 print "Could not open $file: $!";
1706 { exec(@command) }; # BLOCK avoids warning about likely unreachable code
1707 print "Could not exec gpg: $!";
1711 $output .= $_ while (<PIPE>);
1714 } ## end if ( -x $conf::gpg )
1717 msg( "log,mail", "GnuPG signature check failed on $file\n" );
1718 msg( "mail", $output );
1719 msg( "log,mail", "(Exit status ", $stat >> 8, ")\n" );
1723 $output =~ /^(gpg: )?good signature from (user )?"(.*)"\.?$/im;
1724 ( $signator = $3 ) ||= "unknown signator";
1726 debug("GnuPG signature ok (by $signator)");
1729 } ## end sub pgp_check($)
1731 # ---------------------------------------------------------------------------
1733 # ---------------------------------------------------------------------------
1736 # fork a subprocess that watches the 'status' FIFO
1738 # that process blocks until someone opens the FIFO, then sends a
1739 # signal (SIGUSR1) to the main process, expects
1741 sub fork_statusd() {
1747 $statusd_pid = open( STATUSD, "|-" );
1748 die "cannot fork: $!\n" if !defined($statusd_pid);
1750 # parent just returns
1752 msg( "log", "forked status daemon (pid $statusd_pid)\n" );
1753 return $statusd_pid;
1756 # child: the status FIFO daemon
1758 # ignore SIGPIPE here, in case some closes the FIFO without completely
1760 $SIG{"PIPE"} = "IGNORE";
1762 # also ignore SIGCLD, we don't want to inherit the restart-statusd handler
1764 $SIG{"CHLD"} = "DEFAULT";
1766 rm($conf::statusfile);
1767 $errs = `$conf::mkfifo $conf::statusfile`;
1768 die "$main::progname: cannot create named pipe $conf::statusfile: $errs"
1770 chmod( 0644, $conf::statusfile )
1771 or die "Cannot set modes of $conf::statusfile: $!\n";
1773 # close log file, so that log rotating works
1779 my ( $status, $mup, $incw, $ds, $next_run, $last_ping, $currch, $l );
1781 # open the FIFO for writing; this blocks until someone (probably ftpd)
1782 # opens it for reading
1783 open( STATFIFO, ">", $conf::statusfile )
1784 or die "Cannot open $conf::statusfile\n";
1787 # tell main daemon to send us status infos
1788 kill( $main::signo{"USR1"}, $main_pid );
1790 # get the infos from stdin; must loop until enough bytes received!
1791 my $expect_len = 3 + 2 * STATNUM_LEN + STATSTR_LEN;
1792 for ( $status = "" ; ( $l = length($status) ) < $expect_len ; ) {
1793 sysread( STDIN, $status, $expect_len - $l, $l );
1796 # disassemble the status byte stream
1802 [ next_run => STATNUM_LEN ],
1803 [ last_ping => STATNUM_LEN ],
1804 [ currch => STATSTR_LEN ]
1807 eval "\$$_->[0] = substr( \$status, $pos, $_->[1] );";
1809 } ## end foreach ( [ mup => 1 ], [ incw...
1810 $currch =~ s/\n+//g;
1812 print_status( $mup, $incw, $ds, $next_run, $last_ping, $currch );
1815 # This sleep is necessary so that we can't reopen the FIFO
1816 # immediately, in case the reader hasn't closed it yet if we get to
1817 # the open again. Is there a better solution for this??
1820 } ## end sub fork_statusd()
1823 # update the status file, in case we use a plain file and not a FIFO
1825 sub write_status_file() {
1827 return if !$conf::statusfile;
1829 open( STATFILE, ">", $conf::statusfile )
1830 or ( msg( "log", "Could not open $conf::statusfile: $!\n" ), return );
1831 my $oldsel = select(STATFILE);
1834 $main::target_up, $main::incoming_writable,
1835 $main::dstat, $main::next_run,
1836 $main::last_ping_time, $main::current_changes
1841 } ## end sub write_status_file()
1843 sub print_status($$$$$$) {
1847 my $next_run = shift;
1848 my $last_ping = shift;
1853 ( $version = 'Release: 0.9 $Revision: 1.51 $' ) =~ s/\$ ?//g;
1854 print "debianqueued $version\n";
1856 $approx = $conf::statusdelay ? "approx. " : "";
1858 if ( $mup eq "0" ) {
1859 print "$conf::target is down, queue pausing\n";
1861 } elsif ( $conf::upload_method ne "copy" ) {
1862 print "$conf::target seems to be up, last ping $approx",
1863 print_time( time - $last_ping ), " ago\n";
1866 if ( $incw eq "0" ) {
1867 print "The incoming directory is not writable, queue pausing\n";
1872 print "Next queue check in $approx", print_time( $next_run - time ), "\n";
1874 } elsif ( $ds eq "c" ) {
1875 print "Checking queue directory\n";
1876 } elsif ( $ds eq "u" ) {
1877 print "Uploading to $conf::target\n";
1879 print "Bad status data from daemon: \"$mup$incw$ds\"\n";
1883 print "Current job is $currch\n" if $currch;
1884 } ## end sub print_status($$$$$$)
1887 # format a number for sending to statusd (fixed length STATNUM_LEN)
1889 sub format_status_num(\$$) {
1893 $$varref = sprintf "%" . STATNUM_LEN . "d", $num;
1894 } ## end sub format_status_num(\$$)
1897 # format a string for sending to statusd (fixed length STATSTR_LEN)
1899 sub format_status_str(\$$) {
1903 $$varref = substr( $str, 0, STATSTR_LEN );
1904 $$varref .= "\n" x ( STATSTR_LEN - length($$varref) );
1905 } ## end sub format_status_str(\$$)
1908 # send a status string to the status daemon
1910 # Avoid all operations that could call malloc() here! Most libc
1911 # implementations aren't reentrant, so we may not call it from a
1912 # signal handler. So use only already-defined variables.
1915 local $! = 0; # preserve errno
1917 # re-setup handler, in case we have broken SysV signals
1918 $SIG{"USR1"} = \&send_status;
1920 syswrite( STATUSD, $main::target_up, 1 );
1921 syswrite( STATUSD, $main::incoming_writable, 1 );
1922 syswrite( STATUSD, $main::dstat, 1 );
1923 syswrite( STATUSD, $main::next_run, STATNUM_LEN );
1924 syswrite( STATUSD, $main::last_ping_time, STATNUM_LEN );
1925 syswrite( STATUSD, $main::current_changes, STATSTR_LEN );
1926 } ## end sub send_status()
1928 # ---------------------------------------------------------------------------
1930 # ---------------------------------------------------------------------------
1933 # open FTP connection to target host if not already open
1937 if ($main::FTP_chan) {
1939 # is already open, but might have timed out; test with a cwd
1940 return $main::FTP_chan
1941 if $main::FTP_chan->cwd($main::current_targetdir);
1943 # cwd didn't work, channel is closed, try to reopen it
1944 $main::FTP_chan = undef;
1945 } ## end if ($main::FTP_chan)
1952 Debug => $conf::ftpdebug,
1953 Timeout => $conf::ftptimeout,
1959 msg( "log,mail", "Cannot open FTP server $conf::target\n" );
1961 } ## end if ( !( $main::FTP_chan...
1962 if ( !$main::FTP_chan->login() ) {
1963 msg( "log,mail", "Anonymous login on FTP server $conf::target failed\n" );
1966 if ( !$main::FTP_chan->binary() ) {
1967 msg( "log,mail", "Can't set binary FTP mode on $conf::target\n" );
1970 if ( !$main::FTP_chan->cwd($main::current_targetdir) ) {
1972 "Can't cd to $main::current_targetdir on $conf::target\n" );
1975 debug("opened FTP channel to $conf::target");
1979 $main::FTP_chan = undef;
1981 } ## end sub ftp_open()
1986 my $direct_resp_cmd = ( $cmd eq "quot" );
1988 debug( "executing FTP::$cmd(" . join( ", ", @_ ) . ")" );
1989 $SIG{"ALRM"} = sub { die "timeout in FTP::$cmd\n" };
1990 alarm($conf::remote_timeout);
1991 eval { $rv = $main::FTP_chan->$cmd(@_); };
1994 $rv = ( ftp_code() =~ /^2/ ) ? 1 : 0 if $direct_resp_cmd;
1999 $err = ftp_response();
2001 return ( $rv, $err );
2002 } ## end sub ftp_cmd($@)
2005 if ($main::FTP_chan) {
2006 $main::FTP_chan->quit();
2007 $main::FTP_chan = undef;
2010 } ## end sub ftp_close()
2012 sub ftp_response() {
2013 return join( '', @{ ${*$main::FTP_chan}{'net_cmd_resp'} } );
2017 return ${*$main::FTP_chan}{'net_cmd_code'};
2021 my $code = ftp_code();
2022 return ( $code =~ /^[45]/ ) ? 1 : 0;
2025 # ---------------------------------------------------------------------------
2027 # ---------------------------------------------------------------------------
2033 my $ecmd = "$conf::ssh $conf::ssh_options $conf::target "
2034 . "-l $conf::targetlogin \'cd $main::current_targetdir; $cmd\'";
2035 debug("executing $ecmd");
2036 $SIG{"ALRM"} = sub { die "timeout in ssh command\n" };
2037 alarm($conf::remote_timeout);
2038 eval { $msg = `$ecmd 2>&1`; };
2046 return ( $msg, $stat );
2047 } ## end sub ssh_cmd($)
2052 my $ecmd = "$conf::scp $conf::ssh_options @_ "
2053 . "$conf::targetlogin\@$conf::target:$main::current_targetdir";
2054 debug("executing $ecmd");
2055 $SIG{"ALRM"} = sub { die "timeout in scp\n" };
2056 alarm($conf::remote_timeout);
2057 eval { $msg = `$ecmd 2>&1`; };
2065 return ( $msg, $stat );
2066 } ## end sub scp_cmd(@)
2069 # check if target is alive (code stolen from Net::Ping.pm)
2071 sub check_alive(;$) {
2072 my $timeout = shift;
2073 my ( $saddr, $ret, $target_ip );
2076 if ( $conf::upload_method eq "copy" ) {
2077 format_status_num( $main::last_ping_time, time );
2078 $main::target_up = 1;
2084 if ( !( $target_ip = ( gethostbyname($conf::target) )[4] ) ) {
2085 msg( "log", "Cannot get IP address of $conf::target\n" );
2089 $saddr = pack( 'S n a4 x8', AF_INET, $main::echo_port, $target_ip );
2090 $SIG{'ALRM'} = sub { die };
2093 $ret = $main::tcp_proto; # avoid warnings about unused variable
2096 return unless socket( PINGSOCK, PF_INET, SOCK_STREAM, $main::tcp_proto );
2097 return unless connect( PINGSOCK, $saddr );
2102 msg( "log", "pinging $conf::target: " . ( $ret ? "ok" : "down" ) . "\n" );
2104 $main::target_up = $ret ? "1" : "0";
2105 format_status_num( $main::last_ping_time, time );
2106 write_status_file() if $conf::statusdelay;
2107 } ## end sub check_alive(;$)
2110 # check if incoming dir on target is writable
2112 sub check_incoming_writable() {
2113 my $testfile = ".debianqueued-testfile";
2116 if ( $conf::upload_method eq "ssh" ) {
2118 ssh_cmd( "rm -f $testfile; touch $testfile; " . "rm -f $testfile" );
2119 } elsif ( $conf::upload_method eq "ftp" ) {
2120 my $file = "junk-for-writable-test-" . format_time();
2121 $file =~ s/[ :.]/-/g;
2123 open( F, ">", $file );
2126 ( $rv, $msg ) = ftp_cmd( "put", $file );
2128 $msg = "" if !defined $msg;
2130 ftp_cmd( "delete", $file );
2131 } elsif ( $conf::upload_method eq "copy" ) {
2132 unless(POSIX::access($main::current_targetdir, &POSIX::W_OK)) {
2133 $msg = "No write access: $!";
2138 debug("exit status: $stat, output was: $msg");
2142 # change incoming_writable only if ssh didn't return an error
2143 $main::incoming_writable =
2144 ( $msg =~ /(permission denied|read-?only file|cannot create)/i )
2148 debug("local error, keeping old status");
2150 debug("incoming_writable = $main::incoming_writable");
2151 write_status_file() if $conf::statusdelay;
2152 return $main::incoming_writable;
2153 } ## end sub check_incoming_writable()
2156 # remove a list of files, log failing ones
2162 ( unlink $_ and ++$done )
2164 or msg( "log", "Could not delete $_: $!\n" );
2170 # get md5 checksum of a file
2174 my $md5 = Digest::MD5->new;
2176 open my $fh, "<", $file or return "";
2180 return $md5->hexdigest;
2181 } ## end sub md5sum($)
2184 # output a messages to several destinations
2186 # first arg is a comma-separated list of destinations; valid are "log"
2187 # and "mail"; rest is stuff to be printed, just as with print
2190 my @dest = split( ',', shift );
2192 if ( grep /log/, @dest ) {
2193 my $now = format_time();
2194 print LOG "$now ", @_;
2197 if ( grep /mail/, @dest ) {
2198 $main::mail_text .= join( '', @_ );
2200 } ## end sub msg($@)
2203 # print a debug messages, if $debug is true
2206 return if !$conf::debug;
2207 my $now = format_time();
2208 print LOG "$now DEBUG ", @_, "\n";
2212 # intialize the "mail" destination of msg() (this clears text,
2213 # address, subject, ...)
2218 $main::mail_addr = "";
2219 $main::mail_text = "";
2220 %main::packages = ();
2221 $main::mail_subject = $file ? "Processing of $file" : "";
2222 } ## end sub init_mail(;$)
2225 # finalize mail to be sent from msg(): check if something present, and
2230 debug("No mail for $main::mail_addr")
2231 if $main::mail_addr && !$main::mail_text;
2232 return unless $main::mail_addr && $main::mail_text;
2234 if ( !send_mail( $main::mail_addr, $main::mail_subject, $main::mail_text ) )
2237 # store this mail in memory so it isn't lost if executing sendmail
2240 @main::stored_mails,
2242 addr => $main::mail_addr,
2243 subject => $main::mail_subject,
2244 text => $main::mail_text
2247 } ## end if ( !send_mail( $main::mail_addr...
2250 # try to send out stored mails
2252 while ( $mailref = shift(@main::stored_mails) ) {
2254 !send_mail( $mailref->{'addr'}, $mailref->{'subject'},
2255 $mailref->{'text'} )
2258 unshift( @main::stored_mails, $mailref );
2260 } ## end if ( !send_mail( $mailref...
2261 } ## end while ( $mailref = shift(...
2262 } ## end sub finish_mail()
2267 sub send_mail($$$) {
2269 my $subject = shift;
2273 keys %main::packages ? join( ' ', keys %main::packages ) : "";
2277 unless ( defined($Email::Send::Sendmail::SENDMAIL) ) {
2278 $Email::Send::Sendmail::SENDMAIL = $conf::mail;
2281 if ($conf::overridemail) {
2282 $addr = $conf::overridemail;
2285 my $date = sprintf "%s",
2286 strftime( "%a, %d %b %Y %T %z", ( localtime(time) ) );
2287 my $message = <<__MESSAGE__;
2289 From: Debian FTP Masters <ftpmaster\@ftp-master.debian.org>
2296 if ( length $package ) {
2297 $message .= "X-Debian-Package: $package\n";
2300 $message .= "\n$text";
2301 $message .= "\nGreetings,\n\n\tYour Debian queue daemon (running on host $main::hostname)\n";
2303 my $mail = Email::Send->new;
2304 for (qw[Sendmail SMTP]) {
2305 $mail->mailer($_) and last if $mail->mailer_available($_);
2308 my $ret = $mail->send($message);
2309 if ( $ret && $ret !~ /Message sent|success/ ) {
2314 } ## end sub send_mail($$$)
2317 # try to find a mail address for a name in the keyrings
2319 sub try_to_get_mail_addr($$) {
2321 my $listref = shift;
2325 "$conf::gpg --no-options --batch --no-default-keyring "
2326 . "--always-trust --keyring "
2327 . join( " --keyring ", @conf::keyrings )
2331 if ( /^pub / && / $name / ) {
2333 push( @$listref, $1 );
2335 } ## end while (<F>)
2338 return ( @$listref >= 1 ) ? $listref->[0] : "";
2339 } ## end sub try_to_get_mail_addr($$)
2342 # return current time as string
2347 # omit weekday and year for brevity
2348 ( $t = localtime ) =~ /^\w+\s(.*)\s\d+$/;
2350 } ## end sub format_time()
2354 my $hours = int( $secs / ( 60 * 60 ) );
2356 $secs -= $hours * 60 * 60;
2357 return sprintf "%d:%02d:%02d", $hours, int( $secs / 60 ), $secs % 60;
2358 } ## end sub print_time($)
2361 # block some signals during queue processing
2363 # This is just to avoid data inconsistency or uploads being aborted in the
2364 # middle. Only "soft" signals are blocked, i.e. SIGINT and SIGTERM, try harder
2365 # ones if you really want to kill the daemon at once.
2367 sub block_signals() {
2368 POSIX::sigprocmask( SIG_BLOCK, $main::block_sigset );
2371 sub unblock_signals() {
2372 POSIX::sigprocmask( SIG_UNBLOCK, $main::block_sigset );
2376 # process SIGHUP: close log file and reopen it (for logfile cycling)
2383 open( LOG, ">>", $conf::logfile )
2384 or die "Cannot open my logfile $conf::logfile: $!\n";
2385 chmod( 0644, $conf::logfile )
2386 or msg( "log", "Cannot set modes of $conf::logfile: $!\n" );
2387 select( ( select(LOG), $| = 1 )[0] );
2389 open( STDOUT, ">&", \*LOG )
2391 "$main::progname: Can't redirect stdout to " . "$conf::logfile: $!\n" );
2392 open( STDERR, ">&", \*LOG )
2394 "$main::progname: Can't redirect stderr to " . "$conf::logfile: $!\n" );
2395 msg( "log", "Restart after SIGHUP\n" );
2396 } ## end sub close_log($)
2399 # process SIGCHLD: check if it was our statusd process
2404 # reap statusd, so that it's no zombie when we try to kill(0) it
2405 waitpid( $main::statusd_pid, WNOHANG );
2407 # Uncomment the following line if your Perl uses unreliable System V signal
2408 # (i.e. if handlers reset to default if the signal is delivered).
2409 # (Unfortunately, the re-setup can't be done in any case, since on some
2410 # systems this will cause the SIGCHLD to be delivered again if there are
2411 # still unreaped children :-(( )
2413 # $SIG{"CHLD"} = \&kid_died; # resetup handler for SysV
2414 } ## end sub kid_died($)
2416 sub restart_statusd() {
2418 # restart statusd if it died
2419 if ( !kill( 0, $main::statusd_pid ) ) {
2420 close(STATUSD); # close out pipe end
2421 $main::statusd_pid = fork_statusd();
2423 } ## end sub restart_statusd()
2426 # process a fatal signal: cleanup and exit
2428 sub fatal_signal($) {
2429 my $signame = shift;
2432 # avoid recursions of fatal_signal in case of BSD signals
2433 foreach $sig (qw( ILL ABRT BUS FPE SEGV PIPE )) {
2434 $SIG{$sig} = "DEFAULT";
2437 if ( $$ == $main::maind_pid ) {
2439 # only the main daemon should do this
2440 kill( $main::signo{"TERM"}, $main::statusd_pid )
2441 if defined $main::statusd_pid;
2442 unlink( $conf::statusfile, $conf::pidfile );
2443 } ## end if ( $$ == $main::maind_pid)
2444 msg( "log", "Caught SIG$signame -- exiting (pid $$)\n" );
2446 } ## end sub fatal_signal($)