source: perl/modules/jabber.pl @ 12e5f17

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