ip.c revision 65846
1/*
2 *		PPP IP Protocol Interface
3 *
4 *	    Written by Toshiharu OHNO (tony-o@iij.ad.jp)
5 *
6 *   Copyright (C) 1993, Internet Initiative Japan, Inc. All rights reserverd.
7 *
8 * Redistribution and use in source and binary forms are permitted
9 * provided that the above copyright notice and this paragraph are
10 * duplicated in all such forms and that any documentation,
11 * advertising materials, and other materials related to such
12 * distribution and use acknowledge that the software was developed
13 * by the Internet Initiative Japan.  The name of the
14 * IIJ may not be used to endorse or promote products derived
15 * from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19 *
20 * $FreeBSD: head/usr.sbin/ppp/ip.c 65846 2000-09-14 18:01:54Z brian $
21 *
22 *	TODO:
23 *		o Return ICMP message for filterd packet
24 *		  and optionaly record it into log.
25 */
26#include <sys/param.h>
27#include <sys/socket.h>
28#include <netinet/in.h>
29#include <netinet/in_systm.h>
30#include <netinet/ip.h>
31#include <netinet/ip_icmp.h>
32#include <netinet/udp.h>
33#include <netinet/tcp.h>
34#include <arpa/inet.h>
35#include <sys/un.h>
36
37#include <errno.h>
38#include <stdio.h>
39#include <string.h>
40#include <termios.h>
41#include <unistd.h>
42
43#include "layer.h"
44#include "proto.h"
45#include "mbuf.h"
46#include "log.h"
47#include "defs.h"
48#include "timer.h"
49#include "fsm.h"
50#include "lqr.h"
51#include "hdlc.h"
52#include "throughput.h"
53#include "iplist.h"
54#include "slcompress.h"
55#include "ipcp.h"
56#include "filter.h"
57#include "descriptor.h"
58#include "lcp.h"
59#include "ccp.h"
60#include "link.h"
61#include "mp.h"
62#ifndef NORADIUS
63#include "radius.h"
64#endif
65#include "bundle.h"
66#include "tun.h"
67#include "ip.h"
68
69
70#define OPCODE_QUERY	0
71#define OPCODE_IQUERY	1
72#define OPCODE_STATUS	2
73
74struct dns_header {
75  u_short id;
76  unsigned qr : 1;
77  unsigned opcode : 4;
78  unsigned aa : 1;
79  unsigned tc : 1;
80  unsigned rd : 1;
81  unsigned ra : 1;
82  unsigned z : 3;
83  unsigned rcode : 4;
84  u_short qdcount;
85  u_short ancount;
86  u_short nscount;
87  u_short arcount;
88};
89
90static const char *
91dns_Qclass2Txt(u_short qclass)
92{
93  static char failure[6];
94  struct {
95    u_short id;
96    const char *txt;
97  } qtxt[] = {
98    /* rfc1035 */
99    { 1, "IN" }, { 2, "CS" }, { 3, "CH" }, { 4, "HS" }, { 255, "*" }
100  };
101  int f;
102
103  for (f = 0; f < sizeof qtxt / sizeof *qtxt; f++)
104    if (qtxt[f].id == qclass)
105      return qtxt[f].txt;
106
107  return HexStr(qclass, failure, sizeof failure);
108}
109
110static const char *
111dns_Qtype2Txt(u_short qtype)
112{
113  static char failure[6];
114  struct {
115    u_short id;
116    const char *txt;
117  } qtxt[] = {
118    /* rfc1035/rfc1700 */
119    { 1, "A" }, { 2, "NS" }, { 3, "MD" }, { 4, "MF" }, { 5, "CNAME" },
120    { 6, "SOA" }, { 7, "MB" }, { 8, "MG" }, { 9, "MR" }, { 10, "NULL" },
121    { 11, "WKS" }, { 12, "PTR" }, { 13, "HINFO" }, { 14, "MINFO" },
122    { 15, "MX" }, { 16, "TXT" }, { 17, "RP" }, { 18, "AFSDB" },
123    { 19, "X25" }, { 20, "ISDN" }, { 21, "RT" }, { 22, "NSAP" },
124    { 23, "NSAP-PTR" }, { 24, "SIG" }, { 25, "KEY" }, { 26, "PX" },
125    { 27, "GPOS" }, { 28, "AAAA" }, { 252, "AXFR" }, { 253, "MAILB" },
126    { 254, "MAILA" }, { 255, "*" }
127  };
128  int f;
129
130  for (f = 0; f < sizeof qtxt / sizeof *qtxt; f++)
131    if (qtxt[f].id == qtype)
132      return qtxt[f].txt;
133
134  return HexStr(qtype, failure, sizeof failure);
135}
136
137static __inline int
138PortMatch(int op, u_short pport, u_short rport)
139{
140  switch (op) {
141  case OP_EQ:
142    return pport == rport;
143  case OP_GT:
144    return pport > rport;
145  case OP_LT:
146    return pport < rport;
147  default:
148    return 0;
149  }
150}
151
152/*
153 *  Check a packet against a defined filter
154 *  Returns 0 to accept the packet, non-zero to drop the packet
155 *
156 *  If filtering is enabled, the initial fragment of a datagram must
157 *  contain the complete protocol header, and subsequent fragments
158 *  must not attempt to over-write it.
159 */
160static int
161FilterCheck(const struct ip *pip, const struct filter *filter, unsigned *psecs)
162{
163  int gotinfo;			/* true if IP payload decoded */
164  int cproto;			/* P_* protocol type if (gotinfo) */
165  int estab, syn, finrst;	/* TCP state flags if (gotinfo) */
166  u_short sport, dport;		/* src, dest port from packet if (gotinfo) */
167  int n;			/* filter rule to process */
168  int len;			/* bytes used in dbuff */
169  int didname;			/* true if filter header printed */
170  int match;			/* true if condition matched */
171  const struct filterent *fp = filter->rule;
172  char dbuff[100], dstip[16];
173
174  if (fp->f_action == A_NONE)
175    return 0;		/* No rule is given. Permit this packet */
176
177  /*
178   * Deny any packet fragment that tries to over-write the header.
179   * Since we no longer have the real header available, punt on the
180   * largest normal header - 20 bytes for TCP without options, rounded
181   * up to the next possible fragment boundary.  Since the smallest
182   * `legal' MTU is 576, and the smallest recommended MTU is 296, any
183   * fragmentation within this range is dubious at best
184   */
185  len = ntohs(pip->ip_off) & IP_OFFMASK;	/* fragment offset */
186  if (len > 0) {		/* Not first fragment within datagram */
187    if (len < (24 >> 3)) {	/* don't allow fragment to over-write header */
188      log_Printf(LogFILTER, " error: illegal header\n");
189      return 1;
190    }
191    /* permit fragments on in and out filter */
192    if (!filter->fragok) {
193      log_Printf(LogFILTER, " error: illegal fragmentation\n");
194      return 1;
195    } else
196      return 0;
197  }
198
199  cproto = gotinfo = estab = syn = finrst = didname = 0;
200  sport = dport = 0;
201  for (n = 0; n < MAXFILTERS; ) {
202    if (fp->f_action == A_NONE) {
203      n++;
204      fp++;
205      continue;
206    }
207
208    if (!didname) {
209      log_Printf(LogDEBUG, "%s filter:\n", filter->name);
210      didname = 1;
211    }
212
213    match = 0;
214    if (!((pip->ip_src.s_addr ^ fp->f_src.ipaddr.s_addr) &
215          fp->f_src.mask.s_addr) &&
216        !((pip->ip_dst.s_addr ^ fp->f_dst.ipaddr.s_addr) &
217          fp->f_dst.mask.s_addr)) {
218      if (fp->f_proto != P_NONE) {
219        if (!gotinfo) {
220          const char *ptop = (const char *) pip + (pip->ip_hl << 2);
221          const struct tcphdr *th;
222          const struct udphdr *uh;
223          const struct icmp *ih;
224          int datalen;	/* IP datagram length */
225
226          datalen = ntohs(pip->ip_len) - (pip->ip_hl << 2);
227          switch (pip->ip_p) {
228          case IPPROTO_ICMP:
229            cproto = P_ICMP;
230            if (datalen < 8) {	/* ICMP must be at least 8 octets */
231              log_Printf(LogFILTER, " error: ICMP must be at least 8 octets\n");
232              return 1;
233            }
234
235            ih = (const struct icmp *) ptop;
236            sport = ih->icmp_type;
237            estab = syn = finrst = -1;
238            if (log_IsKept(LogDEBUG))
239              snprintf(dbuff, sizeof dbuff, "sport = %d", sport);
240            break;
241          case IPPROTO_IGMP:
242            cproto = P_IGMP;
243            if (datalen < 8) {	/* IGMP uses 8-octet messages */
244              log_Printf(LogFILTER, " error: IGMP must be at least 8 octets\n");
245              return 1;
246            }
247            estab = syn = finrst = -1;
248            sport = ntohs(0);
249            break;
250#ifdef IPPROTO_GRE
251          case IPPROTO_GRE:
252            cproto = P_GRE;
253            if (datalen < 2) {    /* GRE uses 2-octet+ messages */
254              log_Printf(LogFILTER, " error: GRE must be at least 2 octets\n");
255              return 1;
256            }
257            estab = syn = finrst = -1;
258            sport = ntohs(0);
259            break;
260#endif
261#ifdef IPPROTO_OSPFIGP
262          case IPPROTO_OSPFIGP:
263            cproto = P_OSPF;
264            if (datalen < 8) {	/* IGMP uses 8-octet messages */
265              log_Printf(LogFILTER, " error: IGMP must be at least 8 octets\n");
266              return 1;
267            }
268            estab = syn = finrst = -1;
269            sport = ntohs(0);
270            break;
271#endif
272          case IPPROTO_ESP:
273            cproto = P_ESP;
274            estab = syn = finrst = -1;
275            sport = ntohs(0);
276            break;
277          case IPPROTO_AH:
278            cproto = P_AH;
279            estab = syn = finrst = -1;
280            sport = ntohs(0);
281            break;
282          case IPPROTO_UDP:
283          case IPPROTO_IPIP:
284            cproto = P_UDP;
285            if (datalen < 8) {	/* UDP header is 8 octets */
286              log_Printf(LogFILTER, " error: UDP must be at least 8 octets\n");
287              return 1;
288            }
289
290            uh = (const struct udphdr *) ptop;
291            sport = ntohs(uh->uh_sport);
292            dport = ntohs(uh->uh_dport);
293            estab = syn = finrst = -1;
294            if (log_IsKept(LogDEBUG))
295              snprintf(dbuff, sizeof dbuff, "sport = %d, dport = %d",
296                       sport, dport);
297            break;
298          case IPPROTO_TCP:
299            cproto = P_TCP;
300            th = (const struct tcphdr *) ptop;
301            /* TCP headers are variable length.  The following code
302             * ensures that the TCP header length isn't de-referenced if
303             * the datagram is too short
304             */
305            if (datalen < 20 || datalen < (th->th_off << 2)) {
306              log_Printf(LogFILTER, " error: TCP header incorrect\n");
307              return 1;
308            }
309            sport = ntohs(th->th_sport);
310            dport = ntohs(th->th_dport);
311            estab = (th->th_flags & TH_ACK);
312            syn = (th->th_flags & TH_SYN);
313            finrst = (th->th_flags & (TH_FIN|TH_RST));
314            if (log_IsKept(LogDEBUG)) {
315              if (!estab)
316                snprintf(dbuff, sizeof dbuff,
317                         "flags = %02x, sport = %d, dport = %d",
318                         th->th_flags, sport, dport);
319              else
320                *dbuff = '\0';
321            }
322            break;
323          default:
324            log_Printf(LogFILTER, " error: unknown protocol\n");
325            return 1;		/* We'll block unknown type of packet */
326          }
327
328          if (log_IsKept(LogDEBUG)) {
329            if (estab != -1) {
330              len = strlen(dbuff);
331              snprintf(dbuff + len, sizeof dbuff - len,
332                       ", estab = %d, syn = %d, finrst = %d",
333                       estab, syn, finrst);
334            }
335            log_Printf(LogDEBUG, " Filter: proto = %s, %s\n",
336                       filter_Proto2Nam(cproto), dbuff);
337          }
338          gotinfo = 1;
339        }
340        if (log_IsKept(LogDEBUG)) {
341          if (fp->f_srcop != OP_NONE) {
342            snprintf(dbuff, sizeof dbuff, ", src %s %d",
343                     filter_Op2Nam(fp->f_srcop), fp->f_srcport);
344            len = strlen(dbuff);
345          } else
346            len = 0;
347          if (fp->f_dstop != OP_NONE) {
348            snprintf(dbuff + len, sizeof dbuff - len,
349                     ", dst %s %d", filter_Op2Nam(fp->f_dstop),
350                     fp->f_dstport);
351          } else if (!len)
352            *dbuff = '\0';
353
354          log_Printf(LogDEBUG, "  rule = %d: Address match, "
355                     "check against proto %s%s, action = %s\n",
356                     n, filter_Proto2Nam(fp->f_proto),
357                     dbuff, filter_Action2Nam(fp->f_action));
358        }
359
360        if (cproto == fp->f_proto) {
361          if ((fp->f_srcop == OP_NONE ||
362               PortMatch(fp->f_srcop, sport, fp->f_srcport)) &&
363              (fp->f_dstop == OP_NONE ||
364               PortMatch(fp->f_dstop, dport, fp->f_dstport)) &&
365              (fp->f_estab == 0 || estab) &&
366              (fp->f_syn == 0 || syn) &&
367              (fp->f_finrst == 0 || finrst)) {
368            match = 1;
369          }
370        }
371      } else {
372        /* Address is matched and no protocol specified. Make a decision. */
373        log_Printf(LogDEBUG, "  rule = %d: Address match, action = %s\n", n,
374                   filter_Action2Nam(fp->f_action));
375        match = 1;
376      }
377    } else
378      log_Printf(LogDEBUG, "  rule = %d: Address mismatch\n", n);
379
380    if (match != fp->f_invert) {
381      /* Take specified action */
382      if (fp->f_action < A_NONE)
383        fp = &filter->rule[n = fp->f_action];
384      else {
385        if (fp->f_action == A_PERMIT) {
386          if (psecs != NULL)
387            *psecs = fp->timeout;
388          if (strcmp(filter->name, "DIAL") == 0) {
389            /* If dial filter then even print out accept packets */
390            if (log_IsKept(LogFILTER)) {
391              snprintf(dstip, sizeof dstip, "%s", inet_ntoa(pip->ip_dst));
392              log_Printf(LogFILTER, "%sbound rule = %d accept %s "
393                         "src = %s/%d dst = %s/%d\n",
394                         filter->name, n, filter_Proto2Nam(cproto),
395                         inet_ntoa(pip->ip_src), sport, dstip, dport);
396            }
397          }
398          return 0;
399        } else {
400          if (log_IsKept(LogFILTER)) {
401            snprintf(dstip, sizeof dstip, "%s", inet_ntoa(pip->ip_dst));
402            log_Printf(LogFILTER,
403                       "%sbound rule = %d deny %s src = %s/%d dst = %s/%d\n",
404                       filter->name, n, filter_Proto2Nam(cproto),
405                       inet_ntoa(pip->ip_src), sport, dstip, dport);
406          }
407          return 1;
408        }		/* Explict math.  Deny this packet */
409      }
410    } else {
411      n++;
412      fp++;
413    }
414  }
415
416  if (log_IsKept(LogFILTER)) {
417    snprintf(dstip, sizeof dstip, "%s", inet_ntoa(pip->ip_dst));
418    log_Printf(LogFILTER,
419               "%sbound rule = implicit deny %s src = %s/%d dst = %s/%d\n",
420               filter->name, filter_Proto2Nam(cproto),
421               inet_ntoa(pip->ip_src), sport, dstip, dport);
422  }
423
424  return 1;		/* No rule is mached. Deny this packet */
425}
426
427#ifdef notdef
428static void
429IcmpError(struct ip *pip, int code)
430{
431  struct mbuf *bp;
432
433  if (pip->ip_p != IPPROTO_ICMP) {
434    bp = m_get(m_len, MB_IPIN);
435    memcpy(MBUF_CTOP(bp), ptr, m_len);
436    vj_SendFrame(bp);
437    ipcp_AddOutOctets(m_len);
438  }
439}
440#endif
441
442static void
443ip_LogDNS(const struct udphdr *uh, const char *direction)
444{
445  struct dns_header header;
446  const u_short *pktptr;
447  const u_char *ptr;
448  u_short *hptr;
449  int len;
450
451  ptr = (const char *)uh + sizeof *uh;
452  len = ntohs(uh->uh_ulen) - sizeof *uh;
453  if (len < sizeof header + 5)		/* rfc1024 */
454    return;
455
456  pktptr = (const u_short *)ptr;
457  hptr = (u_short *)&header;
458  ptr += sizeof header;
459  len -= sizeof header;
460
461  while (pktptr < (const u_short *)ptr) {
462    *hptr++ = ntohs(*pktptr);		/* Careful of macro side-effects ! */
463    pktptr++;
464  }
465
466  if (header.opcode == OPCODE_QUERY && header.qr == 0) {
467    /* rfc1035 */
468    char name[MAXHOSTNAMELEN + 1], *n;
469    const char *qtype, *qclass;
470    const u_char *end;
471
472    n = name;
473    end = ptr + len - 4;
474    if (end - ptr > MAXHOSTNAMELEN)
475      end = ptr + MAXHOSTNAMELEN;
476    while (ptr < end) {
477      len = *ptr++;
478      if (len > end - ptr)
479        len = end - ptr;
480      if (n != name)
481        *n++ = '.';
482      memcpy(n, ptr, len);
483      ptr += len;
484      n += len;
485    }
486    *n = '\0';
487    qtype = dns_Qtype2Txt(ntohs(*(const u_short *)end));
488    qclass = dns_Qclass2Txt(ntohs(*(const u_short *)(end + 2)));
489
490    log_Printf(LogDNS, "%sbound query %s %s %s\n",
491               direction, qclass, qtype, name);
492  }
493}
494
495/*
496 *  For debugging aid.
497 */
498int
499PacketCheck(struct bundle *bundle, unsigned char *cp, int nb,
500            struct filter *filter, const char *prefix, unsigned *psecs)
501{
502  static const char *const TcpFlags[] = {
503    "FIN", "SYN", "RST", "PSH", "ACK", "URG"
504  };
505  struct ip *pip;
506  struct tcphdr *th;
507  struct udphdr *uh;
508  struct icmp *icmph;
509  unsigned char *ptop;
510  int mask, len, n, pri, logit, loglen, result;
511  char logbuf[200];
512
513  logit = (log_IsKept(LogTCPIP) || log_IsKept(LogDNS)) &&
514          (!filter || filter->logok);
515  loglen = 0;
516  pri = 0;
517
518  pip = (struct ip *)cp;
519  uh = NULL;
520
521  if (logit && loglen < sizeof logbuf) {
522    if (prefix)
523      snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s", prefix);
524    else if (filter)
525      snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s ", filter->name);
526    else
527      snprintf(logbuf + loglen, sizeof logbuf - loglen, "  ");
528    loglen += strlen(logbuf + loglen);
529  }
530  ptop = (cp + (pip->ip_hl << 2));
531
532  switch (pip->ip_p) {
533  case IPPROTO_ICMP:
534    if (logit && loglen < sizeof logbuf) {
535      len = ntohs(pip->ip_len) - (pip->ip_hl << 2) - sizeof *icmph;
536      icmph = (struct icmp *) ptop;
537      snprintf(logbuf + loglen, sizeof logbuf - loglen,
538               "ICMP: %s:%d ---> ", inet_ntoa(pip->ip_src), icmph->icmp_type);
539      loglen += strlen(logbuf + loglen);
540      snprintf(logbuf + loglen, sizeof logbuf - loglen,
541               "%s:%d (%d/%d)", inet_ntoa(pip->ip_dst), icmph->icmp_type,
542               len, nb);
543      loglen += strlen(logbuf + loglen);
544    }
545    break;
546
547  case IPPROTO_UDP:
548    uh = (struct udphdr *) ptop;
549    if (pip->ip_tos == IPTOS_LOWDELAY && bundle->ncp.ipcp.cfg.urgent.tos)
550      pri++;
551
552    if ((ntohs(pip->ip_off) & IP_OFFMASK) == 0 &&
553        ipcp_IsUrgentUdpPort(&bundle->ncp.ipcp, ntohs(uh->uh_sport),
554                          ntohs(uh->uh_dport)))
555      pri++;
556
557    if (logit && loglen < sizeof logbuf) {
558      len = ntohs(pip->ip_len) - (pip->ip_hl << 2) - sizeof *uh;
559      snprintf(logbuf + loglen, sizeof logbuf - loglen,
560               "UDP: %s:%d ---> ", inet_ntoa(pip->ip_src), ntohs(uh->uh_sport));
561      loglen += strlen(logbuf + loglen);
562      snprintf(logbuf + loglen, sizeof logbuf - loglen,
563               "%s:%d (%d/%d)", inet_ntoa(pip->ip_dst), ntohs(uh->uh_dport),
564               len, nb);
565      loglen += strlen(logbuf + loglen);
566    }
567
568    if (Enabled(bundle, OPT_FILTERDECAP) &&
569        ptop[sizeof *uh] == HDLC_ADDR && ptop[sizeof *uh + 1] == HDLC_UI) {
570      u_short proto;
571      const char *type;
572
573      memcpy(&proto, ptop + sizeof *uh + 2, sizeof proto);
574      type = NULL;
575
576      switch (ntohs(proto)) {
577        case PROTO_IP:
578          snprintf(logbuf + loglen, sizeof logbuf - loglen, " contains ");
579          result = PacketCheck(bundle, ptop + sizeof *uh + 4,
580                               nb - (ptop - cp) - sizeof *uh - 4, filter,
581                               logbuf, psecs);
582          if (result != -2)
583              return result;
584          type = "IP";
585          break;
586
587        case PROTO_VJUNCOMP: type = "compressed VJ";   break;
588        case PROTO_VJCOMP:   type = "uncompressed VJ"; break;
589        case PROTO_MP:       type = "Multi-link"; break;
590        case PROTO_ICOMPD:   type = "Individual link CCP"; break;
591        case PROTO_COMPD:    type = "CCP"; break;
592        case PROTO_IPCP:     type = "IPCP"; break;
593        case PROTO_LCP:      type = "LCP"; break;
594        case PROTO_PAP:      type = "PAP"; break;
595        case PROTO_CBCP:     type = "CBCP"; break;
596        case PROTO_LQR:      type = "LQR"; break;
597        case PROTO_CHAP:     type = "CHAP"; break;
598      }
599      if (type) {
600        snprintf(logbuf + loglen, sizeof logbuf - loglen,
601                 " - %s data", type);
602        loglen += strlen(logbuf + loglen);
603      }
604    }
605
606    break;
607
608#ifdef IPPROTO_GRE
609  case IPPROTO_GRE:
610    if (logit && loglen < sizeof logbuf) {
611      len = ntohs(pip->ip_len) - (pip->ip_hl << 2);
612      snprintf(logbuf + loglen, sizeof logbuf - loglen,
613          "GRE: %s ---> ", inet_ntoa(pip->ip_src));
614      loglen += strlen(logbuf + loglen);
615      snprintf(logbuf + loglen, sizeof logbuf - loglen,
616              "%s (%d/%d)", inet_ntoa(pip->ip_dst), len, nb);
617      loglen += strlen(logbuf + loglen);
618    }
619    break;
620#endif
621
622#ifdef IPPROTO_OSPFIGP
623  case IPPROTO_OSPFIGP:
624    if (logit && loglen < sizeof logbuf) {
625      len = ntohs(pip->ip_len) - (pip->ip_hl << 2);
626      snprintf(logbuf + loglen, sizeof logbuf - loglen,
627               "OSPF: %s ---> ", inet_ntoa(pip->ip_src));
628      loglen += strlen(logbuf + loglen);
629      snprintf(logbuf + loglen, sizeof logbuf - loglen,
630               "%s (%d/%d)", inet_ntoa(pip->ip_dst), len, nb);
631      loglen += strlen(logbuf + loglen);
632    }
633    break;
634#endif
635
636  case IPPROTO_IPIP:
637    if (logit && loglen < sizeof logbuf) {
638      uh = (struct udphdr *) ptop;
639      snprintf(logbuf + loglen, sizeof logbuf - loglen,
640               "IPIP: %s:%d ---> ", inet_ntoa(pip->ip_src),
641               ntohs(uh->uh_sport));
642      loglen += strlen(logbuf + loglen);
643      snprintf(logbuf + loglen, sizeof logbuf - loglen,
644               "%s:%d", inet_ntoa(pip->ip_dst), ntohs(uh->uh_dport));
645      loglen += strlen(logbuf + loglen);
646    }
647    break;
648
649  case IPPROTO_ESP:
650    if (logit && loglen < sizeof logbuf) {
651      snprintf(logbuf + loglen, sizeof logbuf - loglen,
652               "ESP: %s ---> ", inet_ntoa(pip->ip_src));
653      loglen += strlen(logbuf + loglen);
654      snprintf(logbuf + loglen, sizeof logbuf - loglen,
655               "%s, spi %08x", inet_ntoa(pip->ip_dst),
656               (u_int32_t) ptop);
657      loglen += strlen(logbuf + loglen);
658    }
659    break;
660
661  case IPPROTO_AH:
662    if (logit && loglen < sizeof logbuf) {
663      snprintf(logbuf + loglen, sizeof logbuf - loglen,
664               "AH: %s ---> ", inet_ntoa(pip->ip_src));
665      loglen += strlen(logbuf + loglen);
666      snprintf(logbuf + loglen, sizeof logbuf - loglen,
667               "%s, spi %08x", inet_ntoa(pip->ip_dst),
668               (u_int32_t) (ptop + sizeof(u_int32_t)));
669      loglen += strlen(logbuf + loglen);
670    }
671    break;
672
673  case IPPROTO_IGMP:
674    if (logit && loglen < sizeof logbuf) {
675      uh = (struct udphdr *) ptop;
676      snprintf(logbuf + loglen, sizeof logbuf - loglen,
677               "IGMP: %s:%d ---> ", inet_ntoa(pip->ip_src),
678               ntohs(uh->uh_sport));
679      loglen += strlen(logbuf + loglen);
680      snprintf(logbuf + loglen, sizeof logbuf - loglen,
681               "%s:%d", inet_ntoa(pip->ip_dst), ntohs(uh->uh_dport));
682      loglen += strlen(logbuf + loglen);
683    }
684    break;
685
686  case IPPROTO_TCP:
687    th = (struct tcphdr *) ptop;
688    if (pip->ip_tos == IPTOS_LOWDELAY && bundle->ncp.ipcp.cfg.urgent.tos)
689      pri++;
690
691    if ((ntohs(pip->ip_off) & IP_OFFMASK) == 0 &&
692        ipcp_IsUrgentTcpPort(&bundle->ncp.ipcp, ntohs(th->th_sport),
693                          ntohs(th->th_dport)))
694      pri++;
695
696    if (logit && loglen < sizeof logbuf) {
697      len = ntohs(pip->ip_len) - (pip->ip_hl << 2) - (th->th_off << 2);
698      snprintf(logbuf + loglen, sizeof logbuf - loglen,
699           "TCP: %s:%d ---> ", inet_ntoa(pip->ip_src), ntohs(th->th_sport));
700      loglen += strlen(logbuf + loglen);
701      snprintf(logbuf + loglen, sizeof logbuf - loglen,
702               "%s:%d", inet_ntoa(pip->ip_dst), ntohs(th->th_dport));
703      loglen += strlen(logbuf + loglen);
704      n = 0;
705      for (mask = TH_FIN; mask != 0x40; mask <<= 1) {
706        if (th->th_flags & mask) {
707          snprintf(logbuf + loglen, sizeof logbuf - loglen, " %s", TcpFlags[n]);
708          loglen += strlen(logbuf + loglen);
709        }
710        n++;
711      }
712      snprintf(logbuf + loglen, sizeof logbuf - loglen,
713               "  seq:%lx  ack:%lx (%d/%d)",
714               (u_long)ntohl(th->th_seq), (u_long)ntohl(th->th_ack), len, nb);
715      loglen += strlen(logbuf + loglen);
716      if ((th->th_flags & TH_SYN) && nb > 40) {
717        u_short *sp;
718
719        ptop += 20;
720        sp = (u_short *) ptop;
721        if (ntohs(sp[0]) == 0x0204) {
722          snprintf(logbuf + loglen, sizeof logbuf - loglen,
723                   " MSS = %d", ntohs(sp[1]));
724          loglen += strlen(logbuf + loglen);
725        }
726      }
727    }
728    break;
729
730  default:
731    if (prefix)
732      return -2;
733  }
734
735  if (filter && FilterCheck(pip, filter, psecs)) {
736    if (logit)
737      log_Printf(LogTCPIP, "%s - BLOCKED\n", logbuf);
738#ifdef notdef
739    if (direction == 0)
740      IcmpError(pip, pri);
741#endif
742    result = -1;
743  } else {
744    /* Check Keep Alive filter */
745    if (logit && log_IsKept(LogTCPIP)) {
746      unsigned alivesecs;
747
748      alivesecs = 0;
749      if (filter && FilterCheck(pip, &bundle->filter.alive, &alivesecs))
750        log_Printf(LogTCPIP, "%s - NO KEEPALIVE\n", logbuf);
751      else if (psecs != NULL) {
752        if(*psecs == 0)
753          *psecs = alivesecs;
754        if (*psecs) {
755          if (*psecs != alivesecs)
756            log_Printf(LogTCPIP, "%s - (timeout = %d / ALIVE = %d secs)\n",
757                       logbuf, *psecs, alivesecs);
758          else
759            log_Printf(LogTCPIP, "%s - (timeout = %d secs)\n", logbuf, *psecs);
760        } else
761          log_Printf(LogTCPIP, "%s\n", logbuf);
762      }
763    }
764    result = pri;
765  }
766
767  if (filter && uh && ntohs(uh->uh_dport) == 53 && log_IsKept(LogDNS))
768    ip_LogDNS(uh, filter->name);
769
770  return result;
771}
772
773struct mbuf *
774ip_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
775{
776  int nb, nw;
777  struct tun_data tun;
778  struct ip *pip;
779  char *data;
780  unsigned secs, alivesecs;
781
782  if (bundle->ncp.ipcp.fsm.state != ST_OPENED) {
783    log_Printf(LogWARN, "ip_Input: IPCP not open - packet dropped\n");
784    m_freem(bp);
785    return NULL;
786  }
787
788  m_settype(bp, MB_IPIN);
789  nb = m_length(bp);
790  if (nb > sizeof tun.data) {
791    log_Printf(LogWARN, "ip_Input: %s: Packet too large (got %d, max %d)\n",
792               l->name, nb, (int)(sizeof tun.data));
793    m_freem(bp);
794    return NULL;
795  }
796  mbuf_Read(bp, tun.data, nb);
797
798  secs = 0;
799  if (PacketCheck(bundle, tun.data, nb, &bundle->filter.in, NULL, &secs) < 0)
800    return NULL;
801
802  pip = (struct ip *)tun.data;
803  alivesecs = 0;
804  if (!FilterCheck(pip, &bundle->filter.alive, &alivesecs)) {
805    if (secs == 0)
806      secs = alivesecs;
807    bundle_StartIdleTimer(bundle, secs);
808  }
809
810  ipcp_AddInOctets(&bundle->ncp.ipcp, nb);
811
812  if (bundle->dev.header) {
813    tun.header.family = htonl(AF_INET);
814    nb += sizeof tun - sizeof tun.data;
815    data = (char *)&tun;
816  } else
817    data = tun.data;
818
819  nw = write(bundle->dev.fd, data, nb);
820  if (nw != nb) {
821    if (nw == -1)
822      log_Printf(LogERROR, "ip_Input: %s: wrote %d, got %s\n",
823                 l->name, nb, strerror(errno));
824    else
825      log_Printf(LogERROR, "ip_Input: %s: wrote %d, got %d\n", l->name, nb, nw);
826  }
827
828  return NULL;
829}
830
831void
832ip_Enqueue(struct ipcp *ipcp, int pri, char *ptr, int count)
833{
834  struct mbuf *bp;
835
836  if (pri < 0 || pri >= IPCP_QUEUES(ipcp))
837    log_Printf(LogERROR, "Can't store in ip queue %d\n", pri);
838  else {
839    /*
840     * We allocate an extra 6 bytes, four at the front and two at the end.
841     * This is an optimisation so that we need to do less work in
842     * m_prepend() in acf_LayerPush() and proto_LayerPush() and
843     * appending in hdlc_LayerPush().
844     */
845    bp = m_get(count + 6, MB_IPOUT);
846    bp->m_offset += 4;
847    bp->m_len -= 6;
848    memcpy(MBUF_CTOP(bp), ptr, count);
849    m_enqueue(ipcp->Queue + pri, bp);
850  }
851}
852
853void
854ip_DeleteQueue(struct ipcp *ipcp)
855{
856  struct mqueue *queue;
857
858  for (queue = ipcp->Queue; queue < ipcp->Queue + IPCP_QUEUES(ipcp); queue++)
859    while (queue->top)
860      m_freem(m_dequeue(queue));
861}
862
863size_t
864ip_QueueLen(struct ipcp *ipcp)
865{
866  struct mqueue *queue;
867  size_t result;
868
869  result = 0;
870  for (queue = ipcp->Queue; queue < ipcp->Queue + IPCP_QUEUES(ipcp); queue++)
871    result += queue->len;
872
873  return result;
874}
875
876int
877ip_PushPacket(struct link *l, struct bundle *bundle)
878{
879  struct ipcp *ipcp = &bundle->ncp.ipcp;
880  struct mqueue *queue;
881  struct mbuf *bp;
882  struct ip *pip;
883  int m_len;
884  u_int32_t secs = 0;
885  unsigned alivesecs = 0;
886
887  if (ipcp->fsm.state != ST_OPENED)
888    return 0;
889
890  queue = ipcp->Queue + IPCP_QUEUES(ipcp) - 1;
891  do {
892    if (queue->top) {
893      bp = m_dequeue(queue);
894      bp = mbuf_Read(bp, &secs, sizeof secs);
895      bp = m_pullup(bp);
896      m_len = m_length(bp);
897      pip = (struct ip *)MBUF_CTOP(bp);
898      if (!FilterCheck(pip, &bundle->filter.alive, &alivesecs)) {
899        if (secs == 0)
900          secs = alivesecs;
901        bundle_StartIdleTimer(bundle, secs);
902      }
903      link_PushPacket(l, bp, bundle, 0, PROTO_IP);
904      ipcp_AddOutOctets(ipcp, m_len);
905      return 1;
906    }
907  } while (queue-- != ipcp->Queue);
908
909  return 0;
910}
911