more pod patches
[p5sagit/p5-mst-13.2.git] / ext / Sys / Syslog / Syslog.pm
1 package Sys::Syslog;
2 require 5.000;
3 require Exporter;
4 require DynaLoader;
5 use Carp;
6
7 @ISA = qw(Exporter DynaLoader);
8 @EXPORT = qw(openlog closelog setlogmask syslog);
9 @EXPORT_OK = qw(setlogsock);
10 $VERSION = '0.01';
11
12 use Socket;
13 use Sys::Hostname;
14
15 # adapted from syslog.pl
16 #
17 # Tom Christiansen <tchrist@convex.com>
18 # modified to use sockets by Larry Wall <lwall@jpl-devvax.jpl.nasa.gov>
19 # NOTE: openlog now takes three arguments, just like openlog(3)
20 # Modified to add UNIX domain sockets by Sean Robinson <robinson_s@sc.maricopa.edu>
21 #  with support from Tim Bunce <Tim.Bunce@ig.co.uk> and the perl5-porters mailing list
22 # Modified to use an XS backend instead of syslog.ph by Tom Hughes <tom@compton.nu>
23
24 # Todo: enable connect to try all three types before failing (auto setlogsock)?
25
26 =head1 NAME
27
28 Sys::Syslog, openlog, closelog, setlogmask, syslog - Perl interface to the UNIX syslog(3) calls
29
30 =head1 SYNOPSIS
31
32     use Sys::Syslog;                          # all except setlogsock, or:
33     use Sys::Syslog qw(:DEFAULT setlogsock);  # default set, plus setlogsock
34
35     setlogsock $sock_type;
36     openlog $ident, $logopt, $facility;
37     syslog $priority, $format, @args;
38     $oldmask = setlogmask $mask_priority;
39     closelog;
40
41 =head1 DESCRIPTION
42
43 Sys::Syslog is an interface to the UNIX C<syslog(3)> program.
44 Call C<syslog()> with a string priority and a list of C<printf()> args
45 just like C<syslog(3)>.
46
47 Syslog provides the functions:
48
49 =over 4
50
51 =item openlog $ident, $logopt, $facility
52
53 I<$ident> is prepended to every message.
54 I<$logopt> contains zero or more of the words I<pid>, I<ndelay>, I<cons>, I<nowait>.
55 I<$facility> specifies the part of the system
56
57 =item syslog $priority, $format, @args
58
59 If I<$priority> permits, logs I<($format, @args)>
60 printed as by C<printf(3V)>, with the addition that I<%m>
61 is replaced with C<"$!"> (the latest error message).
62
63 =item setlogmask $mask_priority
64
65 Sets log mask I<$mask_priority> and returns the old mask.
66
67 =item setlogsock $sock_type (added in 5.004_02)
68
69 Sets the socket type to be used for the next call to
70 C<openlog()> or C<syslog()> and returns TRUE on success,
71 undef on failure.
72
73 A value of 'unix' will connect to the UNIX domain socket returned by the
74 C<_PATH_LOG> macro (if you system defines it) in F<syslog.h>.  A value of
75 'inet' will connect to an INET socket returned by getservbyname().  If
76 C<_PATH_LOG> is unavailable or if getservbyname() fails, returns undef.  Any
77 other value croaks.
78
79 The default is for the INET socket to be used.
80
81 =item closelog
82
83 Closes the log file.
84
85 =back
86
87 Note that C<openlog> now takes three arguments, just like C<openlog(3)>.
88
89 =head1 EXAMPLES
90
91     openlog($program, 'cons,pid', 'user');
92     syslog('info', 'this is another test');
93     syslog('mail|warning', 'this is a better test: %d', time);
94     closelog();
95
96     syslog('debug', 'this is the last test');
97
98     setlogsock('unix');
99     openlog("$program $$", 'ndelay', 'user');
100     syslog('notice', 'fooprogram: this is really done');
101
102     setlogsock('inet');
103     $! = 55;
104     syslog('info', 'problem was %m'); # %m == $! in syslog(3)
105
106 =head1 SEE ALSO
107
108 L<syslog(3)>
109
110 =head1 AUTHOR
111
112 Tom Christiansen E<lt>F<tchrist@perl.com>E<gt> and Larry Wall
113 E<lt>F<larry@wall.org>E<gt>.
114
115 UNIX domain sockets added by Sean Robinson
116 E<lt>F<robinson_s@sc.maricopa.edu>E<gt> with support from Tim Bunce
117 E<lt>F<Tim.Bunce@ig.co.uk>E<gt> and the perl5-porters mailing list.
118
119 Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
120 E<lt>F<tom@compton.nu>E<gt>.
121
122 =cut
123
124 sub AUTOLOAD {
125     # This AUTOLOAD is used to 'autoload' constants from the constant()
126     # XS function.
127
128     my $constname;
129     our $AUTOLOAD;
130     ($constname = $AUTOLOAD) =~ s/.*:://;
131     croak "& not defined" if $constname eq 'constant';
132     my $val = constant($constname);
133     if ($! != 0) {
134         croak "Your vendor has not defined Sys::Syslog macro $constname";
135     }
136     *$AUTOLOAD = sub { $val };
137     goto &$AUTOLOAD;
138 }
139
140 bootstrap Sys::Syslog $VERSION;
141
142 $maskpri = &LOG_UPTO(&LOG_DEBUG);
143
144 sub openlog {
145     ($ident, $logopt, $facility) = @_;  # package vars
146     $lo_pid = $logopt =~ /\bpid\b/;
147     $lo_ndelay = $logopt =~ /\bndelay\b/;
148     $lo_cons = $logopt =~ /\bcons\b/;
149     $lo_nowait = $logopt =~ /\bnowait\b/;
150     return 1 unless $lo_ndelay;
151     &connect;
152
153
154 sub closelog {
155     $facility = $ident = '';
156     &disconnect;
157
158
159 sub setlogmask {
160     local($oldmask) = $maskpri;
161     $maskpri = shift;
162     $oldmask;
163 }
164  
165 sub setlogsock {
166     local($setsock) = shift;
167     &disconnect if $connected;
168     if (lc($setsock) eq 'unix') {
169         if (length _PATH_LOG()) {
170             $sock_type = 1;
171         } else {
172             return undef;
173         }
174     } elsif (lc($setsock) eq 'inet') {
175         if (getservbyname('syslog','udp')) {
176             undef($sock_type);
177         } else {
178             return undef;
179         }
180     } else {
181         croak "Invalid argument passed to setlogsock; must be 'unix' or 'inet'";
182     }
183     return 1;
184 }
185
186 sub syslog {
187     local($priority) = shift;
188     local($mask) = shift;
189     local($message, $whoami);
190     local(@words, $num, $numpri, $numfac, $sum);
191     local($facility) = $facility;       # may need to change temporarily.
192
193     croak "syslog: expected both priority and mask" unless $mask && $priority;
194
195     @words = split(/\W+/, $priority, 2);# Allow "level" or "level|facility".
196     undef $numpri;
197     undef $numfac;
198     foreach (@words) {
199         $num = &xlate($_);              # Translate word to number.
200         if (/^kern$/ || $num < 0) {
201             croak "syslog: invalid level/facility: $_";
202         }
203         elsif ($num <= &LOG_PRIMASK) {
204             croak "syslog: too many levels given: $_" if defined($numpri);
205             $numpri = $num;
206             return 0 unless &LOG_MASK($numpri) & $maskpri;
207         }
208         else {
209             croak "syslog: too many facilities given: $_" if defined($numfac);
210             $facility = $_;
211             $numfac = $num;
212         }
213     }
214
215     croak "syslog: level must be given" unless defined($numpri);
216
217     if (!defined($numfac)) {    # Facility not specified in this call.
218         $facility = 'user' unless $facility;
219         $numfac = &xlate($facility);
220     }
221
222     &connect unless $connected;
223
224     $whoami = $ident;
225
226     if (!$whoami && $mask =~ /^(\S.*?):\s?(.*)/) {
227         $whoami = $1;
228         $mask = $2;
229     } 
230
231     unless ($whoami) {
232         ($whoami = getlogin) ||
233             ($whoami = getpwuid($<)) ||
234                 ($whoami = 'syslog');
235     }
236
237     $whoami .= "[$$]" if $lo_pid;
238
239     $mask =~ s/%m/$!/g;
240     $mask .= "\n" unless $mask =~ /\n$/;
241     $message = sprintf ($mask, @_);
242
243     $sum = $numpri + $numfac;
244     unless (send(SYSLOG,"<$sum>$whoami: $message\0",0)) {
245         if ($lo_cons) {
246             if ($pid = fork) {
247                 unless ($lo_nowait) {
248                     $died = waitpid($pid, 0);
249                 }
250             }
251             else {
252                 if (open(CONS,">/dev/console")) {
253                     print CONS "<$facility.$priority>$whoami: $message\r";
254                     close CONS;
255                 }
256                 exit if defined $pid;           # if fork failed, we're parent
257             }
258         }
259     }
260 }
261
262 sub xlate {
263     local($name) = @_;
264     $name = uc $name;
265     $name = "LOG_$name" unless $name =~ /^LOG_/;
266     $name = "Sys::Syslog::$name";
267     # Can't have just eval { &$name } || -1 because some LOG_XXX may be zero.
268     my $value = eval { &$name };
269     defined $value ? $value : -1;
270 }
271
272 sub connect {
273     unless ($host) {
274         require Sys::Hostname;
275         my($host_uniq) = Sys::Hostname::hostname();
276         ($host) = $host_uniq =~ /([A-Za-z0-9_.-]+)/; # allow FQDN (inc _)
277     }
278     unless ( $sock_type ) {
279         my $udp = getprotobyname('udp')                 || croak "getprotobyname failed for udp";
280         my $syslog = getservbyname('syslog','udp')      || croak "getservbyname failed";
281         my $this = sockaddr_in($syslog, INADDR_ANY);
282         my $that = sockaddr_in($syslog, inet_aton($host) || croak "Can't lookup $host");
283         socket(SYSLOG,AF_INET,SOCK_DGRAM,$udp)           || croak "socket: $!";
284         connect(SYSLOG,$that)                            || croak "connect: $!";
285     } else {
286         my $syslog = _PATH_LOG();
287         length($syslog)                                  || croak "_PATH_LOG unavailable in syslog.h";
288         my $that = sockaddr_un($syslog)                  || croak "Can't locate $syslog";
289         socket(SYSLOG,AF_UNIX,SOCK_STREAM,0)             || croak "socket: $!";
290         if (!connect(SYSLOG,$that)) {
291             socket(SYSLOG,AF_UNIX,SOCK_DGRAM,0)          || croak "socket: $!";
292             connect(SYSLOG,$that) || croak "connect: $! (SOCK_DGRAM after trying SOCK_STREAM)";
293         }
294     }
295     local($old) = select(SYSLOG); $| = 1; select($old);
296     $connected = 1;
297 }
298
299 sub disconnect {
300     close SYSLOG;
301     $connected = 0;
302 }
303
304 1;