RE: Failing tests on VMS blead@26652
[p5sagit/p5-mst-13.2.git] / ext / Sys / Syslog / Syslog.pm
CommitLineData
a0d0e21e 1package Sys::Syslog;
8168e71f 2use strict;
3use Carp;
3b355090 4require 5.006;
a0d0e21e 5require Exporter;
a0d0e21e 6
942974c1 7our $VERSION = '0.11';
db9f82cf 8our @ISA = qw(Exporter);
942974c1 9
10our %EXPORT_TAGS = (
11 standard => [qw(openlog syslog closelog setlogmask)],
12 extended => [qw(setlogsock)],
13 macros => [qw(
14 LOG_ALERT LOG_AUTH LOG_AUTHPRIV LOG_CONS LOG_CRIT LOG_CRON
15 LOG_DAEMON LOG_DEBUG LOG_EMERG LOG_ERR LOG_FACMASK LOG_FTP
16 LOG_INFO LOG_KERN LOG_LFMT LOG_LOCAL0 LOG_LOCAL1 LOG_LOCAL2
17 LOG_LOCAL3 LOG_LOCAL4 LOG_LOCAL5 LOG_LOCAL6 LOG_LOCAL7 LOG_LPR
18 LOG_MAIL LOG_NDELAY LOG_NEWS LOG_NFACILITIES LOG_NOTICE
19 LOG_NOWAIT LOG_ODELAY LOG_PERROR LOG_PID LOG_PRIMASK LOG_SYSLOG
20 LOG_USER LOG_UUCP LOG_WARNING
21 )],
22);
23
24our @EXPORT = (
25 @{$EXPORT_TAGS{standard}},
26);
27
28our @EXPORT_OK = (
29 @{$EXPORT_TAGS{extended}},
30 @{$EXPORT_TAGS{macros}},
31);
a0d0e21e 32
23642f4b 33# it would be nice to try stream/unix first, since that will be
34# most efficient. However streams are dodgy - see _syslog_send_stream
23642f4b 35my @connectMethods = ( 'tcp', 'udp', 'unix', 'stream', 'console' );
dbfdd438 36if ($^O =~ /^(freebsd|linux)$/) {
37 @connectMethods = grep { $_ ne 'udp' } @connectMethods;
38}
23642f4b 39my @defaultMethods = @connectMethods;
40my $syslog_path = undef;
41my $transmit_ok = 0;
42my $current_proto = undef;
43my $failed = undef;
44my $fail_time = undef;
108be7fb 45our ($connected, @fallbackMethods, $syslog_send, $host);
23642f4b 46
108be7fb 47use Socket ':all';
942974c1 48use POSIX qw(strftime setlocale LC_TIME);
37120919 49
5be1dfc7 50=head1 NAME
51
8168e71f 52Sys::Syslog - Perl interface to the UNIX syslog(3) calls
53
54=head1 VERSION
55
942974c1 56Version 0.11
5be1dfc7 57
58=head1 SYNOPSIS
59
8168e71f 60 use Sys::Syslog; # all except setlogsock(), or:
61 use Sys::Syslog qw(:DEFAULT setlogsock); # default set, plus setlogsock()
942974c1 62 use Sys::Syslog qw(:standard :macros); # standard functions, plus macros
5be1dfc7 63
3ffabb8c 64 setlogsock $sock_type;
3d256c0f 65 openlog $ident, $logopt, $facility; # don't forget this
2eae817d 66 syslog $priority, $format, @args;
5be1dfc7 67 $oldmask = setlogmask $mask_priority;
68 closelog;
69
8168e71f 70
5be1dfc7 71=head1 DESCRIPTION
72
8168e71f 73C<Sys::Syslog> is an interface to the UNIX C<syslog(3)> program.
5be1dfc7 74Call C<syslog()> with a string priority and a list of C<printf()> args
75just like C<syslog(3)>.
76
8168e71f 77
78=head1 EXPORTS
79
942974c1 80C<Sys::Syslog> exports the following C<Exporter> tags:
81
82=over 4
83
84=item *
85
86C<:standard> exports the standard C<syslog(3)> functions:
8168e71f 87
88 openlog closelog setlogmask syslog
89
942974c1 90=item *
91
92C<:extended> exports the Perl specific functions for C<syslog(3)>:
93
94 setlogsock
95
96=item *
97
98C<:macros> exports the symbols corresponding to most of your C<syslog(3)>
99macros. See L<"CONSTANTS"> for the supported constants and their meaning.
100
101=back
102
103By default, C<Sys::Syslog> exports the symbols from the C<:standard> tag.
8168e71f 104
105
106=head1 FUNCTIONS
5be1dfc7 107
bbc7dcd2 108=over 4
5be1dfc7 109
8168e71f 110=item B<openlog($ident, $logopt, $facility)>
5be1dfc7 111
b91ed019 112Opens the syslog.
8168e71f 113C<$ident> is prepended to every message. C<$logopt> contains zero or
114more of the words C<pid>, C<ndelay>, C<nowait>. The C<cons> option is
23642f4b 115ignored, since the failover mechanism will drop down to the console
8168e71f 116automatically if all other media fail. C<$facility> specifies the
117part of the system to report about, for example C<LOG_USER> or C<LOG_LOCAL0>:
3d256c0f 118see your C<syslog(3)> documentation for the facilities available in
942974c1 119your system. Facility can be given as a string or a numeric macro.
120
121This function will croak if it can't connect to the syslog daemon.
3d256c0f 122
8168e71f 123Note that C<openlog()> now takes three arguments, just like C<openlog(3)>.
124
3d256c0f 125B<You should use openlog() before calling syslog().>
5be1dfc7 126
942974c1 127B<Options>
128
129=over 4
130
131=item *
132
133C<ndelay> - Open the connection immediately (normally, the connection is
134opened when the first message is logged).
135
136=item *
137
138C<nowait> - Don't wait for child processes that may have been created
139while logging the message. (The GNU C library does not create a child
140process, so this option has no effect on Linux.)
141
142=item *
143
144C<pid> - Include PID with each message.
145
146=back
147
148B<Examples>
149
150Open the syslog with options C<ndelay> and C<pid>, and with facility C<LOCAL0>:
151
152 openlog($name, "ndelay,pid", "local0");
153
154Same thing, but this time using the macro corresponding to C<LOCAL0>:
155
156 openlog($name, "ndelay,pid", LOG_LOCAL0);
157
158
8168e71f 159=item B<syslog($priority, $message)>
ce43db9b 160
8168e71f 161=item B<syslog($priority, $format, @args)>
5be1dfc7 162
8168e71f 163If C<$priority> permits, logs C<$message> or C<sprintf($format, @args)>
942974c1 164with the addition that C<%m> in $message or C<$format> is replaced with
165C<"$!"> (the latest error message).
5be1dfc7 166
942974c1 167C<$priority> can specify a level, or a level and a facility. Levels and
168facilities can be given as strings or as macros.
169
170If you didn't use C<openlog()> before using C<syslog()>, C<syslog()> will
8168e71f 171try to guess the C<$ident> by extracting the shortest prefix of
172C<$format> that ends in a C<":">.
3d256c0f 173
942974c1 174B<Examples>
175
176 syslog("info", $message); # informational level
177 syslog(LOG_INFO, $message); # informational level
178
179 syslog("info|local0", $message); # information level, Local0 facility
180 syslog(LOG_INFO|LOG_LOCAL0, $message); # information level, Local0 facility
181
182=over 4
183
184=item B<Note>
185
186C<Sys::Syslog> version v0.07 and older passed the C<$message> as the
187formatting string to C<sprintf()> even when no formatting arguments
188were provided. If the code calling C<syslog()> might execute with
189older versions of this module, make sure to call the function as
8168e71f 190C<syslog($priority, "%s", $message)> instead of C<syslog($priority,
191$message)>. This protects against hostile formatting sequences that
9903e4c8 192might show up if $message contains tainted data.
193
942974c1 194=back
195
196
8168e71f 197=item B<setlogmask($mask_priority)>
5be1dfc7 198
942974c1 199Sets the log mask for the current process to C<$mask_priority> and
200returns the old mask. If the mask argument is 0, the current log mask
201is not modified. See L<"Levels"> for the list of available levels.
202
203B<Examples>
204
205Only log errors:
206
207 setlogmask(LOG_ERR);
208
209Log critical messages, errors and warnings:
210
211 setlogmask(LOG_CRIT|LOG_ERR|LOG_WARNING);
212
5be1dfc7 213
8168e71f 214=item B<setlogsock($sock_type)>
215
216=item B<setlogsock($sock_type, $stream_location)> (added in 5.004_02)
3ffabb8c 217
cb63fe9d 218Sets the socket type to be used for the next call to
8168e71f 219C<openlog()> or C<syslog()> and returns true on success,
220C<undef> on failure.
3ffabb8c 221
8168e71f 222A value of C<"unix"> will connect to the UNIX domain socket (in some
f66a7beb 223systems a character special device) returned by the C<_PATH_LOG> macro
224(if your system defines it), or F</dev/log> or F</dev/conslog>,
225whatever is writable. A value of 'stream' will connect to the stream
226indicated by the pathname provided as the optional second parameter.
8168e71f 227(For example Solaris and IRIX require C<"stream"> instead of C<"unix">.)
228A value of C<"inet"> will connect to an INET socket (either C<tcp> or C<udp>,
229tried in that order) returned by C<getservbyname()>. C<"tcp"> and C<"udp"> can
230also be given as values. The value C<"console"> will send messages
231directly to the console, as for the C<"cons"> option in the logopts in
232C<openlog()>.
23642f4b 233
234A reference to an array can also be passed as the first parameter.
235When this calling method is used, the array should contain a list of
236sock_types which are attempted in order.
cb63fe9d 237
8168e71f 238The default is to try C<tcp>, C<udp>, C<unix>, C<stream>, C<console>.
23642f4b 239
8168e71f 240Giving an invalid value for C<$sock_type> will croak.
cb63fe9d 241
942974c1 242
8168e71f 243=item B<closelog()>
5be1dfc7 244
942974c1 245Closes the log file and return true on success.
5be1dfc7 246
247=back
248
5be1dfc7 249
250=head1 EXAMPLES
251
252 openlog($program, 'cons,pid', 'user');
e6c138cd 253 syslog('info', '%s', 'this is another test');
5be1dfc7 254 syslog('mail|warning', 'this is a better test: %d', time);
255 closelog();
256
257 syslog('debug', 'this is the last test');
cb63fe9d 258
259 setlogsock('unix');
5be1dfc7 260 openlog("$program $$", 'ndelay', 'user');
261 syslog('notice', 'fooprogram: this is really done');
262
cb63fe9d 263 setlogsock('inet');
5be1dfc7 264 $! = 55;
265 syslog('info', 'problem was %m'); # %m == $! in syslog(3)
266
476b65d9 267 # Log to UDP port on $remotehost instead of logging locally
268 setlogsock('udp');
269 $Sys::Syslog::host = $remotehost;
270 openlog($program, 'ndelay', 'user');
271 syslog('info', 'something happened over here');
272
8168e71f 273
274=head1 CONSTANTS
275
276=head2 Facilities
277
278=over 4
279
280=item *
281
282C<LOG_AUTH> - security/authorization messages
283
284=item *
285
286C<LOG_AUTHPRIV> - security/authorization messages (private)
287
288=item *
289
290C<LOG_CRON> - clock daemon (B<cron> and B<at>)
291
292=item *
293
294C<LOG_DAEMON> - system daemons without separate facility value
295
296=item *
297
298C<LOG_FTP> - ftp daemon
299
300=item *
301
302C<LOG_KERN> - kernel messages
303
304=item *
305
306C<LOG_LOCAL0> through C<LOG_LOCAL7> - reserved for local use
307
308=item *
309
310C<LOG_LPR> - line printer subsystem
311
312=item *
313
314C<LOG_MAIL> - mail subsystem
315
316=item *
317
318C<LOG_NEWS> - USENET news subsystem
319
320=item *
321
322C<LOG_SYSLOG> - messages generated internally by B<syslogd>
323
324=item *
325
326C<LOG_USER> (default) - generic user-level messages
327
328=item *
329
330C<LOG_UUCP> - UUCP subsystem
331
332=back
333
334
335=head2 Levels
336
337=over 4
338
339=item *
340
341C<LOG_EMERG> - system is unusable
342
343=item *
344
345C<LOG_ALERT> - action must be taken immediately
346
347=item *
348
349C<LOG_CRIT> - critical conditions
350
351=item *
352
942974c1 353C<LOG_ERR> - error conditions
8168e71f 354
355=item *
356
357C<LOG_WARNING> - warning conditions
358
359=item *
360
361C<LOG_NOTICE> - normal, but significant, condition
362
363=item *
364
365C<LOG_INFO> - informational message
366
367=item *
368
369C<LOG_DEBUG> - debug-level message
370
371=back
372
373
374=head1 DIAGNOSTICS
375
376=over 4
377
378=item Invalid argument passed to setlogsock
379
380B<(F)> You gave C<setlogsock()> an invalid value for C<$sock_type>.
381
382=item no connection to syslog available
383
384B<(F)> C<syslog()> failed to connect to the specified socket.
385
386=item stream passed to setlogsock, but %s is not writable
387
942974c1 388B<(W)> You asked C<setlogsock()> to use a stream socket, but the given
8168e71f 389path is not writable.
390
391=item stream passed to setlogsock, but could not find any device
392
942974c1 393B<(W)> You asked C<setlogsock()> to use a stream socket, but didn't
8168e71f 394provide a path, and C<Sys::Syslog> was unable to find an appropriate one.
395
396=item tcp passed to setlogsock, but tcp service unavailable
397
942974c1 398B<(W)> You asked C<setlogsock()> to use a TCP socket, but the service
8168e71f 399is not available on the system.
400
401=item syslog: expecting argument %s
402
403B<(F)> You forgot to give C<syslog()> the indicated argument.
404
405=item syslog: invalid level/facility: %s
406
407B<(F)> You specified an invalid level or facility, like C<LOG_KERN>
408(which is reserved to the kernel).
409
410=item syslog: too many levels given: %s
411
412B<(F)> You specified too many levels.
413
414=item syslog: too many facilities given: %s
415
416B<(F)> You specified too many facilities.
417
418=item syslog: level must be given
419
420B<(F)> You forgot to specify a level.
421
422=item udp passed to setlogsock, but udp service unavailable
423
942974c1 424B<(W)> You asked C<setlogsock()> to use a UDP socket, but the service
8168e71f 425is not available on the system.
426
427=item unix passed to setlogsock, but path not available
428
942974c1 429B<(W)> You asked C<setlogsock()> to use a UNIX socket, but C<Sys::Syslog>
8168e71f 430was unable to find an appropriate an appropriate device.
431
432=back
433
434
5be1dfc7 435=head1 SEE ALSO
436
437L<syslog(3)>
438
8168e71f 439
5be1dfc7 440=head1 AUTHOR
441
150b260b 442Tom Christiansen E<lt>F<tchrist@perl.com>E<gt> and Larry Wall
443E<lt>F<larry@wall.org>E<gt>.
444
445UNIX domain sockets added by Sean Robinson
23642f4b 446E<lt>F<robinson_s@sc.maricopa.edu>E<gt> with support from Tim Bunce
8168e71f 447E<lt>F<Tim.Bunce@ig.co.uk>E<gt> and the C<perl5-porters> mailing list.
150b260b 448
449Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
450E<lt>F<tom@compton.nu>E<gt>.
5be1dfc7 451
8168e71f 452Code for C<constant()>s regenerated by Nicholas Clark E<lt>F<nick@ccl4.org>E<gt>.
23642f4b 453
454Failover to different communication modes by Nick Williams
455E<lt>F<Nick.Williams@morganstanley.com>E<gt>.
b903fcff 456
8168e71f 457Extracted from core distribution for publishing on the CPAN by
458SE<eacute>bastien Aperghis-Tramoni E<lt>sebastien@aperghis.netE<gt>.
459
460
461=head1 BUGS
462
463Please report any bugs or feature requests to
464C<bug-sys-syslog at rt.cpan.org>, or through the web interface at
465L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Sys-Syslog>.
466I will be notified, and then you'll automatically be notified of progress on
467your bug as I make changes.
468
469
470=head1 SUPPORT
471
472You can find documentation for this module with the perldoc command.
473
474 perldoc Sys::Syslog
475
476You can also look for information at:
477
478=over 4
479
480=item * AnnoCPAN: Annotated CPAN documentation
481
482L<http://annocpan.org/dist/Sys-Syslog>
483
484=item * CPAN Ratings
485
486L<http://cpanratings.perl.org/d/Sys-Syslog>
487
488=item * RT: CPAN's request tracker
489
490L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Sys-Syslog>
491
492=item * Search CPAN
493
494L<http://search.cpan.org/dist/Sys-Syslog>
495
496=back
497
498
499=head1 LICENSE
500
501This program is free software; you can redistribute it and/or modify it
502under the same terms as Perl itself.
503
5be1dfc7 504=cut
a0d0e21e 505
8ce86de8 506sub AUTOLOAD {
507 # This AUTOLOAD is used to 'autoload' constants from the constant()
508 # XS function.
8ce86de8 509 my $constname;
510 our $AUTOLOAD;
511 ($constname = $AUTOLOAD) =~ s/.*:://;
b903fcff 512 croak "&Sys::Syslog::constant not defined" if $constname eq 'constant';
513 my ($error, $val) = constant($constname);
942974c1 514 croak $error if $error;
108be7fb 515 no strict 'refs';
8ce86de8 516 *$AUTOLOAD = sub { $val };
517 goto &$AUTOLOAD;
518}
519
942974c1 520eval {
521 require XSLoader;
522 XSLoader::load('Sys::Syslog', $VERSION);
523 1
524} or do {
525 require DynaLoader;
526 push @ISA, 'DynaLoader';
527 bootstrap Sys::Syslog $VERSION;
528};
a0d0e21e 529
108be7fb 530our $maskpri = &LOG_UPTO(&LOG_DEBUG);
a0d0e21e 531
532sub openlog {
108be7fb 533 our ($ident, $logopt, $facility) = @_; # package vars
534 our $lo_pid = $logopt =~ /\bpid\b/;
535 our $lo_ndelay = $logopt =~ /\bndelay\b/;
536 our $lo_nowait = $logopt =~ /\bnowait\b/;
a8710ca1 537 return 1 unless $lo_ndelay;
538 &connect;
a0d0e21e 539}
540
541sub closelog {
108be7fb 542 our $facility = our $ident = '';
a0d0e21e 543 &disconnect;
544}
545
546sub setlogmask {
108be7fb 547 my $oldmask = $maskpri;
942974c1 548 $maskpri = shift unless $_[0] == 0;
a0d0e21e 549 $oldmask;
550}
551
cb63fe9d 552sub setlogsock {
108be7fb 553 my $setsock = shift;
23642f4b 554 $syslog_path = shift;
3ffabb8c 555 &disconnect if $connected;
23642f4b 556 $transmit_ok = 0;
557 @fallbackMethods = ();
558 @connectMethods = @defaultMethods;
559 if (ref $setsock eq 'ARRAY') {
560 @connectMethods = @$setsock;
561 } elsif (lc($setsock) eq 'stream') {
f66a7beb 562 unless (defined $syslog_path) {
563 my @try = qw(/dev/log /dev/conslog);
e863979d 564 if (length &_PATH_LOG) { # Undefined _PATH_LOG is "".
f66a7beb 565 unshift @try, &_PATH_LOG;
566 }
567 for my $try (@try) {
568 if (-w $try) {
569 $syslog_path = $try;
570 last;
571 }
572 }
942974c1 573 carp "stream passed to setlogsock, but could not find any device"
574 unless defined $syslog_path
f66a7beb 575 }
e863979d 576 unless (-w $syslog_path) {
942974c1 577 carp "stream passed to setlogsock, but $syslog_path is not writable";
23642f4b 578 return undef;
579 } else {
580 @connectMethods = ( 'stream' );
581 }
582 } elsif (lc($setsock) eq 'unix') {
583 if (length _PATH_LOG() && !defined $syslog_path) {
584 $syslog_path = _PATH_LOG();
585 @connectMethods = ( 'unix' );
3ffabb8c 586 } else {
942974c1 587 carp 'unix passed to setlogsock, but path not available';
23642f4b 588 return undef;
3ffabb8c 589 }
23642f4b 590 } elsif (lc($setsock) eq 'tcp') {
591 if (getservbyname('syslog', 'tcp') || getservbyname('syslogng', 'tcp')) {
592 @connectMethods = ( 'tcp' );
593 } else {
942974c1 594 carp "tcp passed to setlogsock, but tcp service unavailable";
23642f4b 595 return undef;
596 }
597 } elsif (lc($setsock) eq 'udp') {
598 if (getservbyname('syslog', 'udp')) {
599 @connectMethods = ( 'udp' );
600 } else {
942974c1 601 carp "udp passed to setlogsock, but udp service unavailable";
23642f4b 602 return undef;
603 }
cb63fe9d 604 } elsif (lc($setsock) eq 'inet') {
23642f4b 605 @connectMethods = ( 'tcp', 'udp' );
606 } elsif (lc($setsock) eq 'console') {
607 @connectMethods = ( 'console' );
cb63fe9d 608 } else {
942974c1 609 croak "Invalid argument passed to setlogsock; must be 'stream', 'unix', 'tcp', 'udp' or 'inet'"
cb63fe9d 610 }
f8b75b0c 611 return 1;
cb63fe9d 612}
613
a0d0e21e 614sub syslog {
108be7fb 615 my $priority = shift;
616 my $mask = shift;
617 my ($message, $whoami);
618 my (@words, $num, $numpri, $numfac, $sum);
619 our $facility;
a0d0e21e 620 local($facility) = $facility; # may need to change temporarily.
621
942974c1 622 croak "syslog: expecting argument \$priority" unless defined $priority;
623 croak "syslog: expecting argument \$format" unless defined $mask;
a0d0e21e 624
625 @words = split(/\W+/, $priority, 2);# Allow "level" or "level|facility".
626 undef $numpri;
627 undef $numfac;
628 foreach (@words) {
629 $num = &xlate($_); # Translate word to number.
942974c1 630 if ($_ eq 'kern' || $num <= 0) {
631 croak "syslog: invalid level/facility: $_"
a0d0e21e 632 }
633 elsif ($num <= &LOG_PRIMASK) {
634 croak "syslog: too many levels given: $_" if defined($numpri);
635 $numpri = $num;
636 return 0 unless &LOG_MASK($numpri) & $maskpri;
637 }
638 else {
639 croak "syslog: too many facilities given: $_" if defined($numfac);
640 $facility = $_;
641 $numfac = $num;
642 }
643 }
644
645 croak "syslog: level must be given" unless defined($numpri);
646
647 if (!defined($numfac)) { # Facility not specified in this call.
648 $facility = 'user' unless $facility;
649 $numfac = &xlate($facility);
650 }
651
652 &connect unless $connected;
653
108be7fb 654 $whoami = our $ident;
a0d0e21e 655
5dad0344 656 if (!$whoami && $mask =~ /^(\S.*?):\s?(.*)/) {
a0d0e21e 657 $whoami = $1;
658 $mask = $2;
659 }
660
661 unless ($whoami) {
662 ($whoami = getlogin) ||
663 ($whoami = getpwuid($<)) ||
664 ($whoami = 'syslog');
665 }
666
108be7fb 667 $whoami .= "[$$]" if our $lo_pid;
a0d0e21e 668
5007285b 669 if ($mask =~ /%m/) {
670 my $err = $!;
671 # escape percent signs if sprintf will be called
672 $err =~ s/%/%%/g if @_;
673 # replace %m with $err, if preceded by an even number of percent signs
674 $mask =~ s/(?<!%)((?:%%)*)%m/$1$err/g;
675 }
676
a0d0e21e 677 $mask .= "\n" unless $mask =~ /\n$/;
ce43db9b 678 $message = @_ ? sprintf($mask, @_) : $mask;
a0d0e21e 679
680 $sum = $numpri + $numfac;
942974c1 681 my $oldlocale = setlocale(LC_TIME);
682 setlocale(LC_TIME, 'C');
683 my $timestamp = strftime "%b %e %T", localtime;
684 setlocale(LC_TIME, $oldlocale);
685 my $buf = "<$sum>$timestamp $whoami: $message\0";
23642f4b 686
687 # it's possible that we'll get an error from sending
688 # (e.g. if method is UDP and there is no UDP listener,
689 # then we'll get ECONNREFUSED on the send). So what we
690 # want to do at this point is to fallback onto a different
691 # connection method.
692 while (scalar @fallbackMethods || $syslog_send) {
693 if ($failed && (time - $fail_time) > 60) {
694 # it's been a while... maybe things have been fixed
695 @fallbackMethods = ();
696 disconnect();
697 $transmit_ok = 0; # make it look like a fresh attempt
698 &connect;
699 }
700 if ($connected && !connection_ok()) {
701 # Something was OK, but has now broken. Remember coz we'll
702 # want to go back to what used to be OK.
703 $failed = $current_proto unless $failed;
704 $fail_time = time;
705 disconnect();
706 }
707 &connect unless $connected;
60b8437d 708 $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
23642f4b 709 if ($syslog_send) {
710 if (&{$syslog_send}($buf)) {
711 $transmit_ok++;
712 return 1;
a0d0e21e 713 }
23642f4b 714 # typically doesn't happen, since errors are rare from write().
715 disconnect();
716 }
717 }
718 # could not send, could not fallback onto a working
719 # connection method. Lose.
720 return 0;
721}
722
723sub _syslog_send_console {
724 my ($buf) = @_;
725 chop($buf); # delete the NUL from the end
726 # The console print is a method which could block
727 # so we do it in a child process and always return success
728 # to the caller.
729 if (my $pid = fork) {
108be7fb 730 our $lo_nowait;
23642f4b 731 if ($lo_nowait) {
732 return 1;
733 } else {
734 if (waitpid($pid, 0) >= 0) {
735 return ($? >> 8);
736 } else {
737 # it's possible that the caller has other
738 # plans for SIGCHLD, so let's not interfere
739 return 1;
a0d0e21e 740 }
741 }
23642f4b 742 } else {
743 if (open(CONS, ">/dev/console")) {
744 my $ret = print CONS $buf . "\r";
745 exit ($ret) if defined $pid;
746 close CONS;
747 }
748 exit if defined $pid;
a0d0e21e 749 }
750}
751
23642f4b 752sub _syslog_send_stream {
753 my ($buf) = @_;
754 # XXX: this only works if the OS stream implementation makes a write
755 # look like a putmsg() with simple header. For instance it works on
756 # Solaris 8 but not Solaris 7.
757 # To be correct, it should use a STREAMS API, but perl doesn't have one.
758 return syswrite(SYSLOG, $buf, length($buf));
759}
8168e71f 760
23642f4b 761sub _syslog_send_socket {
762 my ($buf) = @_;
763 return syswrite(SYSLOG, $buf, length($buf));
764 #return send(SYSLOG, $buf, 0);
765}
766
a0d0e21e 767sub xlate {
108be7fb 768 my($name) = @_;
b9f13614 769 return $name+0 if $name =~ /^\s*\d+\s*$/;
55497cff 770 $name = uc $name;
a0d0e21e 771 $name = "LOG_$name" unless $name =~ /^LOG_/;
748a9306 772 $name = "Sys::Syslog::$name";
2c3b42a1 773 # Can't have just eval { &$name } || -1 because some LOG_XXX may be zero.
108be7fb 774 my $value = eval { no strict 'refs'; &$name };
2c3b42a1 775 defined $value ? $value : -1;
a0d0e21e 776}
777
778sub connect {
23642f4b 779 @fallbackMethods = @connectMethods unless (scalar @fallbackMethods);
780 if ($transmit_ok && $current_proto) {
781 # Retry what we were on, because it's worked in the past.
782 unshift(@fallbackMethods, $current_proto);
783 }
784 $connected = 0;
785 my @errs = ();
786 my $proto = undef;
787 while ($proto = shift(@fallbackMethods)) {
108be7fb 788 no strict 'refs';
23642f4b 789 my $fn = "connect_$proto";
108be7fb 790 $connected = &$fn(\@errs) if defined &$fn;
23642f4b 791 last if ($connected);
792 }
793
794 $transmit_ok = 0;
795 if ($connected) {
60b8437d 796 $current_proto = $proto;
108be7fb 797 my($old) = select(SYSLOG); $| = 1; select($old);
23642f4b 798 } else {
799 @fallbackMethods = ();
800 foreach my $err (@errs) {
801 carp $err;
802 }
803 croak "no connection to syslog available";
804 }
805}
806
807sub connect_tcp {
808 my ($errs) = @_;
809 unless ($host) {
810 require Sys::Hostname;
811 my($host_uniq) = Sys::Hostname::hostname();
812 ($host) = $host_uniq =~ /([A-Za-z0-9_.-]+)/; # allow FQDN (inc _)
813 }
814 my $tcp = getprotobyname('tcp');
815 if (!defined $tcp) {
816 push(@{$errs}, "getprotobyname failed for tcp");
817 return 0;
818 }
819 my $syslog = getservbyname('syslog','tcp');
820 $syslog = getservbyname('syslogng','tcp') unless (defined $syslog);
821 if (!defined $syslog) {
822 push(@{$errs}, "getservbyname failed for tcp");
823 return 0;
824 }
825
826 my $this = sockaddr_in($syslog, INADDR_ANY);
827 my $that = sockaddr_in($syslog, inet_aton($host));
828 if (!$that) {
829 push(@{$errs}, "can't lookup $host");
830 return 0;
831 }
832 if (!socket(SYSLOG,AF_INET,SOCK_STREAM,$tcp)) {
833 push(@{$errs}, "tcp socket: $!");
834 return 0;
835 }
836 setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
837 setsockopt(SYSLOG, IPPROTO_TCP, TCP_NODELAY, 1);
60b8437d 838 if (!CORE::connect(SYSLOG,$that)) {
23642f4b 839 push(@{$errs}, "tcp connect: $!");
840 return 0;
841 }
842 $syslog_send = \&_syslog_send_socket;
843 return 1;
844}
845
846sub connect_udp {
847 my ($errs) = @_;
4fc7577b 848 unless ($host) {
849 require Sys::Hostname;
2eae817d 850 my($host_uniq) = Sys::Hostname::hostname();
3e3baf6d 851 ($host) = $host_uniq =~ /([A-Za-z0-9_.-]+)/; # allow FQDN (inc _)
4fc7577b 852 }
23642f4b 853 my $udp = getprotobyname('udp');
854 if (!defined $udp) {
855 push(@{$errs}, "getprotobyname failed for udp");
856 return 0;
857 }
858 my $syslog = getservbyname('syslog','udp');
859 if (!defined $syslog) {
860 push(@{$errs}, "getservbyname failed for udp");
861 return 0;
862 }
863 my $this = sockaddr_in($syslog, INADDR_ANY);
864 my $that = sockaddr_in($syslog, inet_aton($host));
865 if (!$that) {
866 push(@{$errs}, "can't lookup $host");
867 return 0;
868 }
869 if (!socket(SYSLOG,AF_INET,SOCK_DGRAM,$udp)) {
870 push(@{$errs}, "udp socket: $!");
871 return 0;
872 }
60b8437d 873 if (!CORE::connect(SYSLOG,$that)) {
23642f4b 874 push(@{$errs}, "udp connect: $!");
875 return 0;
876 }
877 # We want to check that the UDP connect worked. However the only
878 # way to do that is to send a message and see if an ICMP is returned
879 _syslog_send_socket("");
880 if (!connection_ok()) {
881 push(@{$errs}, "udp connect: nobody listening");
882 return 0;
883 }
884 $syslog_send = \&_syslog_send_socket;
885 return 1;
886}
887
888sub connect_stream {
889 my ($errs) = @_;
890 # might want syslog_path to be variable based on syslog.h (if only
891 # it were in there!)
892 $syslog_path = '/dev/conslog';
893 if (!-w $syslog_path) {
894 push(@{$errs}, "stream $syslog_path is not writable");
895 return 0;
896 }
897 if (!open(SYSLOG, ">" . $syslog_path)) {
898 push(@{$errs}, "stream can't open $syslog_path: $!");
899 return 0;
900 }
901 $syslog_send = \&_syslog_send_stream;
902 return 1;
903}
904
905sub connect_unix {
906 my ($errs) = @_;
907 if (length _PATH_LOG()) {
908 $syslog_path = _PATH_LOG();
cb63fe9d 909 } else {
23642f4b 910 push(@{$errs}, "_PATH_LOG not available in syslog.h");
911 return 0;
912 }
913 my $that = sockaddr_un($syslog_path);
914 if (!$that) {
915 push(@{$errs}, "can't locate $syslog_path");
916 return 0;
917 }
918 if (!socket(SYSLOG,AF_UNIX,SOCK_STREAM,0)) {
919 push(@{$errs}, "unix stream socket: $!");
920 return 0;
921 }
60b8437d 922 if (!CORE::connect(SYSLOG,$that)) {
23642f4b 923 if (!socket(SYSLOG,AF_UNIX,SOCK_DGRAM,0)) {
924 push(@{$errs}, "unix dgram socket: $!");
925 return 0;
926 }
60b8437d 927 if (!CORE::connect(SYSLOG,$that)) {
23642f4b 928 push(@{$errs}, "unix dgram connect: $!");
929 return 0;
930 }
cb63fe9d 931 }
23642f4b 932 $syslog_send = \&_syslog_send_socket;
933 return 1;
934}
935
936sub connect_console {
937 my ($errs) = @_;
938 if (!-w '/dev/console') {
939 push(@{$errs}, "console is not writable");
940 return 0;
941 }
942 $syslog_send = \&_syslog_send_console;
943 return 1;
944}
945
946# to test if the connection is still good, we need to check if any
947# errors are present on the connection. The errors will not be raised
948# by a write. Instead, sockets are made readable and the next read
949# would cause the error to be returned. Unfortunately the syslog
950# 'protocol' never provides anything for us to read. But with
951# judicious use of select(), we can see if it would be readable...
952sub connection_ok {
dbfdd438 953 return 1 if (defined $current_proto && $current_proto eq 'console');
23642f4b 954 my $rin = '';
955 vec($rin, fileno(SYSLOG), 1) = 1;
956 my $ret = select $rin, undef, $rin, 0;
957 return ($ret ? 0 : 1);
a0d0e21e 958}
959
960sub disconnect {
a0d0e21e 961 $connected = 0;
23642f4b 962 $syslog_send = undef;
942974c1 963 return close SYSLOG;
a0d0e21e 964}
965
9661;