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