source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 13a3c1db

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