source: perl/modules/jabber.pl @ 140d02a

barnowl_perlaimdebianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 140d02a was 140d02a, checked in by Nelson Elhage <nelhage@mit.edu>, 17 years ago
Oops -- fix to make this actually run. No longer create jabber.log if debug mode is off
  • Property mode set to 100644
File size: 31.8 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(owl::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 ( eval { \&owl::queue_message } ) {
130        register_owl_commands();
131        push @::onMainLoop,     sub { owl_jabber::onMainLoop(@_) };
132        push @::onGetBuddyList, sub { owl_jabber::onGetBuddyList(@_) };
133    }
134    else {
135        # Our owl doesn't support queue_message. Unfortunately, this
136        # means it probably *also* doesn't support owl::error. So just
137        # give up silently.
138    }
139}
140
141push @::onStartSubs, sub { owl_jabber::onStart(@_) };
142
143sub onMainLoop {
144    return if ( !$conn->connected() );
145
146    foreach my $jid ( $conn->getJids() ) {
147        my $client = $conn->getConnectionFromJidStr($jid);
148
149        my $status = $client->Process(0);
150        if ( !defined($status) ) {
151            owl::error("Jabber account $jid disconnected!");
152            do_logout($jid);
153        }
154        if ($::shutdown) {
155            do_logout($jid);
156            return;
157        }
158    }
159}
160
161sub blist_listBuddy {
162    my $roster = shift;
163    my $buddy  = shift;
164    my $blistStr .= "    ";
165    my %jq  = $roster->query($buddy);
166    my $res = $roster->resource($buddy);
167
168    $blistStr .= $jq{name} ? $jq{name} . "\t(" .$buddy->GetJID() . ')' : $buddy->GetJID();
169
170    if ($res) {
171        my %rq = $roster->resourceQuery( $buddy, $res );
172        $blistStr .= " [" . ( $rq{show} ? $rq{show} : 'online' ) . "]";
173        $blistStr .= " " . $rq{status} if $rq{status};
174        $blistStr = boldify($blistStr);
175    }
176    else {
177        if ($jq{ask}) {
178            $blistStr .= " [pending]";
179        }
180        elsif ($jq{subscription} eq 'none' || $jq{subscription} eq 'from') {
181            $blistStr .= " [not subscribed]";
182        }
183        else {
184            $blistStr .= " [offline]";
185        }
186    }
187    return $blistStr . "\n";
188}
189
190sub getSingleBuddyList {
191    my $jid = shift;
192    $jid = resolveJID($jid);
193    return "" unless $jid;
194    my $blist = "";
195    my $roster = $conn->getRosterFromJidStr($jid);
196    if ($roster) {
197        $blist .= "\n" . boldify("Jabber Roster for $jid\n");
198
199        foreach my $group ( $roster->groups() ) {
200            $blist .= "  Group: $group\n";
201            foreach my $buddy ( $roster->jids( 'group', $group ) ) {
202                $blist .= blist_listBuddy( $roster, $buddy );
203            }
204        }
205
206        my @unsorted = $roster->jids('nogroup');
207        if (@unsorted) {
208            $blist .= "  [unsorted]\n";
209            foreach my $buddy (@unsorted) {
210                $blist .= blist_listBuddy( $roster, $buddy );
211            }
212        }
213    }
214    return $blist;
215}
216
217sub onGetBuddyList {
218    my $blist = "";
219    foreach my $jid ($conn->getJids()) {
220        $blist .= getSingleBuddyList($jid);
221    }
222    return $blist;
223}
224
225################################################################################
226### Owl Commands
227sub register_owl_commands() {
228    owl::new_command(
229        jabberlogin => \&cmd_login,
230        { summary => "Log into jabber", }
231    );
232    owl::new_command(
233        jabberlogout => \&cmd_logout,
234        { summary => "Log out of jabber" }
235    );
236    owl::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    owl::new_command(
244        jlist => \&cmd_jlist,
245        {
246            summary => "Show your Jabber roster.",
247            usage   => "jlist"
248        }
249    );
250    owl::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",
265            usage => "jmuc {command} {args}"
266        }
267    );
268    owl::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        owl::error("usage: $cmd {jid}");
291        return;
292    }
293
294    if ( $conn->jidExists($jidStr) ) {
295        owl::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        owl::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        $client->SetMessageCallBacks(
331            chat      => sub { owl_jabber::process_incoming_chat_message(@_) },
332            error     => sub { owl_jabber::process_incoming_error_message(@_) },
333            groupchat => sub { owl_jabber::process_incoming_groupchat_message(@_) },
334            headline  => sub { owl_jabber::process_incoming_headline_message(@_) },
335            normal    => sub { owl_jabber::process_incoming_normal_message(@_) }
336        );
337        $client->SetPresenceCallBacks(
338#            available    => sub { owl_jabber::process_presence_available(@_) },
339#            unavailable  => sub { owl_jabber::process_presence_available(@_) },
340            subscribe    => sub { owl_jabber::process_presence_subscribe(@_) },
341            subscribed   => sub { owl_jabber::process_presence_subscribed(@_) },
342            unsubscribe  => sub { owl_jabber::process_presence_unsubscribe(@_) },
343            unsubscribed => sub { owl_jabber::process_presence_unsubscribed(@_) });
344
345        my $status = $client->Connect( %{ $vars{jlogin_connhash} } );
346        if ( !$status ) {
347            $conn->removeConnection($jidStr);
348            owl::error("We failed to connect");
349        }
350        else {
351            my @result = $client->AuthSend( %{ $vars{jlogin_authhash} } );
352
353            if ( $result[0] ne 'ok' ) {
354            if ( !$vars{jlogin_havepass} && $result[0] == 401 ) {
355                $vars{jlogin_havepass} = 1;
356                $conn->removeConnection($jidStr);
357                owl::start_password( "Password for $jidStr: ", \&do_login );
358                return "";
359            }
360            $conn->removeConnection($jidStr);
361            owl::error(
362                "Error in connect: " . join( " ", @result ) );
363        }
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    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        owl::error("You are not logged in to Jabber.");
423        return;
424    }
425    owl::popless_ztext( onGetBuddyList() );
426}
427
428sub cmd_jwrite {
429    if ( !$conn->connected() ) {
430        owl::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        owl::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            owl::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    owl::message(
487"Type your message below.  End with a dot on a line by itself.  ^C will quit."
488    );
489    owl::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        owl::error("jmuc: Unknown command: $cmd");
511        return;
512    }
513
514    {
515        local @ARGV = @_;
516        my $jid;
517        my $muc;
518        my $m = owl::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            owl::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        owl::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            owl::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' ) {
812
813        #XXX TODO: Check for displayoutgoing.
814        owl::queue_message($m);
815    }
816
817    if ($vars{jwrite}{sid} && $conn->sidExists( $vars{jwrite}{sid} )) {
818        $conn->getConnectionFromSid($vars{jwrite}{sid})->Send($j);
819    }
820    else {
821        $conn->getConnectionFromJidStr($vars{jwrite}{from})->Send($j);
822    }
823
824    delete $vars{jwrite};
825    owl::message("");   # Kludge to make the ``type your message...'' message go away
826}
827
828### XMPP Callbacks
829
830sub process_incoming_chat_message {
831    my ( $sid, $j ) = @_;
832    owl::queue_message( j2o( $j, { direction => 'in',
833                                   sid => $sid } ) );
834}
835
836sub process_incoming_error_message {
837    my ( $sid, $j ) = @_;
838    my %jhash = j2hash( $j, { direction => 'in',
839                              sid => $sid } );
840    $jhash{type} = 'admin';
841    owl::queue_message( owl::Message->new(%jhash) );
842}
843
844sub process_incoming_groupchat_message {
845    my ( $sid, $j ) = @_;
846
847    # HACK IN PROGRESS (ignoring delayed messages)
848    return if ( $j->DefinedX('jabber:x:delay') && $j->GetX('jabber:x:delay') );
849    owl::queue_message( j2o( $j, { direction => 'in',
850                                   sid => $sid } ) );
851}
852
853sub process_incoming_headline_message {
854    my ( $sid, $j ) = @_;
855    owl::queue_message( j2o( $j, { direction => 'in',
856                                   sid => $sid } ) );
857}
858
859sub process_incoming_normal_message {
860    my ( $sid, $j ) = @_;
861    my %jhash = j2hash( $j, { direction => 'in',
862                              sid => $sid } );
863
864    # XXX TODO: handle things such as MUC invites here.
865
866    #    if ($j->HasX('http://jabber.org/protocol/muc#user'))
867    #    {
868    #   my $x = $j->GetX('http://jabber.org/protocol/muc#user');
869    #   if ($x->HasChild('invite'))
870    #   {
871    #       $props
872    #   }
873    #    }
874    #
875    owl::queue_message( owl::Message->new(%jhash) );
876}
877
878sub process_muc_presence {
879    my ( $sid, $p ) = @_;
880    return unless ( $p->HasX('http://jabber.org/protocol/muc#user') );
881}
882
883
884sub process_presence_available {
885    my ( $sid, $p ) = @_;
886    my $from = $p->GetFrom();
887    my $to = $p->GetTo();
888    my $type = $p->GetType();
889    my %props = (
890        to => $to,
891        from => $from,
892        recipient => $to,
893        sender => $from,
894        type => 'jabber',
895        jtype => $p->GetType(),
896        status => $p->GetStatus(),
897        show => $p->GetShow(),
898        xml => $p->GetXML(),
899        direction => 'in');
900
901    if ($type eq '' || $type eq 'available') {
902        $props{body} = "$from is now online. ";
903        $props{loginout} = 'login';
904    }
905    else {
906        $props{body} = "$from is now offline. ";
907        $props{loginout} = 'logout';
908    }
909    $props{replysendercmd} = $props{replycmd} = "jwrite $from -i $sid";
910    owl::queue_message(owl::Message->new(%props));
911}
912
913sub process_presence_subscribe {
914    my ( $sid, $p ) = @_;
915    my $from = $p->GetFrom();
916    my $to = $p->GetTo();
917    my %props = (
918        to => $to,
919        from => $from,
920        xml => $p->GetXML(),
921        type => 'admin',
922        adminheader => 'Jabber presence: subscribe',
923        direction => 'in');
924
925    $props{body} = "The user ($from) wants to subscribe to your ($to) presence.\nReply (r) will authorize, reply-sender (R) will deny.";
926    $props{replycmd} = "jroster auth $from -a $to";
927    $props{replysendercmd} = "jroster deauth $from -a $to";
928    owl::queue_message(owl::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    owl::queue_message(owl::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
979
980### Helper functions
981
982sub j2hash {
983    my $j   = shift;
984    my %initProps = %{ shift() };
985
986    my $dir = 'none';
987    my %props = ( type => 'jabber' );
988
989    foreach my $k (keys %initProps) {
990        $dir = $initProps{$k} if ($k eq 'direction');
991        $props{$k} = $initProps{$k};
992    }
993
994    my $jtype = $props{jtype} = $j->GetType();
995    my $from = $j->GetFrom('jid');
996    my $to   = $j->GetTo('jid');
997
998    $props{from} = $from->GetJID('full');
999    $props{to}   = $to->GetJID('full');
1000
1001    $props{recipient}  = $to->GetJID('base');
1002    $props{sender}     = $from->GetJID('base');
1003    $props{subject}    = $j->GetSubject() if ( $j->DefinedSubject() );
1004    $props{thread}     = $j->GetThread() if ( $j->DefinedThread() );
1005    $props{body}       = $j->GetBody() if ( $j->DefinedBody() );
1006    $props{error}      = $j->GetError() if ( $j->DefinedError() );
1007    $props{error_code} = $j->GetErrorCode() if ( $j->DefinedErrorCode() );
1008    $props{xml}        = $j->GetXML();
1009
1010    if ( $jtype eq 'chat' ) {
1011        $props{replycmd} =
1012          "jwrite " . ( ( $dir eq 'in' ) ? $props{from} : $props{to} );
1013        $props{replycmd} .=
1014          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1015        $props{isprivate} = 1;
1016    }
1017    elsif ( $jtype eq 'groupchat' ) {
1018        my $nick = $props{nick} = $from->GetResource();
1019        my $room = $props{room} = $from->GetJID('base');
1020        $props{replycmd} = "jwrite -g $room";
1021        $props{replycmd} .=
1022          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1023
1024        $props{sender} = $nick || $room;
1025        $props{recipient} = $room;
1026
1027        if ( $props{subject} && !$props{body} ) {
1028            $props{body} =
1029              '[' . $nick . " has set the topic to: " . $props{subject} . "]";
1030        }
1031    }
1032    elsif ( $jtype eq 'normal' ) {
1033        $props{replycmd}  = undef;
1034        $props{isprivate} = 1;
1035    }
1036    elsif ( $jtype eq 'headline' ) {
1037        $props{replycmd} = undef;
1038    }
1039    elsif ( $jtype eq 'error' ) {
1040        $props{replycmd} = undef;
1041        $props{body}     = "Error "
1042          . $props{error_code}
1043          . " sending to "
1044          . $props{from} . "\n"
1045          . $props{error};
1046    }
1047
1048    $props{replysendercmd} = $props{replycmd};
1049    return %props;
1050}
1051
1052sub j2o {
1053    return owl::Message->new( j2hash(@_) );
1054}
1055
1056sub queue_admin_msg {
1057    my $err = shift;
1058    my $m   = owl::Message->new(
1059        type      => 'admin',
1060        direction => 'none',
1061        body      => $err
1062    );
1063    owl::queue_message($m);
1064}
1065
1066sub boldify($) {
1067    my $str = shift;
1068
1069    return '@b(' . $str . ')' if ( $str !~ /\)/ );
1070    return '@b<' . $str . '>' if ( $str !~ /\>/ );
1071    return '@b{' . $str . '}' if ( $str !~ /\}/ );
1072    return '@b[' . $str . ']' if ( $str !~ /\]/ );
1073
1074    my $txt = "\@b($str";
1075    $txt =~ s/\)/\)\@b\[\)\]\@b\(/g;
1076    return $txt . ')';
1077}
1078
1079sub getServerFromJID {
1080    my $jid = shift;
1081    my $res = new Net::DNS::Resolver;
1082    my $packet =
1083      $res->search( '_xmpp-client._tcp.' . $jid->GetServer(), 'srv' );
1084
1085    if ($packet)    # Got srv record.
1086    {
1087        my @answer = $packet->answer;
1088        return $answer[0]{target}, $answer[0]{port};
1089    }
1090
1091    return $jid->GetServer(), 5222;
1092}
1093
1094sub defaultJID {
1095    return ( $conn->getJids() )[0] if ( $conn->connected() == 1 );
1096    return;
1097}
1098
1099sub baseJID {
1100    my $givenJidStr = shift;
1101    my $givenJid    = new Net::XMPP::JID;
1102    $givenJid->SetJID($givenJidStr);
1103    return $givenJid->GetJID('base');
1104}
1105
1106sub resolveJID {
1107    my $givenJidStr = shift;
1108    my $givenJid    = new Net::XMPP::JID;
1109    $givenJid->SetJID($givenJidStr);
1110
1111    # Account fully specified.
1112    if ( $givenJid->GetResource() ) {
1113        # Specified account exists
1114        return $givenJidStr if ($conn->jidExists($givenJidStr) );
1115        owl::error("Invalid account: $givenJidStr");
1116    }
1117
1118    # Disambiguate.
1119    else {
1120        my $matchingJid = "";
1121        my $errStr =
1122          "Ambiguous account reference. Please specify a resource.\n";
1123        my $ambiguous = 0;
1124
1125        foreach my $jid ( $conn->getJids() ) {
1126            my $cJid = new Net::XMPP::JID;
1127            $cJid->SetJID($jid);
1128            if ( $givenJidStr eq $cJid->GetJID('base') ) {
1129                $ambiguous = 1 if ( $matchingJid ne "" );
1130                $matchingJid = $jid;
1131                $errStr .= "\t$jid\n";
1132            }
1133        }
1134
1135        # Need further disambiguation.
1136        if ($ambiguous) {
1137            queue_admin_msg($errStr);
1138        }
1139
1140        # Not one of ours.
1141        elsif ( $matchingJid eq "" ) {
1142            owl::error("Invalid account: $givenJidStr");
1143        }
1144
1145        # It's this one.
1146        else {
1147            return $matchingJid;
1148        }
1149    }
1150    return "";
1151}
1152
11531;
Note: See TracBrowser for help on using the repository browser.