This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
undo a Scalar-List-Utils customisation
[perl5.git] / cpan / Sys-Syslog / Syslog.pm
1 package Sys::Syslog;
2 use strict;
3 use warnings;
4 use warnings::register;
5 use Carp;
6 use Config;
7 use Exporter        ();
8 use File::Basename;
9 use POSIX           qw< strftime setlocale LC_TIME >;
10 use Socket          qw< :all >;
11 require 5.005;
12
13
14 *import = \&Exporter::import;
15
16
17 {   no strict 'vars';
18     $VERSION = '0.35';
19
20     %EXPORT_TAGS = (
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
30             # standard facilities
31             qw(
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 ),
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         ],
55     );
56
57     @EXPORT = (
58         @{$EXPORT_TAGS{standard}}, 
59     );
60
61     @EXPORT_OK = (
62         @{$EXPORT_TAGS{extended}}, 
63         @{$EXPORT_TAGS{macros}}, 
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
78 #
79 # Constants
80 #
81 use constant HAVE_GETPROTOBYNAME     => $Config::Config{d_getpbyname};
82 use constant HAVE_GETPROTOBYNUMBER   => $Config::Config{d_getpbynumber};
83 use constant HAVE_SETLOCALE          => $Config::Config{d_setlocale};
84 use constant HAVE_IPPROTO_TCP        => defined &Socket::IPPROTO_TCP ? 1 : 0;
85 use constant HAVE_IPPROTO_UDP        => defined &Socket::IPPROTO_UDP ? 1 : 0;
86 use constant HAVE_TCP_NODELAY        => defined &Socket::TCP_NODELAY ? 1 : 0;
87
88 use constant SOCKET_IPPROTO_TCP =>
89       HAVE_IPPROTO_TCP      ? Socket::IPPROTO_TCP
90     : HAVE_GETPROTOBYNAME   ? scalar getprotobyname("tcp")
91     : 6;
92
93 use constant SOCKET_IPPROTO_UDP =>
94       HAVE_IPPROTO_UDP      ? Socket::IPPROTO_UDP
95     : HAVE_GETPROTOBYNAME   ? scalar getprotobyname("udp")
96     : 17;
97
98 use constant SOCKET_TCP_NODELAY => HAVE_TCP_NODELAY ? Socket::TCP_NODELAY : 1;
99
100
101
102 # Public variables
103
104 use vars qw($host);             # host to send syslog messages to (see notes at end)
105
106 #
107 # Prototypes
108 #
109 sub silent_eval (&);
110
111
112 # Global variables
113
114 use vars qw($facility);
115 my $connected       = 0;        # flag to indicate if we're connected or not
116 my $syslog_send;                # coderef of the function used to send messages
117 my $syslog_path     = undef;    # syslog path for "stream" and "unix" mechanisms
118 my $syslog_xobj     = undef;    # if defined, holds the external object used to send messages
119 my $transmit_ok     = 0;        # flag to indicate if the last message was transmitted
120 my $sock_port       = undef;    # socket port
121 my $sock_timeout    = 0;        # socket timeout, see below
122 my $current_proto   = undef;    # current mechanism used to transmit messages
123 my $ident           = '';       # identifiant prepended to each message
124 $facility           = '';       # current facility
125 my $maskpri         = LOG_UPTO(&LOG_DEBUG);     # current log mask
126
127 my %options = (
128     ndelay  => 0, 
129     noeol   => 0,
130     nofatal => 0, 
131     nonul   => 0,
132     nowait  => 0, 
133     perror  => 0, 
134     pid     => 0, 
135 );
136
137 # Default is now to first use the native mechanism, so Perl programs 
138 # behave like other normal Unix programs, then try other mechanisms.
139 my @connectMethods = qw(native tcp udp unix pipe stream console);
140 if ($^O eq "freebsd" or $^O eq "linux") {
141     @connectMethods = grep { $_ ne 'udp' } @connectMethods;
142 }
143
144 # And on Win32 systems, we try to use the native mechanism for this 
145 # platform, the events logger, available through Win32::EventLog.
146 EVENTLOG: {
147     my $verbose_if_Win32 = $^O =~ /Win32/i;
148
149     if (can_load_sys_syslog_win32($verbose_if_Win32)) {
150         unshift @connectMethods, 'eventlog';
151     }
152 }
153
154 my @defaultMethods = @connectMethods;
155 my @fallbackMethods = ();
156
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.
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/;
174
175
176 # Perl 5.6.0's warnings.pm doesn't have warnings::warnif()
177 if (not defined &warnings::warnif) {
178     *warnings::warnif = sub {
179         goto &warnings::warn if warnings::enabled(__PACKAGE__)
180     }
181 }
182
183 # coderef for a nicer handling of errors
184 my $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
185
186
187 sub 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);
195     croak $error if $error;
196     no strict 'refs';
197     *$AUTOLOAD = sub { $val };
198     goto &$AUTOLOAD;
199 }
200
201
202 sub openlog {
203     ($ident, my $logopt, $facility) = @_;
204
205     # default values
206     $ident    ||= basename($0) || getlogin() || getpwuid($<) || 'syslog';
207     $logopt   ||= '';
208     $facility ||= LOG_USER();
209
210     for my $opt (split /\b/, $logopt) {
211         $options{$opt} = 1 if exists $options{$opt}
212     }
213
214     $err_sub = delete $options{nofatal} ? \&warnings::warnif : \&croak;
215     return 1 unless $options{ndelay};
216     connect_log();
217
218
219 sub closelog {
220     disconnect_log() if $connected;
221     $options{$_} = 0 for keys %options;
222     $facility = $ident = "";
223     $connected = 0;
224     return 1
225
226
227 sub setlogmask {
228     my $oldmask = $maskpri;
229     $maskpri = shift unless $_[0] == 0;
230     $oldmask;
231 }
232
233
234 my %mechanism = (
235     console => {
236         check   => sub { 1 },
237     },
238     eventlog => {
239         check   => sub { return can_load_sys_syslog_win32() },
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 {
258             if (not defined $syslog_path) {
259                 my @try = qw(/dev/log /dev/conslog);
260                 unshift @try, &_PATH_LOG  if length &_PATH_LOG;
261                 ($syslog_path) = grep { -w } @try;
262             }
263             return defined $syslog_path && -w $syslog_path
264         },
265         err_msg => "could not find any writable device",
266     },
267     tcp => {
268         check   => sub {
269             return 1 if defined $sock_port;
270
271             if (eval { local $SIG{__DIE__};
272                 getservbyname('syslog','tcp') || getservbyname('syslogng','tcp')
273             }) {
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 {
285             return 1 if defined $sock_port;
286
287             if (eval { local $SIG{__DIE__}; getservbyname('syslog', 'udp') }) {
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  
307 sub 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;
320         }
321         elsif ($ref eq "ARRAY") {
322             @opt{qw< type path timeout >} = @_;
323         }
324         else {
325             croak "setlogsock(): Unexpected \L$ref\E reference"
326         }
327     }
328     else {
329         @opt{qw< type path timeout >} = @_;
330     }
331
332     # check socket type, remove invalid ones
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     }
345
346     @sock_types = @tmp;
347
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};
353
354     disconnect_log() if $connected;
355     $transmit_ok = 0;
356     @fallbackMethods = ();
357     @connectMethods = ();
358     my $found = 0;
359
360     # check each given mechanism and test if it can be used on the current system
361     for my $sock_type (@sock_types) {
362         if ( $mechanism{$sock_type}{check}->() ) {
363             push @connectMethods, $sock_type;
364             $found = 1;
365         }
366         else {
367             warnings::warnif("setlogsock(): type='$sock_type': "
368                            . $mechanism{$sock_type}{err_msg});
369         }
370     }
371
372     # if no mechanism worked from the given ones, use the default ones
373     @connectMethods = @defaultMethods unless @connectMethods;
374
375     return $found;
376 }
377
378 sub syslog {
379     my ($priority, $mask, @args) = @_;
380     my ($message, $buf);
381     my (@words, $num, $numpri, $numfac, $sum);
382     my $failed = undef;
383     my $fail_time = undef;
384     my $error = $!;
385
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.
391
392     croak "syslog: expecting argument \$priority" unless defined $priority;
393     croak "syslog: expecting argument \$format"   unless defined $mask;
394
395     if ($priority =~ /^\d+$/) {
396         $numpri = LOG_PRI($priority);
397         $numfac = LOG_FAC($priority) << 3;
398         undef $numfac if $numfac == 0;  # no facility given => use default
399     }
400     elsif ($priority =~ /^\w+/) {
401         # Allow "level" or "level|facility".
402         @words = split /\W+/, $priority, 2;
403
404         undef $numpri;
405         undef $numfac;
406
407         for my $word (@words) {
408             next if length $word == 0;
409
410             # Translate word to number.
411             $num = xlate($word);
412
413             if ($num < 0) {
414                 croak "syslog: invalid level/facility: $word"
415             }
416             elsif ($num <= LOG_PRIMASK() and $word ne "kern") {
417                 croak "syslog: too many levels given: $word"
418                     if defined $numpri;
419                 $numpri = $num;
420             }
421             else {
422                 croak "syslog: too many facilities given: $word"
423                     if defined $numfac;
424                 $facility = $word if $word =~ /^[A-Za-z]/;
425                 $numfac = $num;
426             }
427         }
428     }
429     else {
430         croak "syslog: invalid level/facility: $priority"
431     }
432
433     croak "syslog: level must be given" unless defined $numpri;
434
435     # don't log if priority is below mask level
436     return 0 unless LOG_MASK($numpri) & $maskpri;
437
438     if (not defined $numfac) {  # Facility not specified in this call.
439         $facility = 'user' unless $facility;
440         $numfac = xlate($facility);
441     }
442
443     connect_log() unless $connected;
444
445     if ($mask =~ /%m/) {
446         # escape percent signs for sprintf()
447         $error =~ s/%/%%/g if @args;
448         # replace %m with $error, if preceded by an even number of percent signs
449         $mask =~ s/(?<!%)((?:%%)*)%m/$1$error/g;
450     }
451
452     # add (or not) a newline
453     $mask .= "\n" if !$options{noeol} and rindex($mask, "\n") == -1;
454     $message = @args ? sprintf($mask, @args) : $mask;
455
456     if ($current_proto eq 'native') {
457         $buf = $message;
458     }
459     elsif ($current_proto eq 'eventlog') {
460         $buf = $message;
461     }
462     else {
463         my $whoami = $ident;
464         $whoami .= "[$$]" if $options{pid};
465
466         $sum = $numpri + $numfac;
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;
484
485         # construct the stream that will be transmitted
486         $buf = "<$sum>$timestamp $whoami: $message";
487
488         # add (or not) a NUL character
489         $buf .= "\0" if !$options{nonul};
490     }
491
492     # handle PERROR option
493     # "native" mechanism already handles it by itself
494     if ($options{perror} and $current_proto ne 'native') {
495         my $whoami = $ident;
496         $whoami .= "[$$]" if $options{pid};
497         print STDERR "$whoami: $message";
498         print STDERR "\n" if rindex($message, "\n") == -1;
499     }
500
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         }
514
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         }
522
523         connect_log() unless $connected;
524         $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
525
526         if ($syslog_send) {
527             if ($syslog_send->($buf, $numpri, $numfac)) {
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 }
539
540 sub _syslog_send_console {
541     my ($buf) = @_;
542
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) {
547
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 ?
562             POSIX::_exit($ret) if defined $pid;
563             close CONS;
564         }
565
566         POSIX::_exit(0) if defined $pid;
567     }
568 }
569
570 sub _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 }
578
579 sub _syslog_send_pipe {
580     my ($buf) = @_;
581     return print SYSLOG $buf;
582 }
583
584 sub _syslog_send_socket {
585     my ($buf) = @_;
586     return syswrite(SYSLOG, $buf, length($buf));
587     #return send(SYSLOG, $buf, 0);
588 }
589
590 sub _syslog_send_native {
591     my ($buf, $numpri, $numfac) = @_;
592     syslog_xs($numpri|$numfac, $buf);
593     return 1;
594 }
595
596
597 # xlate()
598 # -----
599 # private function to translate names to numeric values
600
601 sub xlate {
602     my ($name) = @_;
603
604     return $name+0 if $name =~ /^\s*\d+\s*$/;
605     $name = uc $name;
606     $name = "LOG_$name" unless $name =~ /^LOG_/;
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. 
614     my $value = constant($name);
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;
623
624     return defined $value ? $value : -1;
625 }
626
627
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
634 sub connect_log {
635     @fallbackMethods = @connectMethods unless scalar @fallbackMethods;
636
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     }
641
642     $connected = 0;
643     my @errs = ();
644     my $proto = undef;
645
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     }
652
653     $transmit_ok = 0;
654     if ($connected) {
655         $current_proto = $proto;
656         my ($old) = select(SYSLOG); $| = 1; select($old);
657     } else {
658         @fallbackMethods = ();
659         $err_sub->(join "\n\t- ", "no connection to syslog available", @errs);
660         return undef;
661     }
662 }
663
664 sub connect_tcp {
665     my ($errs) = @_;
666
667     my $port = $sock_port
668             || eval { local $SIG{__DIE__}; getservbyname('syslog',   'tcp') }
669             || eval { local $SIG{__DIE__}; getservbyname('syslogng', 'tcp') };
670     if (!defined $port) {
671         push @$errs, "getservbyname failed for syslog/tcp and syslogng/tcp";
672         return 0;
673     }
674
675     my $addr;
676     if (defined $host) {
677         $addr = inet_aton($host);
678         if (!$addr) {
679             push @$errs, "can't lookup $host";
680             return 0;
681         }
682     } else {
683         $addr = INADDR_LOOPBACK;
684     }
685     $addr = sockaddr_in($port, $addr);
686
687     if (!socket(SYSLOG, AF_INET, SOCK_STREAM, SOCKET_IPPROTO_TCP)) {
688         push @$errs, "tcp socket: $!";
689         return 0;
690     }
691
692     setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
693     setsockopt(SYSLOG, SOCKET_IPPROTO_TCP, SOCKET_TCP_NODELAY, 1);
694
695     if (!connect(SYSLOG, $addr)) {
696         push @$errs, "tcp connect: $!";
697         return 0;
698     }
699
700     $syslog_send = \&_syslog_send_socket;
701
702     return 1;
703 }
704
705 sub connect_udp {
706     my ($errs) = @_;
707
708     my $port = $sock_port
709             || eval { local $SIG{__DIE__}; getservbyname('syslog', 'udp') };
710     if (!defined $port) {
711         push @$errs, "getservbyname failed for syslog/udp";
712         return 0;
713     }
714
715     my $addr;
716     if (defined $host) {
717         $addr = inet_aton($host);
718         if (!$addr) {
719             push @$errs, "can't lookup $host";
720             return 0;
721         }
722     } else {
723         $addr = INADDR_LOOPBACK;
724     }
725     $addr = sockaddr_in($port, $addr);
726
727     if (!socket(SYSLOG, AF_INET, SOCK_DGRAM, SOCKET_IPPROTO_UDP)) {
728         push @$errs, "udp socket: $!";
729         return 0;
730     }
731     if (!connect(SYSLOG, $addr)) {
732         push @$errs, "udp connect: $!";
733         return 0;
734     }
735
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     }
743
744     $syslog_send = \&_syslog_send_socket;
745
746     return 1;
747 }
748
749 sub connect_stream {
750     my ($errs) = @_;
751     # might want syslog_path to be variable based on syslog.h (if only
752     # it were in there!)
753     $syslog_path = '/dev/conslog' unless defined $syslog_path; 
754
755     if (!-w $syslog_path) {
756         push @$errs, "stream $syslog_path is not writable";
757         return 0;
758     }
759
760     require Fcntl;
761
762     if (!sysopen(SYSLOG, $syslog_path, Fcntl::O_WRONLY(), 0400)) {
763         push @$errs, "stream can't open $syslog_path: $!";
764         return 0;
765     }
766
767     $syslog_send = \&_syslog_send_stream;
768
769     return 1;
770 }
771
772 sub 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
792 sub connect_unix {
793     my ($errs) = @_;
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";
799         return 0;
800     }
801
802     if (not (-S $syslog_path or -c _)) {
803         push @$errs, "$syslog_path is not a socket";
804         return 0;
805     }
806
807     my $addr = sockaddr_un($syslog_path);
808     if (!$addr) {
809         push @$errs, "can't locate $syslog_path";
810         return 0;
811     }
812     if (!socket(SYSLOG, AF_UNIX, SOCK_STREAM, 0)) {
813         push @$errs, "unix stream socket: $!";
814         return 0;
815     }
816
817     if (!connect(SYSLOG, $addr)) {
818         if (!socket(SYSLOG, AF_UNIX, SOCK_DGRAM, 0)) {
819             push @$errs, "unix dgram socket: $!";
820             return 0;
821         }
822         if (!connect(SYSLOG, $addr)) {
823             push @$errs, "unix dgram connect: $!";
824             return 0;
825         }
826     }
827
828     $syslog_send = \&_syslog_send_socket;
829
830     return 1;
831 }
832
833 sub connect_native {
834     my ($errs) = @_;
835     my $logopt = 0;
836
837     # reconstruct the numeric equivalent of the options
838     for my $opt (keys %options) {
839         $logopt += xlate($opt) if $options{$opt}
840     }
841
842     openlog_xs($ident, $logopt, xlate($facility));
843     $syslog_send = \&_syslog_send_native;
844
845     return 1;
846 }
847
848 sub 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
857 sub 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 }
866
867 # To test if the connection is still good, we need to check if any
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...
873 sub connection_ok {
874     return 1 if defined $current_proto and (
875         $current_proto eq 'native' or $current_proto eq 'console'
876         or $current_proto eq 'eventlog'
877     );
878
879     my $rin = '';
880     vec($rin, fileno(SYSLOG), 1) = 1;
881     my $ret = select $rin, undef, $rin, $sock_timeout;
882     return ($ret ? 0 : 1);
883 }
884
885 sub disconnect_log {
886     $connected = 0;
887     $syslog_send = undef;
888
889     if (defined $current_proto and $current_proto eq 'native') {
890         closelog_xs();
891         unshift @fallbackMethods, $current_proto;
892         $current_proto = undef;
893         return 1;
894     }
895     elsif (defined $current_proto and $current_proto eq 'eventlog') {
896         $syslog_xobj->Close();
897         unshift @fallbackMethods, $current_proto;
898         $current_proto = undef;
899         return 1;
900     }
901
902     return close SYSLOG;
903 }
904
905
906 #
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.
912 #
913 sub silent_eval (&) {
914     local($SIG{__DIE__}, $SIG{__WARN__}, $@);
915     return eval { $_[0]->() }
916 }
917
918 sub can_load_sys_syslog_win32 {
919     my ($verbose) = @_;
920     local($SIG{__DIE__}, $SIG{__WARN__}, $@);
921     (my $module_path = __FILE__) =~ s:Syslog.pm$:Syslog/Win32.pm:;
922     my $loaded = eval { require $module_path } ? 1 : 0;
923     warn $@ if not $loaded and $verbose;
924     return $loaded
925 }
926
927
928 "Eighth Rule: read the documentation."
929
930 __END__
931
932 =head1 NAME
933
934 Sys::Syslog - Perl interface to the UNIX syslog(3) calls
935
936 =head1 VERSION
937
938 This is the documentation of version 0.35
939
940 =head1 SYNOPSIS
941
942     use Sys::Syslog;                        # all except setlogsock()
943     use Sys::Syslog qw(:standard :macros);  # standard functions & macros
944
945     openlog($ident, $logopt, $facility);    # don't forget this
946     syslog($priority, $format, @args);
947     $oldmask = setlogmask($mask_priority);
948     closelog();
949
950
951 =head1 DESCRIPTION
952
953 C<Sys::Syslog> is an interface to the UNIX C<syslog(3)> program.
954 Call C<syslog()> with a string priority and a list of C<printf()> args
955 just like C<syslog(3)>.
956
957
958 =head1 EXPORTS
959
960 C<Sys::Syslog> exports the following C<Exporter> tags: 
961
962 =over 4
963
964 =item *
965
966 C<:standard> exports the standard C<syslog(3)> functions: 
967
968     openlog closelog setlogmask syslog
969
970 =item *
971
972 C<:extended> exports the Perl specific functions for C<syslog(3)>: 
973
974     setlogsock
975
976 =item *
977
978 C<:macros> exports the symbols corresponding to most of your C<syslog(3)> 
979 macros and the C<LOG_UPTO()> and C<LOG_MASK()> functions. 
980 See L<"CONSTANTS"> for the supported constants and their meaning. 
981
982 =back
983
984 By 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
993 Opens the syslog.
994 C<$ident> is prepended to every message.  C<$logopt> contains zero or
995 more of the options detailed below.  C<$facility> specifies the part 
996 of the system to report about, for example C<LOG_USER> or C<LOG_LOCAL0>:
997 see L<"Facilities"> for a list of well-known facilities, and your 
998 C<syslog(3)> documentation for the facilities available in your system. 
999 Check L<"SEE ALSO"> for useful links. Facility can be given as a string 
1000 or a numeric macro. 
1001
1002 This function will croak if it can't connect to the syslog daemon.
1003
1004 Note that C<openlog()> now takes three arguments, just like C<openlog(3)>.
1005
1006 B<You should use C<openlog()> before calling C<syslog()>.>
1007
1008 B<Options>
1009
1010 =over 4
1011
1012 =item *
1013
1014 C<cons> - This option is ignored, since the failover mechanism will drop 
1015 down to the console automatically if all other media fail.
1016
1017 =item *
1018
1019 C<ndelay> - Open the connection immediately (normally, the connection is
1020 opened when the first message is logged).
1021
1022 =item *
1023
1024 C<noeol> - When set to true, no end of line character (C<\n>) will be
1025 appended to the message. This can be useful for some syslog daemons.
1026 Added in C<Sys::Syslog> 0.29.
1027
1028 =item *
1029
1030 C<nofatal> - When set to true, C<openlog()> and C<syslog()> will only 
1031 emit warnings instead of dying if the connection to the syslog can't 
1032 be established. Added in C<Sys::Syslog> 0.15.
1033
1034 =item *
1035
1036 C<nonul> - When set to true, no C<NUL> character (C<\0>) will be
1037 appended to the message. This can be useful for some syslog daemons.
1038 Added in C<Sys::Syslog> 0.29.
1039
1040 =item *
1041
1042 C<nowait> - Don't wait for child processes that may have been created 
1043 while logging the message.  (The GNU C library does not create a child
1044 process, so this option has no effect on Linux.)
1045
1046 =item *
1047
1048 C<perror> - Write the message to standard error output as well to the
1049 system log. Added in C<Sys::Syslog> 0.22.
1050
1051 =item *
1052
1053 C<pid> - Include PID with each message.
1054
1055 =back
1056
1057 B<Examples>
1058
1059 Open the syslog with options C<ndelay> and C<pid>, and with facility C<LOCAL0>: 
1060
1061     openlog($name, "ndelay,pid", "local0");
1062
1063 Same 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
1072 If C<$priority> permits, logs C<$message> or C<sprintf($format, @args)>
1073 with the addition that C<%m> in $message or C<$format> is replaced with
1074 C<"$!"> (the latest error message). 
1075
1076 C<$priority> can specify a level, or a level and a facility.  Levels and 
1077 facilities can be given as strings or as macros.  When using the C<eventlog>
1078 mechanism, priorities C<DEBUG> and C<INFO> are mapped to event type 
1079 C<informational>, C<NOTICE> and C<WARNING> to C<warning> and C<ERR> to 
1080 C<EMERG> to C<error>.
1081
1082 If you didn't use C<openlog()> before using C<syslog()>, C<syslog()> will 
1083 try to guess the C<$ident> by extracting the shortest prefix of 
1084 C<$format> that ends in a C<":">.
1085
1086 B<Examples>
1087
1088     # informational level
1089     syslog("info", $message);
1090     syslog(LOG_INFO, $message);
1091
1092     # information level, Local0 facility
1093     syslog("info|local0", $message);
1094     syslog(LOG_INFO|LOG_LOCAL0, $message);
1095
1096 =over 4
1097
1098 =item B<Note>
1099
1100 C<Sys::Syslog> version v0.07 and older passed the C<$message> as the 
1101 formatting string to C<sprintf()> even when no formatting arguments
1102 were provided.  If the code calling C<syslog()> might execute with 
1103 older versions of this module, make sure to call the function as
1104 C<syslog($priority, "%s", $message)> instead of C<syslog($priority,
1105 $message)>.  This protects against hostile formatting sequences that
1106 might show up if $message contains tainted data.
1107
1108 =back
1109
1110
1111 =item B<setlogmask($mask_priority)>
1112
1113 Sets the log mask for the current process to C<$mask_priority> and 
1114 returns the old mask.  If the mask argument is 0, the current log mask 
1115 is not modified.  See L<"Levels"> for the list of available levels. 
1116 You can use the C<LOG_UPTO()> function to allow all levels up to a 
1117 given priority (but it only accept the numeric macros as arguments).
1118
1119 B<Examples>
1120
1121 Only log errors: 
1122
1123     setlogmask( LOG_MASK(LOG_ERR) );
1124
1125 Log everything except informational messages: 
1126
1127     setlogmask( ~(LOG_MASK(LOG_INFO)) );
1128
1129 Log critical messages, errors and warnings: 
1130
1131     setlogmask( LOG_MASK(LOG_CRIT)
1132               | LOG_MASK(LOG_ERR)
1133               | LOG_MASK(LOG_WARNING) );
1134
1135 Log all messages up to debug: 
1136
1137     setlogmask( LOG_UPTO(LOG_DEBUG) );
1138
1139
1140 =item B<setlogsock()>
1141
1142 Sets the socket type and options to be used for the next call to C<openlog()>
1143 or C<syslog()>.  Returns true on success, C<undef> on failure.
1144
1145 Being Perl-specific, this function has evolved along time.  It can currently
1146 be called as follow:
1147
1148 =over
1149
1150 =item *
1151
1152 C<setlogsock($sock_type)>
1153
1154 =item *
1155
1156 C<setlogsock($sock_type, $stream_location)> (added in Perl 5.004_02)
1157
1158 =item *
1159
1160 C<setlogsock($sock_type, $stream_location, $sock_timeout)> (added in
1161 C<Sys::Syslog> 0.25)
1162
1163 =item *
1164
1165 C<setlogsock(\%options)> (added in C<Sys::Syslog> 0.28)
1166
1167 =back
1168
1169 The available options are:
1170
1171 =over
1172
1173 =item *
1174
1175 C<type> - equivalent to C<$sock_type>, selects the socket type (or
1176 "mechanism").  An array reference can be passed to specify several
1177 mechanisms to try, in the given order.
1178
1179 =item *
1180
1181 C<path> - equivalent to C<$stream_location>, sets the stream location.
1182 Defaults to standard Unix location, or C<_PATH_LOG>.
1183
1184 =item *
1185
1186 C<timeout> - equivalent to C<$sock_timeout>, sets the socket timeout
1187 in seconds.  Defaults to 0 on all systems except S<Mac OS X> where it
1188 is set to 0.25 sec.
1189
1190 =item *
1191
1192 C<host> - sets the hostname to send the messages to.  Defaults to 
1193 the local host.
1194
1195 =item *
1196
1197 C<port> - sets the TCP or UDP port to connect to.  Defaults to the
1198 first standard syslog port available on the system.
1199
1200 =back
1201
1202
1203 The available mechanisms are: 
1204
1205 =over
1206
1207 =item *
1208
1209 C<"native"> - use the native C functions from your C<syslog(3)> library
1210 (added in C<Sys::Syslog> 0.15).
1211
1212 =item *
1213
1214 C<"eventlog"> - send messages to the Win32 events logger (Win32 only; 
1215 added in C<Sys::Syslog> 0.19).
1216
1217 =item *
1218
1219 C<"tcp"> - connect to a TCP socket, on the C<syslog/tcp> or C<syslogng/tcp> 
1220 service.  See also the C<host>, C<port> and C<timeout> options.
1221
1222 =item *
1223
1224 C<"udp"> - connect to a UDP socket, on the C<syslog/udp> service.
1225 See also the C<host>, C<port> and C<timeout> options.
1226
1227 =item *
1228
1229 C<"inet"> - connect to an INET socket, either TCP or UDP, tried in that 
1230 order.  See also the C<host>, C<port> and C<timeout> options.
1231
1232 =item *
1233
1234 C<"unix"> - connect to a UNIX domain socket (in some systems a character 
1235 special device).  The name of that socket is given by the C<path> option
1236 or, if omitted, the value returned by the C<_PATH_LOG> macro (if your
1237 system defines it), F</dev/log> or F</dev/conslog>, whichever is writable.
1238
1239 =item *
1240
1241 C<"stream"> - connect to the stream indicated by the C<path> option, or,
1242 if omitted, the value returned by the C<_PATH_LOG> macro (if your system
1243 defines it), F</dev/log> or F</dev/conslog>, whichever is writable.  For
1244 example Solaris and IRIX system may prefer C<"stream"> instead of C<"unix">. 
1245
1246 =item *
1247
1248 C<"pipe"> - connect to the named pipe indicated by the C<path> option,
1249 or, if omitted, to the value returned by the C<_PATH_LOG> macro (if your
1250 system defines it), or F</dev/log> (added in C<Sys::Syslog> 0.21).
1251 HP-UX is a system which uses such a named pipe.
1252
1253 =item *
1254
1255 C<"console"> - send messages directly to the console, as for the C<"cons"> 
1256 option of C<openlog()>.
1257
1258 =back
1259
1260 The default is to try C<native>, C<tcp>, C<udp>, C<unix>, C<pipe>, C<stream>, 
1261 C<console>.
1262 Under systems with the Win32 API, C<eventlog> will be added as the first 
1263 mechanism to try if C<Win32::EventLog> is available.
1264
1265 Giving an invalid value for C<$sock_type> will C<croak>.
1266
1267 B<Examples>
1268
1269 Select the UDP socket mechanism:
1270
1271     setlogsock("udp");
1272
1273 Send messages using the TCP socket mechanism on a custom port:
1274
1275     setlogsock({ type => "tcp", port => 2486 });
1276
1277 Send messages to a remote host using the TCP socket mechanism:
1278
1279     setlogsock({ type => "tcp", host => $loghost });
1280
1281 Try the native, UDP socket then UNIX domain socket mechanisms: 
1282
1283     setlogsock(["native", "udp", "unix"]);
1284
1285 =over
1286
1287 =item B<Note>
1288
1289 Now that the "native" mechanism is supported by C<Sys::Syslog> and selected 
1290 by default, the use of the C<setlogsock()> function is discouraged because 
1291 other mechanisms are less portable across operating systems.  Authors of 
1292 modules and programs that use this function, especially its cargo-cult form 
1293 C<setlogsock("unix")>, are advised to remove any occurrence of it unless they 
1294 specifically want to use a given mechanism (like TCP or UDP to connect to 
1295 a remote host).
1296
1297 =back
1298
1299 =item B<closelog()>
1300
1301 Closes the log file and returns true on success.
1302
1303 =back
1304
1305
1306 =head1 THE RULES OF SYS::SYSLOG
1307
1308 I<The First Rule of Sys::Syslog is:>
1309 You do not call C<setlogsock>.
1310
1311 I<The Second Rule of Sys::Syslog is:>
1312 You B<do not> call C<setlogsock>.
1313
1314 I<The Third Rule of Sys::Syslog is:>
1315 The program crashes, C<die>s, calls C<closelog>, the log is over.
1316
1317 I<The Fourth Rule of Sys::Syslog is:>
1318 One facility, one priority.
1319
1320 I<The Fifth Rule of Sys::Syslog is:>
1321 One log at a time.
1322
1323 I<The Sixth Rule of Sys::Syslog is:>
1324 No C<syslog> before C<openlog>.
1325
1326 I<The Seventh Rule of Sys::Syslog is:>
1327 Logs will go on as long as they have to. 
1328
1329 I<The Eighth, and Final Rule of Sys::Syslog is:>
1330 If this is your first use of Sys::Syslog, you must read the doc.
1331
1332
1333 =head1 EXAMPLES
1334
1335 An example:
1336
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();
1341
1342     syslog('debug', 'this is the last test');
1343
1344 Another example:
1345
1346     openlog("$program $$", 'ndelay', 'user');
1347     syslog('notice', 'fooprogram: this is really done');
1348
1349 Example of use of C<%m>:
1350
1351     $! = 55;
1352     syslog('info', 'problem was %m');   # %m == $! in syslog(3)
1353
1354 Log to UDP port on C<$remotehost> instead of logging locally:
1355
1356     setlogsock("udp", $remotehost);
1357     openlog($program, 'ndelay', 'user');
1358     syslog('info', 'something happened over here');
1359
1360
1361 =head1 CONSTANTS
1362
1363 =head2 Facilities
1364
1365 =over 4
1366
1367 =item *
1368
1369 C<LOG_AUDIT> - audit daemon (IRIX); falls back to C<LOG_AUTH>
1370
1371 =item *
1372
1373 C<LOG_AUTH> - security/authorization messages
1374
1375 =item *
1376
1377 C<LOG_AUTHPRIV> - security/authorization messages (private)
1378
1379 =item *
1380
1381 C<LOG_CONSOLE> - C</dev/console> output (FreeBSD); falls back to C<LOG_USER>
1382
1383 =item *
1384
1385 C<LOG_CRON> - clock daemons (B<cron> and B<at>)
1386
1387 =item *
1388
1389 C<LOG_DAEMON> - system daemons without separate facility value
1390
1391 =item *
1392
1393 C<LOG_FTP> - FTP daemon
1394
1395 =item *
1396
1397 C<LOG_KERN> - kernel messages
1398
1399 =item *
1400
1401 C<LOG_INSTALL> - installer subsystem (Mac OS X); falls back to C<LOG_USER>
1402
1403 =item *
1404
1405 C<LOG_LAUNCHD> - launchd - general bootstrap daemon (Mac OS X);
1406 falls back to C<LOG_DAEMON>
1407
1408 =item *
1409
1410 C<LOG_LFMT> - logalert facility; falls back to C<LOG_USER>
1411
1412 =item *
1413
1414 C<LOG_LOCAL0> through C<LOG_LOCAL7> - reserved for local use
1415
1416 =item *
1417
1418 C<LOG_LPR> - line printer subsystem
1419
1420 =item *
1421
1422 C<LOG_MAIL> - mail subsystem
1423
1424 =item *
1425
1426 C<LOG_NETINFO> - NetInfo subsystem (Mac OS X); falls back to C<LOG_DAEMON>
1427
1428 =item *
1429
1430 C<LOG_NEWS> - USENET news subsystem
1431
1432 =item *
1433
1434 C<LOG_NTP> - NTP subsystem (FreeBSD, NetBSD); falls back to C<LOG_DAEMON>
1435
1436 =item *
1437
1438 C<LOG_RAS> - Remote Access Service (VPN / PPP) (Mac OS X);
1439 falls back to C<LOG_AUTH>
1440
1441 =item *
1442
1443 C<LOG_REMOTEAUTH> - remote authentication/authorization (Mac OS X);
1444 falls back to C<LOG_AUTH>
1445
1446 =item *
1447
1448 C<LOG_SECURITY> - security subsystems (firewalling, etc.) (FreeBSD);
1449 falls back to C<LOG_AUTH>
1450
1451 =item *
1452
1453 C<LOG_SYSLOG> - messages generated internally by B<syslogd>
1454
1455 =item *
1456
1457 C<LOG_USER> (default) - generic user-level messages
1458
1459 =item *
1460
1461 C<LOG_UUCP> - UUCP subsystem
1462
1463 =back
1464
1465
1466 =head2 Levels
1467
1468 =over 4
1469
1470 =item *
1471
1472 C<LOG_EMERG> - system is unusable
1473
1474 =item *
1475
1476 C<LOG_ALERT> - action must be taken immediately
1477
1478 =item *
1479
1480 C<LOG_CRIT> - critical conditions
1481
1482 =item *
1483
1484 C<LOG_ERR> - error conditions
1485
1486 =item *
1487
1488 C<LOG_WARNING> - warning conditions
1489
1490 =item *
1491
1492 C<LOG_NOTICE> - normal, but significant, condition
1493
1494 =item *
1495
1496 C<LOG_INFO> - informational message
1497
1498 =item *
1499
1500 C<LOG_DEBUG> - debug-level message
1501
1502 =back
1503
1504
1505 =head1 DIAGNOSTICS
1506
1507 =over
1508
1509 =item C<Invalid argument passed to setlogsock>
1510
1511 B<(F)> You gave C<setlogsock()> an invalid value for C<$sock_type>. 
1512
1513 =item C<eventlog passed to setlogsock, but no Win32 API available>
1514
1515 B<(W)> You asked C<setlogsock()> to use the Win32 event logger but the 
1516 operating system running the program isn't Win32 or does not provides Win32
1517 compatible facilities.
1518
1519 =item C<no connection to syslog available>
1520
1521 B<(F)> C<syslog()> failed to connect to the specified socket.
1522
1523 =item C<stream passed to setlogsock, but %s is not writable>
1524
1525 B<(W)> You asked C<setlogsock()> to use a stream socket, but the given 
1526 path is not writable. 
1527
1528 =item C<stream passed to setlogsock, but could not find any device>
1529
1530 B<(W)> You asked C<setlogsock()> to use a stream socket, but didn't 
1531 provide a path, and C<Sys::Syslog> was unable to find an appropriate one.
1532
1533 =item C<tcp passed to setlogsock, but tcp service unavailable>
1534
1535 B<(W)> You asked C<setlogsock()> to use a TCP socket, but the service 
1536 is not available on the system. 
1537
1538 =item C<syslog: expecting argument %s>
1539
1540 B<(F)> You forgot to give C<syslog()> the indicated argument.
1541
1542 =item C<syslog: invalid level/facility: %s>
1543
1544 B<(F)> You specified an invalid level or facility.
1545
1546 =item C<syslog: too many levels given: %s>
1547
1548 B<(F)> You specified too many levels. 
1549
1550 =item C<syslog: too many facilities given: %s>
1551
1552 B<(F)> You specified too many facilities. 
1553
1554 =item C<syslog: level must be given>
1555
1556 B<(F)> You forgot to specify a level.
1557
1558 =item C<udp passed to setlogsock, but udp service unavailable>
1559
1560 B<(W)> You asked C<setlogsock()> to use a UDP socket, but the service 
1561 is not available on the system. 
1562
1563 =item C<unix passed to setlogsock, but path not available>
1564
1565 B<(W)> You asked C<setlogsock()> to use a UNIX socket, but C<Sys::Syslog> 
1566 was unable to find an appropriate an appropriate device.
1567
1568 =back
1569
1570
1571 =head1 HISTORY
1572
1573 C<Sys::Syslog> is a core module, part of the standard Perl distribution
1574 since 1990.  At this time, modules as we know them didn't exist, the
1575 Perl library was a collection of F<.pl> files, and the one for sending
1576 syslog messages with was simply F<lib/syslog.pl>, included with Perl 3.0.
1577 It was converted as a module with Perl 5.0, but had a version number
1578 only starting with Perl 5.6.  Here is a small table with the matching
1579 Perl and C<Sys::Syslog> versions.
1580
1581     Sys::Syslog     Perl
1582     -----------     ----
1583        undef        5.0.0 ~ 5.5.4
1584        0.01         5.6.*
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
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.*
1596
1597
1598 =head1 SEE ALSO
1599
1600 =head2 Other modules
1601
1602 L<Log::Log4perl> - Perl implementation of the Log4j API
1603
1604 L<Log::Dispatch> - Dispatches messages to one or more outputs
1605
1606 L<Log::Report> - Report a problem, with exceptions and language support
1607
1608 =head2 Manual Pages
1609
1610 L<syslog(3)>
1611
1612 SUSv3 issue 6, IEEE Std 1003.1, 2004 edition,
1613 L<http://www.opengroup.org/onlinepubs/000095399/basedefs/syslog.h.html>
1614
1615 GNU C Library documentation on syslog,
1616 L<http://www.gnu.org/software/libc/manual/html_node/Syslog.html>
1617
1618 FreeBSD documentation on syslog,
1619 L<https://www.freebsd.org/cgi/man.cgi?query=syslog>
1620
1621 Solaris 11 documentation on syslog,
1622 L<https://docs.oracle.com/cd/E53394_01/html/E54766/syslog-3c.html>
1623
1624 Mac OS X documentation on syslog,
1625 L<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/syslog.3.html>
1626
1627 IRIX documentation on syslog,
1628 L<http://nixdoc.net/man-pages/IRIX/man3/syslog.3c.html>
1629
1630 AIX 5L 5.3 documentation on syslog,
1631 L<http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf2/syslog.htm>
1632
1633 HP-UX 11i documentation on syslog,
1634 L<http://docs.hp.com/en/B2355-60130/syslog.3C.html>
1635
1636 Tru64 documentation on syslog,
1637 L<http://nixdoc.net/man-pages/Tru64/man3/syslog.3.html>
1638
1639 Stratus VOS 15.1,
1640 L<http://stratadoc.stratus.com/vos/15.1.1/r502-01/wwhelp/wwhimpl/js/html/wwhelp.htm?context=r502-01&file=ch5r502-01bi.html>
1641
1642 =head2 RFCs
1643
1644 I<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 
1646 specify a standard of any kind.
1647
1648 I<RFC 3195 - Reliable Delivery for syslog>, L<http://www.faqs.org/rfcs/rfc3195.html>
1649
1650 =head2 Articles
1651
1652 I<Syslogging with Perl>, L<http://lexington.pm.org/meetings/022001.html>
1653
1654 =head2 Event Log
1655
1656 Windows Event Log,
1657 L<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wes/wes/windows_event_log.asp>
1658
1659
1660 =head1 AUTHORS & ACKNOWLEDGEMENTS
1661
1662 Tom Christiansen E<lt>F<tchrist (at) perl.com>E<gt> and Larry Wall
1663 E<lt>F<larry (at) wall.org>E<gt>.
1664
1665 UNIX domain sockets added by Sean Robinson
1666 E<lt>F<robinson_s (at) sc.maricopa.edu>E<gt> with support from Tim Bunce 
1667 E<lt>F<Tim.Bunce (at) ig.co.uk>E<gt> and the C<perl5-porters> mailing list.
1668
1669 Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
1670 E<lt>F<tom (at) compton.nu>E<gt>.
1671
1672 Code for C<constant()>s regenerated by Nicholas Clark E<lt>F<nick (at) ccl4.org>E<gt>.
1673
1674 Failover to different communication modes by Nick Williams
1675 E<lt>F<Nick.Williams (at) morganstanley.com>E<gt>.
1676
1677 Extracted from core distribution for publishing on the CPAN by 
1678 SE<eacute>bastien Aperghis-Tramoni E<lt>sebastien (at) aperghis.netE<gt>.
1679
1680 XS code for using native C functions borrowed from C<L<Unix::Syslog>>, 
1681 written by Marcus Harnisch E<lt>F<marcus.harnisch (at) gmx.net>E<gt>.
1682
1683 Yves Orton suggested and helped for making C<Sys::Syslog> use the native 
1684 event logger under Win32 systems.
1685
1686 Jerry D. Hedden and Reini Urban provided greatly appreciated help to 
1687 debug and polish C<Sys::Syslog> under Cygwin.
1688
1689
1690 =head1 BUGS
1691
1692 Please report any bugs or feature requests to
1693 C<bug-sys-syslog (at) rt.cpan.org>, or through the web interface at
1694 L<http://rt.cpan.org/Public/Dist/Display.html?Name=Sys-Syslog>.
1695 I will be notified, and then you'll automatically be notified of progress on
1696 your bug as I make changes.
1697
1698
1699 =head1 SUPPORT
1700
1701 You can find documentation for this module with the perldoc command.
1702
1703     perldoc Sys::Syslog
1704
1705 You can also look for information at:
1706
1707 =over
1708
1709 =item * Perl Documentation
1710
1711 L<http://perldoc.perl.org/Sys/Syslog.html>
1712
1713 =item * MetaCPAN
1714
1715 L<https://metacpan.org/module/Sys::Syslog>
1716
1717 =item * Search CPAN
1718
1719 L<http://search.cpan.org/dist/Sys-Syslog/>
1720
1721 =item * AnnoCPAN: Annotated CPAN documentation
1722
1723 L<http://annocpan.org/dist/Sys-Syslog>
1724
1725 =item * CPAN Ratings
1726
1727 L<http://cpanratings.perl.org/d/Sys-Syslog>
1728
1729 =item * RT: CPAN's request tracker
1730
1731 L<http://rt.cpan.org/Dist/Display.html?Queue=Sys-Syslog>
1732
1733 =back
1734
1735 The source code is available on Git Hub:
1736 L<https://github.com/maddingue/Sys-Syslog/>
1737
1738
1739 =head1 COPYRIGHT
1740
1741 Copyright (C) 1990-2012 by Larry Wall and others.
1742
1743
1744 =head1 LICENSE
1745
1746 This program is free software; you can redistribute it and/or modify it
1747 under the same terms as Perl itself.
1748
1749 =cut
1750
1751 =begin comment
1752
1753 Notes for the future maintainer (even if it's still me..)
1754 - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1755
1756 Using Google Code Search, I search who on Earth was relying on $host being 
1757 public. It found 5 hits: 
1758
1759 * First was inside Indigo Star Perl2exe documentation. Just an old version 
1760 of Sys::Syslog. 
1761
1762
1763 * One real hit was inside DalWeathDB, a weather related program. It simply 
1764 does 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
1775 but also has this strange piece of code:
1776
1777     # work around perl5.003 bug
1778     sub Sys::Syslog::hostname {}
1779
1780 I don't know what bug the author referred to.
1781
1782 - L<http://www.tpc.int/>
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 (!).
1787 This 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
1795 I guess this was a more elaborate form of the previous bit, maybe because 
1796 of a bug in Sys::Syslog back then?
1797
1798 - L<ftp://ftp.kiae.su/pub/unix/fido/>
1799
1800
1801 Links
1802 -----
1803 Linux Fast-STREAMS
1804 - L<http://www.openss7.org/streams.html>
1805
1806 II12021: SYSLOGD HOWTO TCPIPINFO (z/OS, OS/390, MVS)
1807 - L<http://www-1.ibm.com/support/docview.wss?uid=isg1II12021>
1808
1809 Getting the most out of the Event Viewer
1810 - L<http://www.codeproject.com/dotnet/evtvwr.asp?print=true>
1811
1812 Log events to the Windows NT Event Log with JNI
1813 - L<http://www.javaworld.com/javaworld/jw-09-2001/jw-0928-ntmessages.html>
1814
1815 =end comment
1816