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