source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 209ea94

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