Import Upstream version 1.22
[cascardo/sendxmpp.git] / sendxmpp
1 #!/usr/bin/perl -w
2
3 eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
4 if 0; # not running under some shell
5
6 #
7 # script to send message using xmpp (aka jabber),
8 # somewhat resembling mail(1)
9 #
10 # Author:     Dirk-Jan C. Binnema <djcb AT djcbsoftware.nl>
11 # Maintainer: Lubomir Host 'rajo' <rajo AT platon.sk>
12 # Copyright (c) 2004 - 2005 Dirk-Jan C. Binnema
13 # Copyright (c) 2006 - 2009 Lubomir Host 'rajo'
14 #
15 # Homepage: http://sendxmpp.platon.sk
16 #
17 # Released under the terms of the GNU General Public License v2
18 #
19 # $Platon: sendxmpp/sendxmpp,v 1.22 2010-10-03 19:36:35 rajo Exp $
20 # $Id: $
21
22 use Authen::SASL qw(Perl); # authentication broken if Authen::SASL::Cyrus module installed
23 use Net::XMPP;
24 use Getopt::Long;
25 use strict;
26
27 use open ':utf8';
28 use open ':std';
29
30 # subroutines decls
31 sub xmpp_login($$$$$$$$$);
32 sub xmpp_send ($$$$);
33 sub xmpp_send_raw_xml($$);
34 sub xmpp_send_message($$$$$$);
35 sub xmpp_send_chatroom_message($$$$$);
36 sub xmpp_logout($);
37 sub xmpp_check_result;
38 sub parse_cmdline();
39 sub error_exit;
40 sub debug_print;
41 sub read_config_file($);
42 sub push_hash($$);
43 sub terminate();
44 sub main();
45
46 my # MakeMaker
47 $VERSION        = [ q$Revision: 1.22 $ =~ m/(\S+)\s*$/g ]->[0];
48 my $RESOURCE = 'sendxmpp';
49 my $VERBOSE  = 0;
50 my $DEBUG    = 0;
51 # http://tools.ietf.org/html/rfc3921#section-2  section 2.1.1 - Types of Message
52 my @suppported_message_types    = qw( chat error groupchat headline );
53 my $message_type                                = 'chat'; # default message type
54
55 # start!
56 &main;
57
58 #
59 # main: main routine
60 #
61 sub main () {
62
63     my $cmdline = parse_cmdline();
64
65     $| = 1; # no output buffering
66
67     $DEBUG   = 1 if ($$cmdline{'debug'});
68     $VERBOSE = 1 if ($$cmdline{'verbose'});
69
70     my $config = read_config_file ($$cmdline{'file'})
71         unless ($$cmdline{'jserver'} && $$cmdline{'username'} && $$cmdline{'password'});
72
73     # login to xmpp
74     my $cnx =  xmpp_login ($$cmdline{'jserver'}  || $$config{'jserver'},
75                            $$cmdline{'port'}     || $$config{'port'} || ($$cmdline{'ssl'} ? 5223 : 5222),
76                            $$cmdline{'username'} || $$config{'username'},
77                            $$cmdline{'password'} || $$config{'password'},
78                            $$cmdline{'component'}|| $$config{'component'},
79                            $$cmdline{'resource'},
80                            $$cmdline{'tls'},
81                            $$cmdline{'ssl'},
82                            $$cmdline{'debug'})
83       or error_exit("cannot login: $!");
84
85
86     # read message from STDIN or or from -m/--message parameter
87     if (!$$cmdline{interactive}) {
88
89         # the non-interactive case
90         my $txt;
91         my $message = $$cmdline{'message'};
92         if ($message) {
93             open (MSG, "<$message")
94               or error_exit ("cannot open message file '$message': $!");
95             while (<MSG>) { $txt .= $_ };
96             close(MSG);
97         }
98         else {
99             $txt .= $_ while (<STDIN>);
100         }
101
102         xmpp_send ($cnx,$cmdline,$config,$txt);
103
104     } else {
105         # the interactive case, read stdin line by line
106
107         # deal with TERM
108         $main::CNX = $cnx;
109         $SIG{INT}=\&terminate;
110
111         # line by line...
112         while (<STDIN>) {
113             chomp;
114             xmpp_send ($cnx,$cmdline,$config,$_);
115         }
116     }
117
118     xmpp_logout($cnx);
119     exit 0;
120 }
121
122
123
124 #
125 # read_config_file: read the configuration file
126 # input: filename
127 # output: hash with 'user', 'jserver' and 'password' keys
128 #
129 sub read_config_file ($) {
130
131     # check permissions
132     my $cfg_file = shift;
133     error_exit ("cannot read $cfg_file: $!")
134         unless (-r $cfg_file);
135     my $owner  = (stat _ )[4];
136     error_exit ("you must own $cfg_file")
137       unless ($owner == $>);
138     my $mode = (stat _ )[2] & 07777;
139     error_exit ("$cfg_file must not be accessible by others")
140       if ($mode & 0077);
141
142     open (CFG,"<$cfg_file")
143       or error_exit("cannot open $cfg_file for reading: $!");
144
145     my %config;
146     my $line = 0;
147         while (<CFG>) {
148
149                 ++$line;
150
151                 next if (/^\s*$/);     # ignore empty lines
152                 next if (/^\s*\#.*/);  # ignore comment lines
153
154                 #s/\#.*$//; # ignore comments in lines
155
156                 # Hugo van der Kooij <hvdkooij AT vanderkooij.org> has account with '#' as username
157                 if (/([\.\w_#-]+)@([-\.\w:;]+)\s+(\S+)\s*(\S+)?$/) {
158                         %config = (
159                                 'username'      => $1,
160                                 'jserver'       => $2,
161                                 'port'          => 0,
162                                 'password'      => $3,
163                                 'component'     => $4,
164                         );
165
166                 }
167                 else {
168                         close CFG;
169                         error_exit ("syntax error in line $line of $cfg_file");
170                 }
171
172                 # account with weird port number
173                 if ($config{'jserver'}  =~ /(.*):(\d+)/) {
174                         $config{'jserver'}      = $1;
175                         $config{'port'}         = $2;
176                 }
177
178                 # account with specific connection host
179                 if ($config{'jserver'}  =~ /(.*);([-\.\w]+)/) {
180                         $config{'jserver'}      = $2;
181                         $config{'username'}     .= "\@$1" unless $config{'component'};
182                 }
183         }
184
185     close CFG;
186
187     error_exit ("no correct config found in $cfg_file")
188       unless (scalar(%config));
189
190     if ($DEBUG || $VERBOSE) {
191         while (my ($key,$val) = each %config) {
192             debug_print ("config: '$key' => '$val'");
193         }
194     }
195
196     return \%config;
197 }
198
199
200
201 #
202 # parse_cmdline: parse commandline options
203 # output: hash with commandline options
204 #
205 sub parse_cmdline () {
206
207     usage() unless (scalar(@ARGV));
208
209         my ($subject,$file,$resource,$jserver,$port,$username,$password,$component,
210         $message, $chatroom, $headline, $debug, $tls, $ssl, $interactive, $help, $raw, $verbose);
211     my $res = GetOptions ('subject|s=s'    => \$subject,
212                           'file|f=s'       => \$file,
213                           'resource|r=s'   => \$resource,
214                           'jserver|j=s'    => \$jserver,
215                           'component|o=s'  => \$component,
216                           'username|u=s'   => \$username,
217                           'password|p=s'   => \$password,
218                           'message|m=s'    => \$message,
219                           'headline|l'     => \$headline,
220                           'message-type=s' => \$message_type,
221                           'chatroom|c'     => \$chatroom,
222                           'tls|t'          => \$tls,
223                           'ssl|e'          => \$ssl,
224                           'interactive|i'  => \$interactive,
225                           'help|usage|h'   => \$help,
226                           'debug|d'        => \$debug,
227                           'raw|w'          => \$raw,
228                           'verbose|v'      => \$verbose);
229     usage () if ($help);
230
231         my @rcpt = @ARGV;
232
233         if (defined($raw) && scalar(@rcpt) > 0) {
234                 error_exit("You must give a recipient or --raw (but not both)");
235         }
236         if ($raw && $subject) {
237                 error_exit("You cannot specify a subject in raw XML mode");
238         }
239         if ($raw && $chatroom) {
240                 error_exit("The chatroom option is pointless in raw XML mode");
241         }
242
243         if ($message && $interactive) {
244                 error_exit("Cannot have both -m (--message) and -i (--interactive)");
245         }
246
247         if (scalar(grep { $message_type eq $_ } @suppported_message_types) == 0) {
248                 error_exit("Unsupported message type '$message_type'");
249         }
250         
251         if ($ssl && $tls) {
252             error_exit("Connect securely wether using -e (--ssl) or -t (--tls)");
253         }
254
255         if ($headline) {
256                 # --headline withouth --message-type
257                 if ($message_type eq 'message') {
258                         $message_type = 'headline'
259                 }
260                 else {
261                         error_exit("Options --headline and --message-type are mutually exclusive");
262                 }
263         }
264
265         if ($jserver && $jserver =~ /(.*):(\d+)/) {
266                 $jserver = $1;
267                 $port    = $2;
268         }
269
270     my %dict = ('subject'     => ($subject  or ''),
271                 'message'       => ($message or ''),
272                 'resource'    => ($resource or $RESOURCE),
273                 'jserver'     => ($jserver or ''),
274                 'component'   => ($component or ''),
275                 'port'        => ($port or 0),
276                 'username'    => ($username or ''),
277                 'password'    => ($password or ''),
278                 'chatroom'    => ($chatroom or 0),
279                 'message-type'    => $message_type,
280                 'interactive' => ($interactive or 0),
281                 'tls'         => ($tls or 0),
282                 'ssl'         => ($ssl or 0),
283                 'debug'       => ($debug or 0),
284                 'verbose'     => ($verbose or 0),
285                 'raw'         => ($raw or 0),
286                 'file'        => ($file or ($ENV{'HOME'}.'/.sendxmpprc')),
287                 'recipient'   => \@rcpt);
288
289    if ($DEBUG || $VERBOSE) {
290        while (my ($key,$val) = each %dict) {
291            debug_print ("cmdline: '$key' => '$val'");
292        }
293    }
294
295    return \%dict;
296 }
297
298
299 #
300 # xmpp_login: login to the xmpp (jabber) server
301 # input: hostname,port,username,password,resource,tls,ssl,debug
302 # output: an XMPP connection object
303 #
304 sub xmpp_login ($$$$$$$$$) {
305
306     my ($host, $port, $user, $pw, $comp, $res, $tls, $ssl, $debug) = @_;
307     my $cnx = new Net::XMPP::Client(debuglevel=>($debug?2:0));
308     error_exit "could not create XMPP client object: $!"
309         unless ($cnx);
310
311     my @res;
312         my $arghash = {
313                 hostname                => $host,
314                 port            => $port,
315                 tls                             => $tls,
316                 ssl             => $ssl,
317                 connectiontype  => 'tcpip',
318                 componentname   => $comp
319         };
320
321         delete $arghash->{port} unless $port; 
322         if ($arghash->{port}) {
323                 @res = $cnx->Connect(%$arghash);
324                 error_exit ("Could not connect to '$host' on port $port: $@") unless @res;
325         } else {
326                 @res = $cnx->Connect(%$arghash);
327                 error_exit ("Could not connect to server '$host': $@") unless @res;
328         }
329
330     xmpp_check_result("Connect",\@res,$cnx);
331
332         if ($comp) {
333                 my $sid = $cnx->{SESSION}->{id};
334                 $cnx->{STREAM}->{SIDS}->{$sid}->{hostname} = $comp
335         }
336
337     @res = $cnx->AuthSend(#'hostname' => $host,
338                           'username' => $user,
339                           'password' => $pw,
340                           'resource' => $res);
341     xmpp_check_result('AuthSend',\@res,$cnx);
342
343     return $cnx;
344 }
345
346
347
348
349 #
350 # xmmp_send: send the message, determine from cmdline
351 # whether it's to individual or chatroom
352 #
353 sub xmpp_send ($$$$) {
354
355         my ($cnx, $cmdline, $config, $txt) = @_;
356
357         unless ($$cmdline{'chatroom'}) {
358         unless ($$cmdline{'raw'}) {
359                         map {
360                                 xmpp_send_message ($cnx,
361                                         $_, #$$cmdline{'recipient'},
362                                         $$cmdline{'component'} || $$config{'component'},
363                                         $$cmdline{'subject'},
364                                         $$cmdline{'message-type'},
365                                         $txt)
366                         } @{$$cmdline{'recipient'}};
367         }
368                 else {
369                         xmpp_send_raw_xml ($cnx, $txt);
370         }
371         }
372         else {
373                 map {
374                         xmpp_send_chatroom_message ($cnx,
375                                 $$cmdline{'resource'},
376                                 $$cmdline{'subject'},
377                                 $_, # $$cmdline{'recipient'},
378                                 $txt)
379                 } @{$$cmdline{'recipient'}};
380         }
381 }
382
383
384
385 #
386 # xmpp_send_raw_xml: send a raw XML packet
387 # input: connection,packet
388 #
389 sub xmpp_send_raw_xml ($$) {
390
391     my ($cnx,$packet) = @_;
392
393     # for some reason, Send does not return anything
394     $cnx->Send($packet);
395     xmpp_check_result('Send',0,$cnx);
396 }
397
398
399 #
400 # xmpp_send_message: send a message to some xmpp user
401 # input: connection,recipient,subject,msg
402 #
403 sub xmpp_send_message ($$$$$$) {
404
405     my ($cnx, $rcpt, $comp, $subject, $message_type, $msg) = @_;
406
407     # for some reason, MessageSend does not return anything
408         # mimeit01@xmpp.hs-esslingen.de: if $comp IS set, AND the rcpt DOESN'T contain an @, then @comp is added
409     $cnx->MessageSend('to'      => $rcpt . ( ($comp && index($rcpt, "@") == -1) ? "\@$comp" : '' ),
410                 'type'          => $message_type,
411                 'subject'       => $subject,
412                 'body'          => $msg);
413
414     xmpp_check_result('MessageSend',0,$cnx);
415 }
416
417
418 #
419 # xmpp_send_chatroom_message: send a message to a chatroom
420 # input: connection,resource,subject,recipient,message
421 #
422 sub xmpp_send_chatroom_message ($$$$$) {
423
424     my ($cnx,$resource,$subject,$rcpt,$msg) =  @_;
425
426     # set the presence
427     my $pres = new Net::XMPP::Presence;
428     my $res = $pres->SetTo("$rcpt/$resource");
429
430     $cnx->Send($pres);
431
432     # create/send the message
433     my $groupmsg = new Net::XMPP::Message;
434     $groupmsg->SetMessage(to      => $rcpt,
435                           body    => $msg,
436                           type    => 'groupchat');
437
438     $res = $cnx->Send($groupmsg);
439     xmpp_check_result ('Send',$res,$cnx);
440
441     # leave the group
442     $pres->SetPresence (Type=>'unavailable',To=>$rcpt);
443 }
444
445
446 #
447 # xmpp_logout: log out from the xmpp server
448 # input: connection
449 #
450 sub xmpp_logout($) {
451
452     # HACK
453     # messages may not be received if we log out too quickly...
454     sleep 1;
455
456     my $cnx = shift;
457     $cnx->Disconnect();
458     xmpp_check_result ('Disconnect',0); # well, nothing to check, really
459 }
460
461
462
463 #
464 # xmpp_check_result: check the return value from some xmpp function execution
465 # input: text, result, [connection]
466 #
467 sub xmpp_check_result
468 {
469     my ($txt, $res, $cnx)=@_;
470
471     error_exit ("Error '$txt': result undefined")
472         unless (defined $res);
473
474     # res may be 0
475         if ($res == 0) {
476                 debug_print "$txt";
477                 # result can be true or 'ok'
478         }
479         elsif ((@$res == 1 && $$res[0]) || $$res[0] eq 'ok') {
480                 debug_print "$txt: " .  $$res[0];
481                 # otherwise, there is some error
482         }
483         else {
484                 my $errmsg = $cnx->GetErrorCode() || '?';
485                 error_exit ("Error '$txt': " . join (': ',@$res) . "[$errmsg]", $cnx);
486         }
487 }
488
489
490 #
491 # terminate; exit the program upon TERM sig reception
492 #
493 sub terminate () {
494     debug_print "caught TERM";
495     xmpp_logout($main::CNX);
496     exit 0;
497 }
498
499
500 #
501 # debug_print: print the data if defined and DEBUG || VERBOSE is TRUE
502 # input: [array of strings]
503 #
504 sub debug_print {
505     print STDERR "sendxmpp: " . (join ' ', @_) . "\n"
506         if (@_ && ($DEBUG ||$VERBOSE));
507 }
508
509
510 #
511 # error_exit: print error message and exit the program
512 #             logs out if there is a connection
513 # input: error, [connection]
514 #
515 sub error_exit {
516
517     my ($err,$cnx) = @_;
518     print STDERR "$err\n";
519     xmpp_logout ($cnx)
520         if ($cnx);
521
522     exit 1;
523 }
524
525
526 #
527 # usage: print short usage message and exit
528 #
529 sub usage () {
530
531     print STDERR
532         "sendxmpp version $VERSION\n" .
533         "Copyright (c) 2004 - 2005 Dirk-Jan C. Binnema\n" .
534         "Copyright (c) 2006 - 2007 Lubomir Host 'rajo'\n" .
535         "usage: sendxmpp [options] <recipient1> [<recipient2> ...]\n" .
536         "or refer to the the sendxmpp manpage\n";
537
538     exit 0;
539 }
540
541
542 #
543 # the fine manual
544 #
545 =pod
546
547 =head1 NAME
548
549 sendxmpp - send xmpp messages from the commandline.
550
551 =head1 SYNOPSIS
552
553 sendxmpp [options] <recipient1> [<recipient2> ...]
554
555 sendxmpp --raw [options]
556
557 =head1 DESCRIPTION
558
559 sendxmpp is a program to send XMPP (Jabber) messages from the commandline, not
560 unlike L<mail(1)>. Messages can be sent both to individual recipients and chatrooms.
561
562 =head1 OPTIONS
563
564 =over
565
566 =item B<-f>,B<--file> I<file>
567
568 Use I<file> configuration file instead of F<~/.sendxmpprc>
569
570 =item B<-u>,B<--username> I<user>
571
572 Use I<user> instead of the one in the configuration file
573
574 =item B<-p>,B<--password> I<password>
575
576 Use I<password> instead of the one in the configuration file
577
578 =item B<-j>,B<--jserver> I<server>
579
580 Use jabber I<server> instead of the one in the configuration file.
581
582 =item B<-o>,B<--component> I<componentname>
583
584 Use componentname in connect call. Seems needed for Google talk.
585
586 =item B<-r>,B<--resource> I<res>
587
588 Use resource I<res> for the sender [default: 'sendxmpp']; when sending to a chatroom, this determines the 'alias'
589
590 =item B<-t>,B<--tls>
591
592 Connect securely, using TLS
593
594 =item B<-e>,B<--ssl>
595
596 Connect securely, using SSL
597
598 =item B<-l>,B<--headline>
599
600 Backward compatibility option. You should use B<--message-type=headline> instead. Send a headline type message (not stored in offline messages)
601
602 =item B<--messages-type>
603
604 Set type of message. Supported types are: B<message chat headline>. Default message type is B<message>. Headline type message can be set also with B<--headline> option, see B<--headline>
605
606 =item B<-c>,B<--chatroom>
607
608 Send the message to a chatroom
609
610 =item B<-s>,B<--subject> I<subject>
611
612 Set the subject for the message to I<subject> [default: '']; when sending to a chatroom, this will set the subject for the chatroom
613
614 =item B<-m>,B<--message> I<message>
615
616 Read the message from I<message> (a file) instead of stdin
617
618 =item B<-i>,B<--interactive>
619
620 Work in interactive mode, reading lines from stdin and sending the one-at-time
621
622 =item B<-w>,B<--raw>
623
624 Send raw XML message to jabber server
625
626 =item B<-v>,B<--verbose>
627
628 Give verbose output about what is happening
629
630 =item B<-h>,B<--help>,B<--usage>
631
632 Show a 'Usage' message
633
634 =item B<-d>,B<--debug>
635
636 Show debugging info while running. B<WARNING>: This will include passwords etc. so be careful with the output!
637
638 =back
639
640 =head1 CONFIGURATION FILE
641
642 You may define a 'F<~/.sendxmpprc>' file with the necessary data for your
643 xmpp-account, with a line of the format:
644
645 =over
646
647 I<user>@I<server> I<password> I<componentname>
648
649 =back
650
651 e.g.:
652
653     # my account
654     alice@jabber.org  secret
655
656 ('#' and newlines are allowed like in shellscripts). You can add a I<host> (or IP address) if it is different from the I<server> part of your JID:
657
658     # account with specific connection host
659     alice@myjabberserver.com;foo.com secret
660
661 You can also add a I<port> if it is not the standard XMPP port:
662
663     # account with weird port number
664     alice@myjabberserver.com:1234 secret
665
666 Of course, you may also mix the two:
667
668     # account with a specific host and port
669     alice@myjabberserver.com;foo.com:1234 secret
670
671 B<NOTE>: for your security, sendxmpp demands that the configuration
672 file is owned by you and readable only to you (permissions 600).
673
674 =head1 EXAMPLE
675
676    $ echo "hello bob!" | sendxmpp -s hello someone@jabber.org
677
678      or to send to a chatroom:
679
680    $ echo "Dinner Time" | sendxmpp -r TheCook --chatroom test2@conference.jabber.org
681
682      or to send your system logs somewhere, as new lines appear:
683
684    $ tail -f /var/log/syslog | sendxmpp -i sysadmin@myjabberserver.com
685
686      NOTE: be careful not the overload public jabber services
687
688 =head1 SEE ALSO
689
690 Documentation for the L<Net::XMPP> module
691
692 The jabber homepage: L<http://www.jabber.org/>
693
694 The sendxmpp homepage: L<http://sendxmpp.platon.sk>
695
696 =head1 AUTHOR
697
698 sendxmpp has been written by Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>, and uses
699 the L<Net::XMPP> modules written by Ryan Eatmon. Current maintainer is
700 Lubomir Host 'rajo' <rajo AT platon.sk>, L<http://rajo.platon.sk>
701
702 =cut