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

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