source: trunk/athena/bin/mitmaildel/mitmaildel.pl @ 22828

Revision 22828, 7.8 KB checked in by tabbott, 16 years ago (diff)
In mitmaildel: * Merged quilt patches into mainline Athena tree
Line 
1#!/usr/bin/perl -w
2
3# $Id: mitmaildel.pl,v 1.3 2004-07-29 19:11:52 rbasch Exp $
4
5# Delete (or undelete) messages in an IMAP folder.
6
7use strict;
8use warnings FATAL => 'all';
9use Cyrus::IMAP;
10use Getopt::Long;
11
12sub usage(;$);
13sub send_command($);
14sub fetch_callback(@);
15sub number_callback(@);
16sub close_and_errorout($);
17sub close_connection();
18sub errorout($);
19
20my $prog = $0;
21my $undelete = ($prog =~ m/undel$/o);
22
23sub usage(;$) {
24    print STDERR "$prog: $_[0]\n" if ($_[0] && $_[0] ne "help");
25    print STDERR <<EOF;
26Usage: $prog [<options>] <message-id> ...
27  Options:
28    --by-uid               specify message UIDs instead of sequence numbers
29    --debug                turn on debugging
30    --expunge              expunge all deleted messages from mailbox
31    --help                 print this usage information
32    --host=<name>          query host <name> instead of default POBOX server
33    --mailbox=<name>       examine mailbox <name> instead of INBOX
34    --silent               suppress acknowledgement output
35EOF
36    exit 1;
37}
38
39# Parse the command line arguments.
40use vars qw($opt_by_uid $opt_debug $opt_expunge $opt_host
41            $opt_mailbox $opt_silent);
42
43GetOptions("by-uid",
44           "debug",
45           "expunge",
46           "help" => \&usage,
47           "host=s",
48           "mailbox=s",
49           "silent") || usage;
50
51usage "Please specify a message number" if @ARGV == 0;
52
53# Check the validity of message ID arguments.
54# The ID can be a number or '*', and we accept a range specification,
55# of the form 'n:m'.
56foreach (@ARGV) {
57    errorout "Invalid message specification $_"
58        unless (m/^(?:\d+|\*)(?::(?:\d+|\*))?$/o);
59}
60
61$opt_mailbox = 'INBOX' unless $opt_mailbox;
62
63my $username = $ENV{'USER'} || getlogin || (getpwuid($<))[0] ||
64    errorout "Cannot determine user name";
65
66unless ($opt_host) {
67    $opt_host = (split(" ", `hesinfo $username pobox`))[1] ||
68        errorout "Cannot find Post Office server for $username";
69}
70
71# Connect to the IMAP server, and authenticate.
72my $client = Cyrus::IMAP->new($opt_host) ||
73    errorout "Cannot connect to IMAP server on $opt_host";
74$client->authenticate(-authz => $username) ||
75    close_and_errorout "Cannot authenticate to $opt_host";
76
77# Select the mailbox (for read-write access).  Store the value of the
78# EXISTS (i.e. highest existing message sequence number) data item,
79# and, if returned, the UIDNEXT (next UID to be assigned) value.
80my $cb_numbered = Cyrus::IMAP::CALLBACK_NUMBERED;
81my $maxseq = 0;
82my $uidnext = 0;
83$client->addcallback({-trigger => 'EXISTS', -flags => $cb_numbered,
84                      -callback => \&number_callback,
85                      -rock => \$maxseq});
86$client->addcallback({-trigger => 'OK',
87                      -callback => sub {
88                          my %cb = @_;
89                          print "In OK callback: text $cb{-text}\n"
90                              if $opt_debug;
91                          return unless ($cb{-text} =~ m/UIDNEXT\s+(\d+)/io);
92                          $uidnext = $1;
93                      }});
94send_command "SELECT \"$opt_mailbox\"";
95
96# If we're operating on UIDs, and did not get the UIDNEXT value above,
97# use the STATUS command to get it explicitly.
98if ($opt_by_uid && !$uidnext) {
99    $client->addcallback({-trigger => 'STATUS',
100                          -callback => sub {
101                              my %cb = @_;
102                              print "In STATUS callback: text $cb{-text}\n"
103                                  if $opt_debug;
104                              return
105                                  unless ($cb{-text} =~ m/UIDNEXT\s+(\d+)/io);
106                              $uidnext = $1;
107                          }});
108    send_command "STATUS \"$opt_mailbox\" (UIDNEXT)";
109}
110
111# Note that the STORE command returns success even when the given
112# message ID does not exist.  So the most feasible way to determine
113# whether the (un)delete was successful for a message is to see if the
114# FETCH callback (invoked during the server response to the STORE
115# command) was invoked for the message, and whether the \Deleted flag
116# was returned.  We thus initialize a hash whose keys are the
117# individual message IDs given; the FETCH callback will remove the key
118# from the hash when it detects that the message flags have been set
119# as desired.  Any keys remaining in the hash upon completion will
120# indicate IDs whose flags could not be modified (presumably because
121# the message does not exist).
122my %unchanged = ();
123my $expect = ($undelete ? "undeleted" : "deleted");
124my $exitcode = 0;
125my $store_cmd = ($opt_by_uid ? 'UID STORE' : 'STORE');
126my $store_item = ($undelete ? '-FLAGS' : '+FLAGS');
127$client->addcallback({-trigger => 'FETCH', -flags => $cb_numbered,
128                      -callback => \&fetch_callback,
129                      -rock => \%unchanged});
130foreach (@ARGV) {
131    if ($opt_by_uid) {
132        # When operating on UIDs, the message numbers in a range are
133        # not necessarily sequential, so we don't detect unchanged
134        # messages in the range.  We can handle '*', though, as that
135        # is simply one less than the next UID to be assigned.
136        $_ = ($uidnext - 1) if ($_ eq '*' && $uidnext);
137        %unchanged = ($_ => 1) if (/^\d+$/);
138    } else {
139        s/\*/$maxseq/o;
140        m/^(\d+)(?::(\d+))?$/o;
141        if ($2) {
142            %unchanged = map { $_ => 1 } ($1 < $2 ? $1 .. $2 : $2 .. $1);
143        } else {
144            %unchanged = ($1 => 1);
145        }
146    }
147    send_command "$store_cmd $_ $store_item (\\Deleted)";
148    foreach my $msg (sort { $a <=> $b } keys %unchanged) {
149        print STDERR "$prog: Could not " .
150            ($undelete ? "un" : "") . "delete $msg\n";
151        $exitcode = 1;
152    }
153}
154
155# Expunge the mailbox if so desired, unless there was an error marking
156# any message.
157send_command "CLOSE" if ($opt_expunge && ($exitcode == 0));
158
159# We are done talking to the IMAP server, close down the connection.
160close_connection();
161
162exit $exitcode;
163
164# Subroutine to send a command to the IMAP server, and wait for the
165# response; any defined callbacks for the response are invoked.
166# If the server response indicates failure, we error out.
167sub send_command($) {
168    print "Sending: $_[0]\n" if $opt_debug;
169    my ($status, $text) = $client->send('', '', $_[0]);
170    print "Response: status $status, text $text\n" if $opt_debug;
171    errorout "Premature end-of-file on IMAP connection to $opt_host"
172        if $status eq 'EOF';
173    close_and_errorout "IMAP error from $opt_host: $text"
174        if $status ne 'OK';
175}
176
177# Callback subroutine to parse the FETCH response from a STORE command.
178# This callback will be invoked for each message.  The "-text" hash
179# element contains the text returned by the server.  The "-rock"
180# element is a reference to the hash containing the message IDs of
181# interest; we delete the appropriate key (sequence number or UID)
182# from this hash.
183sub fetch_callback(@) {
184    my %cb = @_;
185    my ($number, $flags);
186    print "In FETCH callback: msgno $cb{-msgno} text $cb{-text}\n"
187        if $opt_debug;
188    $number = $cb{-msgno};
189    foreach (split /\r\n/, $cb{-text}) {
190        $number = $1 if /UID\s+(\d+)/io;
191        $flags = $1 if /FLAGS\s+\(([^\)]*)\)/io;
192    }
193    delete ${$cb{-rock}}{$number};
194    my $state = ($flags =~ /\\Deleted\b/io ? "deleted" : "undeleted");
195    # Warn if the returned state is not what was expected.
196    if ($state ne $expect) {
197        print STDERR "$prog: Warning: Message $number $state\n";
198    } else {
199        # Display an acknowledgement of success if so desired.
200        print(($opt_by_uid ? "UID" : "Message") . " $number $state\n")
201            unless $opt_silent;
202    }
203}
204
205# Callback subroutine to parse a numeric value.  The "-rock" hash
206# element is a reference to the scalar in which to store the number.
207sub number_callback(@) {
208    my %cb = @_;
209    print "In number callback: keyword $cb{-keyword}, number $cb{-msgno}\n"
210        if $opt_debug;
211    ${$cb{-rock}} = $cb{-msgno};
212}
213
214# Close the connection to the IMAP server, and error out.
215sub close_and_errorout($) {
216    close_connection();
217    errorout $_[0];
218}
219
220# Logout from the IMAP server, and close the connection.
221sub close_connection() {
222    $client->send('', '', "LOGOUT");
223    # Set the client reference to undef, so that perl invokes the
224    # destructor, which closes the connection.  Note that if we invoke
225    # the destructor explicitly here, then perl will still invoke it
226    # again when the program exits, thus touching memory which has
227    # already been freed.
228    $client = undef;
229}
230
231sub errorout($) {
232    print STDERR "$prog: $_[0]\n";
233    exit 1;
234}
Note: See TracBrowser for help on using the repository browser.