source: perl/modules/IRC/lib/BarnOwl/Module/IRC/Connection.pm @ 41ade7f

release-1.10release-1.8release-1.9
Last change on this file since 41ade7f was 41ade7f, checked in by Nelson Elhage <nelhage@mit.edu>, 13 years ago
Try to improve disconnection behavior
  • Property mode set to 100644
File size: 14.7 KB
Line 
1use strict;
2use warnings;
3
4package BarnOwl::Module::IRC::Connection;
5use BarnOwl::Timer;
6
7=head1 NAME
8
9BarnOwl::Module::IRC::Connection
10
11=head1 DESCRIPTION
12
13This module is a wrapper around Net::IRC::Connection for BarnOwl's IRC
14support
15
16=cut
17
18use AnyEvent::IRC::Client;
19use AnyEvent::IRC::Util qw(split_prefix prefix_nick encode_ctcp);
20
21use base qw(Class::Accessor);
22use Exporter 'import';
23__PACKAGE__->mk_accessors(qw(conn alias motd names_tmp whois_tmp server autoconnect_channels));
24our @EXPORT_OK = qw(is_private);
25
26use BarnOwl;
27use Scalar::Util qw(weaken);
28
29sub new {
30    my $class = shift;
31    my $alias = shift;
32    my $host  = shift;
33    my $port  = shift;
34    my $args  = shift;
35    my $nick = $args->{nick};
36    my $conn = AnyEvent::IRC::Client->new();
37    my $self = bless({}, $class);
38    $self->conn($conn);
39    $self->autoconnect_channels([]);
40    $self->alias($alias);
41    $self->server($host);
42    $self->motd("");
43    $self->names_tmp(0);
44    $self->whois_tmp("");
45
46    if(delete $args->{SSL}) {
47        $conn->enable_ssl;
48    }
49    $conn->connect($host, $port, $args);
50    $conn->{heap}{parent} = $self;
51    weaken($conn->{heap}{parent});
52
53    sub on {
54        my $meth = "on_" . shift;
55        return sub {
56            my $conn = shift;
57            return unless $conn->{heap}{parent};
58            $conn->{heap}{parent}->$meth(@_);
59        }
60    }
61
62    # $self->conn->add_default_handler(sub { shift; $self->on_event(@_) });
63    $self->conn->reg_cb(registered => on("connect"),
64                        connfail   => sub { BarnOwl::error("Connection to $host failed!") },
65                        disconnect => on("disconnect"),
66                        publicmsg  => on("msg"),
67                        privatemsg => on("msg"),
68                        irc_error  => on("error"));
69    for my $m (qw(welcome yourhost created
70                  luserclient luserop luserchannels luserme
71                  error)) {
72        $self->conn->reg_cb("irc_$m" => on("admin_msg"));
73    }
74    $self->conn->reg_cb(irc_375       => on("motdstart"),
75                        irc_372       => on("motd"),
76                        irc_376       => on("endofmotd"),
77                        irc_join      => on("join"),
78                        irc_part      => on("part"),
79                        irc_quit      => on("quit"),
80                        irc_433       => on("nickinuse"),
81                        channel_topic => on("topic"),
82                        irc_333       => on("topicinfo"),
83                        irc_353       => on("namreply"),
84                        irc_366       => on("endofnames"),
85                        irc_311       => on("whois"),
86                        irc_312       => on("whois"),
87                        irc_319       => on("whois"),
88                        irc_320       => on("whois"),
89                        irc_318       => on("endofwhois"),
90                        irc_mode      => on("mode"),
91                        irc_401       => on("nosuch"),
92                        irc_402       => on("nosuch"),
93                        irc_403       => on("nosuch"),
94                        nick_change   => on("nick"),
95                        ctcp_action   => on("ctcp_action"),
96                        'irc_*' => sub { BarnOwl::debug("IRC: " . $_[1]->{command} .
97                                                        join(" ", @{$_[1]->{params}})) });
98
99    return $self;
100}
101
102sub nick {
103    my $self = shift;
104    return $self->conn->nick;
105}
106
107sub getSocket
108{
109    my $self = shift;
110    return $self->conn->socket;
111}
112
113sub me {
114    my ($self, $to, $msg) = @_;
115    $self->conn->send_msg('privmsg', $to,
116                          encode_ctcp(['ACTION', $msg]))
117}
118
119################################################################################
120############################### IRC callbacks ##################################
121################################################################################
122
123sub new_message {
124    my $self = shift;
125    my $evt = shift;
126    my %args = (
127        type        => 'IRC',
128        server      => $self->server,
129        network     => $self->alias,
130        @_
131       );
132    if ($evt) {
133        my ($nick, $user, $host) = split_prefix($evt);
134        $args{sender}   ||= $nick;
135        $args{hostname} ||= $host if defined($host);
136        $args{from}     ||= $evt->{prefix};
137        $args{params}   ||= join(' ', @{$evt->{params}})
138    }
139    return BarnOwl::Message->new(%args);
140}
141
142sub on_msg {
143    my ($self, $recipient, $evt) = @_;
144    my $body = strip_irc_formatting($evt->{params}->[1]);
145    $self->handle_message($recipient, $evt, $body);
146}
147
148sub on_ctcp_action {
149    my ($self, $src, $target, $msg) = @_;
150    my $body = strip_irc_formatting($msg);
151    my $evt = {
152        params => [$src],
153        type   => 'privmsg',
154        prefix => $src
155       };
156    $self->handle_message($target, $evt, "* $body");
157}
158
159sub handle_message {
160    my ($self, $recipient, $evt, $body) = @_;
161    my $msg = $self->new_message($evt,
162        direction   => 'in',
163        recipient   => $recipient,
164        body        => $body,
165        ($evt->{command}||'') eq 'notice' ?
166          (notice     => 'true') : (),
167        is_private($recipient) ?
168          (private  => 'true') : (channel => $recipient),
169        replycmd    => BarnOwl::quote('irc-msg', '-a', $self->alias,
170           (is_private($recipient) ? prefix_nick($evt) : $recipient)),
171        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
172       );
173
174    BarnOwl::queue_message($msg);
175}
176
177
178sub on_admin_msg {
179    my ($self, $evt) = @_;
180    return if BarnOwl::Module::IRC->skip_msg($evt->{command});
181    BarnOwl::admin_message("IRC",
182            BarnOwl::Style::boldify('IRC ' . $evt->{command} . ' message from '
183                . $self->alias) . "\n"
184            . strip_irc_formatting(join ' ', cdr($evt->{params})));
185}
186
187sub on_motdstart {
188    my ($self, $evt) = @_;
189    $self->motd(join "\n", cdr(@{$evt->{params}}));
190}
191
192sub on_motd {
193    my ($self, $evt) = @_;
194    $self->motd(join "\n", $self->motd, cdr(@{$evt->{params}}));
195}
196
197sub on_endofmotd {
198    my ($self, $evt) = @_;
199    $self->motd(join "\n", $self->motd, cdr(@{$evt->{params}}));
200    BarnOwl::admin_message("IRC",
201            BarnOwl::Style::boldify('MOTD for ' . $self->alias) . "\n"
202            . strip_irc_formatting($self->motd));
203}
204
205sub on_join {
206    my ($self, $evt) = @_;
207    my $chan = $evt->{params}[0];
208    my $msg = $self->new_message($evt,
209        loginout   => 'login',
210        action     => 'join',
211        channel    => $chan,
212        replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias, $chan),
213        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
214        );
215    BarnOwl::queue_message($msg);
216}
217
218sub on_part {
219    my ($self, $evt) = @_;
220    my $chan = $evt->{params}[0];
221    my $msg = $self->new_message($evt,
222        loginout   => 'logout',
223        action     => 'part',
224        channel    => $chan,
225        replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias, $chan),
226        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
227        );
228    BarnOwl::queue_message($msg);
229}
230
231sub on_quit {
232    my ($self, $evt) = @_;
233    my $msg = $self->new_message($evt,
234        loginout   => 'logout',
235        action     => 'quit',
236        from       => $evt->{prefix},
237        reason     => $evt->{params}->[0],
238        replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
239        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
240        );
241    BarnOwl::queue_message($msg);
242}
243
244sub disconnect {
245    my $self = shift;
246    delete $BarnOwl::Module::IRC::ircnets{$self->alias};
247    for my $k (keys %BarnOwl::Module::IRC::channels) {
248        my @conns = grep {$_ ne $self} @{$BarnOwl::Module::IRC::channels{$k}};
249        if(@conns) {
250            $BarnOwl::Module::IRC::channels{$k} = \@conns;
251        } else {
252            delete $BarnOwl::Module::IRC::channels{$k};
253        }
254    }
255    $self->motd("");
256}
257
258sub on_disconnect {
259    my ($self, $why) = @_;
260    BarnOwl::admin_message('IRC',
261                           "[" . $self->alias . "] Disconnected from server");
262    $self->disconnect;
263    if ($why && $why =~ m{error in connection}) {
264        $self->schedule_reconnect;
265    }
266}
267
268sub on_error {
269    my ($self, $evt) = @_;
270    BarnOwl::admin_message('IRC',
271                           "[" . $self->alias . "] " .
272                           "Error: " . join(" ", @{$evt->{params}}));
273}
274
275sub on_nickinuse {
276    my ($self, $evt) = @_;
277    BarnOwl::admin_message("IRC",
278                           "[" . $self->alias . "] " .
279                           $evt->{params}->[1] . ": Nick already in use");
280}
281
282sub on_nick {
283    my ($self, $old_nick, $new_nick, $is_me) = @_;
284    if ($is_me) {
285        BarnOwl::admin_message("IRC",
286                               "[" . $self->alias . "] " .
287                               "You are now known as $new_nick");
288    } else {
289        my $msg = $self->new_message('',
290            loginout   => 'login',
291            action     => 'nick change',
292            from       => $new_nick,
293            sender     => $new_nick,
294            replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias,
295                                         $new_nick),
296            replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias,
297                                             $new_nick),
298            old_nick   => $old_nick);
299        BarnOwl::queue_message($msg);
300    }
301}
302
303sub on_topic {
304    my ($self, $channel, $topic, $who) = @_;
305    if ($channel) {
306        BarnOwl::admin_message("IRC",
307                "Topic for $channel on " . $self->alias . " is $topic");
308    } else {
309        BarnOwl::admin_message("IRC",
310                "Topic changed to $channel");
311    }
312}
313
314sub on_topicinfo {
315    my ($self, $evt) = @_;
316    my @args = @{$evt->{params}};
317    BarnOwl::admin_message("IRC",
318        "Topic for $args[1] set by $args[2] at " . localtime($args[3]));
319}
320
321# IRC gives us a bunch of namreply messages, followed by an endofnames.
322# We need to collect them from the namreply and wait for the endofnames message.
323# After this happens, the names_tmp variable is cleared.
324
325sub on_namreply {
326    my ($self, $evt) = @_;
327    return unless $self->names_tmp;
328    $self->names_tmp([@{$self->names_tmp}, split(' ', $evt->{params}[3])]);
329}
330
331sub cmp_user {
332    my ($lhs, $rhs) = @_;
333    my ($sigil_l) = ($lhs =~ m{^([+@]?)});
334    my ($sigil_r) = ($rhs =~ m{^([+@]?)});
335    my %rank = ('@' => 1, '+' => 2, '' => 3);
336    return ($rank{$sigil_l} <=> $rank{$sigil_r}) ||
337            $lhs cmp $rhs;
338}
339
340sub on_endofnames {
341    my ($self, $evt) = @_;
342    return unless $self->names_tmp;
343    my $names = BarnOwl::Style::boldify("Members of " . $evt->{params}->[1] . ":\n");
344    for my $name (sort {cmp_user($a, $b)} @{$self->names_tmp}) {
345        $names .= "  $name\n";
346    }
347    BarnOwl::popless_ztext($names);
348    $self->names_tmp(0);
349}
350
351sub on_whois {
352    my ($self, $evt) = @_;
353    my %names = (
354        311 => 'user',
355        312 => 'server',
356        319 => 'channels',
357        330 => 'whowas',
358       );
359    $self->whois_tmp(
360        $self->whois_tmp . "\n" . $names{$evt->{command}} . ":\n  " .
361        join("\n  ", cdr(cdr(@{$evt->{params}}))) . "\n"
362       );
363}
364
365sub on_endofwhois {
366    my ($self, $evt) = @_;
367    BarnOwl::popless_ztext(
368        BarnOwl::Style::boldify("/whois for " . $evt->{params}->[1] . ":\n") .
369        $self->whois_tmp
370    );
371    $self->whois_tmp('');
372}
373
374sub on_mode {
375    my ($self, $evt) = @_;
376    BarnOwl::admin_message("IRC",
377                           "[" . $self->alias . "] User " . (prefix_nick($evt)) . + " set mode " .
378                           join(" ", cdr(@{$evt->{params}})) . "on " . $evt->{params}->[0]
379                          );
380}
381
382sub on_nosuch {
383    my ($self, $evt) = @_;
384    my %things = (401 => 'nick', 402 => 'server', 403 => 'channel');
385    BarnOwl::admin_message("IRC",
386                           "[" . $self->alias . "] " .
387                           "No such @{[$things{$evt->{command}}]}: @{[$evt->{params}->[1]]}")
388}
389
390sub on_event {
391    my ($self, $evt) = @_;
392    return on_whois(@_) if ($evt->type =~ /^whois/);
393    BarnOwl::admin_message("IRC",
394            "[" . $self->alias . "] Unhandled IRC event of type " . $evt->type . ":\n"
395            . strip_irc_formatting(join("\n", $evt->args)))
396        if BarnOwl::getvar('irc:spew') eq 'on';
397}
398
399sub schedule_reconnect {
400    my $self = shift;
401    my $interval = shift || 5;
402
403    my $weak = $self;
404    weaken($weak);
405    if (defined $self->{reconnect_timer}) {
406        $self->{reconnect_timer}->stop;
407    }
408    $self->{reconnect_timer} = 
409        BarnOwl::Timer->new( {
410            name  => 'IRC (' . $self->alias . ') reconnect_timer',
411            after => $interval,
412            cb    => sub {
413                $weak->reconnect( $interval ) if $weak;
414            },
415        } );
416}
417
418sub cancel_reconnect {
419    my $self = shift;
420
421    if (defined $self->{reconnect_timer}) {
422        $self->{reconnect_timer}->stop;
423    }
424    delete $self->{reconnect_timer};
425}
426
427sub on_connect {
428    my $self = shift;
429    $self->connected("Connected to " . $self->alias . " as " . $self->nick)
430}
431
432sub connected {
433    my $self = shift;
434    my $msg = shift;
435    BarnOwl::admin_message("IRC", $msg);
436    $self->cancel_reconnect;
437    if ($self->autoconnect_channels) {
438        for my $c (@{$self->autoconnect_channels}) {
439            $self->conn->send_msg(join => $c);
440        }
441        $self->autoconnect_channels([]);
442    }
443    $self->conn->enable_ping(60, sub {
444                                 $self->disconnect("Connection timed out.");
445                                 $self->schedule_reconnect;
446                             });
447}
448
449sub reconnect {
450    my $self = shift;
451    my $backoff = shift;
452
453    $self->autoconnect_channels([keys(%{$self->channel_list})]);
454    $self->conn->connect;
455    if ($self->conn->connected) {
456        $self->connected("Reconnected to ".$self->alias);
457        return;
458    }
459
460    $backoff *= 2;
461    $backoff = 60*5 if $backoff > 60*5;
462    $self->schedule_reconnect( $backoff );
463}
464
465################################################################################
466########################### Utilities/Helpers ##################################
467################################################################################
468
469sub strip_irc_formatting {
470    my $body = shift;
471    # Strip mIRC colors. If someone wants to write code to convert
472    # these to zephyr colors, be my guest.
473    $body =~ s/\cC\d+(?:,\d+)?//g;
474    $body =~ s/\cO//g;
475   
476    my @pieces = split /\cB/, $body;
477    my $out = '';
478    while(@pieces) {
479        $out .= shift @pieces;
480        $out .= BarnOwl::Style::boldify(shift @pieces) if @pieces;
481    }
482    return $out;
483}
484
485# Determines if the given message recipient is a username, as opposed to
486# a channel that starts with # or &.
487sub is_private {
488    return shift !~ /^[\#\&]/;
489}
490
491sub cdr {
492    shift;
493    return @_;
494}
495
4961;
Note: See TracBrowser for help on using the repository browser.