-
Notifications
You must be signed in to change notification settings - Fork 2
/
syslogd.c
2342 lines (2100 loc) · 52.9 KB
/
syslogd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $NetBSD: syslogd.c,v 1.86 2008/07/21 13:36:59 lukem Exp $ */
/*
* Copyright (c) 1983, 1988, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#ifndef lint
__COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993, 1994\
The Regents of the University of California. All rights reserved.");
#endif /* not lint */
#ifndef lint
#if 0
static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
#else
__RCSID("$NetBSD: syslogd.c,v 1.86 2008/07/21 13:36:59 lukem Exp $");
#endif
#endif /* not lint */
/*
* syslogd -- log system messages
*
* This program implements a system log. It takes a series of lines.
* Each line may have a priority, signified as "<n>" as
* the first characters of the line. If this is
* not present, a default priority is used.
*
* To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
* cause it to reread its configuration file.
*
* Defined Constants:
*
* MAXLINE -- the maximimum line length that can be handled.
* DEFUPRI -- the default priority for user messages
* DEFSPRI -- the default priority for kernel messages
*
* Author: Eric Allman
* extensive changes by Ralph Campbell
* more extensive changes by Eric Allman (again)
* Extension to log by program name as well as facility and priority
* by Peter da Silva.
* -U and -v by Harlan Stenn.
* Priority comparison code by Harlan Stenn.
*/
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <sys/queue.h>
#include <sys/event.h>
#include <netinet/in.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <locale.h>
#include <netdb.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <util.h>
#include "utmpentry.h"
#include "pathnames.h"
#define SYSLOG_NAMES
#include "syslogd.h"
#ifdef LIBWRAP
#include <tcpd.h>
int allow_severity = LOG_AUTH|LOG_INFO;
int deny_severity = LOG_AUTH|LOG_WARNING;
#endif
/*
* Queue of about-to-be-dead processes we should watch out for.
*/
TAILQ_HEAD(, deadq_entry) deadq_head = TAILQ_HEAD_INITIALIZER(deadq_head);
typedef struct deadq_entry {
pid_t dq_pid;
int dq_timeout;
TAILQ_ENTRY(deadq_entry) dq_entries;
} *dq_t;
char *ConfFile = _PATH_LOGCONF;
char ctty[] = _PATH_CONSOLE;
/*
* The timeout to apply to processes waiting on the dead queue. Unit
* of measure is "mark intervals", i.e. 20 minutes by default.
* Processes on the dead queue will be terminated after that time.
*/
#define DQ_TIMO_INIT 2
int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
char *TypeNames[8] = {
"UNUSED", "FILE", "TTY", "CONSOLE",
"FORW", "USERS", "WALL", "PIPE"
};
struct filed *Files;
struct filed consfile;
int Debug; /**< debug flag */
int daemonized = 0; /* we are not daemonized yet */
char LocalHostName[MAXHOSTNAMELEN]; /**< our hostname */
char oldLocalHostName[MAXHOSTNAMELEN];/**< previous hostname */
char *LocalDomain; /**< our local domain name */
char publickey[MAXPATHLEN];
char privkey[MAXPATHLEN];
char cert[MAXPATHLEN];
size_t LocalDomainLen; /**< length of LocalDomain */
int *finet = NULL; /**< Internet datagram sockets @bug Add support for Signature Groups*/
int Initialized; /**< set when we have initialized ourselves */
int ShuttingDown; /* set when we die() */
int MarkInterval = 20 * 60; /* interval between marks in seconds */
int MarkSeq = 0; /* mark sequence number */
int SecureMode = 0; /* listen only on unix domain socks */
int UseNameService = 1; /* make domain name queries */
int NumForwards = 0; /* number of forwarding actions in conf file */
char **LogPaths; /* array of pathnames to read messages from */
int NoRepeat = 0; /* disable "repeated"; log always */
int RemoteAddDate = 0; /* always add date to messages from network */
int SyncKernel = 0; /* write kernel messages synchronously */
int UniquePriority = 0; /* only log specified priority */
int LogFacPri = 0; /* put facility and priority in log messages: */
/* 0=no, 1=numeric, 2=names */
void cfline(char *, struct filed *, char *, char *);
char *cvthname(struct sockaddr_storage *);
void deadq_enter(pid_t, const char *);
int deadq_remove(pid_t);
int decode(const char *, CODE *);
void die(struct kevent *); /* SIGTERM kevent dispatch routine */
void domark(struct kevent *);/* timer kevent dispatch routine */
void fprintlog(struct filed *, int, char *);
int getmsgbufsize(void);
int* socksetup(int, const char *);
void init(struct kevent *); /* SIGHUP kevent dispatch routine */
void logerror(const char *, ...);
void logmsg(int, char *, char *, int);
void log_deadchild(pid_t, int, const char *);
int matches_spec(const char *, const char *,
char *(*)(const char *, const char *));
void printline(char *, char *, int);
void printsys(char *);
int p_open(char *, pid_t *);
void trim_localdomain(char *);
void reapchild(struct kevent *); /* SIGCHLD kevent dispatch routine */
void usage(void);
void wallmsg(struct filed *, struct iovec *, size_t);
int main(int, char *[]);
void logpath_add(char ***, int *, int *, char *);
void logpath_fileadd(char ***, int *, int *, char *);
static int fkq;
static struct kevent *allocevchange(void);
static int wait_for_events(struct kevent *, size_t);
static void dispatch_read_klog(struct kevent *);
static void dispatch_read_finet(struct kevent *);
static void dispatch_read_funix(struct kevent *);
/*
* Global line buffer. Since we only process one event at a time,
* a global one will do.
*/
static char *linebuf;
static size_t linebufsize;
static const char *bindhostname = NULL;
#define A_CNT(x) (sizeof((x)) / sizeof((x)[0]))
int
main(int argc, char *argv[])
{
int ch, *funix, j, fklog;
int funixsize = 0, funixmaxsize = 0;
struct kevent events[16];
struct sockaddr_un sunx;
char **pp;
struct kevent *ev;
uid_t uid = 0;
gid_t gid = 0;
char *user = NULL;
char *group = NULL;
char *root = "/";
char *endp;
struct group *gr;
struct passwd *pw;
unsigned long l;
(void)setlocale(LC_ALL, "");
while ((ch = getopt(argc, argv, "b:dnsSf:m:p:P:ru:g:t:TUvC:K:k")) != -1)
switch(ch) {
case 'b':
bindhostname = optarg;
break;
case 'C':
strlcpy(cert, optarg, strlen(optarg) + 1);
break;
case 'd': /* debug */
Debug++;
break;
case 'f': /* configuration file */
ConfFile = optarg;
break;
case 'g':
group = optarg;
if (*group == '\0')
usage();
break;
case 'm': /* mark interval */
MarkInterval = atoi(optarg) * 60;
break;
case 'n': /* turn off DNS queries */
UseNameService = 0;
break;
case 'p': /* path */
logpath_add(&LogPaths, &funixsize,
&funixmaxsize, optarg);
break;
case 'P': /* file of paths */
logpath_fileadd(&LogPaths, &funixsize,
&funixmaxsize, optarg);
break;
case 'r': /* disable "repeated" compression */
NoRepeat++;
break;
case 'k':
strlcpy(publickey, optarg, strlen(optarg) + 1);
break;
case 'K':
strlcpy(privkey, optarg, strlen(optarg) + 1);
break;
case 's': /* no network listen mode */
SecureMode++;
break;
case 'S':
SyncKernel = 1;
break;
case 't':
root = optarg;
if (*root == '\0')
usage();
break;
case 'T':
RemoteAddDate = 1;
break;
case 'u':
user = optarg;
if (*user == '\0')
usage();
break;
case 'U': /* only log specified priority */
UniquePriority = 1;
break;
case 'v': /* log facility and priority */
if (LogFacPri < 2)
LogFacPri++;
break;
default:
usage();
}
if ((argc -= optind) != 0)
usage();
setlinebuf(stdout);
if (user != NULL) {
if (isdigit((unsigned char)*user)) {
errno = 0;
endp = NULL;
l = strtoul(user, &endp, 0);
if (errno || *endp != '\0')
goto getuser;
uid = (uid_t)l;
if (uid != l) {
errno = 0;
logerror("UID out of range");
die(NULL);
}
} else {
getuser:
if ((pw = getpwnam(user)) != NULL) {
uid = pw->pw_uid;
} else {
errno = 0;
logerror("Cannot find user `%s'", user);
die(NULL);
}
}
}
if (group != NULL) {
if (isdigit((unsigned char)*group)) {
errno = 0;
endp = NULL;
l = strtoul(group, &endp, 0);
if (errno || *endp != '\0')
goto getgroup;
gid = (gid_t)l;
if (gid != l) {
errno = 0;
logerror("GID out of range");
die(NULL);
}
} else {
getgroup:
if ((gr = getgrnam(group)) != NULL) {
gid = gr->gr_gid;
} else {
errno = 0;
logerror("Cannot find group `%s'", group);
die(NULL);
}
}
}
if (access(root, F_OK | R_OK)) {
logerror("Cannot access `%s'", root);
die(NULL);
}
consfile.f_type = F_CONSOLE;
(void)strlcpy(consfile.f_un.f_fname, ctty,
sizeof(consfile.f_un.f_fname));
linebufsize = getmsgbufsize();
if (linebufsize < MAXLINE)
linebufsize = MAXLINE;
linebufsize++;
linebuf = malloc(linebufsize);
if (linebuf == NULL) {
logerror("Couldn't allocate line buffer");
die(NULL);
}
#ifndef SUN_LEN
#define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
#endif
if (funixsize == 0)
logpath_add(&LogPaths, &funixsize,
&funixmaxsize, _PATH_LOG);
funix = (int *)malloc(sizeof(int) * funixsize);
if (funix == NULL) {
logerror("Couldn't allocate funix descriptors");
die(NULL);
}
for (j = 0, pp = LogPaths; *pp; pp++, j++) {
dprintf("Making unix dgram socket `%s'\n", *pp);
unlink(*pp);
memset(&sunx, 0, sizeof(sunx));
sunx.sun_family = AF_LOCAL;
(void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
if (funix[j] < 0 || bind(funix[j],
(struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
chmod(*pp, 0666) < 0) {
logerror("Cannot create `%s'", *pp);
die(NULL);
}
dprintf("Listening on unix dgram socket `%s'\n", *pp);
}
if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
dprintf("Can't open `%s' (%d)\n", _PATH_KLOG, errno);
} else {
dprintf("Listening on kernel log `%s'\n", _PATH_KLOG);
}
/*
* All files are open, we can drop privileges and chroot
*/
/* dprintf("Attempt to chroot to `%s'\n", root);
if (chroot(root)) {
logerror("Failed to chroot to `%s'", root);
die(NULL);
}
dprintf("Attempt to set GID/EGID to `%d'\n", gid);
if (setgid(gid) || setegid(gid)) {
logerror("Failed to set gid to `%d'", gid);
die(NULL);
}*/
dprintf("Attempt to set UID/EUID to `%d'\n", uid);
if (setuid(uid) || seteuid(uid)) {
logerror("Failed to set uid to `%d'", uid);
die(NULL);
}
/*
* We cannot detach from the terminal before we are sure we won't
* have a fatal error, because error message would not go to the
* terminal and would not be logged because syslogd dies.
* All die() calls are behind us, we can call daemon()
*/
if (!Debug) {
(void)daemon(0, 0);
daemonized = 1;
/* tuck my process id away, if i'm not in debug mode */
pidfile(NULL);
}
/*
* Create the global kernel event descriptor.
*
* NOTE: We MUST do this after daemon(), bacause the kqueue()
* API dictates that kqueue descriptors are not inherited
* across forks (lame!).
*/
if ((fkq = kqueue()) < 0) {
logerror("Cannot create event queue");
die(NULL); /* XXX This error is lost! */
}
/*
* We must read the configuration file for the first time
* after the kqueue descriptor is created, because we install
* events during this process.
*/
init(NULL);
/* Initialize message queue list. */
syslog_msg_queue_init();
/* Initialize SSL/sign module */
syslog_ssl_init();
syslog_sign_init();
/** Create default message queue */
/**
* @todo Add support for more than one Signature Group, Fir this adding SD elements to
* standard syslog libc interface would be required.
* @bug Don't support more than one Signature Group ID
*/
syslog_msg_queue_create(SYSLOG_MSG_QUEUE_LENGTH, SYSLOG_MSG_QUEUE_SG_ID);
/*
* Always exit on SIGTERM. Also exit on SIGINT and SIGQUIT
* if we're debugging.
*/
(void)signal(SIGTERM, SIG_IGN);
(void)signal(SIGINT, SIG_IGN);
(void)signal(SIGQUIT, SIG_IGN);
ev = allocevchange();
EV_SET(ev, SIGTERM, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
(intptr_t) die);
if (Debug) {
ev = allocevchange();
EV_SET(ev, SIGINT, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
(intptr_t) die);
ev = allocevchange();
EV_SET(ev, SIGQUIT, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
(intptr_t) die);
}
ev = allocevchange();
EV_SET(ev, SIGCHLD, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
(intptr_t) reapchild);
ev = allocevchange();
EV_SET(ev, 0, EVFILT_TIMER, EV_ADD | EV_ENABLE, 0,
TIMERINTVL * 1000 /* seconds -> ms */, (intptr_t) domark);
(void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
/* Re-read configuration on SIGHUP. */
(void) signal(SIGHUP, SIG_IGN);
ev = allocevchange();
EV_SET(ev, SIGHUP, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
(intptr_t) init);
if (fklog >= 0) {
ev = allocevchange();
EV_SET(ev, fklog, EVFILT_READ, EV_ADD | EV_ENABLE,
0, 0, (intptr_t) dispatch_read_klog);
}
for (j = 0, pp = LogPaths; *pp; pp++, j++) {
ev = allocevchange();
EV_SET(ev, funix[j], EVFILT_READ, EV_ADD | EV_ENABLE,
0, 0, (intptr_t) dispatch_read_funix);
}
dprintf("Off & running....\n");
for (;;) {
void (*handler)(struct kevent *);
int i, rv;
rv = wait_for_events(events, A_CNT(events));
if (rv == 0)
continue;
if (rv < 0) {
if (errno != EINTR)
logerror("kevent() failed");
continue;
}
dprintf("Got an event (%d)\n", rv);
for (i = 0; i < rv; i++) {
handler = (void *) events[i].udata;
(*handler)(&events[i]);
}
}
}
void
usage(void)
{
(void)fprintf(stderr,
"usage: %s [-dnrSsTUv] [-b bind_address] [-f config_file] [-g group]\n"
"\t[-m mark_interval] [-P file_list] [-p log_socket\n"
"\t[-p log_socket2 ...]] [-t chroot_dir] [-u user]\n",
getprogname());
exit(1);
}
/*
* Dispatch routine for reading /dev/klog
*/
static void
dispatch_read_klog(struct kevent *ev)
{
ssize_t rv;
int fd = ev->ident;
dprintf("Kernel log active\n");
rv = read(fd, linebuf, linebufsize - 1);
if (rv > 0) {
linebuf[rv] = '\0';
printsys(linebuf);
} else if (rv < 0 && errno != EINTR) {
/*
* /dev/klog has croaked. Disable the event
* so it won't bother us again.
*/
struct kevent *cev = allocevchange();
logerror("klog failed");
EV_SET(cev, fd, EVFILT_READ, EV_DISABLE,
0, 0, (intptr_t) dispatch_read_klog);
}
}
/*
* Dispatch routine for reading Unix domain sockets.
*/
static void
dispatch_read_funix(struct kevent *ev)
{
struct sockaddr_un myname, fromunix;
ssize_t rv;
socklen_t sunlen;
int fd = ev->ident;
sunlen = sizeof(myname);
if (getsockname(fd, (struct sockaddr *)&myname, &sunlen) != 0) {
/*
* This should never happen, so ensure that it doesn't
* happen again.
*/
struct kevent *cev = allocevchange();
logerror("getsockname() unix failed");
EV_SET(cev, fd, EVFILT_READ, EV_DISABLE,
0, 0, (intptr_t) dispatch_read_funix);
return;
}
dprintf("Unix socket (%s) active\n", myname.sun_path);
sunlen = sizeof(fromunix);
rv = recvfrom(fd, linebuf, MAXLINE, 0,
(struct sockaddr *)&fromunix, &sunlen);
if (rv > 0) {
linebuf[rv] = '\0';
printline(LocalHostName, linebuf, 0);
} else if (rv < 0 && errno != EINTR) {
logerror("recvfrom() unix `%s'", myname.sun_path);
}
}
/*
* Dispatch routine for reading Internet sockets.
*/
static void
dispatch_read_finet(struct kevent *ev)
{
#ifdef LIBWRAP
struct request_info req;
#endif
struct sockaddr_storage frominet;
ssize_t rv;
socklen_t len;
int fd = ev->ident;
int reject = 0;
dprintf("inet socket active\n");
#ifdef LIBWRAP
request_init(&req, RQ_DAEMON, "syslogd", RQ_FILE, fd, NULL);
fromhost(&req);
reject = !hosts_access(&req);
if (reject)
dprintf("access denied\n");
#endif
len = sizeof(frominet);
rv = recvfrom(fd, linebuf, MAXLINE, 0,
(struct sockaddr *)&frominet, &len);
if (rv == 0 || (rv < 0 && errno == EINTR))
return;
else if (rv < 0) {
logerror("recvfrom inet");
return;
}
linebuf[rv] = '\0';
if (!reject)
printline(cvthname(&frominet), linebuf,
RemoteAddDate ? ADDDATE : 0);
}
/*
* given a pointer to an array of char *'s, a pointer to its current
* size and current allocated max size, and a new char * to add, add
* it, update everything as necessary, possibly allocating a new array
*/
void
logpath_add(char ***lp, int *szp, int *maxszp, char *new)
{
char **nlp;
int newmaxsz;
dprintf("Adding `%s' to the %p logpath list\n", new, *lp);
if (*szp == *maxszp) {
if (*maxszp == 0) {
newmaxsz = 4; /* start of with enough for now */
*lp = NULL;
} else
newmaxsz = *maxszp * 2;
nlp = realloc(*lp, sizeof(char *) * (newmaxsz + 1));
if (nlp == NULL) {
logerror("Couldn't allocate line buffer");
die(NULL);
}
*lp = nlp;
*maxszp = newmaxsz;
}
if (((*lp)[(*szp)++] = strdup(new)) == NULL) {
logerror("Couldn't allocate logpath");
die(NULL);
}
(*lp)[(*szp)] = NULL; /* always keep it NULL terminated */
}
/* do a file of log sockets */
void
logpath_fileadd(char ***lp, int *szp, int *maxszp, char *file)
{
FILE *fp;
char *line;
size_t len;
fp = fopen(file, "r");
if (fp == NULL) {
logerror("Could not open socket file list `%s'", file);
die(NULL);
}
while ((line = fgetln(fp, &len))) {
line[len - 1] = 0;
logpath_add(lp, szp, maxszp, line);
}
fclose(fp);
}
/*
* Take a raw input line, decode the message, and print the message
* on the appropriate log files.
*/
/*!
* This function is called from every dispatch routine to get
* data processed.
*/
void
printline(char *hname, char *msg, int flags)
{
int c, pri;
char *p, *q, line[MAXLINE + 1];
long n;
dprintf("printline: %s %s %s\n", hname, LocalHostName, msg);
/* test for special codes */
pri = DEFUPRI;
p = msg;
if (*p == '<') {
errno = 0;
n = strtol(p + 1, &q, 10);
if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
p = q + 1;
pri = (int)n;
}
}
if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
pri = DEFUPRI;
/*
* Don't allow users to log kernel messages.
* NOTE: Since LOG_KERN == 0, this will also match
* messages with no facility specified.
*/
if ((pri & LOG_FACMASK) == LOG_KERN)
pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
q = line;
while ((c = *p++) != '\0' &&
q < &line[sizeof(line) - 2]) {
c &= 0177;
if (iscntrl(c))
if (c == '\n')
*q++ = ' ';
else if (c == '\t')
*q++ = '\t';
else {
*q++ = '^';
*q++ = c ^ 0100;
}
else
*q++ = c;
}
*q = '\0';
logmsg(pri, line, hname, flags);
}
/*
* Take a raw input line from /dev/klog, split and format similar to syslog().
*/
void
printsys(char *msg)
{
int n, pri, flags, is_printf;
char *p, *q;
for (p = msg; *p != '\0'; ) {
flags = ISKERNEL | ADDDATE;
if (SyncKernel)
flags |= SYNC_FILE;
pri = DEFSPRI;
is_printf = 1;
if (*p == '<') {
errno = 0;
n = (int)strtol(p + 1, &q, 10);
if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
p = q + 1;
pri = n;
is_printf = 0;
}
}
if (is_printf) {
/* kernel printf's come out on console */
flags |= IGN_CONS;
}
if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
pri = DEFSPRI;
for (q = p; *q != '\0' && *q != '\n'; q++)
/* look for end of line */;
if (*q != '\0')
*q++ = '\0';
logmsg(pri, p, LocalHostName, flags);
p = q;
}
}
time_t now;
/*
* Check to see if `name' matches the provided specification, using the
* specified strstr function.
*/
int
matches_spec(const char *name, const char *spec,
char *(*check)(const char *, const char *))
{
const char *s;
const char *cursor;
char prev, next;
size_t len;
if (name[0] == '\0')
return (0);
if (strchr(name, ',')) /* sanity */
return (0);
len = strlen(name);
cursor = spec;
while ((s = (*check)(cursor, name)) != NULL) {
prev = s == spec ? ',' : *(s - 1);
cursor = s + len;
next = *cursor;
if (prev == ',' && (next == '\0' || next == ','))
return (1);
}
return (0);
}
/*
* Log a message to the appropriate log files, users, etc. based on
* the priority.
*/
void
logmsg(int pri, char *msg, char *from, int flags)
{
msg_t *mssg;
struct filed *f;
int fac, msglen, omask, prilev, i;
char *timestamp, *header, *sd;
char prog[NAME_MAX + 1];
char buf[MAXLINE + 1];
mssg = syslog_msg_create();
dprintf("logmsg: pri 0%o, flags 0x%x, from %s, msg %s\n",
pri, flags, from, msg);
omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
/*
* Check to see if msg looks non-standard
*/
msglen = strlen(msg);
if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
flags |= ADDDATE;
(void)time(&now);
if (flags & ADDDATE) {
timestamp = ctime(&now) + 4;
timestamp[strlen(timestamp) - 2] = '\0';
} else {
timestamp = msg;
msg += 15;
msglen -= 16;
*msg = '\0';
msg++;
}
/* skip leading whitespace */
while (isspace((unsigned char)*msg)) {
msg++;
msglen--;
}
/* extract facility and priority level */
if (flags & MARK)
fac = LOG_NFACILITIES;
else
fac = LOG_FAC(pri);
prilev = LOG_PRI(pri);
/* extract program name */
for (i = 0; i < NAME_MAX; i++) {
if (!isprint((unsigned char)msg[i]) ||
msg[i] == ':')
break;
prog[i] = msg[i];
}
prog[i] = '\0';
header = syslog_msg_header_create(pri, from, timestamp, prog, -1, mssg->msg_id);
sd = syslog_msg_sd_create();
syslog_msg_set_line(msg, mssg);
syslog_msg_set_header(header, mssg);
syslog_msg_set_sd(sd, mssg);
dprintf("### %s %s %s\n", mssg->header, mssg->sd, mssg->line);
sd = syslog_msg_message_create(mssg);
syslog_msg_queue_add(SYSLOG_MSG_QUEUE_SG_ID, mssg);
/* add kernel prefix for kernel messages */
if (flags & ISKERNEL) {
snprintf(buf, sizeof(buf), "%s: %s",
_PATH_UNIX, msg);
msg = buf;
msglen = strlen(buf);
}
/* log the message to the particular outputs */
if (!Initialized) {
f = &consfile;
f->f_file = open(ctty, O_WRONLY, 0);
if (f->f_file >= 0) {
(void)strncpy(f->f_lasttime, timestamp, 15);
fprintlog(f, flags, msg);
(void)close(f->f_file);
}
(void)sigsetmask(omask);
return;
}
for (f = Files; f; f = f->f_next) {
/* skip messages that are incorrect priority */
if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
)
|| f->f_pmask[fac] == INTERNAL_NOPRI)
continue;
/* skip messages with the incorrect host name */
if (f->f_host != NULL) {
switch (f->f_host[0]) {
case '+':
if (! matches_spec(from, f->f_host + 1,
strcasestr))
continue;
break;
case '-':
if (matches_spec(from, f->f_host + 1,
strcasestr))
continue;
break;
}
}
/* skip messages with the incorrect program name */
if (f->f_program != NULL) {
switch (f->f_program[0]) {
case '+':
if (! matches_spec(prog, f->f_program + 1,
strstr))
continue;
break;
case '-':
if (matches_spec(prog, f->f_program + 1,
strstr))
continue;
break;
default:
if (! matches_spec(prog, f->f_program,
strstr))
continue;
break;
}
}
if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
continue;