The .pm changes to go with #10428.
[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.02';
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 Code for constant()s regenerated by Nicholas Clark E<lt>nick@ccl4.orgE<gt>.
123
124 =cut
125
126 sub AUTOLOAD {
127     # This AUTOLOAD is used to 'autoload' constants from the constant()
128     # XS function.
129
130     my $constname;
131     our $AUTOLOAD;
132     ($constname = $AUTOLOAD) =~ s/.*:://;
133     croak "&Sys::Syslog::constant not defined" if $constname eq 'constant';
134     my ($error, $val) = constant($constname);
135     if ($error) {
136         croak $error;
137     }
138     *$AUTOLOAD = sub { $val };
139     goto &$AUTOLOAD;
140 }
141
142 bootstrap Sys::Syslog $VERSION;
143
144 $maskpri = &LOG_UPTO(&LOG_DEBUG);
145
146 sub openlog {
147     ($ident, $logopt, $facility) = @_;  # package vars
148     $lo_pid = $logopt =~ /\bpid\b/;
149     $lo_ndelay = $logopt =~ /\bndelay\b/;
150     $lo_cons = $logopt =~ /\bcons\b/;
151     $lo_nowait = $logopt =~ /\bnowait\b/;
152     return 1 unless $lo_ndelay;
153     &connect;
154
155
156 sub closelog {
157     $facility = $ident = '';
158     &disconnect;
159
160
161 sub setlogmask {
162     local($oldmask) = $maskpri;
163     $maskpri = shift;
164     $oldmask;
165 }
166  
167 sub setlogsock {
168     local($setsock) = shift;
169     &disconnect if $connected;
170     if (lc($setsock) eq 'unix') {
171         if (length _PATH_LOG()) {
172             $sock_type = 1;
173         } else {
174             return undef;
175         }
176     } elsif (lc($setsock) eq 'inet') {
177         if (getservbyname('syslog','udp')) {
178             undef($sock_type);
179         } else {
180             return undef;
181         }
182     } else {
183         croak "Invalid argument passed to setlogsock; must be 'unix' or 'inet'";
184     }
185     return 1;
186 }
187
188 sub syslog {
189     local($priority) = shift;
190     local($mask) = shift;
191     local($message, $whoami);
192     local(@words, $num, $numpri, $numfac, $sum);
193     local($facility) = $facility;       # may need to change temporarily.
194
195     croak "syslog: expected both priority and mask" unless $mask && $priority;
196
197     @words = split(/\W+/, $priority, 2);# Allow "level" or "level|facility".
198     undef $numpri;
199     undef $numfac;
200     foreach (@words) {
201         $num = &xlate($_);              # Translate word to number.
202         if (/^kern$/ || $num < 0) {
203             croak "syslog: invalid level/facility: $_";
204         }
205         elsif ($num <= &LOG_PRIMASK) {
206             croak "syslog: too many levels given: $_" if defined($numpri);
207             $numpri = $num;
208             return 0 unless &LOG_MASK($numpri) & $maskpri;
209         }
210         else {
211             croak "syslog: too many facilities given: $_" if defined($numfac);
212             $facility = $_;
213             $numfac = $num;
214         }
215     }
216
217     croak "syslog: level must be given" unless defined($numpri);
218
219     if (!defined($numfac)) {    # Facility not specified in this call.
220         $facility = 'user' unless $facility;
221         $numfac = &xlate($facility);
222     }
223
224     &connect unless $connected;
225
226     $whoami = $ident;
227
228     if (!$whoami && $mask =~ /^(\S.*?):\s?(.*)/) {
229         $whoami = $1;
230         $mask = $2;
231     } 
232
233     unless ($whoami) {
234         ($whoami = getlogin) ||
235             ($whoami = getpwuid($<)) ||
236                 ($whoami = 'syslog');
237     }
238
239     $whoami .= "[$$]" if $lo_pid;
240
241     $mask =~ s/%m/$!/g;
242     $mask .= "\n" unless $mask =~ /\n$/;
243     $message = sprintf ($mask, @_);
244
245     $sum = $numpri + $numfac;
246     unless (send(SYSLOG,"<$sum>$whoami: $message\0",0)) {
247         if ($lo_cons) {
248             if ($pid = fork) {
249                 unless ($lo_nowait) {
250                     $died = waitpid($pid, 0);
251                 }
252             }
253             else {
254                 if (open(CONS,">/dev/console")) {
255                     print CONS "<$facility.$priority>$whoami: $message\r";
256                     close CONS;
257                 }
258                 exit if defined $pid;           # if fork failed, we're parent
259             }
260         }
261     }
262 }
263
264 sub xlate {
265     local($name) = @_;
266     $name = uc $name;
267     $name = "LOG_$name" unless $name =~ /^LOG_/;
268     $name = "Sys::Syslog::$name";
269     # Can't have just eval { &$name } || -1 because some LOG_XXX may be zero.
270     my $value = eval { &$name };
271     defined $value ? $value : -1;
272 }
273
274 sub connect {
275     unless ($host) {
276         require Sys::Hostname;
277         my($host_uniq) = Sys::Hostname::hostname();
278         ($host) = $host_uniq =~ /([A-Za-z0-9_.-]+)/; # allow FQDN (inc _)
279     }
280     unless ( $sock_type ) {
281         my $udp = getprotobyname('udp')                 || croak "getprotobyname failed for udp";
282         my $syslog = getservbyname('syslog','udp')      || croak "getservbyname failed";
283         my $this = sockaddr_in($syslog, INADDR_ANY);
284         my $that = sockaddr_in($syslog, inet_aton($host) || croak "Can't lookup $host");
285         socket(SYSLOG,AF_INET,SOCK_DGRAM,$udp)           || croak "socket: $!";
286         connect(SYSLOG,$that)                            || croak "connect: $!";
287     } else {
288         my $syslog = _PATH_LOG();
289         length($syslog)                                  || croak "_PATH_LOG unavailable in syslog.h";
290         my $that = sockaddr_un($syslog)                  || croak "Can't locate $syslog";
291         socket(SYSLOG,AF_UNIX,SOCK_STREAM,0)             || croak "socket: $!";
292         if (!connect(SYSLOG,$that)) {
293             socket(SYSLOG,AF_UNIX,SOCK_DGRAM,0)          || croak "socket: $!";
294             connect(SYSLOG,$that) || croak "connect: $! (SOCK_DGRAM after trying SOCK_STREAM)";
295         }
296     }
297     local($old) = select(SYSLOG); $| = 1; select($old);
298     $connected = 1;
299 }
300
301 sub disconnect {
302     close SYSLOG;
303     $connected = 0;
304 }
305
306 1;