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