source: perl/modules/jabber.pl @ 0ad0e97

barnowl_perlaimdebianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 0ad0e97 was 0ad0e97, checked in by Nelson Elhage <nelhage@mit.edu>, 17 years ago
jabberlogin accepts a password argument
  • Property mode set to 100644
File size: 38.7 KB
Line 
1# -*- mode: cperl; cperl-indent-level: 4; indent-tabs-mode: nil -*-
2package BarnOwl::Jabber;
3use warnings;
4use strict;
5
6use Authen::SASL qw(Perl);
7use Net::Jabber;
8use Net::Jabber::MUC;
9use Net::DNS;
10use Getopt::Long;
11
12no warnings 'redefine';
13
14################################################################################
15# owl perl jabber support
16#
17# XXX Todo:
18# Rosters for MUCs
19# More user feedback
20#  * joining MUC
21#  * parting MUC
22#  * presence (Roster and MUC)
23# Implementing formatting and logging callbacks for C
24# Appropriate callbacks for presence subscription messages.
25#
26################################################################################
27
28
29################################################################################
30################################################################################
31package BarnOwl::Jabber::Connection;
32
33use base qw(Net::Jabber::Client);
34
35sub new {
36    my $class = shift;
37
38    my %args = ();
39    if(BarnOwl::getvar('debug') eq 'on') {
40        $args{debuglevel} = 1;
41        $args{debugfile} = 'jabber.log';
42    }
43    my $self = $class->SUPER::new(%args);
44    $self->{_BARNOWL_MUCS} = [];
45    return $self;
46}
47
48=head2 MUCJoin
49
50Extends MUCJoin to keep track of the MUCs we're joined to as
51Net::Jabber::MUC objects. Takes the same arguments as
52L<Net::Jabber::MUC/new> and L<Net::Jabber::MUC/Connect>
53
54=cut
55
56sub MUCJoin {
57    my $self = shift;
58    my $muc = Net::Jabber::MUC->new(connection => $self, @_);
59    $muc->Join(@_);
60    push @{$self->MUCs}, $muc;
61}
62
63=head2 MUCLeave ARGS
64
65Leave a MUC. The MUC is specified in the same form as L</FindMUC>
66
67=cut
68
69sub MUCLeave {
70    my $self = shift;
71    my $muc = $self->FindMUC(@_);
72    return unless $muc;
73
74    $muc->Leave();
75    $self->{_BARNOWL_MUCS} = [grep {$_->BaseJID ne $muc->BaseJID} $self->MUCs];
76}
77
78=head2 FindMUC ARGS
79
80Return the Net::Jabber::MUC object representing a specific MUC we're
81joined to, undef if it doesn't exists. ARGS can be either JID => $JID,
82or Room => $room, Server => $server.
83
84=cut
85
86sub FindMUC {
87    my $self = shift;
88
89    my %args;
90    while($#_ >= 0) { $args{ lc(pop(@_)) } = pop(@_); }
91
92    my $jid;
93    if($args{jid}) {
94        $jid = $args{jid};
95    } elsif($args{room} && $args{server}) {
96        $jid = Net::Jabber::JID->new(userid => $args{room},
97                                     server => $args{server});
98    }
99    $jid = $jid->GetJID('base') if UNIVERSAL::isa($jid, 'Net::Jabber::JID');
100
101    foreach my $muc ($self->MUCs) {
102        return $muc if $muc->BaseJID eq $jid;
103    }
104    return undef;
105}
106
107=head2 MUCs
108
109Returns a list (or arrayref in scalar context) of Net::Jabber::MUC
110objects we believe ourself to be connected to.
111
112=cut
113
114sub MUCs {
115    my $self = shift;
116    my $mucs = $self->{_BARNOWL_MUCS};
117    return wantarray ? @$mucs : $mucs;
118}
119
120################################################################################
121################################################################################
122package BarnOwl::Jabber::ConnectionManager;
123sub new {
124    my $class = shift;
125    return bless { }, $class;
126}
127
128sub addConnection {
129    my $self = shift;
130    my $jidStr = shift;
131
132    my $client = BarnOwl::Jabber::Connection->new;
133
134    $self->{$jidStr}->{Client} = $client;
135    $self->{$jidStr}->{Roster} = $client->Roster();
136    $self->{$jidStr}->{Status} = "available";
137    return $client;
138}
139
140sub removeConnection {
141    my $self = shift;
142    my $jidStr = shift;
143    return 0 unless exists $self->{$jidStr}->{Client};
144
145    $self->{$jidStr}->{Client}->Disconnect();
146    delete $self->{$jidStr};
147
148    return 1;
149}
150
151sub connected {
152    my $self = shift;
153    return scalar keys %{ $self };
154}
155
156sub getJids {
157    my $self = shift;
158    return keys %{ $self };
159}
160
161sub jidExists {
162    my $self = shift;
163    my $jidStr = shift;
164    return exists $self->{$jidStr};
165}
166
167sub sidExists {
168    my $self = shift;
169    my $sid = shift || "";
170    foreach my $c ( values %{ $self } ) {
171        return 1 if ($c->{Client}->{SESSION}->{id} eq $sid);
172    }
173    return 0;
174}
175
176sub getConnectionFromSid {
177    my $self = shift;
178    my $sid = shift;
179    foreach my $c (values %{ $self }) {
180        return $c->{Client} if $c->{Client}->{SESSION}->{id} eq $sid;
181    }
182    return undef;
183}
184
185sub getConnectionFromJID {
186    my $self = shift;
187    my $jid = shift;
188    $jid = $jid->GetJID('full') if UNIVERSAL::isa($jid, 'Net::XMPP::JID');
189    return $self->{$jid}->{Client} if exists $self->{$jid};
190}
191
192sub getRosterFromSid {
193    my $self = shift;
194    my $sid = shift;
195    foreach my $c (values %{ $self }) {
196        return $c->{Roster}
197          if $c->{Client}->{SESSION}->{id} eq $sid;
198    }
199    return undef;
200}
201
202sub getRosterFromJID {
203    my $self = shift;
204    my $jid = shift;
205    $jid = $jid->GetJID('full') if UNIVERSAL::isa($jid, 'Net::XMPP::JID');
206    return $self->{$jid}->{Roster} if exists $self->{$jid};
207}
208################################################################################
209
210package BarnOwl::Jabber;
211
212our $conn = new BarnOwl::Jabber::ConnectionManager unless $conn;;
213our %vars;
214
215sub onStart {
216    if ( *BarnOwl::queue_message{CODE} ) {
217        register_owl_commands();
218        push @::onMainLoop,     sub { BarnOwl::Jabber::onMainLoop(@_) };
219        push @::onGetBuddyList, sub { BarnOwl::Jabber::onGetBuddyList(@_) };
220        $vars{show} = '';
221    } else {
222        # Our owl doesn't support queue_message. Unfortunately, this
223        # means it probably *also* doesn't support BarnOwl::error. So just
224        # give up silently.
225    }
226}
227
228push @::onStartSubs, sub { BarnOwl::Jabber::onStart(@_) };
229
230sub onMainLoop {
231    return if ( !$conn->connected() );
232
233    $vars{status_changed} = 0;
234    my $idletime = owl::getidletime();
235    if ($idletime >= 900 && $vars{show} eq 'away') {
236        $vars{show} = 'xa';
237        $vars{status} = 'Auto extended-away after 15 minutes idle.';
238        $vars{status_changed} = 1;
239    } elsif ($idletime >= 300 && $vars{show} eq '') {
240        $vars{show} = 'away';
241        $vars{status} = 'Auto away after 5 minutes idle.';
242        $vars{status_changed} = 1;
243    } elsif ($idletime == 0 && $vars{show} ne '') {
244        $vars{show} = '';
245        $vars{status} = '';
246        $vars{status_changed} = 1;
247    }
248
249    foreach my $jid ( $conn->getJids() ) {
250        my $client = $conn->getConnectionFromJID($jid);
251
252        unless($client) {
253            $conn->removeConnection($jid);
254            BarnOwl::error("Connection for $jid undefined -- error in reload?");
255        }
256       
257        my $status = $client->Process(0);
258        if ( !defined($status) ) {
259            BarnOwl::error("Jabber account $jid disconnected!");
260            do_logout($jid);
261        }
262        if ($::shutdown) {
263            do_logout($jid);
264            return;
265        }
266        if ($vars{status_changed}) {
267            my $p = new Net::XMPP::Presence;
268            $p->SetShow($vars{show}) if $vars{show};
269            $p->SetStatus($vars{status}) if $vars{status};
270            $client->Send($p);
271        }
272    }
273}
274
275sub blist_listBuddy {
276    my $roster = shift;
277    my $buddy  = shift;
278    my $blistStr .= "    ";
279    my %jq  = $roster->query($buddy);
280    my $res = $roster->resource($buddy);
281
282    my $name = $jq{name} || $buddy->GetUserID();
283
284    $blistStr .= sprintf '%-15s %s', $name, $buddy->GetJID();
285
286    if ($res) {
287        my %rq = $roster->resourceQuery( $buddy, $res );
288        $blistStr .= " [" . ( $rq{show} ? $rq{show} : 'online' ) . "]";
289        $blistStr .= " " . $rq{status} if $rq{status};
290        $blistStr = boldify($blistStr);
291    }
292    else {
293        if ($jq{ask}) {
294            $blistStr .= " [pending]";
295        }
296        elsif ($jq{subscription} eq 'none' || $jq{subscription} eq 'from') {
297            $blistStr .= " [not subscribed]";
298        }
299        else {
300            $blistStr .= " [offline]";
301        }
302    }
303    return $blistStr . "\n";
304}
305
306sub getSingleBuddyList {
307    my $jid = shift;
308    $jid = resolveConnectedJID($jid);
309    return "" unless $jid;
310    my $blist = "";
311    my $roster = $conn->getRosterFromJID($jid);
312    if ($roster) {
313        $blist .= "\n" . boldify("Jabber Roster for $jid\n");
314
315        foreach my $group ( $roster->groups() ) {
316            $blist .= "  Group: $group\n";
317            my @buddies = $roster->jids( 'group', $group );
318            foreach my $buddy ( @buddies ) {
319                $blist .= blist_listBuddy( $roster, $buddy );
320            }
321        }
322
323        my @unsorted = $roster->jids('nogroup');
324        if (@unsorted) {
325            $blist .= "  [unsorted]\n";
326            foreach my $buddy (@unsorted) {
327                $blist .= blist_listBuddy( $roster, $buddy );
328            }
329        }
330    }
331    return $blist;
332}
333
334sub onGetBuddyList {
335    my $blist = "";
336    foreach my $jid ($conn->getJids()) {
337        $blist .= getSingleBuddyList($jid);
338    }
339    return $blist;
340}
341
342################################################################################
343### Owl Commands
344sub register_owl_commands() {
345    BarnOwl::new_command(
346        jabberlogin => \&cmd_login,
347        { summary => "Log into jabber", },
348        { usage   => "jabberlogin JID [PASSWORD]" }
349    );
350    BarnOwl::new_command(
351        jabberlogout => \&cmd_logout,
352        { summary => "Log out of jabber" }
353    );
354    BarnOwl::new_command(
355        jwrite => \&cmd_jwrite,
356        {
357            summary => "Send a Jabber Message",
358            usage   => "jwrite JID [-t thread] [-s subject]"
359        }
360    );
361    BarnOwl::new_command(
362        jlist => \&cmd_jlist,
363        {
364            summary => "Show your Jabber roster.",
365            usage   => "jlist"
366        }
367    );
368    BarnOwl::new_command(
369        jmuc => \&cmd_jmuc,
370        {
371            summary     => "Jabber MUC related commands.",
372            description => "jmuc sends jabber commands related to muc.\n\n"
373              . "The following commands are available\n\n"
374              . "join MUC    Join a muc.\n\n"
375              . "part MUC    Part a muc.\n"
376              . "            The muc is taken from the current message if not supplied.\n\n"
377              . "invite JID MUC\n"
378              . "            Invite JID to MUC.\n"
379              . "            The muc is taken from the current message if not supplied.\n\n"
380              . "configure MUC\n"
381              . "            Configure [muc].\n"
382              . "            Necessary to initalize a new MUC\n"
383              . "            At present, only the default configuration is supported.",
384            usage => "jmuc COMMAND ARGS"
385        }
386    );
387    BarnOwl::new_command(
388        jroster => \&cmd_jroster,
389        {
390            summary     => "Jabber Roster related commands.",
391            description => "jroster sends jabber commands related to rosters.\n\n",
392            usage       => "jroster COMMAND ARGS"
393        }
394    );
395}
396
397sub cmd_login {
398    my $cmd = shift;
399    my $jid = new Net::XMPP::JID;
400    $jid->SetJID(shift);
401    my $password = undef;
402    $password = shift if @_;
403   
404    my $uid           = $jid->GetUserID();
405    my $componentname = $jid->GetServer();
406    my $resource      = $jid->GetResource() || 'owl';
407    $jid->SetResource($resource);
408    my $jidStr = $jid->GetJID('full');
409
410    if ( !$uid || !$componentname ) {
411        BarnOwl::error("usage: $cmd JID");
412        return;
413    }
414
415    if ( $conn->jidExists($jidStr) ) {
416        BarnOwl::error("Already logged in as $jidStr.");
417        return;
418    }
419
420    my ( $server, $port ) = getServerFromJID($jid);
421
422    $vars{jlogin_jid} = $jidStr;
423    $vars{jlogin_password} = $password;
424    $vars{jlogin_connhash} = {
425        hostname      => $server,
426        tls           => 1,
427        port          => $port,
428        componentname => $componentname
429    };
430    $vars{jlogin_authhash} =
431      { username => $uid,
432        resource => $resource,
433    };
434
435    return do_login($password);
436}
437
438sub do_login {
439    $vars{jlogin_password} = shift;
440    $vars{jlogin_authhash}->{password} = sub { return $vars{jlogin_password} || '' };
441    my $jidStr = $vars{jlogin_jid};
442    if ( !$jidStr && $vars{jlogin_havepass}) {
443        BarnOwl::error("Got password but have no jid!");
444    }
445    else
446    {
447        my $client = $conn->addConnection($jidStr);
448
449        #XXX Todo: Add more callbacks.
450        # * MUC presence handlers
451        # We use the anonymous subrefs in order to have the correct behavior
452        # when we reload
453        $client->SetMessageCallBacks(
454            chat      => sub { BarnOwl::Jabber::process_incoming_chat_message(@_) },
455            error     => sub { BarnOwl::Jabber::process_incoming_error_message(@_) },
456            groupchat => sub { BarnOwl::Jabber::process_incoming_groupchat_message(@_) },
457            headline  => sub { BarnOwl::Jabber::process_incoming_headline_message(@_) },
458            normal    => sub { BarnOwl::Jabber::process_incoming_normal_message(@_) }
459        );
460        $client->SetPresenceCallBacks(
461            available    => sub { BarnOwl::Jabber::process_presence_available(@_) },
462            unavailable  => sub { BarnOwl::Jabber::process_presence_available(@_) },
463            subscribe    => sub { BarnOwl::Jabber::process_presence_subscribe(@_) },
464            subscribed   => sub { BarnOwl::Jabber::process_presence_subscribed(@_) },
465            unsubscribe  => sub { BarnOwl::Jabber::process_presence_unsubscribe(@_) },
466            unsubscribed => sub { BarnOwl::Jabber::process_presence_unsubscribed(@_) },
467            error        => sub { BarnOwl::Jabber::process_presence_error(@_) });
468
469        my $status = $client->Connect( %{ $vars{jlogin_connhash} } );
470        if ( !$status ) {
471            $conn->removeConnection($jidStr);
472            BarnOwl::error("We failed to connect");
473        } else {
474            my @result = $client->AuthSend( %{ $vars{jlogin_authhash} } );
475
476            if ( !@result || $result[0] ne 'ok' ) {
477                if ( !$vars{jlogin_havepass} && ( !@result || $result[0] eq '401' ) ) {
478                    $vars{jlogin_havepass} = 1;
479                    $conn->removeConnection($jidStr);
480                    BarnOwl::start_password( "Password for $jidStr: ", \&do_login );
481                    return "";
482                }
483                $conn->removeConnection($jidStr);
484                BarnOwl::error( "Error in connect: " . join( " ", @result ) );
485            } else {
486                $conn->getRosterFromJID($jidStr)->fetch();
487                $client->PresenceSend( priority => 1 );
488                queue_admin_msg("Connected to jabber as $jidStr");
489            }
490        }
491
492    }
493    delete $vars{jlogin_jid};
494    $vars{jlogin_password} =~ tr/\0-\377/x/;
495    delete $vars{jlogin_password};
496    delete $vars{jlogin_havepass};
497    delete $vars{jlogin_connhash};
498    delete $vars{jlogin_authhash};
499    return "";
500}
501
502sub do_logout {
503    my $jid = shift;
504    my $disconnected = $conn->removeConnection($jid);
505    queue_admin_msg("Jabber disconnected ($jid).") if $disconnected;
506}
507
508sub cmd_logout {
509    # Logged into multiple accounts
510    if ( $conn->connected() > 1 ) {
511        # Logged into multiple accounts, no accout specified.
512        if ( !$_[1] ) {
513            my $errStr =
514              "You are logged into multiple accounts. Please specify an account to log out of.\n";
515            foreach my $jid ( $conn->getJids() ) {
516                $errStr .= "\t$jid\n";
517            }
518            queue_admin_msg($errStr);
519        }
520        # Logged into multiple accounts, account specified.
521        else {
522            if ( $_[1] eq '-a' )    #All accounts.
523            {
524                foreach my $jid ( $conn->getJids() ) {
525                    do_logout($jid);
526                }
527            }
528            else                    #One account.
529            {
530                my $jid = resolveConnectedJID( $_[1] );
531                do_logout($jid) if ( $jid ne '' );
532            }
533        }
534    }
535    else                            # Only one account logged in.
536    {
537        do_logout( ( $conn->getJids() )[0] );
538    }
539    return "";
540}
541
542sub cmd_jlist {
543    if ( !( scalar $conn->getJids() ) ) {
544        BarnOwl::error("You are not logged in to Jabber.");
545        return;
546    }
547    BarnOwl::popless_ztext( onGetBuddyList() );
548}
549
550sub cmd_jwrite {
551    if ( !$conn->connected() ) {
552        BarnOwl::error("You are not logged in to Jabber.");
553        return;
554    }
555
556    my $jwrite_to      = "";
557    my $jwrite_from    = "";
558    my $jwrite_sid     = "";
559    my $jwrite_thread  = "";
560    my $jwrite_subject = "";
561    my $to;
562    my $jwrite_type    = "chat";
563
564    my @args = @_;
565    shift;
566    local @ARGV = @_;
567    my $gc;
568    GetOptions(
569        'thread=s'  => \$jwrite_thread,
570        'subject=s' => \$jwrite_subject,
571        'account=s' => \$jwrite_from,
572        'id=s'     =>  \$jwrite_sid,
573    );
574    $jwrite_type = 'groupchat' if $gc;
575
576    if ( scalar @ARGV != 1 ) {
577        BarnOwl::error(
578            "Usage: jwrite JID [-t thread] [-s 'subject'] [-a account]");
579        return;
580    }
581    else {
582        $to = shift @ARGV;
583    }
584
585    ($jwrite_from, $jwrite_to, $jwrite_type) = guess_jwrite($jwrite_from, $to);
586   
587    unless($jwrite_to) {
588        die("Unable to resolve JID $to");
589    }
590
591    unless($jwrite_from) {
592        die("Unable to resolve account");
593    }
594   
595    $vars{jwrite} = {
596        to      => $jwrite_to,
597        from    => $jwrite_from,
598        sid     => $jwrite_sid,
599        subject => $jwrite_subject,
600        thread  => $jwrite_thread,
601        type    => $jwrite_type
602    };
603
604    BarnOwl::message(
605"Type your message below.  End with a dot on a line by itself.  ^C will quit."
606    );
607    my $cmd = "jwrite $jwrite_to -a $jwrite_from";
608    $cmd .= " -t $jwrite_thread" if $jwrite_thread;
609    $cmd .= " -t $jwrite_subject" if $jwrite_subject;
610    BarnOwl::start_edit_win( $cmd, \&process_owl_jwrite );
611}
612
613sub cmd_jmuc {
614    die "You are not logged in to Jabber" unless $conn->connected();
615    my $ocmd = shift;
616    my $cmd  = shift;
617    if ( !$cmd ) {
618
619        #XXX TODO: Write general usage for jmuc command.
620        return;
621    }
622
623    my %jmuc_commands = (
624        join      => \&jmuc_join,
625        part      => \&jmuc_part,
626        invite    => \&jmuc_invite,
627        configure => \&jmuc_configure,
628        presence  => \&jmuc_presence
629    );
630    my $func = $jmuc_commands{$cmd};
631    if ( !$func ) {
632        BarnOwl::error("jmuc: Unknown command: $cmd");
633        return;
634    }
635
636    {
637        local @ARGV = @_;
638        my $jid;
639        my $muc;
640        my $m = BarnOwl::getcurmsg();
641        if ( $m && $m->is_jabber && $m->{jtype} eq 'groupchat' ) {
642            $muc = $m->{room};
643            $jid = $m->{to};
644        }
645
646        my $getopt = Getopt::Long::Parser->new;
647        $getopt->configure('pass_through');
648        $getopt->getoptions( 'account=s' => \$jid );
649        $jid ||= defaultJID();
650        if ($jid) {
651            $jid = resolveConnectedJID($jid);
652            return unless $jid;
653        }
654        else {
655            BarnOwl::error('You must specify an account with -a {jid}');
656        }
657        return $func->( $jid, $muc, @ARGV );
658    }
659}
660
661sub jmuc_join {
662    my ( $jid, $muc, @args ) = @_;
663    local @ARGV = @args;
664    my $password;
665    GetOptions( 'password=s' => \$password );
666
667    $muc = shift @ARGV
668      or die("Usage: jmuc join MUC [-p password] [-a account]");
669
670    $conn->getConnectionFromJID($jid)->MUCJoin(Jid      => $muc,
671                                                  Password => $password,
672                                                  History  => {
673                                                      MaxChars => 0
674                                                     });
675    return;
676}
677
678sub jmuc_part {
679    my ( $jid, $muc, @args ) = @_;
680
681    $muc = shift @args if scalar @args;
682    die("Usage: jmuc part MUC [-a account]") unless $muc;
683
684    $conn->getConnectionFromJID($jid)->MUCLeave(JID => $muc);
685    queue_admin_msg("$jid has left $muc.");
686}
687
688sub jmuc_invite {
689    my ( $jid, $muc, @args ) = @_;
690
691    my $invite_jid = shift @args;
692    $muc = shift @args if scalar @args;
693
694    die('Usage: jmuc invite JID [muc] [-a account]')
695      unless $muc && $invite_jid;
696
697    my $message = Net::Jabber::Message->new();
698    $message->SetTo($muc);
699    my $x = $message->NewChild('http://jabber.org/protocol/muc#user');
700    $x->AddInvite();
701    $x->GetInvite()->SetTo($invite_jid);
702    $conn->getConnectionFromJID($jid)->Send($message);
703    queue_admin_msg("$jid has invited $invite_jid to $muc.");
704}
705
706sub jmuc_configure {
707    my ( $jid, $muc, @args ) = @_;
708    $muc = shift @args if scalar @args;
709    die("Usage: jmuc configure [muc]") unless $muc;
710    my $iq = Net::Jabber::IQ->new();
711    $iq->SetTo($muc);
712    $iq->SetType('set');
713    my $query = $iq->NewQuery("http://jabber.org/protocol/muc#owner");
714    my $x     = $query->NewChild("jabber:x:data");
715    $x->SetType('submit');
716
717    $conn->getConnectionFromJID($jid)->Send($iq);
718    queue_admin_msg("Accepted default instant configuration for $muc");
719}
720
721sub jmuc_presence {
722    my ( $jid, $muc, @args ) = @_;
723
724    $muc = shift @args if scalar @args;
725    die("Usage: jmuc presence MUC") unless $muc;
726
727    my $m = $conn->getConnectionFromJID($jid)->FindMUC(jid => $muc);
728    die("No such muc: $muc") unless $m;
729
730    my @jids = $m->Presence();
731    BarnOwl::popless_ztext("JIDs present in " . $m->BaseJID . "\n\t" .
732                           join("\n\t", map {$_->GetResource}@jids) . "\n");
733}
734
735
736#XXX TODO: Consider merging this with jmuc and selecting off the first two args.
737sub cmd_jroster {
738    die "You are not logged in to Jabber" unless $conn->connected();
739    my $ocmd = shift;
740    my $cmd  = shift;
741    if ( !$cmd ) {
742
743        #XXX TODO: Write general usage for jroster command.
744        return;
745    }
746
747    my %jroster_commands = (
748        sub      => \&jroster_sub,
749        unsub    => \&jroster_unsub,
750        add      => \&jroster_add,
751        remove   => \&jroster_remove,
752        auth     => \&jroster_auth,
753        deauth   => \&jroster_deauth
754    );
755    my $func = $jroster_commands{$cmd};
756    if ( !$func ) {
757        BarnOwl::error("jroster: Unknown command: $cmd");
758        return;
759    }
760
761    {
762        local @ARGV = @_;
763        my $jid;
764        my $name;
765        my @groups;
766        my $purgeGroups;
767        my $getopt = Getopt::Long::Parser->new;
768        $getopt->configure('pass_through');
769        $getopt->getoptions(
770            'account=s' => \$jid,
771            'group=s' => \@groups,
772            'purgegroups' => \$purgeGroups,
773            'name=s' => \$name
774        );
775        $jid ||= defaultJID();
776        if ($jid) {
777            $jid = resolveConnectedJID($jid);
778            return unless $jid;
779        }
780        else {
781            BarnOwl::error('You must specify an account with -a {jid}');
782        }
783        return $func->( $jid, $name, \@groups, $purgeGroups,  @ARGV );
784    }
785}
786
787sub jroster_sub {
788    my $jid = shift;
789    my $name = shift;
790    my @groups = @{ shift() };
791    my $purgeGroups = shift;
792    my $baseJid = baseJID($jid);
793
794    my $roster = $conn->getRosterFromJID($jid);
795
796    # Adding lots of users with the same name is a bad idea.
797    $name = "" unless (1 == scalar(@ARGV));
798
799    my $p = new Net::XMPP::Presence;
800    $p->SetType('subscribe');
801
802    foreach my $to (@ARGV) {
803        jroster_add($jid, $name, \@groups, $purgeGroups, ($to)) unless ($roster->exists($to));
804
805        $p->SetTo($to);
806        $conn->getConnectionFromJID($jid)->Send($p);
807        queue_admin_msg("You ($baseJid) have requested a subscription to ($to)'s presence.");
808    }
809}
810
811sub jroster_unsub {
812    my $jid = shift;
813    my $name = shift;
814    my @groups = @{ shift() };
815    my $purgeGroups = shift;
816    my $baseJid = baseJID($jid);
817
818    my $p = new Net::XMPP::Presence;
819    $p->SetType('unsubscribe');
820    foreach my $to (@ARGV) {
821        $p->SetTo($to);
822        $conn->getConnectionFromJID($jid)->Send($p);
823        queue_admin_msg("You ($baseJid) have unsubscribed from ($to)'s presence.");
824    }
825}
826
827sub jroster_add {
828    my $jid = shift;
829    my $name = shift;
830    my @groups = @{ shift() };
831    my $purgeGroups = shift;
832    my $baseJid = baseJID($jid);
833
834    my $roster = $conn->getRosterFromJID($jid);
835
836    # Adding lots of users with the same name is a bad idea.
837    $name = "" unless (1 == scalar(@ARGV));
838
839    foreach my $to (@ARGV) {
840        my %jq  = $roster->query($to);
841        my $iq = new Net::XMPP::IQ;
842        $iq->SetType('set');
843        my $item = new XML::Stream::Node('item');
844        $iq->NewChild('jabber:iq:roster')->AddChild($item);
845
846        my %allGroups = ();
847
848        foreach my $g (@groups) {
849            $allGroups{$g} = $g;
850        }
851
852        unless ($purgeGroups) {
853            foreach my $g (@{$jq{groups}}) {
854                $allGroups{$g} = $g;
855            }
856        }
857
858        foreach my $g (keys %allGroups) {
859            $item->add_child('group')->add_cdata($g);
860        }
861
862        $item->put_attrib(jid => $to);
863        $item->put_attrib(name => $name) if $name;
864        $conn->getConnectionFromJID($jid)->Send($iq);
865        my $msg = "$baseJid: "
866          . ($name ? "$name ($to)" : "($to)")
867          . " is on your roster in the following groups: { "
868          . join(" , ", keys %allGroups)
869          . " }";
870        queue_admin_msg($msg);
871    }
872}
873
874sub jroster_remove {
875    my $jid = shift;
876    my $name = shift;
877    my @groups = @{ shift() };
878    my $purgeGroups = shift;
879    my $baseJid = baseJID($jid);
880
881    my $iq = new Net::XMPP::IQ;
882    $iq->SetType('set');
883    my $item = new XML::Stream::Node('item');
884    $iq->NewChild('jabber:iq:roster')->AddChild($item);
885    $item->put_attrib(subscription=> 'remove');
886    foreach my $to (@ARGV) {
887        $item->put_attrib(jid => $to);
888        $conn->getConnectionFromJID($jid)->Send($iq);
889        queue_admin_msg("You ($baseJid) have removed ($to) from your roster.");
890    }
891}
892
893sub jroster_auth {
894    my $jid = shift;
895    my $name = shift;
896    my @groups = @{ shift() };
897    my $purgeGroups = shift;
898    my $baseJid = baseJID($jid);
899
900    my $p = new Net::XMPP::Presence;
901    $p->SetType('subscribed');
902    foreach my $to (@ARGV) {
903        $p->SetTo($to);
904        $conn->getConnectionFromJID($jid)->Send($p);
905        queue_admin_msg("($to) has been subscribed to your ($baseJid) presence.");
906    }
907}
908
909sub jroster_deauth {
910    my $jid = shift;
911    my $name = shift;
912    my @groups = @{ shift() };
913    my $purgeGroups = shift;
914    my $baseJid = baseJID($jid);
915
916    my $p = new Net::XMPP::Presence;
917    $p->SetType('unsubscribed');
918    foreach my $to (@ARGV) {
919        $p->SetTo($to);
920        $conn->getConnectionFromJID($jid)->Send($p);
921        queue_admin_msg("($to) has been unsubscribed from your ($baseJid) presence.");
922    }
923}
924
925################################################################################
926### Owl Callbacks
927sub process_owl_jwrite {
928    my $body = shift;
929
930    my $j = new Net::XMPP::Message;
931    $body =~ s/\n\z//;
932    $j->SetMessage(
933        to   => $vars{jwrite}{to},
934        from => $vars{jwrite}{from},
935        type => $vars{jwrite}{type},
936        body => $body
937    );
938
939    $j->SetThread( $vars{jwrite}{thread} )   if ( $vars{jwrite}{thread} );
940    $j->SetSubject( $vars{jwrite}{subject} ) if ( $vars{jwrite}{subject} );
941
942    my $m = j2o( $j, { direction => 'out' } );
943    if ( $vars{jwrite}{type} ne 'groupchat' && BarnOwl::getvar('displayoutgoing') eq 'on') {
944        BarnOwl::queue_message($m);
945    }
946
947    $j->RemoveFrom(); # Kludge to get around gtalk's random bits after the resouce.
948    if ($vars{jwrite}{sid} && $conn->sidExists( $vars{jwrite}{sid} )) {
949        $conn->getConnectionFromSid($vars{jwrite}{sid})->Send($j);
950    }
951    else {
952        $conn->getConnectionFromJID($vars{jwrite}{from})->Send($j);
953    }
954
955    delete $vars{jwrite};
956    BarnOwl::message("");   # Kludge to make the ``type your message...'' message go away
957}
958
959### XMPP Callbacks
960
961sub process_incoming_chat_message {
962    my ( $sid, $j ) = @_;
963    BarnOwl::queue_message( j2o( $j, { direction => 'in',
964                                   sid => $sid } ) );
965}
966
967sub process_incoming_error_message {
968    my ( $sid, $j ) = @_;
969    my %jhash = j2hash( $j, { direction => 'in',
970                              sid => $sid } );
971    $jhash{type} = 'admin';
972    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
973}
974
975sub process_incoming_groupchat_message {
976    my ( $sid, $j ) = @_;
977
978    # HACK IN PROGRESS (ignoring delayed messages)
979    return if ( $j->DefinedX('jabber:x:delay') && $j->GetX('jabber:x:delay') );
980    BarnOwl::queue_message( j2o( $j, { direction => 'in',
981                                   sid => $sid } ) );
982}
983
984sub process_incoming_headline_message {
985    my ( $sid, $j ) = @_;
986    BarnOwl::queue_message( j2o( $j, { direction => 'in',
987                                   sid => $sid } ) );
988}
989
990sub process_incoming_normal_message {
991    my ( $sid, $j ) = @_;
992    my %jhash = j2hash( $j, { direction => 'in',
993                              sid => $sid } );
994
995    # XXX TODO: handle things such as MUC invites here.
996
997    #    if ($j->HasX('http://jabber.org/protocol/muc#user'))
998    #    {
999    #   my $x = $j->GetX('http://jabber.org/protocol/muc#user');
1000    #   if ($x->HasChild('invite'))
1001    #   {
1002    #       $props
1003    #   }
1004    #    }
1005    #
1006    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
1007}
1008
1009sub process_muc_presence {
1010    my ( $sid, $p ) = @_;
1011    return unless ( $p->HasX('http://jabber.org/protocol/muc#user') );
1012}
1013
1014
1015sub process_presence_available {
1016    my ( $sid, $p ) = @_;
1017    my $from = $p->GetFrom();
1018    my $to = $p->GetTo();
1019    my $type = $p->GetType();
1020    my %props = (
1021        to => $to,
1022        from => $from,
1023        recipient => $to,
1024        sender => $from,
1025        type => 'jabber',
1026        jtype => $p->GetType(),
1027        status => $p->GetStatus(),
1028        show => $p->GetShow(),
1029        xml => $p->GetXML(),
1030        direction => 'in');
1031
1032    if ($type eq '' || $type eq 'available') {
1033        $props{body} = "$from is now online. ";
1034        $props{loginout} = 'login';
1035    }
1036    else {
1037        $props{body} = "$from is now offline. ";
1038        $props{loginout} = 'logout';
1039    }
1040    $props{replysendercmd} = $props{replycmd} = "jwrite $from -i $sid";
1041    if(BarnOwl::getvar('debug') eq 'on') {
1042        BarnOwl::queue_message(BarnOwl::Message->new(%props));
1043    }
1044}
1045
1046sub process_presence_subscribe {
1047    my ( $sid, $p ) = @_;
1048    my $from = $p->GetFrom();
1049    my $to = $p->GetTo();
1050    my %props = (
1051        to => $to,
1052        from => $from,
1053        xml => $p->GetXML(),
1054        type => 'admin',
1055        adminheader => 'Jabber presence: subscribe',
1056        direction => 'in');
1057
1058    $props{body} = "Allow user ($from) to subscribe to your ($to) presence?\n" .
1059                   "(Answer with the `yes' or `no' commands)";
1060    $props{yescommand} = "jroster auth $from -a $to";
1061    $props{nocommand} = "jroster deauth $from -a $to";
1062    $props{question} = "true";
1063    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1064}
1065
1066sub process_presence_unsubscribe {
1067    my ( $sid, $p ) = @_;
1068    my $from = $p->GetFrom();
1069    my $to = $p->GetTo();
1070    my %props = (
1071        to => $to,
1072        from => $from,
1073        xml => $p->GetXML(),
1074        type => 'admin',
1075        adminheader => 'Jabber presence: unsubscribe',
1076        direction => 'in');
1077
1078    $props{body} = "The user ($from) has been unsubscribed from your ($to) presence.\n";
1079    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1080
1081    # Find a connection to reply with.
1082    foreach my $jid ($conn->getJids()) {
1083        my $cJid = new Net::XMPP::JID;
1084        $cJid->SetJID($jid);
1085        if ($to eq $cJid->GetJID('base') ||
1086            $to eq $cJid->GetJID('full')) {
1087            my $reply = $p->Reply(type=>"unsubscribed");
1088            $conn->getConnectionFromJID($jid)->Send($reply);
1089            return;
1090        }
1091    }
1092}
1093
1094sub process_presence_subscribed {
1095    my ( $sid, $p ) = @_;
1096    queue_admin_msg("ignoring:".$p->GetXML());
1097    # RFC 3921 says we should respond to this with a "subscribe"
1098    # but this causes a flood of sub/sub'd presence packets with
1099    # some servers, so we won't. We may want to detect this condition
1100    # later, and have per-server settings.
1101    return;
1102}
1103
1104sub process_presence_unsubscribed {
1105    my ( $sid, $p ) = @_;
1106    queue_admin_msg("ignoring:".$p->GetXML());
1107    # RFC 3921 says we should respond to this with a "subscribe"
1108    # but this causes a flood of unsub/unsub'd presence packets with
1109    # some servers, so we won't. We may want to detect this condition
1110    # later, and have per-server settings.
1111    return;
1112}
1113
1114sub process_presence_error {
1115    my ( $sid, $p ) = @_;
1116    my $code = $p->GetErrorCode();
1117    my $error = $p->GetError();
1118    BarnOwl::error("Jabber: $code $error");
1119}
1120
1121
1122### Helper functions
1123
1124sub j2hash {
1125    my $j   = shift;
1126    my %initProps = %{ shift() };
1127
1128    my $dir = 'none';
1129    my %props = ( type => 'jabber' );
1130
1131    foreach my $k (keys %initProps) {
1132        $dir = $initProps{$k} if ($k eq 'direction');
1133        $props{$k} = $initProps{$k};
1134    }
1135
1136    my $jtype = $props{jtype} = $j->GetType();
1137    my $from = $j->GetFrom('jid');
1138    my $to   = $j->GetTo('jid');
1139
1140    $props{from} = $from->GetJID('full');
1141    $props{to}   = $to->GetJID('full');
1142
1143    $props{recipient}  = $to->GetJID('base');
1144    $props{sender}     = $from->GetJID('base');
1145    $props{subject}    = $j->GetSubject() if ( $j->DefinedSubject() );
1146    $props{thread}     = $j->GetThread() if ( $j->DefinedThread() );
1147    $props{body}       = $j->GetBody() if ( $j->DefinedBody() );
1148    $props{error}      = $j->GetError() if ( $j->DefinedError() );
1149    $props{error_code} = $j->GetErrorCode() if ( $j->DefinedErrorCode() );
1150    $props{xml}        = $j->GetXML();
1151
1152    if ( $jtype eq 'chat' ) {
1153        $props{replycmd} =
1154          "jwrite " . ( ( $dir eq 'in' ) ? $props{from} : $props{to} );
1155        $props{replycmd} .=
1156          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1157        $props{private} = 1;
1158    }
1159    elsif ( $jtype eq 'groupchat' ) {
1160        my $nick = $props{nick} = $from->GetResource();
1161        my $room = $props{room} = $from->GetJID('base');
1162        $props{replycmd} = "jwrite $room";
1163        $props{replycmd} .=
1164          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1165
1166        $props{sender} = $nick || $room;
1167        $props{recipient} = $room;
1168
1169        if ( $props{subject} && !$props{body} ) {
1170            $props{body} =
1171              '[' . $nick . " has set the topic to: " . $props{subject} . "]";
1172        }
1173    }
1174    elsif ( $jtype eq 'normal' ) {
1175        $props{replycmd}  = undef;
1176        $props{private} = 1;
1177    }
1178    elsif ( $jtype eq 'headline' ) {
1179        $props{replycmd} = undef;
1180    }
1181    elsif ( $jtype eq 'error' ) {
1182        $props{replycmd} = undef;
1183        $props{body}     = "Error "
1184          . $props{error_code}
1185          . " sending to "
1186          . $props{from} . "\n"
1187          . $props{error};
1188    }
1189
1190    $props{replysendercmd} = $props{replycmd};
1191    return %props;
1192}
1193
1194sub j2o {
1195    return BarnOwl::Message->new( j2hash(@_) );
1196}
1197
1198sub queue_admin_msg {
1199    my $err = shift;
1200    my $m   = BarnOwl::Message->new(
1201        type      => 'admin',
1202        direction => 'none',
1203        body      => $err
1204    );
1205    BarnOwl::queue_message($m);
1206}
1207
1208sub boldify($) {
1209    my $str = shift;
1210
1211    return '@b(' . $str . ')' if ( $str !~ /\)/ );
1212    return '@b<' . $str . '>' if ( $str !~ /\>/ );
1213    return '@b{' . $str . '}' if ( $str !~ /\}/ );
1214    return '@b[' . $str . ']' if ( $str !~ /\]/ );
1215
1216    my $txt = "$str";
1217    $txt =~ s{[)]}{)\@b[)]\@b(}g;
1218    return '@b(' . $txt . ')';
1219}
1220
1221sub getServerFromJID {
1222    my $jid = shift;
1223    my $res = new Net::DNS::Resolver;
1224    my $packet =
1225      $res->search( '_xmpp-client._tcp.' . $jid->GetServer(), 'srv' );
1226
1227    if ($packet)    # Got srv record.
1228    {
1229        my @answer = $packet->answer;
1230        return $answer[0]{target}, $answer[0]{port};
1231    }
1232
1233    return $jid->GetServer(), 5222;
1234}
1235
1236sub defaultJID {
1237    return ( $conn->getJids() )[0] if ( $conn->connected() == 1 );
1238    return;
1239}
1240
1241sub baseJID {
1242    my $givenJidStr = shift;
1243    my $givenJid    = new Net::XMPP::JID;
1244    $givenJid->SetJID($givenJidStr);
1245    return $givenJid->GetJID('base');
1246}
1247
1248sub resolveConnectedJID {
1249    my $givenJidStr = shift;
1250    my $givenJid    = new Net::XMPP::JID;
1251    $givenJid->SetJID($givenJidStr);
1252
1253    # Account fully specified.
1254    if ( $givenJid->GetResource() ) {
1255        # Specified account exists
1256        return $givenJidStr if ($conn->jidExists($givenJidStr) );
1257        die("Invalid account: $givenJidStr");
1258    }
1259
1260    # Disambiguate.
1261    else {
1262        my $matchingJid = "";
1263        my $errStr =
1264          "Ambiguous account reference. Please specify a resource.\n";
1265        my $ambiguous = 0;
1266
1267        foreach my $jid ( $conn->getJids() ) {
1268            my $cJid = new Net::XMPP::JID;
1269            $cJid->SetJID($jid);
1270            if ( $givenJidStr eq $cJid->GetJID('base') ) {
1271                $ambiguous = 1 if ( $matchingJid ne "" );
1272                $matchingJid = $jid;
1273                $errStr .= "\t$jid\n";
1274            }
1275        }
1276
1277        # Need further disambiguation.
1278        if ($ambiguous) {
1279            die($errStr);
1280        }
1281
1282        # Not one of ours.
1283        elsif ( $matchingJid eq "" ) {
1284            die("Invalid account: $givenJidStr");
1285        }
1286
1287        # It's this one.
1288        else {
1289            return $matchingJid;
1290        }
1291    }
1292    return "";
1293}
1294
1295sub resolveDestJID {
1296    my ($to, $from) = @_;
1297    return $to if $to =~ /@/;
1298    my $jid = Net::Jabber::JID->new($to);
1299
1300    my $roster = $conn->getRosterFromJID($from);
1301    my @jids = $roster->jids('all');
1302    for my $j (@jids) {
1303        if($roster->query($j, 'name') eq $to) {
1304            return $j->GetJID('full');
1305        }
1306    }
1307
1308    return undef;
1309}
1310
1311sub resolveType {
1312    my $to = shift;
1313    my $from = shift;
1314    my @mucs = $conn->getConnectionFromJID($from)->MUCs;
1315    if(grep {$_->BaseJID eq $to } @mucs) {
1316        return 'groupchat';
1317    } else {
1318        return 'chat';
1319    }
1320}
1321
1322sub guess_jwrite {
1323    # Heuristically guess what jids a jwrite was meant to be going to/from
1324    my ($from, $to) = (@_);
1325    my ($from_jid, $to_jid);
1326    if($from) {
1327        $from_jid = resolveConnectedJID($from);
1328        die("Unable to resolve account $from") unless $from_jid;
1329        $to_jid = resolveDestJID($to, $from_jid);
1330    } elsif($to =~ /@/) {
1331        $to_jid = $to;
1332        $from_jid = defaultJID();
1333        die("You must specify an account with -a") unless $from_jid;
1334    } else {
1335        for my $f ($conn->getJids) {
1336            $to_jid = resolveDestJID($to, $f);
1337            if(defined($to_jid)) {
1338                $from_jid = $f;
1339            }
1340        }
1341        die("Unable to resolve JID $to") unless $to_jid;
1342    }
1343
1344    my $type = resolveType($to_jid, $from_jid);
1345    return ($from_jid, $to_jid, $type);
1346}
1347
1348#####################################################################
1349#####################################################################
1350
1351package BarnOwl::Message::Jabber;
1352
1353our @ISA = qw( BarnOwl::Message );
1354
1355sub jtype { shift->{jtype} };
1356sub from { shift->{from} };
1357sub to { shift->{to} };
1358sub room { shift->{room} };
1359
1360sub smartfilter {
1361    my $self = shift;
1362    my $inst = shift;
1363
1364    my ($filter, $ftext);
1365
1366    if($self->jtype eq 'chat') {
1367        my $user;
1368        if($self->direction eq 'in') {
1369            $user = $self->from;
1370        } else {
1371            $user = $self->to;
1372        }
1373        $user = Net::Jabber::JID->new($user)->GetJID($inst ? 'full' : 'base');
1374        $filter = "jabber-user-$user";
1375        $ftext = qq{type ^jabber\$ and ( ( direction ^in\$ and from ^$user ) } .
1376                 qq{or ( direction ^out\$ and to ^$user ) ) };
1377        BarnOwl::filter("$filter $ftext");
1378        return $filter;
1379    } elsif ($self->jtype eq 'groupchat') {
1380        my $room = $self->room;
1381        $filter = "jabber-room-$room";
1382        $ftext = qq{type ^jabber\$ and room ^$room\$};
1383        BarnOwl::filter("$filter $ftext");
1384        return $filter;
1385    }
1386}
1387
13881;
Note: See TracBrowser for help on using the repository browser.