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");
32 # ---------------------------------------------------------------------------
34 # ---------------------------------------------------------------------------
37 ( $conf::queued_dir = ( ( $0 !~ m,^/, ) ? POSIX::getcwd() . "/" : "" ) . $0 )
39 require "$conf::queued_dir/config";
40 my $junk = $conf::debug; # avoid spurious warnings about unused vars
41 $junk = $conf::ssh_key_file;
42 $junk = $conf::stray_remove_timeout;
43 $junk = $conf::problem_report_timeout;
44 $junk = $conf::queue_delay;
45 $junk = $conf::keep_files;
46 $junk = $conf::valid_files;
47 $junk = $conf::max_upload_retries;
48 $junk = $conf::upload_delay_1;
49 $junk = $conf::upload_delay_2;
50 $junk = $conf::check_md5sum;
53 $junk = $conf::ftpdebug;
54 $junk = $conf::ftptimeout;
55 $junk = @conf::nonus_packages;
56 $junk = @conf::test_binaries;
57 $junk = @conf::maintainer_mail;
58 $junk = @conf::targetdir_delayed;
59 $junk = $conf::mail ||= '/usr/sbin/sendmail';
60 $junk = $conf::overridemail;
61 $conf::target = "localhost" if $conf::upload_method eq "copy";
65 ( $main::progname = $0 ) =~ s,.*/,,;
67 ($main::hostname, undef, undef, undef, undef) = gethostbyname(hostname());
70 my $re_file_safe_prefix = qr/\A([a-zA-Z0-9][a-zA-Z0-9_.:~+-]*)/s;
71 my $re_file_safe = qr/$re_file_safe_prefix\z/s;
73 # extract -r and -k args
75 if ( @ARGV == 1 && $ARGV[0] =~ /^-[rk]$/ ) {
76 $main::arg = ( $ARGV[0] eq '-k' ) ? "kill" : "restart";
80 # test for another instance of the queued already running
81 my ( $pid, $delayed_dirs, $adelayedcore );
82 if ( open( PIDFILE, "<", $conf::pidfile ) ) {
83 chomp( $pid = <PIDFILE> );
87 # remove stale pid file
88 unlink($conf::pidfile);
89 } elsif ($main::arg) {
91 print "Killing running daemon (pid $pid) ...";
94 while ( kill( 0, $pid ) && $cnt-- > 0 ) {
98 if ( kill( 0, $pid ) ) {
99 print " failed!\nProcess $pid still running.\n";
103 if ( -e "$conf::incoming/core" ) {
104 unlink("$conf::incoming/core");
105 print "(Removed core file)\n";
107 for ( $delayed_dirs = 0 ;
108 $delayed_dirs <= $conf::max_delayed ;
112 sprintf( "$conf::incoming_delayed/core", $delayed_dirs );
113 if ( -e $adelayedcore ) {
114 unlink($adelayedcore);
115 print "(Removed core file)\n";
117 } ## end for ( $delayed_dirs = 0...
118 exit 0 if $main::arg eq "kill";
120 die "Another $main::progname is already running (pid $pid)\n"
121 if $pid && kill( 0, $pid );
123 } elsif ( $main::arg eq "kill" ) {
124 die "No daemon running\n";
125 } elsif ( $main::arg eq "restart" ) {
126 print "(No daemon running; starting anyway)\n";
129 # if started without arguments (initial invocation), then fork
132 # now go to background
133 die "$main::progname: fork failed: $!\n"
134 unless defined( $pid = fork );
137 # parent: wait for signal from child (SIGCHLD or SIGUSR1) and exit
138 my $sigset = POSIX::SigSet->new();
140 $SIG{"CHLD"} = sub { };
141 $SIG{"USR1"} = sub { };
142 POSIX::sigsuspend($sigset);
143 waitpid( $pid, WNOHANG );
144 if ( kill( 0, $pid ) ) {
145 print "Daemon (on $main::hostname) started in background (pid $pid)\n";
154 if ( $conf::upload_method eq "ssh" ) {
156 # exec an ssh-agent that starts us again
157 # force shell to be /bin/sh, ssh-agent may base its decision
158 # whether to use a fd or a Unix socket on the shell...
159 $ENV{"SHELL"} = "/bin/sh";
160 exec $conf::ssh_agent, $0, "startup", getppid();
161 die "$main::progname: Could not exec $conf::ssh_agent: $!\n";
164 # no need to exec, just set up @ARGV as expected below
165 @ARGV = ( "startup", getppid() );
167 } ## end else [ if ($pid)
168 } ## end if ( !@ARGV )
169 die "Please start without any arguments.\n"
170 if @ARGV != 2 || $ARGV[0] ne "startup";
171 my $parent_pid = $ARGV[1];
175 ( $version = 'Release: 0.95' ) =~ s/\$ ?//g;
176 print "debianqueued $version\n";
179 # check if all programs exist
181 foreach $prg ( $conf::gpg, $conf::ssh, $conf::scp, $conf::ssh_agent,
182 $conf::ssh_add, $conf::mail, $conf::mkfifo )
184 die "Required program $prg doesn't exist or isn't executable\n"
187 # check for correct upload method
188 die "Bad upload method '$conf::upload_method'.\n"
189 if $conf::upload_method ne "ssh"
190 && $conf::upload_method ne "ftp"
191 && $conf::upload_method ne "copy";
192 die "No keyrings\n" if !@conf::keyrings;
194 } ## end foreach $prg ( $conf::gpg, ...
195 die "statusfile path must be absolute."
196 if $conf::statusfile !~ m,^/,;
197 die "upload and target queue paths must be absolute."
198 if $conf::incoming !~ m,^/,
199 || $conf::incoming_delayed !~ m,^/,
200 || $conf::targetdir !~ m,^/,
201 || $conf::targetdir_delayed !~ m,^/,;
203 # ---------------------------------------------------------------------------
205 # ---------------------------------------------------------------------------
210 sub get_filelist_from_known_good_changes($);
211 sub age_delayed_queues();
212 sub process_changes($\@);
213 sub process_commands($);
214 sub age_delayed_queues();
215 sub is_on_target($\@);
216 sub copy_to_target(@);
219 sub check_incoming_writable();
221 sub write_status_file();
222 sub print_status($$$$$$);
223 sub format_status_num(\$$);
224 sub format_status_str(\$$);
235 sub check_incoming_writable();
243 sub try_to_get_mail_addr($$);
247 sub unblock_signals();
250 sub restart_statusd();
253 $ENV{"PATH"} = "/bin:/usr/bin";
254 $ENV{"IFS"} = "" if defined( $ENV{"IFS"} && $ENV{"IFS"} ne "" );
267 sub ST_CTIME() { 10 }
269 # fixed lengths of data items passed over status pipe
270 sub STATNUM_LEN() { 30 }
271 sub STATSTR_LEN() { 128 }
273 # init list of signals
274 defined $Config{sig_name}
275 or die "$main::progname: No signal list defined!\n";
278 foreach $name ( split( ' ', $Config{sig_name} ) ) {
279 $main::signo{$name} = $i++;
282 @main::fatal_signals = qw( INT QUIT ILL TRAP ABRT BUS FPE USR2 SEGV PIPE
283 TERM XCPU XFSZ PWR );
285 $main::block_sigset = POSIX::SigSet->new;
286 $main::block_sigset->addset( $main::signo{"INT"} );
287 $main::block_sigset->addset( $main::signo{"TERM"} );
289 # some constant net stuff
290 $main::tcp_proto = ( getprotobyname('tcp') )[2]
291 or die "Cannot get protocol number for 'tcp'\n";
292 my $used_service = ( $conf::upload_method eq "ssh" ) ? "ssh" : "ftp";
293 $main::echo_port = ( getservbyname( $used_service, 'tcp' ) )[2]
294 or die "Cannot get port number for service '$used_service'\n";
296 # clear queue of stored mails
297 @main::stored_mails = ();
299 # run ssh-add to bring the key into the agent (will use stdin/stdout)
300 if ( $conf::upload_method eq "ssh" ) {
301 system "$conf::ssh_add $conf::ssh_key_file"
302 and die "$main::progname: Running $conf::ssh_add failed "
303 . "(exit status ", $? >> 8, ")\n";
306 # change to queue dir
307 chdir($conf::incoming)
308 or die "$main::progname: cannot cd to $conf::incoming: $!\n";
310 # needed before /dev/null redirects, some system send a SIGHUP when loosing
311 # the controlling tty
312 $SIG{"HUP"} = "IGNORE";
314 # open logfile, make it unbuffered
315 open( LOG, ">>", $conf::logfile )
316 or die "Cannot open my logfile $conf::logfile: $!\n";
317 chmod( 0644, $conf::logfile )
318 or die "Cannot set modes of $conf::logfile: $!\n";
319 select( ( select(LOG), $| = 1 )[0] );
322 $SIG{"HUP"} = \&close_log;
324 # redirect stdin, ... to /dev/null
325 open( STDIN, "<", "/dev/null" )
326 or die "$main::progname: Can't redirect stdin to /dev/null: $!\n";
327 open( STDOUT, ">&", \*LOG )
328 or die "$main::progname: Can't redirect stdout to $conf::logfile: $!\n";
329 open( STDERR, ">&", \*LOG )
330 or die "$main::progname: Can't redirect stderr to $conf::logfile: $!\n";
332 # ok, from this point usually no "die" anymore, stderr is gone!
333 msg( "log", "daemon (pid $$) (on $main::hostname) started\n" );
335 # initialize variables used by send_status before launching the status daemon
337 format_status_num( $main::next_run, time + 10 );
338 format_status_str( $main::current_changes, "" );
340 $main::incoming_writable = 1; # assume this for now
342 # start the daemon watching the 'status' FIFO
343 if ( $conf::statusfile && $conf::statusdelay == 0 ) {
344 $main::statusd_pid = fork_statusd();
345 $SIG{"CHLD"} = \&kid_died; # watch out for dead status daemon
346 # SIGUSR1 triggers status info
347 $SIG{"USR1"} = \&send_status;
348 } ## end if ( $conf::statusfile...
349 $main::maind_pid = $$;
352 kill( $main::signo{"ABRT"}, $$ )
353 if defined $main::signo{"ABRT"};
357 open( PIDFILE, ">", $conf::pidfile )
358 or msg( "log", "Can't open $conf::pidfile: $!\n" );
359 printf PIDFILE "%5d\n", $$;
361 chmod( 0644, $conf::pidfile )
362 or die "Cannot set modes of $conf::pidfile: $!\n";
364 # other signals will just log an error and exit
365 foreach (@main::fatal_signals) {
366 $SIG{$_} = \&fatal_signal;
369 # send signal to user-started process that we're ready and it can exit
370 kill( $main::signo{"USR1"}, $parent_pid );
372 # ---------------------------------------------------------------------------
374 # ---------------------------------------------------------------------------
376 # default to classical incoming/target
377 $main::current_incoming = $conf::incoming;
378 $main::current_targetdir = $conf::targetdir;
381 write_status_file() if $conf::statusdelay;
384 # ping target only if there is the possibility that we'll contact it (but
385 # also don't wait too long).
386 my @have_changes = <*.changes *.commands *.dak-commands>;
387 for ( my $delayed_dirs = 0 ;
388 $delayed_dirs <= $conf::max_delayed ;
391 my $adelayeddir = sprintf( "$conf::incoming_delayed", $delayed_dirs );
392 push( @have_changes, <$adelayeddir/*.changes> );
393 } ## end for ( my $delayed_dirs ...
395 if @have_changes || ( time - $main::last_ping_time ) > 8 * 60 * 60;
397 if ( @have_changes && $main::target_up ) {
398 check_incoming_writable if !$main::incoming_writable;
399 check_dir() if $main::incoming_writable;
402 write_status_file() if $conf::statusdelay;
404 if ( $conf::upload_method eq "copy" ) {
405 age_delayed_queues();
408 # sleep() returns if we received a signal (SIGUSR1 for status FIFO), so
409 # calculate the end time once and wait for it being reached.
410 format_status_num( $main::next_run, time + $conf::queue_delay );
412 while ( ( $delta = calc_delta() ) > 0 ) {
413 debug("mainloop sleeping $delta secs");
416 # check if statusd died, if using status FIFO, or update status file
417 if ($conf::statusdelay) {
422 } ## end while ( ( $delta = calc_delta...
428 $delta = $main::next_run - time;
429 $delta = $conf::statusdelay
430 if $conf::statusdelay && $conf::statusdelay < $delta;
432 } ## end sub calc_delta()
434 # ---------------------------------------------------------------------------
435 # main working functions
436 # ---------------------------------------------------------------------------
439 # main function for checking the incoming dir
442 my ( @files, @changes, @keep_files, @this_keep_files, @stats, $file,
445 debug("starting checkdir");
447 write_status_file() if $conf::statusdelay;
449 # test if needed binaries are available; this is if they're on maybe
450 # slow-mounted NFS filesystems
451 foreach (@conf::test_binaries) {
454 # maybe the mount succeeds now
457 msg( "log", "binary test failed for $_; delaying queue run\n" );
459 } ## end foreach (@conf::test_binaries)
461 for ( $adelay = -1 ; $adelay <= $conf::max_delayed ; $adelay++ ) {
462 if ( $adelay == -1 ) {
463 $main::current_incoming = $conf::incoming;
464 $main::current_incoming_short = "";
465 $main::current_targetdir = $conf::targetdir;
467 $main::current_incoming = sprintf( $conf::incoming_delayed, $adelay );
468 $main::current_incoming_short = sprintf( "DELAYED/%d-day", $adelay );
469 $main::current_targetdir = sprintf( $conf::targetdir_delayed, $adelay );
472 # need to clear directory specific variables
474 undef(@this_keep_files);
476 chdir($main::current_incoming)
480 "Cannot change to dir "
481 . "${main::current_incoming_short}: $!\n"
486 # look for *.commands and *.dak-commands files but not in delayed queues
487 if ( $adelay == -1 ) {
488 foreach $file (<*.commands>) {
489 next unless $file =~ /$re_file_safe/;
492 process_commands($file);
495 write_status_file() if $conf::statusdelay;
497 } ## end foreach $file (<*.commands>)
498 foreach $file (<*.dak-commands>) {
499 next unless $file =~ /$re_file_safe/;
502 process_dak_commands($file);
505 write_status_file() if $conf::statusdelay;
508 } ## end if ( $adelay == -1 )
512 "log", "Cannot open dir ${main::current_incoming_short}: $!\n"
516 @files = readdir(INC);
519 # process all .changes files found
520 @changes = grep /\.changes$/, @files;
521 push( @keep_files, @changes ); # .changes files aren't stray
522 foreach $file (@changes) {
523 next unless $file =~ /$re_file_safe/;
526 # wrap in an eval to allow jumpbacks to here with die in case
529 eval { process_changes( $file, @this_keep_files ); };
531 msg( "log,mail", $@ ) if $@;
533 write_status_file() if $conf::statusdelay;
535 # files which are ok in conjunction with this .changes
536 debug("$file tells to keep @this_keep_files");
537 push( @keep_files, @this_keep_files );
540 # break out of this loop if the incoming dir has become unwritable
541 goto end_run if !$main::incoming_writable;
542 } ## end foreach $file (@changes)
543 ftp_close() if $conf::upload_method eq "ftp";
545 # find files which aren't related to any .changes
546 foreach $file (@files) {
548 # filter out files we never want to delete
549 next if !-f $file || # may have disappeared in the meantime
552 || ( grep { $_ eq $file } @keep_files )
553 || $file =~ /$conf::keep_files/;
555 # Delete such files if they're older than
556 # $stray_remove_timeout; they could be part of an
557 # yet-incomplete upload, with the .changes still missing.
558 # Cannot send any notification, since owner unknown.
559 next if !( @stats = stat($file) );
560 my $age = time - $stats[ST_MTIME];
561 my ( $maint, $pattern, @job_files );
562 if ( $file =~ /^junk-for-writable-test/
563 || $file !~ m,$conf::valid_files,
564 || $file !~ /$re_file_safe/
565 || $age >= $conf::stray_remove_timeout )
568 "Deleted stray file ${main::current_incoming_short}/$file\n" )
572 "found stray file ${main::current_incoming_short}/$file, deleting in ",
573 print_time( $conf::stray_remove_timeout - $age )
575 } ## end else [ if ( $file =~ /^junk-for-writable-test/...
576 } ## end foreach $file (@files)
577 } ## end for ( $adelay = -1 ; $adelay...
578 chdir($conf::incoming);
582 write_status_file() if $conf::statusdelay;
583 } ## end sub check_dir()
585 sub get_filelist_from_known_good_changes($) {
591 # parse the .changes file
592 open( CHANGES, "<", $changes )
593 or die "$changes: $!\n";
594 outer_loop: while (<CHANGES>) {
597 redo outer_loop if !/^\s/;
598 my @field = split(/\s+/);
601 # forbid shell meta chars in the name, we pass it to a
602 # subshell several times...
603 $field[5] =~ /$re_file_safe/;
604 if ( $1 ne $field[5] ) {
605 msg( "log", "found suspicious filename $field[5]\n" );
608 push( @filenames, $field[5] );
609 } ## end while (<CHANGES>)
610 } ## end if (/^Files:/i)
611 } ## end while (<CHANGES>)
614 } ## end sub get_filelist_from_known_good_changes($)
617 # process one .changes file
619 sub process_changes($\@) {
621 my $keep_list = shift;
623 $pgplines, @files, @filenames, @changes_stats,
624 $failure_file, $retries, $last_retry, $upload_time,
625 $file, $do_report, $ls_l, $problems_reported,
626 $errs, $pkgname, $signator, $extralines
631 format_status_str( $main::current_changes,
632 "$main::current_incoming_short/$changes" );
634 $main::mail_addr = "";
635 write_status_file() if $conf::statusdelay;
638 msg( "log", "processing ${main::current_incoming_short}/$changes\n" );
640 # run PGP on the file to check the signature
641 if ( !( $signator = pgp_check($changes) ) ) {
644 "$main::current_incoming_short/$changes has bad PGP/GnuPG signature!\n"
646 goto remove_only_changes;
647 } elsif ( $signator eq "LOCAL ERROR" ) {
649 # An error has appened when starting pgp... Don't process the file,
650 # but also don't delete it
652 "Can't PGP/GnuPG check $main::current_incoming_short/$changes -- don't process it for now"
655 } ## end elsif ( $signator eq "LOCAL ERROR")
657 # parse the .changes file
658 open( CHANGES, "<", $changes )
659 or die "Cannot open ${main::current_incoming_short}/$changes: $!\n";
663 outer_loop: while (<CHANGES>) {
664 if (/^---+(BEGIN|END) PGP .*---+$/) {
668 if ( $pgplines < 1 or $pgplines >= 3 ) {
669 $extralines++ if length $_ > 1;
672 if (/^Maintainer:\s*/i) {
673 chomp( $main::mail_addr = $' );
674 $main::mail_addr = $1 if $main::mail_addr =~ /<([^>]*)>/;
675 } elsif (/^Source:\s*/i) {
676 chomp( $pkgname = $' );
677 $pkgname =~ s/\s+$//;
678 $main::packages{$pkgname}++;
679 } elsif (/^Files:/i) {
681 redo outer_loop if !/^\s/;
682 my @field = split(/\s+/);
685 # forbid shell meta chars in the name, we pass it to a
686 # subshell several times...
687 $field[5] =~ /$re_file_safe/;
688 if ( $1 ne $field[5] ) {
689 msg( "log", "found suspicious filename $field[5]\n" );
692 "File '$field[5]' mentioned in $main::current_incoming_short/$changes\n",
693 "has bad characters in its name. Removed.\n"
697 } ## end if ( $1 ne $field[5] )
706 push( @filenames, $field[5] );
707 debug( "includes file $field[5], size $field[2], ", "md5 $field[1]" );
708 } ## end while (<CHANGES>)
709 } ## end elsif (/^Files:/i)
710 } ## end while (<CHANGES>)
713 # tell check_dir that the files mentioned in this .changes aren't stray,
714 # we know about them somehow
715 @$keep_list = @filenames;
717 # some consistency checks
720 "$main::current_incoming_short/$changes contained lines outside the pgp signed "
721 ."part, cannot process\n" );
722 goto remove_only_changes;
723 } ## end if ( $extralines )
724 if ( !$main::mail_addr ) {
726 "$main::current_incoming_short/$changes doesn't contain a Maintainer: field; "
727 . "cannot process\n" );
728 goto remove_only_changes;
729 } ## end if ( !$main::mail_addr)
730 if ( $main::mail_addr !~ /^(buildd_\S+-\S+|\S+\@\S+\.\S+)/ ) {
732 # doesn't look like a mail address, maybe only the name
733 my ( $new_addr, @addr_list );
734 if ( $new_addr = try_to_get_mail_addr( $main::mail_addr, \@addr_list ) ) {
736 # substitute (unique) found addr, but give a warning
739 "(The Maintainer: field didn't contain a proper "
744 "Looking for `$main::mail_addr' in the Debian "
745 . "keyring gave your address\n"
747 msg( "mail", "as unique result, so I used this.)\n" );
749 "Substituted $new_addr for malformed " . "$main::mail_addr\n" );
750 $main::mail_addr = $new_addr;
753 # not found or not unique: hold the job and inform queue maintainer
754 my $old_addr = $main::mail_addr;
755 $main::mail_addr = $conf::maintainer_mail;
758 "The job ${main::current_incoming_short}/$changes doesn't have a correct email\n"
760 msg( "mail", "address in the Maintainer: field:\n" );
761 msg( "mail", " $old_addr\n" );
762 msg( "mail", "A check for this in the Debian keyring gave:\n" );
765 ? " " . join( ", ", @addr_list ) . "\n"
767 msg( "mail", "Please fix this manually\n" );
770 "Bad Maintainer: field in ${main::current_incoming_short}/$changes: $old_addr\n"
772 goto remove_only_changes;
773 } ## end else [ if ( $new_addr = try_to_get_mail_addr...
774 } ## end if ( $main::mail_addr ...
775 if ( $pgplines < 3 ) {
778 "$main::current_incoming_short/$changes isn't signed with PGP/GnuPG\n"
780 msg( "log", "(uploader $main::mail_addr)\n" );
781 goto remove_only_changes;
782 } ## end if ( $pgplines < 3 )
785 "$main::current_incoming_short/$changes doesn't mention any files\n" );
786 msg( "log", "(uploader $main::mail_addr)\n" );
787 goto remove_only_changes;
788 } ## end if ( !@files )
790 # check for packages that shouldn't be processed
791 if ( grep( $_ eq $pkgname, @conf::nonus_packages ) ) {
794 "$pkgname is a package that must be uploaded "
795 . "to nonus.debian.org\n"
797 msg( "log,mail", "instead of target.\n" );
799 "Job rejected and removed all files belonging " . "to it:\n" );
800 msg( "log,mail", " ", join( ", ", @filenames ), "\n" );
801 rm( $changes, @filenames );
803 } ## end if ( grep( $_ eq $pkgname...
805 $failure_file = $changes . ".failures";
806 $retries = $last_retry = 0;
807 if ( -f $failure_file ) {
808 open( FAILS, "<", $failure_file )
809 or die "Cannot open $main::current_incoming_short/$failure_file: $!\n";
812 ( $retries, $last_retry ) = ( $1, $2 )
813 if $line =~ /^(\d+)\s+(\d+)$/;
814 push( @$keep_list, $failure_file );
815 } ## end if ( -f $failure_file )
817 die "Cannot stat ${main::current_incoming_short}/$changes (??): $!\n"
818 if !( @changes_stats = stat($changes) );
820 # Make $upload_time the maximum of all modification times of files
821 # related to this .changes (and the .changes it self). This is the
822 # last time something changes to these files.
823 $upload_time = $changes_stats[ST_MTIME];
826 next if !( @stats = stat( $file->{"name"} ) );
827 $file->{"stats"} = \@stats;
828 $upload_time = $stats[ST_MTIME] if $stats[ST_MTIME] > $upload_time;
829 } ## end for $file (@files)
831 $do_report = ( time - $upload_time ) > $conf::problem_report_timeout;
832 $problems_reported = $changes_stats[ST_MODE] & S_ISGID;
834 # if any of the files is newer than the .changes' ctime (the time
835 # we sent a report and set the sticky bit), send new problem reports
836 if ( $problems_reported && $changes_stats[ST_CTIME] < $upload_time ) {
837 $problems_reported = 0;
838 chmod +( $changes_stats[ST_MODE] &= ~S_ISGID ), $changes;
839 debug("upload_time>changes-ctime => resetting problems reported");
841 debug("do_report=$do_report problems_reported=$problems_reported");
843 # now check all files for correct size and md5 sum
845 my $filename = $file->{"name"};
846 if ( !defined( $file->{"stats"} ) ) {
848 # could be an upload that isn't complete yet, be quiet,
849 # but don't process the file;
850 msg( "log,mail", "$filename doesn't exist\n" )
851 if $do_report && !$problems_reported;
852 msg( "log", "$filename doesn't exist (ignored for now)\n" )
854 msg( "log", "$filename doesn't exist (already reported)\n" )
855 if $problems_reported;
857 } elsif ( $file->{"stats"}->[ST_SIZE] < $file->{"size"}
861 # could be an upload that isn't complete yet, be quiet,
862 # but don't process the file
863 msg( "log", "$filename is too small (ignored for now)\n" );
865 } elsif ( $file->{"stats"}->[ST_SIZE] != $file->{"size"} ) {
866 msg( "log,mail", "$filename has incorrect size; deleting it\n" );
869 } elsif ( md5sum($filename) ne $file->{"md5"} ) {
871 "$filename has incorrect md5 checksum; ",
875 } ## end elsif ( md5sum($filename)...
876 } ## end for $file (@files)
879 if ( ( time - $upload_time ) > $conf::bad_changes_timeout ) {
881 # if a .changes fails for a really long time (several days
882 # or so), remove it and all associated files
885 "$main::current_incoming_short/$changes couldn't be processed for ",
886 int( $conf::bad_changes_timeout / ( 60 * 60 ) ),
887 " hours and is now deleted\n"
889 msg( "log,mail", "All files it mentions are also removed:\n" );
890 msg( "log,mail", " ", join( ", ", @filenames ), "\n" );
891 rm( $changes, @filenames, $failure_file );
892 } elsif ( $do_report && !$problems_reported ) {
894 # otherwise, send a problem report, if not done already
897 "Due to the errors above, the .changes file couldn't ",
899 "Please fix the problems for the upload to happen.\n"
902 # remember we already have sent a mail regarding this file
903 debug("Sending problem report mail and setting SGID bit");
904 my $mode = $changes_stats[ST_MODE] |= S_ISGID;
905 msg( "log", "chmod failed: $!" )
906 if ( chmod( $mode, $changes ) != 1 );
907 } ## end elsif ( $do_report && !$problems_reported)
914 # if this upload already failed earlier, wait until the delay requirement
917 && ( time - $last_retry ) <
918 ( $retries == 1 ? $conf::upload_delay_1 : $conf::upload_delay_2 ) )
920 msg( "log", "delaying retry of upload\n" );
922 } ## end if ( $retries > 0 && (...
924 return if !ftp_open();
926 # check if the job is already present on target
927 # (moved to here, to avoid bothering target as long as there are errors in
929 if ( $ls_l = is_on_target( $changes, @filenames ) ) {
932 "$main::current_incoming_short/$changes is already present on target host:\n"
934 msg( "log,mail", "$ls_l\n" );
936 "Either you already uploaded it, or someone else ",
938 msg( "log,mail", "Job $changes removed.\n" );
939 rm( $changes, @filenames, $failure_file );
941 } ## end if ( $ls_l = is_on_target...
943 # clear sgid bit before upload, scp would copy it to target. We don't need
944 # it anymore, we know there are no problems if we come here. Also change
945 # mode of files to 644 if this should be done locally.
946 $changes_stats[ST_MODE] &= ~S_ISGID;
947 if ( !$conf::chmod_on_target ) {
948 $changes_stats[ST_MODE] &= ~0777;
949 $changes_stats[ST_MODE] |= 0644;
951 chmod +( $changes_stats[ST_MODE] ), $changes;
953 # try uploading to target
954 if ( !copy_to_target( $changes, @filenames ) ) {
956 # if the upload failed, increment the retry counter and remember the
957 # current time; both things are written to the .failures file. Don't
958 # increment the fail counter if the error was due to incoming
960 return if !$main::incoming_writable;
961 if ( ++$retries >= $conf::max_upload_retries ) {
963 "$changes couldn't be uploaded for $retries times now.\n" );
965 "Giving up and removing it and its associated files:\n" );
966 msg( "log,mail", " ", join( ", ", @filenames ), "\n" );
967 rm( $changes, @filenames, $failure_file );
970 if ( open( FAILS, ">", $failure_file ) ) {
971 print FAILS "$retries $last_retry\n";
973 chmod( 0600, $failure_file )
974 or die "Cannot set modes of $failure_file: $!\n";
975 } ## end if ( open( FAILS, ">$failure_file"...
976 push( @$keep_list, $failure_file );
977 debug("now $retries failed uploads");
980 "The upload will be retried in ",
983 ? $conf::upload_delay_1
984 : $conf::upload_delay_2
988 } ## end else [ if ( ++$retries >= $conf::max_upload_retries)
990 } ## end if ( !copy_to_target( ...
992 # If the files were uploaded ok, remove them
993 rm( $changes, @filenames, $failure_file );
995 msg( "mail", "$changes uploaded successfully to $conf::target\n" );
996 msg( "mail", "along with the files:\n ", join( "\n ", @filenames ),
999 "$changes processed successfully (uploader $main::mail_addr)\n" );
1003 remove_only_changes:
1006 "Removing $main::current_incoming_short/$changes, but keeping its "
1007 . "associated files for now.\n"
1012 # Check for files that have the same stem as the .changes (and weren't
1013 # mentioned there) and delete them. It happens often enough that people
1014 # upload a .orig.tar.gz where it isn't needed and also not in the
1015 # .changes. Explicitly deleting it (and not waiting for the
1016 # $stray_remove_timeout) reduces clutter in the queue dir and maybe also
1017 # educates uploaders :-)
1019 # my $pattern = debian_file_stem( $changes );
1020 # my $spattern = substr( $pattern, 0, -1 ); # strip off '*' at end
1021 # my @other_files = glob($pattern);
1022 # filter out files that have a Debian revision at all and a different
1023 # revision. Those belong to a different upload.
1024 # if ($changes =~ /^\Q$spattern\E-([\d.+-]+)/) {
1025 # my $this_rev = $1;
1026 # @other_files = grep( !/^\Q$spattern\E-([\d.+-]+)/ || $1 eq $this_rev,
1029 # Also do not remove those files if a .changes is among them. Then there
1030 # is probably a second upload for another version or another architecture.
1031 # if (@other_files && !grep( /\.changes$/, @other_files )) {
1032 # rm( @other_files );
1033 # msg( "mail", "\nThe following file(s) seemed to belong to the same ".
1034 # "upload, but weren't listed\n" );
1035 # msg( "mail", "in the .changes file:\n " );
1036 # msg( "mail", join( "\n ", @other_files ), "\n" );
1037 # msg( "mail", "They have been deleted.\n" );
1038 # msg( "log", "Deleted files in upload not in $changes: @other_files\n" );
1040 } ## end sub process_changes($\@)
1043 # process one .dak-commands file
1045 sub process_dak_commands {
1046 my $commands = shift;
1048 msg("log", "processing ${main::current_incoming_short}/$commands\n");
1050 # TODO: get mail address from signed contents
1051 # and NOT implement a third parser for armored PGP...
1052 $main::mail_addr = undef;
1055 my $signator = pgp_check($commands);
1058 "$main::current_incoming_short/$commands has bad PGP/GnuPG signature!\n");
1060 "Removing $main::current_incoming_short/$commands\n");
1064 elsif ($signator eq 'LOCAL ERROR') {
1065 debug("Can't check signature for $main::current_incoming_short/$commands -- don't process it for now");
1068 msg("log,mail", "(PGP/GnuPG signature by $signator)\n");
1070 return if !ftp_open();
1073 my @filenames = ($commands);
1074 if (my $ls_l = is_on_target($commands, @filenames)) {
1075 msg("log,mail", "$main::current_incoming_short/$commands is already present on target host:\n");
1076 msg("log,mail", "$ls_l\n");
1077 msg("log,mail", "Job $commands removed.\n");
1082 if (!copy_to_target($commands)) {
1083 msg("log,mail", "$commands couldn't be uploaded to target.\n");
1084 msg("log,mail", "Giving up and removing it.\n");
1090 msg("mail", "$commands uploaded successfully to $conf::target\n");
1094 # process one .commands file
1096 sub process_commands($) {
1097 my $commands = shift;
1098 my ( @cmds, $cmd, $pgplines, $signator );
1100 my ( @files, $file, @removed, $target_delay );
1102 format_status_str( $main::current_changes, $commands );
1104 $main::mail_addr = "";
1105 write_status_file() if $conf::statusdelay;
1107 msg( "log", "processing $main::current_incoming_short/$commands\n" );
1109 # run PGP on the file to check the signature
1110 if ( !( $signator = pgp_check($commands) ) ) {
1113 "$main::current_incoming_short/$commands has bad PGP/GnuPG signature!\n"
1116 } elsif ( $signator eq "LOCAL ERROR" ) {
1118 # An error has appened when starting pgp... Don't process the file,
1119 # but also don't delete it
1121 "Can't PGP/GnuPG check $main::current_incoming_short/$commands -- don't process it for now"
1124 } ## end elsif ( $signator eq "LOCAL ERROR")
1125 msg( "log", "(PGP/GnuPG signature by $signator)\n" );
1127 # parse the .commands file
1128 if ( !open( COMMANDS, "<", $commands ) ) {
1129 msg( "log", "Cannot open $main::current_incoming_short/$commands: $!\n" );
1134 outer_loop: while (<COMMANDS>) {
1135 if (/^---+(BEGIN|END) PGP .*---+$/) {
1137 } elsif (/^Uploader:\s*/i) {
1138 chomp( $main::mail_addr = $' );
1139 $main::mail_addr = $1 if $main::mail_addr =~ /<([^>]*)>/;
1140 } elsif (/^Commands:/i) {
1143 s/^\s*(.*)\s*$/$1/; # delete whitespace at both ends
1146 debug("includes cmd $_");
1148 last outer_loop if !defined( $_ = scalar(<COMMANDS>) );
1150 redo outer_loop if !/^\s/ || /^$/;
1151 } ## end for ( ; ; )
1152 } ## end elsif (/^Commands:/i)
1153 } ## end while (<COMMANDS>)
1156 # some consistency checks
1157 if ( !$main::mail_addr || $main::mail_addr !~ /^\S+\@\S+\.\S+/ ) {
1159 "$main::current_incoming_short/$commands contains no or bad Uploader: field: "
1160 . "$main::mail_addr\n" );
1162 "cannot process $main::current_incoming_short/$commands\n" );
1163 $main::mail_addr = "";
1165 } ## end if ( !$main::mail_addr...
1166 msg( "log", "(command uploader $main::mail_addr)\n" );
1168 if ( $pgplines < 3 ) {
1171 "$main::current_incoming_short/$commands isn't signed with PGP/GnuPG\n"
1175 "or the uploaded file is broken. Make sure to transfer in binary mode\n"
1177 msg( "mail", "or better yet - use dcut for commands files\n" );
1179 } ## end if ( $pgplines < 3 )
1181 # now process commands
1184 "Log of processing your commands file $main::current_incoming_short/$commands:\n\n"
1186 foreach $cmd (@cmds) {
1187 my @word = split( /\s+/, $cmd );
1188 msg( "mail,log", "> @word\n" );
1189 my $selecteddelayed = -1;
1192 if ( $word[0] eq "rm" ) {
1193 foreach ( @word[ 1 .. $#word ] ) {
1195 if (m,^DELAYED/([0-9]+)-day/,) {
1196 $selecteddelayed = $1;
1197 s,^DELAYED/[0-9]+-day/,,;
1200 msg("mail,log", "$_: filename component cannot start with a wildcard\n");
1201 } elsif ( $origword eq "--searchdirs" ) {
1202 $selecteddelayed = -2;
1206 "$_: filename may not contain slashes except for DELAYED/#-day/ prefixes\n"
1210 # process wildcards but also plain names
1212 my $pat = quotemeta($_);
1213 $pat =~ s/\\\*/.*/g;
1214 $pat =~ s/\\\?/.?/g;
1215 $pat =~ s/\\([][])/$1/g;
1217 if ( $selecteddelayed < 0 ) { # scanning or explicitly incoming
1218 opendir( DIR, "." );
1219 push( @thesefiles, grep /^$pat$/, readdir(DIR) );
1222 if ( $selecteddelayed >= 0 ) {
1223 my $dir = sprintf( $conf::incoming_delayed, $selecteddelayed );
1224 opendir( DIR, $dir );
1226 map ( "$dir/$_", grep /^$pat$/, readdir(DIR) ) );
1228 } elsif ( $selecteddelayed == -2 ) {
1229 for ( my ($adelay) = 0 ;
1230 ( !@thesefiles ) && $adelay <= $conf::max_delayed ;
1233 my $dir = sprintf( $conf::incoming_delayed, $adelay );
1234 opendir( DIR, $dir );
1236 map ( "$dir/$_", grep /^$pat$/, readdir(DIR) ) );
1238 } ## end for ( my ($adelay) = 0 ...
1239 } ## end elsif ( $selecteddelayed ...
1240 push( @files, @thesefiles );
1241 if ( !@thesefiles ) {
1242 msg( "mail,log", "$origword did not match anything\n" );
1244 } ## end else [ if ( $origword eq "--searchdirs")
1245 } ## end foreach ( @word[ 1 .. $#word...
1247 msg( "mail,log", "No files to delete\n" );
1250 foreach $file (@files) {
1252 msg( "mail,log", "$file: no such file\n" );
1253 } elsif ( $file =~ /$conf::keep_files/ ) {
1254 msg( "mail,log", "$file is protected, cannot " . "remove\n" );
1255 } elsif ( !unlink($file) ) {
1256 msg( "mail,log", "$file: rm: $!\n" );
1258 $file =~ s,$conf::incoming/?,,;
1259 push( @removed, $file );
1261 } ## end foreach $file (@files)
1262 msg( "mail,log", "Files removed: @removed\n" ) if @removed;
1263 } ## end else [ if ( !@files )
1264 } elsif ( $word[0] eq "reschedule" ) {
1266 msg( "mail,log", "Wrong number of arguments\n" );
1267 } elsif ( $conf::upload_method ne "copy" ) {
1268 msg( "mail,log", "reschedule not available\n" );
1269 } elsif ( $word[1] =~ m,/, || $word[1] !~ m/\.changes/ ) {
1272 "$word[1]: filename may not contain slashes and must be .changes\n"
1274 } elsif ( !( ($target_delay) = $word[2] =~ m,^([0-9]+)-day$, )
1275 || $target_delay > $conf::max_delayed )
1279 "$word[2]: rescheduling target must be #-day with # between 0 and $conf::max_delayed (in particular, no '/' allowed)\n"
1281 } elsif ( $word[1] =~ /$conf::keep_files/ ) {
1282 msg( "mail,log", "$word[1] is protected, cannot do stuff with it\n" );
1286 $adelay <= $conf::max_delayed
1288 sprintf( "$conf::targetdir_delayed", $adelay ) . "/$word[1]" ) ;
1291 } ## end for ( $adelay = 0 ; $adelay...
1292 if ( $adelay > $conf::max_delayed ) {
1293 msg( "mail,log", "$word[1] not found\n" );
1294 } elsif ( $adelay == $target_delay ) {
1295 msg( "mail,log", "$word[1] already is in $word[2]\n" );
1298 my ($dir) = sprintf( "$conf::targetdir_delayed", $adelay );
1300 sprintf( "$conf::targetdir_delayed", $target_delay );
1301 push( @thesefiles, $word[1] );
1303 get_filelist_from_known_good_changes("$dir/$word[1]") );
1304 for my $afile (@thesefiles) {
1305 if ( $afile =~ m/\.changes$/ ) {
1306 utime undef, undef, ("$dir/$afile");
1308 if ( !move("$dir/$afile", "$target_dir/$afile") ) {
1309 msg( "mail,log", "move: $!\n" );
1311 msg( "mail,log", "$afile moved to $target_delay-day\n" );
1313 } ## end for my $afile (@thesefiles)
1314 } ## end else [ if ( $adelay > $conf::max_delayed)
1315 } ## end else [ if ( @word != 3 )
1316 } elsif ( $word[0] eq "cancel" ) {
1318 msg( "mail,log", "Wrong number of arguments\n" );
1319 } elsif ( $conf::upload_method ne "copy" ) {
1320 msg( "mail,log", "cancel not available\n" );
1322 $word[1] !~ m,$re_file_safe_prefix\.changes\z, )
1325 "argument to cancel must be one .changes filename without path\n" );
1326 } ## end elsif ( $word[1] !~ ...
1328 for ( my ($adelay) = 0 ; $adelay <= $conf::max_delayed ; $adelay++ ) {
1329 my ($dir) = sprintf( "$conf::targetdir_delayed", $adelay );
1330 if ( -f "$dir/$word[1]" ) {
1332 push( @files, "$word[1]" );
1334 get_filelist_from_known_good_changes("$dir/$word[1]") );
1335 foreach $file (@files) {
1336 if ( !-f "$dir/$file" ) {
1337 msg( "mail,log", "$dir/$file: no such file\n" );
1338 } elsif ( "$dir/$file" =~ /$conf::keep_files/ ) {
1340 "$dir/$file is protected, cannot " . "remove\n" );
1341 } elsif ( !unlink("$dir/$file") ) {
1342 msg( "mail,log", "$dir/$file: rm: $!\n" );
1344 push( @removed, $file );
1346 } ## end foreach $file (@files)
1347 msg( "mail,log", "Files removed from $adelay-day: @removed\n" )
1349 } ## end if ( -f "$dir/$word[1]")
1350 } ## end for ( my ($adelay) = 0 ...
1352 msg( "mail,log", "No upload found: $word[1]\n" );
1355 msg( "mail,log", "unknown command $word[0]\n" );
1357 } ## end foreach $cmd (@cmds)
1360 "-- End of $main::current_incoming_short/$commands processing\n" );
1364 msg("log,mail", "Removing $main::current_incoming_short/$commands\n");
1367 } ## end sub process_commands($)
1369 sub age_delayed_queues() {
1370 for ( my ($adelay) = 0 ; $adelay <= $conf::max_delayed ; $adelay++ ) {
1371 my ($dir) = sprintf( "$conf::targetdir_delayed", $adelay );
1373 if ( $adelay == 0 ) {
1374 $target_dir = $conf::targetdir;
1376 $target_dir = sprintf( "$conf::targetdir_delayed", $adelay - 1 );
1378 for my $achanges (<$dir/*.changes>) {
1379 my $mtime = ( stat($achanges) )[9];
1380 if ( $mtime + 24 * 60 * 60 <= time || $adelay == 0 ) {
1381 utime undef, undef, ($achanges);
1382 my @thesefiles = ( $achanges =~ m,.*/([^/]*), );
1383 push( @thesefiles, get_filelist_from_known_good_changes($achanges) );
1384 for my $afile (@thesefiles) {
1385 if ( !move("$dir/$afile", "$target_dir/$afile") ) {
1386 msg( "log", "move: $!\n" );
1388 msg( "log", "$afile moved to $target_dir\n" );
1390 } ## end for my $afile (@thesefiles)
1391 } ## end if ( $mtime + 24 * 60 ...
1392 } ## end for my $achanges (<$dir/*.changes>)
1393 } ## end for ( my ($adelay) = 0 ...
1394 } ## end sub age_delayed_queues()
1397 # check if a file is already on target
1399 sub is_on_target($\@) {
1401 my $filelist = shift;
1405 if ( $conf::upload_method eq "ssh" ) {
1406 ( $msg, $stat ) = ssh_cmd("ls -l $file");
1407 } elsif ( $conf::upload_method eq "ftp" ) {
1409 ( $msg, $err ) = ftp_cmd( "dir", $file );
1415 $msg = "ls: no such file\n";
1418 $msg = join( "\n", @$msg );
1421 my @allfiles = ($file);
1422 push( @allfiles, @$filelist );
1424 $msg = "no such file";
1425 for my $afile (@allfiles) {
1426 if ( -f "$conf::targetdir/$afile" ) {
1430 } ## end for my $afile (@allfiles)
1431 for ( my ($adelay) = 0 ;
1432 $adelay <= $conf::max_delayed && $stat ;
1435 for my $afile (@allfiles) {
1437 -f ( sprintf( "$conf::targetdir_delayed", $adelay ) . "/$afile" ) )
1440 $msg = sprintf( "%d-day", $adelay ) . "/$afile";
1441 } ## end if ( -f ( sprintf( "$conf::targetdir_delayed"...
1442 } ## end for my $afile (@allfiles)
1443 } ## end for ( my ($adelay) = 0 ...
1444 } ## end else [ if ( $conf::upload_method...
1446 debug("exit status: $stat, output was: $msg");
1448 return "" if $stat && $msg =~ /no such file/i; # file not present
1449 msg( "log", "strange ls -l output on target:\n", $msg ), return ""
1450 if $stat || $@; # some other error, but still try to upload
1452 # ls -l returned 0 -> file already there
1453 $msg =~ s/\s\s+/ /g; # make multiple spaces into one, to save space
1455 } ## end sub is_on_target($\@)
1458 # copy a list of files to target
1460 sub copy_to_target(@) {
1462 my ( @md5sum, @expected_files, $sum, $name, $msgs, $stat );
1465 write_status_file() if $conf::statusdelay;
1468 if ( $conf::upload_method eq "ssh" ) {
1469 ( $msgs, $stat ) = scp_cmd(@files);
1471 } elsif ( $conf::upload_method eq "ftp" ) {
1473 if ( !$main::FTP_chan->cwd($main::current_targetdir) ) {
1475 "Can't cd to $main::current_targetdir on $conf::target\n" );
1478 foreach $file (@files) {
1479 ( $rv, $msgs ) = ftp_cmd( "put", $file );
1483 for my $file (@files) {
1484 eval { File::Copy::copy($file, $main::current_targetdir) };
1493 # check md5sums or sizes on target against our own
1494 my $have_md5sums = 1;
1495 if ($conf::check_md5sum) {
1496 if ( $conf::upload_method eq "ssh" ) {
1497 ( $msgs, $stat ) = ssh_cmd("md5sum @files");
1499 @md5sum = split( "\n", $msgs );
1500 } elsif ( $conf::upload_method eq "ftp" ) {
1501 my ( $rv, $err, $file );
1502 foreach $file (@files) {
1503 ( $rv, $err ) = ftp_cmd( "quot", "site", "md5sum", $file );
1505 next if ftp_code() == 550; # file not found
1506 if ( ftp_code() == 500 ) { # unimplemented
1508 goto get_sizes_instead;
1513 chomp( my $t = ftp_response() );
1514 push( @md5sum, $t );
1515 } ## end foreach $file (@files)
1516 if ( !$have_md5sums ) {
1518 foreach $file (@files) {
1519 ( $rv, $err ) = ftp_cmd( "size", $file );
1521 next if ftp_code() == 550; # file not found
1525 push( @md5sum, "$rv $file" );
1526 } ## end foreach $file (@files)
1527 } ## end if ( !$have_md5sums )
1529 for my $file (@files) {
1530 my $md5 = eval { md5sum("$main::current_targetdir/$file") };
1535 push @md5sum, "$md5 $file" if $md5;
1539 @expected_files = @files;
1542 ( $sum, $name ) = split;
1543 next if !grep { $_ eq $name } @files; # a file we didn't upload??
1544 next if $sum eq "md5sum:"; # looks like an error message
1545 if ( ( $have_md5sums && $sum ne md5sum($name) )
1546 || ( !$have_md5sums && $sum != ( -s $name ) ) )
1550 "Upload of $name to $conf::target failed ",
1551 "(" . ( $have_md5sums ? "md5sum" : "size" ) . " mismatch)\n"
1554 } ## end if ( ( $have_md5sums &&...
1556 # seen that file, remove it from expect list
1557 @expected_files = map { $_ eq $name ? () : $_ } @expected_files;
1558 } ## end foreach (@md5sum)
1559 if (@expected_files) {
1560 msg( "log,mail", "Failed to upload the files\n" );
1561 msg( "log,mail", " ", join( ", ", @expected_files ), "\n" );
1562 msg( "log,mail", "(Not present on target after upload)\n" );
1564 } ## end if (@expected_files)
1565 } ## end if ($conf::check_md5sum)
1567 if ($conf::chmod_on_target) {
1569 # change file's mode explicitly to 644 on target
1570 if ( $conf::upload_method eq "ssh" ) {
1571 ( $msgs, $stat ) = ssh_cmd("chmod 644 @files");
1573 } elsif ( $conf::upload_method eq "ftp" ) {
1575 foreach $file (@files) {
1576 ( $rv, $msgs ) = ftp_cmd( "quot", "site", "chmod", "644", $file );
1577 msg( "log", "Can't chmod $file on target:\n$msgs" )
1580 } ## end foreach $file (@files)
1582 for my $file (@files) {
1583 unless (chmod 0644, "$main::current_targetdir/$file") {
1584 $msgs = "Could not chmod $file: $!";
1589 } ## end if ($conf::chmod_on_target)
1592 write_status_file() if $conf::statusdelay;
1597 "Upload to $conf::target failed",
1598 $? ? ", last exit status " . sprintf( "%s", $? >> 8 ) : "", "\n" );
1599 msg( "log,mail", "Error messages:\n", $msgs )
1602 # If "permission denied" was among the errors, test if the incoming is
1604 if ( $msgs && $msgs =~ /(permission denied|read-?only file)/i ) {
1605 if ( !check_incoming_writable() ) {
1606 msg( "log,mail", "(The incoming directory seems to be ",
1609 } ## end if ( $msgs =~ /(permission denied|read-?only file)/i)
1611 # remove bad files or an incomplete upload on target
1612 if ( $conf::upload_method eq "ssh" ) {
1613 ssh_cmd("rm -f @files");
1614 } elsif ( $conf::upload_method eq "ftp" ) {
1616 foreach $file (@files) {
1618 ( $rv, $err ) = ftp_cmd( "delete", $file );
1619 msg( "log", "Can't delete $file on target:\n$err" )
1621 } ## end foreach $file (@files)
1623 my @tfiles = map { "$main::current_targetdir/$_" } @files;
1624 debug("executing unlink(@tfiles)");
1628 write_status_file() if $conf::statusdelay;
1630 } ## end sub copy_to_target(@)
1633 # check if a file is correctly signed with PGP
1644 if ($file =~ /$re_file_safe/) {
1647 msg( "log", "Tainted filename, skipping: $file\n" );
1648 return "LOCAL ERROR";
1651 # check the file has only one clear-signed section
1653 unless (open $fh, "<", $file) {
1654 msg("log,mail", "Could not open $file\n");
1657 unless (<$fh> eq "-----BEGIN PGP SIGNED MESSAGE-----\n") {
1658 msg("log,mail", "$file: does not start with a clearsigned message\n");
1664 msg("log,mail", "$file: dash-escaped messages are not accepted\n");
1667 elsif ($_ eq "-----BEGIN PGP SIGNATURE-----\n"
1668 || $_ eq "-----END PGP SIGNATURE-----\n") {
1672 msg("log,mail", "$file: unexpected OpenPGP armor\n");
1675 elsif ($pgplines > 3 && /\S/) {
1676 msg("log,mail", "$file: found text after end of signature\n");
1680 if ($pgplines != 3) {
1681 msg("log,mail", "$file: doesn't seem to be a valid clearsigned OpenPGP message\n");
1686 if ( -x $conf::gpg ) {
1687 my @command = ("$conf::gpg", "--no-options", "--batch", "--no-tty",
1688 "--trust-model", "always", "--no-default-keyring",
1689 (map +("--keyring" => $_), @conf::keyrings),
1691 debug( "executing " . join(" ", @command) );
1693 my $child = open(PIPE, "-|");
1694 if (!defined($child)) {
1695 msg("log", "Can't open pipe to $conf::gpg: $!\n");
1696 return "LOCAL ERROR";
1699 unless (open(STDERR, ">&", \*STDOUT)) {
1700 print "Could not redirect STDERR.";
1703 unless (open(STDIN, "<", $file)) {
1704 print "Could not open $file: $!";
1707 { exec(@command) }; # BLOCK avoids warning about likely unreachable code
1708 print "Could not exec gpg: $!";
1712 $output .= $_ while (<PIPE>);
1715 } ## end if ( -x $conf::gpg )
1718 msg( "log,mail", "GnuPG signature check failed on $file\n" );
1719 msg( "mail", $output );
1720 msg( "log,mail", "(Exit status ", $stat >> 8, ")\n" );
1724 $output =~ /^(gpg: )?good signature from (user )?"(.*)"\.?$/im;
1725 ( $signator = $3 ) ||= "unknown signator";
1727 debug("GnuPG signature ok (by $signator)");
1730 } ## end sub pgp_check($)
1732 # ---------------------------------------------------------------------------
1734 # ---------------------------------------------------------------------------
1737 # fork a subprocess that watches the 'status' FIFO
1739 # that process blocks until someone opens the FIFO, then sends a
1740 # signal (SIGUSR1) to the main process, expects
1742 sub fork_statusd() {
1748 $statusd_pid = open( STATUSD, "|-" );
1749 die "cannot fork: $!\n" if !defined($statusd_pid);
1751 # parent just returns
1753 msg( "log", "forked status daemon (pid $statusd_pid)\n" );
1754 return $statusd_pid;
1757 # child: the status FIFO daemon
1759 # ignore SIGPIPE here, in case some closes the FIFO without completely
1761 $SIG{"PIPE"} = "IGNORE";
1763 # also ignore SIGCLD, we don't want to inherit the restart-statusd handler
1765 $SIG{"CHLD"} = "DEFAULT";
1767 rm($conf::statusfile);
1768 $errs = `$conf::mkfifo $conf::statusfile`;
1769 die "$main::progname: cannot create named pipe $conf::statusfile: $errs"
1771 chmod( 0644, $conf::statusfile )
1772 or die "Cannot set modes of $conf::statusfile: $!\n";
1774 # close log file, so that log rotating works
1780 my ( $status, $mup, $incw, $ds, $next_run, $last_ping, $currch, $l );
1782 # open the FIFO for writing; this blocks until someone (probably ftpd)
1783 # opens it for reading
1784 open( STATFIFO, ">", $conf::statusfile )
1785 or die "Cannot open $conf::statusfile\n";
1788 # tell main daemon to send us status infos
1789 kill( $main::signo{"USR1"}, $main_pid );
1791 # get the infos from stdin; must loop until enough bytes received!
1792 my $expect_len = 3 + 2 * STATNUM_LEN + STATSTR_LEN;
1793 for ( $status = "" ; ( $l = length($status) ) < $expect_len ; ) {
1794 sysread( STDIN, $status, $expect_len - $l, $l );
1797 # disassemble the status byte stream
1803 [ next_run => STATNUM_LEN ],
1804 [ last_ping => STATNUM_LEN ],
1805 [ currch => STATSTR_LEN ]
1808 eval "\$$_->[0] = substr( \$status, $pos, $_->[1] );";
1810 } ## end foreach ( [ mup => 1 ], [ incw...
1811 $currch =~ s/\n+//g;
1813 print_status( $mup, $incw, $ds, $next_run, $last_ping, $currch );
1816 # This sleep is necessary so that we can't reopen the FIFO
1817 # immediately, in case the reader hasn't closed it yet if we get to
1818 # the open again. Is there a better solution for this??
1821 } ## end sub fork_statusd()
1824 # update the status file, in case we use a plain file and not a FIFO
1826 sub write_status_file() {
1828 return if !$conf::statusfile;
1830 open( STATFILE, ">", $conf::statusfile )
1831 or ( msg( "log", "Could not open $conf::statusfile: $!\n" ), return );
1832 my $oldsel = select(STATFILE);
1835 $main::target_up, $main::incoming_writable,
1836 $main::dstat, $main::next_run,
1837 $main::last_ping_time, $main::current_changes
1842 } ## end sub write_status_file()
1844 sub print_status($$$$$$) {
1848 my $next_run = shift;
1849 my $last_ping = shift;
1854 ( $version = 'Release: 0.9 $Revision: 1.51 $' ) =~ s/\$ ?//g;
1855 print "debianqueued $version\n";
1857 $approx = $conf::statusdelay ? "approx. " : "";
1859 if ( $mup eq "0" ) {
1860 print "$conf::target is down, queue pausing\n";
1862 } elsif ( $conf::upload_method ne "copy" ) {
1863 print "$conf::target seems to be up, last ping $approx",
1864 print_time( time - $last_ping ), " ago\n";
1867 if ( $incw eq "0" ) {
1868 print "The incoming directory is not writable, queue pausing\n";
1873 print "Next queue check in $approx", print_time( $next_run - time ), "\n";
1875 } elsif ( $ds eq "c" ) {
1876 print "Checking queue directory\n";
1877 } elsif ( $ds eq "u" ) {
1878 print "Uploading to $conf::target\n";
1880 print "Bad status data from daemon: \"$mup$incw$ds\"\n";
1884 print "Current job is $currch\n" if $currch;
1885 } ## end sub print_status($$$$$$)
1888 # format a number for sending to statusd (fixed length STATNUM_LEN)
1890 sub format_status_num(\$$) {
1894 $$varref = sprintf "%" . STATNUM_LEN . "d", $num;
1895 } ## end sub format_status_num(\$$)
1898 # format a string for sending to statusd (fixed length STATSTR_LEN)
1900 sub format_status_str(\$$) {
1904 $$varref = substr( $str, 0, STATSTR_LEN );
1905 $$varref .= "\n" x ( STATSTR_LEN - length($$varref) );
1906 } ## end sub format_status_str(\$$)
1909 # send a status string to the status daemon
1911 # Avoid all operations that could call malloc() here! Most libc
1912 # implementations aren't reentrant, so we may not call it from a
1913 # signal handler. So use only already-defined variables.
1916 local $! = 0; # preserve errno
1918 # re-setup handler, in case we have broken SysV signals
1919 $SIG{"USR1"} = \&send_status;
1921 syswrite( STATUSD, $main::target_up, 1 );
1922 syswrite( STATUSD, $main::incoming_writable, 1 );
1923 syswrite( STATUSD, $main::dstat, 1 );
1924 syswrite( STATUSD, $main::next_run, STATNUM_LEN );
1925 syswrite( STATUSD, $main::last_ping_time, STATNUM_LEN );
1926 syswrite( STATUSD, $main::current_changes, STATSTR_LEN );
1927 } ## end sub send_status()
1929 # ---------------------------------------------------------------------------
1931 # ---------------------------------------------------------------------------
1934 # open FTP connection to target host if not already open
1937 return 1 unless $conf::upload_method eq "ftp";
1939 if ($main::FTP_chan) {
1941 # is already open, but might have timed out; test with a cwd
1942 return $main::FTP_chan
1943 if $main::FTP_chan->cwd($main::current_targetdir);
1945 # cwd didn't work, channel is closed, try to reopen it
1946 $main::FTP_chan = undef;
1947 } ## end if ($main::FTP_chan)
1954 Debug => $conf::ftpdebug,
1955 Timeout => $conf::ftptimeout,
1961 msg( "log,mail", "Cannot open FTP server $conf::target\n" );
1963 } ## end if ( !( $main::FTP_chan...
1964 if ( !$main::FTP_chan->login() ) {
1965 msg( "log,mail", "Anonymous login on FTP server $conf::target failed\n" );
1968 if ( !$main::FTP_chan->binary() ) {
1969 msg( "log,mail", "Can't set binary FTP mode on $conf::target\n" );
1972 if ( !$main::FTP_chan->cwd($main::current_targetdir) ) {
1974 "Can't cd to $main::current_targetdir on $conf::target\n" );
1977 debug("opened FTP channel to $conf::target");
1981 $main::FTP_chan = undef;
1983 } ## end sub ftp_open()
1988 my $direct_resp_cmd = ( $cmd eq "quot" );
1990 debug( "executing FTP::$cmd(" . join( ", ", @_ ) . ")" );
1991 $SIG{"ALRM"} = sub { die "timeout in FTP::$cmd\n" };
1992 alarm($conf::remote_timeout);
1993 eval { $rv = $main::FTP_chan->$cmd(@_); };
1996 $rv = ( ftp_code() =~ /^2/ ) ? 1 : 0 if $direct_resp_cmd;
2001 $err = ftp_response();
2003 return ( $rv, $err );
2004 } ## end sub ftp_cmd($@)
2007 if ($main::FTP_chan) {
2008 $main::FTP_chan->quit();
2009 $main::FTP_chan = undef;
2012 } ## end sub ftp_close()
2014 sub ftp_response() {
2015 return join( '', @{ ${*$main::FTP_chan}{'net_cmd_resp'} } );
2019 return ${*$main::FTP_chan}{'net_cmd_code'};
2023 my $code = ftp_code();
2024 return ( $code =~ /^[45]/ ) ? 1 : 0;
2027 # ---------------------------------------------------------------------------
2029 # ---------------------------------------------------------------------------
2035 my $ecmd = "$conf::ssh $conf::ssh_options $conf::target "
2036 . "-l $conf::targetlogin \'cd $main::current_targetdir; $cmd\'";
2037 debug("executing $ecmd");
2038 $SIG{"ALRM"} = sub { die "timeout in ssh command\n" };
2039 alarm($conf::remote_timeout);
2040 eval { $msg = `$ecmd 2>&1`; };
2048 return ( $msg, $stat );
2049 } ## end sub ssh_cmd($)
2054 my $ecmd = "$conf::scp $conf::ssh_options @_ "
2055 . "$conf::targetlogin\@$conf::target:$main::current_targetdir";
2056 debug("executing $ecmd");
2057 $SIG{"ALRM"} = sub { die "timeout in scp\n" };
2058 alarm($conf::remote_timeout);
2059 eval { $msg = `$ecmd 2>&1`; };
2067 return ( $msg, $stat );
2068 } ## end sub scp_cmd(@)
2071 # check if target is alive (code stolen from Net::Ping.pm)
2073 sub check_alive(;$) {
2074 my $timeout = shift;
2075 my ( $saddr, $ret, $target_ip );
2078 if ( $conf::upload_method eq "copy" ) {
2079 format_status_num( $main::last_ping_time, time );
2080 $main::target_up = 1;
2086 if ( !( $target_ip = ( gethostbyname($conf::target) )[4] ) ) {
2087 msg( "log", "Cannot get IP address of $conf::target\n" );
2091 $saddr = pack( 'S n a4 x8', AF_INET, $main::echo_port, $target_ip );
2092 $SIG{'ALRM'} = sub { die };
2095 $ret = $main::tcp_proto; # avoid warnings about unused variable
2098 return unless socket( PINGSOCK, PF_INET, SOCK_STREAM, $main::tcp_proto );
2099 return unless connect( PINGSOCK, $saddr );
2104 msg( "log", "pinging $conf::target: " . ( $ret ? "ok" : "down" ) . "\n" );
2106 $main::target_up = $ret ? "1" : "0";
2107 format_status_num( $main::last_ping_time, time );
2108 write_status_file() if $conf::statusdelay;
2109 } ## end sub check_alive(;$)
2112 # check if incoming dir on target is writable
2114 sub check_incoming_writable() {
2115 my $testfile = ".debianqueued-testfile";
2118 if ( $conf::upload_method eq "ssh" ) {
2120 ssh_cmd( "rm -f $testfile; touch $testfile; " . "rm -f $testfile" );
2121 } elsif ( $conf::upload_method eq "ftp" ) {
2122 my $file = "junk-for-writable-test-" . format_time();
2123 $file =~ s/[ :.]/-/g;
2125 open( F, ">", $file );
2128 ( $rv, $msg ) = ftp_cmd( "put", $file );
2130 $msg = "" if !defined $msg;
2132 ftp_cmd( "delete", $file );
2133 } elsif ( $conf::upload_method eq "copy" ) {
2134 unless(POSIX::access($main::current_targetdir, &POSIX::W_OK)) {
2135 $msg = "No write access: $!";
2140 debug("exit status: $stat, output was: $msg");
2144 # change incoming_writable only if ssh didn't return an error
2145 $main::incoming_writable =
2146 ( $msg =~ /(permission denied|read-?only file|cannot create)/i )
2150 debug("local error, keeping old status");
2152 debug("incoming_writable = $main::incoming_writable");
2153 write_status_file() if $conf::statusdelay;
2154 return $main::incoming_writable;
2155 } ## end sub check_incoming_writable()
2158 # remove a list of files, log failing ones
2164 ( unlink $_ and ++$done )
2166 or msg( "log", "Could not delete $_: $!\n" );
2172 # get md5 checksum of a file
2176 my $md5 = Digest::MD5->new;
2178 open my $fh, "<", $file or return "";
2182 return $md5->hexdigest;
2183 } ## end sub md5sum($)
2186 # output a messages to several destinations
2188 # first arg is a comma-separated list of destinations; valid are "log"
2189 # and "mail"; rest is stuff to be printed, just as with print
2192 my @dest = split( ',', shift );
2194 if ( grep /log/, @dest ) {
2195 my $now = format_time();
2196 print LOG "$now ", @_;
2199 if ( grep /mail/, @dest ) {
2200 $main::mail_text .= join( '', @_ );
2202 } ## end sub msg($@)
2205 # print a debug messages, if $debug is true
2208 return if !$conf::debug;
2209 my $now = format_time();
2210 print LOG "$now DEBUG ", @_, "\n";
2214 # intialize the "mail" destination of msg() (this clears text,
2215 # address, subject, ...)
2220 $main::mail_addr = "";
2221 $main::mail_text = "";
2222 %main::packages = ();
2223 $main::mail_subject = $file ? "Processing of $file" : "";
2224 } ## end sub init_mail(;$)
2227 # finalize mail to be sent from msg(): check if something present, and
2232 debug("No mail for $main::mail_addr")
2233 if $main::mail_addr && !$main::mail_text;
2234 return unless $main::mail_addr && $main::mail_text;
2236 if ( !send_mail( $main::mail_addr, $main::mail_subject, $main::mail_text ) )
2239 # store this mail in memory so it isn't lost if executing sendmail
2242 @main::stored_mails,
2244 addr => $main::mail_addr,
2245 subject => $main::mail_subject,
2246 text => $main::mail_text
2249 } ## end if ( !send_mail( $main::mail_addr...
2252 # try to send out stored mails
2254 while ( $mailref = shift(@main::stored_mails) ) {
2256 !send_mail( $mailref->{'addr'}, $mailref->{'subject'},
2257 $mailref->{'text'} )
2260 unshift( @main::stored_mails, $mailref );
2262 } ## end if ( !send_mail( $mailref...
2263 } ## end while ( $mailref = shift(...
2264 } ## end sub finish_mail()
2269 sub send_mail($$$) {
2271 my $subject = shift;
2275 keys %main::packages ? join( ' ', keys %main::packages ) : "";
2279 unless ( defined($Email::Send::Sendmail::SENDMAIL) ) {
2280 $Email::Send::Sendmail::SENDMAIL = $conf::mail;
2283 if ($conf::overridemail) {
2284 $addr = $conf::overridemail;
2287 my $date = sprintf "%s",
2288 strftime( "%a, %d %b %Y %T %z", ( localtime(time) ) );
2289 my $message = <<__MESSAGE__;
2291 From: Debian FTP Masters <ftpmaster\@ftp-master.debian.org>
2297 Auto-Submitted: auto-generated
2300 if ( length $package ) {
2301 $message .= "X-Debian-Package: $package\n";
2304 $message .= "\n$text";
2305 $message .= "\nGreetings,\n\n\tYour Debian queue daemon (running on host $main::hostname)\n";
2307 my $mail = Email::Send->new;
2308 for (qw[Sendmail SMTP]) {
2309 $mail->mailer($_) and last if $mail->mailer_available($_);
2312 my $ret = $mail->send($message);
2313 if ( $ret && $ret !~ /Message sent|success/ ) {
2318 } ## end sub send_mail($$$)
2321 # try to find a mail address for a name in the keyrings
2323 sub try_to_get_mail_addr($$) {
2325 my $listref = shift;
2329 "$conf::gpg --no-options --batch --no-default-keyring "
2330 . "--always-trust --keyring "
2331 . join( " --keyring ", @conf::keyrings )
2335 if ( /^pub / && / $name / ) {
2337 push( @$listref, $1 );
2339 } ## end while (<F>)
2342 return ( @$listref >= 1 ) ? $listref->[0] : "";
2343 } ## end sub try_to_get_mail_addr($$)
2346 # return current time as string
2351 # omit weekday and year for brevity
2352 ( $t = localtime ) =~ /^\w+\s(.*)\s\d+$/;
2354 } ## end sub format_time()
2358 my $hours = int( $secs / ( 60 * 60 ) );
2360 $secs -= $hours * 60 * 60;
2361 return sprintf "%d:%02d:%02d", $hours, int( $secs / 60 ), $secs % 60;
2362 } ## end sub print_time($)
2365 # block some signals during queue processing
2367 # This is just to avoid data inconsistency or uploads being aborted in the
2368 # middle. Only "soft" signals are blocked, i.e. SIGINT and SIGTERM, try harder
2369 # ones if you really want to kill the daemon at once.
2371 sub block_signals() {
2372 POSIX::sigprocmask( SIG_BLOCK, $main::block_sigset );
2375 sub unblock_signals() {
2376 POSIX::sigprocmask( SIG_UNBLOCK, $main::block_sigset );
2380 # process SIGHUP: close log file and reopen it (for logfile cycling)
2387 open( LOG, ">>", $conf::logfile )
2388 or die "Cannot open my logfile $conf::logfile: $!\n";
2389 chmod( 0644, $conf::logfile )
2390 or msg( "log", "Cannot set modes of $conf::logfile: $!\n" );
2391 select( ( select(LOG), $| = 1 )[0] );
2393 open( STDOUT, ">&", \*LOG )
2395 "$main::progname: Can't redirect stdout to " . "$conf::logfile: $!\n" );
2396 open( STDERR, ">&", \*LOG )
2398 "$main::progname: Can't redirect stderr to " . "$conf::logfile: $!\n" );
2399 msg( "log", "Restart after SIGHUP\n" );
2400 } ## end sub close_log($)
2403 # process SIGCHLD: check if it was our statusd process
2408 # reap statusd, so that it's no zombie when we try to kill(0) it
2409 waitpid( $main::statusd_pid, WNOHANG );
2411 # Uncomment the following line if your Perl uses unreliable System V signal
2412 # (i.e. if handlers reset to default if the signal is delivered).
2413 # (Unfortunately, the re-setup can't be done in any case, since on some
2414 # systems this will cause the SIGCHLD to be delivered again if there are
2415 # still unreaped children :-(( )
2417 # $SIG{"CHLD"} = \&kid_died; # resetup handler for SysV
2418 } ## end sub kid_died($)
2420 sub restart_statusd() {
2422 # restart statusd if it died
2423 if ( !kill( 0, $main::statusd_pid ) ) {
2424 close(STATUSD); # close out pipe end
2425 $main::statusd_pid = fork_statusd();
2427 } ## end sub restart_statusd()
2430 # process a fatal signal: cleanup and exit
2432 sub fatal_signal($) {
2433 my $signame = shift;
2436 # avoid recursions of fatal_signal in case of BSD signals
2437 foreach $sig (qw( ILL ABRT BUS FPE SEGV PIPE )) {
2438 $SIG{$sig} = "DEFAULT";
2441 if ( $$ == $main::maind_pid ) {
2443 # only the main daemon should do this
2444 kill( $main::signo{"TERM"}, $main::statusd_pid )
2445 if defined $main::statusd_pid;
2446 unlink( $conf::statusfile, $conf::pidfile );
2447 } ## end if ( $$ == $main::maind_pid)
2448 msg( "log", "Caught SIG$signame -- exiting (pid $$)\n" );
2450 } ## end sub fatal_signal($)