Merge from vendor branch LIBSTDC++:
[dragonfly.git] / contrib / ipfilter / ipmon.c
1 /* $FreeBSD: src/contrib/ipfilter/ipmon.c,v 1.5.2.7 2003/03/01 03:55:51 darrenr Exp $ */
2 /* $DragonFly: src/contrib/ipfilter/ipmon.c,v 1.2 2003/06/17 04:24:02 dillon Exp $ */
3 /*
4  * Copyright (C) 1993-2002 by Darren Reed.
5  *
6  * See the IPFILTER.LICENCE file for details on licencing.
7  */
8 #ifndef SOLARIS
9 #define SOLARIS (defined(__SVR4) || defined(__svr4__)) && defined(sun)
10 #endif
11
12 #if defined(__sgi) && (IRIX > 602)
13 # include <sys/ptimers.h>
14 #endif
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <sys/param.h>
18 #include <sys/file.h>
19 #include <sys/time.h>
20 #include <sys/socket.h>
21 #include <sys/ioctl.h>
22
23 #include <stdio.h>
24 #include <unistd.h>
25 #include <string.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #if !defined(__SVR4) && !defined(__svr4__)
29 # if (__FreeBSD_version >= 300000)
30 #  include <sys/dirent.h>
31 # else
32 #  include <sys/dir.h>
33 # endif
34 #else
35 # include <sys/filio.h>
36 # include <sys/byteorder.h>
37 #endif
38 #if !defined(__SVR4) && !defined(__GNUC__)
39 # include <strings.h>
40 #endif
41 #include <signal.h>
42 #include <stdlib.h>
43 #include <stddef.h>
44 #include <netinet/in.h>
45 #include <netinet/in_systm.h>
46 #include <net/if.h>
47 #include <netinet/ip.h>
48 #include <netinet/tcp_fsm.h>
49 #include <netdb.h>
50 #include <arpa/inet.h>
51 #include <arpa/nameser.h>
52 #include <resolv.h>
53
54 #ifndef linux
55 # include <sys/protosw.h>
56 # include <netinet/ip_var.h>
57 #endif
58
59 #include <netinet/tcp.h>
60 #include <netinet/ip_icmp.h>
61
62 #include <ctype.h>
63 #include <syslog.h>
64
65 #include "netinet/ip_compat.h"
66 #include <netinet/tcpip.h>
67 #include "netinet/ip_fil.h"
68 #include "netinet/ip_nat.h"
69 #include "netinet/ip_state.h"
70
71 #if !defined(lint)
72 static const char sccsid[] = "@(#)ipmon.c       1.21 6/5/96 (C)1993-2000 Darren Reed";
73 static const char rcsid[] = "@(#)$Id: ipmon.c,v 2.12.2.37 2002/12/06 11:40:26 darrenr Exp $";
74 #endif
75
76
77 #if     defined(sun) && !defined(SOLARIS2)
78 #define STRERROR(x)     sys_errlist[x]
79 extern  char    *sys_errlist[];
80 #else
81 #define STRERROR(x)     strerror(x)
82 #endif
83
84
85 struct  flags {
86         int     value;
87         char    flag;
88 };
89
90
91 typedef struct  icmp_subtype {
92         int     ist_val;
93         char    *ist_name;
94 } icmp_subtype_t;
95
96 typedef struct  icmp_type {
97         int     it_val;
98         struct  icmp_subtype *it_subtable;
99         size_t  it_stsize;
100         char    *it_name;
101 } icmp_type_t;
102
103
104 #define IST_SZ(x)       (sizeof(x)/sizeof(icmp_subtype_t))
105
106
107 struct  flags   tcpfl[] = {
108         { TH_ACK, 'A' },
109         { TH_RST, 'R' },
110         { TH_SYN, 'S' },
111         { TH_FIN, 'F' },
112         { TH_URG, 'U' },
113         { TH_PUSH,'P' },
114         { TH_ECN, 'E' },
115         { TH_CWR, 'C' },
116         { 0, '\0' }
117 };
118
119 #if SOLARIS
120 static  char    *pidfile = "/etc/opt/ipf/ipmon.pid";
121 #else
122 # if BSD >= 199306
123 static  char    *pidfile = "/var/run/ipmon.pid";
124 # else
125 static  char    *pidfile = "/etc/ipmon.pid";
126 # endif
127 #endif
128
129 static  char    line[2048];
130 static  int     opts = 0;
131 static  FILE    *newlog = NULL;
132 static  char    *logfile = NULL;
133 static  int     donehup = 0;
134 static  void    usage __P((char *));
135 static  void    handlehup __P((int));
136 static  void    flushlogs __P((char *, FILE *));
137 static  void    print_log __P((int, FILE *, char *, int));
138 static  void    print_ipflog __P((FILE *, char *, int));
139 static  void    print_natlog __P((FILE *, char *, int));
140 static  void    print_statelog __P((FILE *, char *, int));
141 static  void    dumphex __P((FILE *, u_char *, int));
142 static  int     read_log __P((int, int *, char *, int));
143 static  void    write_pid __P((char *));
144 static  char    *icmpname __P((u_int, u_int));
145 static  char    *icmpname6 __P((u_int, u_int));
146 static  icmp_type_t *find_icmptype __P((int, icmp_type_t *, size_t));
147 static  icmp_subtype_t *find_icmpsubtype __P((int, icmp_subtype_t *, size_t));
148
149 char    *hostname __P((int, int, u_32_t *));
150 char    *portname __P((int, char *, u_int));
151 int     main __P((int, char *[]));
152
153 static  void    logopts __P((int, char *));
154 static  void    init_tabs __P((void));
155 static  char    *getproto __P((u_int));
156
157 static  char    **protocols = NULL;
158 static  char    **udp_ports = NULL;
159 static  char    **tcp_ports = NULL;
160
161 #define OPT_SYSLOG      0x001
162 #define OPT_RESOLVE     0x002
163 #define OPT_HEXBODY     0x004
164 #define OPT_VERBOSE     0x008
165 #define OPT_HEXHDR      0x010
166 #define OPT_TAIL        0x020
167 #define OPT_NAT         0x080
168 #define OPT_STATE       0x100
169 #define OPT_FILTER      0x200
170 #define OPT_PORTNUM     0x400
171 #define OPT_LOGALL      (OPT_NAT|OPT_STATE|OPT_FILTER)
172 #define OPT_LOGBODY     0x800
173
174 #define HOSTNAME_V4(a,b)        hostname((a), 4, (u_32_t *)&(b))
175
176 #ifndef LOGFAC
177 #define LOGFAC  LOG_LOCAL0
178 #endif
179
180
181 static icmp_subtype_t icmpunreachnames[] = {
182         { ICMP_UNREACH_NET,             "net" },
183         { ICMP_UNREACH_HOST,            "host" },
184         { ICMP_UNREACH_PROTOCOL,        "protocol" },
185         { ICMP_UNREACH_PORT,            "port" },
186         { ICMP_UNREACH_NEEDFRAG,        "needfrag" },
187         { ICMP_UNREACH_SRCFAIL,         "srcfail" },
188         { ICMP_UNREACH_NET_UNKNOWN,     "net_unknown" },
189         { ICMP_UNREACH_HOST_UNKNOWN,    "host_unknown" },
190         { ICMP_UNREACH_NET,             "isolated" },
191         { ICMP_UNREACH_NET_PROHIB,      "net_prohib" },
192         { ICMP_UNREACH_NET_PROHIB,      "host_prohib" },
193         { ICMP_UNREACH_TOSNET,          "tosnet" },
194         { ICMP_UNREACH_TOSHOST,         "toshost" },
195         { ICMP_UNREACH_ADMIN_PROHIBIT,  "admin_prohibit" },
196         { -2,                           NULL }
197 };
198
199 static icmp_subtype_t redirectnames[] = {
200         { ICMP_REDIRECT_NET,            "net" },
201         { ICMP_REDIRECT_HOST,           "host" },
202         { ICMP_REDIRECT_TOSNET,         "tosnet" },
203         { ICMP_REDIRECT_TOSHOST,        "toshost" },
204         { -2,                           NULL }
205 };
206
207 static icmp_subtype_t timxceednames[] = {
208         { ICMP_TIMXCEED_INTRANS,        "transit" },
209         { ICMP_TIMXCEED_REASS,          "reassem" },
210         { -2,                           NULL }
211 };
212
213 static icmp_subtype_t paramnames[] = {
214         { ICMP_PARAMPROB_ERRATPTR,      "errata_pointer" },
215         { ICMP_PARAMPROB_OPTABSENT,     "optmissing" },
216         { ICMP_PARAMPROB_LENGTH,        "length" },
217         { -2,                           NULL }
218 };
219
220 static icmp_type_t icmptypes[] = {
221         { ICMP_ECHOREPLY,       NULL,   0,              "echoreply" },
222         { -1,                   NULL,   0,              NULL },
223         { -1,                   NULL,   0,              NULL },
224         { ICMP_UNREACH,         icmpunreachnames,
225                                 IST_SZ(icmpunreachnames),"unreach" },
226         { ICMP_SOURCEQUENCH,    NULL,   0,              "sourcequench" },
227         { ICMP_REDIRECT,        redirectnames,
228                                 IST_SZ(redirectnames),  "redirect" },
229         { -1,                   NULL,   0,              NULL },
230         { -1,                   NULL,   0,              NULL },
231         { ICMP_ECHO,            NULL,   0,              "echo" },
232         { ICMP_ROUTERADVERT,    NULL,   0,              "routeradvert" },
233         { ICMP_ROUTERSOLICIT,   NULL,   0,              "routersolicit" },
234         { ICMP_TIMXCEED,        timxceednames,
235                                 IST_SZ(timxceednames),  "timxceed" },
236         { ICMP_PARAMPROB,       paramnames,
237                                 IST_SZ(paramnames),     "paramprob" },
238         { ICMP_TSTAMP,          NULL,   0,              "timestamp" },
239         { ICMP_TSTAMPREPLY,     NULL,   0,              "timestampreply" },
240         { ICMP_IREQ,            NULL,   0,              "inforeq" },
241         { ICMP_IREQREPLY,       NULL,   0,              "inforeply" },
242         { ICMP_MASKREQ,         NULL,   0,              "maskreq" },
243         { ICMP_MASKREPLY,       NULL,   0,              "maskreply" },
244         { -2,                   NULL,   0,              NULL }
245 };
246
247 static icmp_subtype_t icmpredirect6[] = {
248         { ICMP6_DST_UNREACH_NOROUTE,            "noroute" },
249         { ICMP6_DST_UNREACH_ADMIN,              "admin" },
250         { ICMP6_DST_UNREACH_NOTNEIGHBOR,        "neighbour" },
251         { ICMP6_DST_UNREACH_ADDR,               "address" },
252         { ICMP6_DST_UNREACH_NOPORT,             "noport" },
253         { -2,                                   NULL }
254 };
255
256 static icmp_subtype_t icmptimexceed6[] = {
257         { ICMP6_TIME_EXCEED_TRANSIT,            "intransit" },
258         { ICMP6_TIME_EXCEED_REASSEMBLY,         "reassem" },
259         { -2,                                   NULL }
260 };
261
262 static icmp_subtype_t icmpparamprob6[] = {
263         { ICMP6_PARAMPROB_HEADER,               "header" },
264         { ICMP6_PARAMPROB_NEXTHEADER,           "nextheader" },
265         { ICMP6_PARAMPROB_OPTION,               "option" },
266         { -2,                                   NULL }
267 };
268
269 static icmp_subtype_t icmpquerysubject6[] = {
270         { ICMP6_NI_SUBJ_IPV6,                   "ipv6" },
271         { ICMP6_NI_SUBJ_FQDN,                   "fqdn" },
272         { ICMP6_NI_SUBJ_IPV4,                   "ipv4" },
273         { -2,                                   NULL },
274 };
275
276 static icmp_subtype_t icmpnodeinfo6[] = {
277         { ICMP6_NI_SUCCESS,                     "success" },
278         { ICMP6_NI_REFUSED,                     "refused" },
279         { ICMP6_NI_UNKNOWN,                     "unknown" },
280         { -2,                                   NULL }
281 };
282
283 static icmp_subtype_t icmprenumber6[] = {
284         { ICMP6_ROUTER_RENUMBERING_COMMAND,             "command" },
285         { ICMP6_ROUTER_RENUMBERING_RESULT,              "result" },
286         { ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET,        "seqnum_reset" },
287         { -2,                                           NULL }
288 };
289
290 static icmp_type_t icmptypes6[] = {
291         { 0,                    NULL,   0,              NULL },
292         { ICMP6_DST_UNREACH,    icmpredirect6,
293                         IST_SZ(icmpredirect6),          "unreach" },
294         { ICMP6_PACKET_TOO_BIG, NULL,   0,              "toobig" },
295         { ICMP6_TIME_EXCEEDED,  icmptimexceed6,
296                         IST_SZ(icmptimexceed6),         "timxceed" },
297         { ICMP6_PARAM_PROB,     icmpparamprob6,
298                         IST_SZ(icmpparamprob6),         "paramprob" },
299         { ICMP6_ECHO_REQUEST,   NULL,   0,              "echo" },
300         { ICMP6_ECHO_REPLY,     NULL,   0,              "echoreply" },
301         { ICMP6_MEMBERSHIP_QUERY, icmpquerysubject6,
302                         IST_SZ(icmpquerysubject6),      "groupmemberquery" },
303         { ICMP6_MEMBERSHIP_REPORT,NULL, 0,              "groupmemberreport" },
304         { ICMP6_MEMBERSHIP_REDUCTION,NULL,      0,      "groupmemberterm" },
305         { ND_ROUTER_SOLICIT,    NULL,   0,              "routersolicit" },
306         { ND_ROUTER_ADVERT,     NULL,   0,              "routeradvert" },
307         { ND_NEIGHBOR_SOLICIT,  NULL,   0,              "neighborsolicit" },
308         { ND_NEIGHBOR_ADVERT,   NULL,   0,              "neighboradvert" },
309         { ND_REDIRECT,          NULL,   0,              "redirect" },
310         { ICMP6_ROUTER_RENUMBERING,     icmprenumber6,
311                         IST_SZ(icmprenumber6),          "routerrenumber" },
312         { ICMP6_WRUREQUEST,     NULL,   0,              "whoareyourequest" },
313         { ICMP6_WRUREPLY,       NULL,   0,              "whoareyoureply" },
314         { ICMP6_FQDN_QUERY,     NULL,   0,              "fqdnquery" },
315         { ICMP6_FQDN_REPLY,     NULL,   0,              "fqdnreply" },
316         { ICMP6_NI_QUERY,       icmpnodeinfo6,
317                         IST_SZ(icmpnodeinfo6),          "nodeinforequest" },
318         { ICMP6_NI_REPLY,       NULL,   0,              "nodeinforeply" },
319         { MLD6_MTRACE_RESP,     NULL,   0,              "mtraceresponse" },
320         { MLD6_MTRACE,          NULL,   0,              "mtracerequest" },
321         { -2,                   NULL,   0,              NULL }
322 };
323
324 static icmp_subtype_t *find_icmpsubtype(type, table, tablesz)
325 int type;
326 icmp_subtype_t *table;
327 size_t tablesz;
328 {
329         icmp_subtype_t *ist;
330         int i;
331
332         if (tablesz < 2)
333                 return NULL;
334
335         if ((type < 0) || (type > table[tablesz - 2].ist_val))
336                 return NULL;
337
338         i = type;
339         if (table[type].ist_val == type)
340                 return table + type;
341
342         for (i = 0, ist = table; ist->ist_val != -2; i++, ist++)
343                 if (ist->ist_val == type)
344                         return ist;
345         return NULL;
346 }
347
348
349 static icmp_type_t *find_icmptype(type, table, tablesz)
350 int type;
351 icmp_type_t *table;
352 size_t tablesz;
353 {
354         icmp_type_t *it;
355         int i;
356
357         if (tablesz < 2)
358                 return NULL;
359
360         if ((type < 0) || (type > table[tablesz - 2].it_val))
361                 return NULL;
362
363         i = type;
364         if (table[type].it_val == type)
365                 return table + type;
366
367         for (i = 0, it = table; it->it_val != -2; i++, it++)
368                 if (it->it_val == type)
369                         return it;
370         return NULL;
371 }
372
373
374 static void handlehup(sig)
375 int sig;
376 {
377         FILE    *fp;
378
379         signal(SIGHUP, handlehup);
380         if (logfile && (fp = fopen(logfile, "a")))
381                 newlog = fp;
382         init_tabs();
383         donehup = 1;
384 }
385
386
387 static void init_tabs()
388 {
389         struct  protoent        *p;
390         struct  servent *s;
391         char    *name, **tab;
392         int     port;
393
394         if (protocols != NULL) {
395                 free(protocols);
396                 protocols = NULL;
397         }
398         protocols = (char **)malloc(256 * sizeof(*protocols));
399         if (protocols != NULL) {
400                 bzero((char *)protocols, 256 * sizeof(*protocols));
401
402                 setprotoent(1);
403                 while ((p = getprotoent()) != NULL)
404                         if (p->p_proto >= 0 && p->p_proto <= 255 &&
405                             p->p_name != NULL && protocols[p->p_proto] == NULL)
406                                 protocols[p->p_proto] = strdup(p->p_name);
407                 endprotoent();
408         }
409
410         if (udp_ports != NULL) {
411                 free(udp_ports);
412                 udp_ports = NULL;
413         }
414         udp_ports = (char **)malloc(65536 * sizeof(*udp_ports));
415         if (udp_ports != NULL)
416                 bzero((char *)udp_ports, 65536 * sizeof(*udp_ports));
417
418         if (tcp_ports != NULL) {
419                 free(tcp_ports);
420                 tcp_ports = NULL;
421         }
422         tcp_ports = (char **)malloc(65536 * sizeof(*tcp_ports));
423         if (tcp_ports != NULL)
424                 bzero((char *)tcp_ports, 65536 * sizeof(*tcp_ports));
425
426         setservent(1);
427         while ((s = getservent()) != NULL) {
428                 if (s->s_proto == NULL)
429                         continue;
430                 else if (!strcmp(s->s_proto, "tcp")) {
431                         port = ntohs(s->s_port);
432                         name = s->s_name;
433                         tab = tcp_ports;
434                 } else if (!strcmp(s->s_proto, "udp")) {
435                         port = ntohs(s->s_port);
436                         name = s->s_name;
437                         tab = udp_ports;
438                 } else
439                         continue;
440                 if ((port < 0 || port > 65535) || (name == NULL))
441                         continue;
442                 tab[port] = strdup(name);
443         }
444         endservent();
445 }
446
447
448 static char *getproto(p)
449 u_int p;
450 {
451         static char pnum[4];
452         char *s;
453
454         p &= 0xff;
455         s = protocols ? protocols[p] : NULL;
456         if (s == NULL) {
457                 sprintf(pnum, "%u", p);
458                 s = pnum;
459         }
460         return s;
461 }
462
463
464 static int read_log(fd, lenp, buf, bufsize)
465 int fd, bufsize, *lenp;
466 char *buf;
467 {
468         int     nr;
469
470         nr = read(fd, buf, bufsize);
471         if (!nr)
472                 return 2;
473         if ((nr < 0) && (errno != EINTR))
474                 return -1;
475         *lenp = nr;
476         return 0;
477 }
478
479
480 char    *hostname(res, v, ip)
481 int     res, v;
482 u_32_t  *ip;
483 {
484 # define MAX_INETA      16
485         static char hname[MAXHOSTNAMELEN + MAX_INETA + 3];
486 #ifdef  USE_INET6
487         static char hostbuf[MAXHOSTNAMELEN+1];
488 #endif
489         struct hostent *hp;
490         struct in_addr ipa;
491
492         if (v == 4) {
493                 ipa.s_addr = *ip;
494                 if (!res)
495                         return inet_ntoa(ipa);
496                 hp = gethostbyaddr((char *)ip, sizeof(*ip), AF_INET);
497                 if (!hp)
498                         return inet_ntoa(ipa);
499                 sprintf(hname, "%.*s[%s]", MAXHOSTNAMELEN, hp->h_name,
500                         inet_ntoa(ipa));
501                 return hname;
502         }
503 #ifdef  USE_INET6
504         (void) inet_ntop(AF_INET6, ip, hostbuf, sizeof(hostbuf) - 1);
505         hostbuf[MAXHOSTNAMELEN] = '\0';
506         return hostbuf;
507 #else
508         return "IPv6";
509 #endif
510 }
511
512
513 char    *portname(res, proto, port)
514 int     res;
515 char    *proto;
516 u_int   port;
517 {
518         static  char    pname[8];
519         char    *s;
520
521         port = ntohs(port);
522         port &= 0xffff;
523         (void) sprintf(pname, "%u", port);
524         if (!res || (opts & OPT_PORTNUM))
525                 return pname;
526         s = NULL;
527         if (!strcmp(proto, "tcp"))
528                 s = tcp_ports[port];
529         else if (!strcmp(proto, "udp"))
530                 s = udp_ports[port];
531         if (s == NULL)
532                 s = pname;
533         return s;
534 }
535
536
537 static  char    *icmpname(type, code)
538 u_int   type;
539 u_int   code;
540 {
541         static char name[80];
542         icmp_subtype_t *ist;
543         icmp_type_t *it;
544         char *s;
545
546         s = NULL;
547         it = find_icmptype(type, icmptypes, sizeof(icmptypes) / sizeof(*it));
548         if (it != NULL)
549                 s = it->it_name;
550
551         if (s == NULL)
552                 sprintf(name, "icmptype(%d)/", type);
553         else
554                 sprintf(name, "%s/", s);
555
556         ist = NULL;
557         if (it != NULL && it->it_subtable != NULL)
558                 ist = find_icmpsubtype(code, it->it_subtable, it->it_stsize);
559
560         if (ist != NULL && ist->ist_name != NULL)
561                 strcat(name, ist->ist_name);
562         else
563                 sprintf(name + strlen(name), "%d", code);
564
565         return name;
566 }
567
568 static  char    *icmpname6(type, code)
569 u_int   type;
570 u_int   code;
571 {
572         static char name[80];
573         icmp_subtype_t *ist;
574         icmp_type_t *it;
575         char *s;
576
577         s = NULL;
578         it = find_icmptype(type, icmptypes6, sizeof(icmptypes6) / sizeof(*it));
579         if (it != NULL)
580                 s = it->it_name;
581
582         if (s == NULL)
583                 sprintf(name, "icmpv6type(%d)/", type);
584         else
585                 sprintf(name, "%s/", s);
586
587         ist = NULL;
588         if (it != NULL && it->it_subtable != NULL)
589                 ist = find_icmpsubtype(code, it->it_subtable, it->it_stsize);
590
591         if (ist != NULL && ist->ist_name != NULL)
592                 strcat(name, ist->ist_name);
593         else
594                 sprintf(name + strlen(name), "%d", code);
595
596         return name;
597 }
598
599
600 static  void    dumphex(log, buf, len)
601 FILE    *log;
602 u_char  *buf;
603 int     len;
604 {
605         char    line[80];
606         int     i, j, k;
607         u_char  *s = buf, *t = (u_char *)line;
608
609         if (len == 0 || buf == 0)
610                 return;
611         *line = '\0';
612
613         for (i = len, j = 0; i; i--, j++, s++) {
614                 if (j && !(j & 0xf)) {
615                         *t++ = '\n';
616                         *t = '\0';
617                         if (!(opts & OPT_SYSLOG))
618                                 fputs(line, log);
619                         else
620                                 syslog(LOG_INFO, "%s", line);
621                         t = (u_char *)line;
622                         *t = '\0';
623                 }
624                 sprintf((char *)t, "%02x", *s & 0xff);
625                 t += 2;
626                 if (!((j + 1) & 0xf)) {
627                         s -= 15;
628                         sprintf((char *)t, "        ");
629                         t += 8;
630                         for (k = 16; k; k--, s++)
631                                 *t++ = (isprint(*s) ? *s : '.');
632                         s--;
633                 }
634                         
635                 if ((j + 1) & 0xf)
636                         *t++ = ' ';;
637         }
638
639         if (j & 0xf) {
640                 for (k = 16 - (j & 0xf); k; k--) {
641                         *t++ = ' ';
642                         *t++ = ' ';
643                         *t++ = ' ';
644                 }
645                 sprintf((char *)t, "       ");
646                 t += 7;
647                 s -= j & 0xf;
648                 for (k = j & 0xf; k; k--, s++)
649                         *t++ = (isprint(*s) ? *s : '.');
650                 *t++ = '\n';
651                 *t = '\0';
652         }
653         if (!(opts & OPT_SYSLOG)) {
654                 fputs(line, log);
655                 fflush(log);
656         } else
657                 syslog(LOG_INFO, "%s", line);
658 }
659
660 static  void    print_natlog(log, buf, blen)
661 FILE    *log;
662 char    *buf;
663 int     blen;
664 {
665         struct  natlog  *nl;
666         iplog_t *ipl = (iplog_t *)buf;
667         char    *t = line;
668         struct  tm      *tm;
669         int     res, i, len;
670         char    *proto;
671
672         nl = (struct natlog *)((char *)ipl + IPLOG_SIZE);
673         res = (opts & OPT_RESOLVE) ? 1 : 0;
674         tm = localtime((time_t *)&ipl->ipl_sec);
675         len = sizeof(line);
676         if (!(opts & OPT_SYSLOG)) {
677                 (void) strftime(t, len, "%d/%m/%Y ", tm);
678                 i = strlen(t);
679                 len -= i;
680                 t += i;
681         }
682         (void) strftime(t, len, "%T", tm);
683         t += strlen(t);
684         (void) sprintf(t, ".%-.6ld @%hd ", ipl->ipl_usec, nl->nl_rule + 1);
685         t += strlen(t);
686
687         if (nl->nl_type == NL_NEWMAP)
688                 strcpy(t, "NAT:MAP ");
689         else if (nl->nl_type == NL_NEWRDR)
690                 strcpy(t, "NAT:RDR ");
691         else if (nl->nl_type == NL_EXPIRE)
692                 strcpy(t, "NAT:EXPIRE ");
693         else if (nl->nl_type == NL_FLUSH)
694                 strcpy(t, "NAT:FLUSH ");
695         else if (nl->nl_type == NL_NEWBIMAP)
696                 strcpy(t, "NAT:BIMAP ");
697         else if (nl->nl_type == NL_NEWBLOCK)
698                 strcpy(t, "NAT:MAPBLOCK ");
699         else
700                 sprintf(t, "Type: %d ", nl->nl_type);
701         t += strlen(t);
702
703         proto = getproto(nl->nl_p);
704
705         (void) sprintf(t, "%s,%s <- -> ", HOSTNAME_V4(res, nl->nl_inip),
706                 portname(res, proto, (u_int)nl->nl_inport));
707         t += strlen(t);
708         (void) sprintf(t, "%s,%s ", HOSTNAME_V4(res, nl->nl_outip),
709                 portname(res, proto, (u_int)nl->nl_outport));
710         t += strlen(t);
711         (void) sprintf(t, "[%s,%s]", HOSTNAME_V4(res, nl->nl_origip),
712                 portname(res, proto, (u_int)nl->nl_origport));
713         t += strlen(t);
714         if (nl->nl_type == NL_EXPIRE) {
715 #ifdef  USE_QUAD_T
716                 (void) sprintf(t, " Pkts %qd Bytes %qd",
717                                 (long long)nl->nl_pkts,
718                                 (long long)nl->nl_bytes);
719 #else
720                 (void) sprintf(t, " Pkts %ld Bytes %ld",
721                                 nl->nl_pkts, nl->nl_bytes);
722 #endif
723                 t += strlen(t);
724         }
725
726         *t++ = '\n';
727         *t++ = '\0';
728         if (opts & OPT_SYSLOG)
729                 syslog(LOG_INFO, "%s", line);
730         else
731                 (void) fprintf(log, "%s", line);
732 }
733
734
735 static  void    print_statelog(log, buf, blen)
736 FILE    *log;
737 char    *buf;
738 int     blen;
739 {
740         struct  ipslog *sl;
741         iplog_t *ipl = (iplog_t *)buf;
742         char    *t = line, *proto;
743         struct  tm      *tm;
744         int     res, i, len;
745
746         sl = (struct ipslog *)((char *)ipl + IPLOG_SIZE);
747         res = (opts & OPT_RESOLVE) ? 1 : 0;
748         tm = localtime((time_t *)&ipl->ipl_sec);
749         len = sizeof(line);
750         if (!(opts & OPT_SYSLOG)) {
751                 (void) strftime(t, len, "%d/%m/%Y ", tm);
752                 i = strlen(t);
753                 len -= i;
754                 t += i;
755         }
756         (void) strftime(t, len, "%T", tm);
757         t += strlen(t);
758         (void) sprintf(t, ".%-.6ld ", ipl->ipl_usec);
759         t += strlen(t);
760
761         if (sl->isl_type == ISL_NEW)
762                 strcpy(t, "STATE:NEW ");
763         else if (sl->isl_type == ISL_EXPIRE) {
764                 if ((sl->isl_p == IPPROTO_TCP) &&
765                     (sl->isl_state[0] > TCPS_ESTABLISHED ||
766                      sl->isl_state[1] > TCPS_ESTABLISHED))
767                         strcpy(t, "STATE:CLOSE ");
768                 else
769                         strcpy(t, "STATE:EXPIRE ");
770         } else if (sl->isl_type == ISL_FLUSH)
771                 strcpy(t, "STATE:FLUSH ");
772         else if (sl->isl_type == ISL_REMOVE)
773                 strcpy(t, "STATE:REMOVE ");
774         else
775                 sprintf(t, "Type: %d ", sl->isl_type);
776         t += strlen(t);
777
778         proto = getproto(sl->isl_p);
779
780         if (sl->isl_p == IPPROTO_TCP || sl->isl_p == IPPROTO_UDP) {
781                 (void) sprintf(t, "%s,%s -> ",
782                         hostname(res, sl->isl_v, (u_32_t *)&sl->isl_src),
783                         portname(res, proto, (u_int)sl->isl_sport));
784                 t += strlen(t);
785                 (void) sprintf(t, "%s,%s PR %s",
786                         hostname(res, sl->isl_v, (u_32_t *)&sl->isl_dst),
787                         portname(res, proto, (u_int)sl->isl_dport), proto);
788         } else if (sl->isl_p == IPPROTO_ICMP) {
789                 (void) sprintf(t, "%s -> ", hostname(res, sl->isl_v,
790                                                      (u_32_t *)&sl->isl_src));
791                 t += strlen(t);
792                 (void) sprintf(t, "%s PR icmp %d",
793                         hostname(res, sl->isl_v, (u_32_t *)&sl->isl_dst),
794                         sl->isl_itype);
795         } else if (sl->isl_p == IPPROTO_ICMPV6) {
796                 (void) sprintf(t, "%s -> ", hostname(res, sl->isl_v,
797                                                      (u_32_t *)&sl->isl_src));
798                 t += strlen(t);
799                 (void) sprintf(t, "%s PR icmpv6 %d",
800                         hostname(res, sl->isl_v, (u_32_t *)&sl->isl_dst),
801                         sl->isl_itype);
802         }
803         t += strlen(t);
804         if (sl->isl_type != ISL_NEW) {
805 #ifdef  USE_QUAD_T
806                 (void) sprintf(t, " Pkts %qd Bytes %qd",
807                                 (long long)sl->isl_pkts,
808                                 (long long)sl->isl_bytes);
809 #else
810                 (void) sprintf(t, " Pkts %ld Bytes %ld",
811                                 sl->isl_pkts, sl->isl_bytes);
812 #endif
813                 t += strlen(t);
814         }
815
816         *t++ = '\n';
817         *t++ = '\0';
818         if (opts & OPT_SYSLOG)
819                 syslog(LOG_INFO, "%s", line);
820         else
821                 (void) fprintf(log, "%s", line);
822 }
823
824
825 static  void    print_log(logtype, log, buf, blen)
826 FILE    *log;
827 char    *buf;
828 int     logtype, blen;
829 {
830         iplog_t *ipl;
831         char *bp = NULL, *bpo = NULL;
832         int psize;
833
834         while (blen > 0) {
835                 ipl = (iplog_t *)buf;
836                 if ((u_long)ipl & (sizeof(long)-1)) {
837                         if (bp)
838                                 bpo = bp;
839                         bp = (char *)malloc(blen);
840                         bcopy((char *)ipl, bp, blen);
841                         if (bpo) {
842                                 free(bpo);
843                                 bpo = NULL;
844                         }
845                         buf = bp;
846                         continue;
847                 }
848                 if (ipl->ipl_magic != IPL_MAGIC) {
849                         /* invalid data or out of sync */
850                         break;
851                 }
852                 psize = ipl->ipl_dsize;
853                 switch (logtype)
854                 {
855                 case IPL_LOGIPF :
856                         print_ipflog(log, buf, psize);
857                         break;
858                 case IPL_LOGNAT :
859                         print_natlog(log, buf, psize);
860                         break;
861                 case IPL_LOGSTATE :
862                         print_statelog(log, buf, psize);
863                         break;
864                 }
865
866                 blen -= psize;
867                 buf += psize;
868         }
869         if (bp)
870                 free(bp);
871         return;
872 }
873
874
875 static  void    print_ipflog(log, buf, blen)
876 FILE    *log;
877 char    *buf;
878 int     blen;
879 {
880         tcphdr_t        *tp;
881         struct  icmp    *ic;
882         struct  icmp    *icmp;
883         struct  tm      *tm;
884         char    *t, *proto;
885         int     i, v, lvl, res, len, off, plen, ipoff;
886         ip_t    *ipc, *ip;
887         u_short hl, p;
888         ipflog_t *ipf;
889         iplog_t *ipl;
890         u_32_t  *s, *d;
891 #ifdef  USE_INET6
892         ip6_t *ip6;
893 #endif
894
895         ipl = (iplog_t *)buf;
896         ipf = (ipflog_t *)((char *)buf + IPLOG_SIZE);
897         ip = (ip_t *)((char *)ipf + sizeof(*ipf));
898         v = ip->ip_v;
899         res = (opts & OPT_RESOLVE) ? 1 : 0;
900         t = line;
901         *t = '\0';
902         tm = localtime((time_t *)&ipl->ipl_sec);
903 #ifdef  linux
904         if (v == 4)
905                 ip->ip_len = ntohs(ip->ip_len);
906 #endif
907
908         len = sizeof(line);
909         if (!(opts & OPT_SYSLOG)) {
910                 (void) strftime(t, len, "%d/%m/%Y ", tm);
911                 i = strlen(t);
912                 len -= i;
913                 t += i;
914         }
915         (void) strftime(t, len, "%T", tm);
916         t += strlen(t);
917         (void) sprintf(t, ".%-.6ld ", ipl->ipl_usec);
918         t += strlen(t);
919         if (ipl->ipl_count > 1) {
920                 (void) sprintf(t, "%dx ", ipl->ipl_count);
921                 t += strlen(t);
922         }
923 #if (SOLARIS || \
924         (defined(NetBSD) && (NetBSD <= 1991011) && (NetBSD >= 199603)) || \
925         (defined(OpenBSD) && (OpenBSD >= 199603))) || defined(linux)
926         {
927         char    ifname[sizeof(ipf->fl_ifname) + 1];
928
929         strncpy(ifname, (char *)ipf->fl_ifname, sizeof(ipf->fl_ifname));
930         ifname[sizeof(ipf->fl_ifname)] = '\0';
931         (void) sprintf(t, "%s", ifname);
932         t += strlen(t);
933 # if SOLARIS
934         if (isalpha(*(t - 1))) {
935                 sprintf(t, "%d", ipf->fl_unit);
936                 t += strlen(t);
937         }
938 # endif
939         }
940 #else
941         for (len = 0; len < 3; len++)
942                 if (ipf->fl_ifname[len] == '\0')
943                         break;
944         if (ipf->fl_ifname[len])
945                 len++;
946         (void) sprintf(t, "%*.*s%u", len, len, ipf->fl_ifname, ipf->fl_unit);
947         t += strlen(t);
948 #endif
949         if (ipf->fl_group == 0xffffffff)
950                 strcat(t, " @-1:");
951         else
952                 (void) sprintf(t, " @%u:", ipf->fl_group);
953         t += strlen(t);
954         if (ipf->fl_rule == 0xffffffff)
955                 strcat(t, "-1 ");
956         else
957                 (void) sprintf(t, "%u ", ipf->fl_rule + 1);
958         t += strlen(t);
959
960         if (ipf->fl_flags & FF_SHORT) {
961                 *t++ = 'S';
962                 lvl = LOG_ERR;
963         } else if (ipf->fl_flags & FR_PASS) {
964                 if (ipf->fl_flags & FR_LOG)
965                         *t++ = 'p';
966                 else
967                         *t++ = 'P';
968                 lvl = LOG_NOTICE;
969         } else if (ipf->fl_flags & FR_BLOCK) {
970                 if (ipf->fl_flags & FR_LOG)
971                         *t++ = 'b';
972                 else
973                         *t++ = 'B';
974                 lvl = LOG_WARNING;
975         } else if (ipf->fl_flags & FF_LOGNOMATCH) {
976                 *t++ = 'n';
977                 lvl = LOG_NOTICE;
978         } else {
979                 *t++ = 'L';
980                 lvl = LOG_INFO;
981         }
982         if (ipf->fl_loglevel != 0xffff)
983                 lvl = ipf->fl_loglevel;
984         *t++ = ' ';
985         *t = '\0';
986
987         if (v == 6) {
988 #ifdef  USE_INET6
989                 off = 0;
990                 ipoff = 0;
991                 hl = sizeof(ip6_t);
992                 ip6 = (ip6_t *)ip;
993                 p = (u_short)ip6->ip6_nxt;
994                 s = (u_32_t *)&ip6->ip6_src;
995                 d = (u_32_t *)&ip6->ip6_dst;
996                 plen = ntohs(ip6->ip6_plen);
997 #else
998                 sprintf(t, "ipv6");
999                 goto printipflog;
1000 #endif
1001         } else if (v == 4) {
1002                 hl = (ip->ip_hl << 2);
1003                 ipoff = ip->ip_off;
1004                 off = ipoff & IP_OFFMASK;
1005                 p = (u_short)ip->ip_p;
1006                 s = (u_32_t *)&ip->ip_src;
1007                 d = (u_32_t *)&ip->ip_dst;
1008                 plen = ip->ip_len;
1009         } else {
1010                 goto printipflog;
1011         }
1012         proto = getproto(p);
1013
1014         if ((p == IPPROTO_TCP || p == IPPROTO_UDP) && !off) {
1015                 tp = (tcphdr_t *)((char *)ip + hl);
1016                 if (!(ipf->fl_flags & FF_SHORT)) {
1017                         (void) sprintf(t, "%s,%s -> ", hostname(res, v, s),
1018                                 portname(res, proto, (u_int)tp->th_sport));
1019                         t += strlen(t);
1020                         (void) sprintf(t, "%s,%s PR %s len %hu %hu",
1021                                 hostname(res, v, d),
1022                                 portname(res, proto, (u_int)tp->th_dport),
1023                                 proto, hl, plen);
1024                         t += strlen(t);
1025
1026                         if (p == IPPROTO_TCP) {
1027                                 *t++ = ' ';
1028                                 *t++ = '-';
1029                                 for (i = 0; tcpfl[i].value; i++)
1030                                         if (tp->th_flags & tcpfl[i].value)
1031                                                 *t++ = tcpfl[i].flag;
1032                                 if (opts & OPT_VERBOSE) {
1033                                         (void) sprintf(t, " %lu %lu %hu",
1034                                                 (u_long)(ntohl(tp->th_seq)),
1035                                                 (u_long)(ntohl(tp->th_ack)),
1036                                                 ntohs(tp->th_win));
1037                                         t += strlen(t);
1038                                 }
1039                         }
1040                         *t = '\0';
1041                 } else {
1042                         (void) sprintf(t, "%s -> ", hostname(res, v, s));
1043                         t += strlen(t);
1044                         (void) sprintf(t, "%s PR %s len %hu %hu",
1045                                 hostname(res, v, d), proto, hl, plen);
1046                 }
1047         } else if ((p == IPPROTO_ICMPV6) && !off && (v == 6)) {
1048                 ic = (struct icmp *)((char *)ip + hl);
1049                 (void) sprintf(t, "%s -> ", hostname(res, v, s));
1050                 t += strlen(t);
1051                 (void) sprintf(t, "%s PR icmpv6 len %hu %hu icmpv6 %s",
1052                         hostname(res, v, d), hl, plen,
1053                         icmpname6(ic->icmp_type, ic->icmp_code));
1054         } else if ((p == IPPROTO_ICMP) && !off && (v == 4)) {
1055                 ic = (struct icmp *)((char *)ip + hl);
1056                 (void) sprintf(t, "%s -> ", hostname(res, v, s));
1057                 t += strlen(t);
1058                 (void) sprintf(t, "%s PR icmp len %hu %hu icmp %s",
1059                         hostname(res, v, d), hl, plen,
1060                         icmpname(ic->icmp_type, ic->icmp_code));
1061                 if (ic->icmp_type == ICMP_UNREACH ||
1062                     ic->icmp_type == ICMP_SOURCEQUENCH ||
1063                     ic->icmp_type == ICMP_PARAMPROB ||
1064                     ic->icmp_type == ICMP_REDIRECT ||
1065                     ic->icmp_type == ICMP_TIMXCEED) {
1066                         ipc = &ic->icmp_ip;
1067                         i = ntohs(ipc->ip_len);
1068                         ipoff = ntohs(ipc->ip_off);
1069                         proto = getproto(ipc->ip_p);
1070
1071                         if (!(ipoff & IP_OFFMASK) &&
1072                             ((ipc->ip_p == IPPROTO_TCP) ||
1073                              (ipc->ip_p == IPPROTO_UDP))) {
1074                                 tp = (tcphdr_t *)((char *)ipc + hl);
1075                                 t += strlen(t);
1076                                 (void) sprintf(t, " for %s,%s -",
1077                                         HOSTNAME_V4(res, ipc->ip_src),
1078                                         portname(res, proto,
1079                                                  (u_int)tp->th_sport));
1080                                 t += strlen(t);
1081                                 (void) sprintf(t, " %s,%s PR %s len %hu %hu",
1082                                         HOSTNAME_V4(res, ipc->ip_dst),
1083                                         portname(res, proto,
1084                                                  (u_int)tp->th_dport),
1085                                         proto, ipc->ip_hl << 2, i);
1086                         } else if (!(ipoff & IP_OFFMASK) &&
1087                                    (ipc->ip_p == IPPROTO_ICMP)) {
1088                                 icmp = (icmphdr_t *)((char *)ipc + hl);
1089
1090                                 t += strlen(t);
1091                                 (void) sprintf(t, " for %s -",
1092                                         HOSTNAME_V4(res, ipc->ip_src));
1093                                 t += strlen(t);
1094                                 (void) sprintf(t,
1095                                         " %s PR icmp len %hu %hu icmp %d/%d",
1096                                         HOSTNAME_V4(res, ipc->ip_dst),
1097                                         ipc->ip_hl << 2, i,
1098                                         icmp->icmp_type, icmp->icmp_code);
1099
1100                         } else {
1101                                 t += strlen(t);
1102                                 (void) sprintf(t, " for %s -",
1103                                                 HOSTNAME_V4(res, ipc->ip_src));
1104                                 t += strlen(t);
1105                                 (void) sprintf(t, " %s PR %s len %hu (%hu)",
1106                                         HOSTNAME_V4(res, ipc->ip_dst), proto,
1107                                         ipc->ip_hl << 2, i);
1108                                 t += strlen(t);
1109                                 if (ipoff & IP_OFFMASK) {
1110                                         (void) sprintf(t, " frag %s%s%hu@%hu",
1111                                                 ipoff & IP_MF ? "+" : "",
1112                                                 ipoff & IP_DF ? "-" : "",
1113                                                 i - (ipc->ip_hl<<2),
1114                                                 (ipoff & IP_OFFMASK) << 3);
1115                                 }
1116                         }
1117                 }
1118         } else {
1119                 (void) sprintf(t, "%s -> ", hostname(res, v, s));
1120                 t += strlen(t);
1121                 (void) sprintf(t, "%s PR %s len %hu (%hu)",
1122                         hostname(res, v, d), proto, hl, plen);
1123                 t += strlen(t);
1124                 if (off & IP_OFFMASK)
1125                         (void) sprintf(t, " frag %s%s%hu@%hu",
1126                                 ipoff & IP_MF ? "+" : "",
1127                                 ipoff & IP_DF ? "-" : "",
1128                                 plen - hl, (off & IP_OFFMASK) << 3);
1129         }
1130         t += strlen(t);
1131
1132         if (ipf->fl_flags & FR_KEEPSTATE) {
1133                 (void) strcpy(t, " K-S");
1134                 t += strlen(t);
1135         }
1136
1137         if (ipf->fl_flags & FR_KEEPFRAG) {
1138                 (void) strcpy(t, " K-F");
1139                 t += strlen(t);
1140         }
1141
1142         if (ipf->fl_dir == 0)
1143                 strcpy(t, " IN");
1144         else if (ipf->fl_dir == 1)
1145                 strcpy(t, " OUT");
1146         t += strlen(t);
1147 printipflog:
1148         *t++ = '\n';
1149         *t++ = '\0';
1150         if (opts & OPT_SYSLOG)
1151                 syslog(lvl, "%s", line);
1152         else
1153                 (void) fprintf(log, "%s", line);
1154         if (opts & OPT_HEXHDR)
1155                 dumphex(log, (u_char *)buf, sizeof(iplog_t) + sizeof(*ipf));
1156         if (opts & OPT_HEXBODY)
1157                 dumphex(log, (u_char *)ip, ipf->fl_plen + ipf->fl_hlen);
1158         else if ((opts & OPT_LOGBODY) && (ipf->fl_flags & FR_LOGBODY))
1159                 dumphex(log, (u_char *)ip + ipf->fl_hlen, ipf->fl_plen);
1160 }
1161
1162
1163 static void usage(prog)
1164 char *prog;
1165 {
1166         fprintf(stderr, "%s: [-NFhstvxX] [-f <logfile>]\n", prog);
1167         exit(1);
1168 }
1169
1170
1171 static void write_pid(file)
1172 char *file;
1173 {
1174         FILE *fp = NULL;
1175         int fd;
1176
1177         if ((fd = open(file, O_CREAT|O_TRUNC|O_WRONLY, 0644)) >= 0)
1178                 fp = fdopen(fd, "w");
1179         if (!fp) {
1180                 close(fd);
1181                 fprintf(stderr, "unable to open/create pid file: %s\n", file);
1182                 return;
1183         }
1184         fprintf(fp, "%d", getpid());
1185         fclose(fp);
1186         close(fd);
1187 }
1188
1189
1190 static void flushlogs(file, log)
1191 char *file;
1192 FILE *log;
1193 {
1194         int     fd, flushed = 0;
1195
1196         if ((fd = open(file, O_RDWR)) == -1) {
1197                 (void) fprintf(stderr, "%s: open: %s\n",
1198                                file, STRERROR(errno));
1199                 exit(1);
1200         }
1201
1202         if (ioctl(fd, SIOCIPFFB, &flushed) == 0) {
1203                 printf("%d bytes flushed from log buffer\n",
1204                         flushed);
1205                 fflush(stdout);
1206         } else
1207                 perror("SIOCIPFFB");
1208         (void) close(fd);
1209
1210         if (flushed) {
1211                 if (opts & OPT_SYSLOG)
1212                         syslog(LOG_INFO, "%d bytes flushed from log\n",
1213                                 flushed);
1214                 else if (log != stdout)
1215                         fprintf(log, "%d bytes flushed from log\n", flushed);
1216         }
1217 }
1218
1219
1220 static void logopts(turnon, options)
1221 int turnon;
1222 char *options;
1223 {
1224         int flags = 0;
1225         char *s;
1226
1227         for (s = options; *s; s++)
1228         {
1229                 switch (*s)
1230                 {
1231                 case 'N' :
1232                         flags |= OPT_NAT;
1233                         break;
1234                 case 'S' :
1235                         flags |= OPT_STATE;
1236                         break;
1237                 case 'I' :
1238                         flags |= OPT_FILTER;
1239                         break;
1240                 default :
1241                         fprintf(stderr, "Unknown log option %c\n", *s);
1242                         exit(1);
1243                 }
1244         }
1245
1246         if (turnon)
1247                 opts |= flags;
1248         else
1249                 opts &= ~(flags);
1250 }
1251
1252
1253 int main(argc, argv)
1254 int argc;
1255 char *argv[];
1256 {
1257         int     fdt[3], devices = 0, make_daemon = 0;
1258         char    buf[IPLLOGSIZE], *iplfile[3], *s;
1259         int     fd[3], doread, n, i;
1260         extern  char    *optarg;
1261         extern  int     optind;
1262         int     regular[3], c;
1263         FILE    *log = stdout;
1264         struct  stat    sb;
1265         size_t  nr, tr;
1266
1267         fd[0] = fd[1] = fd[2] = -1;
1268         fdt[0] = fdt[1] = fdt[2] = -1;
1269         iplfile[0] = IPL_NAME;
1270         iplfile[1] = IPNAT_NAME;
1271         iplfile[2] = IPSTATE_NAME;
1272
1273         while ((c = getopt(argc, argv, "?abDf:FhnN:o:O:pP:sS:tvxX")) != -1)
1274                 switch (c)
1275                 {
1276                 case 'a' :
1277                         opts |= OPT_LOGALL;
1278                         fdt[0] = IPL_LOGIPF;
1279                         fdt[1] = IPL_LOGNAT;
1280                         fdt[2] = IPL_LOGSTATE;
1281                         break;
1282                 case 'b' :
1283                         opts |= OPT_LOGBODY;
1284                         break;
1285                 case 'D' :
1286                         make_daemon = 1;
1287                         break;
1288                 case 'f' : case 'I' :
1289                         opts |= OPT_FILTER;
1290                         fdt[0] = IPL_LOGIPF;
1291                         iplfile[0] = optarg;
1292                         break;
1293                 case 'F' :
1294                         flushlogs(iplfile[0], log);
1295                         flushlogs(iplfile[1], log);
1296                         flushlogs(iplfile[2], log);
1297                         break;
1298                 case 'n' :
1299                         opts |= OPT_RESOLVE;
1300                         break;
1301                 case 'N' :
1302                         opts |= OPT_NAT;
1303                         fdt[1] = IPL_LOGNAT;
1304                         iplfile[1] = optarg;
1305                         break;
1306                 case 'o' : case 'O' :
1307                         logopts(c == 'o', optarg);
1308                         fdt[0] = fdt[1] = fdt[2] = -1;
1309                         if (opts & OPT_FILTER)
1310                                 fdt[0] = IPL_LOGIPF;
1311                         if (opts & OPT_NAT)
1312                                 fdt[1] = IPL_LOGNAT;
1313                         if (opts & OPT_STATE)
1314                                 fdt[2] = IPL_LOGSTATE;
1315                         break;
1316                 case 'p' :
1317                         opts |= OPT_PORTNUM;
1318                         break;
1319                 case 'P' :
1320                         pidfile = optarg;
1321                         break;
1322                 case 's' :
1323                         s = strrchr(argv[0], '/');
1324                         if (s == NULL)
1325                                 s = argv[0];
1326                         else
1327                                 s++;
1328                         openlog(s, LOG_NDELAY|LOG_PID, LOGFAC);
1329                         opts |= OPT_SYSLOG;
1330                         log = NULL;
1331                         break;
1332                 case 'S' :
1333                         opts |= OPT_STATE;
1334                         fdt[2] = IPL_LOGSTATE;
1335                         iplfile[2] = optarg;
1336                         break;
1337                 case 't' :
1338                         opts |= OPT_TAIL;
1339                         break;
1340                 case 'v' :
1341                         opts |= OPT_VERBOSE;
1342                         break;
1343                 case 'x' :
1344                         opts |= OPT_HEXBODY;
1345                         break;
1346                 case 'X' :
1347                         opts |= OPT_HEXHDR;
1348                         break;
1349                 default :
1350                 case 'h' :
1351                 case '?' :
1352                         usage(argv[0]);
1353                 }
1354
1355         init_tabs();
1356
1357         /*
1358          * Default action is to only open the filter log file.
1359          */
1360         if ((fdt[0] == -1) && (fdt[1] == -1) && (fdt[2] == -1))
1361                 fdt[0] = IPL_LOGIPF;
1362
1363         for (i = 0; i < 3; i++) {
1364                 if (fdt[i] == -1)
1365                         continue;
1366                 if (!strcmp(iplfile[i], "-"))
1367                         fd[i] = 0;
1368                 else {
1369                         if ((fd[i] = open(iplfile[i], O_RDONLY)) == -1) {
1370                                 (void) fprintf(stderr,
1371                                                "%s: open: %s\n", iplfile[i],
1372                                                STRERROR(errno));
1373                                 exit(1);
1374                                 /* NOTREACHED */
1375                         }
1376                         if (fstat(fd[i], &sb) == -1) {
1377                                 (void) fprintf(stderr, "%d: fstat: %s\n",
1378                                                fd[i], STRERROR(errno));
1379                                 exit(1);
1380                                 /* NOTREACHED */
1381                         }
1382                         if (!(regular[i] = !S_ISCHR(sb.st_mode)))
1383                                 devices++;
1384                 }
1385         }
1386
1387         if (!(opts & OPT_SYSLOG)) {
1388                 logfile = argv[optind];
1389                 log = logfile ? fopen(logfile, "a") : stdout;
1390                 if (log == NULL) {
1391                         (void) fprintf(stderr, "%s: fopen: %s\n",
1392                                        argv[optind], STRERROR(errno));
1393                         exit(1);
1394                         /* NOTREACHED */
1395                 }
1396                 setvbuf(log, NULL, _IONBF, 0);
1397         } else
1398                 log = NULL;
1399
1400         if (make_daemon && ((log != stdout) || (opts & OPT_SYSLOG))) {
1401 #if BSD
1402                 daemon(0, !(opts & OPT_SYSLOG));
1403 #else
1404                 int pid;
1405                 if ((pid = fork()) > 0)
1406                         exit(0);
1407                 if (pid < 0) {
1408                         (void) fprintf(stderr, "%s: fork() failed: %s\n",
1409                                        argv[0], STRERROR(errno));
1410                         exit(1);
1411                         /* NOTREACHED */
1412                 }
1413                 setsid();
1414                 if ((opts & OPT_SYSLOG))
1415                         close(2);
1416 #endif /* !BSD */
1417                 close(0);
1418                 close(1);
1419         }
1420         write_pid(pidfile);
1421
1422         signal(SIGHUP, handlehup);
1423
1424         for (doread = 1; doread; ) {
1425                 nr = 0;
1426
1427                 for (i = 0; i < 3; i++) {
1428                         tr = 0;
1429                         if (fdt[i] == -1)
1430                                 continue;
1431                         if (!regular[i]) {
1432                                 if (ioctl(fd[i], FIONREAD, &tr) == -1) {
1433                                         if (opts & OPT_SYSLOG)
1434                                                 syslog(LOG_CRIT,
1435                                                        "ioctl(FIONREAD): %m");
1436                                         else
1437                                                 perror("ioctl(FIONREAD)");
1438                                         exit(1);
1439                                         /* NOTREACHED */
1440                                 }
1441                         } else {
1442                                 tr = (lseek(fd[i], 0, SEEK_CUR) < sb.st_size);
1443                                 if (!tr && !(opts & OPT_TAIL))
1444                                         doread = 0;
1445                         }
1446                         if (!tr)
1447                                 continue;
1448                         nr += tr;
1449
1450                         tr = read_log(fd[i], &n, buf, sizeof(buf));
1451                         if (donehup) {
1452                                 donehup = 0;
1453                                 if (newlog) {
1454                                         fclose(log);
1455                                         log = newlog;
1456                                         newlog = NULL;
1457                                 }
1458                         }
1459
1460                         switch (tr)
1461                         {
1462                         case -1 :
1463                                 if (opts & OPT_SYSLOG)
1464                                         syslog(LOG_CRIT, "read: %m\n");
1465                                 else
1466                                         perror("read");
1467                                 doread = 0;
1468                                 break;
1469                         case 1 :
1470                                 if (opts & OPT_SYSLOG)
1471                                         syslog(LOG_CRIT, "aborting logging\n");
1472                                 else
1473                                         fprintf(log, "aborting logging\n");
1474                                 doread = 0;
1475                                 break;
1476                         case 2 :
1477                                 break;
1478                         case 0 :
1479                                 if (n > 0) {
1480                                         print_log(fdt[i], log, buf, n);
1481                                         if (!(opts & OPT_SYSLOG))
1482                                                 fflush(log);
1483                                 }
1484                                 break;
1485                         }
1486                 }
1487                 if (!nr && ((opts & OPT_TAIL) || devices))
1488                         sleep(1);
1489         }
1490         exit(0);
1491         /* NOTREACHED */
1492 }