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