my $NAME = 'imapsync';
use Getopt::Long qw/:config posix_default no_ignore_case gnu_compat
bundling auto_version/;
-
-use List::Util 'first';
use DBI ();
+use List::Util 'first';
+use POSIX 'strftime';
use lib 'lib';
use Net::IMAP::Sync qw/read_config compact_set $IMAP_text $IMAP_cond/;
my $CONF = read_config( delete $CONFIG{config} // $NAME
, [qw/_ local remote/]
- , database => qr/\A(\P{Control}+)\z/ );
-my ($DBFILE, $LOCKFILE);
+ , database => qr/\A(\P{Control}+)\z/
+ , logfile => qr/\A(\P{Control}+)\z/ );
+my ($DBFILE, $LOCKFILE, $LOGGER_FD);
{
$DBFILE = $CONF->{_}->{database} if defined $CONF->{_};
$dir = $1;
$DBFILE = $dir .'/'. $DBFILE;
unless (-d $dir) {
- mkdir $dir, 0700 or die "Cannot mkdir $dir: $!\n";
+ mkdir $dir, 0700 or die "Can't mkdir $dir: $!\n";
}
}
$LOCKFILE = $DBFILE =~ s/([^\/]+)\z/.$1.lck/r;
+
+ if (defined $CONF->{_} and defined $CONF->{_}->{logfile}) {
+ open $LOGGER_FD, '>>', $CONF->{_}->{logfile}
+ or die "Can't open $CONF->{_}->{logfile}: $!\n";
+ $LOGGER_FD->autoflush(1);
+ }
}
my $DBH;
# Clean after us
sub cleanup() {
- print STDERR "Cleaning up...\n" if $CONFIG{debug};
+ logger("Cleaning up...") if $CONFIG{debug};
unlink $LOCKFILE if defined $LOCKFILE and -f $LOCKFILE;
+ close $LOGGER_FD if defined $LOGGER_FD;
$DBH->disconnect() if defined $DBH;
}
-$SIG{$_} = sub { cleanup(); print STDERR "$!\n"; exit 1; } foreach qw/INT TERM/;
-$SIG{$_} = sub { cleanup(); print STDERR "$!\n"; exit 0; } foreach qw/HUP/;
+$SIG{$_} = sub { cleanup(); msg($!); exit 1; } foreach qw/INT TERM/;
+$SIG{$_} = sub { cleanup(); msg($!); exit 0; } foreach qw/HUP/;
#############################################################################
# Lock the database
{
if (-f $LOCKFILE) {
- open my $lock, '<', $LOCKFILE or die "Cannot open $LOCKFILE: $!\n";
+ open my $lock, '<', $LOCKFILE or die "Can't open $LOCKFILE: $!\n";
my $pid = <$lock>;
close $lock;
chomp $pid;
die $msg, "\n";
}
- open my $lock, '>', $LOCKFILE or die "Cannot open $LOCKFILE: $!\n";
+ open my $lock, '>', $LOCKFILE or die "Can't open $LOCKFILE: $!\n";
print $lock $$, "\n";
close $lock;
}
sub msg($@) {
my $name = shift;
return unless @_;
+ logger($name, @_) if defined $LOGGER_FD and $LOGGER_FD ne \*STDERR;
my $prefix = defined $name ? "$name: " : '';
print STDERR $prefix, @_, "\n";
}
+sub logger($@) {
+ my $name = shift;
+ return unless @_ and defined $LOGGER_FD;
+ my $prefix = strftime "%b %e %H:%M:%S ", localtime;
+ $prefix .= "$name: " if defined $name;
+ $LOGGER_FD->say($prefix, @_);
+}
+logger(undef, ">>> $NAME $VERSION");
#############################################################################
$config{$_} = $CONFIG{$_} foreach keys %CONFIG;
$config{enable} = 'QRESYNC';
$config{name} = $name;
+ $config{'logger-fd'} = $LOGGER_FD if defined $LOGGER_FD;
$IMAP->{$name} = { client => Net::IMAP::Sync::->new(%config) };
my $client = $IMAP->{$name}->{client};
my $uid = $mail->{UID};
my $from = first { defined $_ and @$_ } @{$mail->{ENVELOPE}}[2,3,4];
$from = (defined $from and @$from) ? $from->[0]->[2].'@'.$from->[0]->[3] : '';
- print STDERR "$source($mailbox): UID $uid from <$from> ($mail->{INTERNALDATE})\n" unless $CONFIG{quiet};
+ msg("$source($mailbox): UID $uid from <$from> ($mail->{INTERNALDATE})") unless $CONFIG{quiet};
callback_new_message($idx, $mailbox, $source, $mail, \@uids, $buff, \$bufflen)
});
my %flags = map {$_ => 1} (split(/ /, $lFlags), split(/ /, $rFlags));
my $flags = join ' ', sort(keys %flags);
- warn "WARNING: Conflicting flag update in $mailbox for local UID $lUID ($lFlags) ".
- "and remote UID $rUID ($rFlags). Setting both to the union ($flags).\n";
+ msg("WARNING: Conflicting flag update in $mailbox for local UID $lUID ($lFlags) ".
+ "and remote UID $rUID ($rFlags). Setting both to the union ($flags).");
return $flags
}
my ($idx, $lUID) = @_;
my $r = $STH_DELETE_MAPPING->execute($idx, $lUID);
die if $r > 1; # sanity check
- warn "WARNING: Can't delete (idx,lUID) = ($idx,$lUID) from the database\n" if $r == 0;
+ msg("WARNING: Can't delete (idx,lUID) = ($idx,$lUID) from the database") if $r == 0;
}
}
else {
# conflict
- warn "WARNING: Missed flag update in $mailbox for (lUID,rUID) = ($lUID,$rUID). Repairing.\n"
+ msg("WARNING: Missed flag update in $mailbox for (lUID,rUID) = ($lUID,$rUID). Repairing.")
if $lModified->{$lUID}->[0] <= $cache->{lHIGHESTMODSEQ} and
$rModified->{$rUID}->[0] <= $cache->{rHIGHESTMODSEQ};
# set both $lUID and $rUID to the union of $lFlags and $rFlags
}
elsif (!defined $lModified->{$lUID} and !defined $rModified->{$rUID}) {
unless ($lVanished{$lUID} and $rVanished{$rUID}) {
- warn "WARNING: Pair (lUID,rUID) = ($lUID,$rUID) vanished from $mailbox. Repairing.\n";
+ msg("WARNING: Pair (lUID,rUID) = ($lUID,$rUID) vanished from $mailbox. Repairing.");
push @delete_mapping, $lUID;
}
}
if ($lVanished{$lUID}) {
push @rToRemove, $rUID;
} else {
- warn "local($mailbox): WARNING: UID $lUID disappeared. Downloading remote UID $rUID again.\n";
+ msg("local($mailbox): WARNING: UID $lUID disappeared. Downloading remote UID $rUID again.");
push @rMissing, $rUID;
}
}
if ($rVanished{$rUID}) {
push @lToRemove, $lUID;
} else {
- warn "remote($mailbox): WARNING: UID $rUID disappeared. Downloading local UID $lUID again.\n";
+ msg("remote($mailbox): WARNING: UID $rUID disappeared. Downloading local UID $lUID again.");
push @lMissing, $lUID;
}
}
# Process UID found in IMAP but not in the mapping table.
- warn "remote($mailbox): WARNING: No match for vanished local UID $_. Ignoring.\n" foreach keys %lVanished;
- warn "local($mailbox): WARNING: No match for vanished remote UID $_. Ignoring.\n" foreach keys %rVanished;
+ msg("remote($mailbox): WARNING: No match for vanished local UID $_. Ignoring.") foreach keys %lVanished;
+ msg("local($mailbox): WARNING: No match for vanished remote UID $_. Ignoring.") foreach keys %rVanished;
foreach my $lUID (keys %$lModified) {
- warn "remote($mailbox): WARNING: No match for modified local UID $lUID. Downloading again.\n";
+ msg("remote($mailbox): WARNING: No match for modified local UID $lUID. Downloading again.");
push @lMissing, $lUID;
}
foreach my $rUID (keys %$rModified) {
- warn "local($mailbox): WARNING: No match for modified remote UID $rUID. Downloading again.\n";
+ msg("local($mailbox): WARNING: No match for modified remote UID $rUID. Downloading again.");
push @rMissing, $rUID;
}
my ($rUID) = $STH_GET_REMOTE_UID->fetchrow_array();
die if defined $STH_GET_REMOTE_UID->fetchrow_arrayref(); # sanity check
if (!defined $rUID) {
- warn "remote($mailbox): WARNING: No match for vanished local UID $lUID. Ignoring.\n";
+ msg("remote($mailbox): WARNING: No match for vanished local UID $lUID. Ignoring.");
}
elsif (!exists $rVanished{$rUID}) {
push @rToRemove, $rUID;
my ($lUID) = $STH_GET_LOCAL_UID->fetchrow_array();
die if defined $STH_GET_LOCAL_UID->fetchrow_arrayref(); # sanity check
if (!defined $lUID) {
- warn "local($mailbox): WARNING: No match for vanished remote UID $rUID. Ignoring.\n";
+ msg("local($mailbox): WARNING: No match for vanished remote UID $rUID. Ignoring.");
}
elsif (!exists $lVanished{$lUID}) {
push @lToRemove, $lUID;
my ($rUID) = $STH_GET_REMOTE_UID->fetchrow_array();
die if defined $STH_GET_REMOTE_UID->fetchrow_arrayref(); # sanity check
if (!defined $rUID) {
- warn "remote($mailbox): WARNING: No match for modified local UID $lUID. Try '--repair'.\n";
+ msg("remote($mailbox): WARNING: No match for modified local UID $lUID. Try '--repair'.");
}
elsif (defined (my $rFlags = $rModified->{$rUID})) {
unless ($lFlags eq $rFlags) {
my ($lUID) = $STH_GET_LOCAL_UID->fetchrow_array();
die if defined $STH_GET_LOCAL_UID->fetchrow_arrayref(); # sanity check
if (!defined $lUID) {
- warn "local($mailbox): WARNING: No match for modified remote UID $rUID. Try '--repair'.\n";
+ msg("local($mailbox): WARNING: No match for modified remote UID $rUID. Try '--repair'.");
}
elsif (!exists $lModified->{$lUID}) {
# conflicts are taken care of above
my $length = length $mail->{RFC822};
if ($length == 0) {
- warn "$name($mailbox): WARNING: Ignoring new 0-length message (UID $mail->{UID})\n";
+ msg("$name($mailbox): WARNING: Ignoring new 0-length message (UID $mail->{UID})");
return;
}
my ($lUIDs, $rUIDs) = $name eq 'local' ? (\@sUID,\@tUID) : (\@tUID,\@sUID);
for (my $k=0; $k<=$#messages; $k++) {
- print STDERR "Adding mapping (lUID,rUID) = ($lUIDs->[$k],$rUIDs->[$k]) for $mailbox\n"
- if $CONFIG{debug};
+ logger("Adding mapping (lUID,rUID) = ($lUIDs->[$k],$rUIDs->[$k]) for $mailbox") if $CONFIG{debug};
$STH_INSERT_MAPPING->execute($idx, $lUIDs->[$k], $rUIDs->[$k]);
}
$DBH->commit(); # commit only once per batch
$STH_LIST_INTERRUPTED->execute();
while (defined (my $row = $STH_LIST_INTERRUPTED->fetchrow_arrayref())) {
($IDX, $MAILBOX) = @$row;
- print STDERR "Resuming interrupted sync for $MAILBOX\n";
+ msg("Resuming interrupted sync for $MAILBOX");
my %lUIDs;
$STH_GET_INTERRUPTED_BY_IDX->execute($IDX);
use Config::Tiny ();
use IO::Select ();
use List::Util 'first';
+use POSIX 'strftime';
use Socket 'SO_KEEPALIVE';
use Exporter 'import';
# advertise "ENABLE" in its CAPABILITY list or does not reply with
# an untagged ENABLED response with all the given extensions.
#
-# - 'STDERR': Where to log debug and informational messages (default:
-# STDERR)
-#
# - 'name': An optional instance name to include in log messages.
#
# - 'read-only': Use only commands that don't modify the server state.
# when getting new mails, in addition to (MODSEQ FLAGS INTERNALDATE
# BODY.PEEK[]).
#
+# - 'logger-fd': An optional filehandle to use for debug output.
+#
sub new($%) {
my $class = shift;
my $self = { @_ };
# whether we're allowed to to use read-write command
$self->{'read-only'} = uc ($self->{'read-only'} // 'NO') ne 'YES' ? 0 : 1;
- # where to log
- $self->{STDERR} //= \*STDERR;
-
# the IMAP state: one of 'UNAUTH', 'AUTH', 'SELECTED' or 'LOGOUT'
# (cf RFC 3501 section 3)
$self->{_STATE} = '';
}
-# Close handles when the Net::IMAP::Sync object is destroyed.
+# Log out when the Net::IMAP::Sync object is destroyed.
sub DESTROY($) {
my $self = shift;
if (defined $self->{STDIN} and $self->{STDIN}->opened() and
defined $self->{STDOUT} and $self->{STDOUT}->opened()) {
$self->logout();
}
- $self->{STDERR}->close() if defined $self->{STDERR} and $self->{STDERR}->opened()
- and $self->{STDERR} ne \*STDERR;
}
# $self->log($message, [...])
-# Log a $message.
+# $self->logger($message, [...])
+# Log a $message. The latter method is used to log in the 'logger-fd', and
+# add timestamps.
sub log($@) {
my $self = shift;
return unless @_;
+ $self->logger(@_) if defined $self->{'logger-fd'} and $self->{'logger-fd'} ne \*STDERR;
my $prefix = defined $self->{name} ? $self->{name} : '';
$prefix .= "($self->{_SELECTED})" if $self->{_STATE} eq 'SELECTED';
- $prefix .= ': ';
- $self->{STDERR}->say($prefix, @_);
+ print STDERR $prefix, ': ', @_, "\n";
+}
+sub logger($@) {
+ my $self = shift;
+ return unless @_ and defined $self->{'logger-fd'};
+ my $prefix = strftime "%b %e %H:%M:%S ", localtime;
+ $prefix .= defined "$self->{name}" ? $self->{name} : '';
+ $prefix .= "($self->{_SELECTED})" if $self->{_STATE} eq 'SELECTED';
+ $self->{'logger-fd'}->say($prefix, ': ', @_);
}
$cache->{$k} = $v;
}
- $self->log("Update last clean state for $mailbox: ".
- '('.join(' ', map {"$_ $cache->{$_}"} keys %$cache).')')
+ $self->logger("Update last clean state for $mailbox: ".
+ '('.join(' ', map {"$_ $cache->{$_}"} keys %$cache).')')
if $self->{debug};
}
my @dirty = grep { (!%mailboxes or $mailboxes{$_}) and $self->is_dirty($_) }
keys %{$self->{_CACHE}};
if ($self->{debug}) {
- @dirty ? $self->log("Dirty mailboxes: ".join(', ', @dirty))
- : $self->log("Clean state!");
+ @dirty ? $self->logger("Dirty mailboxes: ".join(', ', @dirty))
+ : $self->logger("Clean state!");
}
return $dirty[0];
}
my $x = $self->{STDOUT}->getline() // $self->panic("Can't read: $!");
$x =~ s/\r\n\z// or $self->panic($x);
- $self->log("S: $msg", $x) if $self->{debug};
+ $self->logger("S: $msg", $x) if $self->{debug};
return $x;
}
$litplus //= $self->_capable('LITERAL+') ? '+' : '';
push @command, $str, "{$len$litplus}", "\r\n";
- $self->log($dbg_cmd, $str, "{$len$litplus}") if $self->{debug};
+ $self->logger($dbg_cmd, $str, "{$len$litplus}") if $self->{debug};
$dbg_cmd = 'C: [...]';
unless ($litplus) {
push @command, $lit;
}
push @command, $command, "\r\n";
- $self->log($dbg_cmd, $command) if $self->{debug};
+ $self->logger($dbg_cmd, $command) if $self->{debug};
$self->{STDIN}->write(join('',@command)) // $self->panic("Can't write: $!");
$self->{STDIN}->flush();
local $_ = shift;
if (/\A\[ALERT\] $RE_TEXT_CHAR+\z/) {
- print STDERR $_, "\n";
+ $self->log($_);
}
elsif (/\A\[BADCHARSET .*\] $RE_TEXT_CHAR+\z/) {
$self->fail($_);
elsif (s/\A\+ //) {
if (defined $callback and $cmd eq 'AUTHENTICATE') {
my $x = $callback->($_);
- print STDERR "C: ", $x, "\n" if $self->{debug};
+ $self->logger("C: ", $x) if $self->{debug};
$self->{STDIN}->write($x."\r\n") // $self->panic("Can't write: $!");
$self->{STDIN}->flush();
}