source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 94b4ecb5

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