source: perl/modules/jabber.pl @ 60986b2

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