source: perl/modules/jabber.pl @ f62550d

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