This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade Test-Simple from version 1.302101 to 1.302103
[perl5.git] / cpan / Sys-Syslog / Syslog.pm
CommitLineData
a0d0e21e 1package Sys::Syslog;
8168e71f 2use strict;
f93f88eb 3use warnings;
89c3c464 4use warnings::register;
8168e71f 5use Carp;
e57ea7c9
CBW
6use Config;
7use Exporter ();
07b7e4bc 8use File::Basename;
06fd9d7a
CBW
9use POSIX qw< strftime setlocale LC_TIME >;
10use Socket qw< :all >;
d329efa2 11require 5.005;
a0d0e21e 12
06fd9d7a 13
e57ea7c9
CBW
14*import = \&Exporter::import;
15
16
89c3c464 17{ no strict 'vars';
9f0af693 18 $VERSION = '0.35';
942974c1 19
89c3c464 20 %EXPORT_TAGS = (
4b035b3d
SP
21 standard => [qw(openlog syslog closelog setlogmask)],
22 extended => [qw(setlogsock)],
23 macros => [
24 # levels
25 qw(
26 LOG_ALERT LOG_CRIT LOG_DEBUG LOG_EMERG LOG_ERR
27 LOG_INFO LOG_NOTICE LOG_WARNING
28 ),
29
a650b841 30 # standard facilities
4b035b3d 31 qw(
a650b841
AT
32 LOG_AUTH LOG_AUTHPRIV LOG_CRON LOG_DAEMON LOG_FTP LOG_KERN
33 LOG_LOCAL0 LOG_LOCAL1 LOG_LOCAL2 LOG_LOCAL3 LOG_LOCAL4
34 LOG_LOCAL5 LOG_LOCAL6 LOG_LOCAL7 LOG_LPR LOG_MAIL LOG_NEWS
35 LOG_SYSLOG LOG_USER LOG_UUCP
36 ),
37 # Mac OS X specific facilities
38 qw( LOG_INSTALL LOG_LAUNCHD LOG_NETINFO LOG_RAS LOG_REMOTEAUTH ),
39 # modern BSD specific facilities
40 qw( LOG_CONSOLE LOG_NTP LOG_SECURITY ),
41 # IRIX specific facilities
42 qw( LOG_AUDIT LOG_LFMT ),
4b035b3d
SP
43
44 # options
45 qw(
46 LOG_CONS LOG_PID LOG_NDELAY LOG_NOWAIT LOG_ODELAY LOG_PERROR
47 ),
48
49 # others macros
50 qw(
51 LOG_FACMASK LOG_NFACILITIES LOG_PRIMASK
52 LOG_MASK LOG_UPTO
53 ),
54 ],
89c3c464 55 );
942974c1 56
89c3c464 57 @EXPORT = (
07b7e4bc 58 @{$EXPORT_TAGS{standard}},
89c3c464 59 );
942974c1 60
89c3c464 61 @EXPORT_OK = (
07b7e4bc
RGS
62 @{$EXPORT_TAGS{extended}},
63 @{$EXPORT_TAGS{macros}},
89c3c464
AT
64 );
65
66 eval {
67 require XSLoader;
68 XSLoader::load('Sys::Syslog', $VERSION);
69 1
70 } or do {
71 require DynaLoader;
72 push @ISA, 'DynaLoader';
73 bootstrap Sys::Syslog $VERSION;
74 };
75}
76
77
e57ea7c9
CBW
78#
79# Constants
80#
81use constant HAVE_GETPROTOBYNAME => $Config::Config{d_getpbyname};
82use constant HAVE_GETPROTOBYNUMBER => $Config::Config{d_getpbynumber};
83use constant HAVE_SETLOCALE => $Config::Config{d_setlocale};
84use constant HAVE_IPPROTO_TCP => defined &Socket::IPPROTO_TCP ? 1 : 0;
85use constant HAVE_IPPROTO_UDP => defined &Socket::IPPROTO_UDP ? 1 : 0;
86use constant HAVE_TCP_NODELAY => defined &Socket::TCP_NODELAY ? 1 : 0;
87
88use constant SOCKET_IPPROTO_TCP =>
89 HAVE_IPPROTO_TCP ? Socket::IPPROTO_TCP
90 : HAVE_GETPROTOBYNAME ? scalar getprotobyname("tcp")
91 : 6;
92
93use constant SOCKET_IPPROTO_UDP =>
94 HAVE_IPPROTO_UDP ? Socket::IPPROTO_UDP
95 : HAVE_GETPROTOBYNAME ? scalar getprotobyname("udp")
96 : 17;
97
98use constant SOCKET_TCP_NODELAY => HAVE_TCP_NODELAY ? Socket::TCP_NODELAY : 1;
99
100
89c3c464
AT
101#
102# Public variables
103#
a650b841 104use vars qw($host); # host to send syslog messages to (see notes at end)
89c3c464 105
f93f88eb
AT
106#
107# Prototypes
108#
109sub silent_eval (&);
110
89c3c464
AT
111#
112# Global variables
113#
a650b841 114use vars qw($facility);
06fd9d7a 115my $connected = 0; # flag to indicate if we're connected or not
89c3c464 116my $syslog_send; # coderef of the function used to send messages
06fd9d7a
CBW
117my $syslog_path = undef; # syslog path for "stream" and "unix" mechanisms
118my $syslog_xobj = undef; # if defined, holds the external object used to send messages
aaa7a444 119my $transmit_ok = 0; # flag to indicate if the last message was transmitted
06fd9d7a
CBW
120my $sock_port = undef; # socket port
121my $sock_timeout = 0; # socket timeout, see below
122my $current_proto = undef; # current mechanism used to transmit messages
123my $ident = ''; # identifiant prepended to each message
124$facility = ''; # current facility
125my $maskpri = LOG_UPTO(&LOG_DEBUG); # current log mask
89c3c464
AT
126
127my %options = (
128 ndelay => 0,
06fd9d7a 129 noeol => 0,
89c3c464 130 nofatal => 0,
06fd9d7a 131 nonul => 0,
89c3c464 132 nowait => 0,
35a209d1 133 perror => 0,
89c3c464 134 pid => 0,
942974c1 135);
a0d0e21e 136
a650b841 137# Default is now to first use the native mechanism, so Perl programs
d329efa2
AT
138# behave like other normal Unix programs, then try other mechanisms.
139my @connectMethods = qw(native tcp udp unix pipe stream console);
06fd9d7a 140if ($^O eq "freebsd" or $^O eq "linux") {
dbfdd438
SR
141 @connectMethods = grep { $_ ne 'udp' } @connectMethods;
142}
a650b841 143
f93f88eb
AT
144# And on Win32 systems, we try to use the native mechanism for this
145# platform, the events logger, available through Win32::EventLog.
26f266f7 146EVENTLOG: {
9f0af693 147 my $verbose_if_Win32 = $^O =~ /Win32/i;
a650b841 148
9f0af693 149 if (can_load_sys_syslog_win32($verbose_if_Win32)) {
26f266f7
AT
150 unshift @connectMethods, 'eventlog';
151 }
26f266f7 152}
35a209d1 153
23642f4b 154my @defaultMethods = @connectMethods;
89c3c464 155my @fallbackMethods = ();
8168e71f 156
f93f88eb
AT
157# The timeout in connection_ok() was pushed up to 0.25 sec in
158# Sys::Syslog v0.19 in order to address a heisenbug on MacOSX:
159# http://london.pm.org/pipermail/london.pm/Week-of-Mon-20061211/005961.html
160#
161# However, this also had the effect of slowing this test for
162# all other operating systems, which apparently impacted some
163# users (cf. CPAN-RT #34753). So, in order to make everybody
164# happy, the timeout is now zero by default on all systems
165# except on OSX where it is set to 250 msec, and can be set
166# with the infamous setlogsock() function.
0374b0a2
SH
167#
168# Update 2011-08: this issue is also been seen on multiprocessor
169# Debian GNU/kFreeBSD systems. See http://bugs.debian.org/627821
170# and https://rt.cpan.org/Ticket/Display.html?id=69997
171# Also, lowering the delay to 1 ms, which should be enough.
172
173$sock_timeout = 0.001 if $^O =~ /darwin|gnukfreebsd/;
f93f88eb 174
aaa7a444
CBW
175
176# Perl 5.6.0's warnings.pm doesn't have warnings::warnif()
177if (not defined &warnings::warnif) {
178 *warnings::warnif = sub {
179 goto &warnings::warn if warnings::enabled(__PACKAGE__)
180 }
181}
182
89c3c464
AT
183# coderef for a nicer handling of errors
184my $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
5be1dfc7 185
5be1dfc7 186
89c3c464
AT
187sub AUTOLOAD {
188 # This AUTOLOAD is used to 'autoload' constants from the constant()
189 # XS function.
190 no strict 'vars';
191 my $constname;
192 ($constname = $AUTOLOAD) =~ s/.*:://;
193 croak "Sys::Syslog::constant() not defined" if $constname eq 'constant';
194 my ($error, $val) = constant($constname);
a650b841 195 croak $error if $error;
89c3c464
AT
196 no strict 'refs';
197 *$AUTOLOAD = sub { $val };
198 goto &$AUTOLOAD;
199}
5be1dfc7 200
5be1dfc7 201
89c3c464
AT
202sub openlog {
203 ($ident, my $logopt, $facility) = @_;
8168e71f 204
a650b841
AT
205 # default values
206 $ident ||= basename($0) || getlogin() || getpwuid($<) || 'syslog';
207 $logopt ||= '';
208 $facility ||= LOG_USER();
209
89c3c464
AT
210 for my $opt (split /\b/, $logopt) {
211 $options{$opt} = 1 if exists $options{$opt}
212 }
5be1dfc7 213
f93f88eb 214 $err_sub = delete $options{nofatal} ? \&warnings::warnif : \&croak;
89c3c464
AT
215 return 1 unless $options{ndelay};
216 connect_log();
217}
5be1dfc7 218
89c3c464 219sub closelog {
06fd9d7a
CBW
220 disconnect_log() if $connected;
221 $options{$_} = 0 for keys %options;
222 $facility = $ident = "";
223 $connected = 0;
224 return 1
89c3c464 225}
8168e71f 226
89c3c464
AT
227sub setlogmask {
228 my $oldmask = $maskpri;
229 $maskpri = shift unless $_[0] == 0;
230 $oldmask;
231}
f93f88eb 232
a650b841 233
06fd9d7a
CBW
234my %mechanism = (
235 console => {
236 check => sub { 1 },
237 },
238 eventlog => {
9f0af693 239 check => sub { return can_load_sys_syslog_win32() },
06fd9d7a
CBW
240 err_msg => "no Win32 API available",
241 },
242 inet => {
243 check => sub { 1 },
244 },
245 native => {
246 check => sub { 1 },
247 },
248 pipe => {
249 check => sub {
250 ($syslog_path) = grep { defined && length && -p && -w _ }
251 $syslog_path, &_PATH_LOG, "/dev/log";
252 return $syslog_path ? 1 : 0
253 },
254 err_msg => "path not available",
255 },
256 stream => {
257 check => sub {
a650b841 258 if (not defined $syslog_path) {
06fd9d7a
CBW
259 my @try = qw(/dev/log /dev/conslog);
260 unshift @try, &_PATH_LOG if length &_PATH_LOG;
261 ($syslog_path) = grep { -w } @try;
a650b841 262 }
06fd9d7a
CBW
263 return defined $syslog_path && -w $syslog_path
264 },
265 err_msg => "could not find any writable device",
266 },
267 tcp => {
268 check => sub {
33f804f6
SH
269 return 1 if defined $sock_port;
270
e57ea7c9
CBW
271 if (eval { local $SIG{__DIE__};
272 getservbyname('syslog','tcp') || getservbyname('syslogng','tcp')
273 }) {
06fd9d7a
CBW
274 $host = $syslog_path;
275 return 1
276 }
277 else {
278 return
279 }
280 },
281 err_msg => "TCP service unavailable",
282 },
283 udp => {
284 check => sub {
33f804f6
SH
285 return 1 if defined $sock_port;
286
e57ea7c9 287 if (eval { local $SIG{__DIE__}; getservbyname('syslog', 'udp') }) {
06fd9d7a
CBW
288 $host = $syslog_path;
289 return 1
290 }
291 else {
292 return
293 }
294 },
295 err_msg => "UDP service unavailable",
296 },
297 unix => {
298 check => sub {
299 my @try = ($syslog_path, &_PATH_LOG);
300 ($syslog_path) = grep { defined && length && -w } @try;
301 return defined $syslog_path && -w $syslog_path
302 },
303 err_msg => "path not available",
304 },
305);
306
307sub setlogsock {
308 my %opt;
309
310 # handle arguments
311 # - old API: setlogsock($sock_type, $sock_path, $sock_timeout)
312 # - new API: setlogsock(\%options)
313 croak "setlogsock(): Invalid number of arguments"
314 unless @_ >= 1 and @_ <= 3;
315
316 if (my $ref = ref $_[0]) {
317 if ($ref eq "HASH") {
318 %opt = %{ $_[0] };
319 croak "setlogsock(): No argument given" unless keys %opt;
89c3c464 320 }
06fd9d7a
CBW
321 elsif ($ref eq "ARRAY") {
322 @opt{qw< type path timeout >} = @_;
d329efa2 323 }
06fd9d7a
CBW
324 else {
325 croak "setlogsock(): Unexpected \L$ref\E reference"
a650b841 326 }
06fd9d7a
CBW
327 }
328 else {
329 @opt{qw< type path timeout >} = @_;
330 }
8168e71f 331
0374b0a2 332 # check socket type, remove invalid ones
06fd9d7a
CBW
333 my $diag_invalid_type = "setlogsock(): Invalid type%s; must be one of "
334 . join ", ", map { "'$_'" } sort keys %mechanism;
335 croak sprintf $diag_invalid_type, "" unless defined $opt{type};
336 my @sock_types = ref $opt{type} eq "ARRAY" ? @{$opt{type}} : ($opt{type});
337 my @tmp;
338
339 for my $sock_type (@sock_types) {
340 carp sprintf $diag_invalid_type, " '$sock_type'" and next
341 unless exists $mechanism{$sock_type};
342 push @tmp, "tcp", "udp" and next if $sock_type eq "inet";
343 push @tmp, $sock_type;
344 }
942974c1 345
06fd9d7a 346 @sock_types = @tmp;
942974c1 347
06fd9d7a
CBW
348 # set global options
349 $syslog_path = $opt{path} if defined $opt{path};
350 $host = $opt{host} if defined $opt{host};
351 $sock_timeout = $opt{timeout} if defined $opt{timeout};
352 $sock_port = $opt{port} if defined $opt{port};
942974c1 353
06fd9d7a
CBW
354 disconnect_log() if $connected;
355 $transmit_ok = 0;
356 @fallbackMethods = ();
0374b0a2
SH
357 @connectMethods = ();
358 my $found = 0;
942974c1 359
0374b0a2 360 # check each given mechanism and test if it can be used on the current system
06fd9d7a
CBW
361 for my $sock_type (@sock_types) {
362 if ( $mechanism{$sock_type}{check}->() ) {
0374b0a2
SH
363 push @connectMethods, $sock_type;
364 $found = 1;
06fd9d7a
CBW
365 }
366 else {
aaa7a444
CBW
367 warnings::warnif("setlogsock(): type='$sock_type': "
368 . $mechanism{$sock_type}{err_msg});
06fd9d7a 369 }
89c3c464 370 }
942974c1 371
0374b0a2
SH
372 # if no mechanism worked from the given ones, use the default ones
373 @connectMethods = @defaultMethods unless @connectMethods;
374
375 return $found;
89c3c464 376}
942974c1 377
89c3c464 378sub syslog {
aaa7a444 379 my ($priority, $mask, @args) = @_;
89c3c464
AT
380 my ($message, $buf);
381 my (@words, $num, $numpri, $numfac, $sum);
382 my $failed = undef;
383 my $fail_time = undef;
8edeb3ad 384 my $error = $!;
8168e71f 385
a650b841
AT
386 # if $ident is undefined, it means openlog() wasn't previously called
387 # so do it now in order to have sensible defaults
388 openlog() unless $ident;
389
390 local $facility = $facility; # may need to change temporarily.
8168e71f 391
89c3c464
AT
392 croak "syslog: expecting argument \$priority" unless defined $priority;
393 croak "syslog: expecting argument \$format" unless defined $mask;
5be1dfc7 394
06fd9d7a
CBW
395 if ($priority =~ /^\d+$/) {
396 $numpri = LOG_PRI($priority);
0374b0a2 397 $numfac = LOG_FAC($priority) << 3;
e57ea7c9 398 undef $numfac if $numfac == 0; # no facility given => use default
06fd9d7a
CBW
399 }
400 elsif ($priority =~ /^\w+/) {
401 # Allow "level" or "level|facility".
402 @words = split /\W+/, $priority, 2;
5be1dfc7 403
06fd9d7a
CBW
404 undef $numpri;
405 undef $numfac;
f93f88eb 406
06fd9d7a
CBW
407 for my $word (@words) {
408 next if length $word == 0;
f93f88eb 409
06fd9d7a
CBW
410 # Translate word to number.
411 $num = xlate($word);
412
413 if ($num < 0) {
414 croak "syslog: invalid level/facility: $word"
415 }
0374b0a2 416 elsif ($num <= LOG_PRIMASK() and $word ne "kern") {
06fd9d7a
CBW
417 croak "syslog: too many levels given: $word"
418 if defined $numpri;
419 $numpri = $num;
06fd9d7a
CBW
420 }
421 else {
422 croak "syslog: too many facilities given: $word"
423 if defined $numfac;
424 $facility = $word if $word =~ /^[A-Za-z]/;
0374b0a2 425 $numfac = $num;
06fd9d7a 426 }
f93f88eb 427 }
89c3c464 428 }
06fd9d7a
CBW
429 else {
430 croak "syslog: invalid level/facility: $priority"
431 }
5be1dfc7 432
89c3c464 433 croak "syslog: level must be given" unless defined $numpri;
942974c1 434
0374b0a2
SH
435 # don't log if priority is below mask level
436 return 0 unless LOG_MASK($numpri) & $maskpri;
437
89c3c464
AT
438 if (not defined $numfac) { # Facility not specified in this call.
439 $facility = 'user' unless $facility;
440 $numfac = xlate($facility);
441 }
3d256c0f 442
89c3c464 443 connect_log() unless $connected;
8168e71f 444
89c3c464 445 if ($mask =~ /%m/) {
07b7e4bc 446 # escape percent signs for sprintf()
aaa7a444 447 $error =~ s/%/%%/g if @args;
a650b841 448 # replace %m with $error, if preceded by an even number of percent signs
8edeb3ad 449 $mask =~ s/(?<!%)((?:%%)*)%m/$1$error/g;
89c3c464 450 }
5be1dfc7 451
e57ea7c9
CBW
452 # add (or not) a newline
453 $mask .= "\n" if !$options{noeol} and rindex($mask, "\n") == -1;
aaa7a444 454 $message = @args ? sprintf($mask, @args) : $mask;
942974c1 455
d329efa2 456 if ($current_proto eq 'native') {
89c3c464 457 $buf = $message;
a650b841
AT
458 }
459 elsif ($current_proto eq 'eventlog') {
460 $buf = $message;
461 }
462 else {
89c3c464 463 my $whoami = $ident;
89c3c464 464 $whoami .= "[$$]" if $options{pid};
942974c1 465
89c3c464 466 $sum = $numpri + $numfac;
e57ea7c9
CBW
467
468 my $oldlocale;
469 if (HAVE_SETLOCALE) {
470 $oldlocale = setlocale(LC_TIME);
471 setlocale(LC_TIME, 'C');
472 }
473
474 # %e format isn't available on all systems (Win32, cf. CPAN RT #69310)
475 my $day = strftime "%e", localtime;
476
477 if (index($day, "%") == 0) {
478 $day = strftime "%d", localtime;
479 $day =~ s/^0/ /;
480 }
481
482 my $timestamp = strftime "%b $day %H:%M:%S", localtime;
483 setlocale(LC_TIME, $oldlocale) if HAVE_SETLOCALE;
06fd9d7a
CBW
484
485 # construct the stream that will be transmitted
486 $buf = "<$sum>$timestamp $whoami: $message";
487
06fd9d7a
CBW
488 # add (or not) a NUL character
489 $buf .= "\0" if !$options{nonul};
89c3c464 490 }
942974c1 491
35a209d1
AT
492 # handle PERROR option
493 # "native" mechanism already handles it by itself
494 if ($options{perror} and $current_proto ne 'native') {
35a209d1
AT
495 my $whoami = $ident;
496 $whoami .= "[$$]" if $options{pid};
e57ea7c9
CBW
497 print STDERR "$whoami: $message";
498 print STDERR "\n" if rindex($message, "\n") == -1;
35a209d1
AT
499 }
500
89c3c464
AT
501 # it's possible that we'll get an error from sending
502 # (e.g. if method is UDP and there is no UDP listener,
503 # then we'll get ECONNREFUSED on the send). So what we
504 # want to do at this point is to fallback onto a different
505 # connection method.
506 while (scalar @fallbackMethods || $syslog_send) {
507 if ($failed && (time - $fail_time) > 60) {
508 # it's been a while... maybe things have been fixed
509 @fallbackMethods = ();
510 disconnect_log();
511 $transmit_ok = 0; # make it look like a fresh attempt
512 connect_log();
513 }
942974c1 514
89c3c464
AT
515 if ($connected && !connection_ok()) {
516 # Something was OK, but has now broken. Remember coz we'll
517 # want to go back to what used to be OK.
518 $failed = $current_proto unless $failed;
519 $fail_time = time;
520 disconnect_log();
521 }
942974c1 522
89c3c464
AT
523 connect_log() unless $connected;
524 $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
942974c1 525
89c3c464 526 if ($syslog_send) {
a650b841 527 if ($syslog_send->($buf, $numpri, $numfac)) {
89c3c464
AT
528 $transmit_ok++;
529 return 1;
530 }
531 # typically doesn't happen, since errors are rare from write().
532 disconnect_log();
533 }
534 }
535 # could not send, could not fallback onto a working
536 # connection method. Lose.
537 return 0;
538}
942974c1 539
89c3c464
AT
540sub _syslog_send_console {
541 my ($buf) = @_;
06fd9d7a 542
89c3c464
AT
543 # The console print is a method which could block
544 # so we do it in a child process and always return success
545 # to the caller.
546 if (my $pid = fork) {
942974c1 547
89c3c464
AT
548 if ($options{nowait}) {
549 return 1;
550 } else {
551 if (waitpid($pid, 0) >= 0) {
552 return ($? >> 8);
553 } else {
554 # it's possible that the caller has other
555 # plans for SIGCHLD, so let's not interfere
556 return 1;
557 }
558 }
559 } else {
560 if (open(CONS, ">/dev/console")) {
561 my $ret = print CONS $buf . "\r"; # XXX: should this be \x0A ?
848ca32c 562 POSIX::_exit($ret) if defined $pid;
89c3c464
AT
563 close CONS;
564 }
06fd9d7a 565
848ca32c 566 POSIX::_exit(0) if defined $pid;
89c3c464
AT
567 }
568}
942974c1 569
89c3c464
AT
570sub _syslog_send_stream {
571 my ($buf) = @_;
572 # XXX: this only works if the OS stream implementation makes a write
573 # look like a putmsg() with simple header. For instance it works on
574 # Solaris 8 but not Solaris 7.
575 # To be correct, it should use a STREAMS API, but perl doesn't have one.
576 return syswrite(SYSLOG, $buf, length($buf));
577}
942974c1 578
d329efa2
AT
579sub _syslog_send_pipe {
580 my ($buf) = @_;
581 return print SYSLOG $buf;
582}
583
89c3c464
AT
584sub _syslog_send_socket {
585 my ($buf) = @_;
586 return syswrite(SYSLOG, $buf, length($buf));
587 #return send(SYSLOG, $buf, 0);
588}
942974c1 589
89c3c464 590sub _syslog_send_native {
06fd9d7a
CBW
591 my ($buf, $numpri, $numfac) = @_;
592 syslog_xs($numpri|$numfac, $buf);
a650b841 593 return 1;
89c3c464 594}
ce43db9b 595
5be1dfc7 596
89c3c464
AT
597# xlate()
598# -----
599# private function to translate names to numeric values
600#
601sub xlate {
f93f88eb
AT
602 my ($name) = @_;
603
89c3c464
AT
604 return $name+0 if $name =~ /^\s*\d+\s*$/;
605 $name = uc $name;
606 $name = "LOG_$name" unless $name =~ /^LOG_/;
2605937c
AT
607
608 # ExtUtils::Constant 0.20 introduced a new way to implement
609 # constants, called ProxySubs. When it was used to generate
610 # the C code, the constant() function no longer returns the
611 # correct value. Therefore, we first try a direct call to
612 # constant(), and if the value is an error we try to call the
613 # constant by its full name.
f93f88eb 614 my $value = constant($name);
2605937c
AT
615
616 if (index($value, "not a valid") >= 0) {
617 $name = "Sys::Syslog::$name";
618 $value = eval { no strict "refs"; &$name };
619 $value = $@ unless defined $value;
620 }
621
622 $value = -1 if index($value, "not a valid") >= 0;
f93f88eb 623
35a209d1 624 return defined $value ? $value : -1;
89c3c464 625}
5be1dfc7 626
942974c1 627
89c3c464
AT
628# connect_log()
629# -----------
630# This function acts as a kind of front-end: it tries to connect to
631# a syslog service using the selected methods, trying each one in the
632# selected order.
633#
634sub connect_log {
635 @fallbackMethods = @connectMethods unless scalar @fallbackMethods;
07b7e4bc 636
89c3c464
AT
637 if ($transmit_ok && $current_proto) {
638 # Retry what we were on, because it has worked in the past.
639 unshift(@fallbackMethods, $current_proto);
640 }
07b7e4bc 641
89c3c464
AT
642 $connected = 0;
643 my @errs = ();
644 my $proto = undef;
07b7e4bc 645
89c3c464
AT
646 while ($proto = shift @fallbackMethods) {
647 no strict 'refs';
648 my $fn = "connect_$proto";
649 $connected = &$fn(\@errs) if defined &$fn;
650 last if $connected;
651 }
3d256c0f 652
89c3c464
AT
653 $transmit_ok = 0;
654 if ($connected) {
655 $current_proto = $proto;
a650b841 656 my ($old) = select(SYSLOG); $| = 1; select($old);
89c3c464
AT
657 } else {
658 @fallbackMethods = ();
659 $err_sub->(join "\n\t- ", "no connection to syslog available", @errs);
660 return undef;
661 }
662}
942974c1 663
89c3c464
AT
664sub connect_tcp {
665 my ($errs) = @_;
4b035b3d 666
e57ea7c9
CBW
667 my $port = $sock_port
668 || eval { local $SIG{__DIE__}; getservbyname('syslog', 'tcp') }
669 || eval { local $SIG{__DIE__}; getservbyname('syslogng', 'tcp') };
06fd9d7a 670 if (!defined $port) {
89c3c464
AT
671 push @$errs, "getservbyname failed for syslog/tcp and syslogng/tcp";
672 return 0;
673 }
942974c1 674
4b035b3d 675 my $addr;
89c3c464 676 if (defined $host) {
4b035b3d
SP
677 $addr = inet_aton($host);
678 if (!$addr) {
89c3c464
AT
679 push @$errs, "can't lookup $host";
680 return 0;
681 }
682 } else {
4b035b3d 683 $addr = INADDR_LOOPBACK;
89c3c464 684 }
06fd9d7a 685 $addr = sockaddr_in($port, $addr);
942974c1 686
e57ea7c9 687 if (!socket(SYSLOG, AF_INET, SOCK_STREAM, SOCKET_IPPROTO_TCP)) {
89c3c464
AT
688 push @$errs, "tcp socket: $!";
689 return 0;
690 }
a650b841 691
89c3c464 692 setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
e57ea7c9
CBW
693 setsockopt(SYSLOG, SOCKET_IPPROTO_TCP, SOCKET_TCP_NODELAY, 1);
694
4b035b3d 695 if (!connect(SYSLOG, $addr)) {
89c3c464
AT
696 push @$errs, "tcp connect: $!";
697 return 0;
698 }
4b035b3d 699
89c3c464 700 $syslog_send = \&_syslog_send_socket;
4b035b3d 701
89c3c464
AT
702 return 1;
703}
942974c1 704
89c3c464
AT
705sub connect_udp {
706 my ($errs) = @_;
4b035b3d 707
e57ea7c9
CBW
708 my $port = $sock_port
709 || eval { local $SIG{__DIE__}; getservbyname('syslog', 'udp') };
06fd9d7a 710 if (!defined $port) {
89c3c464
AT
711 push @$errs, "getservbyname failed for syslog/udp";
712 return 0;
713 }
4b035b3d
SP
714
715 my $addr;
89c3c464 716 if (defined $host) {
4b035b3d
SP
717 $addr = inet_aton($host);
718 if (!$addr) {
89c3c464
AT
719 push @$errs, "can't lookup $host";
720 return 0;
721 }
722 } else {
4b035b3d 723 $addr = INADDR_LOOPBACK;
89c3c464 724 }
06fd9d7a 725 $addr = sockaddr_in($port, $addr);
942974c1 726
e57ea7c9 727 if (!socket(SYSLOG, AF_INET, SOCK_DGRAM, SOCKET_IPPROTO_UDP)) {
89c3c464
AT
728 push @$errs, "udp socket: $!";
729 return 0;
730 }
4b035b3d 731 if (!connect(SYSLOG, $addr)) {
89c3c464
AT
732 push @$errs, "udp connect: $!";
733 return 0;
734 }
4b035b3d 735
89c3c464
AT
736 # We want to check that the UDP connect worked. However the only
737 # way to do that is to send a message and see if an ICMP is returned
738 _syslog_send_socket("");
739 if (!connection_ok()) {
740 push @$errs, "udp connect: nobody listening";
741 return 0;
742 }
4b035b3d 743
89c3c464 744 $syslog_send = \&_syslog_send_socket;
4b035b3d 745
89c3c464
AT
746 return 1;
747}
9903e4c8 748
89c3c464
AT
749sub connect_stream {
750 my ($errs) = @_;
751 # might want syslog_path to be variable based on syslog.h (if only
752 # it were in there!)
8edeb3ad 753 $syslog_path = '/dev/conslog' unless defined $syslog_path;
848ca32c 754
89c3c464
AT
755 if (!-w $syslog_path) {
756 push @$errs, "stream $syslog_path is not writable";
757 return 0;
758 }
848ca32c
CBW
759
760 require Fcntl;
761
762 if (!sysopen(SYSLOG, $syslog_path, Fcntl::O_WRONLY(), 0400)) {
89c3c464
AT
763 push @$errs, "stream can't open $syslog_path: $!";
764 return 0;
765 }
848ca32c 766
89c3c464 767 $syslog_send = \&_syslog_send_stream;
848ca32c 768
89c3c464
AT
769 return 1;
770}
942974c1 771
d329efa2
AT
772sub connect_pipe {
773 my ($errs) = @_;
774
775 $syslog_path ||= &_PATH_LOG || "/dev/log";
776
777 if (not -w $syslog_path) {
778 push @$errs, "$syslog_path is not writable";
779 return 0;
780 }
781
782 if (not open(SYSLOG, ">$syslog_path")) {
783 push @$errs, "can't write to $syslog_path: $!";
784 return 0;
785 }
786
787 $syslog_send = \&_syslog_send_pipe;
788
789 return 1;
790}
791
89c3c464
AT
792sub connect_unix {
793 my ($errs) = @_;
4b035b3d
SP
794
795 $syslog_path ||= _PATH_LOG() if length _PATH_LOG();
796
797 if (not defined $syslog_path) {
798 push @$errs, "_PATH_LOG not available in syslog.h and no user-supplied socket path";
89c3c464
AT
799 return 0;
800 }
4b035b3d 801
35a209d1 802 if (not (-S $syslog_path or -c _)) {
89c3c464
AT
803 push @$errs, "$syslog_path is not a socket";
804 return 0;
805 }
4b035b3d
SP
806
807 my $addr = sockaddr_un($syslog_path);
808 if (!$addr) {
89c3c464
AT
809 push @$errs, "can't locate $syslog_path";
810 return 0;
811 }
4b035b3d 812 if (!socket(SYSLOG, AF_UNIX, SOCK_STREAM, 0)) {
89c3c464
AT
813 push @$errs, "unix stream socket: $!";
814 return 0;
815 }
a650b841 816
4b035b3d
SP
817 if (!connect(SYSLOG, $addr)) {
818 if (!socket(SYSLOG, AF_UNIX, SOCK_DGRAM, 0)) {
89c3c464
AT
819 push @$errs, "unix dgram socket: $!";
820 return 0;
821 }
4b035b3d 822 if (!connect(SYSLOG, $addr)) {
89c3c464
AT
823 push @$errs, "unix dgram connect: $!";
824 return 0;
825 }
826 }
4b035b3d 827
89c3c464 828 $syslog_send = \&_syslog_send_socket;
4b035b3d 829
89c3c464
AT
830 return 1;
831}
942974c1 832
89c3c464
AT
833sub connect_native {
834 my ($errs) = @_;
835 my $logopt = 0;
5be1dfc7 836
89c3c464
AT
837 # reconstruct the numeric equivalent of the options
838 for my $opt (keys %options) {
839 $logopt += xlate($opt) if $options{$opt}
840 }
942974c1 841
f93f88eb 842 openlog_xs($ident, $logopt, xlate($facility));
89c3c464 843 $syslog_send = \&_syslog_send_native;
942974c1 844
89c3c464
AT
845 return 1;
846}
6e4ef777 847
a650b841
AT
848sub connect_eventlog {
849 my ($errs) = @_;
850
851 $syslog_xobj = Sys::Syslog::Win32::_install();
852 $syslog_send = \&Sys::Syslog::Win32::_syslog_send;
853
854 return 1;
855}
856
89c3c464
AT
857sub connect_console {
858 my ($errs) = @_;
859 if (!-w '/dev/console') {
860 push @$errs, "console is not writable";
861 return 0;
862 }
863 $syslog_send = \&_syslog_send_console;
864 return 1;
865}
6e4ef777 866
a650b841 867# To test if the connection is still good, we need to check if any
89c3c464
AT
868# errors are present on the connection. The errors will not be raised
869# by a write. Instead, sockets are made readable and the next read
870# would cause the error to be returned. Unfortunately the syslog
871# 'protocol' never provides anything for us to read. But with
872# judicious use of select(), we can see if it would be readable...
873sub connection_ok {
874 return 1 if defined $current_proto and (
875 $current_proto eq 'native' or $current_proto eq 'console'
a650b841 876 or $current_proto eq 'eventlog'
89c3c464 877 );
a650b841 878
89c3c464
AT
879 my $rin = '';
880 vec($rin, fileno(SYSLOG), 1) = 1;
f93f88eb 881 my $ret = select $rin, undef, $rin, $sock_timeout;
89c3c464
AT
882 return ($ret ? 0 : 1);
883}
942974c1 884
89c3c464
AT
885sub disconnect_log {
886 $connected = 0;
887 $syslog_send = undef;
942974c1 888
a650b841
AT
889 if (defined $current_proto and $current_proto eq 'native') {
890 closelog_xs();
06fd9d7a
CBW
891 unshift @fallbackMethods, $current_proto;
892 $current_proto = undef;
a650b841
AT
893 return 1;
894 }
895 elsif (defined $current_proto and $current_proto eq 'eventlog') {
896 $syslog_xobj->Close();
06fd9d7a
CBW
897 unshift @fallbackMethods, $current_proto;
898 $current_proto = undef;
89c3c464
AT
899 return 1;
900 }
6e4ef777 901
89c3c464
AT
902 return close SYSLOG;
903}
6e4ef777 904
f93f88eb
AT
905
906#
9f0af693
SH
907# Wrappers around eval() that makes sure that nobody, ever knows that
908# we wanted to poke & test if something was here or not. This is needed
909# because some applications are trying to be too smart, install their
910# own __DIE__ handler, and mysteriously, things are starting to fail
911# when they shouldn't. SpamAssassin among them.
f93f88eb
AT
912#
913sub silent_eval (&) {
914 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
2605937c 915 return eval { $_[0]->() }
f93f88eb
AT
916}
917
9f0af693
SH
918sub can_load_sys_syslog_win32 {
919 my ($verbose) = @_;
f93f88eb 920 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
9f0af693
SH
921 (my $module_path = __FILE__) =~ s:Syslog.pm$:Syslog/Win32.pm:;
922 my $loaded = eval { require $module_path } ? 1 : 0;
06fd9d7a
CBW
923 warn $@ if not $loaded and $verbose;
924 return $loaded
f93f88eb
AT
925}
926
927
928"Eighth Rule: read the documentation."
942974c1 929
89c3c464 930__END__
5be1dfc7 931
89c3c464 932=head1 NAME
8168e71f 933
89c3c464 934Sys::Syslog - Perl interface to the UNIX syslog(3) calls
3ffabb8c 935
89c3c464 936=head1 VERSION
3ffabb8c 937
9f0af693 938This is the documentation of version 0.35
23642f4b 939
89c3c464 940=head1 SYNOPSIS
cb63fe9d 941
06fd9d7a
CBW
942 use Sys::Syslog; # all except setlogsock()
943 use Sys::Syslog qw(:standard :macros); # standard functions & macros
23642f4b 944
06fd9d7a
CBW
945 openlog($ident, $logopt, $facility); # don't forget this
946 syslog($priority, $format, @args);
947 $oldmask = setlogmask($mask_priority);
948 closelog();
cb63fe9d 949
942974c1 950
89c3c464 951=head1 DESCRIPTION
5be1dfc7 952
89c3c464
AT
953C<Sys::Syslog> is an interface to the UNIX C<syslog(3)> program.
954Call C<syslog()> with a string priority and a list of C<printf()> args
955just like C<syslog(3)>.
5be1dfc7 956
5be1dfc7 957
89c3c464 958=head1 EXPORTS
5be1dfc7 959
89c3c464 960C<Sys::Syslog> exports the following C<Exporter> tags:
5be1dfc7 961
89c3c464
AT
962=over 4
963
964=item *
965
966C<:standard> exports the standard C<syslog(3)> functions:
967
968 openlog closelog setlogmask syslog
969
970=item *
971
972C<:extended> exports the Perl specific functions for C<syslog(3)>:
973
974 setlogsock
975
976=item *
977
978C<:macros> exports the symbols corresponding to most of your C<syslog(3)>
979macros and the C<LOG_UPTO()> and C<LOG_MASK()> functions.
980See L<"CONSTANTS"> for the supported constants and their meaning.
981
982=back
983
984By default, C<Sys::Syslog> exports the symbols from the C<:standard> tag.
985
986
987=head1 FUNCTIONS
988
989=over 4
990
991=item B<openlog($ident, $logopt, $facility)>
992
993Opens the syslog.
994C<$ident> is prepended to every message. C<$logopt> contains zero or
995more of the options detailed below. C<$facility> specifies the part
996of the system to report about, for example C<LOG_USER> or C<LOG_LOCAL0>:
997see L<"Facilities"> for a list of well-known facilities, and your
998C<syslog(3)> documentation for the facilities available in your system.
999Check L<"SEE ALSO"> for useful links. Facility can be given as a string
1000or a numeric macro.
1001
1002This function will croak if it can't connect to the syslog daemon.
1003
1004Note that C<openlog()> now takes three arguments, just like C<openlog(3)>.
1005
1006B<You should use C<openlog()> before calling C<syslog()>.>
1007
1008B<Options>
1009
1010=over 4
1011
1012=item *
1013
1014C<cons> - This option is ignored, since the failover mechanism will drop
1015down to the console automatically if all other media fail.
1016
1017=item *
1018
1019C<ndelay> - Open the connection immediately (normally, the connection is
1020opened when the first message is logged).
1021
1022=item *
1023
06fd9d7a 1024C<noeol> - When set to true, no end of line character (C<\n>) will be
9f0af693
SH
1025appended to the message. This can be useful for some syslog daemons.
1026Added in C<Sys::Syslog> 0.29.
06fd9d7a
CBW
1027
1028=item *
1029
89c3c464
AT
1030C<nofatal> - When set to true, C<openlog()> and C<syslog()> will only
1031emit warnings instead of dying if the connection to the syslog can't
9f0af693 1032be established. Added in C<Sys::Syslog> 0.15.
89c3c464
AT
1033
1034=item *
1035
06fd9d7a 1036C<nonul> - When set to true, no C<NUL> character (C<\0>) will be
9f0af693
SH
1037appended to the message. This can be useful for some syslog daemons.
1038Added in C<Sys::Syslog> 0.29.
06fd9d7a
CBW
1039
1040=item *
1041
89c3c464
AT
1042C<nowait> - Don't wait for child processes that may have been created
1043while logging the message. (The GNU C library does not create a child
1044process, so this option has no effect on Linux.)
1045
1046=item *
1047
35a209d1 1048C<perror> - Write the message to standard error output as well to the
9f0af693 1049system log. Added in C<Sys::Syslog> 0.22.
35a209d1
AT
1050
1051=item *
1052
89c3c464
AT
1053C<pid> - Include PID with each message.
1054
1055=back
1056
1057B<Examples>
1058
1059Open the syslog with options C<ndelay> and C<pid>, and with facility C<LOCAL0>:
1060
1061 openlog($name, "ndelay,pid", "local0");
1062
1063Same thing, but this time using the macro corresponding to C<LOCAL0>:
1064
1065 openlog($name, "ndelay,pid", LOG_LOCAL0);
1066
1067
1068=item B<syslog($priority, $message)>
1069
1070=item B<syslog($priority, $format, @args)>
1071
1072If C<$priority> permits, logs C<$message> or C<sprintf($format, @args)>
1073with the addition that C<%m> in $message or C<$format> is replaced with
1074C<"$!"> (the latest error message).
1075
1076C<$priority> can specify a level, or a level and a facility. Levels and
a650b841
AT
1077facilities can be given as strings or as macros. When using the C<eventlog>
1078mechanism, priorities C<DEBUG> and C<INFO> are mapped to event type
06fd9d7a 1079C<informational>, C<NOTICE> and C<WARNING> to C<warning> and C<ERR> to
a650b841 1080C<EMERG> to C<error>.
89c3c464
AT
1081
1082If you didn't use C<openlog()> before using C<syslog()>, C<syslog()> will
1083try to guess the C<$ident> by extracting the shortest prefix of
1084C<$format> that ends in a C<":">.
1085
1086B<Examples>
1087
06fd9d7a
CBW
1088 # informational level
1089 syslog("info", $message);
1090 syslog(LOG_INFO, $message);
89c3c464 1091
06fd9d7a
CBW
1092 # information level, Local0 facility
1093 syslog("info|local0", $message);
1094 syslog(LOG_INFO|LOG_LOCAL0, $message);
89c3c464
AT
1095
1096=over 4
1097
1098=item B<Note>
1099
1100C<Sys::Syslog> version v0.07 and older passed the C<$message> as the
1101formatting string to C<sprintf()> even when no formatting arguments
1102were provided. If the code calling C<syslog()> might execute with
1103older versions of this module, make sure to call the function as
1104C<syslog($priority, "%s", $message)> instead of C<syslog($priority,
1105$message)>. This protects against hostile formatting sequences that
1106might show up if $message contains tainted data.
1107
1108=back
1109
1110
1111=item B<setlogmask($mask_priority)>
1112
1113Sets the log mask for the current process to C<$mask_priority> and
1114returns the old mask. If the mask argument is 0, the current log mask
1115is not modified. See L<"Levels"> for the list of available levels.
1116You can use the C<LOG_UPTO()> function to allow all levels up to a
1117given priority (but it only accept the numeric macros as arguments).
1118
1119B<Examples>
1120
1121Only log errors:
1122
1123 setlogmask( LOG_MASK(LOG_ERR) );
1124
1125Log everything except informational messages:
1126
1127 setlogmask( ~(LOG_MASK(LOG_INFO)) );
1128
1129Log critical messages, errors and warnings:
1130
06fd9d7a
CBW
1131 setlogmask( LOG_MASK(LOG_CRIT)
1132 | LOG_MASK(LOG_ERR)
1133 | LOG_MASK(LOG_WARNING) );
89c3c464
AT
1134
1135Log all messages up to debug:
1136
1137 setlogmask( LOG_UPTO(LOG_DEBUG) );
1138
1139
06fd9d7a
CBW
1140=item B<setlogsock()>
1141
1142Sets the socket type and options to be used for the next call to C<openlog()>
1143or C<syslog()>. Returns true on success, C<undef> on failure.
89c3c464 1144
06fd9d7a
CBW
1145Being Perl-specific, this function has evolved along time. It can currently
1146be called as follow:
89c3c464 1147
06fd9d7a
CBW
1148=over
1149
1150=item *
1151
1152C<setlogsock($sock_type)>
1153
1154=item *
1155
1156C<setlogsock($sock_type, $stream_location)> (added in Perl 5.004_02)
1157
1158=item *
1159
1160C<setlogsock($sock_type, $stream_location, $sock_timeout)> (added in
1161C<Sys::Syslog> 0.25)
1162
1163=item *
1164
1165C<setlogsock(\%options)> (added in C<Sys::Syslog> 0.28)
1166
1167=back
f93f88eb 1168
06fd9d7a
CBW
1169The available options are:
1170
1171=over
1172
1173=item *
1174
1175C<type> - equivalent to C<$sock_type>, selects the socket type (or
1176"mechanism"). An array reference can be passed to specify several
1177mechanisms to try, in the given order.
1178
1179=item *
1180
1181C<path> - equivalent to C<$stream_location>, sets the stream location.
1182Defaults to standard Unix location, or C<_PATH_LOG>.
1183
1184=item *
1185
1186C<timeout> - equivalent to C<$sock_timeout>, sets the socket timeout
1187in seconds. Defaults to 0 on all systems except S<Mac OS X> where it
1188is set to 0.25 sec.
1189
1190=item *
1191
1192C<host> - sets the hostname to send the messages to. Defaults to
1193the local host.
1194
1195=item *
1196
1197C<port> - sets the TCP or UDP port to connect to. Defaults to the
1198first standard syslog port available on the system.
1199
1200=back
1201
1202
1203The available mechanisms are:
4b035b3d
SP
1204
1205=over
1206
1207=item *
1208
07b7e4bc
RGS
1209C<"native"> - use the native C functions from your C<syslog(3)> library
1210(added in C<Sys::Syslog> 0.15).
4b035b3d
SP
1211
1212=item *
1213
d329efa2
AT
1214C<"eventlog"> - send messages to the Win32 events logger (Win32 only;
1215added in C<Sys::Syslog> 0.19).
1216
1217=item *
1218
4b035b3d 1219C<"tcp"> - connect to a TCP socket, on the C<syslog/tcp> or C<syslogng/tcp>
06fd9d7a 1220service. See also the C<host>, C<port> and C<timeout> options.
4b035b3d
SP
1221
1222=item *
1223
1224C<"udp"> - connect to a UDP socket, on the C<syslog/udp> service.
06fd9d7a 1225See also the C<host>, C<port> and C<timeout> options.
4b035b3d
SP
1226
1227=item *
1228
f93f88eb 1229C<"inet"> - connect to an INET socket, either TCP or UDP, tried in that
06fd9d7a 1230order. See also the C<host>, C<port> and C<timeout> options.
4b035b3d
SP
1231
1232=item *
1233
1234C<"unix"> - connect to a UNIX domain socket (in some systems a character
06fd9d7a
CBW
1235special device). The name of that socket is given by the C<path> option
1236or, if omitted, the value returned by the C<_PATH_LOG> macro (if your
1237system defines it), F</dev/log> or F</dev/conslog>, whichever is writable.
4b035b3d
SP
1238
1239=item *
1240
06fd9d7a
CBW
1241C<"stream"> - connect to the stream indicated by the C<path> option, or,
1242if omitted, the value returned by the C<_PATH_LOG> macro (if your system
1243defines it), F</dev/log> or F</dev/conslog>, whichever is writable. For
1244example Solaris and IRIX system may prefer C<"stream"> instead of C<"unix">.
4b035b3d
SP
1245
1246=item *
1247
06fd9d7a
CBW
1248C<"pipe"> - connect to the named pipe indicated by the C<path> option,
1249or, if omitted, to the value returned by the C<_PATH_LOG> macro (if your
1250system defines it), or F</dev/log> (added in C<Sys::Syslog> 0.21).
1251HP-UX is a system which uses such a named pipe.
4b035b3d 1252
a650b841
AT
1253=item *
1254
d329efa2
AT
1255C<"console"> - send messages directly to the console, as for the C<"cons">
1256option of C<openlog()>.
a650b841 1257
4b035b3d 1258=back
89c3c464 1259
f93f88eb
AT
1260The default is to try C<native>, C<tcp>, C<udp>, C<unix>, C<pipe>, C<stream>,
1261C<console>.
35a209d1
AT
1262Under systems with the Win32 API, C<eventlog> will be added as the first
1263mechanism to try if C<Win32::EventLog> is available.
89c3c464 1264
07b7e4bc 1265Giving an invalid value for C<$sock_type> will C<croak>.
89c3c464 1266
4b035b3d
SP
1267B<Examples>
1268
06fd9d7a 1269Select the UDP socket mechanism:
4b035b3d
SP
1270
1271 setlogsock("udp");
1272
06fd9d7a
CBW
1273Send messages using the TCP socket mechanism on a custom port:
1274
1275 setlogsock({ type => "tcp", port => 2486 });
1276
1277Send messages to a remote host using the TCP socket mechanism:
1278
1279 setlogsock({ type => "tcp", host => $loghost });
1280
1281Try the native, UDP socket then UNIX domain socket mechanisms:
4b035b3d
SP
1282
1283 setlogsock(["native", "udp", "unix"]);
1284
07b7e4bc
RGS
1285=over
1286
1287=item B<Note>
1288
1289Now that the "native" mechanism is supported by C<Sys::Syslog> and selected
1290by default, the use of the C<setlogsock()> function is discouraged because
1291other mechanisms are less portable across operating systems. Authors of
1292modules and programs that use this function, especially its cargo-cult form
848ca32c 1293C<setlogsock("unix")>, are advised to remove any occurrence of it unless they
07b7e4bc
RGS
1294specifically want to use a given mechanism (like TCP or UDP to connect to
1295a remote host).
1296
1297=back
89c3c464
AT
1298
1299=item B<closelog()>
1300
4b035b3d 1301Closes the log file and returns true on success.
89c3c464
AT
1302
1303=back
1304
1305
a650b841
AT
1306=head1 THE RULES OF SYS::SYSLOG
1307
1308I<The First Rule of Sys::Syslog is:>
1309You do not call C<setlogsock>.
1310
1311I<The Second Rule of Sys::Syslog is:>
1312You B<do not> call C<setlogsock>.
1313
1314I<The Third Rule of Sys::Syslog is:>
1315The program crashes, C<die>s, calls C<closelog>, the log is over.
1316
1317I<The Fourth Rule of Sys::Syslog is:>
1318One facility, one priority.
1319
1320I<The Fifth Rule of Sys::Syslog is:>
1321One log at a time.
1322
1323I<The Sixth Rule of Sys::Syslog is:>
1324No C<syslog> before C<openlog>.
1325
1326I<The Seventh Rule of Sys::Syslog is:>
1327Logs will go on as long as they have to.
1328
1329I<The Eighth, and Final Rule of Sys::Syslog is:>
1330If this is your first use of Sys::Syslog, you must read the doc.
1331
1332
89c3c464
AT
1333=head1 EXAMPLES
1334
a650b841
AT
1335An example:
1336
89c3c464
AT
1337 openlog($program, 'cons,pid', 'user');
1338 syslog('info', '%s', 'this is another test');
1339 syslog('mail|warning', 'this is a better test: %d', time);
1340 closelog();
5be1dfc7
HF
1341
1342 syslog('debug', 'this is the last test');
cb63fe9d 1343
a650b841
AT
1344Another example:
1345
5be1dfc7
HF
1346 openlog("$program $$", 'ndelay', 'user');
1347 syslog('notice', 'fooprogram: this is really done');
1348
a650b841
AT
1349Example of use of C<%m>:
1350
5be1dfc7 1351 $! = 55;
6e4ef777
SP
1352 syslog('info', 'problem was %m'); # %m == $! in syslog(3)
1353
1354Log to UDP port on C<$remotehost> instead of logging locally:
5be1dfc7 1355
f93f88eb 1356 setlogsock("udp", $remotehost);
476b65d9
JH
1357 openlog($program, 'ndelay', 'user');
1358 syslog('info', 'something happened over here');
1359
8168e71f
SP
1360
1361=head1 CONSTANTS
1362
1363=head2 Facilities
1364
1365=over 4
1366
1367=item *
1368
a650b841
AT
1369C<LOG_AUDIT> - audit daemon (IRIX); falls back to C<LOG_AUTH>
1370
1371=item *
1372
8168e71f
SP
1373C<LOG_AUTH> - security/authorization messages
1374
1375=item *
1376
1377C<LOG_AUTHPRIV> - security/authorization messages (private)
1378
1379=item *
1380
a650b841
AT
1381C<LOG_CONSOLE> - C</dev/console> output (FreeBSD); falls back to C<LOG_USER>
1382
1383=item *
1384
4b035b3d 1385C<LOG_CRON> - clock daemons (B<cron> and B<at>)
8168e71f
SP
1386
1387=item *
1388
1389C<LOG_DAEMON> - system daemons without separate facility value
1390
1391=item *
1392
4b035b3d 1393C<LOG_FTP> - FTP daemon
8168e71f
SP
1394
1395=item *
1396
1397C<LOG_KERN> - kernel messages
1398
1399=item *
1400
a650b841 1401C<LOG_INSTALL> - installer subsystem (Mac OS X); falls back to C<LOG_USER>
4b035b3d
SP
1402
1403=item *
1404
a650b841
AT
1405C<LOG_LAUNCHD> - launchd - general bootstrap daemon (Mac OS X);
1406falls back to C<LOG_DAEMON>
1407
1408=item *
1409
1410C<LOG_LFMT> - logalert facility; falls back to C<LOG_USER>
4b035b3d
SP
1411
1412=item *
1413
8168e71f
SP
1414C<LOG_LOCAL0> through C<LOG_LOCAL7> - reserved for local use
1415
1416=item *
1417
1418C<LOG_LPR> - line printer subsystem
1419
1420=item *
1421
1422C<LOG_MAIL> - mail subsystem
1423
1424=item *
1425
a650b841 1426C<LOG_NETINFO> - NetInfo subsystem (Mac OS X); falls back to C<LOG_DAEMON>
4b035b3d
SP
1427
1428=item *
1429
8168e71f
SP
1430C<LOG_NEWS> - USENET news subsystem
1431
1432=item *
1433
a650b841
AT
1434C<LOG_NTP> - NTP subsystem (FreeBSD, NetBSD); falls back to C<LOG_DAEMON>
1435
1436=item *
1437
1438C<LOG_RAS> - Remote Access Service (VPN / PPP) (Mac OS X);
1439falls back to C<LOG_AUTH>
4b035b3d
SP
1440
1441=item *
1442
a650b841
AT
1443C<LOG_REMOTEAUTH> - remote authentication/authorization (Mac OS X);
1444falls back to C<LOG_AUTH>
1445
1446=item *
1447
1448C<LOG_SECURITY> - security subsystems (firewalling, etc.) (FreeBSD);
1449falls back to C<LOG_AUTH>
4b035b3d
SP
1450
1451=item *
1452
8168e71f
SP
1453C<LOG_SYSLOG> - messages generated internally by B<syslogd>
1454
1455=item *
1456
1457C<LOG_USER> (default) - generic user-level messages
1458
1459=item *
1460
1461C<LOG_UUCP> - UUCP subsystem
1462
1463=back
1464
1465
1466=head2 Levels
1467
1468=over 4
1469
1470=item *
1471
1472C<LOG_EMERG> - system is unusable
1473
1474=item *
1475
1476C<LOG_ALERT> - action must be taken immediately
1477
1478=item *
1479
1480C<LOG_CRIT> - critical conditions
1481
1482=item *
1483
942974c1 1484C<LOG_ERR> - error conditions
8168e71f
SP
1485
1486=item *
1487
1488C<LOG_WARNING> - warning conditions
1489
1490=item *
1491
1492C<LOG_NOTICE> - normal, but significant, condition
1493
1494=item *
1495
1496C<LOG_INFO> - informational message
1497
1498=item *
1499
1500C<LOG_DEBUG> - debug-level message
1501
1502=back
1503
1504
1505=head1 DIAGNOSTICS
1506
a650b841 1507=over
8168e71f 1508
a650b841 1509=item C<Invalid argument passed to setlogsock>
8168e71f
SP
1510
1511B<(F)> You gave C<setlogsock()> an invalid value for C<$sock_type>.
1512
35a209d1 1513=item C<eventlog passed to setlogsock, but no Win32 API available>
a650b841
AT
1514
1515B<(W)> You asked C<setlogsock()> to use the Win32 event logger but the
1516operating system running the program isn't Win32 or does not provides Win32
35a209d1 1517compatible facilities.
a650b841
AT
1518
1519=item C<no connection to syslog available>
8168e71f
SP
1520
1521B<(F)> C<syslog()> failed to connect to the specified socket.
1522
a650b841 1523=item C<stream passed to setlogsock, but %s is not writable>
8168e71f 1524
942974c1 1525B<(W)> You asked C<setlogsock()> to use a stream socket, but the given
8168e71f
SP
1526path is not writable.
1527
a650b841 1528=item C<stream passed to setlogsock, but could not find any device>
8168e71f 1529
942974c1 1530B<(W)> You asked C<setlogsock()> to use a stream socket, but didn't
8168e71f
SP
1531provide a path, and C<Sys::Syslog> was unable to find an appropriate one.
1532
a650b841 1533=item C<tcp passed to setlogsock, but tcp service unavailable>
8168e71f 1534
942974c1 1535B<(W)> You asked C<setlogsock()> to use a TCP socket, but the service
8168e71f
SP
1536is not available on the system.
1537
a650b841 1538=item C<syslog: expecting argument %s>
8168e71f
SP
1539
1540B<(F)> You forgot to give C<syslog()> the indicated argument.
1541
a650b841 1542=item C<syslog: invalid level/facility: %s>
8168e71f 1543
6e4ef777 1544B<(F)> You specified an invalid level or facility.
8168e71f 1545
a650b841 1546=item C<syslog: too many levels given: %s>
8168e71f
SP
1547
1548B<(F)> You specified too many levels.
1549
a650b841 1550=item C<syslog: too many facilities given: %s>
8168e71f
SP
1551
1552B<(F)> You specified too many facilities.
1553
a650b841 1554=item C<syslog: level must be given>
8168e71f
SP
1555
1556B<(F)> You forgot to specify a level.
1557
a650b841 1558=item C<udp passed to setlogsock, but udp service unavailable>
8168e71f 1559
942974c1 1560B<(W)> You asked C<setlogsock()> to use a UDP socket, but the service
8168e71f
SP
1561is not available on the system.
1562
a650b841 1563=item C<unix passed to setlogsock, but path not available>
8168e71f 1564
942974c1 1565B<(W)> You asked C<setlogsock()> to use a UNIX socket, but C<Sys::Syslog>
8168e71f
SP
1566was unable to find an appropriate an appropriate device.
1567
1568=back
1569
1570
06fd9d7a
CBW
1571=head1 HISTORY
1572
1573C<Sys::Syslog> is a core module, part of the standard Perl distribution
1574since 1990. At this time, modules as we know them didn't exist, the
1575Perl library was a collection of F<.pl> files, and the one for sending
1576syslog messages with was simply F<lib/syslog.pl>, included with Perl 3.0.
1577It was converted as a module with Perl 5.0, but had a version number
1578only starting with Perl 5.6. Here is a small table with the matching
1579Perl and C<Sys::Syslog> versions.
1580
1581 Sys::Syslog Perl
1582 ----------- ----
33f804f6
SH
1583 undef 5.0.0 ~ 5.5.4
1584 0.01 5.6.*
06fd9d7a
CBW
1585 0.03 5.8.0
1586 0.04 5.8.1, 5.8.2, 5.8.3
1587 0.05 5.8.4, 5.8.5, 5.8.6
1588 0.06 5.8.7
1589 0.13 5.8.8
1590 0.22 5.10.0
9f0af693
SH
1591 0.27 5.8.9, 5.10.1 ~ 5.14.*
1592 0.29 5.16.*
1593 0.32 5.18.*
1594 0.33 5.20.*
1595 0.33 5.22.*
06fd9d7a
CBW
1596
1597
5be1dfc7
HF
1598=head1 SEE ALSO
1599
848ca32c
CBW
1600=head2 Other modules
1601
1602L<Log::Log4perl> - Perl implementation of the Log4j API
1603
1604L<Log::Dispatch> - Dispatches messages to one or more outputs
1605
1606L<Log::Report> - Report a problem, with exceptions and language support
1607
a650b841
AT
1608=head2 Manual Pages
1609
5be1dfc7
HF
1610L<syslog(3)>
1611
9f0af693 1612SUSv3 issue 6, IEEE Std 1003.1, 2004 edition,
6e4ef777
SP
1613L<http://www.opengroup.org/onlinepubs/000095399/basedefs/syslog.h.html>
1614
9f0af693 1615GNU C Library documentation on syslog,
6e4ef777
SP
1616L<http://www.gnu.org/software/libc/manual/html_node/Syslog.html>
1617
9f0af693
SH
1618FreeBSD documentation on syslog,
1619L<https://www.freebsd.org/cgi/man.cgi?query=syslog>
1620
1621Solaris 11 documentation on syslog,
1622L<https://docs.oracle.com/cd/E53394_01/html/E54766/syslog-3c.html>
f93f88eb
AT
1623
1624Mac OS X documentation on syslog,
1625L<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/syslog.3.html>
6e4ef777 1626
9f0af693
SH
1627IRIX documentation on syslog,
1628L<http://nixdoc.net/man-pages/IRIX/man3/syslog.3c.html>
a650b841 1629
9f0af693 1630AIX 5L 5.3 documentation on syslog,
d329efa2 1631L<http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf2/syslog.htm>
6e4ef777 1632
9f0af693 1633HP-UX 11i documentation on syslog,
f93f88eb 1634L<http://docs.hp.com/en/B2355-60130/syslog.3C.html>
6e4ef777 1635
9f0af693
SH
1636Tru64 documentation on syslog,
1637L<http://nixdoc.net/man-pages/Tru64/man3/syslog.3.html>
6e4ef777 1638
9f0af693 1639Stratus VOS 15.1,
6e4ef777
SP
1640L<http://stratadoc.stratus.com/vos/15.1.1/r502-01/wwhelp/wwhimpl/js/html/wwhelp.htm?context=r502-01&file=ch5r502-01bi.html>
1641
a650b841
AT
1642=head2 RFCs
1643
6e4ef777
SP
1644I<RFC 3164 - The BSD syslog Protocol>, L<http://www.faqs.org/rfcs/rfc3164.html>
1645-- Please note that this is an informational RFC, and therefore does not
1646specify a standard of any kind.
1647
1648I<RFC 3195 - Reliable Delivery for syslog>, L<http://www.faqs.org/rfcs/rfc3195.html>
1649
a650b841
AT
1650=head2 Articles
1651
04f98b29
RGS
1652I<Syslogging with Perl>, L<http://lexington.pm.org/meetings/022001.html>
1653
a650b841 1654=head2 Event Log
8168e71f 1655
a650b841
AT
1656Windows Event Log,
1657L<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wes/wes/windows_event_log.asp>
5be1dfc7 1658
a650b841
AT
1659
1660=head1 AUTHORS & ACKNOWLEDGEMENTS
1661
1662Tom Christiansen E<lt>F<tchrist (at) perl.com>E<gt> and Larry Wall
1663E<lt>F<larry (at) wall.org>E<gt>.
150b260b
GS
1664
1665UNIX domain sockets added by Sean Robinson
a650b841
AT
1666E<lt>F<robinson_s (at) sc.maricopa.edu>E<gt> with support from Tim Bunce
1667E<lt>F<Tim.Bunce (at) ig.co.uk>E<gt> and the C<perl5-porters> mailing list.
150b260b
GS
1668
1669Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
a650b841 1670E<lt>F<tom (at) compton.nu>E<gt>.
5be1dfc7 1671
a650b841 1672Code for C<constant()>s regenerated by Nicholas Clark E<lt>F<nick (at) ccl4.org>E<gt>.
23642f4b
NW
1673
1674Failover to different communication modes by Nick Williams
a650b841
AT
1675E<lt>F<Nick.Williams (at) morganstanley.com>E<gt>.
1676
1677Extracted from core distribution for publishing on the CPAN by
1678SE<eacute>bastien Aperghis-Tramoni E<lt>sebastien (at) aperghis.netE<gt>.
b903fcff 1679
89c3c464 1680XS code for using native C functions borrowed from C<L<Unix::Syslog>>,
a650b841 1681written by Marcus Harnisch E<lt>F<marcus.harnisch (at) gmx.net>E<gt>.
89c3c464 1682
a650b841
AT
1683Yves Orton suggested and helped for making C<Sys::Syslog> use the native
1684event logger under Win32 systems.
1685
1686Jerry D. Hedden and Reini Urban provided greatly appreciated help to
1687debug and polish C<Sys::Syslog> under Cygwin.
8168e71f
SP
1688
1689
1690=head1 BUGS
1691
1692Please report any bugs or feature requests to
a650b841 1693C<bug-sys-syslog (at) rt.cpan.org>, or through the web interface at
35a209d1 1694L<http://rt.cpan.org/Public/Dist/Display.html?Name=Sys-Syslog>.
8168e71f
SP
1695I will be notified, and then you'll automatically be notified of progress on
1696your bug as I make changes.
1697
1698
1699=head1 SUPPORT
1700
1701You can find documentation for this module with the perldoc command.
1702
1703 perldoc Sys::Syslog
1704
1705You can also look for information at:
1706
e57ea7c9 1707=over
8168e71f 1708
e57ea7c9 1709=item * Perl Documentation
8168e71f 1710
e57ea7c9 1711L<http://perldoc.perl.org/Sys/Syslog.html>
8168e71f 1712
e57ea7c9 1713=item * MetaCPAN
8168e71f 1714
e57ea7c9 1715L<https://metacpan.org/module/Sys::Syslog>
8168e71f
SP
1716
1717=item * Search CPAN
1718
6e4ef777
SP
1719L<http://search.cpan.org/dist/Sys-Syslog/>
1720
e57ea7c9 1721=item * AnnoCPAN: Annotated CPAN documentation
6e4ef777 1722
e57ea7c9 1723L<http://annocpan.org/dist/Sys-Syslog>
6e4ef777 1724
e57ea7c9 1725=item * CPAN Ratings
6e4ef777 1726
e57ea7c9
CBW
1727L<http://cpanratings.perl.org/d/Sys-Syslog>
1728
1729=item * RT: CPAN's request tracker
1730
1731L<http://rt.cpan.org/Dist/Display.html?Queue=Sys-Syslog>
8168e71f
SP
1732
1733=back
1734
e57ea7c9
CBW
1735The source code is available on Git Hub:
1736L<https://github.com/maddingue/Sys-Syslog/>
1737
8168e71f 1738
35a209d1
AT
1739=head1 COPYRIGHT
1740
33f804f6 1741Copyright (C) 1990-2012 by Larry Wall and others.
35a209d1
AT
1742
1743
8168e71f
SP
1744=head1 LICENSE
1745
1746This program is free software; you can redistribute it and/or modify it
1747under the same terms as Perl itself.
1748
5be1dfc7 1749=cut
a650b841
AT
1750
1751=begin comment
1752
1753Notes for the future maintainer (even if it's still me..)
1754- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1755
1756Using Google Code Search, I search who on Earth was relying on $host being
1757public. It found 5 hits:
1758
1759* First was inside Indigo Star Perl2exe documentation. Just an old version
1760of Sys::Syslog.
1761
1762
1763* One real hit was inside DalWeathDB, a weather related program. It simply
1764does a
1765
1766 $Sys::Syslog::host = '127.0.0.1';
1767
1768- L<http://www.gallistel.net/nparker/weather/code/>
1769
1770
1771* Two hits were in TPC, a fax server thingy. It does a
1772
1773 $Sys::Syslog::host = $TPC::LOGHOST;
1774
1775but also has this strange piece of code:
1776
1777 # work around perl5.003 bug
1778 sub Sys::Syslog::hostname {}
1779
1780I don't know what bug the author referred to.
1781
1782- L<http://www.tpc.int/>
a650b841
AT
1783- L<ftp://ftp-usa.tpc.int/pub/tpc/server/UNIX/>
1784
1785
1786* Last hit was in Filefix, which seems to be a FIDOnet mail program (!).
1787This one does not use $host, but has the following piece of code:
1788
1789 sub Sys::Syslog::hostname
1790 {
1791 use Sys::Hostname;
1792 return hostname;
1793 }
1794
1795I guess this was a more elaborate form of the previous bit, maybe because
1796of a bug in Sys::Syslog back then?
1797
1798- L<ftp://ftp.kiae.su/pub/unix/fido/>
1799
d329efa2
AT
1800
1801Links
1802-----
f93f88eb
AT
1803Linux Fast-STREAMS
1804- L<http://www.openss7.org/streams.html>
1805
d329efa2
AT
1806II12021: SYSLOGD HOWTO TCPIPINFO (z/OS, OS/390, MVS)
1807- L<http://www-1.ibm.com/support/docview.wss?uid=isg1II12021>
1808
1809Getting the most out of the Event Viewer
1810- L<http://www.codeproject.com/dotnet/evtvwr.asp?print=true>
1811
1812Log events to the Windows NT Event Log with JNI
1813- L<http://www.javaworld.com/javaworld/jw-09-2001/jw-0928-ntmessages.html>
1814
a650b841 1815=end comment
d329efa2 1816