Coverage Report

Created: 2026-09-14 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libpcap/gencode.c
Line
Count
Source
1
/*
2
 * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998
3
 *  The Regents of the University of California.  All rights reserved.
4
 *
5
 * Redistribution and use in source and binary forms, with or without
6
 * modification, are permitted provided that: (1) source code distributions
7
 * retain the above copyright notice and this paragraph in its entirety, (2)
8
 * distributions including binary code include the above copyright notice and
9
 * this paragraph in its entirety in the documentation or other materials
10
 * provided with the distribution, and (3) all advertising materials mentioning
11
 * features or use of this software display the following acknowledgement:
12
 * ``This product includes software developed by the University of California,
13
 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14
 * the University nor the names of its contributors may be used to endorse
15
 * or promote products derived from this software without specific prior
16
 * written permission.
17
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20
 */
21
22
#include <config.h>
23
24
#ifdef _WIN32
25
  #include <ws2tcpip.h>
26
#else
27
  #include <netinet/in.h>
28
#endif /* _WIN32 */
29
30
#include <stdlib.h>
31
#include <string.h>
32
#include <memory.h>
33
#include <setjmp.h>
34
#include <stdarg.h>
35
#include <stdio.h>
36
#include <stdint.h>
37
#include <stddef.h>
38
#include <stdbool.h>
39
40
#include "pcap-int.h"
41
#include "thread-local.h"
42
43
#include "extract.h"
44
45
#include "ethertype.h"
46
#include "llc.h"
47
#include "gencode.h"
48
#include "ieee80211.h"
49
#include "pflog.h"
50
#include "ppp.h"
51
#include "pcap/sll.h"
52
#include "pcap/ipnet.h"
53
#include "diag-control.h"
54
#include "no_sanitize.h"
55
#include "pcap-util.h"
56
57
#include "scanner.h"
58
59
#if defined(__linux__)
60
#include <linux/types.h>
61
#include <linux/if_packet.h>
62
#include <linux/filter.h>
63
#endif
64
65
#ifdef _WIN32
66
  #ifdef HAVE_NPCAP_BPF_H
67
    /* Defines BPF extensions for Npcap */
68
    #include <npcap-bpf.h>
69
  #endif
70
    #if defined(__MINGW32__) && defined(DEFINE_ADDITIONAL_IPV6_STUFF)
71
/* IPv6 address */
72
struct in6_addr
73
  {
74
    union
75
      {
76
  uint8_t   u6_addr8[16];
77
  uint16_t  u6_addr16[8];
78
  uint32_t  u6_addr32[4];
79
      } in6_u;
80
#define s6_addr     in6_u.u6_addr8
81
#define s6_addr16   in6_u.u6_addr16
82
#define s6_addr32   in6_u.u6_addr32
83
#define s6_addr64   in6_u.u6_addr64
84
  };
85
86
typedef unsigned short  sa_family_t;
87
88
#define __SOCKADDR_COMMON(sa_prefix) \
89
  sa_family_t sa_prefix##family
90
91
/* Ditto, for IPv6.  */
92
struct sockaddr_in6
93
  {
94
    __SOCKADDR_COMMON (sin6_);
95
    uint16_t sin6_port;   /* Transport layer port # */
96
    uint32_t sin6_flowinfo; /* IPv6 flow information */
97
    struct in6_addr sin6_addr;  /* IPv6 address */
98
  };
99
100
      #ifndef EAI_ADDRFAMILY
101
struct addrinfo {
102
  int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
103
  int ai_family;  /* PF_xxx */
104
  int ai_socktype;  /* SOCK_xxx */
105
  int ai_protocol;  /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
106
  size_t  ai_addrlen; /* length of ai_addr */
107
  char  *ai_canonname;  /* canonical name for hostname */
108
  struct sockaddr *ai_addr; /* binary address */
109
  struct addrinfo *ai_next; /* next structure in linked list */
110
};
111
      #endif /* EAI_ADDRFAMILY */
112
    #endif /* defined(__MINGW32__) && defined(DEFINE_ADDITIONAL_IPV6_STUFF) */
113
#else /* _WIN32 */
114
  #include <netdb.h>  /* for "struct addrinfo" */
115
#endif /* _WIN32 */
116
#include <pcap/namedb.h>
117
118
#include "nametoaddr.h"
119
120
15.6k
#define ETHERMTU  1500
121
122
#ifndef IPPROTO_HOPOPTS
123
#define IPPROTO_HOPOPTS    0
124
#endif
125
#ifndef IPPROTO_IGMP
126
#define IPPROTO_IGMP       2
127
#endif
128
#ifndef IPPROTO_IGRP
129
2.06k
#define IPPROTO_IGRP       9
130
#endif
131
#ifndef IPPROTO_ROUTING
132
#define IPPROTO_ROUTING   43
133
#endif
134
#ifndef IPPROTO_FRAGMENT
135
#define IPPROTO_FRAGMENT  44
136
#endif
137
#ifndef IPPROTO_ESP
138
#define IPPROTO_ESP       50
139
#endif
140
#ifndef IPPROTO_AH
141
#define IPPROTO_AH        51
142
#endif
143
#ifndef IPPROTO_ICMPV6
144
#define IPPROTO_ICMPV6    58
145
#endif
146
#ifndef IPPROTO_NONE
147
#define IPPROTO_NONE      59
148
#endif
149
#ifndef IPPROTO_DSTOPTS
150
#define IPPROTO_DSTOPTS   60
151
#endif
152
#ifndef IPPROTO_PIM
153
#define IPPROTO_PIM      103
154
#endif
155
#ifndef IPPROTO_CARP
156
2.06k
#define IPPROTO_CARP     112
157
#endif
158
#ifndef IPPROTO_VRRP
159
2.06k
#define IPPROTO_VRRP     112
160
#endif
161
#ifndef IPPROTO_SCTP
162
#define IPPROTO_SCTP     132
163
#endif
164
165
0
#define GENEVE_PORT 6081
166
578
#define VXLAN_PORT  4789
167
168
169
/*
170
 * from: NetBSD: if_arc.h,v 1.13 1999/11/19 20:41:19 thorpej Exp
171
 */
172
173
/* RFC 1051 */
174
#define ARCTYPE_IP_OLD    240 /* IP protocol */
175
#define ARCTYPE_ARP_OLD   241 /* address resolution protocol */
176
177
/* RFC 1201 */
178
421
#define ARCTYPE_IP    212  /* IP protocol */
179
277
#define ARCTYPE_ARP   213  /* address resolution protocol */
180
271
#define ARCTYPE_REVARP    214  /* reverse addr resolution protocol */
181
182
34
#define ARCTYPE_ATALK   221  /* Appletalk */
183
#define ARCTYPE_BANIAN    247 /* Banyan Vines */
184
#define ARCTYPE_IPX   250 /* Novell IPX */
185
186
182
#define ARCTYPE_INET6   0xc4  /* IPng */
187
#define ARCTYPE_DIAGNOSE  0x80  /* as per ANSI/ATA 878.1 */
188
189
190
/* Based on UNI3.1 standard by ATM Forum */
191
192
/* ATM traffic types based on VPI=0 and (the following VCI */
193
#define VCI_PPC     0x05  /* Point-to-point signal msg */
194
#define VCI_BCC     0x02  /* Broadcast signal msg */
195
#define VCI_OAMF4SC   0x03  /* Segment OAM F4 flow cell */
196
#define VCI_OAMF4EC   0x04  /* End-to-end OAM F4 flow cell */
197
#define VCI_METAC   0x01  /* Meta signal msg */
198
#define VCI_ILMIC   0x10  /* ILMI msg */
199
200
/* Q.2931 signalling messages */
201
0
#define CALL_PROCEED    0x02  /* call proceeding */
202
0
#define CONNECT     0x07  /* connect */
203
0
#define CONNECT_ACK   0x0f  /* connect_ack */
204
0
#define SETUP     0x05  /* setup */
205
0
#define RELEASE     0x4d  /* release */
206
0
#define RELEASE_DONE    0x5a  /* release_done */
207
#define RESTART     0x46  /* restart */
208
#define RESTART_ACK   0x4e  /* restart ack */
209
#define STATUS      0x7d  /* status */
210
#define STATUS_ENQ    0x75  /* status ack */
211
#define ADD_PARTY   0x80  /* add party */
212
#define ADD_PARTY_ACK   0x81  /* add party ack */
213
#define ADD_PARTY_REJ   0x82  /* add party rej */
214
#define DROP_PARTY    0x83  /* drop party */
215
#define DROP_PARTY_ACK    0x84  /* drop party ack */
216
217
/* Information Element Parameters in the signalling messages */
218
#define CAUSE     0x08  /* cause */
219
#define ENDPT_REF   0x54  /* endpoint reference */
220
#define AAL_PARA    0x58  /* ATM adaptation layer parameters */
221
#define TRAFF_DESCRIP   0x59  /* atm traffic descriptors */
222
#define CONNECT_ID    0x5a  /* connection identifier */
223
#define QOS_PARA    0x5c  /* quality of service parameters */
224
#define B_HIGHER    0x5d  /* broadband higher layer information */
225
#define B_BEARER    0x5e  /* broadband bearer capability */
226
#define B_LOWER     0x5f  /* broadband lower information */
227
#define CALLING_PARTY   0x6c  /* calling party number */
228
#define CALLED_PARTY    0x70  /* called party number */
229
230
#define Q2931     0x09
231
232
/* Q.2931 signalling general messages format */
233
300
#define PROTO_POS       0  /* offset of protocol discriminator */
234
#define CALL_REF_POS    2 /* offset of call reference value */
235
0
#define MSG_TYPE_POS    5  /* offset of message type */
236
#define MSG_LEN_POS     7 /* offset of message length */
237
#define IE_BEGIN_POS    9 /* offset of first information element */
238
239
/* format of signalling messages */
240
#define TYPE_POS  0
241
#define LEN_POS   2
242
#define FIELD_BEGIN_POS 4
243
244
245
/* SunATM header for ATM packet */
246
#define SUNATM_DIR_POS    0
247
300
#define SUNATM_VPI_POS    1
248
300
#define SUNATM_VCI_POS    2
249
1.72k
#define SUNATM_PKT_BEGIN_POS  4  /* Start of ATM packet */
250
251
/* Protocol type values in the bottom for bits of the byte at SUNATM_DIR_POS. */
252
86
#define PT_LANE   0x01  /* LANE */
253
1.18k
#define PT_LLC    0x02  /* LLC encapsulation */
254
#define PT_ILMI   0x05  /* ILMI */
255
#define PT_QSAAL  0x06  /* Q.SAAL */
256
257
258
/* Types missing from some systems */
259
260
/*
261
 * Network layer protocol identifiers
262
 * ITU-T Rec. X.263 (1998 E)
263
 * ISO/IEC TR 9577:1999(E)
264
 */
265
#ifndef ISO8473_CLNP
266
186
#define ISO8473_CLNP    0x81
267
#endif
268
#ifndef ISO9542_ESIS
269
180
#define ISO9542_ESIS    0x82
270
#endif
271
#ifndef ISO10589_ISIS
272
19.1k
#define ISO10589_ISIS   0x83
273
#endif
274
#ifndef ISO9577_IPV6
275
165
#define ISO9577_IPV6    0x8e
276
#endif
277
#ifndef ISO9577_IPV4
278
349
#define ISO9577_IPV4    0xcc
279
#endif
280
281
2.05k
#define ISIS_L1_LAN_IIH      15
282
1.79k
#define ISIS_L2_LAN_IIH      16
283
3.57k
#define ISIS_PTP_IIH         17
284
2.05k
#define ISIS_L1_LSP          18
285
1.78k
#define ISIS_L2_LSP          20
286
2.05k
#define ISIS_L1_CSNP         24
287
1.79k
#define ISIS_L2_CSNP         25
288
2.06k
#define ISIS_L1_PSNP         26
289
1.80k
#define ISIS_L2_PSNP         27
290
/*
291
 * The maximum possible value can also be used as a bit mask because the
292
 * "PDU Type" field comprises the least significant 5 bits of a particular
293
 * octet, see sections 9.5~9.13 of ISO/IEC 10589:2002(E).
294
 */
295
37.9k
#define ISIS_PDU_TYPE_MAX 0x1FU
296
297
// Same as in tcpdump/print-sl.c.
298
0
#define SLIPDIR_IN 0
299
0
#define SLIPDIR_OUT 1
300
301
/*
302
 * Offsets of various fields from the beginning of their network-layer
303
 * header, which is the link-layer payload (OR_LINKPL).
304
 */
305
16.1k
#define IPV6_PROTO_OFFSET    6
306
822
#define IPV6_SRCADDR_OFFSET  8
307
743
#define IPV6_DSTADDR_OFFSET 24
308
16.4k
#define IPV4_PROTO_OFFSET    9
309
5.28k
#define IPV4_SRCADDR_OFFSET 12
310
5.28k
#define IPV4_DSTADDR_OFFSET 16
311
5.13k
#define ARP_SRCADDR_OFFSET  14
312
5.13k
#define ARP_DSTADDR_OFFSET  24
313
5.13k
#define RARP_SRCADDR_OFFSET 14
314
5.13k
#define RARP_DSTADDR_OFFSET 24
315
316
/*
317
 * Offsets of supported (TCP, UDP and SCTP) ports from the beginning of their
318
 * header, which is the network-layer payload (OR_TRAN_IPV4 and OR_TRAN_IPV6).
319
 */
320
9.23k
#define TRAN_SRCPORT_OFFSET 0
321
10.0k
#define TRAN_DSTPORT_OFFSET 2
322
323
// IPv6 mandatory outer header (Version, ..., Destination Address) length.
324
11.8k
#define IP6_HDRLEN 40
325
326
// RFC 3032 Section 2.1, the "Label Stack Entry" 32-bit structure.
327
1.43k
#define MPLS_STACKENTRY_LEN 4
328
// Ibid., the "Label" 20-bit field.
329
240
#define MPLS_LABEL_MAX 0xfffffU
330
240
#define MPLS_LABEL_SHIFT 12
331
332
#ifdef HAVE_OS_PROTO_H
333
#include "os-proto.h"
334
#endif
335
336
/*
337
 * A valid jump instruction code is a bitwise OR of three values and one of the
338
 * values is BPF_JMP.  To make sure both of the other two values are always
339
 * present, define a macro of two arguments and use it instead of ORing the
340
 * values in place.
341
 *
342
 * Note that "ja L" (documented as "jmp L" in the 1993 BPF paper) does not quite
343
 * follow the pattern and there is no "ja x", but internally it works very much
344
 * like "ja #k", so JMP(BPF_JA, BPF_K) is appropriate enough.
345
 */
346
274k
#define JMP(jtype, src) (BPF_JMP | (jtype) | (src))
347
348
/*
349
 * "Push" the current value of the link-layer header type and link-layer
350
 * header offset onto a "stack", and set a new value.  (It's not a
351
 * full-blown stack; we keep only the top two items.)
352
 */
353
558
#define PUSH_LINKHDR(cs, new_linktype, new_is_variable, new_constant_part, new_reg) \
354
558
{ \
355
558
  (cs)->prevlinktype = (cs)->linktype; \
356
558
  (cs)->off_prevlinkhdr = (cs)->off_linkhdr; \
357
558
  (cs)->linktype = (new_linktype); \
358
558
  (cs)->off_linkhdr.is_variable = (new_is_variable); \
359
558
  (cs)->off_linkhdr.constant_part = (new_constant_part); \
360
558
  (cs)->off_linkhdr.reg = (new_reg); \
361
558
  (cs)->is_encap = 0; \
362
558
}
363
364
/*
365
 * Offset "not set" value.
366
 */
367
154k
#define OFFSET_NOT_SET  0xffffffffU
368
369
/*
370
 * Absolute offsets, which are offsets from the beginning of the raw
371
 * packet data, are, in the general case, the sum of a variable value
372
 * and a constant value; the variable value may be absent, in which
373
 * case the offset is only the constant value, and the constant value
374
 * may be zero, in which case the offset is only the variable value.
375
 *
376
 * bpf_abs_offset is a structure containing all that information:
377
 *
378
 *   is_variable is 1 if there's a variable part.
379
 *
380
 *   constant_part is the constant part of the value, possibly zero;
381
 *
382
 *   if is_variable is 1, reg is the register number for a register
383
 *   containing the variable value if the register has been assigned,
384
 *   and -1 otherwise.
385
 */
386
typedef struct {
387
  int is_variable;
388
  u_int constant_part;
389
  int reg;
390
} bpf_abs_offset;
391
392
/*
393
 * Value passed to gen_load_a() to indicate what the offset argument
394
 * is relative to the beginning of.
395
 */
396
enum e_offrel {
397
  OR_PACKET,    /* full packet data */
398
  OR_LINKHDR,   /* link-layer header */
399
  OR_PREVLINKHDR,   /* previous link-layer header */
400
  OR_LLC,     /* 802.2 LLC header */
401
  OR_PREVMPLSHDR,   /* previous MPLS header */
402
  OR_LINKTYPE,    /* link-layer type */
403
  OR_LINKPL,    /* link-layer payload */
404
  OR_LINKPL_NOSNAP, /* link-layer payload, with no SNAP header at the link layer */
405
  OR_TRAN_IPV4,   /* transport-layer header, with IPv4 network layer */
406
  OR_TRAN_IPV6    /* transport-layer header, with IPv6 network layer */
407
};
408
409
/*
410
 * Divvy out chunks of memory rather than call calloc() each time: this way
411
 * pcap_compile() induces orders of magnitude fewer calloc() calls, which
412
 * eventually require orders of magnitude fewer free() calls, which makes it
413
 * much easier to prevent memory leaks, which is important in a library.
414
 *
415
 * The total amount of memory that can be allocated using 16 chunks, where
416
 * chunk 0 size is 1KiB and each next chunk is double the size of the previous,
417
 * is (64MiB - 1KiB).
418
 */
419
487k
#define NCHUNKS 16
420
44.9k
#define CHUNKSIZE(idx) (1024U << (idx))
421
struct chunk {
422
  size_t n_left;
423
  void *m;
424
};
425
426
/*
427
 * A chunk can store any of:
428
 *  - a string (guaranteed alignment 1 but present for completeness)
429
 *  - a block
430
 *  - an slist
431
 *  - an arth
432
 * For this simple allocator every allocated chunk gets rounded up to the
433
 * alignment needed for any chunk.
434
 */
435
struct chunk_align {
436
  char dummy;
437
  union {
438
    char c;
439
    struct block b;
440
    struct slist s;
441
    struct arth a;
442
  } u;
443
};
444
1.86M
#define CHUNK_ALIGN (offsetof(struct chunk_align, u))
445
446
/* Code generator state */
447
448
struct _compiler_state {
449
  jmp_buf top_ctx;
450
  pcap_t *bpf_pcap;
451
  int error_set;
452
453
  struct icode ic;
454
455
  int snaplen;
456
457
  int linktype;
458
  int prevlinktype;
459
  int outermostlinktype;
460
461
  bpf_u_int32 netmask;
462
  int no_optimize;
463
464
  /* Hack for handling VLAN and MPLS stacks. */
465
  u_int label_stack_depth;
466
  u_int vlan_stack_depth;
467
468
  /* XXX */
469
  u_int pcap_fddipad;
470
471
  /*
472
   * As errors are handled by a longjmp, anything allocated must
473
   * be freed in the longjmp handler, so it must be reachable
474
   * from that handler.
475
   *
476
   * One thing that's allocated is the result of pcap_nametoaddrinfo();
477
   * it must be freed with freeaddrinfo().  This variable points to
478
   * any addrinfo structure that would need to be freed.
479
   */
480
  struct addrinfo *ai;
481
482
  /*
483
   * Various code constructs need to know the layout of the packet.
484
   * These values give the necessary offsets from the beginning
485
   * of the packet data.
486
   */
487
488
  /*
489
   * Absolute offset of the beginning of the link-layer header.
490
   */
491
  bpf_abs_offset off_linkhdr;
492
493
  /*
494
   * If we're checking a link-layer header for a packet encapsulated
495
   * in another protocol layer, this is the equivalent information
496
   * for the previous layers' link-layer header from the beginning
497
   * of the raw packet data.
498
   */
499
  bpf_abs_offset off_prevlinkhdr;
500
501
  /*
502
   * This is the equivalent information for the outermost layers'
503
   * link-layer header.
504
   */
505
  bpf_abs_offset off_outermostlinkhdr;
506
507
  /*
508
   * Absolute offset of the beginning of the link-layer payload.
509
   */
510
  bpf_abs_offset off_linkpl;
511
512
  /*
513
   * "off_linktype" is the offset to information in the link-layer
514
   * header giving the packet type. This is an absolute offset
515
   * from the beginning of the packet.
516
   *
517
   * For Ethernet, it's the offset of the Ethernet type field; this
518
   * means that it must have a value that skips VLAN tags.
519
   *
520
   * For link-layer types that always use 802.2 headers, it's the
521
   * offset of the LLC header; this means that it must have a value
522
   * that skips VLAN tags.
523
   *
524
   * For PPP, it's the offset of the PPP type field.
525
   *
526
   * For Cisco HDLC, it's the offset of the CHDLC type field.
527
   *
528
   * For BSD loopback, it's the offset of the AF_ value.
529
   *
530
   * For Linux cooked sockets, it's the offset of the type field.
531
   *
532
   * off_linktype.constant_part is set to OFFSET_NOT_SET for no
533
   * encapsulation, in which case, IP is assumed.
534
   */
535
  bpf_abs_offset off_linktype;
536
537
  /*
538
   * TRUE if the link layer includes an ATM pseudo-header.
539
   */
540
  int is_atm;
541
542
  /* TRUE if "geneve" or "vxlan" appeared in the filter; it
543
   * causes us to generate code that checks for a Geneve or
544
   * VXLAN header respectively and assume that later filters
545
   * apply to the encapsulated payload.
546
   */
547
  int is_encap;
548
549
  /*
550
   * TRUE if we need variable length part of VLAN offset
551
   */
552
  int is_vlan_vloffset;
553
554
  /*
555
   * These are offsets for the ATM pseudo-header.
556
   */
557
  u_int off_vpi;
558
  u_int off_vci;
559
  u_int off_proto;
560
561
  /*
562
   * These are offsets for the MTP2 fields.
563
   */
564
  u_int off_li;
565
  u_int off_li_hsl;
566
567
  /*
568
   * These are offsets for the MTP3 fields.
569
   */
570
  u_int off_sio;
571
  u_int off_opc;
572
  u_int off_dpc;
573
  u_int off_sls;
574
575
  /*
576
   * This is the offset of the first byte after the ATM pseudo_header,
577
   * or -1 if there is no ATM pseudo-header.
578
   */
579
  u_int off_payload;
580
581
  /*
582
   * These are offsets to the beginning of the network-layer header.
583
   * They are relative to the beginning of the link-layer payload
584
   * (i.e., they don't include off_linkhdr.constant_part or
585
   * off_linkpl.constant_part).
586
   *
587
   * If the link layer never uses 802.2 LLC:
588
   *
589
   *  "off_nl" and "off_nl_nosnap" are the same.
590
   *
591
   * If the link layer always uses 802.2 LLC:
592
   *
593
   *  "off_nl" is the offset if there's a SNAP header following
594
   *  the 802.2 header;
595
   *
596
   *  "off_nl_nosnap" is the offset if there's no SNAP header.
597
   *
598
   * If the link layer is Ethernet:
599
   *
600
   *  "off_nl" is the offset if the packet is an Ethernet II packet
601
   *  (we assume no 802.3+802.2+SNAP);
602
   *
603
   *  "off_nl_nosnap" is the offset if the packet is an 802.3 packet
604
   *  with an 802.2 header following it.
605
   */
606
  u_int off_nl;
607
  u_int off_nl_nosnap;
608
609
  /*
610
   * Here we handle simple allocation of the scratch registers.
611
   * If too many registers are alloc'd, the allocator punts.
612
   */
613
  int regused[BPF_MEMWORDS];
614
  int curreg;
615
616
  /*
617
   * Memory chunks.
618
   */
619
  struct chunk chunks[NCHUNKS];
620
  unsigned cur_chunk;
621
};
622
623
/*
624
 * For use by routines outside this file.
625
 */
626
/* VARARGS */
627
void
628
bpf_set_error(compiler_state_t *cstate, const char *fmt, ...)
629
2.14k
{
630
2.14k
  va_list ap;
631
632
  /*
633
   * If we've already set an error, don't override it.
634
   * The lexical analyzer reports some errors by setting
635
   * the error and then returning a LEX_ERROR token, which
636
   * is not recognized by any grammar rule, and thus forces
637
   * the parse to stop.  We don't want the error reported
638
   * by the lexical analyzer to be overwritten by the syntax
639
   * error.
640
   */
641
2.14k
  if (!cstate->error_set) {
642
2.09k
    va_start(ap, fmt);
643
2.09k
    (void)vsnprintf(cstate->bpf_pcap->errbuf, PCAP_ERRBUF_SIZE,
644
2.09k
        fmt, ap);
645
2.09k
    va_end(ap);
646
2.09k
    cstate->error_set = 1;
647
2.09k
  }
648
2.14k
}
649
650
/*
651
 * For use *ONLY* in routines in this file.
652
 */
653
static void PCAP_NORETURN bpf_error(compiler_state_t *, const char *, ...)
654
    PCAP_PRINTFLIKE(2, 3);
655
656
/* VARARGS */
657
static void PCAP_NORETURN
658
bpf_error(compiler_state_t *cstate, const char *fmt, ...)
659
2.52k
{
660
2.52k
  va_list ap;
661
662
2.52k
  va_start(ap, fmt);
663
2.52k
  (void)vsnprintf(cstate->bpf_pcap->errbuf, PCAP_ERRBUF_SIZE,
664
2.52k
      fmt, ap);
665
2.52k
  va_end(ap);
666
2.52k
  longjmp(cstate->top_ctx, 1);
667
  /*NOTREACHED*/
668
#ifdef _AIX
669
  PCAP_UNREACHABLE
670
#endif /* _AIX */
671
2.52k
}
672
673
static int init_linktype(compiler_state_t *, pcap_t *);
674
675
static void init_regs(compiler_state_t *);
676
static int alloc_reg(compiler_state_t *);
677
static void free_reg(compiler_state_t *, int);
678
679
static bool initchunks_ok(compiler_state_t *cstate);
680
static void *newchunk_nolongjmp(compiler_state_t *cstate, size_t);
681
static void *newchunk(compiler_state_t *cstate, size_t);
682
static void freechunks(compiler_state_t *cstate);
683
static inline struct block *new_block(compiler_state_t *cstate, int);
684
static inline struct slist *new_stmt(compiler_state_t *cstate, int);
685
static struct block *sprepend_to_block(struct slist *, struct block *);
686
static struct block *gen_retblk(compiler_state_t *cstate, int);
687
static inline void syntax(compiler_state_t *cstate);
688
689
static void backpatch(struct block *, struct block *);
690
static void merge(struct block *, struct block *);
691
static struct block *gen_cmp(compiler_state_t *, enum e_offrel, u_int,
692
    u_int, bpf_u_int32);
693
static struct block *gen_cmp_gt(compiler_state_t *, enum e_offrel, u_int,
694
    u_int, bpf_u_int32);
695
static struct block *gen_cmp_ge(compiler_state_t *, enum e_offrel, u_int,
696
    u_int, bpf_u_int32);
697
static struct block *gen_cmp_lt(compiler_state_t *, enum e_offrel, u_int,
698
    u_int, bpf_u_int32);
699
static struct block *gen_cmp_le(compiler_state_t *, enum e_offrel, u_int,
700
    u_int, bpf_u_int32);
701
static struct block *gen_cmp_ne(compiler_state_t *, enum e_offrel, u_int,
702
    u_int size, bpf_u_int32);
703
static struct block *gen_mcmp(compiler_state_t *, enum e_offrel, u_int,
704
    u_int, bpf_u_int32, bpf_u_int32);
705
static struct block *gen_mcmp_ne(compiler_state_t *, enum e_offrel, u_int,
706
    u_int, bpf_u_int32, bpf_u_int32);
707
static struct block *gen_bcmp(compiler_state_t *, enum e_offrel, u_int,
708
    u_int, const u_char *);
709
static struct block *gen_jmp_k(compiler_state_t *, const int,
710
    const bpf_u_int32, struct slist *);
711
static struct block *gen_jmp_x(compiler_state_t *, const int, struct slist *);
712
static struct block *gen_set(compiler_state_t *, bpf_u_int32, struct slist *);
713
static struct block *gen_unset(compiler_state_t *, bpf_u_int32, struct slist *);
714
static struct block *gen_ncmp(compiler_state_t *, enum e_offrel, u_int,
715
    u_int, bpf_u_int32, int, int, bpf_u_int32);
716
static struct slist *gen_load_absoffsetrel(compiler_state_t *, struct slist *,
717
    const u_int, const u_int);
718
static struct slist *gen_load_absoffsetarthrel(compiler_state_t *,
719
    struct slist *, const bpf_u_int32, const struct arth *, const u_int);
720
static struct slist *gen_load_a(compiler_state_t *, const enum e_offrel, u_int,
721
    const u_int);
722
static struct slist *gen_loadx_iphdrlen(compiler_state_t *);
723
static struct block *gen_uncond(compiler_state_t *, const u_char);
724
static inline struct block *gen_true(compiler_state_t *);
725
static inline struct block *gen_false(compiler_state_t *);
726
static struct block *gen_ether_linktype(compiler_state_t *, bpf_u_int32);
727
static struct block *gen_ipnet_linktype(compiler_state_t *, bpf_u_int32);
728
static struct block *gen_linux_sll_linktype(compiler_state_t *, bpf_u_int32);
729
static struct slist *gen_load_pflog_llprefixlen(compiler_state_t *);
730
static struct slist *gen_load_prism_llprefixlen(compiler_state_t *);
731
static struct slist *gen_load_avs_llprefixlen(compiler_state_t *);
732
static struct slist *gen_load_radiotap_llprefixlen(compiler_state_t *);
733
static struct slist *gen_load_ppi_llprefixlen(compiler_state_t *);
734
static void insert_compute_vloffsets(compiler_state_t *, struct block *);
735
static struct slist *gen_abs_offset_varpart(compiler_state_t *,
736
    bpf_abs_offset *);
737
static uint16_t ethertype_to_ppptype(compiler_state_t *, bpf_u_int32);
738
static struct block *gen_linktype(compiler_state_t *, bpf_u_int32);
739
static struct block *gen_snap(compiler_state_t *, bpf_u_int32, bpf_u_int32);
740
static struct block *gen_llc_linktype(compiler_state_t *, bpf_u_int32);
741
static struct block *gen_hostop(compiler_state_t *, bpf_u_int32, bpf_u_int32,
742
    int, u_int, u_int);
743
static struct block *gen_hostop6(compiler_state_t *, const struct in6_addr *,
744
    const struct in6_addr *, const u_char);
745
static struct block *gen_wlanhostop(compiler_state_t *, const u_char *, int);
746
static unsigned char is_mac48_linktype(const int);
747
static struct block *gen_mac48host(compiler_state_t *, const u_char *,
748
    const u_char, const char *);
749
static struct block *gen_mac48host_byname(compiler_state_t *, const char *,
750
    const u_char, const char *);
751
static struct block *gen_mac8host(compiler_state_t *, const uint8_t,
752
    const u_char, const char *);
753
static struct block *gen_dnhostop(compiler_state_t *, bpf_u_int32, int);
754
static struct block *gen_mpls_linktype(compiler_state_t *, bpf_u_int32);
755
static struct block *gen_host(compiler_state_t *, const size_t,
756
    const bpf_u_int32 *, const bpf_u_int32 *, const u_char, const u_char,
757
    const u_char, const char *);
758
static struct block *gen_host6(compiler_state_t *, const size_t,
759
    const struct in6_addr *, const struct in6_addr *, const u_char,
760
    const u_char, const u_char, const char *);
761
static struct block *gen_host46_byname(compiler_state_t *, const char *,
762
    const u_char, const u_char, const u_char, const u_char);
763
static struct block *gen_dnhost(compiler_state_t *, const char *, bpf_u_int32,
764
    const struct qual);
765
static struct block *gen_gateway(compiler_state_t *, const char *, const u_char);
766
static struct block *gen_ip_proto(compiler_state_t *, const uint8_t);
767
static struct block *gen_ip6_proto(compiler_state_t *, const uint8_t);
768
static struct block *gen_ipfrag(compiler_state_t *);
769
static struct block *gen_portatom(compiler_state_t *, int, uint16_t);
770
static struct block *gen_portrangeatom(compiler_state_t *, u_int, uint16_t,
771
    uint16_t);
772
static struct block *gen_portatom6(compiler_state_t *, int, uint16_t);
773
static struct block *gen_portrangeatom6(compiler_state_t *, u_int, uint16_t,
774
    uint16_t);
775
static struct block *gen_port(compiler_state_t *, const uint16_t, const int,
776
    const u_char, const u_char);
777
static struct block *gen_port_common(compiler_state_t *, int, struct block *);
778
static struct block *gen_portrange(compiler_state_t *, uint16_t, uint16_t,
779
    int, int);
780
static struct block *gen_port6(compiler_state_t *, const uint16_t, const int,
781
    const u_char, const u_char);
782
static struct block *gen_port6_common(compiler_state_t *, int, struct block *);
783
static struct block *gen_portrange6(compiler_state_t *, uint16_t, uint16_t,
784
    int, int);
785
static int lookup_proto(compiler_state_t *, const char *, const struct qual);
786
#if !defined(NO_PROTOCHAIN)
787
static struct block *gen_protochain(compiler_state_t *, bpf_u_int32, int);
788
#endif /* !defined(NO_PROTOCHAIN) */
789
static struct block *gen_proto(compiler_state_t *, bpf_u_int32, int);
790
static struct slist *xfer_to_x(compiler_state_t *, const struct arth *);
791
static struct slist *xfer_to_a(compiler_state_t *, const struct arth *);
792
static struct block *gen_mac_multicast(compiler_state_t *, int);
793
static struct block *gen_len(compiler_state_t *, int, int);
794
static struct block *gen_encap_ll_check(compiler_state_t *cstate);
795
796
static struct block *gen_atmfield_code_internal(compiler_state_t *, int,
797
    bpf_u_int32, int, int);
798
static struct block *gen_atmtype_llc(compiler_state_t *);
799
static struct block *gen_msg_abbrev(compiler_state_t *, const uint8_t);
800
static struct block *gen_atm_prototype(compiler_state_t *, const uint8_t);
801
static struct block *gen_atm_vpi(compiler_state_t *, const uint8_t);
802
static struct block *gen_atm_vci(compiler_state_t *, const uint16_t);
803
804
0
#define ERRSTR_FUNC_VAR_INT "internal error in %s(): %s == %d"
805
806
static bool
807
initcurrentchunk_ok(compiler_state_t *cstate)
808
29.0k
{
809
29.0k
  if (cstate->cur_chunk >= NCHUNKS) {
810
0
    bpf_set_error(cstate, ERRSTR_FUNC_VAR_INT, __func__,
811
0
        "cur_chunk", cstate->cur_chunk);
812
0
    return false;
813
0
  }
814
29.0k
  const size_t size = CHUNKSIZE(cstate->cur_chunk);
815
29.0k
  cstate->chunks[cstate->cur_chunk].m = calloc(1, size);
816
29.0k
  if (cstate->chunks[cstate->cur_chunk].m == NULL) {
817
0
    bpf_set_error(cstate, "%s: calloc() failed", __func__);
818
0
    return false;
819
0
  }
820
29.0k
  cstate->chunks[cstate->cur_chunk].n_left = size;
821
29.0k
  return true;
822
29.0k
}
823
824
static bool
825
initchunks_ok(compiler_state_t *cstate)
826
13.0k
{
827
13.0k
  int i;
828
829
221k
  for (i = 0; i < NCHUNKS; i++) {
830
208k
    cstate->chunks[i].n_left = 0;
831
208k
    cstate->chunks[i].m = NULL;
832
208k
  }
833
13.0k
  cstate->cur_chunk = 0;
834
13.0k
  return initcurrentchunk_ok(cstate);
835
13.0k
}
836
837
static void *
838
newchunk_nolongjmp(compiler_state_t *cstate, size_t n)
839
934k
{
840
  /* Round up to chunk alignment. */
841
934k
  n = (n + CHUNK_ALIGN - 1) & ~(CHUNK_ALIGN - 1);
842
843
934k
  if (n > cstate->chunks[cstate->cur_chunk].n_left) {
844
15.9k
    if (cstate->cur_chunk >= NCHUNKS - 1) {
845
0
      bpf_set_error(cstate,
846
0
          "will not allocate more than %u chunks", NCHUNKS);
847
0
      return (NULL);
848
0
    }
849
15.9k
    if (n > CHUNKSIZE(cstate->cur_chunk + 1)) {
850
0
      bpf_set_error(cstate,
851
0
          "%zu bytes would not fit into chunk %u",
852
0
          n, cstate->cur_chunk + 1);
853
0
      return (NULL);
854
0
    }
855
15.9k
    ++cstate->cur_chunk;
856
15.9k
    if (! initcurrentchunk_ok(cstate))
857
0
      return (NULL); // The error buffer has been filled.
858
15.9k
  }
859
934k
  cstate->chunks[cstate->cur_chunk].n_left -= n;
860
934k
  return (void *)((char *)cstate->chunks[cstate->cur_chunk].m +
861
934k
      cstate->chunks[cstate->cur_chunk].n_left);
862
934k
}
863
864
static void *
865
newchunk(compiler_state_t *cstate, size_t n)
866
927k
{
867
927k
  void *p;
868
869
927k
  p = newchunk_nolongjmp(cstate, n);
870
927k
  if (p == NULL) {
871
0
    longjmp(cstate->top_ctx, 1);
872
    /*NOTREACHED*/
873
0
  }
874
927k
  return (p);
875
927k
}
876
877
static void
878
freechunks(compiler_state_t *cstate)
879
13.0k
{
880
13.0k
  int i;
881
882
221k
  for (i = 0; i < NCHUNKS; ++i)
883
208k
    if (cstate->chunks[i].m != NULL)
884
29.0k
      free(cstate->chunks[i].m);
885
13.0k
}
886
887
/*
888
 * A strdup whose allocations are freed after code generation is over.
889
 * This is used by the lexical analyzer, so it can't longjmp; it just
890
 * returns NULL on an allocation error, and the callers must check
891
 * for it.
892
 */
893
char *
894
sdup(compiler_state_t *cstate, const char *s)
895
7.45k
{
896
7.45k
  size_t n = strlen(s) + 1;
897
7.45k
  char *cp = newchunk_nolongjmp(cstate, n);
898
899
7.45k
  if (cp == NULL)
900
0
    return (NULL);
901
7.45k
  pcapint_strlcpy(cp, s, n);
902
7.45k
  return (cp);
903
7.45k
}
904
905
static inline struct block *
906
new_block(compiler_state_t *cstate, int code)
907
283k
{
908
283k
  struct block *p;
909
910
283k
  p = (struct block *)newchunk(cstate, sizeof(*p));
911
283k
  p->s.code = code;
912
283k
  p->head = p;
913
914
283k
  return p;
915
283k
}
916
917
static inline struct slist *
918
new_stmt(compiler_state_t *cstate, int code)
919
617k
{
920
617k
  struct slist *p;
921
922
617k
  p = (struct slist *)newchunk(cstate, sizeof(*p));
923
617k
  p->s.code = code;
924
925
617k
  return p;
926
617k
}
927
928
static struct block *
929
gen_retblk_internal(compiler_state_t *cstate, int v)
930
15.3k
{
931
15.3k
  struct block *b = new_block(cstate, BPF_RET|BPF_K);
932
933
15.3k
  b->s.k = v;
934
15.3k
  return b;
935
15.3k
}
936
937
static struct block *
938
gen_retblk(compiler_state_t *cstate, int v)
939
2.47k
{
940
2.47k
  if (setjmp(cstate->top_ctx)) {
941
    /*
942
     * gen_retblk() only fails because a memory
943
     * allocation failed in newchunk(), meaning
944
     * that it can't return a pointer.
945
     *
946
     * Return NULL.
947
     */
948
0
    return NULL;
949
0
  }
950
2.47k
  return gen_retblk_internal(cstate, v);
951
2.47k
}
952
953
static inline PCAP_NORETURN_DEF void
954
syntax(compiler_state_t *cstate)
955
207
{
956
207
  bpf_error(cstate, "syntax error in filter expression");
957
207
}
958
959
/*
960
 * For the given integer return a string with the keyword (or the nominal
961
 * keyword if there is more than one).  This is a simpler version of tok2str()
962
 * in tcpdump because in this problem space a valid integer value is not
963
 * greater than 71.
964
 */
965
static const char *
966
qual2kw(const char *kind, const unsigned id, const char *tokens[],
967
    const size_t size)
968
7.80k
{
969
7.80k
  static thread_local char buf[4][64];
970
7.80k
  static thread_local int idx = 0;
971
972
7.80k
  if (id < size && tokens[id])
973
7.79k
    return tokens[id];
974
975
12
  char *ret = buf[idx];
976
12
  idx = (idx + 1) % (sizeof(buf) / sizeof(buf[0]));
977
12
  ret[0] = '\0'; // just in case
978
12
  snprintf(ret, sizeof(buf[0]), "<invalid %s %u>", kind, id);
979
12
  return ret;
980
7.80k
}
981
982
// protocol qualifier keywords
983
static const char *
984
pqkw(const unsigned id)
985
236
{
986
236
  const char * tokens[] = {
987
236
    [Q_LINK] = "link",
988
236
    [Q_IP] = "ip",
989
236
    [Q_ARP] = "arp",
990
236
    [Q_RARP] = "rarp",
991
236
    [Q_SCTP] = "sctp",
992
236
    [Q_TCP] = "tcp",
993
236
    [Q_UDP] = "udp",
994
236
    [Q_ICMP] = "icmp",
995
236
    [Q_IGMP] = "igmp",
996
236
    [Q_IGRP] = "igrp",
997
236
    [Q_ATALK] = "atalk",
998
236
    [Q_DECNET] = "decnet",
999
236
    [Q_LAT] = "lat",
1000
236
    [Q_SCA] = "sca",
1001
236
    [Q_MOPRC] = "moprc",
1002
236
    [Q_MOPDL] = "mopdl",
1003
236
    [Q_IPV6] = "ip6",
1004
236
    [Q_ICMPV6] = "icmp6",
1005
236
    [Q_AH] = "ah",
1006
236
    [Q_ESP] = "esp",
1007
236
    [Q_PIM] = "pim",
1008
236
    [Q_VRRP] = "vrrp",
1009
236
    [Q_AARP] = "aarp",
1010
236
    [Q_ISO] = "iso",
1011
236
    [Q_ESIS] = "esis",
1012
236
    [Q_ISIS] = "isis",
1013
236
    [Q_CLNP] = "clnp",
1014
236
    [Q_STP] = "stp",
1015
236
    [Q_IPX] = "ipx",
1016
236
    [Q_NETBEUI] = "netbeui",
1017
236
    [Q_ISIS_L1] = "l1",
1018
236
    [Q_ISIS_L2] = "l2",
1019
236
    [Q_ISIS_IIH] = "iih",
1020
236
    [Q_ISIS_SNP] = "snp",
1021
236
    [Q_ISIS_CSNP] = "csnp",
1022
236
    [Q_ISIS_PSNP] = "psnp",
1023
236
    [Q_ISIS_LSP] = "lsp",
1024
236
    [Q_RADIO] = "radio",
1025
236
    [Q_CARP] = "carp",
1026
236
  };
1027
236
  return qual2kw("proto", id, tokens, sizeof(tokens) / sizeof(tokens[0]));
1028
236
}
1029
1030
// direction qualifier keywords
1031
static const char *
1032
dqkw(const unsigned id)
1033
82
{
1034
82
  const char * tokens[] = {
1035
82
    [Q_SRC] = "src",
1036
82
    [Q_DST] = "dst",
1037
82
    [Q_OR] = "src or dst",
1038
82
    [Q_AND] = "src and dst",
1039
82
    [Q_ADDR1] = "addr1",
1040
82
    [Q_ADDR2] = "addr2",
1041
82
    [Q_ADDR3] = "addr3",
1042
82
    [Q_ADDR4] = "addr4",
1043
82
    [Q_RA] = "ra",
1044
82
    [Q_TA] = "ta",
1045
82
  };
1046
82
  return qual2kw("dir", id, tokens, sizeof(tokens) / sizeof(tokens[0]));
1047
82
}
1048
1049
// type (in the man page) / address (in the code) qualifier keywords
1050
static const char *
1051
tqkw(const unsigned id)
1052
4.93k
{
1053
4.93k
  const char * tokens[] = {
1054
4.93k
    [Q_HOST] = "host",
1055
4.93k
    [Q_NET] = "net",
1056
4.93k
    [Q_PORT] = "port",
1057
4.93k
    [Q_GATEWAY] = "gateway",
1058
4.93k
    [Q_PROTO] = "proto",
1059
4.93k
    [Q_PROTOCHAIN] = "protochain",
1060
4.93k
    [Q_PORTRANGE] = "portrange",
1061
4.93k
  };
1062
4.93k
  return qual2kw("type", id, tokens, sizeof(tokens) / sizeof(tokens[0]));
1063
4.93k
}
1064
1065
// ATM keywords
1066
static const char *
1067
atmkw(const unsigned id)
1068
751
{
1069
751
  const char * tokens[] = {
1070
751
    [A_METAC] = "metac",
1071
751
    [A_BCC] = "bcc",
1072
751
    [A_OAMF4SC] = "oamf4sc",
1073
751
    [A_OAMF4EC] = "oamf4ec",
1074
751
    [A_SC] = "sc",
1075
751
    [A_ILMIC] = "ilmic",
1076
751
    [A_OAM] = "oam",
1077
751
    [A_OAMF4] = "oamf4",
1078
751
    [A_LANE] = "lane",
1079
751
    [A_VPI] = "vpi",
1080
751
    [A_VCI] = "vci",
1081
751
    [A_CONNECTMSG] = "connectmsg",
1082
751
    [A_METACONNECT] = "metaconnect",
1083
751
  };
1084
751
  return qual2kw("ATM keyword", id, tokens, sizeof(tokens) / sizeof(tokens[0]));
1085
751
}
1086
1087
// SS7 keywords
1088
static const char *
1089
ss7kw(const unsigned id)
1090
1.80k
{
1091
1.80k
  const char * tokens[] = {
1092
1.80k
    [M_FISU] = "fisu",
1093
1.80k
    [M_LSSU] = "lssu",
1094
1.80k
    [M_MSU] = "msu",
1095
1.80k
    [MH_FISU] = "hfisu",
1096
1.80k
    [MH_LSSU] = "hlssu",
1097
1.80k
    [MH_MSU] = "hmsu",
1098
1.80k
    [M_SIO] = "sio",
1099
1.80k
    [M_OPC] = "opc",
1100
1.80k
    [M_DPC] = "dpc",
1101
1.80k
    [M_SLS] = "sls",
1102
1.80k
    [MH_SIO] = "hsio",
1103
1.80k
    [MH_OPC] = "hopc",
1104
1.80k
    [MH_DPC] = "hdpc",
1105
1.80k
    [MH_SLS] = "hsls",
1106
1.80k
  };
1107
1.80k
  return qual2kw("MTP keyword", id, tokens, sizeof(tokens) / sizeof(tokens[0]));
1108
1.80k
}
1109
1110
// Produce as descriptive an identification string of the DLT as possible.
1111
static const char *
1112
pcapint_datalink_val_to_string(const int dlt)
1113
136
{
1114
136
  static thread_local char ret[1024];
1115
136
  const char *name = pcap_datalink_val_to_name(dlt);
1116
136
  const char *descr = pcap_datalink_val_to_description(dlt);
1117
  /*
1118
   * Belt and braces: if dlt_choices[] continues to be defined the way it is
1119
   * defined now and everything goes well, either both pointers are NULL or
1120
   * both pointers are not NULL.  But let's not rely on that.
1121
   */
1122
136
  if (name) {
1123
113
    if (descr)
1124
113
      snprintf(ret, sizeof(ret), "DLT_%s (%s)", name, descr);
1125
0
    else
1126
0
      snprintf(ret, sizeof(ret), "DLT_%s", name);
1127
113
    return ret;
1128
113
  }
1129
  // name == NULL
1130
23
  if (descr) {
1131
0
    snprintf(ret, sizeof(ret), "DLT %d (%s)", dlt, descr);
1132
0
    return ret;
1133
0
  }
1134
  // Both are NULL, use a function that always returns a non-NULL.
1135
23
  return pcap_datalink_val_to_description_or_dlt(dlt);
1136
23
}
1137
1138
static PCAP_NORETURN_DEF void
1139
fail_kw_on_dlt(compiler_state_t *cstate, const char *keyword)
1140
86
{
1141
86
  bpf_error(cstate, "'%s' not supported on %s", keyword,
1142
86
      pcapint_datalink_val_to_string(cstate->linktype));
1143
86
}
1144
1145
static void
1146
assert_pflog(compiler_state_t *cstate, const char *kw)
1147
126
{
1148
126
  if (cstate->linktype != DLT_PFLOG)
1149
34
    bpf_error(cstate, "'%s' supported only on PFLOG linktype", kw);
1150
126
}
1151
1152
static void
1153
assert_atm(compiler_state_t *cstate, const char *kw)
1154
751
{
1155
  /*
1156
   * Belt and braces: init_linktype() sets either all of these struct
1157
   * members (for DLT_SUNATM) or none (otherwise).
1158
   */
1159
751
  if (cstate->linktype != DLT_SUNATM ||
1160
720
      ! cstate->is_atm ||
1161
720
      cstate->off_vpi == OFFSET_NOT_SET ||
1162
720
      cstate->off_vci == OFFSET_NOT_SET ||
1163
720
      cstate->off_proto == OFFSET_NOT_SET ||
1164
720
      cstate->off_payload == OFFSET_NOT_SET)
1165
31
    bpf_error(cstate, "'%s' supported only on SUNATM", kw);
1166
751
}
1167
1168
static void
1169
assert_ss7(compiler_state_t *cstate, const char *kw)
1170
1.02k
{
1171
1.02k
  switch (cstate->linktype) {
1172
404
  case DLT_MTP2:
1173
667
  case DLT_ERF:
1174
1.02k
  case DLT_MTP2_WITH_PHDR:
1175
    // Belt and braces, same as in assert_atm().
1176
1.02k
    if (cstate->off_sio != OFFSET_NOT_SET &&
1177
1.02k
        cstate->off_opc != OFFSET_NOT_SET &&
1178
1.02k
        cstate->off_dpc != OFFSET_NOT_SET &&
1179
1.02k
        cstate->off_sls != OFFSET_NOT_SET)
1180
1.02k
      return;
1181
1.02k
  }
1182
7
  bpf_error(cstate, "'%s' supported only on SS7", kw);
1183
1.02k
}
1184
1185
static void
1186
assert_maxval(compiler_state_t *cstate, const char *name,
1187
    const bpf_u_int32 val, const bpf_u_int32 maxval)
1188
63.8k
{
1189
63.8k
  if (val > maxval)
1190
857
    bpf_error(cstate, "%s %u greater than maximum %u",
1191
857
        name, val, maxval);
1192
63.8k
}
1193
1194
static void
1195
assert_nonwlan_dqual(compiler_state_t *cstate, const u_char dir)
1196
23.6k
{
1197
23.6k
  switch (dir) {
1198
1.88k
  case Q_SRC:
1199
3.37k
  case Q_DST:
1200
4.93k
  case Q_AND:
1201
22.6k
  case Q_DEFAULT:
1202
23.5k
  case Q_OR:
1203
23.5k
    break;
1204
81
  default:
1205
81
    bpf_error(cstate, "'%s' is valid for 802.11 syntax only", dqkw(dir));
1206
23.6k
  }
1207
23.6k
}
1208
1209
46
#define ERRSTR_INVALID_QUAL "'%s' is not a valid qualifier for '%s'"
1210
71
#define ERRSTR_UNKNOWN_MAC48HOST "unknown Ethernet-like host '%s'"
1211
5
#define ERRSTR_INVALID_IPV4_ADDR "invalid IPv4 address '%s'"
1212
0
#define ERRSTR_FUNC_VAR_STR "internal error in %s(): %s == '%s'"
1213
1214
// Validate a port/portrange proto qualifier and map to an IP protocol number.
1215
static int
1216
port_pq_to_ipproto(compiler_state_t *cstate, const int proto, const char *kw)
1217
5.09k
{
1218
5.09k
  switch (proto) {
1219
179
  case Q_UDP:
1220
179
    return IPPROTO_UDP;
1221
246
  case Q_TCP:
1222
246
    return IPPROTO_TCP;
1223
241
  case Q_SCTP:
1224
241
    return IPPROTO_SCTP;
1225
4.42k
  case Q_DEFAULT:
1226
4.42k
    return PROTO_UNDEF;
1227
5.09k
  }
1228
4
  bpf_error(cstate, ERRSTR_INVALID_QUAL, pqkw(proto), kw);
1229
5.09k
}
1230
1231
static uint8_t
1232
pq_to_ipproto(compiler_state_t *cstate, const uint8_t pqual)
1233
2.06k
{
1234
2.06k
  static const uint8_t map[UINT8_MAX + 1] = {
1235
2.06k
    [Q_AH]     = IPPROTO_AH,
1236
2.06k
    [Q_CARP]   = IPPROTO_CARP,
1237
2.06k
    [Q_ESP]    = IPPROTO_ESP,
1238
2.06k
    [Q_ICMP]   = IPPROTO_ICMP,
1239
2.06k
    [Q_ICMPV6] = IPPROTO_ICMPV6,
1240
2.06k
    [Q_IGMP]   = IPPROTO_IGMP,
1241
2.06k
    [Q_IGRP]   = IPPROTO_IGRP,
1242
2.06k
    [Q_PIM]    = IPPROTO_PIM,
1243
2.06k
    [Q_SCTP]   = IPPROTO_SCTP,
1244
2.06k
    [Q_TCP]    = IPPROTO_TCP,
1245
2.06k
    [Q_UDP]    = IPPROTO_UDP,
1246
2.06k
    [Q_VRRP]   = IPPROTO_VRRP,
1247
2.06k
  };
1248
2.06k
  if (map[pqual])
1249
2.06k
    return map[pqual];
1250
0
  bpf_error(cstate, "Proto qualifier '%s' has no IP protocol",
1251
0
      pqkw(pqual));
1252
2.06k
}
1253
1254
static uint8_t
1255
pq_to_llcsap(compiler_state_t *cstate, const uint8_t pqual)
1256
783
{
1257
783
  static const uint8_t map[UINT8_MAX + 1] = {
1258
783
    [Q_IPX]     = LLCSAP_IPX,
1259
783
    [Q_ISO]     = LLCSAP_ISONS,
1260
783
    [Q_NETBEUI] = LLCSAP_NETBEUI,
1261
783
    [Q_STP]     = LLCSAP_8021D,
1262
783
  };
1263
783
  if (map[pqual])
1264
783
    return map[pqual];
1265
0
  bpf_error(cstate, "Proto qualifier '%s' has no LLC SAP", pqkw(pqual));
1266
783
}
1267
1268
static uint16_t
1269
pq_to_ethertype(compiler_state_t *cstate, const uint8_t pqual)
1270
3.46k
{
1271
3.46k
  static const uint16_t map[UINT8_MAX + 1] = {
1272
3.46k
    [Q_AARP]   = ETHERTYPE_AARP,
1273
3.46k
    [Q_ARP]    = ETHERTYPE_ARP,
1274
3.46k
    [Q_ATALK]  = ETHERTYPE_ATALK,
1275
3.46k
    [Q_DECNET] = ETHERTYPE_DN,
1276
3.46k
    [Q_IP]     = ETHERTYPE_IP,
1277
3.46k
    [Q_IPV6]   = ETHERTYPE_IPV6,
1278
3.46k
    [Q_LAT]    = ETHERTYPE_LAT,
1279
3.46k
    [Q_MOPDL]  = ETHERTYPE_MOPDL,
1280
3.46k
    [Q_MOPRC]  = ETHERTYPE_MOPRC,
1281
3.46k
    [Q_RARP]   = ETHERTYPE_REVARP,
1282
3.46k
    [Q_SCA]    = ETHERTYPE_SCA,
1283
3.46k
  };
1284
3.46k
  if (map[pqual])
1285
3.46k
    return map[pqual];
1286
0
  bpf_error(cstate, "Proto qualifier '%s' has no EtherType", pqkw(pqual));
1287
3.46k
}
1288
1289
static uint8_t
1290
pq_to_nlpid(compiler_state_t *cstate, const uint8_t pqual)
1291
144
{
1292
144
  static const uint8_t map[UINT8_MAX + 1] = {
1293
144
    [Q_ESIS] = ISO9542_ESIS,
1294
144
    [Q_ISIS] = ISO10589_ISIS,
1295
144
    [Q_CLNP] = ISO8473_CLNP,
1296
144
  };
1297
144
  if (map[pqual])
1298
144
    return map[pqual];
1299
0
  bpf_error(cstate, "Proto qualifier '%s' has no NLPID", pqkw(pqual));
1300
144
}
1301
1302
int
1303
pcap_compile(pcap_t *p, struct bpf_program *program,
1304
       const char *buf, int optimize, bpf_u_int32 mask)
1305
13.0k
{
1306
#ifdef _WIN32
1307
  int err;
1308
  WSADATA wsaData;
1309
#endif
1310
13.0k
  compiler_state_t cstate;
1311
13.0k
  yyscan_t scanner = NULL;
1312
13.0k
  YY_BUFFER_STATE in_buffer = NULL;
1313
13.0k
  u_int len;
1314
13.0k
  int rc;
1315
1316
  /*
1317
   * If this pcap_t hasn't been activated, it doesn't have a
1318
   * link-layer type, so we can't use it.
1319
   */
1320
13.0k
  if (!p->activated) {
1321
0
    (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1322
0
        "not-yet-activated pcap_t passed to pcap_compile");
1323
0
    return (PCAP_ERROR);
1324
0
  }
1325
1326
#ifdef _WIN32
1327
  /*
1328
   * Initialize Winsock, asking for the latest version (2.2),
1329
   * as we may be calling Winsock routines to translate
1330
   * host names to addresses.
1331
   */
1332
  err = WSAStartup(MAKEWORD(2, 2), &wsaData);
1333
  if (err != 0) {
1334
    pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1335
        err, "Error calling WSAStartup()");
1336
    return (PCAP_ERROR);
1337
  }
1338
#endif
1339
1340
#ifdef ENABLE_REMOTE
1341
  /*
1342
   * If the device on which we're capturing need to be notified
1343
   * that a new filter is being compiled, do so.
1344
   *
1345
   * This allows them to save a copy of it, in case, for example,
1346
   * they're implementing a form of remote packet capture, and
1347
   * want the remote machine to filter out the packets in which
1348
   * it's sending the packets it's captured.
1349
   *
1350
   * XXX - the fact that we happen to be compiling a filter
1351
   * doesn't necessarily mean we'll be installing it as the
1352
   * filter for this pcap_t; we might be running it from userland
1353
   * on captured packets to do packet classification.  We really
1354
   * need a better way of handling this, but this is all that
1355
   * the WinPcap remote capture code did.
1356
   */
1357
  if (p->save_current_filter_op != NULL)
1358
    (p->save_current_filter_op)(p, buf);
1359
#endif
1360
1361
13.0k
  cstate.no_optimize = 0;
1362
13.0k
  cstate.ai = NULL;
1363
13.0k
  cstate.ic.root = NULL;
1364
13.0k
  cstate.ic.cur_mark = 0;
1365
13.0k
  cstate.bpf_pcap = p;
1366
13.0k
  cstate.error_set = 0;
1367
13.0k
  init_regs(&cstate);
1368
1369
  // cstate.error_set must have been initialized first.
1370
13.0k
  if (! initchunks_ok(&cstate)) {
1371
    // The error buffer has been filled.
1372
0
    rc = PCAP_ERROR;
1373
0
    goto quit;
1374
0
  }
1375
1376
13.0k
  cstate.netmask = mask;
1377
1378
13.0k
  cstate.snaplen = pcap_snapshot(p);
1379
13.0k
  if (cstate.snaplen == 0) {
1380
0
    (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1381
0
       "snaplen of 0 rejects all packets");
1382
0
    rc = PCAP_ERROR;
1383
0
    goto quit;
1384
0
  }
1385
1386
13.0k
  if (pcap_lex_init(&scanner) != 0) {
1387
0
    pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1388
0
        errno, "can't initialize scanner");
1389
0
    rc = PCAP_ERROR;
1390
0
    goto quit;
1391
0
  }
1392
13.0k
  in_buffer = pcap__scan_string(buf ? buf : "", scanner);
1393
1394
  /*
1395
   * Associate the compiler state with the lexical analyzer
1396
   * state.
1397
   */
1398
13.0k
  pcap_set_extra(&cstate, scanner);
1399
1400
13.0k
  if (init_linktype(&cstate, p) == -1) {
1401
69
    rc = PCAP_ERROR;
1402
69
    goto quit;
1403
69
  }
1404
12.9k
  if (pcap_parse(scanner, &cstate) != 0) {
1405
4.54k
    if (cstate.ai != NULL)
1406
6
      freeaddrinfo(cstate.ai);
1407
4.54k
    rc = PCAP_ERROR;
1408
4.54k
    goto quit;
1409
4.54k
  }
1410
1411
8.39k
  if (cstate.ic.root == NULL) {
1412
2.47k
    cstate.ic.root = gen_retblk(&cstate, cstate.snaplen);
1413
1414
    /*
1415
     * Catch errors reported by gen_retblk().
1416
     */
1417
2.47k
    if (cstate.ic.root== NULL) {
1418
0
      rc = PCAP_ERROR;
1419
0
      goto quit;
1420
0
    }
1421
2.47k
  }
1422
1423
8.39k
  if (optimize && !cstate.no_optimize) {
1424
7.74k
    if (bpf_optimize(&cstate.ic, p->errbuf) == -1) {
1425
      /* Failure */
1426
82
      rc = PCAP_ERROR;
1427
82
      goto quit;
1428
82
    }
1429
7.66k
    if (cstate.ic.root == NULL ||
1430
7.66k
        (cstate.ic.root->s.code == (BPF_RET|BPF_K) && cstate.ic.root->s.k == 0)) {
1431
779
      (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1432
779
          "expression rejects all packets");
1433
779
      rc = PCAP_ERROR;
1434
779
      goto quit;
1435
779
    }
1436
7.66k
  }
1437
7.53k
  program->bf_insns = icode_to_fcode(&cstate.ic,
1438
7.53k
      cstate.ic.root, &len, p->errbuf);
1439
7.53k
  if (program->bf_insns == NULL) {
1440
    /* Failure */
1441
0
    rc = PCAP_ERROR;
1442
0
    goto quit;
1443
0
  }
1444
7.53k
  program->bf_len = len;
1445
1446
  /*
1447
   * If the code generator and the optimizer (if involved) work
1448
   * correctly, the resulting filter program is valid.  If it is invalid,
1449
   * fail now to make these types of bugs easier to detect and to debug.
1450
   *
1451
   * This sanity check is duplicate when the result is immediately used
1452
   * with pcap_setfilter(), which validates the program too.  However,
1453
   * pcap_offline_filter() will just quietly reject the packet if the BPF
1454
   * interpreter runs into an invalid detail.  Also the program could be
1455
   * used in external code and/or at a later time and/or after being
1456
   * stored in a file or transmitted over the network.
1457
   */
1458
7.53k
  if (pcapint_validate_filter(program->bf_insns, program->bf_len))
1459
7.53k
    rc = 0; /* We're all okay */
1460
0
  else {
1461
0
    snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1462
0
        "%s: program validation failed", __func__);
1463
0
    rc = PCAP_ERROR;
1464
0
  }
1465
1466
13.0k
quit:
1467
  /*
1468
   * Clean up everything for the lexical analyzer.
1469
   */
1470
13.0k
  if (in_buffer != NULL)
1471
13.0k
    pcap__delete_buffer(in_buffer, scanner);
1472
13.0k
  if (scanner != NULL)
1473
13.0k
    pcap_lex_destroy(scanner);
1474
1475
  /*
1476
   * Clean up our own allocated memory.
1477
   */
1478
13.0k
  freechunks(&cstate);
1479
1480
#ifdef _WIN32
1481
  WSACleanup();
1482
#endif
1483
1484
13.0k
  return (rc);
1485
7.53k
}
1486
1487
/*
1488
 * entry point for using the compiler with no pcap open
1489
 * pass in all the stuff that is needed explicitly instead.
1490
 */
1491
int
1492
pcap_compile_nopcap(int snaplen_arg, int linktype_arg,
1493
        struct bpf_program *program,
1494
        const char *buf, int optimize, bpf_u_int32 mask)
1495
0
{
1496
0
  pcap_t *p;
1497
0
  int ret;
1498
1499
0
  p = pcap_open_dead(linktype_arg, snaplen_arg);
1500
0
  if (p == NULL)
1501
0
    return (PCAP_ERROR);
1502
0
  ret = pcap_compile(p, program, buf, optimize, mask);
1503
0
  pcap_close(p);
1504
0
  return (ret);
1505
0
}
1506
1507
/*
1508
 * Clean up a "struct bpf_program" by freeing all the memory allocated
1509
 * in it.
1510
 */
1511
void
1512
pcap_freecode(struct bpf_program *program)
1513
24.2k
{
1514
24.2k
  program->bf_len = 0;
1515
24.2k
  if (program->bf_insns != NULL) {
1516
7.53k
    free(program->bf_insns);
1517
7.53k
    program->bf_insns = NULL;
1518
7.53k
  }
1519
24.2k
}
1520
1521
/*
1522
 * Backpatch the blocks in 'list' to 'target'.  The 'sense' field indicates
1523
 * which of the jt and jf fields has been resolved and which is a pointer
1524
 * back to another unresolved block (or nil).  At least one of the fields
1525
 * in each block is already resolved.
1526
 */
1527
static void
1528
backpatch(struct block *list, struct block *target)
1529
229k
{
1530
229k
  struct block *next;
1531
1532
651k
  while (list) {
1533
422k
    if (!list->sense) {
1534
210k
      next = JT(list);
1535
210k
      JT(list) = target;
1536
211k
    } else {
1537
211k
      next = JF(list);
1538
211k
      JF(list) = target;
1539
211k
    }
1540
422k
    list = next;
1541
422k
  }
1542
229k
}
1543
1544
/*
1545
 * Merge the lists in b0 and b1, using the 'sense' field to indicate
1546
 * which of jt and jf is the link.
1547
 */
1548
static void
1549
merge(struct block *b0, struct block *b1)
1550
216k
{
1551
216k
  struct block **p = &b0;
1552
1553
  /* Find end of list. */
1554
558k
  while (*p)
1555
341k
    p = !((*p)->sense) ? &JT(*p) : &JF(*p);
1556
1557
  /* Concatenate the lists. */
1558
216k
  *p = b1;
1559
216k
}
1560
1561
int
1562
finish_parse(compiler_state_t *cstate, struct block *p_arg)
1563
6.44k
{
1564
  /*
1565
   * Catch errors reported by us and routines below us, and return -1
1566
   * on an error.
1567
   */
1568
6.44k
  if (setjmp(cstate->top_ctx))
1569
0
    return (-1);
1570
1571
6.44k
  struct block *p = p_arg; // "might be clobbered by longjmp()"
1572
1573
  /*
1574
   * Insert before the statements of the first (root) block any
1575
   * statements needed to load the lengths of any variable-length
1576
   * headers into registers.
1577
   *
1578
   * XXX - a fancier strategy would be to insert those before the
1579
   * statements of all blocks that use those lengths and that
1580
   * have no predecessors that use them, so that we only compute
1581
   * the lengths if we need them.  There might be even better
1582
   * approaches than that.
1583
   *
1584
   * However, those strategies would be more complicated, and
1585
   * as we don't generate code to compute a length if the
1586
   * program has no tests that use the length, and as most
1587
   * tests will probably use those lengths, we would just
1588
   * postpone computing the lengths so that it's not done
1589
   * for tests that fail early, and it's not clear that's
1590
   * worth the effort.
1591
   */
1592
6.44k
  insert_compute_vloffsets(cstate, p->head);
1593
1594
  /*
1595
   * For DLT_PPI captures, generate a check of the per-packet
1596
   * DLT value to make sure it's DLT_IEEE802_11.
1597
   *
1598
   * XXX - TurboCap cards use DLT_PPI for Ethernet.
1599
   * Can we just define some DLT_ETHERNET_WITH_PHDR pseudo-header
1600
   * with appropriate Ethernet information and use that rather
1601
   * than using something such as DLT_PPI where you don't know
1602
   * the link-layer header type until runtime, which, in the
1603
   * general case, would force us to generate both Ethernet *and*
1604
   * 802.11 code (*and* anything else for which PPI is used)
1605
   * and choose between them early in the BPF program?
1606
   */
1607
6.44k
  if (cstate->linktype == DLT_PPI) {
1608
179
    struct block *ppi_dlt_check = gen_cmp(cstate, OR_PACKET,
1609
179
      4, BPF_W, PCAP_BSWAP_32(DLT_IEEE802_11));
1610
179
    p = gen_and(ppi_dlt_check, p);
1611
179
  }
1612
1613
6.44k
  backpatch(p, gen_retblk_internal(cstate, cstate->snaplen));
1614
6.44k
  p->sense = !p->sense;
1615
6.44k
  backpatch(p, gen_retblk_internal(cstate, 0));
1616
6.44k
  cstate->ic.root = p->head;
1617
6.44k
  return (0);
1618
6.44k
}
1619
1620
struct block *
1621
gen_and(struct block *b0, struct block *b1)
1622
136k
{
1623
  // False and X is false.
1624
136k
  if (b0->meaning == IS_FALSE)
1625
12.4k
    return b0;
1626
  // X and false is false.
1627
124k
  if (b1->meaning == IS_FALSE)
1628
120
    return b1;
1629
  // True and X is X.
1630
123k
  if (b0->meaning == IS_TRUE)
1631
3.59k
    return b1;
1632
  // X and true is X.
1633
120k
  if (b1->meaning == IS_TRUE)
1634
1.77k
    return b0;
1635
1636
  // b0->meaning == IS_UNCERTAIN && b1->meaning == IS_UNCERTAIN
1637
118k
  backpatch(b0, b1->head);
1638
118k
  b0->sense = !b0->sense;
1639
118k
  b1->sense = !b1->sense;
1640
118k
  merge(b1, b0);
1641
118k
  b1->sense = !b1->sense;
1642
118k
  b1->head = b0->head;
1643
118k
  return b1;
1644
120k
}
1645
1646
struct block *
1647
gen_or(struct block *b0, struct block *b1)
1648
122k
{
1649
  // False or X is X.
1650
122k
  if (b0->meaning == IS_FALSE)
1651
21.2k
    return b1;
1652
  // X or false is X.
1653
101k
  if (b1->meaning == IS_FALSE)
1654
2.90k
    return b0;
1655
  // True or X is true.
1656
98.6k
  if (b0->meaning == IS_TRUE)
1657
319
    return b0;
1658
  // X or true is true.
1659
98.3k
  if (b1->meaning == IS_TRUE)
1660
26
    return b1;
1661
1662
  // b0->meaning == IS_UNCERTAIN && b1->meaning == IS_UNCERTAIN
1663
98.3k
  b0->sense = !b0->sense;
1664
98.3k
  backpatch(b0, b1->head);
1665
98.3k
  b0->sense = !b0->sense;
1666
98.3k
  merge(b1, b0);
1667
98.3k
  b1->head = b0->head;
1668
98.3k
  return b1;
1669
98.3k
}
1670
1671
struct block *
1672
gen_not(struct block *b)
1673
21.7k
{
1674
21.7k
  b->sense = !b->sense;
1675
  // A switch on an enum is a source of compiler warnings.
1676
21.7k
  if (b->meaning == IS_TRUE)
1677
111
    b->meaning = IS_FALSE;
1678
21.6k
  else if (b->meaning == IS_FALSE)
1679
547
    b->meaning = IS_TRUE;
1680
21.7k
  return b;
1681
21.7k
}
1682
1683
static struct block *
1684
gen_cmp(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1685
    u_int size, bpf_u_int32 v)
1686
142k
{
1687
142k
  return gen_ncmp(cstate, offrel, offset, size, 0xffffffff, BPF_JEQ, 0, v);
1688
142k
}
1689
1690
static struct block *
1691
gen_cmp_gt(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1692
    u_int size, bpf_u_int32 v)
1693
28
{
1694
28
  return gen_ncmp(cstate, offrel, offset, size, 0xffffffff, BPF_JGT, 0, v);
1695
28
}
1696
1697
static struct block *
1698
gen_cmp_ge(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1699
    u_int size, bpf_u_int32 v)
1700
0
{
1701
0
  return gen_ncmp(cstate, offrel, offset, size, 0xffffffff, BPF_JGE, 0, v);
1702
0
}
1703
1704
static struct block *
1705
gen_cmp_lt(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1706
    u_int size, bpf_u_int32 v)
1707
19
{
1708
19
  return gen_ncmp(cstate, offrel, offset, size, 0xffffffff, BPF_JGE, 1, v);
1709
19
}
1710
1711
static struct block *
1712
gen_cmp_le(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1713
    u_int size, bpf_u_int32 v)
1714
4.23k
{
1715
4.23k
  return gen_ncmp(cstate, offrel, offset, size, 0xffffffff, BPF_JGT, 1, v);
1716
4.23k
}
1717
1718
static struct block *
1719
gen_cmp_ne(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1720
    u_int size, bpf_u_int32 v)
1721
1.77k
{
1722
1.77k
  return gen_ncmp(cstate, offrel, offset, size, 0xffffffff, BPF_JEQ, 1, v);
1723
1.77k
}
1724
1725
static struct block *
1726
gen_mcmp(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1727
    u_int size, bpf_u_int32 v, bpf_u_int32 mask)
1728
68.4k
{
1729
  /*
1730
   * For any A: if mask == 0, it means A & mask == 0, so the result is
1731
   * true iff v == 0.  In this case ideally the caller should have
1732
   * skipped this invocation and have fewer statement blocks to juggle.
1733
   * If the caller could have skipped, but has not, produce a block with
1734
   * fewer statements.
1735
   *
1736
   * This could be done in gen_ncmp() in a more generic way, but this
1737
   * function is the only code path that can have mask == 0.
1738
   */
1739
68.4k
  if (mask == 0)
1740
2.28k
    return v ? gen_false(cstate) : gen_true(cstate);
1741
1742
66.1k
  return gen_ncmp(cstate, offrel, offset, size, mask, BPF_JEQ, 0, v);
1743
68.4k
}
1744
1745
static struct block *
1746
gen_mcmp_ne(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1747
    u_int size, bpf_u_int32 v, bpf_u_int32 mask)
1748
1.28k
{
1749
1.28k
  return gen_ncmp(cstate, offrel, offset, size, mask, BPF_JEQ, 1, v);
1750
1.28k
}
1751
1752
static struct block *
1753
gen_bcmp(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1754
    u_int size, const u_char *v)
1755
5.50k
{
1756
5.50k
  struct block *b, *tmp;
1757
1758
5.50k
  b = NULL;
1759
  /*
1760
   * If everything everywhere always goes right, the initial value of
1761
   * 'size' is greater than zero, this check is dead code and 'b' will
1762
   * not remain NULL.  However, various code that calls this function
1763
   * does not check for a NULL return value, so just in case something
1764
   * goes wrong somewhere else fail safely here instead of causing a NULL
1765
   * dereference upon return.
1766
   */
1767
5.50k
  if (! size)
1768
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "size", size);
1769
11.4k
  while (size >= 4) {
1770
5.89k
    const u_char *p = &v[size - 4];
1771
1772
5.89k
    tmp = gen_cmp(cstate, offrel, offset + size - 4, BPF_W,
1773
5.89k
        EXTRACT_BE_U_4(p));
1774
5.89k
    b = b ? gen_and(b, tmp) : tmp;
1775
5.89k
    size -= 4;
1776
5.89k
  }
1777
10.5k
  while (size >= 2) {
1778
5.06k
    const u_char *p = &v[size - 2];
1779
1780
5.06k
    tmp = gen_cmp(cstate, offrel, offset + size - 2, BPF_H,
1781
5.06k
        EXTRACT_BE_U_2(p));
1782
5.06k
    b = b ? gen_and(b, tmp) : tmp;
1783
5.06k
    size -= 2;
1784
5.06k
  }
1785
5.50k
  if (size > 0) {
1786
44
    tmp = gen_cmp(cstate, offrel, offset, BPF_B, v[0]);
1787
44
    b = b ? gen_and(b, tmp) : tmp;
1788
44
  }
1789
5.50k
  return b;
1790
5.50k
}
1791
1792
/*
1793
 * Generate an instruction block for one of {"jeq #k", "jgt #k", "jge #k",
1794
 * "jset #k", "ja L"}.
1795
 */
1796
static struct block *
1797
gen_jmp_k(compiler_state_t *cstate, const int jtype, const bpf_u_int32 v,
1798
          struct slist *stmts)
1799
263k
{
1800
263k
  struct block *b = new_block(cstate, JMP(jtype, BPF_K));
1801
263k
  b->s.k = v;
1802
263k
  b->stmts = stmts;
1803
263k
  return b;
1804
263k
}
1805
1806
/*
1807
 * Generate an instruction block for one of {"jeq x", "jgt x", "jge x",
1808
 * "jset x"}.
1809
 */
1810
static struct block *
1811
gen_jmp_x(compiler_state_t *cstate, const int jtype, struct slist *stmts)
1812
4.85k
{
1813
4.85k
  struct block *b = new_block(cstate, JMP(jtype, BPF_X));
1814
4.85k
  b->stmts = stmts;
1815
4.85k
  return b;
1816
4.85k
}
1817
1818
static struct block *
1819
gen_set(compiler_state_t *cstate, bpf_u_int32 v, struct slist *stmts)
1820
13.0k
{
1821
13.0k
  return gen_jmp_k(cstate, BPF_JSET, v, stmts);
1822
13.0k
}
1823
1824
static struct block *
1825
gen_unset(compiler_state_t *cstate, bpf_u_int32 v, struct slist *stmts)
1826
9.57k
{
1827
9.57k
  return gen_not(gen_set(cstate, v, stmts));
1828
9.57k
}
1829
1830
/*
1831
 * AND the field of size "size" at offset "offset" relative to the header
1832
 * specified by "offrel" with "mask", and compare it with the value "v"
1833
 * with the test specified by "jtype"; if "reverse" is true, the test
1834
 * should test the opposite of "jtype".
1835
 */
1836
static struct block *
1837
gen_ncmp(compiler_state_t *cstate, enum e_offrel offrel, u_int offset,
1838
    u_int size, bpf_u_int32 mask, int jtype, int reverse,
1839
    bpf_u_int32 v)
1840
217k
{
1841
217k
  struct slist *s, *s2;
1842
217k
  struct block *b;
1843
1844
217k
  s = gen_load_a(cstate, offrel, offset, size);
1845
1846
217k
  if (mask != 0xffffffff) {
1847
55.3k
    s2 = new_stmt(cstate, BPF_ALU|BPF_AND|BPF_K);
1848
55.3k
    s2->s.k = mask;
1849
55.3k
    sappend(s, s2);
1850
55.3k
  }
1851
1852
217k
  b = gen_jmp_k(cstate, jtype, v, s);
1853
217k
  return reverse ? gen_not(b) : b;
1854
217k
}
1855
1856
static int
1857
init_linktype(compiler_state_t *cstate, pcap_t *p)
1858
13.0k
{
1859
13.0k
  cstate->pcap_fddipad = p->fddipad;
1860
1861
  /*
1862
   * We start out with only one link-layer header.
1863
   */
1864
13.0k
  cstate->outermostlinktype = pcap_datalink(p);
1865
13.0k
  cstate->off_outermostlinkhdr.constant_part = 0;
1866
13.0k
  cstate->off_outermostlinkhdr.is_variable = 0;
1867
13.0k
  cstate->off_outermostlinkhdr.reg = -1;
1868
1869
13.0k
  cstate->prevlinktype = cstate->outermostlinktype;
1870
13.0k
  cstate->off_prevlinkhdr.constant_part = 0;
1871
13.0k
  cstate->off_prevlinkhdr.is_variable = 0;
1872
13.0k
  cstate->off_prevlinkhdr.reg = -1;
1873
1874
13.0k
  cstate->linktype = cstate->outermostlinktype;
1875
13.0k
  cstate->off_linkhdr.constant_part = 0;
1876
13.0k
  cstate->off_linkhdr.is_variable = 0;
1877
13.0k
  cstate->off_linkhdr.reg = -1;
1878
1879
  /*
1880
   * XXX
1881
   */
1882
13.0k
  cstate->off_linkpl.constant_part = 0;
1883
13.0k
  cstate->off_linkpl.is_variable = 0;
1884
13.0k
  cstate->off_linkpl.reg = -1;
1885
1886
13.0k
  cstate->off_linktype.constant_part = 0;
1887
13.0k
  cstate->off_linktype.is_variable = 0;
1888
13.0k
  cstate->off_linktype.reg = -1;
1889
1890
  /*
1891
   * Assume it's not raw ATM with a pseudo-header, for now.
1892
   */
1893
13.0k
  cstate->is_atm = 0;
1894
13.0k
  cstate->off_vpi = OFFSET_NOT_SET;
1895
13.0k
  cstate->off_vci = OFFSET_NOT_SET;
1896
13.0k
  cstate->off_proto = OFFSET_NOT_SET;
1897
13.0k
  cstate->off_payload = OFFSET_NOT_SET;
1898
1899
  /*
1900
   * And not encapsulated with either Geneve or VXLAN.
1901
   */
1902
13.0k
  cstate->is_encap = 0;
1903
1904
  /*
1905
   * No variable length VLAN offset by default
1906
   */
1907
13.0k
  cstate->is_vlan_vloffset = 0;
1908
1909
  /*
1910
   * And assume we're not doing SS7.
1911
   */
1912
13.0k
  cstate->off_li = OFFSET_NOT_SET;
1913
13.0k
  cstate->off_li_hsl = OFFSET_NOT_SET;
1914
13.0k
  cstate->off_sio = OFFSET_NOT_SET;
1915
13.0k
  cstate->off_opc = OFFSET_NOT_SET;
1916
13.0k
  cstate->off_dpc = OFFSET_NOT_SET;
1917
13.0k
  cstate->off_sls = OFFSET_NOT_SET;
1918
1919
13.0k
  cstate->label_stack_depth = 0;
1920
13.0k
  cstate->vlan_stack_depth = 0;
1921
1922
13.0k
  switch (cstate->linktype) {
1923
1924
156
  case DLT_ARCNET:
1925
156
    cstate->off_linktype.constant_part = 2;
1926
156
    cstate->off_linkpl.constant_part = 6;
1927
156
    cstate->off_nl = 0;   /* XXX in reality, variable! */
1928
156
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
1929
156
    break;
1930
1931
90
  case DLT_ARCNET_LINUX:
1932
90
    cstate->off_linktype.constant_part = 4;
1933
90
    cstate->off_linkpl.constant_part = 8;
1934
90
    cstate->off_nl = 0;   /* XXX in reality, variable! */
1935
90
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
1936
90
    break;
1937
1938
678
  case DLT_EN10MB:
1939
678
    cstate->off_linktype.constant_part = 12;
1940
678
    cstate->off_linkpl.constant_part = 14;  /* Ethernet header length */
1941
678
    cstate->off_nl = 0;   /* Ethernet II */
1942
678
    cstate->off_nl_nosnap = 3;  /* 802.3+802.2 */
1943
678
    break;
1944
1945
129
  case DLT_SLIP:
1946
    /*
1947
     * SLIP doesn't have a link level type.  The 16 byte
1948
     * header is hacked into our SLIP driver.
1949
     */
1950
129
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
1951
129
    cstate->off_linkpl.constant_part = 16;
1952
129
    cstate->off_nl = 0;
1953
129
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
1954
129
    break;
1955
1956
47
  case DLT_SLIP_BSDOS:
1957
    /* XXX this may be the same as the DLT_PPP_BSDOS case */
1958
47
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
1959
    /* XXX end */
1960
47
    cstate->off_linkpl.constant_part = 24;
1961
47
    cstate->off_nl = 0;
1962
47
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
1963
47
    break;
1964
1965
2.95k
  case DLT_NULL:
1966
3.01k
  case DLT_LOOP:
1967
3.01k
    cstate->off_linktype.constant_part = 0;
1968
3.01k
    cstate->off_linkpl.constant_part = 4;
1969
3.01k
    cstate->off_nl = 0;
1970
3.01k
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
1971
3.01k
    break;
1972
1973
64
  case DLT_ENC:
1974
64
    cstate->off_linktype.constant_part = 0;
1975
64
    cstate->off_linkpl.constant_part = 12;
1976
64
    cstate->off_nl = 0;
1977
64
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
1978
64
    break;
1979
1980
229
  case DLT_PPP:
1981
261
  case DLT_PPP_PPPD:
1982
341
  case DLT_C_HDLC:   /* BSD/OS Cisco HDLC */
1983
471
  case DLT_HDLC:     /* NetBSD (Cisco) HDLC */
1984
573
  case DLT_PPP_SERIAL:   /* NetBSD sync/async serial PPP */
1985
573
    cstate->off_linktype.constant_part = 2; /* skip HDLC-like framing */
1986
573
    cstate->off_linkpl.constant_part = 4; /* skip HDLC-like framing and protocol field */
1987
573
    cstate->off_nl = 0;
1988
573
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
1989
573
    break;
1990
1991
94
  case DLT_PPP_ETHER:
1992
    /*
1993
     * This does not include the Ethernet header, and
1994
     * only covers session state.
1995
     */
1996
94
    cstate->off_linktype.constant_part = 6;
1997
94
    cstate->off_linkpl.constant_part = 8;
1998
94
    cstate->off_nl = 0;
1999
94
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
2000
94
    break;
2001
2002
405
  case DLT_PPP_BSDOS:
2003
405
    cstate->off_linktype.constant_part = 5;
2004
405
    cstate->off_linkpl.constant_part = 24;
2005
405
    cstate->off_nl = 0;
2006
405
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
2007
405
    break;
2008
2009
132
  case DLT_FDDI:
2010
    /*
2011
     * FDDI doesn't really have a link-level type field.
2012
     * We set "off_linktype" to the offset of the LLC header.
2013
     *
2014
     * To check for Ethernet types, we assume that SSAP = SNAP
2015
     * is being used and pick out the encapsulated Ethernet type.
2016
     * XXX - should we generate code to check for SNAP?
2017
     */
2018
132
    cstate->off_linktype.constant_part = 13;
2019
132
    cstate->off_linktype.constant_part += cstate->pcap_fddipad;
2020
132
    cstate->off_linkpl.constant_part = 13;  /* FDDI MAC header length */
2021
132
    cstate->off_linkpl.constant_part += cstate->pcap_fddipad;
2022
132
    cstate->off_nl = 8;   /* 802.2+SNAP */
2023
132
    cstate->off_nl_nosnap = 3;  /* 802.2 */
2024
132
    break;
2025
2026
117
  case DLT_IEEE802:
2027
    /*
2028
     * Token Ring doesn't really have a link-level type field.
2029
     * We set "off_linktype" to the offset of the LLC header.
2030
     *
2031
     * To check for Ethernet types, we assume that SSAP = SNAP
2032
     * is being used and pick out the encapsulated Ethernet type.
2033
     * XXX - should we generate code to check for SNAP?
2034
     *
2035
     * XXX - the header is actually variable-length.
2036
     * Some various Linux patched versions gave 38
2037
     * as "off_linktype" and 40 as "off_nl"; however,
2038
     * if a token ring packet has *no* routing
2039
     * information, i.e. is not source-routed, the correct
2040
     * values are 20 and 22, as they are in the vanilla code.
2041
     *
2042
     * A packet is source-routed iff the uppermost bit
2043
     * of the first byte of the source address, at an
2044
     * offset of 8, has the uppermost bit set.  If the
2045
     * packet is source-routed, the total number of bytes
2046
     * of routing information is 2 plus bits 0x1F00 of
2047
     * the 16-bit value at an offset of 14 (shifted right
2048
     * 8 - figure out which byte that is).
2049
     */
2050
117
    cstate->off_linktype.constant_part = 14;
2051
117
    cstate->off_linkpl.constant_part = 14;  /* Token Ring MAC header length */
2052
117
    cstate->off_nl = 8;   /* 802.2+SNAP */
2053
117
    cstate->off_nl_nosnap = 3;  /* 802.2 */
2054
117
    break;
2055
2056
311
  case DLT_PRISM_HEADER:
2057
464
  case DLT_IEEE802_11_RADIO_AVS:
2058
679
  case DLT_IEEE802_11_RADIO:
2059
679
    cstate->off_linkhdr.is_variable = 1;
2060
    /* Fall through, 802.11 doesn't have a variable link
2061
     * prefix but is otherwise the same. */
2062
    /* FALLTHROUGH */
2063
2064
947
  case DLT_IEEE802_11:
2065
    /*
2066
     * 802.11 doesn't really have a link-level type field.
2067
     * We set "off_linktype.constant_part" to the offset of
2068
     * the LLC header.
2069
     *
2070
     * To check for Ethernet types, we assume that SSAP = SNAP
2071
     * is being used and pick out the encapsulated Ethernet type.
2072
     * XXX - should we generate code to check for SNAP?
2073
     *
2074
     * We also handle variable-length radio headers here.
2075
     * The Prism header is in theory variable-length, but in
2076
     * practice it's always 144 bytes long.  However, some
2077
     * drivers on Linux use ARPHRD_IEEE80211_PRISM, but
2078
     * sometimes or always supply an AVS header, so we
2079
     * have to check whether the radio header is a Prism
2080
     * header or an AVS header, so, in practice, it's
2081
     * variable-length.
2082
     */
2083
947
    cstate->off_linktype.constant_part = 24;
2084
947
    cstate->off_linkpl.constant_part = 0; /* link-layer header is variable-length */
2085
947
    cstate->off_linkpl.is_variable = 1;
2086
947
    cstate->off_nl = 8;   /* 802.2+SNAP */
2087
947
    cstate->off_nl_nosnap = 3;  /* 802.2 */
2088
947
    break;
2089
2090
239
  case DLT_PPI:
2091
    /*
2092
     * At the moment we treat PPI the same way that we treat
2093
     * normal Radiotap encoded packets. The difference is in
2094
     * the function that generates the code at the beginning
2095
     * to compute the header length.  Since this code generator
2096
     * of PPI supports bare 802.11 encapsulation only (i.e.
2097
     * the encapsulated DLT should be DLT_IEEE802_11) we
2098
     * generate code to check for this too.
2099
     */
2100
239
    cstate->off_linktype.constant_part = 24;
2101
239
    cstate->off_linkpl.constant_part = 0; /* link-layer header is variable-length */
2102
239
    cstate->off_linkpl.is_variable = 1;
2103
239
    cstate->off_linkhdr.is_variable = 1;
2104
239
    cstate->off_nl = 8;   /* 802.2+SNAP */
2105
239
    cstate->off_nl_nosnap = 3;  /* 802.2 */
2106
239
    break;
2107
2108
123
  case DLT_ATM_RFC1483:
2109
163
  case DLT_ATM_CLIP: /* Linux ATM defines this */
2110
    /*
2111
     * assume routed, non-ISO PDUs
2112
     * (i.e., LLC = 0xAA-AA-03, OUT = 0x00-00-00)
2113
     *
2114
     * XXX - what about ISO PDUs, e.g. CLNP, ISIS, ESIS,
2115
     * or PPP with the PPP NLPID (e.g., PPPoA)?  The
2116
     * latter would presumably be treated the way PPPoE
2117
     * should be, so you can do "pppoe and udp port 2049"
2118
     * or "pppoa and tcp port 80" and have it check for
2119
     * PPPo{A,E} and a PPP protocol of IP and....
2120
     */
2121
163
    cstate->off_linktype.constant_part = 0;
2122
163
    cstate->off_linkpl.constant_part = 0; /* packet begins with LLC header */
2123
163
    cstate->off_nl = 8;   /* 802.2+SNAP */
2124
163
    cstate->off_nl_nosnap = 3;  /* 802.2 */
2125
163
    break;
2126
2127
300
  case DLT_SUNATM:
2128
    /*
2129
     * Full Frontal ATM; you get AALn PDUs with an ATM
2130
     * pseudo-header.
2131
     */
2132
300
    cstate->is_atm = 1;
2133
300
    cstate->off_vpi = SUNATM_VPI_POS;
2134
300
    cstate->off_vci = SUNATM_VCI_POS;
2135
300
    cstate->off_proto = PROTO_POS;
2136
300
    cstate->off_payload = SUNATM_PKT_BEGIN_POS;
2137
300
    cstate->off_linktype.constant_part = cstate->off_payload;
2138
300
    cstate->off_linkpl.constant_part = cstate->off_payload; /* if LLC-encapsulated */
2139
300
    cstate->off_nl = 8;   /* 802.2+SNAP */
2140
300
    cstate->off_nl_nosnap = 3;  /* 802.2 */
2141
300
    break;
2142
2143
159
  case DLT_RAW:
2144
358
  case DLT_IPV4:
2145
503
  case DLT_IPV6:
2146
503
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2147
503
    cstate->off_linkpl.constant_part = 0;
2148
503
    cstate->off_nl = 0;
2149
503
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
2150
503
    break;
2151
2152
505
  case DLT_LINUX_SLL: /* fake header for Linux cooked socket v1 */
2153
505
    cstate->off_linktype.constant_part = 14;
2154
505
    cstate->off_linkpl.constant_part = 16;
2155
505
    cstate->off_nl = 0;
2156
505
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
2157
505
    break;
2158
2159
306
  case DLT_LINUX_SLL2: /* fake header for Linux cooked socket v2 */
2160
306
    cstate->off_linktype.constant_part = 0;
2161
306
    cstate->off_linkpl.constant_part = 20;
2162
306
    cstate->off_nl = 0;
2163
306
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
2164
306
    break;
2165
2166
189
  case DLT_LTALK:
2167
    /*
2168
     * LocalTalk does have a 1-byte type field in the LLAP header,
2169
     * but really it just indicates whether there is a "short" or
2170
     * "long" DDP packet following.
2171
     */
2172
189
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2173
189
    cstate->off_linkpl.constant_part = 0;
2174
189
    cstate->off_nl = 0;
2175
189
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
2176
189
    break;
2177
2178
91
  case DLT_IP_OVER_FC:
2179
    /*
2180
     * RFC 2625 IP-over-Fibre-Channel doesn't really have a
2181
     * link-level type field.  We set "off_linktype" to the
2182
     * offset of the LLC header.
2183
     *
2184
     * To check for Ethernet types, we assume that SSAP = SNAP
2185
     * is being used and pick out the encapsulated Ethernet type.
2186
     * XXX - should we generate code to check for SNAP? RFC
2187
     * 2625 says SNAP should be used.
2188
     */
2189
91
    cstate->off_linktype.constant_part = 16;
2190
91
    cstate->off_linkpl.constant_part = 16;
2191
91
    cstate->off_nl = 8;   /* 802.2+SNAP */
2192
91
    cstate->off_nl_nosnap = 3;  /* 802.2 */
2193
91
    break;
2194
2195
153
  case DLT_FRELAY:
2196
    /*
2197
     * XXX - we should set this to handle SNAP-encapsulated
2198
     * frames (NLPID of 0x80).
2199
     */
2200
153
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2201
153
    cstate->off_linkpl.constant_part = 0;
2202
153
    cstate->off_nl = 0;
2203
153
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
2204
153
    break;
2205
2206
    /*
2207
     * the only BPF-interesting FRF.16 frames are non-control frames;
2208
     * Frame Relay has a variable length link-layer
2209
     * so lets start with offset 4 for now and increments later on (FIXME);
2210
     */
2211
4
  case DLT_MFR:
2212
4
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2213
4
    cstate->off_linkpl.constant_part = 0;
2214
4
    cstate->off_nl = 4;
2215
4
    cstate->off_nl_nosnap = 0;  /* XXX - for now -> no 802.2 LLC */
2216
4
    break;
2217
2218
24
  case DLT_APPLE_IP_OVER_IEEE1394:
2219
24
    cstate->off_linktype.constant_part = 16;
2220
24
    cstate->off_linkpl.constant_part = 18;
2221
24
    cstate->off_nl = 0;
2222
24
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
2223
24
    break;
2224
2225
80
  case DLT_SYMANTEC_FIREWALL:
2226
80
    cstate->off_linktype.constant_part = 6;
2227
80
    cstate->off_linkpl.constant_part = 44;
2228
80
    cstate->off_nl = 0;   /* Ethernet II */
2229
80
    cstate->off_nl_nosnap = 0;  /* XXX - what does it do with 802.3 packets? */
2230
80
    break;
2231
2232
578
  case DLT_PFLOG:
2233
578
    cstate->off_linktype.constant_part = 0;
2234
578
    cstate->off_linkpl.constant_part = 0; /* link-layer header is variable-length */
2235
578
    cstate->off_linkpl.is_variable = 1;
2236
578
    cstate->off_nl = 0;
2237
578
    cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
2238
578
    break;
2239
2240
16
  case DLT_JUNIPER_MFR:
2241
37
  case DLT_JUNIPER_MLFR:
2242
63
  case DLT_JUNIPER_MLPPP:
2243
79
  case DLT_JUNIPER_PPP:
2244
105
  case DLT_JUNIPER_CHDLC:
2245
121
  case DLT_JUNIPER_FRELAY:
2246
121
    cstate->off_linktype.constant_part = 4;
2247
121
    cstate->off_linkpl.constant_part = 4;
2248
121
    cstate->off_nl = 0;
2249
121
    cstate->off_nl_nosnap = OFFSET_NOT_SET; /* no 802.2 LLC */
2250
121
    break;
2251
2252
22
  case DLT_JUNIPER_ATM1:
2253
22
    cstate->off_linktype.constant_part = 4;   /* in reality variable between 4-8 */
2254
22
    cstate->off_linkpl.constant_part = 4; /* in reality variable between 4-8 */
2255
22
    cstate->off_nl = 0;
2256
22
    cstate->off_nl_nosnap = 10;
2257
22
    break;
2258
2259
21
  case DLT_JUNIPER_ATM2:
2260
21
    cstate->off_linktype.constant_part = 8;   /* in reality variable between 8-12 */
2261
21
    cstate->off_linkpl.constant_part = 8; /* in reality variable between 8-12 */
2262
21
    cstate->off_nl = 0;
2263
21
    cstate->off_nl_nosnap = 10;
2264
21
    break;
2265
2266
    /* frames captured on a Juniper PPPoE service PIC
2267
     * contain raw ethernet frames */
2268
29
  case DLT_JUNIPER_PPPOE:
2269
76
  case DLT_JUNIPER_ETHER:
2270
76
    cstate->off_linkpl.constant_part = 14;
2271
76
    cstate->off_linktype.constant_part = 16;
2272
76
    cstate->off_nl = 18;    /* Ethernet II */
2273
76
    cstate->off_nl_nosnap = 21; /* 802.3+802.2 */
2274
76
    break;
2275
2276
30
  case DLT_JUNIPER_PPPOE_ATM:
2277
30
    cstate->off_linktype.constant_part = 4;
2278
30
    cstate->off_linkpl.constant_part = 6;
2279
30
    cstate->off_nl = 0;
2280
30
    cstate->off_nl_nosnap = OFFSET_NOT_SET; /* no 802.2 LLC */
2281
30
    break;
2282
2283
18
  case DLT_JUNIPER_GGSN:
2284
18
    cstate->off_linktype.constant_part = 6;
2285
18
    cstate->off_linkpl.constant_part = 12;
2286
18
    cstate->off_nl = 0;
2287
18
    cstate->off_nl_nosnap = OFFSET_NOT_SET; /* no 802.2 LLC */
2288
18
    break;
2289
2290
36
  case DLT_JUNIPER_ES:
2291
36
    cstate->off_linktype.constant_part = 6;
2292
36
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET; /* not really a network layer but raw IP addresses */
2293
36
    cstate->off_nl = OFFSET_NOT_SET; /* not really a network layer but raw IP addresses */
2294
36
    cstate->off_nl_nosnap = OFFSET_NOT_SET; /* no 802.2 LLC */
2295
36
    break;
2296
2297
15
  case DLT_JUNIPER_MONITOR:
2298
15
    cstate->off_linktype.constant_part = 12;
2299
15
    cstate->off_linkpl.constant_part = 12;
2300
15
    cstate->off_nl = 0;     /* raw IP/IP6 header */
2301
15
    cstate->off_nl_nosnap = OFFSET_NOT_SET; /* no 802.2 LLC */
2302
15
    break;
2303
2304
29
  case DLT_JUNIPER_SERVICES:
2305
29
    cstate->off_linktype.constant_part = 12;
2306
29
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET; /* L3 proto location dep. on cookie type */
2307
29
    cstate->off_nl = OFFSET_NOT_SET; /* L3 proto location dep. on cookie type */
2308
29
    cstate->off_nl_nosnap = OFFSET_NOT_SET; /* no 802.2 LLC */
2309
29
    break;
2310
2311
27
  case DLT_JUNIPER_VP:
2312
27
    cstate->off_linktype.constant_part = 18;
2313
27
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET;
2314
27
    cstate->off_nl = OFFSET_NOT_SET;
2315
27
    cstate->off_nl_nosnap = OFFSET_NOT_SET;
2316
27
    break;
2317
2318
27
  case DLT_JUNIPER_ST:
2319
27
    cstate->off_linktype.constant_part = 18;
2320
27
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET;
2321
27
    cstate->off_nl = OFFSET_NOT_SET;
2322
27
    cstate->off_nl_nosnap = OFFSET_NOT_SET;
2323
27
    break;
2324
2325
28
  case DLT_JUNIPER_ISM:
2326
28
    cstate->off_linktype.constant_part = 8;
2327
28
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET;
2328
28
    cstate->off_nl = OFFSET_NOT_SET;
2329
28
    cstate->off_nl_nosnap = OFFSET_NOT_SET;
2330
28
    break;
2331
2332
19
  case DLT_JUNIPER_VS:
2333
46
  case DLT_JUNIPER_SRX_E2E:
2334
68
  case DLT_JUNIPER_FIBRECHANNEL:
2335
93
  case DLT_JUNIPER_ATM_CEMIC:
2336
93
    cstate->off_linktype.constant_part = 8;
2337
93
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET;
2338
93
    cstate->off_nl = OFFSET_NOT_SET;
2339
93
    cstate->off_nl_nosnap = OFFSET_NOT_SET;
2340
93
    break;
2341
2342
116
  case DLT_MTP2:
2343
116
    cstate->off_li = 2;
2344
116
    cstate->off_li_hsl = 4;
2345
116
    cstate->off_sio = 3;
2346
116
    cstate->off_opc = 4;
2347
116
    cstate->off_dpc = 4;
2348
116
    cstate->off_sls = 7;
2349
116
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2350
116
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET;
2351
116
    cstate->off_nl = OFFSET_NOT_SET;
2352
116
    cstate->off_nl_nosnap = OFFSET_NOT_SET;
2353
116
    break;
2354
2355
129
  case DLT_MTP2_WITH_PHDR:
2356
129
    cstate->off_li = 6;
2357
129
    cstate->off_li_hsl = 8;
2358
129
    cstate->off_sio = 7;
2359
129
    cstate->off_opc = 8;
2360
129
    cstate->off_dpc = 8;
2361
129
    cstate->off_sls = 11;
2362
129
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2363
129
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET;
2364
129
    cstate->off_nl = OFFSET_NOT_SET;
2365
129
    cstate->off_nl_nosnap = OFFSET_NOT_SET;
2366
129
    break;
2367
2368
68
  case DLT_ERF:
2369
68
    cstate->off_li = 22;
2370
68
    cstate->off_li_hsl = 24;
2371
68
    cstate->off_sio = 23;
2372
68
    cstate->off_opc = 24;
2373
68
    cstate->off_dpc = 24;
2374
68
    cstate->off_sls = 27;
2375
68
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2376
68
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET;
2377
68
    cstate->off_nl = OFFSET_NOT_SET;
2378
68
    cstate->off_nl_nosnap = OFFSET_NOT_SET;
2379
68
    break;
2380
2381
7
  case DLT_PFSYNC:
2382
7
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2383
7
    cstate->off_linkpl.constant_part = 4;
2384
7
    cstate->off_nl = 0;
2385
7
    cstate->off_nl_nosnap = 0;
2386
7
    break;
2387
2388
101
  case DLT_IPNET:
2389
101
    cstate->off_linktype.constant_part = 1;
2390
101
    cstate->off_linkpl.constant_part = 24;  /* ipnet header length */
2391
101
    cstate->off_nl = 0;
2392
101
    cstate->off_nl_nosnap = OFFSET_NOT_SET;
2393
101
    break;
2394
2395
138
  case DLT_NETANALYZER:
2396
138
    cstate->off_linkhdr.constant_part = 4;  /* Ethernet header is past 4-byte pseudo-header */
2397
138
    cstate->off_linktype.constant_part = cstate->off_linkhdr.constant_part + 12;
2398
138
    cstate->off_linkpl.constant_part = cstate->off_linkhdr.constant_part + 14;  /* pseudo-header+Ethernet header length */
2399
138
    cstate->off_nl = 0;   /* Ethernet II */
2400
138
    cstate->off_nl_nosnap = 3;  /* 802.3+802.2 */
2401
138
    break;
2402
2403
96
  case DLT_NETANALYZER_TRANSPARENT:
2404
96
    cstate->off_linkhdr.constant_part = 12; /* MAC header is past 4-byte pseudo-header, preamble, and SFD */
2405
96
    cstate->off_linktype.constant_part = cstate->off_linkhdr.constant_part + 12;
2406
96
    cstate->off_linkpl.constant_part = cstate->off_linkhdr.constant_part + 14;  /* pseudo-header+preamble+SFD+Ethernet header length */
2407
96
    cstate->off_nl = 0;   /* Ethernet II */
2408
96
    cstate->off_nl_nosnap = 3;  /* 802.3+802.2 */
2409
96
    break;
2410
2411
46
  case DLT_DSA_TAG_BRCM:
2412
46
    cstate->off_linktype.constant_part = 6 + 6 + 4; // dst, src, DSA tag
2413
46
    cstate->off_linkpl.constant_part = cstate->off_linktype.constant_part + 2; // idem + EtherType
2414
46
    cstate->off_nl = 0; // Ethernet II
2415
46
    cstate->off_nl_nosnap = 3; // 802.3+802.2
2416
46
    break;
2417
2418
55
  case DLT_DSA_TAG_DSA:
2419
55
    cstate->off_linktype.constant_part = 6 + 6 + 4; // dst, src, DSA tag
2420
55
    cstate->off_linkpl.constant_part = cstate->off_linktype.constant_part + 2; // idem + EtherType
2421
55
    cstate->off_nl = 0; // Ethernet II
2422
55
    cstate->off_nl_nosnap = 3; // 802.3+802.2
2423
55
    break;
2424
2425
50
  case DLT_EN3MB:
2426
91
  case DLT_AX25:
2427
137
  case DLT_PRONET:
2428
155
  case DLT_CHAOS:
2429
#ifdef DLT_HIPPI
2430
  case DLT_HIPPI:
2431
#endif
2432
183
  case DLT_REDBACK_SMARTEDGE:
2433
183
#ifdef DLT_HHDLC
2434
191
  case DLT_HHDLC:
2435
191
#endif
2436
    /*
2437
     * Currently, only raw "link[N:M]" filtering is supported.
2438
     */
2439
194
  case DLT_AX25_KISS:
2440
    /*
2441
     * Idem, plus the initial code for AX.25 KISS commented:
2442
     *
2443
     * - "variable, min 15, max 71 steps of 7" about off_linktype
2444
     * - "variable, min 16, max 71 steps of 7" about off_nl
2445
     *
2446
     * It is not clear how that relates with the AX.25 and KISS
2447
     * specifications, also there is a possibility of Linux kernel
2448
     * modifying the packet type and/or structure.  So if anybody
2449
     * would like to implement a better filtering support for this
2450
     * DLT, it would be a good idea to verify and to document all
2451
     * particulars of the encoding first.
2452
     */
2453
221
  case DLT_BACNET_MS_TP:
2454
    /*
2455
     * This DLT supports a few primitives besides "link[N:M]", but
2456
     * "link proto", whether explicit or implicit, is not one of
2457
     * these.
2458
     *
2459
     * The third octet of an MS/TP frame is Frame Type, but it is
2460
     * the MS/TP frame type [0..7] rather than a network protocol
2461
     * type.  It can be tested using "link[2]".  If in future it
2462
     * becomes necessary to have a solution that matches the
2463
     * problem space better, it would need to be a new special
2464
     * primitive that works on MS/TP DLT(s) only and takes names
2465
     * for the types, for example, "ms-tp type token".
2466
     */
2467
221
    cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2468
221
    cstate->off_linkpl.constant_part = OFFSET_NOT_SET;
2469
221
    cstate->off_nl = OFFSET_NOT_SET;
2470
221
    cstate->off_nl_nosnap = OFFSET_NOT_SET; /* no 802.2 LLC */
2471
221
    break;
2472
2473
1.91k
  default:
2474
    /*
2475
     * For values in the range in which we've assigned new
2476
     * DLT_ values, only raw "link[N:M]" filtering is supported.
2477
     */
2478
1.91k
    if (cstate->linktype >= DLT_HIGH_MATCHING_MIN &&
2479
1.90k
        cstate->linktype <= DLT_HIGH_MATCHING_MAX) {
2480
1.84k
      cstate->off_linktype.constant_part = OFFSET_NOT_SET;
2481
1.84k
      cstate->off_linkpl.constant_part = OFFSET_NOT_SET;
2482
1.84k
      cstate->off_nl = OFFSET_NOT_SET;
2483
1.84k
      cstate->off_nl_nosnap = OFFSET_NOT_SET;
2484
1.84k
    } else {
2485
69
      bpf_set_error(cstate, "unknown data link type %d",
2486
69
          cstate->linktype);
2487
69
      return (-1);
2488
69
    }
2489
1.84k
    break;
2490
13.0k
  }
2491
2492
12.9k
  cstate->off_outermostlinkhdr = cstate->off_prevlinkhdr = cstate->off_linkhdr;
2493
12.9k
  return (0);
2494
13.0k
}
2495
2496
/*
2497
 * Load a value relative to the specified absolute offset.
2498
 */
2499
static struct slist *
2500
gen_load_absoffsetrel(compiler_state_t *cstate, struct slist *s,
2501
    const u_int offset, const u_int size)
2502
234k
{
2503
234k
  switch (size) {
2504
102k
  case BPF_B:
2505
177k
  case BPF_H:
2506
234k
  case BPF_W:
2507
234k
    break;
2508
0
  default:
2509
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "size", size);
2510
234k
  }
2511
2512
  /*
2513
   * If "s" is non-null, it has code to arrange that the X register
2514
   * contains the variable part of the absolute offset, so we
2515
   * generate a load relative to that, with an offset of the constant
2516
   * part of the absolute offset:
2517
   *   (ldb|ldh|ld) [x + k]
2518
   *
2519
   * Otherwise, we can do an absolute load with an offset of the
2520
   * constant part of the absolute offset:
2521
   *   (ldb|ldh|ld) [k]
2522
   */
2523
234k
  if (s != NULL) {
2524
    /*
2525
     * "s" points to a list of statements that puts the
2526
     * variable part of the absolute offset into the X register.
2527
     * Do an indirect load, to use the X register as an offset.
2528
     */
2529
61.7k
    struct slist *s2 = new_stmt(cstate, BPF_LD|BPF_IND|size);
2530
61.7k
    s2->s.k = offset;
2531
61.7k
    sappend(s, s2);
2532
172k
  } else {
2533
    /*
2534
     * There is no variable part of the absolute offset, so
2535
     * just do an absolute load.
2536
     */
2537
172k
    s = new_stmt(cstate, BPF_LD|BPF_ABS|size);
2538
172k
    s->s.k = offset;
2539
172k
  }
2540
234k
  return s;
2541
234k
}
2542
2543
/*
2544
 * Load a value relative to the specified absolute offset and the specified
2545
 * arithmetic expression.
2546
 */
2547
static struct slist *
2548
gen_load_absoffsetarthrel(compiler_state_t *cstate, struct slist *varpart,
2549
    const bpf_u_int32 constpart, const struct arth *arthpart,
2550
    const u_int bpf_size)
2551
3.67k
{
2552
  /*
2553
   * The required loading offset is a function of three inputs:
2554
   *
2555
   * - the variable part of an absolute offset (either absent or already
2556
   *   loaded into X using the given sequence of instructions),
2557
   * - the constant part of an absolute offset (the given integer), and
2558
   * - the value of a given arithmetic expression (loadable into A or X
2559
   *   from a scratch memory register).
2560
   *
2561
   * Converge this to "(ld|ldh|ldb) [x + k]", where 'k' holds the
2562
   * constant part and 'x' holds the sum of the variable part (if any)
2563
   * and the arithmetic expression value.  That is, if the variable part
2564
   * is absent:
2565
   *   X = <arithmetic expression value>
2566
   * otherwise:
2567
   *   A = <arithmetic expression value>
2568
   *   A = A + X
2569
   *   X = A
2570
   * The rest is a case of a problem that already has a solution.
2571
   */
2572
3.67k
  if (! varpart)
2573
1.71k
    varpart = xfer_to_x(cstate, arthpart);
2574
1.96k
  else {
2575
1.96k
    sappend(varpart, xfer_to_a(cstate, arthpart));
2576
1.96k
    sappend(varpart, new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_X));
2577
1.96k
    sappend(varpart, new_stmt(cstate, BPF_MISC|BPF_TAX));
2578
1.96k
  }
2579
3.67k
  return gen_load_absoffsetrel(cstate, varpart, constpart, bpf_size);
2580
3.67k
}
2581
2582
/*
2583
 * Load a value relative to the beginning of the specified header.
2584
 */
2585
static struct slist *
2586
gen_load_a(compiler_state_t *cstate, const enum e_offrel offrel, u_int offset,
2587
    const u_int size)
2588
230k
{
2589
230k
  struct slist *s;
2590
2591
  /*
2592
   * Squelch warnings from compilers that *don't* assume that
2593
   * offrel always has a valid enum value and therefore don't
2594
   * assume that we'll always go through one of the case arms.
2595
   *
2596
   * If we have a default case, compilers that *do* assume that
2597
   * will then complain about the default case code being
2598
   * unreachable.
2599
   *
2600
   * Damned if you do, damned if you don't.
2601
   */
2602
230k
  s = NULL;
2603
2604
230k
  switch (offrel) {
2605
2606
1.21k
  case OR_PACKET:
2607
1.21k
    break;
2608
2609
55.5k
  case OR_LINKHDR:
2610
55.5k
    s = gen_abs_offset_varpart(cstate, &cstate->off_linkhdr);
2611
55.5k
    offset += cstate->off_linkhdr.constant_part;
2612
55.5k
    break;
2613
2614
1.42k
  case OR_PREVLINKHDR:
2615
1.42k
    s = gen_abs_offset_varpart(cstate, &cstate->off_prevlinkhdr);
2616
1.42k
    offset += cstate->off_prevlinkhdr.constant_part;
2617
1.42k
    break;
2618
2619
16.9k
  case OR_LLC:
2620
16.9k
    s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
2621
16.9k
    offset += cstate->off_linkpl.constant_part;
2622
16.9k
    break;
2623
2624
881
  case OR_PREVMPLSHDR:
2625
881
    s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
2626
881
    offset += cstate->off_linkpl.constant_part + cstate->off_nl -
2627
881
        MPLS_STACKENTRY_LEN;
2628
881
    break;
2629
2630
72.8k
  case OR_LINKPL:
2631
72.8k
    s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
2632
72.8k
    offset += cstate->off_linkpl.constant_part + cstate->off_nl;
2633
72.8k
    break;
2634
2635
37.8k
  case OR_LINKPL_NOSNAP:
2636
37.8k
    s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
2637
37.8k
    offset += cstate->off_linkpl.constant_part +
2638
37.8k
        cstate->off_nl_nosnap;
2639
37.8k
    break;
2640
2641
24.2k
  case OR_LINKTYPE:
2642
24.2k
    s = gen_abs_offset_varpart(cstate, &cstate->off_linktype);
2643
24.2k
    offset += cstate->off_linktype.constant_part;
2644
24.2k
    break;
2645
2646
9.99k
  case OR_TRAN_IPV4:
2647
    /*
2648
     * Load the X register with the length of the IPv4 header
2649
     * (plus the offset of the link-layer header, if it's
2650
     * preceded by a variable-length header such as a radio
2651
     * header), in bytes.
2652
     */
2653
9.99k
    s = gen_loadx_iphdrlen(cstate);
2654
2655
    /*
2656
     * Load the item at {offset of the link-layer payload} +
2657
     * {offset, relative to the start of the link-layer
2658
     * payload, of the IPv4 header} + {length of the IPv4 header} +
2659
     * {specified offset}.
2660
     *
2661
     * If the offset of the link-layer payload is variable,
2662
     * the variable part of that offset is included in the
2663
     * value in the X register, and we include the constant
2664
     * part in the offset of the load.
2665
     */
2666
9.99k
    offset += cstate->off_linkpl.constant_part + cstate->off_nl;
2667
9.99k
    break;
2668
2669
9.97k
  case OR_TRAN_IPV6:
2670
9.97k
    s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
2671
9.97k
    offset += cstate->off_linkpl.constant_part + cstate->off_nl +
2672
9.97k
        IP6_HDRLEN;
2673
9.97k
    break;
2674
230k
  }
2675
230k
  return gen_load_absoffsetrel(cstate, s, offset, size);
2676
230k
}
2677
2678
/*
2679
 * Generate code to load into the X register the sum of the length of
2680
 * the IPv4 header and the variable part of the offset of the link-layer
2681
 * payload.
2682
 */
2683
static struct slist *
2684
gen_loadx_iphdrlen(compiler_state_t *cstate)
2685
12.0k
{
2686
12.0k
  struct slist *s, *s2;
2687
2688
12.0k
  s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
2689
12.0k
  if (s != NULL) {
2690
    /*
2691
     * The offset of the link-layer payload has a variable
2692
     * part.  "s" points to a list of statements that put
2693
     * the variable part of that offset into the X register.
2694
     *
2695
     * The 4*([k]&0xf) addressing mode can't be used, as we
2696
     * don't have a constant offset, so we have to load the
2697
     * value in question into the A register and add to it
2698
     * the value from the X register.
2699
     */
2700
3.48k
    s2 = new_stmt(cstate, BPF_LD|BPF_IND|BPF_B);
2701
3.48k
    s2->s.k = cstate->off_linkpl.constant_part + cstate->off_nl;
2702
3.48k
    sappend(s, s2);
2703
3.48k
    s2 = new_stmt(cstate, BPF_ALU|BPF_AND|BPF_K);
2704
3.48k
    s2->s.k = 0xf;
2705
3.48k
    sappend(s, s2);
2706
3.48k
    s2 = new_stmt(cstate, BPF_ALU|BPF_LSH|BPF_K);
2707
3.48k
    s2->s.k = 2;
2708
3.48k
    sappend(s, s2);
2709
2710
    /*
2711
     * The A register now contains the length of the IP header.
2712
     * We need to add to it the variable part of the offset of
2713
     * the link-layer payload, which is still in the X
2714
     * register, and move the result into the X register.
2715
     */
2716
3.48k
    sappend(s, new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_X));
2717
3.48k
    sappend(s, new_stmt(cstate, BPF_MISC|BPF_TAX));
2718
8.55k
  } else {
2719
    /*
2720
     * The offset of the link-layer payload is a constant,
2721
     * so no code was generated to load the (nonexistent)
2722
     * variable part of that offset.
2723
     *
2724
     * This means we can use the 4*([k]&0xf) addressing
2725
     * mode.  Load the length of the IPv4 header, which
2726
     * is at an offset of cstate->off_nl from the beginning of
2727
     * the link-layer payload, and thus at an offset of
2728
     * cstate->off_linkpl.constant_part + cstate->off_nl from the beginning
2729
     * of the raw packet data, using that addressing mode.
2730
     */
2731
8.55k
    s = new_stmt(cstate, BPF_LDX|BPF_MSH|BPF_B);
2732
8.55k
    s->s.k = cstate->off_linkpl.constant_part + cstate->off_nl;
2733
8.55k
  }
2734
12.0k
  return s;
2735
12.0k
}
2736
2737
/*
2738
 * Produce an instruction block with a final branch statement that takes the
2739
 * true branch iff rsense is not zero.  Since this function detects Boolean
2740
 * constants for potential later use, the resulting block must not be modified
2741
 * directly afterwards, instead it should be used as an argument to gen_and(),
2742
 * gen_or(), gen_not() and sprepend_to_block().
2743
 */
2744
static struct block *
2745
gen_uncond(compiler_state_t *cstate, const u_char rsense)
2746
32.5k
{
2747
32.5k
  struct slist *s;
2748
2749
32.5k
  s = new_stmt(cstate, BPF_LD|BPF_IMM);
2750
32.5k
  s->s.k = !rsense;
2751
32.5k
  struct block *ret = gen_jmp_k(cstate, BPF_JEQ, 0, s);
2752
32.5k
  ret->meaning = rsense ? IS_TRUE : IS_FALSE;
2753
32.5k
  return ret;
2754
32.5k
}
2755
2756
static inline struct block *
2757
gen_true(compiler_state_t *cstate)
2758
5.93k
{
2759
5.93k
  return gen_uncond(cstate, 1);
2760
5.93k
}
2761
2762
static inline struct block *
2763
gen_false(compiler_state_t *cstate)
2764
26.6k
{
2765
26.6k
  return gen_uncond(cstate, 0);
2766
26.6k
}
2767
2768
/*
2769
 * Generate code to match a particular packet type.
2770
 *
2771
 * "proto" is an Ethernet type value, if > ETHERMTU, or an LLC SAP
2772
 * value, if <= ETHERMTU.  We use that to determine whether to
2773
 * match the type/length field or to check the type/length field for
2774
 * a value <= ETHERMTU to see whether it's a type field and then do
2775
 * the appropriate test.
2776
 */
2777
static struct block *
2778
gen_ether_linktype(compiler_state_t *cstate, bpf_u_int32 ll_proto)
2779
7.64k
{
2780
7.64k
  struct block *b0, *b1;
2781
2782
7.64k
  switch (ll_proto) {
2783
2784
3.44k
  case LLCSAP_ISONS:
2785
3.51k
  case LLCSAP_IP:
2786
3.55k
  case LLCSAP_NETBEUI:
2787
    /*
2788
     * OSI protocols and NetBEUI always use 802.2 encapsulation,
2789
     * so we check the DSAP and SSAP.
2790
     *
2791
     * LLCSAP_IP checks for IP-over-802.2, rather
2792
     * than IP-over-Ethernet or IP-over-SNAP.
2793
     *
2794
     * XXX - should we check both the DSAP and the
2795
     * SSAP, like this, or should we check just the
2796
     * DSAP, as we do for other types <= ETHERMTU
2797
     * (i.e., other SAP values)?
2798
     */
2799
3.55k
    b0 = gen_cmp_le(cstate, OR_LINKTYPE, 0, BPF_H, ETHERMTU);
2800
3.55k
    b1 = gen_cmp(cstate, OR_LLC, 0, BPF_H, (ll_proto << 8) | ll_proto);
2801
3.55k
    return gen_and(b0, b1);
2802
2803
182
  case LLCSAP_IPX:
2804
    /*
2805
     * Check for;
2806
     *
2807
     *  Ethernet_II frames, which are Ethernet
2808
     *  frames with a frame type of ETHERTYPE_IPX;
2809
     *
2810
     *  Ethernet_802.3 frames, which are 802.3
2811
     *  frames (i.e., the type/length field is
2812
     *  a length field, <= ETHERMTU, rather than
2813
     *  a type field) with the first two bytes
2814
     *  after the Ethernet/802.3 header being
2815
     *  0xFFFF;
2816
     *
2817
     *  Ethernet_802.2 frames, which are 802.3
2818
     *  frames with an 802.2 LLC header and
2819
     *  with the IPX LSAP as the DSAP in the LLC
2820
     *  header;
2821
     *
2822
     *  Ethernet_SNAP frames, which are 802.3
2823
     *  frames with an LLC header and a SNAP
2824
     *  header and with an OUI of 0x000000
2825
     *  (encapsulated Ethernet) and a protocol
2826
     *  ID of ETHERTYPE_IPX in the SNAP header.
2827
     *
2828
     * XXX - should we generate the same code both
2829
     * for tests for LLCSAP_IPX and for ETHERTYPE_IPX?
2830
     */
2831
2832
    /*
2833
     * This generates code to check both for the
2834
     * IPX LSAP (Ethernet_802.2) and for Ethernet_802.3.
2835
     */
2836
182
    b0 = gen_cmp(cstate, OR_LLC, 0, BPF_B, LLCSAP_IPX);
2837
182
    b1 = gen_cmp(cstate, OR_LLC, 0, BPF_H, 0xFFFF);
2838
182
    b1 = gen_or(b0, b1);
2839
2840
    /*
2841
     * Now we add code to check for SNAP frames with
2842
     * ETHERTYPE_IPX, i.e. Ethernet_SNAP.
2843
     */
2844
182
    b0 = gen_snap(cstate, 0x000000, ETHERTYPE_IPX);
2845
182
    b1 = gen_or(b0, b1);
2846
2847
    /*
2848
     * Now we generate code to check for 802.3
2849
     * frames in general.
2850
     */
2851
182
    b0 = gen_cmp_le(cstate, OR_LINKTYPE, 0, BPF_H, ETHERMTU);
2852
2853
    /*
2854
     * Now add the check for 802.3 frames before the
2855
     * check for Ethernet_802.2 and Ethernet_802.3,
2856
     * as those checks should only be done on 802.3
2857
     * frames, not on Ethernet frames.
2858
     */
2859
182
    b1 = gen_and(b0, b1);
2860
2861
    /*
2862
     * Now add the check for Ethernet_II frames, and
2863
     * do that before checking for the other frame
2864
     * types.
2865
     */
2866
182
    b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, ETHERTYPE_IPX);
2867
182
    return gen_or(b0, b1);
2868
2869
35
  case ETHERTYPE_ATALK:
2870
53
  case ETHERTYPE_AARP:
2871
    /*
2872
     * EtherTalk (AppleTalk protocols on Ethernet link
2873
     * layer) may use 802.2 encapsulation.
2874
     */
2875
2876
    /*
2877
     * Check for 802.2 encapsulation (EtherTalk phase 2?);
2878
     * we check for an Ethernet type field less or equal than
2879
     * 1500, which means it's an 802.3 length field.
2880
     */
2881
53
    b0 = gen_cmp_le(cstate, OR_LINKTYPE, 0, BPF_H, ETHERMTU);
2882
2883
    /*
2884
     * 802.2-encapsulated ETHERTYPE_ATALK packets are
2885
     * SNAP packets with an organization code of
2886
     * 0x080007 (Apple, for Appletalk) and a protocol
2887
     * type of ETHERTYPE_ATALK (Appletalk).
2888
     *
2889
     * 802.2-encapsulated ETHERTYPE_AARP packets are
2890
     * SNAP packets with an organization code of
2891
     * 0x000000 (encapsulated Ethernet) and a protocol
2892
     * type of ETHERTYPE_AARP (Appletalk ARP).
2893
     */
2894
53
    if (ll_proto == ETHERTYPE_ATALK)
2895
35
      b1 = gen_snap(cstate, 0x080007, ETHERTYPE_ATALK);
2896
18
    else  /* ll_proto == ETHERTYPE_AARP */
2897
18
      b1 = gen_snap(cstate, 0x000000, ETHERTYPE_AARP);
2898
53
    b1 = gen_and(b0, b1);
2899
2900
    /*
2901
     * Check for Ethernet encapsulation (Ethertalk
2902
     * phase 1?); we just check for the Ethernet
2903
     * protocol type.
2904
     */
2905
53
    b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, ll_proto);
2906
2907
53
    return gen_or(b0, b1);
2908
2909
3.85k
  default:
2910
3.85k
    if (ll_proto <= ETHERMTU) {
2911
116
      assert_maxval(cstate, "LLC DSAP", ll_proto, UINT8_MAX);
2912
      /*
2913
       * This is an LLC SAP value, so the frames
2914
       * that match would be 802.2 frames.
2915
       * Check that the frame is an 802.2 frame
2916
       * (i.e., that the length/type field is
2917
       * a length field, <= ETHERMTU) and
2918
       * then check the DSAP.
2919
       */
2920
116
      b0 = gen_cmp_le(cstate, OR_LINKTYPE, 0, BPF_H, ETHERMTU);
2921
116
      b1 = gen_cmp(cstate, OR_LINKTYPE, 2, BPF_B, ll_proto);
2922
116
      return gen_and(b0, b1);
2923
3.74k
    } else {
2924
3.74k
      assert_maxval(cstate, "EtherType", ll_proto, UINT16_MAX);
2925
      /*
2926
       * This is an Ethernet type, so compare
2927
       * the length/type field with it (if
2928
       * the frame is an 802.2 frame, the length
2929
       * field will be <= ETHERMTU, and, as
2930
       * "ll_proto" is > ETHERMTU, this test
2931
       * will fail and the frame won't match,
2932
       * which is what we want).
2933
       */
2934
3.74k
      return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, ll_proto);
2935
3.74k
    }
2936
7.64k
  }
2937
7.64k
}
2938
2939
/*
2940
 * AF_INET is 2 in all the operating systems we support...
2941
 *
2942
 * ...except for Haiku, which defines it as 1.
2943
 *
2944
 * So we define BSD_AFNUM_INET as 2 (as AF_INET originated in 4.2BSD,
2945
 * and *almost* everybody just adopted it).
2946
 *
2947
 * Haiku doesn't use DLT_NULL (it uses DLT_RAW for the loopback device),
2948
 * so we don't need to check for it in DLT_NULL captures. We should,
2949
 * however, use BSD_AFNUM_INET rathr than AF_INET when checking for
2950
 * IPv4 in DLT_NULL, DLT_LOOP, and DLT_ENC captures.
2951
 */
2952
6.02k
#define BSD_AFNUM_INET    2  /* Everybody but Haiku (and BeOS?) */
2953
2954
/*
2955
 * The three different values we should check for when checking for an
2956
 * IPv6 packet with DLT_NULL.
2957
 */
2958
4.58k
#define BSD_AFNUM_INET6_BSD 24  /* NetBSD, OpenBSD, BSD/OS, Npcap */
2959
4.58k
#define BSD_AFNUM_INET6_FREEBSD 28  /* FreeBSD */
2960
4.58k
#define BSD_AFNUM_INET6_DARWIN  30  /* macOS, iOS, other Darwin-based OSes */
2961
2962
static struct block *
2963
gen_endian_linktype(compiler_state_t *cstate, u_int offset, u_int size,
2964
    bpf_u_int32 ll_proto, int swapped)
2965
19.7k
{
2966
19.7k
  return (gen_cmp(cstate, OR_LINKHDR, offset, size,
2967
19.7k
      swapped ? PCAP_BSWAP_32(ll_proto) : ll_proto));
2968
19.7k
}
2969
2970
static struct block *
2971
gen_bsd_af_linktype_live(compiler_state_t *cstate, u_int offset, u_int size,
2972
    bpf_u_int32 ll_proto, int swapped)
2973
0
{
2974
0
  switch (ll_proto) {
2975
2976
0
  case ETHERTYPE_IP:
2977
0
    return (gen_endian_linktype(cstate, offset, size, AF_INET,
2978
0
        swapped));
2979
2980
0
  case ETHERTYPE_IPV6:
2981
0
    return (gen_endian_linktype(cstate, offset, size, AF_INET6,
2982
0
        swapped));
2983
2984
0
  default:
2985
    /*
2986
     * Not a type on which we support filtering.
2987
     * XXX - support those that have AF_ values
2988
     * #defined on this platform, at least?
2989
     */
2990
0
    return gen_false(cstate);
2991
0
  }
2992
0
}
2993
2994
static struct block *
2995
gen_bsd_af_linktype_offline(compiler_state_t *cstate, u_int offset, u_int size,
2996
    bpf_u_int32 ll_proto, int swapped)
2997
17.7k
{
2998
17.7k
  struct block *b0, *b1;
2999
3000
17.7k
  switch (ll_proto) {
3001
3002
6.02k
  case ETHERTYPE_IP:
3003
    /*
3004
     * Only Haiku (and BeOS?) define AF_INET differently
3005
     * from the value 4.2BSD used (2), and Haiku doesn't
3006
     * have any capture type that uses AF_INET values
3007
     * (its loopback device uses DLT_RAW), so, while
3008
     * we must use BSD_AFNUM_INET when comparing,
3009
     * we don't have to test for more than one value.
3010
     */
3011
6.02k
    return (gen_endian_linktype(cstate, offset, size, BSD_AFNUM_INET,
3012
6.02k
        swapped));
3013
3014
4.58k
  case ETHERTYPE_IPV6:
3015
    /*
3016
     * AF_INET6 values are, unfortunately, be platform-dependent,
3017
     * even on platforms that use it in link-layer headers,
3018
     * because 4.2BSD didn't have a value for it (given that
3019
     * IPv6 didn't exist back in the early 1980's), and they
3020
     * all picked their own values.
3021
     *
3022
     * This means that, if we're reading from a savefile, we
3023
     * need to check for all the possible values.
3024
     *
3025
     * If we're doing a live capture, we only need to check
3026
     * for this platform's value; however, Npcap uses 24,
3027
     * which isn't Windows's AF_INET6 value.  (Given the
3028
     * multiple different values, programs that read pcap
3029
     * files shouldn't be checking for their platform's
3030
     * AF_INET6 value anyway, they should check for all of the
3031
     * possible values. and they might as well do that even for
3032
     * live captures.)
3033
     */
3034
4.58k
    b0 = gen_endian_linktype(cstate, offset, size,
3035
4.58k
        BSD_AFNUM_INET6_BSD, swapped);
3036
4.58k
    b1 = gen_endian_linktype(cstate, offset, size,
3037
4.58k
        BSD_AFNUM_INET6_FREEBSD, swapped);
3038
4.58k
    b1 = gen_or(b0, b1);
3039
4.58k
    b0 = gen_endian_linktype(cstate, offset, size,
3040
4.58k
        BSD_AFNUM_INET6_DARWIN, swapped);
3041
4.58k
    return gen_or(b0, b1);
3042
3043
7.15k
  default:
3044
    /*
3045
     * Not a type on which we support filtering.
3046
     * XXX - support those that have AF_ values
3047
     * #defined on this platform, at least?
3048
     */
3049
7.15k
    return gen_false(cstate);
3050
17.7k
  }
3051
17.7k
}
3052
3053
/*
3054
 * Generate a test for a loopback or DLT_ENC link-layer type; the type
3055
 * is the link-layer type.
3056
 */
3057
static struct block *
3058
gen_loopback_linktype_live(compiler_state_t *cstate, bpf_u_int32 ll_proto)
3059
0
{
3060
0
  switch (cstate->linktype) {
3061
3062
0
  case DLT_NULL:
3063
0
  case DLT_ENC:
3064
    /*
3065
     * The value is in host byte order in the packet.
3066
     *
3067
     * If that's big-endian, we can just compare it
3068
     * with the specified type.
3069
     *
3070
     * if that's little-endian, we have to compare it
3071
     * with a byte-swapped version of the specified
3072
     * type.
3073
     *
3074
     * htonl(the specified type) will do nothing to
3075
     * the specified type on a big-endian machine, and
3076
     * will byte-swap the specified type on a little-
3077
     * endian machine, so just use that as the value
3078
     * against which to compare.
3079
     */
3080
0
    return (gen_cmp(cstate, OR_LINKHDR, 0, BPF_W, htonl(ll_proto)));
3081
3082
0
  case DLT_LOOP:
3083
    /*
3084
     * The value is in network byte order in the packet,
3085
     * so just compare it with the specified type.
3086
     */
3087
0
    return (gen_cmp(cstate, OR_LINKHDR, 0, BPF_W, ll_proto));
3088
3089
0
  default:
3090
    /* Should not happen. */
3091
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "linktype",
3092
0
        cstate->linktype);
3093
0
  }
3094
0
}
3095
3096
/*
3097
 * Generate a test for the DLT_PFLOG  link-layer type; the type is the
3098
 * link-layer type.
3099
 */
3100
static struct block *
3101
gen_pflog_linktype(compiler_state_t *cstate, bpf_u_int32 ll_proto)
3102
2.41k
{
3103
2.41k
  if (cstate->bpf_pcap->bpf_codegen_flags & BPF_OFFLINE_AF_HANDLING) {
3104
2.41k
    return (gen_bsd_af_linktype_offline(cstate,
3105
2.41k
        offsetof(struct pfloghdr, af), BPF_B, ll_proto, 0));
3106
2.41k
  }
3107
0
  return (gen_bsd_af_linktype_live(cstate, offsetof(struct pfloghdr, af),
3108
0
      BPF_B, ll_proto, 0));
3109
2.41k
}
3110
3111
static struct block *
3112
gen_loopback_linktype(compiler_state_t *cstate, bpf_u_int32 ll_proto)
3113
7.88k
{
3114
7.88k
  struct block *b0, *b1;
3115
3116
  /*
3117
   * For DLT_NULL, the link-layer header is a 32-bit word
3118
   * containing an AF_ value in *host* byte order, and for
3119
   * DLT_ENC, the link-layer header begins with a 32-bit
3120
   * word containing an AF_ value in host byte order.
3121
   *
3122
   * In addition, if we're reading a saved capture file,
3123
   * the host byte order in the capture may not be the
3124
   * same as the host byte order on this machine.
3125
   *
3126
   * For DLT_LOOP, the link-layer header is a 32-bit
3127
   * word containing an AF_ value in *network* byte order.
3128
   */
3129
7.88k
  if (!(cstate->bpf_pcap->bpf_codegen_flags & BPF_OFFLINE_AF_HANDLING)) {
3130
    /*
3131
     * This is a live caapture, so we just check for this
3132
     * platform's AF_ value (except when we don't).
3133
     *
3134
     * The AF_ value is in host byte order, but the BPF
3135
     * interpreter will convert it to network byte order,
3136
     * so we run it through "htonl()", and generate
3137
     * code to compare against the result.
3138
     */
3139
0
    switch (ll_proto) {
3140
3141
0
    case ETHERTYPE_IP:
3142
0
      return (gen_loopback_linktype_live(cstate, AF_INET));
3143
3144
0
    case ETHERTYPE_IPV6:
3145
#ifdef _WIN32
3146
      /*
3147
       * Npcap doesn't use Windows's AF_INET6,
3148
       * as that collides with AF_IPX on
3149
       * some BSDs (both have the value 23).
3150
       * Instead, it uses 24 (BSD_AFNUM_INET6_BSD).
3151
       */
3152
      return (gen_loopback_linktype_live(cstate, BSD_AFNUM_INET6_BSD));
3153
#else /* _WIN32 */
3154
0
      return (gen_loopback_linktype_live(cstate, AF_INET6));
3155
0
#endif /* _WIN32 */
3156
3157
0
    default:
3158
      /*
3159
       * Not a type on which we support filtering.
3160
       * XXX - support those that have AF_ values
3161
       * #defined on this platform, at least?
3162
       */
3163
0
      return gen_false(cstate);
3164
0
    }
3165
0
  }
3166
3167
  /*
3168
   * This is a savefile.
3169
   *
3170
   * for DLT_NULL and DLT_ENC, the endianness of the value in the
3171
   * packets is not necessarily the endianness of the capture file,
3172
   * as the endianness of the value in the packets is the endianness
3173
   * of the host that did the capture, but the endianness of the file
3174
   * is the endianness of the host that wrote the file, and this
3175
   * file might be the result of a host with one byte order processing
3176
   * another file from a host with a different order.
3177
   *
3178
   * For those types, we first test for all the types using the
3179
   * byte order of the file, and then test again for all the types
3180
   * with the opposite byte order of the file, under the assumption
3181
   * that the most likely case is that the file was written as
3182
   * a live capture.
3183
   *
3184
   * for DLT_LOOP, the endianness of the value in the packets
3185
   * is always big-endian.
3186
   *
3187
   * For DLT_PFLOG, the field is one byte long, so it has no
3188
   * endianness. (None of our platform are nibble-addressible. :-))
3189
   */
3190
7.88k
  switch (cstate->linktype) {
3191
3192
7.18k
  case DLT_NULL:
3193
7.47k
  case DLT_ENC:
3194
7.47k
    b0 = gen_bsd_af_linktype_offline(cstate, 0, BPF_W, ll_proto,
3195
7.47k
        cstate->bpf_pcap->swapped);
3196
7.47k
    b1 = gen_bsd_af_linktype_offline(cstate, 0, BPF_W, ll_proto,
3197
7.47k
        !cstate->bpf_pcap->swapped);
3198
7.47k
    return (gen_or(b0, b1));
3199
3200
418
  case DLT_LOOP:
3201
418
    return (gen_bsd_af_linktype_offline(cstate, 0, BPF_W, ll_proto, 0));
3202
3203
0
  default:
3204
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "linktype",
3205
0
        cstate->linktype);
3206
7.88k
  }
3207
7.88k
}
3208
3209
/*
3210
 * "proto" is an Ethernet type value and for IPNET, if it is not IPv4
3211
 * or IPv6 then we have an error.
3212
 */
3213
static struct block *
3214
gen_ipnet_linktype(compiler_state_t *cstate, bpf_u_int32 ll_proto)
3215
738
{
3216
738
  switch (ll_proto) {
3217
3218
190
  case ETHERTYPE_IP:
3219
190
    return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_B, IPH_AF_INET);
3220
    /*NOTREACHED*/
3221
3222
118
  case ETHERTYPE_IPV6:
3223
118
    return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_B, IPH_AF_INET6);
3224
    /*NOTREACHED*/
3225
3226
430
  default:
3227
430
    break;
3228
738
  }
3229
3230
430
  return gen_false(cstate);
3231
738
}
3232
3233
/*
3234
 * Generate code to match a particular packet type.
3235
 *
3236
 * "ll_proto" is an Ethernet type value, if > ETHERMTU, or an LLC SAP
3237
 * value, if <= ETHERMTU.  We use that to determine whether to
3238
 * match the type field or to check the type field for the special
3239
 * LINUX_SLL_P_802_2 value and then do the appropriate test.
3240
 */
3241
static struct block *
3242
gen_linux_sll_linktype(compiler_state_t *cstate, bpf_u_int32 ll_proto)
3243
1.58k
{
3244
1.58k
  struct block *b0, *b1;
3245
3246
1.58k
  switch (ll_proto) {
3247
3248
536
  case LLCSAP_ISONS:
3249
650
  case LLCSAP_IP:
3250
684
  case LLCSAP_NETBEUI:
3251
    /*
3252
     * OSI protocols and NetBEUI always use 802.2 encapsulation,
3253
     * so we check the DSAP and SSAP.
3254
     *
3255
     * LLCSAP_IP checks for IP-over-802.2, rather
3256
     * than IP-over-Ethernet or IP-over-SNAP.
3257
     *
3258
     * XXX - should we check both the DSAP and the
3259
     * SSAP, like this, or should we check just the
3260
     * DSAP, as we do for other types <= ETHERMTU
3261
     * (i.e., other SAP values)?
3262
     */
3263
684
    b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, LINUX_SLL_P_802_2);
3264
684
    b1 = gen_cmp(cstate, OR_LLC, 0, BPF_H, (ll_proto << 8) | ll_proto);
3265
684
    return gen_and(b0, b1);
3266
3267
76
  case LLCSAP_IPX:
3268
    /*
3269
     *  Ethernet_II frames, which are Ethernet
3270
     *  frames with a frame type of ETHERTYPE_IPX;
3271
     *
3272
     *  Ethernet_802.3 frames, which have a frame
3273
     *  type of LINUX_SLL_P_802_3;
3274
     *
3275
     *  Ethernet_802.2 frames, which are 802.3
3276
     *  frames with an 802.2 LLC header (i.e, have
3277
     *  a frame type of LINUX_SLL_P_802_2) and
3278
     *  with the IPX LSAP as the DSAP in the LLC
3279
     *  header;
3280
     *
3281
     *  Ethernet_SNAP frames, which are 802.3
3282
     *  frames with an LLC header and a SNAP
3283
     *  header and with an OUI of 0x000000
3284
     *  (encapsulated Ethernet) and a protocol
3285
     *  ID of ETHERTYPE_IPX in the SNAP header.
3286
     *
3287
     * First, do the checks on LINUX_SLL_P_802_2
3288
     * frames; generate the check for either
3289
     * Ethernet_802.2 or Ethernet_SNAP frames, and
3290
     * then put a check for LINUX_SLL_P_802_2 frames
3291
     * before it.
3292
     */
3293
76
    b0 = gen_cmp(cstate, OR_LLC, 0, BPF_B, LLCSAP_IPX);
3294
76
    b1 = gen_snap(cstate, 0x000000, ETHERTYPE_IPX);
3295
76
    b1 = gen_or(b0, b1);
3296
76
    b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, LINUX_SLL_P_802_2);
3297
76
    b1 = gen_and(b0, b1);
3298
3299
    /*
3300
     * Now check for 802.3 frames and OR that with
3301
     * the previous test.
3302
     */
3303
76
    b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, LINUX_SLL_P_802_3);
3304
76
    b1 = gen_or(b0, b1);
3305
3306
    /*
3307
     * Now add the check for Ethernet_II frames, and
3308
     * do that before checking for the other frame
3309
     * types.
3310
     */
3311
76
    b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, ETHERTYPE_IPX);
3312
76
    return gen_or(b0, b1);
3313
3314
38
  case ETHERTYPE_ATALK:
3315
56
  case ETHERTYPE_AARP:
3316
    /*
3317
     * EtherTalk (AppleTalk protocols on Ethernet link
3318
     * layer) may use 802.2 encapsulation.
3319
     */
3320
3321
    /*
3322
     * Check for 802.2 encapsulation (EtherTalk phase 2?);
3323
     * we check for the 802.2 protocol type in the
3324
     * "Ethernet type" field.
3325
     */
3326
56
    b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, LINUX_SLL_P_802_2);
3327
3328
    /*
3329
     * 802.2-encapsulated ETHERTYPE_ATALK packets are
3330
     * SNAP packets with an organization code of
3331
     * 0x080007 (Apple, for Appletalk) and a protocol
3332
     * type of ETHERTYPE_ATALK (Appletalk).
3333
     *
3334
     * 802.2-encapsulated ETHERTYPE_AARP packets are
3335
     * SNAP packets with an organization code of
3336
     * 0x000000 (encapsulated Ethernet) and a protocol
3337
     * type of ETHERTYPE_AARP (Appletalk ARP).
3338
     */
3339
56
    if (ll_proto == ETHERTYPE_ATALK)
3340
38
      b1 = gen_snap(cstate, 0x080007, ETHERTYPE_ATALK);
3341
18
    else  /* ll_proto == ETHERTYPE_AARP */
3342
18
      b1 = gen_snap(cstate, 0x000000, ETHERTYPE_AARP);
3343
56
    b1 = gen_and(b0, b1);
3344
3345
    /*
3346
     * Check for Ethernet encapsulation (Ethertalk
3347
     * phase 1?); we just check for the Ethernet
3348
     * protocol type.
3349
     */
3350
56
    b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, ll_proto);
3351
3352
56
    return gen_or(b0, b1);
3353
3354
767
  default:
3355
767
    if (ll_proto <= ETHERMTU) {
3356
157
      assert_maxval(cstate, "LLC DSAP", ll_proto, UINT8_MAX);
3357
      /*
3358
       * This is an LLC SAP value, so the frames
3359
       * that match would be 802.2 frames.
3360
       * Check for the 802.2 protocol type
3361
       * in the "Ethernet type" field, and
3362
       * then check the DSAP.
3363
       */
3364
157
      b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, LINUX_SLL_P_802_2);
3365
157
      b1 = gen_cmp(cstate, OR_LINKHDR, cstate->off_linkpl.constant_part, BPF_B,
3366
157
           ll_proto);
3367
157
      return gen_and(b0, b1);
3368
610
    } else {
3369
610
      assert_maxval(cstate, "EtherType", ll_proto, UINT16_MAX);
3370
      /*
3371
       * This is an Ethernet type, so compare
3372
       * the length/type field with it (if
3373
       * the frame is an 802.2 frame, the length
3374
       * field will be <= ETHERMTU, and, as
3375
       * "ll_proto" is > ETHERMTU, this test
3376
       * will fail and the frame won't match,
3377
       * which is what we want).
3378
       */
3379
610
      return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, ll_proto);
3380
610
    }
3381
1.58k
  }
3382
1.58k
}
3383
3384
/*
3385
 * Load a value relative to the beginning of the link-layer header after the
3386
 * pflog header.
3387
 */
3388
static struct slist *
3389
gen_load_pflog_llprefixlen(compiler_state_t *cstate)
3390
284
{
3391
284
  struct slist *s1, *s2;
3392
3393
  /*
3394
   * Generate code to load the length of the pflog header into
3395
   * the register assigned to hold that length, if one has been
3396
   * assigned.  (If one hasn't been assigned, no code we've
3397
   * generated uses that prefix, so we don't need to generate any
3398
   * code to load it.)
3399
   */
3400
284
  if (cstate->off_linkpl.reg != -1) {
3401
    /*
3402
     * The length is in the first byte of the header.
3403
     */
3404
254
    s1 = new_stmt(cstate, BPF_LD|BPF_B|BPF_ABS);
3405
254
    s1->s.k = 0;
3406
3407
    /*
3408
     * Round it up to a multiple of 4.
3409
     * Add 3, and clear the lower 2 bits.
3410
     */
3411
254
    s2 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
3412
254
    s2->s.k = 3;
3413
254
    sappend(s1, s2);
3414
254
    s2 = new_stmt(cstate, BPF_ALU|BPF_AND|BPF_K);
3415
254
    s2->s.k = 0xfffffffc;
3416
254
    sappend(s1, s2);
3417
3418
    /*
3419
     * Now allocate a register to hold that value and store
3420
     * it.
3421
     */
3422
254
    s2 = new_stmt(cstate, BPF_ST);
3423
254
    s2->s.k = cstate->off_linkpl.reg;
3424
254
    sappend(s1, s2);
3425
3426
    /*
3427
     * Now move it into the X register.
3428
     */
3429
254
    s2 = new_stmt(cstate, BPF_MISC|BPF_TAX);
3430
254
    sappend(s1, s2);
3431
3432
254
    return (s1);
3433
254
  } else
3434
30
    return (NULL);
3435
284
}
3436
3437
static struct slist *
3438
gen_load_prism_llprefixlen(compiler_state_t *cstate)
3439
243
{
3440
243
  struct slist *s1, *s2;
3441
243
  struct slist *sjeq_avs_cookie;
3442
243
  struct slist *sjcommon;
3443
3444
  /*
3445
   * This code is not compatible with the optimizer, as
3446
   * we are generating jmp instructions within a normal
3447
   * slist of instructions
3448
   */
3449
243
  cstate->no_optimize = 1;
3450
3451
  /*
3452
   * Generate code to load the length of the radio header into
3453
   * the register assigned to hold that length, if one has been
3454
   * assigned.  (If one hasn't been assigned, no code we've
3455
   * generated uses that prefix, so we don't need to generate any
3456
   * code to load it.)
3457
   *
3458
   * Some Linux drivers use ARPHRD_IEEE80211_PRISM but sometimes
3459
   * or always use the AVS header rather than the Prism header.
3460
   * We load a 4-byte big-endian value at the beginning of the
3461
   * raw packet data, and see whether, when masked with 0xFFFFF000,
3462
   * it's equal to 0x80211000.  If so, that indicates that it's
3463
   * an AVS header (the masked-out bits are the version number).
3464
   * Otherwise, it's a Prism header.
3465
   *
3466
   * XXX - the Prism header is also, in theory, variable-length,
3467
   * but no known software generates headers that aren't 144
3468
   * bytes long.
3469
   */
3470
243
  if (cstate->off_linkhdr.reg != -1) {
3471
    /*
3472
     * Load the cookie.
3473
     */
3474
102
    s1 = new_stmt(cstate, BPF_LD|BPF_W|BPF_ABS);
3475
102
    s1->s.k = 0;
3476
3477
    /*
3478
     * AND it with 0xFFFFF000.
3479
     */
3480
102
    s2 = new_stmt(cstate, BPF_ALU|BPF_AND|BPF_K);
3481
102
    s2->s.k = 0xFFFFF000;
3482
102
    sappend(s1, s2);
3483
3484
    /*
3485
     * Compare with 0x80211000.
3486
     */
3487
102
    sjeq_avs_cookie = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
3488
102
    sjeq_avs_cookie->s.k = 0x80211000;
3489
102
    sappend(s1, sjeq_avs_cookie);
3490
3491
    /*
3492
     * If it's AVS:
3493
     *
3494
     * The 4 bytes at an offset of 4 from the beginning of
3495
     * the AVS header are the length of the AVS header.
3496
     * That field is big-endian.
3497
     */
3498
102
    s2 = new_stmt(cstate, BPF_LD|BPF_W|BPF_ABS);
3499
102
    s2->s.k = 4;
3500
102
    sappend(s1, s2);
3501
102
    sjeq_avs_cookie->s.jt = s2;
3502
3503
    /*
3504
     * Now jump to the code to allocate a register
3505
     * into which to save the header length and
3506
     * store the length there.  (The "jump always"
3507
     * instruction needs to have the k field set;
3508
     * it's added to the PC, so, as we're jumping
3509
     * over a single instruction, it should be 1.)
3510
     */
3511
102
    sjcommon = new_stmt(cstate, JMP(BPF_JA, BPF_K));
3512
102
    sjcommon->s.k = 1;
3513
102
    sappend(s1, sjcommon);
3514
3515
    /*
3516
     * Now for the code that handles the Prism header.
3517
     * Just load the length of the Prism header (144)
3518
     * into the A register.  Have the test for an AVS
3519
     * header branch here if we don't have an AVS header.
3520
     */
3521
102
    s2 = new_stmt(cstate, BPF_LD|BPF_W|BPF_IMM);
3522
102
    s2->s.k = 144;
3523
102
    sappend(s1, s2);
3524
102
    sjeq_avs_cookie->s.jf = s2;
3525
3526
    /*
3527
     * Now allocate a register to hold that value and store
3528
     * it.  The code for the AVS header will jump here after
3529
     * loading the length of the AVS header.
3530
     */
3531
102
    s2 = new_stmt(cstate, BPF_ST);
3532
102
    s2->s.k = cstate->off_linkhdr.reg;
3533
102
    sappend(s1, s2);
3534
102
    sjcommon->s.jf = s2;
3535
3536
    /*
3537
     * Now move it into the X register.
3538
     */
3539
102
    s2 = new_stmt(cstate, BPF_MISC|BPF_TAX);
3540
102
    sappend(s1, s2);
3541
3542
102
    return (s1);
3543
102
  } else
3544
141
    return (NULL);
3545
243
}
3546
3547
static struct slist *
3548
gen_load_avs_llprefixlen(compiler_state_t *cstate)
3549
105
{
3550
105
  struct slist *s1, *s2;
3551
3552
  /*
3553
   * Generate code to load the length of the AVS header into
3554
   * the register assigned to hold that length, if one has been
3555
   * assigned.  (If one hasn't been assigned, no code we've
3556
   * generated uses that prefix, so we don't need to generate any
3557
   * code to load it.)
3558
   */
3559
105
  if (cstate->off_linkhdr.reg != -1) {
3560
    /*
3561
     * The 4 bytes at an offset of 4 from the beginning of
3562
     * the AVS header are the length of the AVS header.
3563
     * That field is big-endian.
3564
     */
3565
91
    s1 = new_stmt(cstate, BPF_LD|BPF_W|BPF_ABS);
3566
91
    s1->s.k = 4;
3567
3568
    /*
3569
     * Now allocate a register to hold that value and store
3570
     * it.
3571
     */
3572
91
    s2 = new_stmt(cstate, BPF_ST);
3573
91
    s2->s.k = cstate->off_linkhdr.reg;
3574
91
    sappend(s1, s2);
3575
3576
    /*
3577
     * Now move it into the X register.
3578
     */
3579
91
    s2 = new_stmt(cstate, BPF_MISC|BPF_TAX);
3580
91
    sappend(s1, s2);
3581
3582
91
    return (s1);
3583
91
  } else
3584
14
    return (NULL);
3585
105
}
3586
3587
static struct slist *
3588
gen_load_radiotap_llprefixlen(compiler_state_t *cstate)
3589
154
{
3590
154
  struct slist *s1, *s2;
3591
3592
  /*
3593
   * Generate code to load the length of the radiotap header into
3594
   * the register assigned to hold that length, if one has been
3595
   * assigned.  (If one hasn't been assigned, no code we've
3596
   * generated uses that prefix, so we don't need to generate any
3597
   * code to load it.)
3598
   */
3599
154
  if (cstate->off_linkhdr.reg != -1) {
3600
    /*
3601
     * The 2 bytes at offsets of 2 and 3 from the beginning
3602
     * of the radiotap header are the length of the radiotap
3603
     * header; unfortunately, it's little-endian, so we have
3604
     * to load it a byte at a time and construct the value.
3605
     */
3606
3607
    /*
3608
     * Load the high-order byte, at an offset of 3, shift it
3609
     * left a byte, and put the result in the X register.
3610
     */
3611
143
    s1 = new_stmt(cstate, BPF_LD|BPF_B|BPF_ABS);
3612
143
    s1->s.k = 3;
3613
143
    s2 = new_stmt(cstate, BPF_ALU|BPF_LSH|BPF_K);
3614
143
    sappend(s1, s2);
3615
143
    s2->s.k = 8;
3616
143
    s2 = new_stmt(cstate, BPF_MISC|BPF_TAX);
3617
143
    sappend(s1, s2);
3618
3619
    /*
3620
     * Load the next byte, at an offset of 2, and OR the
3621
     * value from the X register into it.
3622
     */
3623
143
    s2 = new_stmt(cstate, BPF_LD|BPF_B|BPF_ABS);
3624
143
    sappend(s1, s2);
3625
143
    s2->s.k = 2;
3626
143
    s2 = new_stmt(cstate, BPF_ALU|BPF_OR|BPF_X);
3627
143
    sappend(s1, s2);
3628
3629
    /*
3630
     * Now allocate a register to hold that value and store
3631
     * it.
3632
     */
3633
143
    s2 = new_stmt(cstate, BPF_ST);
3634
143
    s2->s.k = cstate->off_linkhdr.reg;
3635
143
    sappend(s1, s2);
3636
3637
    /*
3638
     * Now move it into the X register.
3639
     */
3640
143
    s2 = new_stmt(cstate, BPF_MISC|BPF_TAX);
3641
143
    sappend(s1, s2);
3642
3643
143
    return (s1);
3644
143
  } else
3645
11
    return (NULL);
3646
154
}
3647
3648
/*
3649
 * At the moment we treat PPI as normal Radiotap encoded
3650
 * packets. The difference is in the function that generates
3651
 * the code at the beginning to compute the header length.
3652
 * Since this code generator of PPI supports bare 802.11
3653
 * encapsulation only (i.e. the encapsulated DLT should be
3654
 * DLT_IEEE802_11) we generate code to check for this too;
3655
 * that's done in finish_parse().
3656
 */
3657
static struct slist *
3658
gen_load_ppi_llprefixlen(compiler_state_t *cstate)
3659
180
{
3660
180
  struct slist *s1, *s2;
3661
3662
  /*
3663
   * Generate code to load the length of the radiotap header
3664
   * into the register assigned to hold that length, if one has
3665
   * been assigned.
3666
   */
3667
180
  if (cstate->off_linkhdr.reg != -1) {
3668
    /*
3669
     * The 2 bytes at offsets of 2 and 3 from the beginning
3670
     * of the radiotap header are the length of the radiotap
3671
     * header; unfortunately, it's little-endian, so we have
3672
     * to load it a byte at a time and construct the value.
3673
     */
3674
3675
    /*
3676
     * Load the high-order byte, at an offset of 3, shift it
3677
     * left a byte, and put the result in the X register.
3678
     */
3679
155
    s1 = new_stmt(cstate, BPF_LD|BPF_B|BPF_ABS);
3680
155
    s1->s.k = 3;
3681
155
    s2 = new_stmt(cstate, BPF_ALU|BPF_LSH|BPF_K);
3682
155
    sappend(s1, s2);
3683
155
    s2->s.k = 8;
3684
155
    s2 = new_stmt(cstate, BPF_MISC|BPF_TAX);
3685
155
    sappend(s1, s2);
3686
3687
    /*
3688
     * Load the next byte, at an offset of 2, and OR the
3689
     * value from the X register into it.
3690
     */
3691
155
    s2 = new_stmt(cstate, BPF_LD|BPF_B|BPF_ABS);
3692
155
    sappend(s1, s2);
3693
155
    s2->s.k = 2;
3694
155
    s2 = new_stmt(cstate, BPF_ALU|BPF_OR|BPF_X);
3695
155
    sappend(s1, s2);
3696
3697
    /*
3698
     * Now allocate a register to hold that value and store
3699
     * it.
3700
     */
3701
155
    s2 = new_stmt(cstate, BPF_ST);
3702
155
    s2->s.k = cstate->off_linkhdr.reg;
3703
155
    sappend(s1, s2);
3704
3705
    /*
3706
     * Now move it into the X register.
3707
     */
3708
155
    s2 = new_stmt(cstate, BPF_MISC|BPF_TAX);
3709
155
    sappend(s1, s2);
3710
3711
155
    return (s1);
3712
155
  } else
3713
25
    return (NULL);
3714
180
}
3715
3716
/*
3717
 * Load a value relative to the beginning of the link-layer header after the 802.11
3718
 * header, i.e. LLC_SNAP.
3719
 * The link-layer header doesn't necessarily begin at the beginning
3720
 * of the packet data; there might be a variable-length prefix containing
3721
 * radio information.
3722
 */
3723
static struct slist *
3724
gen_load_802_11_header_len(compiler_state_t *cstate, struct slist *s, struct slist *snext)
3725
851
{
3726
851
  struct slist *s2;
3727
851
  struct slist *sjset_data_frame_1;
3728
851
  struct slist *sjset_data_frame_2;
3729
851
  struct slist *sjset_qos;
3730
851
  struct slist *sjset_radiotap_flags_present;
3731
851
  struct slist *sjset_radiotap_ext_present;
3732
851
  struct slist *sjset_radiotap_tsft_present;
3733
851
  struct slist *sjset_tsft_datapad, *sjset_notsft_datapad;
3734
851
  struct slist *s_roundup;
3735
3736
851
  if (cstate->off_linkpl.reg == -1) {
3737
    /*
3738
     * No register has been assigned to the offset of
3739
     * the link-layer payload, which means nobody needs
3740
     * it; don't bother computing it - just return
3741
     * what we already have.
3742
     */
3743
434
    return (s);
3744
434
  }
3745
3746
  /*
3747
   * This code is not compatible with the optimizer, as
3748
   * we are generating jmp instructions within a normal
3749
   * slist of instructions
3750
   */
3751
417
  cstate->no_optimize = 1;
3752
3753
  /*
3754
   * If "s" is non-null, it has code to arrange that the X register
3755
   * contains the length of the prefix preceding the link-layer
3756
   * header.
3757
   *
3758
   * Otherwise, the length of the prefix preceding the link-layer
3759
   * header is "off_outermostlinkhdr.constant_part".
3760
   */
3761
417
  if (s == NULL) {
3762
    /*
3763
     * There is no variable-length header preceding the
3764
     * link-layer header.
3765
     *
3766
     * Load the length of the fixed-length prefix preceding
3767
     * the link-layer header (if any) into the X register,
3768
     * and store it in the cstate->off_linkpl.reg register.
3769
     * That length is off_outermostlinkhdr.constant_part.
3770
     */
3771
117
    s = new_stmt(cstate, BPF_LDX|BPF_IMM);
3772
117
    s->s.k = cstate->off_outermostlinkhdr.constant_part;
3773
117
  }
3774
3775
  /*
3776
   * The X register contains the offset of the beginning of the
3777
   * link-layer header; add 24, which is the minimum length
3778
   * of the MAC header for a data frame, to that, and store it
3779
   * in cstate->off_linkpl.reg, and then load the Frame Control field,
3780
   * which is at the offset in the X register, with an indexed load.
3781
   */
3782
417
  s2 = new_stmt(cstate, BPF_MISC|BPF_TXA);
3783
417
  sappend(s, s2);
3784
417
  s2 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
3785
417
  s2->s.k = 24;
3786
417
  sappend(s, s2);
3787
417
  s2 = new_stmt(cstate, BPF_ST);
3788
417
  s2->s.k = cstate->off_linkpl.reg;
3789
417
  sappend(s, s2);
3790
3791
417
  s2 = new_stmt(cstate, BPF_LD|BPF_IND|BPF_B);
3792
417
  s2->s.k = 0;
3793
417
  sappend(s, s2);
3794
3795
  /*
3796
   * Check the Frame Control field to see if this is a data frame;
3797
   * a data frame has the 0x08 bit (b3) in that field set and the
3798
   * 0x04 bit (b2) clear.
3799
   */
3800
417
  sjset_data_frame_1 = new_stmt(cstate, JMP(BPF_JSET, BPF_K));
3801
417
  sjset_data_frame_1->s.k = IEEE80211_FC0_TYPE_DATA;
3802
417
  sappend(s, sjset_data_frame_1);
3803
3804
  /*
3805
   * If b3 is set, test b2, otherwise go to the first statement of
3806
   * the rest of the program.
3807
   */
3808
417
  sjset_data_frame_1->s.jt = sjset_data_frame_2 = new_stmt(cstate, JMP(BPF_JSET, BPF_K));
3809
417
  sjset_data_frame_2->s.k = IEEE80211_FC0_TYPE_CTL;
3810
417
  sappend(s, sjset_data_frame_2);
3811
417
  sjset_data_frame_1->s.jf = snext;
3812
3813
  /*
3814
   * If b2 is not set, this is a data frame; test the QoS bit.
3815
   * Otherwise, go to the first statement of the rest of the
3816
   * program.
3817
   */
3818
417
  sjset_data_frame_2->s.jt = snext;
3819
417
  sjset_data_frame_2->s.jf = sjset_qos = new_stmt(cstate, JMP(BPF_JSET, BPF_K));
3820
417
  sjset_qos->s.k = IEEE80211_FC0_SUBTYPE_QOS;
3821
417
  sappend(s, sjset_qos);
3822
3823
  /*
3824
   * If it's set, add 2 to cstate->off_linkpl.reg, to skip the QoS
3825
   * field.
3826
   * Otherwise, go to the first statement of the rest of the
3827
   * program.
3828
   */
3829
417
  sjset_qos->s.jt = s2 = new_stmt(cstate, BPF_LD|BPF_MEM);
3830
417
  s2->s.k = cstate->off_linkpl.reg;
3831
417
  sappend(s, s2);
3832
417
  s2 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_IMM);
3833
417
  s2->s.k = 2;
3834
417
  sappend(s, s2);
3835
417
  s2 = new_stmt(cstate, BPF_ST);
3836
417
  s2->s.k = cstate->off_linkpl.reg;
3837
417
  sappend(s, s2);
3838
3839
  /*
3840
   * If we have a radiotap header, look at it to see whether
3841
   * there's Atheros padding between the MAC-layer header
3842
   * and the payload.
3843
   *
3844
   * Note: all of the fields in the radiotap header are
3845
   * little-endian, so we byte-swap all of the values
3846
   * we test against, as they will be loaded as big-endian
3847
   * values.
3848
   *
3849
   * XXX - in the general case, we would have to scan through
3850
   * *all* the presence bits, if there's more than one word of
3851
   * presence bits.  That would require a loop, meaning that
3852
   * we wouldn't be able to run the filter in the kernel.
3853
   *
3854
   * We assume here that the Atheros adapters that insert the
3855
   * annoying padding don't have multiple antennae and therefore
3856
   * do not generate radiotap headers with multiple presence words.
3857
   */
3858
417
  if (cstate->linktype == DLT_IEEE802_11_RADIO) {
3859
    /*
3860
     * Is the IEEE80211_RADIOTAP_FLAGS bit (0x0000002) set
3861
     * in the first presence flag word?
3862
     */
3863
82
    sjset_qos->s.jf = s2 = new_stmt(cstate, BPF_LD|BPF_ABS|BPF_W);
3864
82
    s2->s.k = 4;
3865
82
    sappend(s, s2);
3866
3867
82
    sjset_radiotap_flags_present = new_stmt(cstate, JMP(BPF_JSET, BPF_K));
3868
82
    sjset_radiotap_flags_present->s.k = PCAP_BSWAP_32(0x00000002);
3869
82
    sappend(s, sjset_radiotap_flags_present);
3870
3871
    /*
3872
     * If not, skip all of this.
3873
     */
3874
82
    sjset_radiotap_flags_present->s.jf = snext;
3875
3876
    /*
3877
     * Otherwise, is the "extension" bit set in that word?
3878
     */
3879
82
    sjset_radiotap_ext_present = new_stmt(cstate, JMP(BPF_JSET, BPF_K));
3880
82
    sjset_radiotap_ext_present->s.k = PCAP_BSWAP_32(0x80000000);
3881
82
    sappend(s, sjset_radiotap_ext_present);
3882
82
    sjset_radiotap_flags_present->s.jt = sjset_radiotap_ext_present;
3883
3884
    /*
3885
     * If so, skip all of this.
3886
     */
3887
82
    sjset_radiotap_ext_present->s.jt = snext;
3888
3889
    /*
3890
     * Otherwise, is the IEEE80211_RADIOTAP_TSFT bit set?
3891
     */
3892
82
    sjset_radiotap_tsft_present = new_stmt(cstate, JMP(BPF_JSET, BPF_K));
3893
82
    sjset_radiotap_tsft_present->s.k = PCAP_BSWAP_32(0x00000001);
3894
82
    sappend(s, sjset_radiotap_tsft_present);
3895
82
    sjset_radiotap_ext_present->s.jf = sjset_radiotap_tsft_present;
3896
3897
    /*
3898
     * If IEEE80211_RADIOTAP_TSFT is set, the flags field is
3899
     * at an offset of 16 from the beginning of the raw packet
3900
     * data (8 bytes for the radiotap header and 8 bytes for
3901
     * the TSFT field).
3902
     *
3903
     * Test whether the IEEE80211_RADIOTAP_F_DATAPAD bit (0x20)
3904
     * is set.
3905
     */
3906
82
    s2 = new_stmt(cstate, BPF_LD|BPF_ABS|BPF_B);
3907
82
    s2->s.k = 16;
3908
82
    sappend(s, s2);
3909
82
    sjset_radiotap_tsft_present->s.jt = s2;
3910
3911
82
    sjset_tsft_datapad = new_stmt(cstate, JMP(BPF_JSET, BPF_K));
3912
82
    sjset_tsft_datapad->s.k = 0x20;
3913
82
    sappend(s, sjset_tsft_datapad);
3914
3915
    /*
3916
     * If IEEE80211_RADIOTAP_TSFT is not set, the flags field is
3917
     * at an offset of 8 from the beginning of the raw packet
3918
     * data (8 bytes for the radiotap header).
3919
     *
3920
     * Test whether the IEEE80211_RADIOTAP_F_DATAPAD bit (0x20)
3921
     * is set.
3922
     */
3923
82
    s2 = new_stmt(cstate, BPF_LD|BPF_ABS|BPF_B);
3924
82
    s2->s.k = 8;
3925
82
    sappend(s, s2);
3926
82
    sjset_radiotap_tsft_present->s.jf = s2;
3927
3928
82
    sjset_notsft_datapad = new_stmt(cstate, JMP(BPF_JSET, BPF_K));
3929
82
    sjset_notsft_datapad->s.k = 0x20;
3930
82
    sappend(s, sjset_notsft_datapad);
3931
3932
    /*
3933
     * In either case, if IEEE80211_RADIOTAP_F_DATAPAD is
3934
     * set, round the length of the 802.11 header to
3935
     * a multiple of 4.  Do that by adding 3 and then
3936
     * dividing by and multiplying by 4, which we do by
3937
     * ANDing with ~3.
3938
     */
3939
82
    s_roundup = new_stmt(cstate, BPF_LD|BPF_MEM);
3940
82
    s_roundup->s.k = cstate->off_linkpl.reg;
3941
82
    sappend(s, s_roundup);
3942
82
    s2 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_IMM);
3943
82
    s2->s.k = 3;
3944
82
    sappend(s, s2);
3945
82
    s2 = new_stmt(cstate, BPF_ALU|BPF_AND|BPF_IMM);
3946
82
    s2->s.k = (bpf_u_int32)~3;
3947
82
    sappend(s, s2);
3948
82
    s2 = new_stmt(cstate, BPF_ST);
3949
82
    s2->s.k = cstate->off_linkpl.reg;
3950
82
    sappend(s, s2);
3951
3952
82
    sjset_tsft_datapad->s.jt = s_roundup;
3953
82
    sjset_tsft_datapad->s.jf = snext;
3954
82
    sjset_notsft_datapad->s.jt = s_roundup;
3955
82
    sjset_notsft_datapad->s.jf = snext;
3956
82
  } else
3957
335
    sjset_qos->s.jf = snext;
3958
3959
417
  return s;
3960
851
}
3961
3962
static void
3963
insert_compute_vloffsets(compiler_state_t *cstate, struct block *b)
3964
6.44k
{
3965
6.44k
  struct slist *s;
3966
3967
  /* There is an implicit dependency between the link
3968
   * payload and link header since the payload computation
3969
   * includes the variable part of the header. Therefore,
3970
   * if nobody else has allocated a register for the link
3971
   * header and we need it, do it now. */
3972
6.44k
  if (cstate->off_linkpl.reg != -1 && cstate->off_linkhdr.is_variable &&
3973
434
      cstate->off_linkhdr.reg == -1)
3974
16
    cstate->off_linkhdr.reg = alloc_reg(cstate);
3975
3976
  /*
3977
   * For link-layer types that have a variable-length header
3978
   * preceding the link-layer header, generate code to load
3979
   * the offset of the link-layer header into the register
3980
   * assigned to that offset, if any.
3981
   *
3982
   * XXX - this, and the next switch statement, won't handle
3983
   * encapsulation of 802.11 or 802.11+radio information in
3984
   * some other protocol stack.  That's significantly more
3985
   * complicated.
3986
   */
3987
6.44k
  switch (cstate->outermostlinktype) {
3988
3989
243
  case DLT_PRISM_HEADER:
3990
243
    s = gen_load_prism_llprefixlen(cstate);
3991
243
    break;
3992
3993
105
  case DLT_IEEE802_11_RADIO_AVS:
3994
105
    s = gen_load_avs_llprefixlen(cstate);
3995
105
    break;
3996
3997
154
  case DLT_IEEE802_11_RADIO:
3998
154
    s = gen_load_radiotap_llprefixlen(cstate);
3999
154
    break;
4000
4001
180
  case DLT_PPI:
4002
180
    s = gen_load_ppi_llprefixlen(cstate);
4003
180
    break;
4004
4005
5.76k
  default:
4006
5.76k
    s = NULL;
4007
5.76k
    break;
4008
6.44k
  }
4009
4010
  /*
4011
   * For link-layer types that have a variable-length link-layer
4012
   * header, generate code to load the offset of the link-layer
4013
   * payload into the register assigned to that offset, if any.
4014
   */
4015
6.44k
  switch (cstate->outermostlinktype) {
4016
4017
169
  case DLT_IEEE802_11:
4018
412
  case DLT_PRISM_HEADER:
4019
517
  case DLT_IEEE802_11_RADIO_AVS:
4020
671
  case DLT_IEEE802_11_RADIO:
4021
851
  case DLT_PPI:
4022
851
    s = gen_load_802_11_header_len(cstate, s, b->stmts);
4023
    /*
4024
     * After this call s may have changed, b->stmts has not
4025
     * changed, s and b->stmts have not merged into one linked
4026
     * list, therefore the meaning of b, whether a Boolean constant
4027
     * or not, has not changed.
4028
     */
4029
851
    break;
4030
4031
284
  case DLT_PFLOG:
4032
284
    s = gen_load_pflog_llprefixlen(cstate);
4033
284
    break;
4034
6.44k
  }
4035
4036
  /*
4037
   * If there is no initialization yet and we need variable
4038
   * length offsets for VLAN, initialize them to zero
4039
   */
4040
6.44k
  if (s == NULL && cstate->is_vlan_vloffset) {
4041
0
    struct slist *s2;
4042
4043
0
    if (cstate->off_linkpl.reg == -1)
4044
0
      cstate->off_linkpl.reg = alloc_reg(cstate);
4045
0
    if (cstate->off_linktype.reg == -1)
4046
0
      cstate->off_linktype.reg = alloc_reg(cstate);
4047
4048
0
    s = new_stmt(cstate, BPF_LD|BPF_W|BPF_IMM);
4049
0
    s->s.k = 0;
4050
0
    s2 = new_stmt(cstate, BPF_ST);
4051
0
    s2->s.k = cstate->off_linkpl.reg;
4052
0
    sappend(s, s2);
4053
0
    s2 = new_stmt(cstate, BPF_ST);
4054
0
    s2->s.k = cstate->off_linktype.reg;
4055
0
    sappend(s, s2);
4056
0
  }
4057
4058
  /*
4059
   * If we have any offset-loading code, append all the
4060
   * existing statements in the block to those statements,
4061
   * and make the resulting list the list of statements
4062
   * for the block.
4063
   */
4064
6.44k
  sprepend_to_block(s, b);
4065
6.44k
}
4066
4067
/*
4068
 * Take an absolute offset, and:
4069
 *
4070
 *    if it has no variable part, return NULL;
4071
 *
4072
 *    if it has a variable part, generate code to load the register
4073
 *    containing that variable part into the X register, returning
4074
 *    a pointer to that code - if no register for that offset has
4075
 *    been allocated, allocate it first.
4076
 *
4077
 * (The code to set that register will be generated later, but will
4078
 * be placed earlier in the code sequence.)
4079
 */
4080
static struct slist *
4081
gen_abs_offset_varpart(compiler_state_t *cstate, bpf_abs_offset *off)
4082
234k
{
4083
234k
  struct slist *s;
4084
4085
234k
  if (off->is_variable) {
4086
52.3k
    if (off->reg == -1) {
4087
      /*
4088
       * We haven't yet assigned a register for the
4089
       * variable part of the offset of the link-layer
4090
       * header; allocate one.
4091
       */
4092
1.68k
      off->reg = alloc_reg(cstate);
4093
1.68k
    }
4094
4095
    /*
4096
     * Load the register containing the variable part of the
4097
     * offset of the link-layer header into the X register.
4098
     */
4099
52.3k
    s = new_stmt(cstate, BPF_LDX|BPF_MEM);
4100
52.3k
    s->s.k = off->reg;
4101
52.3k
    return s;
4102
181k
  } else {
4103
    /*
4104
     * That offset isn't variable, there's no variable part,
4105
     * so we don't need to generate any code.
4106
     */
4107
181k
    return NULL;
4108
181k
  }
4109
234k
}
4110
4111
/*
4112
 * Map an Ethernet type to the equivalent PPP type.
4113
 */
4114
static uint16_t
4115
ethertype_to_ppptype(compiler_state_t *cstate, bpf_u_int32 ll_proto)
4116
6.11k
{
4117
6.11k
  switch (ll_proto) {
4118
4119
647
  case ETHERTYPE_IP:
4120
647
    return PPP_IP;
4121
4122
833
  case ETHERTYPE_IPV6:
4123
833
    return PPP_IPV6;
4124
4125
189
  case ETHERTYPE_DN:
4126
189
    return PPP_DECNET;
4127
4128
69
  case ETHERTYPE_ATALK:
4129
69
    return PPP_APPLE;
4130
4131
20
  case ETHERTYPE_NS:
4132
20
    return PPP_NS;
4133
4134
1.22k
  case LLCSAP_ISONS:
4135
1.22k
    return PPP_OSI;
4136
4137
135
  case LLCSAP_8021D:
4138
    /*
4139
     * I'm assuming the "Bridging PDU"s that go
4140
     * over PPP are Spanning Tree Protocol
4141
     * Bridging PDUs.
4142
     */
4143
135
    return PPP_BRPDU;
4144
4145
176
  case LLCSAP_IPX:
4146
176
    return PPP_IPX;
4147
6.11k
  }
4148
2.82k
  assert_maxval(cstate, "PPP protocol", ll_proto, UINT16_MAX);
4149
2.82k
  return (uint16_t)ll_proto;
4150
6.11k
}
4151
4152
/*
4153
 * Generate any tests that, for encapsulation of a link-layer packet
4154
 * inside another protocol stack, need to be done to check for those
4155
 * link-layer packets (and that haven't already been done by a check
4156
 * for that encapsulation).
4157
 */
4158
static struct block *
4159
gen_prevlinkhdr_check(compiler_state_t *cstate)
4160
7.50k
{
4161
7.50k
  if (cstate->is_encap)
4162
35
    return gen_encap_ll_check(cstate);
4163
4164
7.47k
  switch (cstate->prevlinktype) {
4165
4166
1.42k
  case DLT_SUNATM:
4167
    /*
4168
     * This is LANE-encapsulated Ethernet; check that the LANE
4169
     * packet doesn't begin with an LE Control marker, i.e.
4170
     * that it's data, not a control message.
4171
     *
4172
     * (We've already generated a test for LANE.)
4173
     */
4174
1.42k
    return gen_cmp_ne(cstate, OR_PREVLINKHDR, SUNATM_PKT_BEGIN_POS, BPF_H, 0xFF00);
4175
4176
6.04k
  default:
4177
    /*
4178
     * No such tests are necessary.
4179
     */
4180
6.04k
    return NULL;
4181
7.47k
  }
4182
  /*NOTREACHED*/
4183
7.47k
}
4184
4185
// Match the specified version number in the Internet Protocol header.
4186
static struct block *
4187
gen_ip_version(compiler_state_t *cstate, const enum e_offrel offrel,
4188
    const uint8_t ver)
4189
1.36k
{
4190
1.36k
  switch (ver) {
4191
798
  case 4:
4192
1.36k
  case 6:
4193
1.36k
    return gen_mcmp(cstate, offrel, 0, BPF_B, ver << 4, 0xf0);
4194
0
  default:
4195
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "ver", ver);
4196
1.36k
  }
4197
1.36k
}
4198
4199
/*
4200
 * Match a Frame Relay (ITU-T Rec. Q.922) header with the Control field set to
4201
 * UI (Unnumbered information, 0x03, ibid., Table 3) and the NLPID field set to
4202
 * the given value.
4203
 *
4204
 * This code assumes a Frame Relay header encoding that has the Control field
4205
 * at offset 2 and the NLPID field at offset 3, which means no flags before the
4206
 * Address field (thus not the RFC 2427 encoding) and exactly 2 bytes for the
4207
 * Address field (thus the default, but not the only possible address format,
4208
 * ibid., Table 1).
4209
 */
4210
static struct block *
4211
gen_frelay_nlpid(compiler_state_t *cstate, const uint8_t nlpid)
4212
819
{
4213
819
  return gen_cmp(cstate, OR_LINKHDR, 2, BPF_H, (0x03 << 8) | nlpid);
4214
819
}
4215
4216
/*
4217
 * Generate code to match a particular packet type by matching the
4218
 * link-layer type field or fields in the 802.2 LLC header.
4219
 *
4220
 * "proto" is an Ethernet type value, if > ETHERMTU, or an LLC SAP
4221
 * value, if <= ETHERMTU.
4222
 */
4223
static struct block *
4224
gen_linktype(compiler_state_t *cstate, bpf_u_int32 ll_proto)
4225
57.7k
{
4226
57.7k
  struct block *b0, *b1, *b2;
4227
4228
  /* are we checking MPLS-encapsulated packets? */
4229
57.7k
  if (cstate->label_stack_depth > 0)
4230
847
    return gen_mpls_linktype(cstate, ll_proto);
4231
4232
56.9k
  switch (cstate->linktype) {
4233
4234
4.97k
  case DLT_EN10MB:
4235
5.77k
  case DLT_NETANALYZER:
4236
6.60k
  case DLT_NETANALYZER_TRANSPARENT:
4237
7.13k
  case DLT_DSA_TAG_BRCM:
4238
7.64k
  case DLT_DSA_TAG_DSA:
4239
    /* Geneve has an EtherType regardless of whether there is an
4240
     * L2 header. VXLAN always has an EtherType. */
4241
7.64k
    if (!cstate->is_encap)
4242
6.93k
      b0 = gen_prevlinkhdr_check(cstate);
4243
709
    else
4244
709
      b0 = NULL;
4245
4246
7.64k
    b1 = gen_ether_linktype(cstate, ll_proto);
4247
7.64k
    return b0 ? gen_and(b0, b1) : b1;
4248
    /*NOTREACHED*/
4249
4250
521
  case DLT_C_HDLC:
4251
1.08k
  case DLT_HDLC:
4252
1.08k
    assert_maxval(cstate, "HDLC protocol", ll_proto, UINT16_MAX);
4253
1.08k
    switch (ll_proto) {
4254
4255
18
    case LLCSAP_ISONS:
4256
18
      ll_proto = (ll_proto << 8 | LLCSAP_ISONS);
4257
      /* fall through */
4258
4259
1.06k
    default:
4260
1.06k
      return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, ll_proto);
4261
      /*NOTREACHED*/
4262
1.08k
    }
4263
4264
2.16k
  case DLT_IEEE802_11:
4265
3.11k
  case DLT_PRISM_HEADER:
4266
4.17k
  case DLT_IEEE802_11_RADIO_AVS:
4267
5.65k
  case DLT_IEEE802_11_RADIO:
4268
6.79k
  case DLT_PPI:
4269
    /*
4270
     * Check that we have a data frame.
4271
     */
4272
6.79k
    b0 = gen_mcmp(cstate, OR_LINKHDR, 0, BPF_B,
4273
6.79k
      IEEE80211_FC0_TYPE_DATA,
4274
6.79k
      IEEE80211_FC0_TYPE_MASK);
4275
4276
    /*
4277
     * Now check for the specified link-layer type.
4278
     */
4279
6.79k
    b1 = gen_llc_linktype(cstate, ll_proto);
4280
6.79k
    return gen_and(b0, b1);
4281
    /*NOTREACHED*/
4282
4283
610
  case DLT_FDDI:
4284
    /*
4285
     * XXX - check for LLC frames.
4286
     */
4287
610
    return gen_llc_linktype(cstate, ll_proto);
4288
    /*NOTREACHED*/
4289
4290
547
  case DLT_IEEE802:
4291
    /*
4292
     * XXX - check for LLC PDUs, as per IEEE 802.5.
4293
     */
4294
547
    return gen_llc_linktype(cstate, ll_proto);
4295
    /*NOTREACHED*/
4296
4297
884
  case DLT_ATM_RFC1483:
4298
1.24k
  case DLT_ATM_CLIP:
4299
1.64k
  case DLT_IP_OVER_FC:
4300
1.64k
    return gen_llc_linktype(cstate, ll_proto);
4301
    /*NOTREACHED*/
4302
4303
1.10k
  case DLT_SUNATM:
4304
    /*
4305
     * Check for an LLC-encapsulated version of this protocol;
4306
     * if we were checking for LANE, linktype would no longer
4307
     * be DLT_SUNATM.
4308
     *
4309
     * Check for LLC encapsulation and then check the protocol.
4310
     */
4311
1.10k
    b0 = gen_atm_prototype(cstate, PT_LLC);
4312
1.10k
    b1 = gen_llc_linktype(cstate, ll_proto);
4313
1.10k
    return gen_and(b0, b1);
4314
    /*NOTREACHED*/
4315
4316
1.58k
  case DLT_LINUX_SLL:
4317
1.58k
    return gen_linux_sll_linktype(cstate, ll_proto);
4318
    /*NOTREACHED*/
4319
4320
388
  case DLT_SLIP:
4321
883
  case DLT_SLIP_BSDOS:
4322
1.50k
  case DLT_RAW:
4323
    /*
4324
     * These types don't provide any type field; packets
4325
     * are always IPv4 or IPv6.  Hence in this context the
4326
     * to-be-confirmed IPv4/IPv6 header begins at the link-layer
4327
     * header.
4328
     */
4329
1.50k
    switch (ll_proto) {
4330
4331
351
    case ETHERTYPE_IP:
4332
351
      return gen_ip_version(cstate, OR_LINKHDR, 4);
4333
4334
232
    case ETHERTYPE_IPV6:
4335
232
      return gen_ip_version(cstate, OR_LINKHDR, 6);
4336
4337
917
    default:
4338
917
      return gen_false(cstate); /* always false */
4339
1.50k
    }
4340
    /*NOTREACHED*/
4341
4342
2.00k
  case DLT_IPV4:
4343
    /*
4344
     * Raw IPv4, so no type field.
4345
     */
4346
2.00k
    if (ll_proto == ETHERTYPE_IP)
4347
871
      return gen_true(cstate);  /* always true */
4348
4349
    /* Checking for something other than IPv4; always false */
4350
1.13k
    return gen_false(cstate);
4351
    /*NOTREACHED*/
4352
4353
1.64k
  case DLT_IPV6:
4354
    /*
4355
     * Raw IPv6, so no type field.
4356
     */
4357
1.64k
    if (ll_proto == ETHERTYPE_IPV6)
4358
520
      return gen_true(cstate);  /* always true */
4359
4360
    /* Checking for something other than IPv6; always false */
4361
1.12k
    return gen_false(cstate);
4362
    /*NOTREACHED*/
4363
4364
1.12k
  case DLT_PPP:
4365
1.56k
  case DLT_PPP_PPPD:
4366
2.68k
  case DLT_PPP_SERIAL:
4367
3.18k
  case DLT_PPP_ETHER:
4368
    /*
4369
     * We use Ethernet protocol types inside libpcap;
4370
     * map them to the corresponding PPP protocol types.
4371
     */
4372
3.18k
    return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H,
4373
3.18k
        ethertype_to_ppptype(cstate, ll_proto));
4374
    /*NOTREACHED*/
4375
4376
4.64k
  case DLT_PPP_BSDOS:
4377
    /*
4378
     * We use Ethernet protocol types inside libpcap;
4379
     * map them to the corresponding PPP protocol types.
4380
     */
4381
4.64k
    switch (ll_proto) {
4382
4383
1.70k
    case ETHERTYPE_IP:
4384
      /*
4385
       * Also check for Van Jacobson-compressed IP.
4386
       * XXX - do this for other forms of PPP?
4387
       */
4388
1.70k
      b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, PPP_IP);
4389
1.70k
      b1 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, PPP_VJC);
4390
1.70k
      b1 = gen_or(b0, b1);
4391
1.70k
      b0 = gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, PPP_VJNC);
4392
1.70k
      return gen_or(b1, b0);
4393
4394
2.93k
    default:
4395
2.93k
      return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H,
4396
2.93k
          ethertype_to_ppptype(cstate, ll_proto));
4397
4.64k
    }
4398
    /*NOTREACHED*/
4399
4400
7.18k
  case DLT_NULL:
4401
7.60k
  case DLT_LOOP:
4402
7.88k
  case DLT_ENC:
4403
    /*
4404
     * 4-byte AF_ value at the beginning of the packet.
4405
     */
4406
7.88k
    return (gen_loopback_linktype(cstate, ll_proto));
4407
4408
2.41k
  case DLT_PFLOG:
4409
    /*
4410
     * 1-byte AF_ value.
4411
     */
4412
2.41k
    return (gen_pflog_linktype(cstate, ll_proto));
4413
4414
1.03k
  case DLT_ARCNET:
4415
1.74k
  case DLT_ARCNET_LINUX:
4416
    /*
4417
     * In ARCnet header the 8-bit SC (System Code) field identifies
4418
     * the higher-level protocol in the INFO (Information) part of
4419
     * the packet, same as the 16-bit EtherType > 1500 in Ethernet.
4420
     * RFC 1051 (March 1988) allocated ARCTYPE_IP_OLD to IPv4 and
4421
     * ARCTYPE_ARP_OLD to ARP, RFC 1201 (February 1991) allocated
4422
     * ARCTYPE_IP to IPv4 and ARCTYPE_ARP to ARP.  ARCnet header
4423
     * encoding and length differ between the two specifications.
4424
     *
4425
     * This DLT case previously matched IPv4 and ARP by ORing, for
4426
     * backward compatibility reasons, respective SCs from RFC 1051
4427
     * and RFC 1201.  This worked as expected when a filter program
4428
     * tested SC to tell whether a packet is an IPv4/ARP packet,
4429
     * but did not access INFO (where the IPv4 or ARP header is).
4430
     *
4431
     * However, for filter expressions that need to access INFO the
4432
     * C code that processes IPv4/ARP header fields generates
4433
     * exactly one match and uses the DLT's off_linkpl, which
4434
     * init_linktype() initializes to RFC 1201 encoding, so
4435
     * combining that with an RFC 1051 SC match produced incorrect
4436
     * filter programs.  This is why this DLT case in the current
4437
     * implementation matches RFC 1201 SCs only.
4438
     *
4439
     * XXX should we check for first fragment if the protocol
4440
     * uses PHDS?
4441
     */
4442
1.74k
    switch (ll_proto) {
4443
4444
556
    default:
4445
556
      return gen_false(cstate);
4446
4447
182
    case ETHERTYPE_IPV6:
4448
182
      return (gen_cmp(cstate, OR_LINKTYPE, 0, BPF_B,
4449
182
        ARCTYPE_INET6));
4450
4451
421
    case ETHERTYPE_IP:
4452
421
      return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_B,
4453
421
          ARCTYPE_IP);
4454
4455
277
    case ETHERTYPE_ARP:
4456
277
      return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_B,
4457
277
          ARCTYPE_ARP);
4458
4459
271
    case ETHERTYPE_REVARP:
4460
271
      return (gen_cmp(cstate, OR_LINKTYPE, 0, BPF_B,
4461
271
          ARCTYPE_REVARP));
4462
4463
34
    case ETHERTYPE_ATALK:
4464
34
      return (gen_cmp(cstate, OR_LINKTYPE, 0, BPF_B,
4465
34
          ARCTYPE_ATALK));
4466
1.74k
    }
4467
    /*NOTREACHED*/
4468
4469
1.91k
  case DLT_LTALK:
4470
1.91k
    switch (ll_proto) {
4471
36
    case ETHERTYPE_ATALK:
4472
36
      return gen_true(cstate);
4473
1.87k
    default:
4474
1.87k
      return gen_false(cstate);
4475
1.91k
    }
4476
    /*NOTREACHED*/
4477
4478
1.01k
  case DLT_FRELAY:
4479
1.01k
    switch (ll_proto) {
4480
4481
349
    case ETHERTYPE_IP:
4482
349
      return gen_frelay_nlpid(cstate, ISO9577_IPV4);
4483
4484
165
    case ETHERTYPE_IPV6:
4485
165
      return gen_frelay_nlpid(cstate, ISO9577_IPV6);
4486
4487
18
    case LLCSAP_ISONS:
4488
      /*
4489
       * Check for several OSI protocols.
4490
       *
4491
       * Frame Relay packets typically have an OSI
4492
       * NLPID at the beginning; we check for each
4493
       * of them.
4494
       */
4495
18
      b0 = gen_frelay_nlpid(cstate, ISO8473_CLNP);
4496
18
      b1 = gen_frelay_nlpid(cstate, ISO9542_ESIS);
4497
18
      b2 = gen_frelay_nlpid(cstate, ISO10589_ISIS);
4498
18
      b2 = gen_or(b1, b2);
4499
18
      return gen_or(b0, b2);
4500
4501
478
    default:
4502
478
      return gen_false(cstate);
4503
1.01k
    }
4504
    /*NOTREACHED*/
4505
4506
1
  case DLT_MFR:
4507
1
    break; // not implemented
4508
4509
241
  case DLT_JUNIPER_MFR:
4510
527
  case DLT_JUNIPER_MLFR:
4511
808
  case DLT_JUNIPER_MLPPP:
4512
1.02k
  case DLT_JUNIPER_ATM1:
4513
1.24k
  case DLT_JUNIPER_ATM2:
4514
1.49k
  case DLT_JUNIPER_PPPOE:
4515
1.70k
  case DLT_JUNIPER_PPPOE_ATM:
4516
2.13k
  case DLT_JUNIPER_GGSN:
4517
2.43k
  case DLT_JUNIPER_ES:
4518
2.67k
  case DLT_JUNIPER_MONITOR:
4519
2.96k
  case DLT_JUNIPER_SERVICES:
4520
3.21k
  case DLT_JUNIPER_ETHER:
4521
3.50k
  case DLT_JUNIPER_PPP:
4522
3.72k
  case DLT_JUNIPER_FRELAY:
4523
4.13k
  case DLT_JUNIPER_CHDLC:
4524
4.48k
  case DLT_JUNIPER_VP:
4525
4.90k
  case DLT_JUNIPER_ST:
4526
5.24k
  case DLT_JUNIPER_ISM:
4527
5.46k
  case DLT_JUNIPER_VS:
4528
5.96k
  case DLT_JUNIPER_SRX_E2E:
4529
6.24k
  case DLT_JUNIPER_FIBRECHANNEL:
4530
6.53k
  case DLT_JUNIPER_ATM_CEMIC:
4531
4532
    /* just lets verify the magic number for now -
4533
     * on ATM we may have up to 6 different encapsulations on the wire
4534
     * and need a lot of heuristics to figure out that the payload
4535
     * might be;
4536
     *
4537
     * FIXME encapsulation specific BPF_ filters
4538
     */
4539
6.53k
    return gen_mcmp(cstate, OR_LINKHDR, 0, BPF_W, 0x4d474300, 0xffffff00); /* compare the magic number */
4540
4541
738
  case DLT_IPNET:
4542
738
    return gen_ipnet_linktype(cstate, ll_proto);
4543
4544
712
  default:
4545
    /*
4546
     * Does this link-layer header type have a field
4547
     * indicating the type of the next protocol?  If
4548
     * so, off_linktype.constant_part will be the offset of that
4549
     * field in the packet; if not, it will be OFFSET_NOT_SET.
4550
     */
4551
712
    if (cstate->off_linktype.constant_part != OFFSET_NOT_SET) {
4552
      /*
4553
       * Yes; assume it's an Ethernet type.  (If
4554
       * it's not, it needs to be handled specially
4555
       * above.)
4556
       */
4557
663
      assert_maxval(cstate, "EtherType", ll_proto, UINT16_MAX);
4558
663
      return gen_cmp(cstate, OR_LINKTYPE, 0, BPF_H, ll_proto);
4559
      /*NOTREACHED */
4560
663
    }
4561
56.9k
  }
4562
  /*
4563
   * For example, using the fixed-size NFLOG header it is possible
4564
   * to tell only the address family of the packet, other meaningful
4565
   * data is either missing or behind TLVs.
4566
   */
4567
50
  bpf_error(cstate, "link-layer protocol filtering not implemented for %s",
4568
50
      pcapint_datalink_val_to_string(cstate->linktype));
4569
56.9k
}
4570
4571
/*
4572
 * Check for an LLC SNAP packet with a given organization code and
4573
 * protocol type; we check the entire contents of the 802.2 LLC and
4574
 * snap headers, checking for DSAP and SSAP of SNAP and a control
4575
 * field of 0x03 in the LLC header, and for the specified organization
4576
 * code and protocol type in the SNAP header.
4577
 */
4578
static struct block *
4579
gen_snap(compiler_state_t *cstate, bpf_u_int32 orgcode, bpf_u_int32 ptype)
4580
428
{
4581
428
  u_char snapblock[8];
4582
4583
428
  snapblock[0] = LLCSAP_SNAP;   /* DSAP = SNAP */
4584
428
  snapblock[1] = LLCSAP_SNAP;   /* SSAP = SNAP */
4585
428
  snapblock[2] = 0x03;      /* control = UI */
4586
428
  snapblock[3] = (u_char)(orgcode >> 16); /* upper 8 bits of organization code */
4587
428
  snapblock[4] = (u_char)(orgcode >> 8);  /* middle 8 bits of organization code */
4588
428
  snapblock[5] = (u_char)(orgcode >> 0);  /* lower 8 bits of organization code */
4589
428
  snapblock[6] = (u_char)(ptype >> 8);  /* upper 8 bits of protocol type */
4590
428
  snapblock[7] = (u_char)(ptype >> 0);  /* lower 8 bits of protocol type */
4591
428
  return gen_bcmp(cstate, OR_LLC, 0, 8, snapblock);
4592
428
}
4593
4594
/*
4595
 * Generate code to match frames with an LLC header.
4596
 */
4597
static struct block *
4598
gen_llc_internal(compiler_state_t *cstate)
4599
1.29k
{
4600
1.29k
  struct block *b0, *b1;
4601
4602
1.29k
  switch (cstate->linktype) {
4603
4604
203
  case DLT_EN10MB:
4605
274
  case DLT_DSA_TAG_BRCM:
4606
343
  case DLT_DSA_TAG_DSA:
4607
    /*
4608
     * We check for an Ethernet type field less or equal than
4609
     * 1500, which means it's an 802.3 length field.
4610
     */
4611
343
    b0 = gen_cmp_le(cstate, OR_LINKTYPE, 0, BPF_H, ETHERMTU);
4612
4613
    /*
4614
     * Now check for the purported DSAP and SSAP not being
4615
     * 0xFF, to rule out NetWare-over-802.3.
4616
     */
4617
343
    b1 = gen_cmp_ne(cstate, OR_LLC, 0, BPF_H, 0xFFFF);
4618
4619
343
    return gen_and(b0, b1);
4620
4621
76
  case DLT_SUNATM:
4622
    /*
4623
     * We check for LLC traffic.
4624
     */
4625
76
    return gen_atmtype_llc(cstate);
4626
4627
140
  case DLT_IEEE802: /* Token Ring */
4628
    /*
4629
     * XXX - check for LLC frames.
4630
     */
4631
140
    return gen_true(cstate);
4632
4633
132
  case DLT_FDDI:
4634
    /*
4635
     * XXX - check for LLC frames.
4636
     */
4637
132
    return gen_true(cstate);
4638
4639
115
  case DLT_ATM_RFC1483:
4640
    /*
4641
     * For LLC encapsulation, these are defined to have an
4642
     * 802.2 LLC header.
4643
     *
4644
     * For VC encapsulation, they don't, but there's no
4645
     * way to check for that; the protocol used on the VC
4646
     * is negotiated out of band.
4647
     */
4648
115
    return gen_true(cstate);
4649
4650
110
  case DLT_IEEE802_11:
4651
207
  case DLT_PRISM_HEADER:
4652
313
  case DLT_IEEE802_11_RADIO:
4653
380
  case DLT_IEEE802_11_RADIO_AVS:
4654
470
  case DLT_PPI:
4655
    /*
4656
     * Check that we have a data frame.
4657
     */
4658
470
    return gen_mcmp(cstate, OR_LINKHDR, 0, BPF_B,
4659
470
      IEEE80211_FC0_TYPE_DATA,
4660
470
      IEEE80211_FC0_TYPE_MASK);
4661
4662
17
  default:
4663
17
    fail_kw_on_dlt(cstate, "llc");
4664
    /*NOTREACHED*/
4665
1.29k
  }
4666
1.29k
}
4667
4668
struct block *
4669
gen_llc(compiler_state_t *cstate)
4670
799
{
4671
  /*
4672
   * Catch errors reported by us and routines below us, and return NULL
4673
   * on an error.
4674
   */
4675
799
  if (setjmp(cstate->top_ctx))
4676
9
    return (NULL);
4677
4678
790
  return gen_llc_internal(cstate);
4679
799
}
4680
4681
struct block *
4682
gen_llc_i(compiler_state_t *cstate)
4683
108
{
4684
108
  struct block *b0, *b1;
4685
108
  struct slist *s;
4686
4687
  /*
4688
   * Catch errors reported by us and routines below us, and return NULL
4689
   * on an error.
4690
   */
4691
108
  if (setjmp(cstate->top_ctx))
4692
1
    return (NULL);
4693
4694
  /*
4695
   * Check whether this is an LLC frame.
4696
   */
4697
107
  b0 = gen_llc_internal(cstate);
4698
4699
  /*
4700
   * Load the control byte and test the low-order bit; it must
4701
   * be clear for I frames.
4702
   */
4703
107
  s = gen_load_a(cstate, OR_LLC, 2, BPF_B);
4704
107
  b1 = gen_unset(cstate, 0x01, s);
4705
4706
107
  return gen_and(b0, b1);
4707
108
}
4708
4709
struct block *
4710
gen_llc_s(compiler_state_t *cstate)
4711
71
{
4712
71
  struct block *b0, *b1;
4713
4714
  /*
4715
   * Catch errors reported by us and routines below us, and return NULL
4716
   * on an error.
4717
   */
4718
71
  if (setjmp(cstate->top_ctx))
4719
1
    return (NULL);
4720
4721
  /*
4722
   * Check whether this is an LLC frame.
4723
   */
4724
70
  b0 = gen_llc_internal(cstate);
4725
4726
  /*
4727
   * Now compare the low-order 2 bit of the control byte against
4728
   * the appropriate value for S frames.
4729
   */
4730
70
  b1 = gen_mcmp(cstate, OR_LLC, 2, BPF_B, LLC_S_FMT, 0x03);
4731
4732
70
  return gen_and(b0, b1);
4733
71
}
4734
4735
struct block *
4736
gen_llc_u(compiler_state_t *cstate)
4737
122
{
4738
122
  struct block *b0, *b1;
4739
4740
  /*
4741
   * Catch errors reported by us and routines below us, and return NULL
4742
   * on an error.
4743
   */
4744
122
  if (setjmp(cstate->top_ctx))
4745
1
    return (NULL);
4746
4747
  /*
4748
   * Check whether this is an LLC frame.
4749
   */
4750
121
  b0 = gen_llc_internal(cstate);
4751
4752
  /*
4753
   * Now compare the low-order 2 bit of the control byte against
4754
   * the appropriate value for U frames.
4755
   */
4756
121
  b1 = gen_mcmp(cstate, OR_LLC, 2, BPF_B, LLC_U_FMT, 0x03);
4757
4758
121
  return gen_and(b0, b1);
4759
122
}
4760
4761
struct block *
4762
gen_llc_s_subtype(compiler_state_t *cstate, bpf_u_int32 subtype)
4763
75
{
4764
75
  struct block *b0, *b1;
4765
4766
  /*
4767
   * Catch errors reported by us and routines below us, and return NULL
4768
   * on an error.
4769
   */
4770
75
  if (setjmp(cstate->top_ctx))
4771
2
    return (NULL);
4772
4773
  /*
4774
   * Check whether this is an LLC frame.
4775
   */
4776
73
  b0 = gen_llc_internal(cstate);
4777
4778
  /*
4779
   * Now check for an S frame with the appropriate type.
4780
   */
4781
73
  b1 = gen_mcmp(cstate, OR_LLC, 2, BPF_B, subtype, LLC_S_CMD_MASK);
4782
4783
73
  return gen_and(b0, b1);
4784
75
}
4785
4786
struct block *
4787
gen_llc_u_subtype(compiler_state_t *cstate, bpf_u_int32 subtype)
4788
118
{
4789
118
  struct block *b0, *b1;
4790
4791
  /*
4792
   * Catch errors reported by us and routines below us, and return NULL
4793
   * on an error.
4794
   */
4795
118
  if (setjmp(cstate->top_ctx))
4796
3
    return (NULL);
4797
4798
  /*
4799
   * Check whether this is an LLC frame.
4800
   */
4801
115
  b0 = gen_llc_internal(cstate);
4802
4803
  /*
4804
   * Now check for a U frame with the appropriate type.
4805
   */
4806
115
  b1 = gen_mcmp(cstate, OR_LLC, 2, BPF_B, subtype, LLC_U_CMD_MASK);
4807
4808
115
  return gen_and(b0, b1);
4809
118
}
4810
4811
/*
4812
 * Generate code to match a particular packet type, for link-layer types
4813
 * using 802.2 LLC headers.
4814
 *
4815
 * This is *NOT* used for Ethernet; "gen_ether_linktype()" is used
4816
 * for that - it handles the D/I/X Ethernet vs. 802.3+802.2 issues.
4817
 *
4818
 * "proto" is an Ethernet type value, if > ETHERMTU, or an LLC SAP
4819
 * value, if <= ETHERMTU.  We use that to determine whether to
4820
 * match the DSAP or both DSAP and LSAP or to check the OUI and
4821
 * protocol ID in a SNAP header.
4822
 */
4823
static struct block *
4824
gen_llc_linktype(compiler_state_t *cstate, bpf_u_int32 ll_proto)
4825
10.7k
{
4826
  /*
4827
   * XXX - handle token-ring variable-length header.
4828
   */
4829
10.7k
  switch (ll_proto) {
4830
4831
74
  case LLCSAP_IP:
4832
3.71k
  case LLCSAP_ISONS:
4833
3.77k
  case LLCSAP_NETBEUI:
4834
    /*
4835
     * XXX - should we check both the DSAP and the
4836
     * SSAP, like this, or should we check just the
4837
     * DSAP, as we do for other SAP values?
4838
     */
4839
3.77k
    return gen_cmp(cstate, OR_LLC, 0, BPF_H, (bpf_u_int32)
4840
3.77k
           ((ll_proto << 8) | ll_proto));
4841
4842
78
  case LLCSAP_IPX:
4843
    /*
4844
     * XXX - are there ever SNAP frames for IPX on
4845
     * non-Ethernet 802.x networks?
4846
     */
4847
78
    return gen_cmp(cstate, OR_LLC, 0, BPF_B, LLCSAP_IPX);
4848
4849
61
  case ETHERTYPE_ATALK:
4850
    /*
4851
     * 802.2-encapsulated ETHERTYPE_ATALK packets are
4852
     * SNAP packets with an organization code of
4853
     * 0x080007 (Apple, for Appletalk) and a protocol
4854
     * type of ETHERTYPE_ATALK (Appletalk).
4855
     *
4856
     * XXX - check for an organization code of
4857
     * encapsulated Ethernet as well?
4858
     */
4859
61
    return gen_snap(cstate, 0x080007, ETHERTYPE_ATALK);
4860
4861
6.78k
  default:
4862
    /*
4863
     * XXX - we don't have to check for IPX 802.3
4864
     * here, but should we check for the IPX EtherType?
4865
     */
4866
6.78k
    if (ll_proto <= ETHERMTU) {
4867
108
      assert_maxval(cstate, "LLC DSAP", ll_proto, UINT8_MAX);
4868
      /*
4869
       * This is an LLC SAP value, so check
4870
       * the DSAP.
4871
       */
4872
108
      return gen_cmp(cstate, OR_LLC, 0, BPF_B, ll_proto);
4873
6.68k
    } else {
4874
6.68k
      assert_maxval(cstate, "EtherType", ll_proto, UINT16_MAX);
4875
      /*
4876
       * This is an Ethernet type; we assume that it's
4877
       * unlikely that it'll appear in the right place
4878
       * at random, and therefore check only the
4879
       * location that would hold the Ethernet type
4880
       * in a SNAP frame with an organization code of
4881
       * 0x000000 (encapsulated Ethernet).
4882
       *
4883
       * XXX - if we were to check for the SNAP DSAP and
4884
       * LSAP, as per XXX, and were also to check for an
4885
       * organization code of 0x000000 (encapsulated
4886
       * Ethernet), we'd do
4887
       *
4888
       *  return gen_snap(cstate, 0x000000, ll_proto);
4889
       *
4890
       * here; for now, we don't, as per the above.
4891
       * I don't know whether it's worth the extra CPU
4892
       * time to do the right check or not.
4893
       */
4894
6.68k
      return gen_cmp(cstate, OR_LLC, 6, BPF_H, ll_proto);
4895
6.68k
    }
4896
10.7k
  }
4897
10.7k
}
4898
4899
static struct block *
4900
gen_hostop(compiler_state_t *cstate, bpf_u_int32 addr, bpf_u_int32 mask,
4901
    int dir, u_int src_off, u_int dst_off)
4902
33.4k
{
4903
33.4k
  struct block *b0, *b1;
4904
33.4k
  u_int offset;
4905
4906
33.4k
  switch (dir) {
4907
4908
11.5k
  case Q_SRC:
4909
11.5k
    offset = src_off;
4910
11.5k
    break;
4911
4912
11.2k
  case Q_DST:
4913
11.2k
    offset = dst_off;
4914
11.2k
    break;
4915
4916
751
  case Q_AND:
4917
751
    b0 = gen_hostop(cstate, addr, mask, Q_SRC, src_off, dst_off);
4918
751
    b1 = gen_hostop(cstate, addr, mask, Q_DST, src_off, dst_off);
4919
751
    return gen_and(b0, b1);
4920
4921
9.61k
  case Q_DEFAULT:
4922
9.92k
  case Q_OR:
4923
9.92k
    b0 = gen_hostop(cstate, addr, mask, Q_SRC, src_off, dst_off);
4924
9.92k
    b1 = gen_hostop(cstate, addr, mask, Q_DST, src_off, dst_off);
4925
9.92k
    return gen_or(b0, b1);
4926
4927
0
  default:
4928
    // Bug: a WLAN dqual should have been rejected earlier.
4929
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_STR, __func__, "dir", dqkw(dir));
4930
    /*NOTREACHED*/
4931
33.4k
  }
4932
22.7k
  return gen_mcmp(cstate, OR_LINKPL, offset, BPF_W, addr, mask);
4933
33.4k
}
4934
4935
static struct block *
4936
gen_hostop6(compiler_state_t *cstate, const struct in6_addr *addr,
4937
    const struct in6_addr *mask, const u_char dir)
4938
2.28k
{
4939
2.28k
  struct block *b0, *b1;
4940
2.28k
  u_int offset;
4941
  /*
4942
   * Code below needs to access four separate 32-bit parts of the 128-bit
4943
   * IPv6 address and mask.  In some OSes this is as simple as using the
4944
   * s6_addr32 pseudo-member of struct in6_addr, which contains a union of
4945
   * 8-, 16- and 32-bit arrays.  In other OSes this is not the case, as
4946
   * far as libpcap sees it.  Hence copy the data before use to avoid
4947
   * potential unaligned memory access and the associated compiler
4948
   * warnings (whether genuine or not).
4949
   */
4950
2.28k
  bpf_u_int32 a[4], m[4];
4951
4952
2.28k
  switch (dir) {
4953
4954
822
  case Q_SRC:
4955
822
    offset = IPV6_SRCADDR_OFFSET;
4956
822
    break;
4957
4958
743
  case Q_DST:
4959
743
    offset = IPV6_DSTADDR_OFFSET;
4960
743
    break;
4961
4962
162
  case Q_AND:
4963
162
    b0 = gen_hostop6(cstate, addr, mask, Q_SRC);
4964
162
    b1 = gen_hostop6(cstate, addr, mask, Q_DST);
4965
162
    return gen_and(b0, b1);
4966
4967
450
  case Q_DEFAULT:
4968
560
  case Q_OR:
4969
560
    b0 = gen_hostop6(cstate, addr, mask, Q_SRC);
4970
560
    b1 = gen_hostop6(cstate, addr, mask, Q_DST);
4971
560
    return gen_or(b0, b1);
4972
4973
0
  default:
4974
    // Bug: a WLAN dqual should have been rejected earlier.
4975
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_STR, __func__, "dir", dqkw(dir));
4976
    /*NOTREACHED*/
4977
2.28k
  }
4978
  /* this order is important */
4979
1.56k
  memcpy(a, addr, sizeof(a));
4980
1.56k
  memcpy(m, mask, sizeof(m));
4981
1.56k
  b1 = gen_true(cstate);
4982
7.82k
  for (int i = 3; i >= 0; i--) {
4983
6.26k
    b0 = gen_mcmp(cstate, OR_LINKPL, offset + 4 * i, BPF_W,
4984
6.26k
        ntohl(a[i]), ntohl(m[i]));
4985
6.26k
    b1 = gen_and(b0, b1);
4986
6.26k
  }
4987
1.56k
  return b1;
4988
2.28k
}
4989
4990
/*
4991
 * Like gen_mac48host(), but for DLT_IEEE802_11 (802.11 wireless LAN) and
4992
 * various 802.11 + radio headers.
4993
 */
4994
static struct block *
4995
gen_wlanhostop(compiler_state_t *cstate, const u_char *eaddr, int dir)
4996
1.97k
{
4997
1.97k
  struct block *b0, *b1, *b2;
4998
1.97k
  struct slist *s;
4999
5000
#ifdef ENABLE_WLAN_FILTERING_PATCH
5001
  /*
5002
   * TODO GV 20070613
5003
   * We need to disable the optimizer because the optimizer is buggy
5004
   * and wipes out some LD instructions generated by the below
5005
   * code to validate the Frame Control bits
5006
   */
5007
  cstate->no_optimize = 1;
5008
#endif /* ENABLE_WLAN_FILTERING_PATCH */
5009
5010
1.97k
  switch (dir) {
5011
382
  case Q_SRC:
5012
    /*
5013
     * Oh, yuk.
5014
     *
5015
     *  For control frames, there is no SA.
5016
     *
5017
     *  For management frames, SA is at an
5018
     *  offset of 10 from the beginning of
5019
     *  the packet.
5020
     *
5021
     *  For data frames, SA is at an offset
5022
     *  of 10 from the beginning of the packet
5023
     *  if From DS is clear, at an offset of
5024
     *  16 from the beginning of the packet
5025
     *  if From DS is set and To DS is clear,
5026
     *  and an offset of 24 from the beginning
5027
     *  of the packet if From DS is set and To DS
5028
     *  is set.
5029
     */
5030
5031
    /*
5032
     * Generate the tests to be done for data frames
5033
     * with From DS set.
5034
     *
5035
     * First, check for To DS set, i.e. check "link[1] & 0x01".
5036
     */
5037
382
    s = gen_load_a(cstate, OR_LINKHDR, 1, BPF_B);
5038
382
    b1 = gen_set(cstate, IEEE80211_FC1_DIR_TODS, s);
5039
5040
    /*
5041
     * If To DS is set, the SA is at 24.
5042
     */
5043
382
    b0 = gen_bcmp(cstate, OR_LINKHDR, 24, 6, eaddr);
5044
382
    b0 = gen_and(b1, b0);
5045
5046
    /*
5047
     * Now, check for To DS not set, i.e. check
5048
     * "!(link[1] & 0x01)".
5049
     */
5050
382
    s = gen_load_a(cstate, OR_LINKHDR, 1, BPF_B);
5051
382
    b2 = gen_unset(cstate, IEEE80211_FC1_DIR_TODS, s);
5052
5053
    /*
5054
     * If To DS is not set, the SA is at 16.
5055
     */
5056
382
    b1 = gen_bcmp(cstate, OR_LINKHDR, 16, 6, eaddr);
5057
382
    b1 = gen_and(b2, b1);
5058
5059
    /*
5060
     * Now OR together the last two checks.  That gives
5061
     * the complete set of checks for data frames with
5062
     * From DS set.
5063
     */
5064
382
    b0 = gen_or(b1, b0);
5065
5066
    /*
5067
     * Now check for From DS being set, and AND that with
5068
     * the ORed-together checks.
5069
     */
5070
382
    s = gen_load_a(cstate, OR_LINKHDR, 1, BPF_B);
5071
382
    b1 = gen_set(cstate, IEEE80211_FC1_DIR_FROMDS, s);
5072
382
    b0 = gen_and(b1, b0);
5073
5074
    /*
5075
     * Now check for data frames with From DS not set.
5076
     */
5077
382
    s = gen_load_a(cstate, OR_LINKHDR, 1, BPF_B);
5078
382
    b2 = gen_unset(cstate, IEEE80211_FC1_DIR_FROMDS, s);
5079
5080
    /*
5081
     * If From DS isn't set, the SA is at 10.
5082
     */
5083
382
    b1 = gen_bcmp(cstate, OR_LINKHDR, 10, 6, eaddr);
5084
382
    b1 = gen_and(b2, b1);
5085
5086
    /*
5087
     * Now OR together the checks for data frames with
5088
     * From DS not set and for data frames with From DS
5089
     * set; that gives the checks done for data frames.
5090
     */
5091
382
    b0 = gen_or(b1, b0);
5092
5093
    /*
5094
     * Now check for a data frame.
5095
     * I.e, check "link[0] & 0x08".
5096
     */
5097
382
    s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
5098
382
    b1 = gen_set(cstate, IEEE80211_FC0_TYPE_DATA, s);
5099
5100
    /*
5101
     * AND that with the checks done for data frames.
5102
     */
5103
382
    b0 = gen_and(b1, b0);
5104
5105
    /*
5106
     * If the high-order bit of the type value is 0, this
5107
     * is a management frame.
5108
     * I.e, check "!(link[0] & 0x08)".
5109
     */
5110
382
    s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
5111
382
    b2 = gen_unset(cstate, IEEE80211_FC0_TYPE_DATA, s);
5112
5113
    /*
5114
     * For management frames, the SA is at 10.
5115
     */
5116
382
    b1 = gen_bcmp(cstate, OR_LINKHDR, 10, 6, eaddr);
5117
382
    b1 = gen_and(b2, b1);
5118
5119
    /*
5120
     * OR that with the checks done for data frames.
5121
     * That gives the checks done for management and
5122
     * data frames.
5123
     */
5124
382
    b0 = gen_or(b1, b0);
5125
5126
    /*
5127
     * If the low-order bit of the type value is 1,
5128
     * this is either a control frame or a frame
5129
     * with a reserved type, and thus not a
5130
     * frame with an SA.
5131
     *
5132
     * I.e., check "!(link[0] & 0x04)".
5133
     */
5134
382
    s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
5135
382
    b1 = gen_unset(cstate, IEEE80211_FC0_TYPE_CTL, s);
5136
5137
    /*
5138
     * AND that with the checks for data and management
5139
     * frames.
5140
     */
5141
382
    return gen_and(b1, b0);
5142
5143
469
  case Q_DST:
5144
    /*
5145
     * Oh, yuk.
5146
     *
5147
     *  For control frames, there is no DA.
5148
     *
5149
     *  For management frames, DA is at an
5150
     *  offset of 4 from the beginning of
5151
     *  the packet.
5152
     *
5153
     *  For data frames, DA is at an offset
5154
     *  of 4 from the beginning of the packet
5155
     *  if To DS is clear and at an offset of
5156
     *  16 from the beginning of the packet
5157
     *  if To DS is set.
5158
     */
5159
5160
    /*
5161
     * Generate the tests to be done for data frames.
5162
     *
5163
     * First, check for To DS set, i.e. "link[1] & 0x01".
5164
     */
5165
469
    s = gen_load_a(cstate, OR_LINKHDR, 1, BPF_B);
5166
469
    b1 = gen_set(cstate, IEEE80211_FC1_DIR_TODS, s);
5167
5168
    /*
5169
     * If To DS is set, the DA is at 16.
5170
     */
5171
469
    b0 = gen_bcmp(cstate, OR_LINKHDR, 16, 6, eaddr);
5172
469
    b0 = gen_and(b1, b0);
5173
5174
    /*
5175
     * Now, check for To DS not set, i.e. check
5176
     * "!(link[1] & 0x01)".
5177
     */
5178
469
    s = gen_load_a(cstate, OR_LINKHDR, 1, BPF_B);
5179
469
    b2 = gen_unset(cstate, IEEE80211_FC1_DIR_TODS, s);
5180
5181
    /*
5182
     * If To DS is not set, the DA is at 4.
5183
     */
5184
469
    b1 = gen_bcmp(cstate, OR_LINKHDR, 4, 6, eaddr);
5185
469
    b1 = gen_and(b2, b1);
5186
5187
    /*
5188
     * Now OR together the last two checks.  That gives
5189
     * the complete set of checks for data frames.
5190
     */
5191
469
    b0 = gen_or(b1, b0);
5192
5193
    /*
5194
     * Now check for a data frame.
5195
     * I.e, check "link[0] & 0x08".
5196
     */
5197
469
    s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
5198
469
    b1 = gen_set(cstate, IEEE80211_FC0_TYPE_DATA, s);
5199
5200
    /*
5201
     * AND that with the checks done for data frames.
5202
     */
5203
469
    b0 = gen_and(b1, b0);
5204
5205
    /*
5206
     * If the high-order bit of the type value is 0, this
5207
     * is a management frame.
5208
     * I.e, check "!(link[0] & 0x08)".
5209
     */
5210
469
    s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
5211
469
    b2 = gen_unset(cstate, IEEE80211_FC0_TYPE_DATA, s);
5212
5213
    /*
5214
     * For management frames, the DA is at 4.
5215
     */
5216
469
    b1 = gen_bcmp(cstate, OR_LINKHDR, 4, 6, eaddr);
5217
469
    b1 = gen_and(b2, b1);
5218
5219
    /*
5220
     * OR that with the checks done for data frames.
5221
     * That gives the checks done for management and
5222
     * data frames.
5223
     */
5224
469
    b0 = gen_or(b1, b0);
5225
5226
    /*
5227
     * If the low-order bit of the type value is 1,
5228
     * this is either a control frame or a frame
5229
     * with a reserved type, and thus not a
5230
     * frame with an SA.
5231
     *
5232
     * I.e., check "!(link[0] & 0x04)".
5233
     */
5234
469
    s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
5235
469
    b1 = gen_unset(cstate, IEEE80211_FC0_TYPE_CTL, s);
5236
5237
    /*
5238
     * AND that with the checks for data and management
5239
     * frames.
5240
     */
5241
469
    return gen_and(b1, b0);
5242
5243
82
  case Q_AND:
5244
82
    b0 = gen_wlanhostop(cstate, eaddr, Q_SRC);
5245
82
    b1 = gen_wlanhostop(cstate, eaddr, Q_DST);
5246
82
    return gen_and(b0, b1);
5247
5248
172
  case Q_DEFAULT:
5249
234
  case Q_OR:
5250
234
    b0 = gen_wlanhostop(cstate, eaddr, Q_SRC);
5251
234
    b1 = gen_wlanhostop(cstate, eaddr, Q_DST);
5252
234
    return gen_or(b0, b1);
5253
5254
  /*
5255
   * XXX - add BSSID keyword?
5256
   */
5257
78
  case Q_ADDR1:
5258
78
    return (gen_bcmp(cstate, OR_LINKHDR, 4, 6, eaddr));
5259
5260
65
  case Q_ADDR2:
5261
    /*
5262
     * Not present in CTS or ACK control frames.
5263
     */
5264
65
    b0 = gen_mcmp_ne(cstate, OR_LINKHDR, 0, BPF_B, IEEE80211_FC0_TYPE_CTL,
5265
65
      IEEE80211_FC0_TYPE_MASK);
5266
65
    b1 = gen_mcmp_ne(cstate, OR_LINKHDR, 0, BPF_B, IEEE80211_FC0_SUBTYPE_CTS,
5267
65
      IEEE80211_FC0_SUBTYPE_MASK);
5268
65
    b2 = gen_mcmp_ne(cstate, OR_LINKHDR, 0, BPF_B, IEEE80211_FC0_SUBTYPE_ACK,
5269
65
      IEEE80211_FC0_SUBTYPE_MASK);
5270
65
    b2 = gen_and(b1, b2);
5271
65
    b2 = gen_or(b0, b2);
5272
65
    b1 = gen_bcmp(cstate, OR_LINKHDR, 10, 6, eaddr);
5273
65
    return gen_and(b2, b1);
5274
5275
57
  case Q_ADDR3:
5276
    /*
5277
     * Not present in control frames.
5278
     */
5279
57
    b0 = gen_mcmp_ne(cstate, OR_LINKHDR, 0, BPF_B, IEEE80211_FC0_TYPE_CTL,
5280
57
      IEEE80211_FC0_TYPE_MASK);
5281
57
    b1 = gen_bcmp(cstate, OR_LINKHDR, 16, 6, eaddr);
5282
57
    return gen_and(b0, b1);
5283
5284
90
  case Q_ADDR4:
5285
    /*
5286
     * Present only if the direction mask has both "From DS"
5287
     * and "To DS" set.  Neither control frames nor management
5288
     * frames should have both of those set, so we don't
5289
     * check the frame type.
5290
     */
5291
90
    b0 = gen_mcmp(cstate, OR_LINKHDR, 1, BPF_B,
5292
90
      IEEE80211_FC1_DIR_DSTODS, IEEE80211_FC1_DIR_MASK);
5293
90
    b1 = gen_bcmp(cstate, OR_LINKHDR, 24, 6, eaddr);
5294
90
    return gen_and(b0, b1);
5295
5296
175
  case Q_RA:
5297
    /*
5298
     * Not present in management frames; addr1 in other
5299
     * frames.
5300
     */
5301
5302
    /*
5303
     * If the high-order bit of the type value is 0, this
5304
     * is a management frame.
5305
     * I.e, check "(link[0] & 0x08)".
5306
     */
5307
175
    s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
5308
175
    b1 = gen_set(cstate, IEEE80211_FC0_TYPE_DATA, s);
5309
5310
    /*
5311
     * Check addr1.
5312
     */
5313
175
    b0 = gen_bcmp(cstate, OR_LINKHDR, 4, 6, eaddr);
5314
5315
    /*
5316
     * AND that with the check of addr1.
5317
     */
5318
175
    return gen_and(b1, b0);
5319
5320
344
  case Q_TA:
5321
    /*
5322
     * Not present in management frames; addr2, if present,
5323
     * in other frames.
5324
     */
5325
5326
    /*
5327
     * Not present in CTS or ACK control frames.
5328
     */
5329
344
    b0 = gen_mcmp_ne(cstate, OR_LINKHDR, 0, BPF_B, IEEE80211_FC0_TYPE_CTL,
5330
344
      IEEE80211_FC0_TYPE_MASK);
5331
344
    b1 = gen_mcmp_ne(cstate, OR_LINKHDR, 0, BPF_B, IEEE80211_FC0_SUBTYPE_CTS,
5332
344
      IEEE80211_FC0_SUBTYPE_MASK);
5333
344
    b2 = gen_mcmp_ne(cstate, OR_LINKHDR, 0, BPF_B, IEEE80211_FC0_SUBTYPE_ACK,
5334
344
      IEEE80211_FC0_SUBTYPE_MASK);
5335
344
    b2 = gen_and(b1, b2);
5336
344
    b2 = gen_or(b0, b2);
5337
5338
    /*
5339
     * If the high-order bit of the type value is 0, this
5340
     * is a management frame.
5341
     * I.e, check "(link[0] & 0x08)".
5342
     */
5343
344
    s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
5344
344
    b1 = gen_set(cstate, IEEE80211_FC0_TYPE_DATA, s);
5345
5346
    /*
5347
     * AND that with the check for frames other than
5348
     * CTS and ACK frames.
5349
     */
5350
344
    b2 = gen_and(b1, b2);
5351
5352
    /*
5353
     * Check addr2.
5354
     */
5355
344
    b1 = gen_bcmp(cstate, OR_LINKHDR, 10, 6, eaddr);
5356
344
    return gen_and(b2, b1);
5357
1.97k
  }
5358
0
  bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "dir", dir);
5359
  /*NOTREACHED*/
5360
1.97k
}
5361
5362
/*
5363
 * This is quite tricky because there may be pad bytes in front of the
5364
 * DECNET header, and then there are two possible data packet formats that
5365
 * carry both src and dst addresses, plus 5 packet types in a format that
5366
 * carries only the src node, plus 2 types that use a different format and
5367
 * also carry just the src node.
5368
 *
5369
 * Yuck.
5370
 *
5371
 * Instead of doing those all right, we just look for data packets with
5372
 * 0 or 1 bytes of padding.  If you want to look at other packets, that
5373
 * will require a lot more hacking.
5374
 *
5375
 * To add support for filtering on DECNET "areas" (network numbers)
5376
 * one would want to add a "mask" argument to this routine.  That would
5377
 * make the filter even more inefficient, although one could be clever
5378
 * and not generate masking instructions if the mask is 0xFFFF.
5379
 */
5380
static struct block *
5381
gen_dnhostop(compiler_state_t *cstate, bpf_u_int32 addr, int dir)
5382
1.02k
{
5383
1.02k
  struct block *b0, *b1, *b2, *tmp;
5384
1.02k
  u_int offset_lh;  /* offset if long header is received */
5385
1.02k
  u_int offset_sh;  /* offset if short header is received */
5386
5387
1.02k
  switch (dir) {
5388
5389
344
  case Q_DST:
5390
344
    offset_sh = 1;  /* follows flags */
5391
344
    offset_lh = 7;  /* flgs,darea,dsubarea,HIORD */
5392
344
    break;
5393
5394
351
  case Q_SRC:
5395
351
    offset_sh = 3;  /* follows flags, dstnode */
5396
351
    offset_lh = 15; /* flgs,darea,dsubarea,did,sarea,ssub,HIORD */
5397
351
    break;
5398
5399
131
  case Q_AND:
5400
    /* Inefficient because we do our Calvinball dance twice */
5401
131
    b0 = gen_dnhostop(cstate, addr, Q_SRC);
5402
131
    b1 = gen_dnhostop(cstate, addr, Q_DST);
5403
131
    return gen_and(b0, b1);
5404
5405
23
  case Q_DEFAULT:
5406
202
  case Q_OR:
5407
    /* Inefficient because we do our Calvinball dance twice */
5408
202
    b0 = gen_dnhostop(cstate, addr, Q_SRC);
5409
202
    b1 = gen_dnhostop(cstate, addr, Q_DST);
5410
202
    return gen_or(b0, b1);
5411
5412
0
  default:
5413
    // Bug: a WLAN dqual should have been rejected earlier.
5414
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_STR, __func__, "dir", dqkw(dir));
5415
    /*NOTREACHED*/
5416
1.02k
  }
5417
  /*
5418
   * In a DECnet message inside an Ethernet frame the first two bytes
5419
   * immediately after EtherType are the [little-endian] DECnet message
5420
   * length, which is irrelevant in this context.
5421
   *
5422
   * "pad = 1" means the third byte equals 0x81, thus it is the PLENGTH
5423
   * 8-bit bitmap of the optional padding before the packet route header.
5424
   * The bitmap always has bit 7 set to 1 and in this case has bits 0-6
5425
   * (TOTAL-PAD-SEQUENCE-LENGTH) set to integer value 1.  The latter
5426
   * means there aren't any PAD bytes after the bitmap, so the header
5427
   * begins at the fourth byte.  "pad = 0" means bit 7 of the third byte
5428
   * is set to 0, thus the header begins at the third byte.
5429
   *
5430
   * The header can be in several (as mentioned above) formats, all of
5431
   * which begin with the FLAGS 8-bit bitmap, which always has bit 7
5432
   * (PF, "pad field") set to 0 regardless of any padding present before
5433
   * the header.  "Short header" means bits 0-2 of the bitmap encode the
5434
   * integer value 2 (SFDP), and "long header" means value 6 (LFDP).
5435
   *
5436
   * To test PLENGTH and FLAGS, use multiple-byte constants with the
5437
   * values and the masks, this maps to the required single bytes of
5438
   * the message correctly on both big-endian and little-endian hosts.
5439
   * For the DECnet address use PCAP_BSWAP_16(), which always swaps bytes,
5440
   * because the wire encoding is little-endian and BPF multiple-byte
5441
   * loads are big-endian.  When the destination address is near enough
5442
   * to PLENGTH and FLAGS, generate one 32-bit comparison instead of two
5443
   * smaller ones.
5444
   */
5445
  /* Check for pad = 1, long header case */
5446
695
  tmp = gen_mcmp(cstate, OR_LINKPL, 2, BPF_H, 0x8106U, 0xFF07U);
5447
695
  b1 = gen_cmp(cstate, OR_LINKPL, 2 + 1 + offset_lh,
5448
695
      BPF_H, PCAP_BSWAP_16(addr));
5449
695
  b1 = gen_and(tmp, b1);
5450
  /* Check for pad = 0, long header case */
5451
695
  tmp = gen_mcmp(cstate, OR_LINKPL, 2, BPF_B, 0x06U, 0x07U);
5452
695
  b2 = gen_cmp(cstate, OR_LINKPL, 2 + offset_lh, BPF_H,
5453
695
      PCAP_BSWAP_16(addr));
5454
695
  b2 = gen_and(tmp, b2);
5455
695
  b1 = gen_or(b2, b1);
5456
  /* Check for pad = 1, short header case */
5457
695
  if (dir == Q_DST) {
5458
344
    b2 = gen_mcmp(cstate, OR_LINKPL, 2, BPF_W,
5459
344
        0x81020000U | PCAP_BSWAP_16(addr),
5460
344
        0xFF07FFFFU);
5461
351
  } else {
5462
351
    tmp = gen_mcmp(cstate, OR_LINKPL, 2, BPF_H, 0x8102U, 0xFF07U);
5463
351
    b2 = gen_cmp(cstate, OR_LINKPL, 2 + 1 + offset_sh, BPF_H,
5464
351
        PCAP_BSWAP_16(addr));
5465
351
    b2 = gen_and(tmp, b2);
5466
351
  }
5467
695
  b1 = gen_or(b2, b1);
5468
  /* Check for pad = 0, short header case */
5469
695
  if (dir == Q_DST) {
5470
344
    b2 = gen_mcmp(cstate, OR_LINKPL, 2, BPF_W,
5471
344
        0x02000000U | PCAP_BSWAP_16(addr) << 8,
5472
344
        0x07FFFF00U);
5473
351
  } else {
5474
351
    tmp = gen_mcmp(cstate, OR_LINKPL, 2, BPF_B, 0x02U, 0x07U);
5475
351
    b2 = gen_cmp(cstate, OR_LINKPL, 2 + offset_sh, BPF_H,
5476
351
        PCAP_BSWAP_16(addr));
5477
351
    b2 = gen_and(tmp, b2);
5478
351
  }
5479
5480
695
  return gen_or(b2, b1);
5481
1.02k
}
5482
5483
/*
5484
 * Assume the link-layer payload data just before off_nl (L3) is an MPLS label
5485
 * (L2.5) and test whether the label has Bottom of Stack bit set.
5486
 */
5487
static struct block *
5488
gen_just_after_mpls_stack(compiler_state_t *cstate)
5489
881
{
5490
881
  return gen_set(cstate, 0x01, gen_load_a(cstate, OR_PREVMPLSHDR, 2, BPF_B));
5491
881
}
5492
5493
/*
5494
 * Generate a check for IPv4 or IPv6 for MPLS-encapsulated packets;
5495
 * test the bottom-of-stack bit, and then check the version number
5496
 * field in the IP header.
5497
 */
5498
static struct block *
5499
gen_mpls_linktype(compiler_state_t *cstate, bpf_u_int32 ll_proto)
5500
847
{
5501
847
  struct block *b0, *b1;
5502
5503
  /*
5504
   * In this context the to-be-confirmed IPv4/IPv6 header begins at the
5505
   * link-layer payload.
5506
   */
5507
847
  switch (ll_proto) {
5508
5509
447
  case ETHERTYPE_IP:
5510
447
    b0 = gen_just_after_mpls_stack(cstate);
5511
447
    b1 = gen_ip_version(cstate, OR_LINKPL, 4);
5512
447
    return gen_and(b0, b1);
5513
5514
339
  case ETHERTYPE_IPV6:
5515
339
    b0 = gen_just_after_mpls_stack(cstate);
5516
339
    b1 = gen_ip_version(cstate, OR_LINKPL, 6);
5517
339
    return gen_and(b0, b1);
5518
5519
61
  default:
5520
    /* FIXME add other L3 proto IDs */
5521
61
    bpf_error(cstate, "unsupported protocol over mpls");
5522
    /*NOTREACHED*/
5523
847
  }
5524
847
}
5525
5526
static struct block *
5527
gen_host(compiler_state_t *cstate, const size_t n, const bpf_u_int32 *a,
5528
    const bpf_u_int32 *m, const u_char proto, const u_char dir,
5529
    const u_char not, const char *context)
5530
20.7k
{
5531
  /*
5532
   * WLAN direction qualifiers are never valid for IPv4 addresses.
5533
   *
5534
   * It is important to validate this now because the call to
5535
   * gen_hostop() may be optimized out below.
5536
   */
5537
20.7k
  assert_nonwlan_dqual(cstate, dir);
5538
5539
20.7k
  struct block *b0, *b1;
5540
20.7k
  bpf_u_int32 llproto;
5541
20.7k
  u_int src_off, dst_off;
5542
5543
20.7k
  switch (proto) {
5544
5545
5.22k
  case Q_DEFAULT:
5546
5.22k
    b0 = gen_host(cstate, n, a, m, Q_IP, dir, not, context);
5547
    /*
5548
     * Only check for non-IPv4 addresses if we're not
5549
     * checking MPLS-encapsulated packets.
5550
     */
5551
5.22k
    if (cstate->label_stack_depth == 0) {
5552
5.10k
      b1 = gen_host(cstate, n, a, m, Q_ARP, dir, not, context);
5553
5.10k
      b1 = gen_or(b0, b1);
5554
5.10k
      b0 = gen_host(cstate, n, a, m, Q_RARP, dir, not, context);
5555
5.10k
      b0 = gen_or(b1, b0);
5556
5.10k
    }
5557
5.22k
    return b0;
5558
5559
5.28k
  case Q_IP:
5560
5.28k
    llproto = ETHERTYPE_IP;
5561
5.28k
    src_off = IPV4_SRCADDR_OFFSET;
5562
5.28k
    dst_off = IPV4_DSTADDR_OFFSET;
5563
5.28k
    break;
5564
5565
5.13k
  case Q_RARP:
5566
5.13k
    llproto = ETHERTYPE_REVARP;
5567
5.13k
    src_off = RARP_SRCADDR_OFFSET;
5568
5.13k
    dst_off = RARP_DSTADDR_OFFSET;
5569
5.13k
    break;
5570
5571
5.13k
  case Q_ARP:
5572
5.13k
    llproto = ETHERTYPE_ARP;
5573
5.13k
    src_off = ARP_SRCADDR_OFFSET;
5574
5.13k
    dst_off = ARP_DSTADDR_OFFSET;
5575
5.13k
    break;
5576
5577
3
  default:
5578
3
    bpf_error(cstate, ERRSTR_INVALID_QUAL, pqkw(proto), context);
5579
20.7k
  }
5580
15.5k
  b0 = gen_linktype(cstate, llproto);
5581
15.5k
  if (b0->meaning == IS_FALSE) {
5582
    /*
5583
     * If this DLT does not support ARP or RARP, the result of
5584
     * gen_linktype() is a Boolean false, then the subsequent
5585
     * gen_and() would discard the result of gen_hostop() and
5586
     * return the Boolean false.
5587
     *
5588
     * However, if this DLT also uses a variable-length link-layer
5589
     * header (which means DLT_PFLOG only at the time of this
5590
     * writing), a side effect of the gen_hostop() invocation
5591
     * would be registering a demand for a variable-length offset
5592
     * preamble, which a Boolean constant never needs, so in this
5593
     * case return early and have one fewer reasons to produce the
5594
     * preamble in insert_compute_vloffsets().
5595
     */
5596
3.42k
    return b0;
5597
3.42k
  }
5598
12.1k
  b1 = gen_false(cstate);
5599
24.2k
  for (size_t i = 0; i < n; i++)
5600
12.1k
    b1 = gen_or(b1,
5601
12.1k
        gen_hostop(cstate, a[i], m[i], dir, src_off, dst_off));
5602
12.1k
  return gen_and(b0, not ? gen_not(b1) : b1);
5603
15.5k
}
5604
5605
static struct block *
5606
gen_host6(compiler_state_t *cstate, const size_t n,
5607
    const struct in6_addr *a, const struct in6_addr *m,
5608
    const u_char proto, const u_char dir, const u_char not,
5609
    const char *context)
5610
859
{
5611
  // WLAN direction qualifiers are never valid for IPv6 addresses.
5612
859
  assert_nonwlan_dqual(cstate, dir);
5613
5614
859
  if (proto != Q_DEFAULT && proto != Q_IPV6)
5615
8
    bpf_error(cstate, ERRSTR_INVALID_QUAL, pqkw(proto), context);
5616
5617
851
  struct block *linkproto = gen_linktype(cstate, ETHERTYPE_IPV6);
5618
851
  struct block *host = gen_false(cstate);
5619
1.69k
  for (size_t i = 0; i < n; i++)
5620
843
    host = gen_or(host, gen_hostop6(cstate, a + i, m + i, dir));
5621
851
  return gen_and(linkproto, not ? gen_not(host) : host);
5622
859
}
5623
5624
static int
5625
uint32_t_cmp(const void *a, const void *b)
5626
0
{
5627
  /*
5628
   * Host byte order.  One potential way to do the comparison would be
5629
   * to return "a32 - b32", but that would require to prove -- to both
5630
   * humans and C compilers -- that for all possible [uint32_t] values
5631
   * of a32 and b32 the difference would always map to a correct sign of
5632
   * the [int] return value on all architectures, so let's instead do it
5633
   * in a way that is obviously correct.
5634
   */
5635
0
  const uint32_t a32 = *((uint32_t *)a), b32 = *((uint32_t *)b);
5636
0
  return a32 < b32 ? -1 :
5637
0
      a32 > b32 ? 1 :
5638
0
      0;
5639
0
}
5640
5641
static int
5642
in6_addr_cmp(const void *a, const void *b)
5643
0
{
5644
  // Network byte order is straightforward.
5645
0
  return memcmp(a, b, sizeof(struct in6_addr));
5646
0
}
5647
5648
/*
5649
 * The maximum supported number of resolved addresses per family (IPv4/IPv6)
5650
 * for a given Internet hostname.
5651
 */
5652
240
#define MAX_PER_AF 100
5653
5654
static struct block *
5655
gen_host46_byname(compiler_state_t *cstate, const char *name,
5656
    const u_char proto4, const u_char proto6, const u_char dir,
5657
    const u_char not)
5658
269
{
5659
  /*
5660
   * Both gen_host() and gen_host6() require a context argument to
5661
   * generate an error message if the proto qualifier is invalid.  The
5662
   * only two invocations of this function are from gen_gateway() and
5663
   * gen_scode().  Because the former validates pqual first, the only
5664
   * possible context here is from the latter, so there is no sense in
5665
   * using a function argument for what effectively is a constant.
5666
   */
5667
269
  static const char *context = "host <Internet hostname>";
5668
5669
269
  if ((cstate->ai = pcap_nametoaddrinfo(name)) == NULL)
5670
27
    bpf_error(cstate, "unknown host '%s'", name);
5671
242
  struct block *ret = NULL;
5672
5673
  /*
5674
   * For a hostname that resolves to both IPv4 and IPv6 addresses the
5675
   * AF_INET addresses may come before or after the AF_INET6 addresses
5676
   * depending on which getaddrinfo() implementation it is, what the
5677
   * resolving host's network configuration is and (on Linux with glibc)
5678
   * the contents of gai.conf(5).  This is because getaddrinfo() presumes
5679
   * a subsequent bind(2) or connect(2) use of the addresses, which is
5680
   * not the case here, so there is no sense in preserving the order of
5681
   * the AFs in the resolved addresses.  However, there is sense in
5682
   * hard-coding the order of AFs when generating a match block for more
5683
   * than one AF because this way the result reflects fewer external
5684
   * effects and is easier to test.
5685
   */
5686
5687
  /*
5688
   * Ignore any IPv4 addresses when resolving "ip6 host NAME", validate
5689
   * all other proto qualifiers in gen_host().
5690
   */
5691
242
  if (proto4 != Q_IPV6) {
5692
230
    uint32_t addrs[MAX_PER_AF], masks[MAX_PER_AF];
5693
230
    size_t count = 0;
5694
460
    for (struct addrinfo *ai = cstate->ai; ai; ai = ai->ai_next) {
5695
230
      if (ai->ai_family != AF_INET)
5696
18
        continue;
5697
212
      if (count == MAX_PER_AF)
5698
0
        bpf_error(cstate,
5699
0
                  "More than %u IPv4 addresses per name",
5700
0
                  MAX_PER_AF);
5701
212
      struct sockaddr_in *sin4 =
5702
212
          (struct sockaddr_in *)ai->ai_addr;
5703
212
      addrs[count] = ntohl(sin4->sin_addr.s_addr);
5704
212
      masks[count] = 0xffffffff;
5705
212
      count++;
5706
212
    }
5707
230
    if (count > 1)
5708
0
      qsort(addrs, count, sizeof(*addrs), uint32_t_cmp);
5709
230
    if (count)
5710
212
      ret = gen_host(cstate, count, addrs, masks, proto4,
5711
212
                     dir, not, context);
5712
230
  }
5713
5714
  /*
5715
   * Ignore any IPv6 addresses when resolving "(arp|ip|rarp) host NAME",
5716
   * validate all other proto qualifiers in gen_host6().
5717
   */
5718
242
  static const struct in6_addr mask128 = { .s6_addr = {
5719
242
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
5720
242
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
5721
242
  }};
5722
242
  if (proto6 != Q_ARP && proto6 != Q_IP && proto6 != Q_RARP) {
5723
162
    struct in6_addr addrs[MAX_PER_AF], masks[MAX_PER_AF];
5724
162
    size_t count = 0;
5725
324
    for (struct addrinfo *ai = cstate->ai; ai; ai = ai->ai_next) {
5726
162
      if (ai->ai_family != AF_INET6)
5727
134
        continue;
5728
28
      if (count == MAX_PER_AF)
5729
0
        bpf_error(cstate,
5730
0
                  "More than %u IPv6 addresses per name",
5731
0
                  MAX_PER_AF);
5732
28
      struct sockaddr_in6 *sin6 =
5733
28
          (struct sockaddr_in6 *)ai->ai_addr;
5734
28
      addrs[count] = sin6->sin6_addr;
5735
28
      masks[count] = mask128;
5736
28
      count++;
5737
28
    }
5738
162
    if (count > 1)
5739
0
      qsort(addrs, count, sizeof(*addrs), in6_addr_cmp);
5740
162
    if (count) {
5741
28
      struct block *hosts6 =
5742
28
          gen_host6(cstate, count, addrs, masks, proto6, dir,
5743
28
                    not, context);
5744
28
      ret = ret ? gen_or(ret, hosts6) : hosts6;
5745
28
    }
5746
162
  }
5747
5748
242
  freeaddrinfo(cstate->ai);
5749
242
  cstate->ai = NULL;
5750
5751
242
  if (! ret)
5752
2
    bpf_error(cstate, "unknown host '%s'%s", name,
5753
2
        proto4 == Q_DEFAULT
5754
2
        ? ""
5755
2
        : " for specified address family");
5756
240
  return ret;
5757
242
}
5758
5759
#undef MAX_PER_AF
5760
5761
static struct block *
5762
gen_dnhost(compiler_state_t *cstate, const char *s, bpf_u_int32 v,
5763
    const struct qual q)
5764
394
{
5765
  // WLAN direction qualifiers are never valid for DECnet addresses.
5766
394
  assert_nonwlan_dqual(cstate, q.dir);
5767
5768
  /*
5769
   * libpcap defines exactly one primitive that has "decnet" as
5770
   * the protocol qualifier: "decnet host AREANUMBER.NODENUMBER".
5771
   */
5772
394
  if (q.addr != Q_DEFAULT && q.addr != Q_HOST)
5773
1
    bpf_error(cstate, ERRSTR_INVALID_QUAL, "decnet", tqkw(q.addr));
5774
5775
393
  if (s == NULL) {
5776
    /*
5777
     * v contains a 32-bit unsigned parsed from a string of the
5778
     * form {N}, which could be decimal, hexadecimal or octal.
5779
     * Although it would be possible to use the value as a raw
5780
     * 16-bit DECnet address when the value fits into 16 bits,
5781
     * this would be a questionable feature: DECnet address wire
5782
     * encoding is little-endian, so this would not work as
5783
     * intuitively as the same works for [big-endian] IPv4
5784
     * addresses (0x01020304 means 1.2.3.4).
5785
     */
5786
4
    bpf_error(cstate, "invalid DECnet address '%u'", v);
5787
4
  }
5788
5789
  /*
5790
   * s points to a string of the form {N}.{N}, {N}.{N}.{N} or
5791
   * {N}.{N}.{N}.{N}, of which only the first potentially stands
5792
   * for a valid DECnet address.
5793
   */
5794
389
  uint16_t addr;
5795
389
  if (! pcapint_atodn(s, &addr))
5796
26
    bpf_error(cstate, "invalid DECnet address '%s'", s);
5797
5798
363
  struct block *b0 = gen_linktype(cstate, ETHERTYPE_DN);
5799
363
  struct block *b1 = gen_dnhostop(cstate, addr, q.dir);
5800
363
  return gen_and(b0, b1);
5801
389
}
5802
5803
static unsigned char
5804
is_mac48_linktype(const int linktype)
5805
2.38k
{
5806
2.38k
  switch (linktype) {
5807
270
  case DLT_EN10MB:
5808
380
  case DLT_FDDI:
5809
473
  case DLT_IEEE802:
5810
895
  case DLT_IEEE802_11:
5811
1.21k
  case DLT_IEEE802_11_RADIO:
5812
1.39k
  case DLT_IEEE802_11_RADIO_AVS:
5813
1.56k
  case DLT_IP_OVER_FC:
5814
1.65k
  case DLT_NETANALYZER:
5815
1.75k
  case DLT_NETANALYZER_TRANSPARENT:
5816
1.81k
  case DLT_DSA_TAG_BRCM:
5817
1.87k
  case DLT_DSA_TAG_DSA:
5818
2.20k
  case DLT_PPI:
5819
2.35k
  case DLT_PRISM_HEADER:
5820
2.35k
    return 1;
5821
26
  default:
5822
26
    return 0;
5823
2.38k
  }
5824
2.38k
}
5825
5826
static struct block *
5827
gen_mac48host(compiler_state_t *cstate, const u_char *eaddr, const u_char dir,
5828
    const char *keyword)
5829
2.28k
{
5830
2.28k
  struct block *b1 = NULL;
5831
2.28k
  u_int src_off, dst_off;
5832
5833
  /*
5834
   * Do not validate dir yet and let gen_wlanhostop() handle the DLTs
5835
   * that support WLAN direction qualifiers.
5836
   */
5837
2.28k
  switch (cstate->linktype) {
5838
265
  case DLT_EN10MB:
5839
355
  case DLT_NETANALYZER:
5840
448
  case DLT_NETANALYZER_TRANSPARENT:
5841
505
  case DLT_DSA_TAG_BRCM:
5842
571
  case DLT_DSA_TAG_DSA:
5843
571
    b1 = gen_prevlinkhdr_check(cstate);
5844
571
    src_off = 6;
5845
571
    dst_off = 0;
5846
571
    break;
5847
107
  case DLT_FDDI:
5848
107
    src_off = 6 + 1 + cstate->pcap_fddipad;
5849
107
    dst_off = 0 + 1 + cstate->pcap_fddipad;
5850
107
    break;
5851
92
  case DLT_IEEE802:
5852
92
    src_off = 8;
5853
92
    dst_off = 2;
5854
92
    break;
5855
409
  case DLT_IEEE802_11:
5856
552
  case DLT_PRISM_HEADER:
5857
724
  case DLT_IEEE802_11_RADIO_AVS:
5858
1.03k
  case DLT_IEEE802_11_RADIO:
5859
1.34k
  case DLT_PPI:
5860
1.34k
    return gen_wlanhostop(cstate, eaddr, dir);
5861
170
  case DLT_IP_OVER_FC:
5862
    /*
5863
     * Assume that the addresses are IEEE 48-bit MAC addresses,
5864
     * as RFC 2625 states.
5865
     */
5866
170
    src_off = 10;
5867
170
    dst_off = 2;
5868
170
    break;
5869
0
  case DLT_SUNATM:
5870
    /*
5871
     * This is LLC-multiplexed traffic; if it were
5872
     * LANE, cstate->linktype would have been set to
5873
     * DLT_EN10MB.
5874
     */
5875
     /* FALLTHROUGH */
5876
0
  default:
5877
0
    fail_kw_on_dlt(cstate, keyword);
5878
2.28k
  }
5879
  // Now validate.
5880
940
  assert_nonwlan_dqual(cstate, dir);
5881
5882
940
  struct block *b0, *tmp;
5883
5884
940
  switch (dir) {
5885
203
  case Q_SRC:
5886
203
    b0 = gen_bcmp(cstate, OR_LINKHDR, src_off, 6, eaddr);
5887
203
    break;
5888
254
  case Q_DST:
5889
254
    b0 = gen_bcmp(cstate, OR_LINKHDR, dst_off, 6, eaddr);
5890
254
    break;
5891
105
  case Q_AND:
5892
105
    tmp = gen_bcmp(cstate, OR_LINKHDR, src_off, 6, eaddr);
5893
105
    b0 = gen_bcmp(cstate, OR_LINKHDR, dst_off, 6, eaddr);
5894
105
    b0 = gen_and(tmp, b0);
5895
105
    break;
5896
135
  case Q_DEFAULT:
5897
308
  case Q_OR:
5898
308
    tmp = gen_bcmp(cstate, OR_LINKHDR, src_off, 6, eaddr);
5899
308
    b0 = gen_bcmp(cstate, OR_LINKHDR, dst_off, 6, eaddr);
5900
308
    b0 = gen_or(tmp, b0);
5901
308
    break;
5902
0
  default:
5903
    // Bug: a WLAN dqual should have been rejected earlier.
5904
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_STR, __func__, "dir", dqkw(dir));
5905
940
  }
5906
5907
870
  return b1 ? gen_and(b1, b0) : b0;
5908
940
}
5909
5910
static struct block *
5911
gen_mac48host_byname(compiler_state_t *cstate, const char *name,
5912
    const u_char dir, const char *context)
5913
84
{
5914
84
  if (! is_mac48_linktype(cstate->linktype))
5915
13
    fail_kw_on_dlt(cstate, context);
5916
5917
71
  u_char *eaddrp = pcap_ether_hostton(name);
5918
71
  if (eaddrp == NULL)
5919
71
    bpf_error(cstate, ERRSTR_UNKNOWN_MAC48HOST, name);
5920
0
  u_char eaddr[6];
5921
0
  memcpy(eaddr, eaddrp, sizeof(eaddr));
5922
0
  free(eaddrp);
5923
5924
0
  return gen_mac48host(cstate, eaddr, dir, context);
5925
71
}
5926
5927
static struct block *
5928
gen_mac8host(compiler_state_t *cstate, const uint8_t mac8, const u_char dir,
5929
    const char *context)
5930
690
{
5931
690
  u_int src_off, dst_off;
5932
5933
690
  switch (cstate->linktype) {
5934
245
  case DLT_ARCNET:
5935
408
  case DLT_ARCNET_LINUX:
5936
    /*
5937
     * ARCnet is different from Ethernet: the source address comes
5938
     * before the destination address, each is one byte long.
5939
     * This holds for all three "buffer formats" in RFC 1201
5940
     * Section 2.1, see also page 4-10 in the 1983 edition of the
5941
     * "ARCNET Designer's Handbook" published by Datapoint
5942
     * (document number 61610-01).
5943
     */
5944
408
    src_off = 0;
5945
408
    dst_off = 1;
5946
408
    break;
5947
278
  case DLT_BACNET_MS_TP:
5948
    /*
5949
     * MS/TP resembles both Ethernet (in that the destination
5950
     * station address precedes the source station address) and
5951
     * ARCnet (in that a station address is one byte long).
5952
     */
5953
278
    src_off = 4;
5954
278
    dst_off = 3;
5955
278
    break;
5956
4
  default:
5957
4
    fail_kw_on_dlt(cstate, context);
5958
690
  }
5959
5960
686
  struct block *src, *dst;
5961
5962
686
  switch (dir) {
5963
120
  case Q_SRC:
5964
120
    return gen_cmp(cstate, OR_LINKHDR, src_off, BPF_B, mac8);
5965
267
  case Q_DST:
5966
267
    return gen_cmp(cstate, OR_LINKHDR, dst_off, BPF_B, mac8);
5967
49
  case Q_AND:
5968
49
    src = gen_cmp(cstate, OR_LINKHDR, src_off, BPF_B, mac8);
5969
49
    dst = gen_cmp(cstate, OR_LINKHDR, dst_off, BPF_B, mac8);
5970
49
    return gen_and(src, dst);
5971
212
  case Q_DEFAULT:
5972
250
  case Q_OR:
5973
250
    src = gen_cmp(cstate, OR_LINKHDR, src_off, BPF_B, mac8);
5974
250
    dst = gen_cmp(cstate, OR_LINKHDR, dst_off, BPF_B, mac8);
5975
250
    return gen_or(src, dst);
5976
0
  default:
5977
    // Bug: a WLAN dqual should have been rejected earlier.
5978
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_STR, __func__, "dir", dqkw(dir));
5979
686
  }
5980
686
}
5981
5982
/*
5983
 * This primitive is non-directional by design, so the grammar does not allow
5984
 * to qualify it with a direction.
5985
 */
5986
static struct block *
5987
gen_gateway(compiler_state_t *cstate, const char *name, const u_char proto)
5988
0
{
5989
0
  switch (proto) {
5990
0
  case Q_DEFAULT:
5991
0
  case Q_IP:
5992
0
  case Q_ARP:
5993
0
  case Q_RARP:
5994
0
    break;
5995
0
  default:
5996
0
    bpf_error(cstate, ERRSTR_INVALID_QUAL, pqkw(proto), "gateway");
5997
0
  }
5998
0
  if (cstate->label_stack_depth)
5999
0
    bpf_error(cstate, "'gateway' cannot be used within MPLS");
6000
0
  if (cstate->is_encap)
6001
0
    bpf_error(cstate, "'gateway' cannot be used within VXLAN or Geneve");
6002
6003
0
  struct block *b0 = gen_mac48host_byname(cstate, name, Q_OR, "gateway");
6004
  /*
6005
   * For "gateway NAME" not qualified with a protocol skip the IPv6 leg
6006
   * of the name-to-address translation to match the documented
6007
   * IPv4-only behaviour.
6008
   */
6009
0
  struct block *b1 = gen_host46_byname(cstate, name, proto, Q_IP, Q_OR, 1);
6010
0
  return gen_and(b0, b1);
6011
0
}
6012
6013
static struct block *
6014
gen_proto_abbrev_internal(compiler_state_t *cstate, int proto)
6015
9.24k
{
6016
9.24k
  struct block *b0;
6017
9.24k
  struct block *b1;
6018
6019
9.24k
  switch (proto) {
6020
6021
10
  case Q_SCTP:
6022
68
  case Q_TCP:
6023
96
  case Q_UDP:
6024
425
  case Q_AH:
6025
498
  case Q_ESP:
6026
516
  case Q_PIM:
6027
    // protocols based on IPv4/IPv6
6028
516
    return gen_proto(cstate,
6029
516
        pq_to_ipproto(cstate, (uint8_t)proto), Q_DEFAULT);
6030
6031
13
  case Q_ICMP:
6032
36
  case Q_IGMP:
6033
48
  case Q_IGRP:
6034
61
  case Q_VRRP:
6035
99
  case Q_CARP:
6036
    // protocols based on IPv4 only
6037
99
    return gen_proto(cstate,
6038
99
        pq_to_ipproto(cstate, (uint8_t)proto), Q_IP);
6039
6040
13
  case Q_ICMPV6:
6041
    // protocols based on IPv6 only
6042
13
    return gen_proto(cstate,
6043
13
        pq_to_ipproto(cstate, (uint8_t)proto), Q_IPV6);
6044
6045
2.28k
  case Q_IP:
6046
2.35k
  case Q_ARP:
6047
2.38k
  case Q_RARP:
6048
2.67k
  case Q_ATALK:
6049
2.72k
  case Q_AARP:
6050
2.76k
  case Q_DECNET:
6051
2.78k
  case Q_SCA:
6052
2.86k
  case Q_LAT:
6053
2.91k
  case Q_MOPDL:
6054
3.10k
  case Q_MOPRC:
6055
3.46k
  case Q_IPV6:
6056
    // link-layer protocols not based on LLC
6057
3.46k
    return gen_linktype(cstate,
6058
3.46k
        pq_to_ethertype(cstate, (uint8_t)proto));
6059
6060
47
  case Q_ISO:
6061
267
  case Q_STP:
6062
731
  case Q_IPX:
6063
783
  case Q_NETBEUI:
6064
    // link-layer protocols based on LLC
6065
783
    return gen_linktype(cstate,
6066
783
        pq_to_llcsap(cstate, (uint8_t)proto));
6067
6068
43
  case Q_ESIS:
6069
114
  case Q_ISIS:
6070
144
  case Q_CLNP:
6071
    // ISO protocols
6072
144
    return gen_proto(cstate,
6073
144
        pq_to_nlpid(cstate, (uint8_t)proto), Q_ISO);
6074
6075
1.78k
  case Q_ISIS_L1: /* all IS-IS Level1 PDU-Types */
6076
1.78k
    b0 = gen_proto(cstate, ISIS_L1_LAN_IIH, Q_ISIS);
6077
1.78k
    b1 = gen_proto(cstate, ISIS_PTP_IIH, Q_ISIS); /* FIXME extract the circuit-type bits */
6078
1.78k
    b1 = gen_or(b0, b1);
6079
1.78k
    b0 = gen_proto(cstate, ISIS_L1_LSP, Q_ISIS);
6080
1.78k
    b1 = gen_or(b0, b1);
6081
1.78k
    b0 = gen_proto(cstate, ISIS_L1_CSNP, Q_ISIS);
6082
1.78k
    b1 = gen_or(b0, b1);
6083
1.78k
    b0 = gen_proto(cstate, ISIS_L1_PSNP, Q_ISIS);
6084
1.78k
    return gen_or(b0, b1);
6085
6086
1.52k
  case Q_ISIS_L2: /* all IS-IS Level2 PDU-Types */
6087
1.52k
    b0 = gen_proto(cstate, ISIS_L2_LAN_IIH, Q_ISIS);
6088
1.52k
    b1 = gen_proto(cstate, ISIS_PTP_IIH, Q_ISIS); /* FIXME extract the circuit-type bits */
6089
1.52k
    b1 = gen_or(b0, b1);
6090
1.52k
    b0 = gen_proto(cstate, ISIS_L2_LSP, Q_ISIS);
6091
1.52k
    b1 = gen_or(b0, b1);
6092
1.52k
    b0 = gen_proto(cstate, ISIS_L2_CSNP, Q_ISIS);
6093
1.52k
    b1 = gen_or(b0, b1);
6094
1.52k
    b0 = gen_proto(cstate, ISIS_L2_PSNP, Q_ISIS);
6095
1.52k
    return gen_or(b0, b1);
6096
6097
265
  case Q_ISIS_IIH: /* all IS-IS Hello PDU-Types */
6098
265
    b0 = gen_proto(cstate, ISIS_L1_LAN_IIH, Q_ISIS);
6099
265
    b1 = gen_proto(cstate, ISIS_L2_LAN_IIH, Q_ISIS);
6100
265
    b1 = gen_or(b0, b1);
6101
265
    b0 = gen_proto(cstate, ISIS_PTP_IIH, Q_ISIS);
6102
265
    return gen_or(b0, b1);
6103
6104
264
  case Q_ISIS_LSP:
6105
264
    b0 = gen_proto(cstate, ISIS_L1_LSP, Q_ISIS);
6106
264
    b1 = gen_proto(cstate, ISIS_L2_LSP, Q_ISIS);
6107
264
    return gen_or(b0, b1);
6108
6109
164
  case Q_ISIS_SNP:
6110
164
    b0 = gen_proto(cstate, ISIS_L1_CSNP, Q_ISIS);
6111
164
    b1 = gen_proto(cstate, ISIS_L2_CSNP, Q_ISIS);
6112
164
    b1 = gen_or(b0, b1);
6113
164
    b0 = gen_proto(cstate, ISIS_L1_PSNP, Q_ISIS);
6114
164
    b1 = gen_or(b0, b1);
6115
164
    b0 = gen_proto(cstate, ISIS_L2_PSNP, Q_ISIS);
6116
164
    return gen_or(b0, b1);
6117
6118
105
  case Q_ISIS_CSNP:
6119
105
    b0 = gen_proto(cstate, ISIS_L1_CSNP, Q_ISIS);
6120
105
    b1 = gen_proto(cstate, ISIS_L2_CSNP, Q_ISIS);
6121
105
    return gen_or(b0, b1);
6122
6123
112
  case Q_ISIS_PSNP:
6124
112
    b0 = gen_proto(cstate, ISIS_L1_PSNP, Q_ISIS);
6125
112
    b1 = gen_proto(cstate, ISIS_L2_PSNP, Q_ISIS);
6126
112
    return gen_or(b0, b1);
6127
9.24k
  }
6128
4
  bpf_error(cstate, "'%s' cannot be used as an abbreviation", pqkw(proto));
6129
9.24k
}
6130
6131
struct block *
6132
gen_proto_abbrev(compiler_state_t *cstate, int proto)
6133
6.49k
{
6134
  /*
6135
   * Catch errors reported by us and routines below us, and return NULL
6136
   * on an error.
6137
   */
6138
6.49k
  if (setjmp(cstate->top_ctx))
6139
31
    return (NULL);
6140
6141
6.46k
  return gen_proto_abbrev_internal(cstate, proto);
6142
6.49k
}
6143
6144
static struct block *
6145
gen_ip_proto(compiler_state_t *cstate, const uint8_t proto)
6146
16.1k
{
6147
16.1k
  return gen_cmp(cstate, OR_LINKPL, IPV4_PROTO_OFFSET, BPF_B, proto);
6148
16.1k
}
6149
6150
static struct block *
6151
gen_ip6_proto(compiler_state_t *cstate, const uint8_t proto)
6152
15.7k
{
6153
15.7k
  return gen_cmp(cstate, OR_LINKPL, IPV6_PROTO_OFFSET, BPF_B, proto);
6154
15.7k
}
6155
6156
static struct block *
6157
gen_ipfrag(compiler_state_t *cstate)
6158
6.53k
{
6159
6.53k
  struct slist *s;
6160
6161
  /* not IPv4 frag other than the first frag */
6162
6.53k
  s = gen_load_a(cstate, OR_LINKPL, 6, BPF_H);
6163
6.53k
  return gen_unset(cstate, 0x1fff, s);
6164
6.53k
}
6165
6166
/*
6167
 * Generate a comparison to a port value in the transport-layer header
6168
 * at the specified offset from the beginning of that header.
6169
 *
6170
 * XXX - this handles a variable-length prefix preceding the link-layer
6171
 * header, such as the radiotap or AVS radio prefix, but doesn't handle
6172
 * variable-length link-layer headers (such as Token Ring or 802.11
6173
 * headers).
6174
 */
6175
static struct block *
6176
gen_portatom(compiler_state_t *cstate, int off, uint16_t v)
6177
9.63k
{
6178
9.63k
  return gen_cmp(cstate, OR_TRAN_IPV4, off, BPF_H, v);
6179
9.63k
}
6180
6181
static struct block *
6182
gen_portatom6(compiler_state_t *cstate, int off, uint16_t v)
6183
9.61k
{
6184
9.61k
  return gen_cmp(cstate, OR_TRAN_IPV6, off, BPF_H, v);
6185
9.61k
}
6186
6187
static struct block *
6188
gen_port(compiler_state_t *cstate, const uint16_t port, const int proto,
6189
    const u_char dir, const u_char addr)
6190
5.10k
{
6191
5.10k
  struct block *b1, *tmp;
6192
6193
5.10k
  switch (dir) {
6194
81
  case Q_SRC:
6195
81
    b1 = gen_portatom(cstate, TRAN_SRCPORT_OFFSET, port);
6196
81
    break;
6197
6198
484
  case Q_DST:
6199
484
    b1 = gen_portatom(cstate, TRAN_DSTPORT_OFFSET, port);
6200
484
    break;
6201
6202
130
  case Q_AND:
6203
130
    tmp = gen_portatom(cstate, TRAN_SRCPORT_OFFSET, port);
6204
130
    b1 = gen_portatom(cstate, TRAN_DSTPORT_OFFSET, port);
6205
130
    b1 = gen_and(tmp, b1);
6206
130
    break;
6207
6208
4.33k
  case Q_DEFAULT:
6209
4.40k
  case Q_OR:
6210
4.40k
    tmp = gen_portatom(cstate, TRAN_SRCPORT_OFFSET, port);
6211
4.40k
    b1 = gen_portatom(cstate, TRAN_DSTPORT_OFFSET, port);
6212
4.40k
    b1 = gen_or(tmp, b1);
6213
4.40k
    break;
6214
6215
1
  default:
6216
1
    bpf_error(cstate, ERRSTR_INVALID_QUAL, dqkw(dir), tqkw(addr));
6217
    /*NOTREACHED*/
6218
5.10k
  }
6219
6220
5.10k
  return gen_port_common(cstate, proto, b1);
6221
5.10k
}
6222
6223
static struct block *
6224
gen_port_common(compiler_state_t *cstate, int proto, struct block *b1)
6225
5.10k
{
6226
5.10k
  struct block *b0, *tmp;
6227
6228
  /*
6229
   * ether proto ip
6230
   *
6231
   * For FDDI, RFC 1188 says that SNAP encapsulation is used,
6232
   * not LLC encapsulation with LLCSAP_IP.
6233
   *
6234
   * For IEEE 802 networks - which includes 802.5 token ring
6235
   * (which is what DLT_IEEE802 means) and 802.11 - RFC 1042
6236
   * says that SNAP encapsulation is used, not LLC encapsulation
6237
   * with LLCSAP_IP.
6238
   *
6239
   * For LLC-encapsulated ATM/"Classical IP", RFC 1483 and
6240
   * RFC 2225 say that SNAP encapsulation is used, not LLC
6241
   * encapsulation with LLCSAP_IP.
6242
   *
6243
   * So we always check for ETHERTYPE_IP.
6244
   *
6245
   * At the time of this writing all three L4 protocols the "port" and
6246
   * "portrange" primitives support (TCP, UDP and SCTP) have the source
6247
   * and the destination ports identically encoded in the transport
6248
   * protocol header.  So without a proto qualifier the only difference
6249
   * between the implemented cases is the protocol number and all other
6250
   * checks need to be made exactly once.
6251
   *
6252
   * If the expression syntax in future starts to support ports for
6253
   * another L4 protocol that has unsigned integer ports encoded using a
6254
   * different size and/or offset, this will require a different code.
6255
   */
6256
5.10k
  switch (proto) {
6257
449
  case IPPROTO_UDP:
6258
687
  case IPPROTO_TCP:
6259
921
  case IPPROTO_SCTP:
6260
921
    tmp = gen_ip_proto(cstate, (uint8_t)proto);
6261
921
    break;
6262
6263
4.18k
  case PROTO_UNDEF:
6264
4.18k
    tmp = gen_ip_proto(cstate, IPPROTO_SCTP);
6265
4.18k
    tmp = gen_or(gen_ip_proto(cstate, IPPROTO_UDP), tmp);
6266
4.18k
    tmp = gen_or(gen_ip_proto(cstate, IPPROTO_TCP), tmp);
6267
4.18k
    break;
6268
6269
0
  default:
6270
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "proto", proto);
6271
5.10k
  }
6272
  // Not a fragment other than the first fragment.
6273
5.10k
  b0 = gen_ipfrag(cstate);
6274
5.10k
  b0 = gen_and(tmp, b0);
6275
5.10k
  b1 = gen_and(b0, b1);
6276
  // "link proto \ip"
6277
5.10k
  return gen_and(gen_linktype(cstate, ETHERTYPE_IP), b1);
6278
5.10k
}
6279
6280
static struct block *
6281
gen_port6(compiler_state_t *cstate, const uint16_t port, const int proto,
6282
    const u_char dir, const u_char addr)
6283
5.08k
{
6284
5.08k
  struct block *b1, *tmp;
6285
6286
5.08k
  switch (dir) {
6287
81
  case Q_SRC:
6288
81
    b1 = gen_portatom6(cstate, TRAN_SRCPORT_OFFSET, port);
6289
81
    break;
6290
6291
472
  case Q_DST:
6292
472
    b1 = gen_portatom6(cstate, TRAN_DSTPORT_OFFSET, port);
6293
472
    break;
6294
6295
130
  case Q_AND:
6296
130
    tmp = gen_portatom6(cstate, TRAN_SRCPORT_OFFSET, port);
6297
130
    b1 = gen_portatom6(cstate, TRAN_DSTPORT_OFFSET, port);
6298
130
    b1 = gen_and(tmp, b1);
6299
130
    break;
6300
6301
4.33k
  case Q_DEFAULT:
6302
4.40k
  case Q_OR:
6303
4.40k
    tmp = gen_portatom6(cstate, TRAN_SRCPORT_OFFSET, port);
6304
4.40k
    b1 = gen_portatom6(cstate, TRAN_DSTPORT_OFFSET, port);
6305
4.40k
    b1 = gen_or(tmp, b1);
6306
4.40k
    break;
6307
6308
0
  default:
6309
0
    bpf_error(cstate, ERRSTR_INVALID_QUAL, dqkw(dir), tqkw(addr));
6310
    /*NOTREACHED*/
6311
5.08k
  }
6312
6313
5.08k
  return gen_port6_common(cstate, proto, b1);
6314
5.08k
}
6315
6316
static struct block *
6317
gen_port6_common(compiler_state_t *cstate, int proto, struct block *b1)
6318
5.08k
{
6319
5.08k
  struct block *tmp;
6320
6321
  // "ip6 proto 'ip_proto'"
6322
5.08k
  switch (proto) {
6323
437
  case IPPROTO_UDP:
6324
675
  case IPPROTO_TCP:
6325
909
  case IPPROTO_SCTP:
6326
909
    tmp = gen_ip6_proto(cstate, (uint8_t)proto);
6327
909
    break;
6328
6329
4.17k
  case PROTO_UNDEF:
6330
    // Same as in gen_port_common().
6331
4.17k
    tmp = gen_ip6_proto(cstate, IPPROTO_SCTP);
6332
4.17k
    tmp = gen_or(gen_ip6_proto(cstate, IPPROTO_UDP), tmp);
6333
4.17k
    tmp = gen_or(gen_ip6_proto(cstate, IPPROTO_TCP), tmp);
6334
4.17k
    break;
6335
6336
0
  default:
6337
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "proto", proto);
6338
5.08k
  }
6339
  // XXX - catch the first fragment of a fragmented packet?
6340
5.08k
  b1 = gen_and(tmp, b1);
6341
  // "link proto \ip6"
6342
5.08k
  return gen_and(gen_linktype(cstate, ETHERTYPE_IPV6), b1);
6343
5.08k
}
6344
6345
/* gen_portrange code */
6346
static struct block *
6347
gen_portrangeatom(compiler_state_t *cstate, u_int off, uint16_t v1,
6348
    uint16_t v2)
6349
0
{
6350
0
  if (v1 == v2)
6351
0
    return gen_portatom(cstate, off, v1);
6352
6353
0
  struct block *b1, *b2;
6354
6355
0
  b1 = gen_cmp_ge(cstate, OR_TRAN_IPV4, off, BPF_H, min(v1, v2));
6356
0
  b2 = gen_cmp_le(cstate, OR_TRAN_IPV4, off, BPF_H, max(v1, v2));
6357
6358
0
  return gen_and(b1, b2);
6359
0
}
6360
6361
static struct block *
6362
gen_portrange(compiler_state_t *cstate, uint16_t port1, uint16_t port2,
6363
    int proto, int dir)
6364
0
{
6365
0
  struct block *b1, *tmp;
6366
6367
0
  switch (dir) {
6368
0
  case Q_SRC:
6369
0
    b1 = gen_portrangeatom(cstate, TRAN_SRCPORT_OFFSET, port1, port2);
6370
0
    break;
6371
6372
0
  case Q_DST:
6373
0
    b1 = gen_portrangeatom(cstate, TRAN_DSTPORT_OFFSET, port1, port2);
6374
0
    break;
6375
6376
0
  case Q_AND:
6377
0
    tmp = gen_portrangeatom(cstate, TRAN_SRCPORT_OFFSET, port1, port2);
6378
0
    b1 = gen_portrangeatom(cstate, TRAN_DSTPORT_OFFSET, port1, port2);
6379
0
    b1 = gen_and(tmp, b1);
6380
0
    break;
6381
6382
0
  case Q_DEFAULT:
6383
0
  case Q_OR:
6384
0
    tmp = gen_portrangeatom(cstate, TRAN_SRCPORT_OFFSET, port1, port2);
6385
0
    b1 = gen_portrangeatom(cstate, TRAN_DSTPORT_OFFSET, port1, port2);
6386
0
    b1 = gen_or(tmp, b1);
6387
0
    break;
6388
6389
0
  default:
6390
0
    bpf_error(cstate, ERRSTR_INVALID_QUAL, dqkw(dir), "portrange");
6391
    /*NOTREACHED*/
6392
0
  }
6393
6394
0
  return gen_port_common(cstate, proto, b1);
6395
0
}
6396
6397
static struct block *
6398
gen_portrangeatom6(compiler_state_t *cstate, u_int off, uint16_t v1,
6399
    uint16_t v2)
6400
0
{
6401
0
  if (v1 == v2)
6402
0
    return gen_portatom6(cstate, off, v1);
6403
6404
0
  struct block *b1, *b2;
6405
6406
0
  b1 = gen_cmp_ge(cstate, OR_TRAN_IPV6, off, BPF_H, min(v1, v2));
6407
0
  b2 = gen_cmp_le(cstate, OR_TRAN_IPV6, off, BPF_H, max(v1, v2));
6408
6409
0
  return gen_and(b1, b2);
6410
0
}
6411
6412
static struct block *
6413
gen_portrange6(compiler_state_t *cstate, uint16_t port1, uint16_t port2,
6414
    int proto, int dir)
6415
0
{
6416
0
  struct block *b1, *tmp;
6417
6418
0
  switch (dir) {
6419
0
  case Q_SRC:
6420
0
    b1 = gen_portrangeatom6(cstate, TRAN_SRCPORT_OFFSET, port1, port2);
6421
0
    break;
6422
6423
0
  case Q_DST:
6424
0
    b1 = gen_portrangeatom6(cstate, TRAN_DSTPORT_OFFSET, port1, port2);
6425
0
    break;
6426
6427
0
  case Q_AND:
6428
0
    tmp = gen_portrangeatom6(cstate, TRAN_SRCPORT_OFFSET, port1, port2);
6429
0
    b1 = gen_portrangeatom6(cstate, TRAN_DSTPORT_OFFSET, port1, port2);
6430
0
    b1 = gen_and(tmp, b1);
6431
0
    break;
6432
6433
0
  case Q_DEFAULT:
6434
0
  case Q_OR:
6435
0
    tmp = gen_portrangeatom6(cstate, TRAN_SRCPORT_OFFSET, port1, port2);
6436
0
    b1 = gen_portrangeatom6(cstate, TRAN_DSTPORT_OFFSET, port1, port2);
6437
0
    b1 = gen_or(tmp, b1);
6438
0
    break;
6439
6440
0
  default:
6441
0
    bpf_error(cstate, ERRSTR_INVALID_QUAL, dqkw(dir), "portrange");
6442
    /*NOTREACHED*/
6443
0
  }
6444
6445
0
  return gen_port6_common(cstate, proto, b1);
6446
0
}
6447
6448
static int
6449
lookup_proto(compiler_state_t *cstate, const char *name, const struct qual q)
6450
603
{
6451
  /*
6452
   * Do not check here whether q.proto is valid (e.g. in "udp proto abc"
6453
   * fail the "abc", but not the "udp proto").  Likewise, do not check
6454
   * here whether the combination of q.proto and q.addr is valid (e.g.
6455
   * in "(link|iso|isis) protochain abc" fail the "abc", but not the
6456
   * "(link|iso|isis) protochain").
6457
   *
6458
   * On the one hand, this avoids a layering violation: gen_proto() and
6459
   * gen_protochain() implement the semantic checks.  On the other hand,
6460
   * the protocol name lookup error arguably is a problem smaller than
6461
   * the semantic error, hence the latter ought to be the reported cause
6462
   * of failure in both cases.  In future this potentially could be made
6463
   * more consistent by attempting the lookup after the semantic checks.
6464
   */
6465
6466
603
  int v = PROTO_UNDEF;
6467
603
  switch (q.proto) {
6468
6469
228
  case Q_DEFAULT:
6470
245
  case Q_IP:
6471
268
  case Q_IPV6:
6472
268
    v = pcap_nametoproto(name);
6473
268
    break;
6474
6475
228
  case Q_LINK:
6476
    /* XXX should look up h/w protocol type based on cstate->linktype */
6477
228
    v = pcap_nametoeproto(name);
6478
228
    if (v == PROTO_UNDEF)
6479
193
      v = pcap_nametollc(name);
6480
228
    break;
6481
6482
105
  case Q_ISO:
6483
105
    if (strcmp(name, "esis") == 0)
6484
18
      v = ISO9542_ESIS;
6485
87
    else if (strcmp(name, "isis") == 0)
6486
4
      v = ISO10589_ISIS;
6487
83
    else if (strcmp(name, "clnp") == 0)
6488
24
      v = ISO8473_CLNP;
6489
105
    break;
6490
6491
  // "isis proto" is a valid syntax, but it takes only numeric IDs.
6492
603
  }
6493
  // In theory, the only possible negative value of v is PROTO_UNDEF.
6494
603
  if (v >= 0)
6495
164
    return v;
6496
6497
439
  if (q.proto == Q_DEFAULT)
6498
228
    bpf_error(cstate, "unknown '%s' value '%s'",
6499
228
        tqkw(q.addr), name);
6500
211
  bpf_error(cstate, "unknown '%s %s' value '%s'",
6501
211
      pqkw(q.proto), tqkw(q.addr), name);
6502
439
}
6503
6504
#if !defined(NO_PROTOCHAIN)
6505
/*
6506
 * This primitive is non-directional by design, so the grammar does not allow
6507
 * to qualify it with a direction.
6508
 */
6509
static struct block *
6510
gen_protochain(compiler_state_t *cstate, bpf_u_int32 v, int proto)
6511
969
{
6512
969
  struct block *b0, *b;
6513
969
  struct slist *s[100];
6514
969
  int fix2, fix3, fix4, fix5;
6515
969
  int ahcheck, again, end;
6516
969
  int i, max;
6517
969
  int reg2 = alloc_reg(cstate);
6518
6519
969
  memset(s, 0, sizeof(s));
6520
969
  fix3 = fix4 = fix5 = 0;
6521
6522
969
  switch (proto) {
6523
363
  case Q_IP:
6524
740
  case Q_IPV6:
6525
740
    assert_maxval(cstate, "protocol number", v, UINT8_MAX);
6526
740
    break;
6527
227
  case Q_DEFAULT:
6528
227
    b0 = gen_protochain(cstate, v, Q_IP);
6529
227
    b = gen_protochain(cstate, v, Q_IPV6);
6530
227
    return gen_or(b0, b);
6531
1
  default:
6532
1
    bpf_error(cstate, ERRSTR_INVALID_QUAL, pqkw(proto), "protochain");
6533
    /*NOTREACHED*/
6534
969
  }
6535
6536
  /*
6537
   * We don't handle variable-length prefixes before the link-layer
6538
   * header, or variable-length link-layer headers, here yet.
6539
   * We might want to add BPF instructions to do the protochain
6540
   * work, to simplify that and, on platforms that have a BPF
6541
   * interpreter with the new instructions, let the filtering
6542
   * be done in the kernel.  (We already require a modified BPF
6543
   * engine to do the protochain stuff, to support backward
6544
   * branches, and backward branch support is unlikely to appear
6545
   * in kernel BPF engines.)
6546
   *
6547
   * Hence in the current implementation the gen_abs_offset_varpart()
6548
   * invocations incurred from gen_load_a() and gen_loadx_iphdrlen()
6549
   * below do not affect the offset because off_linkpl.is_variable == 0.
6550
   */
6551
707
  if (cstate->off_linkpl.is_variable)
6552
2
    bpf_error(cstate, "'protochain' not supported with variable length headers");
6553
6554
  /*
6555
   * To quote a comment in optimize.c:
6556
   *
6557
   * "These data structures are used in a Cocke and Schwartz style
6558
   * value numbering scheme.  Since the flowgraph is acyclic,
6559
   * exit values can be propagated from a node's predecessors
6560
   * provided it is uniquely defined."
6561
   *
6562
   * "Acyclic" means "no backward branches", which means "no
6563
   * loops", so we have to turn the optimizer off.
6564
   */
6565
705
  cstate->no_optimize = 1;
6566
6567
  /*
6568
   * s[0] is a dummy entry to protect other BPF insn from damage
6569
   * by s[fix] = foo with uninitialized variable "fix".  It is somewhat
6570
   * hard to find interdependency made by jump table fixup.
6571
   */
6572
705
  i = 0;
6573
705
  s[i] = new_stmt(cstate, 0); /*dummy*/
6574
705
  i++;
6575
6576
705
  switch (proto) {
6577
328
  case Q_IP:
6578
328
    b0 = gen_linktype(cstate, ETHERTYPE_IP);
6579
6580
    /* A = ip->ip_p */
6581
328
    s[i] = gen_load_a(cstate, OR_LINKPL, IPV4_PROTO_OFFSET, BPF_B);
6582
328
    i++;
6583
    /* X = ip->ip_hl << 2 */
6584
328
    s[i] = gen_loadx_iphdrlen(cstate);
6585
328
    i++;
6586
328
    break;
6587
6588
377
  case Q_IPV6:
6589
377
    b0 = gen_linktype(cstate, ETHERTYPE_IPV6);
6590
6591
    /* A = ip6->ip_nxt */
6592
377
    s[i] = gen_load_a(cstate, OR_LINKPL, IPV6_PROTO_OFFSET, BPF_B);
6593
377
    i++;
6594
    /* X = sizeof(struct ip6_hdr) */
6595
377
    s[i] = new_stmt(cstate, BPF_LDX|BPF_IMM);
6596
377
    s[i]->s.k = IP6_HDRLEN;
6597
377
    i++;
6598
377
    break;
6599
6600
0
  default:
6601
0
    bpf_error(cstate, "unsupported proto to gen_protochain");
6602
    /*NOTREACHED*/
6603
705
  }
6604
6605
  /* again: if (A == v) goto end; else fall through; */
6606
705
  again = i;
6607
705
  s[i] = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
6608
705
  s[i]->s.k = v;
6609
705
  s[i]->s.jt = NULL;   /*later*/
6610
705
  s[i]->s.jf = NULL;   /*update in next stmt*/
6611
705
  fix5 = i;
6612
705
  i++;
6613
6614
  /* if (A == IPPROTO_NONE) goto end */
6615
705
  s[i] = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
6616
705
  s[i]->s.jt = NULL; /*later*/
6617
705
  s[i]->s.jf = NULL; /*update in next stmt*/
6618
705
  s[i]->s.k = IPPROTO_NONE;
6619
705
  s[fix5]->s.jf = s[i];
6620
705
  fix2 = i;
6621
705
  i++;
6622
6623
705
  if (proto == Q_IPV6) {
6624
377
    int v6start, v6end, v6advance, j;
6625
6626
377
    v6start = i;
6627
    /* if (A == IPPROTO_HOPOPTS) goto v6advance */
6628
377
    s[i] = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
6629
377
    s[i]->s.jt = NULL; /*later*/
6630
377
    s[i]->s.jf = NULL; /*update in next stmt*/
6631
377
    s[i]->s.k = IPPROTO_HOPOPTS;
6632
377
    s[fix2]->s.jf = s[i];
6633
377
    i++;
6634
    /* if (A == IPPROTO_DSTOPTS) goto v6advance */
6635
377
    s[i - 1]->s.jf = s[i] = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
6636
377
    s[i]->s.jt = NULL; /*later*/
6637
377
    s[i]->s.jf = NULL; /*update in next stmt*/
6638
377
    s[i]->s.k = IPPROTO_DSTOPTS;
6639
377
    i++;
6640
    /* if (A == IPPROTO_ROUTING) goto v6advance */
6641
377
    s[i - 1]->s.jf = s[i] = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
6642
377
    s[i]->s.jt = NULL; /*later*/
6643
377
    s[i]->s.jf = NULL; /*update in next stmt*/
6644
377
    s[i]->s.k = IPPROTO_ROUTING;
6645
377
    i++;
6646
    /* if (A == IPPROTO_FRAGMENT) goto v6advance; else goto ahcheck; */
6647
377
    s[i - 1]->s.jf = s[i] = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
6648
377
    s[i]->s.jt = NULL; /*later*/
6649
377
    s[i]->s.jf = NULL; /*later*/
6650
377
    s[i]->s.k = IPPROTO_FRAGMENT;
6651
377
    fix3 = i;
6652
377
    v6end = i;
6653
377
    i++;
6654
6655
    /* v6advance: */
6656
377
    v6advance = i;
6657
6658
    /*
6659
     * in short,
6660
     * A = P[X + packet head];
6661
     * X = X + (P[X + packet head + 1] + 1) * 8;
6662
     */
6663
    /* A = P[X + packet head] */
6664
377
    s[i] = new_stmt(cstate, BPF_LD|BPF_IND|BPF_B);
6665
377
    s[i]->s.k = cstate->off_linkpl.constant_part + cstate->off_nl;
6666
377
    i++;
6667
    /* MEM[reg2] = A */
6668
377
    s[i] = new_stmt(cstate, BPF_ST);
6669
377
    s[i]->s.k = reg2;
6670
377
    i++;
6671
    /* A = P[X + packet head + 1]; */
6672
377
    s[i] = new_stmt(cstate, BPF_LD|BPF_IND|BPF_B);
6673
377
    s[i]->s.k = cstate->off_linkpl.constant_part + cstate->off_nl + 1;
6674
377
    i++;
6675
    /* A += 1 */
6676
377
    s[i] = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
6677
377
    s[i]->s.k = 1;
6678
377
    i++;
6679
    /* A *= 8 */
6680
377
    s[i] = new_stmt(cstate, BPF_ALU|BPF_MUL|BPF_K);
6681
377
    s[i]->s.k = 8;
6682
377
    i++;
6683
    /* A += X */
6684
377
    s[i] = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_X);
6685
377
    s[i]->s.k = 0;
6686
377
    i++;
6687
    /* X = A; */
6688
377
    s[i] = new_stmt(cstate, BPF_MISC|BPF_TAX);
6689
377
    i++;
6690
    /* A = MEM[reg2] */
6691
377
    s[i] = new_stmt(cstate, BPF_LD|BPF_MEM);
6692
377
    s[i]->s.k = reg2;
6693
377
    i++;
6694
6695
    /* goto again; (must use BPF_JA for backward jump) */
6696
377
    s[i] = new_stmt(cstate, JMP(BPF_JA, BPF_K));
6697
377
    s[i]->s.k = again - i - 1;
6698
377
    s[i - 1]->s.jf = s[i];
6699
377
    i++;
6700
6701
    /* fixup */
6702
1.88k
    for (j = v6start; j <= v6end; j++)
6703
1.50k
      s[j]->s.jt = s[v6advance];
6704
377
  } else {
6705
    /* nop */
6706
328
    s[i] = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
6707
328
    s[i]->s.k = 0;
6708
328
    s[fix2]->s.jf = s[i];
6709
328
    i++;
6710
328
  }
6711
6712
  /* ahcheck: */
6713
705
  ahcheck = i;
6714
  /* if (A == IPPROTO_AH) then fall through; else goto end; */
6715
705
  s[i] = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
6716
705
  s[i]->s.jt = NULL; /*later*/
6717
705
  s[i]->s.jf = NULL; /*later*/
6718
705
  s[i]->s.k = IPPROTO_AH;
6719
705
  if (fix3)
6720
377
    s[fix3]->s.jf = s[ahcheck];
6721
705
  fix4 = i;
6722
705
  i++;
6723
6724
  /*
6725
   * in short,
6726
   * A = P[X];
6727
   * X = X + (P[X + 1] + 2) * 4;
6728
   */
6729
  /* A = P[X + packet head]; */
6730
705
  s[i] = new_stmt(cstate, BPF_LD|BPF_IND|BPF_B);
6731
705
  s[i]->s.k = cstate->off_linkpl.constant_part + cstate->off_nl;
6732
705
  s[i - 1]->s.jt = s[i];
6733
705
  i++;
6734
  /* MEM[reg2] = A */
6735
705
  s[i] = new_stmt(cstate, BPF_ST);
6736
705
  s[i]->s.k = reg2;
6737
705
  i++;
6738
  /* A = X */
6739
705
  s[i - 1]->s.jt = s[i] = new_stmt(cstate, BPF_MISC|BPF_TXA);
6740
705
  i++;
6741
  /* A += 1 */
6742
705
  s[i] = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
6743
705
  s[i]->s.k = 1;
6744
705
  i++;
6745
  /* X = A */
6746
705
  s[i] = new_stmt(cstate, BPF_MISC|BPF_TAX);
6747
705
  i++;
6748
  /* A = P[X + packet head] */
6749
705
  s[i] = new_stmt(cstate, BPF_LD|BPF_IND|BPF_B);
6750
705
  s[i]->s.k = cstate->off_linkpl.constant_part + cstate->off_nl;
6751
705
  i++;
6752
  /* A += 2 */
6753
705
  s[i] = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
6754
705
  s[i]->s.k = 2;
6755
705
  i++;
6756
  /* A *= 4 */
6757
705
  s[i] = new_stmt(cstate, BPF_ALU|BPF_MUL|BPF_K);
6758
705
  s[i]->s.k = 4;
6759
705
  i++;
6760
  /* X = A; */
6761
705
  s[i] = new_stmt(cstate, BPF_MISC|BPF_TAX);
6762
705
  i++;
6763
  /* A = MEM[reg2] */
6764
705
  s[i] = new_stmt(cstate, BPF_LD|BPF_MEM);
6765
705
  s[i]->s.k = reg2;
6766
705
  i++;
6767
6768
  /* goto again; (must use BPF_JA for backward jump) */
6769
705
  s[i] = new_stmt(cstate, JMP(BPF_JA, BPF_K));
6770
705
  s[i]->s.k = again - i - 1;
6771
705
  i++;
6772
6773
  /* end: nop */
6774
705
  end = i;
6775
705
  s[i] = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
6776
705
  s[i]->s.k = 0;
6777
705
  s[fix2]->s.jt = s[end];
6778
705
  s[fix4]->s.jf = s[end];
6779
705
  s[fix5]->s.jt = s[end];
6780
705
  i++;
6781
6782
  /*
6783
   * make slist chain
6784
   */
6785
705
  max = i;
6786
17.9k
  for (i = 0; i < max - 1; i++)
6787
17.2k
    s[i]->next = s[i + 1];
6788
705
  s[max - 1]->next = NULL;
6789
6790
  /*
6791
   * emit final check
6792
   * Remember, s[0] is dummy.
6793
   */
6794
705
  b = gen_jmp_k(cstate, BPF_JEQ, v, s[1]);
6795
6796
705
  free_reg(cstate, reg2);
6797
6798
705
  return gen_and(b0, b);
6799
705
}
6800
#endif /* !defined(NO_PROTOCHAIN) */
6801
6802
/*
6803
 * Generate code that checks whether the packet is a packet for protocol
6804
 * <proto> and whether the type field in that protocol's header has
6805
 * the value <v>, e.g. if <proto> is Q_IP, it checks whether it's an
6806
 * IP packet and checks the protocol number in the IP header against <v>.
6807
 *
6808
 * If <proto> is Q_DEFAULT, i.e. just "proto" was specified, it checks
6809
 * against Q_IP and Q_IPV6.
6810
 *
6811
 * This primitive is non-directional by design, so the grammar does not allow
6812
 * to qualify it with a direction.
6813
 */
6814
static struct block *
6815
gen_proto(compiler_state_t *cstate, bpf_u_int32 v, int proto)
6816
43.5k
{
6817
43.5k
  struct block *b0, *b1;
6818
43.5k
  struct block *b2;
6819
6820
43.5k
  switch (proto) {
6821
964
  case Q_DEFAULT:
6822
964
    b0 = gen_proto(cstate, v, Q_IP);
6823
964
    b1 = gen_proto(cstate, v, Q_IPV6);
6824
964
    return gen_or(b0, b1);
6825
6826
2.02k
  case Q_LINK:
6827
2.02k
    return gen_linktype(cstate, v);
6828
6829
1.33k
  case Q_IP:
6830
1.33k
    assert_maxval(cstate, "protocol number", v, UINT8_MAX);
6831
    /*
6832
     * For FDDI, RFC 1188 says that SNAP encapsulation is used,
6833
     * not LLC encapsulation with LLCSAP_IP.
6834
     *
6835
     * For IEEE 802 networks - which includes 802.5 token ring
6836
     * (which is what DLT_IEEE802 means) and 802.11 - RFC 1042
6837
     * says that SNAP encapsulation is used, not LLC encapsulation
6838
     * with LLCSAP_IP.
6839
     *
6840
     * For LLC-encapsulated ATM/"Classical IP", RFC 1483 and
6841
     * RFC 2225 say that SNAP encapsulation is used, not LLC
6842
     * encapsulation with LLCSAP_IP.
6843
     *
6844
     * So we always check for ETHERTYPE_IP.
6845
     */
6846
1.33k
    b0 = gen_linktype(cstate, ETHERTYPE_IP);
6847
    // 0 <= v <= UINT8_MAX
6848
1.33k
    b1 = gen_ip_proto(cstate, (uint8_t)v);
6849
1.33k
    return gen_and(b0, b1);
6850
6851
1.09k
  case Q_IPV6:
6852
1.09k
    assert_maxval(cstate, "protocol number", v, UINT8_MAX);
6853
1.09k
    b0 = gen_linktype(cstate, ETHERTYPE_IPV6);
6854
    /*
6855
     * Also check for a fragment header before the final
6856
     * header.
6857
     */
6858
1.09k
    b2 = gen_ip6_proto(cstate, IPPROTO_FRAGMENT);
6859
1.09k
    b1 = gen_cmp(cstate, OR_LINKPL, IP6_HDRLEN, BPF_B, v);
6860
1.09k
    b1 = gen_and(b2, b1);
6861
    // 0 <= v <= UINT8_MAX
6862
1.09k
    b2 = gen_ip6_proto(cstate, (uint8_t)v);
6863
1.09k
    b1 = gen_or(b2, b1);
6864
1.09k
    return gen_and(b0, b1);
6865
6866
19.1k
  case Q_ISO:
6867
19.1k
    assert_maxval(cstate, "ISO protocol", v, UINT8_MAX);
6868
19.1k
    switch (cstate->linktype) {
6869
6870
251
    case DLT_FRELAY:
6871
      /*
6872
       * Frame Relay packets typically have an OSI
6873
       * NLPID at the beginning; "gen_linktype(cstate, LLCSAP_ISONS)"
6874
       * generates code to check for all the OSI
6875
       * NLPIDs, so calling it and then adding a check
6876
       * for the particular NLPID for which we're
6877
       * looking is bogus, as we can just check for
6878
       * the NLPID.
6879
       *
6880
       * XXX - what about SNAP-encapsulated frames?
6881
       */
6882
251
      return gen_frelay_nlpid(cstate, (uint8_t)v);
6883
      /*NOTREACHED*/
6884
6885
334
    case DLT_C_HDLC:
6886
579
    case DLT_HDLC:
6887
      /*
6888
       * Cisco uses an EtherType lookalike - for OSI,
6889
       * it's 0xfefe.
6890
       */
6891
579
      b0 = gen_linktype(cstate, LLCSAP_ISONS<<8 | LLCSAP_ISONS);
6892
      /* OSI in C-HDLC is stuffed with a fudge byte */
6893
579
      b1 = gen_cmp(cstate, OR_LINKPL_NOSNAP, 1, BPF_B, v);
6894
579
      return gen_and(b0, b1);
6895
6896
18.3k
    default:
6897
18.3k
      b0 = gen_linktype(cstate, LLCSAP_ISONS);
6898
18.3k
      b1 = gen_cmp(cstate, OR_LINKPL_NOSNAP, 0, BPF_B, v);
6899
18.3k
      return gen_and(b0, b1);
6900
19.1k
    }
6901
6902
18.9k
  case Q_ISIS:
6903
18.9k
    assert_maxval(cstate, "IS-IS PDU type", v, ISIS_PDU_TYPE_MAX);
6904
18.9k
    b0 = gen_proto(cstate, ISO10589_ISIS, Q_ISO);
6905
    /*
6906
     * 4 is the offset of the PDU type relative to the IS-IS
6907
     * header.
6908
     * Except when it is not, see above.
6909
     */
6910
18.9k
    unsigned pdu_type_offset;
6911
18.9k
    switch (cstate->linktype) {
6912
326
    case DLT_C_HDLC:
6913
568
    case DLT_HDLC:
6914
568
      pdu_type_offset = 5;
6915
568
      break;
6916
18.3k
    default:
6917
18.3k
      pdu_type_offset = 4;
6918
18.9k
    }
6919
18.9k
    b1 = gen_mcmp(cstate, OR_LINKPL_NOSNAP, pdu_type_offset, BPF_B,
6920
18.9k
        v, ISIS_PDU_TYPE_MAX);
6921
18.9k
    return gen_and(b0, b1);
6922
43.5k
  }
6923
1
  bpf_error(cstate, ERRSTR_INVALID_QUAL, pqkw(proto), "proto");
6924
  /*NOTREACHED*/
6925
43.5k
}
6926
6927
/*
6928
 * Convert a non-numeric name to a port number.
6929
 */
6930
static int
6931
nametoport(compiler_state_t *cstate, const char *name, int ipproto)
6932
0
{
6933
0
  struct addrinfo hints, *res, *ai;
6934
0
  int error;
6935
0
  struct sockaddr_in *in4;
6936
0
  struct sockaddr_in6 *in6;
6937
0
  int port = -1;
6938
6939
  /*
6940
   * We check for both TCP and UDP in case there are
6941
   * ambiguous entries.
6942
   */
6943
0
  memset(&hints, 0, sizeof(hints));
6944
0
  hints.ai_family = PF_UNSPEC;
6945
0
  hints.ai_socktype = (ipproto == IPPROTO_TCP) ? SOCK_STREAM : SOCK_DGRAM;
6946
0
  hints.ai_protocol = ipproto;
6947
0
  error = getaddrinfo(NULL, name, &hints, &res);
6948
0
  if (error != 0) {
6949
0
    switch (error) {
6950
6951
0
    case EAI_NONAME:
6952
0
    case EAI_SERVICE:
6953
      /*
6954
       * No such port.  Just return -1.
6955
       */
6956
0
      break;
6957
6958
0
#ifdef EAI_SYSTEM
6959
0
    case EAI_SYSTEM:
6960
      /*
6961
       * We don't use strerror() because it's not
6962
       * guaranteed to be thread-safe on all platforms
6963
       * (probably because it might use a non-thread-local
6964
       * buffer into which to format an error message
6965
       * if the error code isn't one for which it has
6966
       * a canned string; three cheers for C string
6967
       * handling).
6968
       */
6969
0
      bpf_set_error(cstate, "getaddrinfo(\"%s\" fails with system error: %d",
6970
0
          name, errno);
6971
0
      port = -2;  /* a real error */
6972
0
      break;
6973
0
#endif
6974
6975
0
    default:
6976
      /*
6977
       * This is a real error, not just "there's
6978
       * no such service name".
6979
       *
6980
       * We don't use gai_strerror() because it's not
6981
       * guaranteed to be thread-safe on all platforms
6982
       * (probably because it might use a non-thread-local
6983
       * buffer into which to format an error message
6984
       * if the error code isn't one for which it has
6985
       * a canned string; three cheers for C string
6986
       * handling).
6987
       */
6988
0
      bpf_set_error(cstate, "getaddrinfo(\"%s\") fails with error: %d",
6989
0
          name, error);
6990
0
      port = -2;  /* a real error */
6991
0
      break;
6992
0
    }
6993
0
  } else {
6994
    /*
6995
     * OK, we found it.  Did it find anything?
6996
     */
6997
0
    for (ai = res; ai != NULL; ai = ai->ai_next) {
6998
      /*
6999
       * Does it have an address?
7000
       */
7001
0
      if (ai->ai_addr != NULL) {
7002
        /*
7003
         * Yes.  Get a port number; we're done.
7004
         */
7005
0
        if (ai->ai_addr->sa_family == AF_INET) {
7006
0
          in4 = (struct sockaddr_in *)ai->ai_addr;
7007
0
          port = ntohs(in4->sin_port);
7008
0
          break;
7009
0
        }
7010
0
        if (ai->ai_addr->sa_family == AF_INET6) {
7011
0
          in6 = (struct sockaddr_in6 *)ai->ai_addr;
7012
0
          port = ntohs(in6->sin6_port);
7013
0
          break;
7014
0
        }
7015
0
      }
7016
0
    }
7017
0
    freeaddrinfo(res);
7018
0
  }
7019
0
  return port;
7020
0
}
7021
7022
/*
7023
 * Convert a string to a port number.
7024
 */
7025
static bpf_u_int32
7026
stringtoport(compiler_state_t *cstate, const char *string, size_t string_size,
7027
    int *proto)
7028
0
{
7029
0
  stoulen_ret ret;
7030
0
  char *cpy;
7031
0
  bpf_u_int32 val;
7032
0
  int tcp_port = -1;
7033
0
  int udp_port = -1;
7034
7035
  /*
7036
   * See if it's a number.
7037
   */
7038
0
  ret = stoulen(string, string_size, &val, cstate);
7039
0
  switch (ret) {
7040
7041
0
  case STOULEN_OK:
7042
    /* Unknown port type - it's just a number. */
7043
0
    *proto = PROTO_UNDEF;
7044
0
    break;
7045
7046
0
  case STOULEN_NOT_OCTAL_NUMBER:
7047
0
  case STOULEN_NOT_HEX_NUMBER:
7048
0
  case STOULEN_NOT_DECIMAL_NUMBER:
7049
    /*
7050
     * Not a valid number; try looking it up as a port.
7051
     */
7052
0
    cpy = malloc(string_size + 1);  /* +1 for terminating '\0' */
7053
0
    if (cpy == NULL) {
7054
0
      bpf_set_error(cstate, "%s: out of memory", __func__);
7055
0
      longjmp(cstate->top_ctx, 1);
7056
      /*NOTREACHED*/
7057
0
    }
7058
0
    memcpy(cpy, string, string_size);
7059
0
    cpy[string_size] = '\0';
7060
0
    tcp_port = nametoport(cstate, cpy, IPPROTO_TCP);
7061
0
    if (tcp_port == -2) {
7062
      /*
7063
       * We got a hard error; the error string has
7064
       * already been set.
7065
       */
7066
0
      free(cpy);
7067
0
      longjmp(cstate->top_ctx, 1);
7068
      /*NOTREACHED*/
7069
0
    }
7070
0
    udp_port = nametoport(cstate, cpy, IPPROTO_UDP);
7071
0
    if (udp_port == -2) {
7072
      /*
7073
       * We got a hard error; the error string has
7074
       * already been set.
7075
       */
7076
0
      free(cpy);
7077
0
      longjmp(cstate->top_ctx, 1);
7078
      /*NOTREACHED*/
7079
0
    }
7080
7081
    /*
7082
     * We need to check /etc/services for ambiguous entries.
7083
     * If we find an ambiguous entry, and it has the
7084
     * same port number, change the proto to PROTO_UNDEF
7085
     * so both TCP and UDP will be checked.
7086
     */
7087
0
    if (tcp_port >= 0) {
7088
0
      val = (bpf_u_int32)tcp_port;
7089
0
      *proto = IPPROTO_TCP;
7090
0
      if (udp_port >= 0) {
7091
0
        if (udp_port == tcp_port)
7092
0
          *proto = PROTO_UNDEF;
7093
#ifdef notdef
7094
        else
7095
          /* Can't handle ambiguous names that refer
7096
             to different port numbers. */
7097
          warning("ambiguous port %s in /etc/services",
7098
            cpy);
7099
#endif
7100
0
      }
7101
0
      free(cpy);
7102
0
      break;
7103
0
    }
7104
0
    if (udp_port >= 0) {
7105
0
      val = (bpf_u_int32)udp_port;
7106
0
      *proto = IPPROTO_UDP;
7107
0
      free(cpy);
7108
0
      break;
7109
0
    }
7110
0
    bpf_set_error(cstate, "'%s' is not a valid port", cpy);
7111
0
    free(cpy);
7112
0
    longjmp(cstate->top_ctx, 1);
7113
    /*NOTREACHED*/
7114
#ifdef _AIX
7115
    PCAP_UNREACHABLE
7116
#endif /* _AIX */
7117
7118
0
  case STOULEN_ERROR:
7119
    /* Error already set. */
7120
0
    longjmp(cstate->top_ctx, 1);
7121
    /*NOTREACHED*/
7122
#ifdef _AIX
7123
    PCAP_UNREACHABLE
7124
#endif /* _AIX */
7125
7126
0
  default:
7127
    /* Should not happen */
7128
0
    bpf_set_error(cstate, "stoulen returned %d - this should not happen", ret);
7129
0
    longjmp(cstate->top_ctx, 1);
7130
    /*NOTREACHED*/
7131
0
  }
7132
0
  return (val);
7133
0
}
7134
7135
/*
7136
 * Convert a string in the form PPP-PPP, which correspond to ports, to
7137
 * a starting and ending port in a port range.
7138
 */
7139
static void
7140
stringtoportrange(compiler_state_t *cstate, const char *string,
7141
    bpf_u_int32 *port1, bpf_u_int32 *port2, int *proto)
7142
0
{
7143
0
  const char *hyphen_off;
7144
0
  const char *first, *second;
7145
0
  size_t first_size, second_size;
7146
0
  int save_proto;
7147
7148
0
  if ((hyphen_off = strchr(string, '-')) == NULL)
7149
0
    bpf_error(cstate, "port range '%s' contains no hyphen", string);
7150
7151
  /*
7152
   * Make sure there are no other hyphens.
7153
   *
7154
   * XXX - we support named ports, but there are some port names
7155
   * in /etc/services that include hyphens, so this would rule
7156
   * that out.
7157
   */
7158
0
  if (strchr(hyphen_off + 1, '-') != NULL)
7159
0
    bpf_error(cstate, "port range '%s' contains more than one hyphen",
7160
0
        string);
7161
7162
  /*
7163
   * Get the length of the first port.
7164
   */
7165
0
  first = string;
7166
0
  first_size = hyphen_off - string;
7167
0
  if (first_size == 0) {
7168
    /* Range of "-port", which we don't support. */
7169
0
    bpf_error(cstate, "port range '%s' has no starting port", string);
7170
0
  }
7171
7172
  /*
7173
   * Try to convert it to a port.
7174
   */
7175
0
  *port1 = stringtoport(cstate, first, first_size, proto);
7176
0
  save_proto = *proto;
7177
7178
  /*
7179
   * Get the length of the second port.
7180
   */
7181
0
  second = hyphen_off + 1;
7182
0
  second_size = strlen(second);
7183
0
  if (second_size == 0) {
7184
    /* Range of "port-", which we don't support. */
7185
0
    bpf_error(cstate, "port range '%s' has no ending port", string);
7186
0
  }
7187
7188
  /*
7189
   * Try to convert it to a port.
7190
   */
7191
0
  *port2 = stringtoport(cstate, second, second_size, proto);
7192
0
  if (*proto != save_proto)
7193
0
    *proto = PROTO_UNDEF;
7194
0
}
7195
7196
struct block *
7197
gen_scode(compiler_state_t *cstate, const char *name, struct qual q)
7198
1.78k
{
7199
1.78k
  int proto = q.proto;
7200
1.78k
  int dir = q.dir;
7201
1.78k
  bpf_u_int32 mask, addr;
7202
1.78k
  int port, real_proto;
7203
1.78k
  bpf_u_int32 port1, port2;
7204
7205
  /*
7206
   * Catch errors reported by us and routines below us, and return NULL
7207
   * on an error.
7208
   */
7209
1.78k
  if (setjmp(cstate->top_ctx))
7210
1.02k
    return (NULL);
7211
7212
762
  if (q.proto == Q_DECNET) {
7213
    /*
7214
     * A long time ago on Ultrix libpcap supported translation of
7215
     * DECnet host names into DECnet addresses, but this feature
7216
     * is history now.  The current implementation does not define
7217
     * any primitives that have "decnet" as the protocol qualifier
7218
     * and a name as the ID.
7219
     */
7220
6
    bpf_error(cstate, ERRSTR_INVALID_QUAL, "decnet",
7221
6
              tqkw(q.addr == Q_DEFAULT ? Q_HOST : q.addr));
7222
6
  }
7223
7224
756
  struct block *b, *b6;
7225
756
  switch (q.addr) {
7226
7227
7
  case Q_NET:
7228
7
    addr = pcap_nametonetaddr(name);
7229
7
    if (addr == 0)
7230
7
      bpf_error(cstate, "unknown network '%s'", name);
7231
    /* Left justify network addr and calculate its network mask */
7232
0
    mask = 0xffffffff;
7233
0
    while (addr && (addr & 0xff000000) == 0) {
7234
0
      addr <<= 8;
7235
0
      mask <<= 8;
7236
0
    }
7237
0
    return gen_host(cstate, 1, &addr, &mask, q.proto, q.dir, 0,
7238
0
                    "net <IPv4 network name>");
7239
7240
226
  case Q_DEFAULT:
7241
353
  case Q_HOST:
7242
353
    if (proto == Q_LINK) {
7243
84
      return gen_mac48host_byname(cstate, name, q.dir, "link host NAME");
7244
269
    } else {
7245
269
      return gen_host46_byname(cstate, name, q.proto,
7246
269
          q.proto, q.dir, 0);
7247
269
    }
7248
7249
622
  case Q_PORT:
7250
622
    (void)port_pq_to_ipproto(cstate, proto, "port"); // validate only
7251
622
    if (pcap_nametoport(name, &port, &real_proto) == 0)
7252
254
      bpf_error(cstate, "unknown port '%s'", name);
7253
368
    if (proto == Q_UDP) {
7254
53
      if (real_proto == IPPROTO_TCP)
7255
0
        bpf_error(cstate, "port '%s' is tcp", name);
7256
53
      else if (real_proto == IPPROTO_SCTP)
7257
0
        bpf_error(cstate, "port '%s' is sctp", name);
7258
53
      else
7259
        /* override PROTO_UNDEF */
7260
53
        real_proto = IPPROTO_UDP;
7261
53
    }
7262
368
    if (proto == Q_TCP) {
7263
49
      if (real_proto == IPPROTO_UDP)
7264
0
        bpf_error(cstate, "port '%s' is udp", name);
7265
7266
49
      else if (real_proto == IPPROTO_SCTP)
7267
0
        bpf_error(cstate, "port '%s' is sctp", name);
7268
49
      else
7269
        /* override PROTO_UNDEF */
7270
49
        real_proto = IPPROTO_TCP;
7271
49
    }
7272
368
    if (proto == Q_SCTP) {
7273
42
      if (real_proto == IPPROTO_UDP)
7274
0
        bpf_error(cstate, "port '%s' is udp", name);
7275
7276
42
      else if (real_proto == IPPROTO_TCP)
7277
0
        bpf_error(cstate, "port '%s' is tcp", name);
7278
42
      else
7279
        /* override PROTO_UNDEF */
7280
42
        real_proto = IPPROTO_SCTP;
7281
42
    }
7282
7283
    /*
7284
     * These two checks are redundant at this point: here name is
7285
     * a string that the lexer does not recognize as a number
7286
     * hence did not attempt stoulen(), pcap_nametoport() does not
7287
     * use stoulen() and has successfully translated the string to
7288
     * an uint16_t value using getaddrinfo().
7289
     */
7290
368
    if (port < 0)
7291
0
      bpf_error(cstate, "illegal port number %d < 0", port);
7292
368
    if (port > 65535)
7293
0
      bpf_error(cstate, "illegal port number %d > 65535", port);
7294
7295
    // real_proto can be PROTO_UNDEF
7296
368
    b = gen_port(cstate, (uint16_t)port, real_proto, q.dir, q.addr);
7297
368
    b6 = gen_port6(cstate, (uint16_t)port, real_proto, q.dir, q.addr);
7298
368
    return gen_or(b6, b);
7299
7300
0
  case Q_PORTRANGE:
7301
0
    (void)port_pq_to_ipproto(cstate, proto, "portrange"); // validate only
7302
0
    stringtoportrange(cstate, name, &port1, &port2, &real_proto);
7303
0
    if (proto == Q_UDP) {
7304
0
      if (real_proto == IPPROTO_TCP)
7305
0
        bpf_error(cstate, "port in range '%s' is tcp", name);
7306
0
      else if (real_proto == IPPROTO_SCTP)
7307
0
        bpf_error(cstate, "port in range '%s' is sctp", name);
7308
0
      else
7309
        /* override PROTO_UNDEF */
7310
0
        real_proto = IPPROTO_UDP;
7311
0
    }
7312
0
    if (proto == Q_TCP) {
7313
0
      if (real_proto == IPPROTO_UDP)
7314
0
        bpf_error(cstate, "port in range '%s' is udp", name);
7315
0
      else if (real_proto == IPPROTO_SCTP)
7316
0
        bpf_error(cstate, "port in range '%s' is sctp", name);
7317
0
      else
7318
        /* override PROTO_UNDEF */
7319
0
        real_proto = IPPROTO_TCP;
7320
0
    }
7321
0
    if (proto == Q_SCTP) {
7322
0
      if (real_proto == IPPROTO_UDP)
7323
0
        bpf_error(cstate, "port in range '%s' is udp", name);
7324
0
      else if (real_proto == IPPROTO_TCP)
7325
0
        bpf_error(cstate, "port in range '%s' is tcp", name);
7326
0
      else
7327
        /* override PROTO_UNDEF */
7328
0
        real_proto = IPPROTO_SCTP;
7329
0
    }
7330
7331
    /*
7332
     * When name is a string of the form "str1-str2", these two
7333
     * checks are redundant at this point: in both stringtoport()
7334
     * invocations stoulen() has rejected the argument and
7335
     * getaddrinfo() has successfully translated it to an uint16_t
7336
     * value.
7337
     *
7338
     * When name is a string of the form "num1-num2", "num-str" or
7339
     * "str-num", these two checks are necessary: in at least one
7340
     * stringtoport() invocation stoulen() can return any uint32_t
7341
     * value if it has accepted the argument.
7342
     */
7343
0
    assert_maxval(cstate, "port number", port1, UINT16_MAX);
7344
0
    assert_maxval(cstate, "port number", port2, UINT16_MAX);
7345
7346
    // real_proto can be PROTO_UNDEF
7347
0
    b = gen_portrange(cstate, (uint16_t)port1, (uint16_t)port2,
7348
0
        real_proto, dir);
7349
0
    b6 = gen_portrange6(cstate, (uint16_t)port1, (uint16_t)port2,
7350
0
        real_proto, dir);
7351
0
    return gen_or(b6, b);
7352
7353
0
  case Q_GATEWAY:
7354
0
    return gen_gateway(cstate, name, q.proto);
7355
7356
544
  case Q_PROTO:
7357
544
    return gen_proto(cstate, lookup_proto(cstate, name, q), proto);
7358
7359
0
#if !defined(NO_PROTOCHAIN)
7360
59
  case Q_PROTOCHAIN:
7361
59
    return gen_protochain(cstate, lookup_proto(cstate, name, q), proto);
7362
0
#endif /* !defined(NO_PROTOCHAIN) */
7363
7364
192
  case Q_UNDEF:
7365
192
    syntax(cstate);
7366
    /*NOTREACHED*/
7367
756
  }
7368
0
  bpf_error(cstate, ERRSTR_INVALID_QUAL, tqkw(q.addr), name);
7369
  /*NOTREACHED*/
7370
756
}
7371
7372
struct block *
7373
gen_mcode(compiler_state_t *cstate, const char *s1, const char *s2,
7374
    bpf_u_int32 masklen, struct qual q)
7375
219
{
7376
219
  int nlen, mlen;
7377
219
  bpf_u_int32 n, m;
7378
219
  uint64_t m64;
7379
7380
  /*
7381
   * Catch errors reported by us and routines below us, and return NULL
7382
   * on an error.
7383
   */
7384
219
  if (setjmp(cstate->top_ctx))
7385
74
    return (NULL);
7386
7387
145
  if (q.proto == Q_DECNET) {
7388
    /*
7389
     * libpcap has never defined any primitives that have "decnet"
7390
     * as the protocol qualifier and an IPv4 network with a
7391
     * netmask as the ID.
7392
     */
7393
2
    bpf_error(cstate, ERRSTR_INVALID_QUAL, "decnet",
7394
2
              tqkw(q.addr == Q_DEFAULT ? Q_HOST : q.addr));
7395
2
  }
7396
7397
143
  nlen = pcapint_atoin(s1, &n);
7398
143
  if (nlen < 0)
7399
1
    bpf_error(cstate, ERRSTR_INVALID_IPV4_ADDR, s1);
7400
  /* Promote short ipaddr */
7401
142
  n <<= 32 - nlen;
7402
7403
142
  char idstr[PCAP_BUF_SIZE];
7404
142
  if (s2 != NULL) {
7405
0
    mlen = pcapint_atoin(s2, &m);
7406
0
    if (mlen < 0)
7407
0
      bpf_error(cstate, ERRSTR_INVALID_IPV4_ADDR, s2);
7408
    /* Promote short ipaddr */
7409
0
    m <<= 32 - mlen;
7410
0
    snprintf(idstr, sizeof(idstr), "%s mask %s", s1, s2);
7411
142
  } else {
7412
    /* Convert mask len to mask */
7413
142
    assert_maxval(cstate, "netmask length", masklen, 32);
7414
142
    m64 = UINT64_C(0xffffffff) << (32 - masklen);
7415
142
    m = (bpf_u_int32)m64;
7416
142
    snprintf(idstr, sizeof(idstr), "%s/%u", s1, masklen);
7417
142
  }
7418
142
  if ((n & ~m) != 0)
7419
43
    bpf_error(cstate, "non-network bits set in \"%s\"", idstr);
7420
7421
99
  switch (q.addr) {
7422
7423
147
  case Q_NET:
7424
147
    return gen_host(cstate, 1, &n, &m, q.proto, q.dir, 0,
7425
147
                    "net <IPv4 prefix>");
7426
7427
2
  default:
7428
2
    bpf_error(cstate, ERRSTR_INVALID_QUAL, tqkw(q.addr), idstr);
7429
    /*NOTREACHED*/
7430
99
  }
7431
  /*NOTREACHED*/
7432
99
}
7433
7434
UNSIGNED_SHIFT_OK struct block *
7435
gen_ncode(compiler_state_t *cstate, const char *s, bpf_u_int32 v, struct qual q)
7436
13.2k
{
7437
13.2k
  bpf_u_int32 mask;
7438
13.2k
  int proto;
7439
13.2k
  int vlen;
7440
7441
  /*
7442
   * Catch errors reported by us and routines below us, and return NULL
7443
   * on an error.
7444
   */
7445
13.2k
  if (setjmp(cstate->top_ctx))
7446
690
    return (NULL);
7447
7448
12.5k
  if (q.proto == Q_DECNET)
7449
394
    return gen_dnhost(cstate, s, v, q);
7450
7451
12.1k
  proto = q.proto;
7452
12.1k
  char idstr[PCAP_BUF_SIZE];
7453
12.6k
  if (s == NULL) {
7454
    /*
7455
     * v contains a 32-bit unsigned parsed from a string of the
7456
     * form {N}, which could be decimal, hexadecimal or octal.
7457
     * This is a valid IPv4 address, in the sense of inet_aton(3).
7458
     */
7459
12.6k
    vlen = 32;
7460
12.6k
    snprintf(idstr, sizeof(idstr), "%u", v);
7461
18.4E
  } else {
7462
    /*
7463
     * s points to a string of the form {N}.{N}, {N}.{N}.{N} or
7464
     * {N}.{N}.{N}.{N}, all of which potentially stand for a valid
7465
     * IPv4 address, in the sense of inet_aton(3).
7466
     */
7467
18.4E
    vlen = pcapint_atoin(s, &v);
7468
18.4E
    if (vlen < 0)
7469
4
      bpf_error(cstate, ERRSTR_INVALID_IPV4_ADDR, s);
7470
18.4E
    snprintf(idstr, sizeof(idstr), "%s", s);
7471
18.4E
  }
7472
7473
12.1k
  struct block *b, *b6;
7474
12.1k
  switch (q.addr) {
7475
7476
745
  case Q_DEFAULT:
7477
1.23k
  case Q_HOST:
7478
4.99k
  case Q_NET:
7479
4.99k
    if (proto == Q_LINK) {
7480
2
      bpf_error(cstate, "illegal link-layer address '%s'", idstr);
7481
4.98k
    } else {
7482
4.98k
      mask = 0xffffffff;
7483
4.98k
      if (s == NULL && q.addr == Q_NET) {
7484
        /* Promote short net number */
7485
12.0k
        while (v && (v & 0xff000000) == 0) {
7486
8.36k
          v <<= 8;
7487
8.36k
          mask <<= 8;
7488
8.36k
        }
7489
3.68k
      } else {
7490
        /* Promote short ipaddr */
7491
1.30k
        v <<= 32 - vlen;
7492
1.30k
        mask <<= 32 - vlen ;
7493
1.30k
      }
7494
4.98k
      return gen_host(cstate, 1, &v, &mask, q.proto, q.dir, 0,
7495
4.98k
                      q.addr == Q_NET ? "net <IPv4 address>" :
7496
4.98k
                      "host <IPv4 address>");
7497
4.98k
    }
7498
7499
0
  case Q_PORTRANGE: // "portrange <n>" means the same as "port <n>".
7500
4.47k
  case Q_PORT:
7501
4.47k
    proto = port_pq_to_ipproto(cstate, proto, tqkw(q.addr));
7502
7503
    // This check is necessary: v can hold any uint32_t value.
7504
4.47k
    assert_maxval(cstate, "port number", v, UINT16_MAX);
7505
7506
    // proto can be PROTO_UNDEF
7507
4.47k
    b = gen_port(cstate, (uint16_t)v, proto, q.dir, q.addr);
7508
4.47k
    b6 = gen_port6(cstate, (uint16_t)v, proto, q.dir, q.addr);
7509
4.47k
    return gen_or(b6, b);
7510
7511
2.84k
  case Q_PROTO:
7512
2.84k
    return gen_proto(cstate, v, proto);
7513
7514
0
#if !defined(NO_PROTOCHAIN)
7515
551
  case Q_PROTOCHAIN:
7516
551
    return gen_protochain(cstate, v, proto);
7517
0
#endif
7518
7519
15
  case Q_UNDEF:
7520
15
    syntax(cstate);
7521
    /*NOTREACHED*/
7522
7523
0
  default:
7524
0
    bpf_error(cstate, ERRSTR_INVALID_QUAL, tqkw(q.addr), idstr);
7525
    /*NOTREACHED*/
7526
12.1k
  }
7527
  /*NOTREACHED*/
7528
12.1k
}
7529
7530
struct block *
7531
gen_mcode6(compiler_state_t *cstate, const char *s, bpf_u_int32 masklen,
7532
    struct qual q)
7533
925
{
7534
925
  struct in6_addr addr;
7535
925
  struct in6_addr mask;
7536
925
  bpf_u_int32 a[4], m[4]; /* Same as in gen_hostop6(). */
7537
7538
  /*
7539
   * Catch errors reported by us and routines below us, and return NULL
7540
   * on an error.
7541
   */
7542
925
  if (setjmp(cstate->top_ctx))
7543
107
    return (NULL);
7544
7545
  /*
7546
   * If everything works correctly, this call never fails: a string that
7547
   * is valid for HID6 and the associated validating inet_pton() in the
7548
   * lexer is valid for inet_pton() here.
7549
   */
7550
818
  if (1 != inet_pton(AF_INET6, s, &addr))
7551
0
    bpf_error(cstate, "'%s' is not a valid IPv6 address", s);
7552
7553
818
  if (masklen > sizeof(mask.s6_addr) * 8)
7554
30
    bpf_error(cstate, "mask length must be <= %zu", sizeof(mask.s6_addr) * 8);
7555
788
  memset(&mask, 0, sizeof(mask));
7556
788
  memset(&mask.s6_addr, 0xff, masklen / 8);
7557
788
  if (masklen % 8) {
7558
159
    mask.s6_addr[masklen / 8] =
7559
159
      (0xff << (8 - masklen % 8)) & 0xff;
7560
159
  }
7561
7562
788
  memcpy(a, &addr, sizeof(a));
7563
788
  memcpy(m, &mask, sizeof(m));
7564
866
  if ((a[0] & ~m[0]) || (a[1] & ~m[1])
7565
849
   || (a[2] & ~m[2]) || (a[3] & ~m[3])) {
7566
48
    bpf_error(cstate, "non-network bits set in \"%s/%d\"", s, masklen);
7567
48
  }
7568
7569
740
  char buf[INET6_ADDRSTRLEN + sizeof("/128")];
7570
740
  switch (q.addr) {
7571
7572
203
  case Q_DEFAULT:
7573
247
  case Q_HOST:
7574
247
    if (masklen != 128) {
7575
8
      snprintf(buf, sizeof(buf), "%s/%u", s, masklen);
7576
8
      bpf_error(cstate, ERRSTR_INVALID_QUAL, "host", buf);
7577
8
    }
7578
    /* FALLTHROUGH */
7579
7580
831
  case Q_NET:
7581
831
    return gen_host6(cstate, 1, &addr, &mask, q.proto, q.dir, 0,
7582
831
                     q.addr == Q_HOST ? "host <IPv6 address>" :
7583
831
                     "net <IPv6 prefix>");
7584
7585
8
  default:
7586
8
    if (masklen == 128)
7587
2
      bpf_error(cstate, ERRSTR_INVALID_QUAL, tqkw(q.addr), s);
7588
6
    else {
7589
6
      snprintf(buf, sizeof(buf), "%s/%u", s, masklen);
7590
6
      bpf_error(cstate, ERRSTR_INVALID_QUAL, tqkw(q.addr), buf);
7591
6
    }
7592
    /*NOTREACHED*/
7593
740
  }
7594
740
}
7595
7596
struct block *
7597
gen_ecode(compiler_state_t *cstate, const char *s, struct qual q)
7598
2.30k
{
7599
  /*
7600
   * Catch errors reported by us and routines below us, and return NULL
7601
   * on an error.
7602
   */
7603
2.30k
  if (setjmp(cstate->top_ctx))
7604
86
    return (NULL);
7605
7606
2.21k
  const char *context = "link host XX:XX:XX:XX:XX:XX";
7607
7608
2.29k
  if (! ((q.addr == Q_HOST || q.addr == Q_DEFAULT) && q.proto == Q_LINK))
7609
3
    bpf_error(cstate, "Ethernet address used in non-ether expression");
7610
2.21k
  if (! is_mac48_linktype(cstate->linktype))
7611
13
    fail_kw_on_dlt(cstate, context);
7612
7613
2.19k
  u_char eaddr[6];
7614
  /*
7615
   * Belt and braces: so long as the lexer regexp guards MAC-48 syntax,
7616
   * here the attempt to parse it will always succeed.
7617
   */
7618
2.19k
  if (! pcapint_atomac48(s, eaddr))
7619
0
    bpf_error(cstate, "invalid MAC-48 address '%s'", s);
7620
7621
2.19k
  return gen_mac48host(cstate, eaddr, q.dir, context);
7622
2.19k
}
7623
7624
// Process a regular primitive, the ID is a MAC-8 address string.
7625
struct block *
7626
gen_acode(compiler_state_t *cstate, const char *s, struct qual q)
7627
695
{
7628
  /*
7629
   * Catch errors reported by us and routines below us, and return NULL
7630
   * on an error.
7631
   */
7632
695
  if (setjmp(cstate->top_ctx))
7633
9
    return (NULL);
7634
7635
  // WLAN direction qualifiers are never valid for MAC-8 addresses.
7636
686
  assert_nonwlan_dqual(cstate, q.dir);
7637
7638
686
  if (q.addr != Q_HOST && q.addr != Q_DEFAULT)
7639
1
    bpf_error(cstate, ERRSTR_INVALID_QUAL, tqkw(q.addr), "$XX");
7640
685
  if (q.proto != Q_LINK)
7641
2
    bpf_error(cstate, "'link' is the only valid proto qualifier for 'host $XX'");
7642
7643
683
  uint8_t addr;
7644
  /*
7645
   * The lexer currently defines the address format in a way that makes
7646
   * this error condition never true.  Let's check it anyway in case this
7647
   * part of the lexer changes in future.
7648
   */
7649
683
  if (! pcapint_atoan(s, &addr))
7650
0
      bpf_error(cstate, "invalid MAC-8 address '%s'", s);
7651
7652
683
  return gen_mac8host(cstate, addr, q.dir, "link host $XX");
7653
683
}
7654
7655
void
7656
sappend(struct slist *s0, struct slist *s1)
7657
305k
{
7658
  /*
7659
   * This is definitely not the best way to do this, but the
7660
   * lists will rarely get long.
7661
   */
7662
9.63M
  while (s0->next)
7663
9.33M
    s0 = s0->next;
7664
305k
  s0->next = s1;
7665
305k
}
7666
7667
/*
7668
 * Prepend the given list of statements to the list of side effect statements
7669
 * of the block.  Either of the lists may be NULL to mean the valid edge case
7670
 * of an empty list.
7671
 */
7672
static struct block *
7673
sprepend_to_block(struct slist *s, struct block *b)
7674
6.71k
{
7675
6.71k
  if (s) {
7676
1.13k
    if (b->stmts)
7677
1.13k
      sappend(s, b->stmts);
7678
1.13k
    b->stmts = s;
7679
    /*
7680
     * The block has changed.  It could have been a Boolean
7681
     * constant before.
7682
     */
7683
1.13k
    b->meaning = IS_UNCERTAIN;
7684
1.13k
  }
7685
6.71k
  return b;
7686
6.71k
}
7687
7688
static struct slist *
7689
xfer_to_x(compiler_state_t *cstate, const struct arth *a)
7690
21.9k
{
7691
21.9k
  struct slist *s;
7692
7693
21.9k
  s = new_stmt(cstate, BPF_LDX|BPF_MEM);
7694
21.9k
  s->s.k = a->regno;
7695
21.9k
  return s;
7696
21.9k
}
7697
7698
static struct slist *
7699
xfer_to_a(compiler_state_t *cstate, const struct arth *a)
7700
39.5k
{
7701
39.5k
  struct slist *s;
7702
7703
39.5k
  s = new_stmt(cstate, BPF_LD|BPF_MEM);
7704
39.5k
  s->s.k = a->regno;
7705
39.5k
  return s;
7706
39.5k
}
7707
7708
/*
7709
 * Modify "inst" to use the value stored into its register as an
7710
 * offset relative to the beginning of the header for the protocol
7711
 * "proto", and allocate a register and put an item "size" bytes long
7712
 * (1, 2, or 4) at that offset into that register, making it the register
7713
 * for "inst".
7714
 */
7715
static struct arth *
7716
gen_load_internal(compiler_state_t *cstate, int proto, struct arth *inst,
7717
    bpf_u_int32 size)
7718
3.70k
{
7719
3.70k
  int size_code;
7720
3.70k
  int regno = alloc_reg(cstate);
7721
7722
3.70k
  free_reg(cstate, inst->regno);
7723
3.70k
  switch (size) {
7724
7725
1
  default:
7726
1
    bpf_error(cstate, "data size must be 1, 2, or 4");
7727
    /*NOTREACHED*/
7728
7729
3.34k
  case 1:
7730
3.34k
    size_code = BPF_B;
7731
3.34k
    break;
7732
7733
200
  case 2:
7734
200
    size_code = BPF_H;
7735
200
    break;
7736
7737
155
  case 4:
7738
155
    size_code = BPF_W;
7739
155
    break;
7740
3.70k
  }
7741
3.70k
  struct block *b = NULL; // protocol checks
7742
3.70k
  struct slist *s = NULL; // the variable part of an absolute offset
7743
3.70k
  u_int constpart = 0;    // the constant part of an absolute offset
7744
3.70k
  switch (proto) {
7745
4
  default:
7746
4
    bpf_error(cstate, "'%s' does not support the index operation", pqkw(proto));
7747
7748
124
  case Q_RADIO:
7749
    /*
7750
     * This corresponds to OR_PACKET in gen_load_a().
7751
     *
7752
     * The offset is relative to the beginning of the packet
7753
     * data, if we have a radio header.  (If we don't, this
7754
     * is an error.)
7755
     */
7756
124
    if (cstate->linktype != DLT_IEEE802_11_RADIO_AVS &&
7757
83
        cstate->linktype != DLT_IEEE802_11_RADIO &&
7758
46
        cstate->linktype != DLT_PRISM_HEADER)
7759
11
      bpf_error(cstate, "radio information not present in capture");
7760
7761
    /*
7762
     * Load into the X register the offset computed into the
7763
     * register specified by "inst".
7764
     *
7765
     * Load the item at that offset.
7766
     *
7767
     * In other words, the variable part is not present, the
7768
     * constant part is zero and there are no protocol checks, so
7769
     * just break out to proceed with "inst" only.
7770
     */
7771
113
    break;
7772
7773
818
  case Q_LINK:
7774
    /*
7775
     * This corresponds to OR_LINKHDR in gen_load_a().
7776
     *
7777
     * The offset is relative to the beginning of
7778
     * the link-layer header.
7779
     *
7780
     * XXX - what about ATM LANE?  Should "inst" be
7781
     * relative to the beginning of the AAL5 frame, so
7782
     * that 0 refers to the beginning of the LE Control
7783
     * field, or relative to the beginning of the LAN
7784
     * frame, so that 0 refers, for Ethernet LANE, to
7785
     * the beginning of the destination address?
7786
     */
7787
818
    s = gen_abs_offset_varpart(cstate, &cstate->off_linkhdr);
7788
7789
    /*
7790
     * If "s" is non-null, it has code to arrange that the
7791
     * X register contains the length of the prefix preceding
7792
     * the link-layer header.  Add to it the offset computed
7793
     * into the register specified by "inst", and move that
7794
     * into the X register.  Otherwise, just load into the X
7795
     * register the offset computed into the register specified
7796
     * by "inst".
7797
     *
7798
     * Load the item at the sum of the offset we've put in the
7799
     * X register and the offset of the start of the link
7800
     * layer header (which is 0 if the radio header is
7801
     * variable-length; that header length is what we put
7802
     * into the X register and then added to "inst").
7803
     */
7804
818
    constpart = cstate->off_linkhdr.constant_part;
7805
    // There are no protocol checks.
7806
818
    break;
7807
7808
651
  case Q_IP:
7809
706
  case Q_ARP:
7810
730
  case Q_RARP:
7811
758
  case Q_ATALK:
7812
782
  case Q_DECNET:
7813
801
  case Q_SCA:
7814
873
  case Q_LAT:
7815
913
  case Q_MOPRC:
7816
961
  case Q_MOPDL:
7817
1.15k
  case Q_IPV6:
7818
    /*
7819
     * This corresponds to OR_LINKPL in gen_load_a().
7820
     *
7821
     * The offset is relative to the beginning of
7822
     * the network-layer header.
7823
     * XXX - are there any cases where we want
7824
     * cstate->off_nl_nosnap?
7825
     */
7826
1.15k
    s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
7827
7828
    /*
7829
     * If "s" is non-null, it has code to arrange that the
7830
     * X register contains the variable part of the offset
7831
     * of the link-layer payload.  Add to it the offset
7832
     * computed into the register specified by "inst",
7833
     * and move that into the X register.  Otherwise, just
7834
     * load into the X register the offset computed into
7835
     * the register specified by "inst".
7836
     *
7837
     * Load the item at the sum of the offset we've put in the
7838
     * X register, the offset of the start of the network
7839
     * layer header from the beginning of the link-layer
7840
     * payload, and the constant part of the offset of the
7841
     * start of the link-layer payload.
7842
     */
7843
1.15k
    constpart = cstate->off_linkpl.constant_part + cstate->off_nl;
7844
7845
    /*
7846
     * Do the computation only if the packet contains
7847
     * the protocol in question.
7848
     */
7849
1.15k
    b = gen_proto_abbrev_internal(cstate, proto);
7850
1.15k
    break;
7851
7852
109
  case Q_SCTP:
7853
285
  case Q_TCP:
7854
808
  case Q_UDP:
7855
860
  case Q_ICMP:
7856
921
  case Q_IGMP:
7857
962
  case Q_IGRP:
7858
1.37k
  case Q_PIM:
7859
1.41k
  case Q_VRRP:
7860
1.43k
  case Q_CARP:
7861
    /*
7862
     * This corresponds to OR_TRAN_IPV4 in gen_load_a().
7863
     *
7864
     * The offset is relative to the beginning of
7865
     * the transport-layer header.
7866
     *
7867
     * Load the X register with the length of the IPv4 header
7868
     * (plus the offset of the link-layer header, if it's
7869
     * a variable-length header), in bytes.
7870
     *
7871
     * XXX - are there any cases where we want
7872
     * cstate->off_nl_nosnap?
7873
     * XXX - we should, if we're built with
7874
     * IPv6 support, generate code to load either
7875
     * IPv4, IPv6, or both, as appropriate.
7876
     */
7877
1.43k
    s = gen_loadx_iphdrlen(cstate);
7878
7879
    /*
7880
     * The X register now contains the sum of the variable
7881
     * part of the offset of the link-layer payload and the
7882
     * length of the network-layer header.
7883
     *
7884
     * Load into the A register the offset relative to
7885
     * the beginning of the transport layer header,
7886
     * add the X register to that, move that to the
7887
     * X register, and load with an offset from the
7888
     * X register equal to the sum of the constant part of
7889
     * the offset of the link-layer payload and the offset,
7890
     * relative to the beginning of the link-layer payload,
7891
     * of the network-layer header.
7892
     */
7893
1.43k
    constpart = cstate->off_linkpl.constant_part + cstate->off_nl;
7894
7895
    /*
7896
     * Do the computation only if the packet contains
7897
     * the protocol in question - which is true only
7898
     * if this is an IP datagram and is the first or
7899
     * only fragment of that datagram.
7900
     *
7901
     * Do not use gen_proto_abbrev_internal(cstate, proto): if it
7902
     * matches the given proto qualifier using Q_DEFAULT, this
7903
     * would produce an unreachable IPv6 branch.
7904
     */
7905
1.43k
    b = gen_proto_abbrev_internal(cstate, Q_IP);
7906
1.43k
    b = gen_and(b, gen_ip_proto(cstate, pq_to_ipproto(cstate,
7907
1.43k
        (u_char)proto)));
7908
1.43k
    b = gen_and(b, gen_ipfrag(cstate));
7909
1.43k
    break;
7910
165
  case Q_ICMPV6:
7911
    /*
7912
     * This corresponds to OR_TRAN_IPV6 in gen_load_a().
7913
     *
7914
     * Do the computation only if the packet contains
7915
     * the protocol in question.
7916
     *
7917
     * Do not use gen_proto(..., Q_IPV6): this would also match
7918
     * IPPROTO_FRAGMENT and the side effect statements would
7919
     * quietly load incorrect data.
7920
     */
7921
165
    b = gen_proto_abbrev_internal(cstate, Q_IPV6);
7922
7923
    /*
7924
     * Check if we have an icmp6 next header
7925
     */
7926
165
    b = gen_and(b, gen_ip6_proto(cstate, IPPROTO_ICMPV6));
7927
7928
165
    s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
7929
    /*
7930
     * If "s" is non-null, it has code to arrange that the
7931
     * X register contains the variable part of the offset
7932
     * of the link-layer payload.  Add to it the offset
7933
     * computed into the register specified by "inst",
7934
     * and move that into the X register.  Otherwise, just
7935
     * load into the X register the offset computed into
7936
     * the register specified by "inst".
7937
     *
7938
     * Load the item at the sum of the offset we've put in the
7939
     * X register, the offset of the start of the network
7940
     * layer header from the beginning of the link-layer
7941
     * payload, and the constant part of the offset of the
7942
     * start of the link-layer payload.
7943
     */
7944
165
    constpart = cstate->off_linkpl.constant_part + cstate->off_nl +
7945
165
        IP6_HDRLEN;
7946
165
    break;
7947
3.70k
  }
7948
7949
3.67k
  if (b)
7950
2.74k
    inst->b = inst->b ? gen_and(inst->b, b) : b;
7951
  // NULL is a valid value for 's'.
7952
3.67k
  sappend(inst->s, gen_load_absoffsetarthrel(cstate, s, constpart, inst,
7953
3.67k
      size_code));
7954
7955
3.67k
  inst->regno = regno;
7956
3.67k
  s = new_stmt(cstate, BPF_ST);
7957
3.67k
  s->s.k = regno;
7958
3.67k
  sappend(inst->s, s);
7959
7960
3.67k
  return inst;
7961
3.70k
}
7962
7963
struct arth *
7964
gen_load(compiler_state_t *cstate, int proto, struct arth *inst,
7965
    bpf_u_int32 size)
7966
3.70k
{
7967
  /*
7968
   * Catch errors reported by us and routines below us, and return NULL
7969
   * on an error.
7970
   */
7971
3.70k
  if (setjmp(cstate->top_ctx))
7972
30
    return (NULL);
7973
7974
3.67k
  return gen_load_internal(cstate, proto, inst, size);
7975
3.70k
}
7976
7977
static struct block *
7978
gen_relation_internal(compiler_state_t *cstate, int code, struct arth *a0,
7979
    struct arth *a1, int reversed)
7980
4.25k
{
7981
4.25k
  struct slist *s0, *s1;
7982
4.25k
  struct block *b;
7983
7984
4.25k
  s0 = xfer_to_x(cstate, a1);
7985
4.25k
  s1 = xfer_to_a(cstate, a0);
7986
4.25k
  sappend(s0, s1);
7987
4.25k
  sappend(a1->s, s0);
7988
4.25k
  sappend(a0->s, a1->s);
7989
7990
4.25k
  b = gen_jmp_x(cstate, code, a0->s);
7991
4.25k
  if (reversed)
7992
1.56k
    gen_not(b);
7993
7994
4.25k
  free_reg(cstate, a0->regno);
7995
4.25k
  free_reg(cstate, a1->regno);
7996
7997
  /* 'and' together protocol checks */
7998
4.25k
  if (a0->b)
7999
320
    b = gen_and(a0->b, b);
8000
4.25k
  if (a1->b)
8001
325
    b = gen_and(a1->b, b);
8002
4.25k
  return b;
8003
4.25k
}
8004
8005
struct block *
8006
gen_relation(compiler_state_t *cstate, int code, struct arth *a0,
8007
    struct arth *a1, int reversed)
8008
4.25k
{
8009
  /*
8010
   * Catch errors reported by us and routines below us, and return NULL
8011
   * on an error.
8012
   */
8013
4.25k
  if (setjmp(cstate->top_ctx))
8014
0
    return (NULL);
8015
8016
4.25k
  return gen_relation_internal(cstate, code, a0, a1, reversed);
8017
4.25k
}
8018
8019
struct arth *
8020
gen_loadlen(compiler_state_t *cstate)
8021
3.10k
{
8022
3.10k
  int regno;
8023
3.10k
  struct arth *a;
8024
3.10k
  struct slist *s;
8025
8026
  /*
8027
   * Catch errors reported by us and routines below us, and return NULL
8028
   * on an error.
8029
   */
8030
3.10k
  if (setjmp(cstate->top_ctx))
8031
1
    return (NULL);
8032
8033
3.10k
  regno = alloc_reg(cstate);
8034
3.10k
  a = (struct arth *)newchunk(cstate, sizeof(*a));
8035
3.10k
  s = new_stmt(cstate, BPF_LD|BPF_LEN);
8036
3.10k
  s->next = new_stmt(cstate, BPF_ST);
8037
3.10k
  s->next->s.k = regno;
8038
3.10k
  a->s = s;
8039
3.10k
  a->regno = regno;
8040
8041
3.10k
  return a;
8042
3.10k
}
8043
8044
static struct arth *
8045
gen_loadi_internal(compiler_state_t *cstate, bpf_u_int32 val)
8046
22.5k
{
8047
22.5k
  struct arth *a;
8048
22.5k
  struct slist *s;
8049
22.5k
  int reg;
8050
8051
22.5k
  a = (struct arth *)newchunk(cstate, sizeof(*a));
8052
8053
22.5k
  reg = alloc_reg(cstate);
8054
8055
22.5k
  s = new_stmt(cstate, BPF_LD|BPF_IMM);
8056
22.5k
  s->s.k = val;
8057
22.5k
  s->next = new_stmt(cstate, BPF_ST);
8058
22.5k
  s->next->s.k = reg;
8059
22.5k
  a->s = s;
8060
22.5k
  a->regno = reg;
8061
8062
22.5k
  return a;
8063
22.5k
}
8064
8065
struct arth *
8066
gen_loadi(compiler_state_t *cstate, bpf_u_int32 val)
8067
22.5k
{
8068
  /*
8069
   * Catch errors reported by us and routines below us, and return NULL
8070
   * on an error.
8071
   */
8072
22.5k
  if (setjmp(cstate->top_ctx))
8073
2
    return (NULL);
8074
8075
22.5k
  return gen_loadi_internal(cstate, val);
8076
22.5k
}
8077
8078
/*
8079
 * The a_arg dance is to avoid annoying whining by compilers that
8080
 * a might be clobbered by longjmp - yeah, it might, but *WHO CARES*?
8081
 * It's not *used* after setjmp returns.
8082
 */
8083
struct arth *
8084
gen_neg(compiler_state_t *cstate, struct arth *a_arg)
8085
17.2k
{
8086
17.2k
  struct arth *a = a_arg;
8087
17.2k
  struct slist *s;
8088
8089
  /*
8090
   * Catch errors reported by us and routines below us, and return NULL
8091
   * on an error.
8092
   */
8093
17.2k
  if (setjmp(cstate->top_ctx))
8094
0
    return (NULL);
8095
8096
17.2k
  s = xfer_to_a(cstate, a);
8097
17.2k
  sappend(a->s, s);
8098
17.2k
  s = new_stmt(cstate, BPF_ALU|BPF_NEG);
8099
17.2k
  s->s.k = 0;
8100
17.2k
  sappend(a->s, s);
8101
17.2k
  s = new_stmt(cstate, BPF_ST);
8102
17.2k
  s->s.k = a->regno;
8103
17.2k
  sappend(a->s, s);
8104
8105
17.2k
  return a;
8106
17.2k
}
8107
8108
/*
8109
 * The a0_arg dance is to avoid annoying whining by compilers that
8110
 * a0 might be clobbered by longjmp - yeah, it might, but *WHO CARES*?
8111
 * It's not *used* after setjmp returns.
8112
 */
8113
struct arth *
8114
gen_arth(compiler_state_t *cstate, int code, struct arth *a0_arg,
8115
    struct arth *a1)
8116
16.0k
{
8117
16.0k
  struct arth *a0 = a0_arg;
8118
16.0k
  struct slist *s0, *s1, *s2;
8119
8120
  /*
8121
   * Catch errors reported by us and routines below us, and return NULL
8122
   * on an error.
8123
   */
8124
16.0k
  if (setjmp(cstate->top_ctx))
8125
55
    return (NULL);
8126
8127
  /*
8128
   * Disallow division by, or modulus by, zero; we do this here
8129
   * so that it gets done even if the optimizer is disabled.
8130
   *
8131
   * Also disallow shifts by a value greater than 31; we do this
8132
   * here, for the same reason.
8133
   */
8134
16.0k
  if (code == BPF_DIV) {
8135
1.90k
    if (a1->s->s.code == (BPF_LD|BPF_IMM) && a1->s->s.k == 0)
8136
5
      bpf_error(cstate, "division by zero");
8137
14.1k
  } else if (code == BPF_MOD) {
8138
1.31k
    if (a1->s->s.code == (BPF_LD|BPF_IMM) && a1->s->s.k == 0)
8139
5
      bpf_error(cstate, "modulus by zero");
8140
12.8k
  } else if (code == BPF_LSH || code == BPF_RSH) {
8141
1.44k
    if (a1->s->s.code == (BPF_LD|BPF_IMM) && a1->s->s.k > 31)
8142
45
      bpf_error(cstate, "shift by more than 31 bits");
8143
1.44k
  }
8144
15.9k
  s0 = xfer_to_x(cstate, a1);
8145
15.9k
  s1 = xfer_to_a(cstate, a0);
8146
15.9k
  s2 = new_stmt(cstate, BPF_ALU|BPF_X|code);
8147
8148
15.9k
  sappend(s1, s2);
8149
15.9k
  sappend(s0, s1);
8150
15.9k
  sappend(a1->s, s0);
8151
15.9k
  sappend(a0->s, a1->s);
8152
8153
15.9k
  free_reg(cstate, a0->regno);
8154
15.9k
  free_reg(cstate, a1->regno);
8155
8156
15.9k
  s0 = new_stmt(cstate, BPF_ST);
8157
15.9k
  a0->regno = s0->s.k = alloc_reg(cstate);
8158
15.9k
  sappend(a0->s, s0);
8159
8160
15.9k
  return a0;
8161
16.0k
}
8162
8163
/*
8164
 * Initialize the table of used registers and the current register.
8165
 */
8166
static void
8167
init_regs(compiler_state_t *cstate)
8168
13.0k
{
8169
13.0k
  cstate->curreg = 0;
8170
13.0k
  memset(cstate->regused, 0, sizeof cstate->regused);
8171
13.0k
}
8172
8173
/*
8174
 * Return the next free register.
8175
 */
8176
static int
8177
alloc_reg(compiler_state_t *cstate)
8178
48.8k
{
8179
48.8k
  int n = BPF_MEMWORDS;
8180
8181
77.9k
  while (--n >= 0) {
8182
77.9k
    if (cstate->regused[cstate->curreg])
8183
29.1k
      cstate->curreg = (cstate->curreg + 1) % BPF_MEMWORDS;
8184
48.8k
    else {
8185
48.8k
      cstate->regused[cstate->curreg] = 1;
8186
48.8k
      return cstate->curreg;
8187
48.8k
    }
8188
77.9k
  }
8189
20
  bpf_error(cstate, "too many registers needed to evaluate expression");
8190
  /*NOTREACHED*/
8191
48.8k
}
8192
8193
/*
8194
 * Return a register to the table so it can
8195
 * be used later.
8196
 */
8197
static void
8198
free_reg(compiler_state_t *cstate, int n)
8199
44.9k
{
8200
44.9k
  cstate->regused[n] = 0;
8201
44.9k
}
8202
8203
static struct block *
8204
gen_len(compiler_state_t *cstate, int jmp, int n)
8205
31
{
8206
31
  struct slist *s;
8207
8208
31
  s = new_stmt(cstate, BPF_LD|BPF_LEN);
8209
31
  return gen_jmp_k(cstate, jmp, n, s);
8210
31
}
8211
8212
struct block *
8213
gen_greater(compiler_state_t *cstate, int n)
8214
0
{
8215
  /*
8216
   * Catch errors reported by us and routines below us, and return NULL
8217
   * on an error.
8218
   */
8219
0
  if (setjmp(cstate->top_ctx))
8220
0
    return (NULL);
8221
8222
0
  return gen_len(cstate, BPF_JGE, n);
8223
0
}
8224
8225
/*
8226
 * Actually, this is less than or equal.
8227
 */
8228
struct block *
8229
gen_less(compiler_state_t *cstate, int n)
8230
31
{
8231
  /*
8232
   * Catch errors reported by us and routines below us, and return NULL
8233
   * on an error.
8234
   */
8235
31
  if (setjmp(cstate->top_ctx))
8236
0
    return (NULL);
8237
8238
31
  return gen_not(gen_len(cstate, BPF_JGT, n));
8239
31
}
8240
8241
/*
8242
 * This is for "byte {idx} {op} {val}"; "idx" is treated as relative to
8243
 * the beginning of the link-layer header.
8244
 */
8245
struct block *
8246
gen_byteop(compiler_state_t *cstate, int op, int idx, bpf_u_int32 val)
8247
158
{
8248
158
  struct block *b;
8249
158
  struct slist *s;
8250
8251
  /*
8252
   * Catch errors reported by us and routines below us, and return NULL
8253
   * on an error.
8254
   */
8255
158
  if (setjmp(cstate->top_ctx))
8256
18
    return (NULL);
8257
8258
140
  assert_maxval(cstate, "byte argument", val, UINT8_MAX);
8259
8260
140
  switch (op) {
8261
0
  default:
8262
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "op", op);
8263
8264
10
  case '=':
8265
10
    return gen_cmp(cstate, OR_LINKHDR, (u_int)idx, BPF_B, val);
8266
8267
19
  case '<':
8268
19
    return gen_cmp_lt(cstate, OR_LINKHDR, (u_int)idx, BPF_B, val);
8269
8270
28
  case '>':
8271
28
    return gen_cmp_gt(cstate, OR_LINKHDR, (u_int)idx, BPF_B, val);
8272
8273
16
  case '|':
8274
16
    s = new_stmt(cstate, BPF_ALU|BPF_OR|BPF_K);
8275
16
    break;
8276
8277
67
  case '&':
8278
67
    s = new_stmt(cstate, BPF_ALU|BPF_AND|BPF_K);
8279
67
    break;
8280
140
  }
8281
83
  s->s.k = val;
8282
  // Load the required byte first.
8283
83
  struct slist *s0 = gen_load_a(cstate, OR_LINKHDR, idx, BPF_B);
8284
83
  sappend(s0, s);
8285
83
  b = gen_jmp_k(cstate, BPF_JEQ, 0, s0);
8286
8287
83
  return gen_not(b);
8288
140
}
8289
8290
struct block *
8291
gen_broadcast(compiler_state_t *cstate, int proto)
8292
0
{
8293
0
  bpf_u_int32 hostmask;
8294
0
  struct block *b0, *b1, *b2;
8295
0
  static const u_char ebroadcast[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
8296
8297
  /*
8298
   * Catch errors reported by us and routines below us, and return NULL
8299
   * on an error.
8300
   */
8301
0
  if (setjmp(cstate->top_ctx))
8302
0
    return (NULL);
8303
8304
0
  switch (proto) {
8305
8306
0
  case Q_DEFAULT:
8307
0
  case Q_LINK:
8308
0
    switch (cstate->linktype) {
8309
0
    case DLT_ARCNET:
8310
0
    case DLT_ARCNET_LINUX:
8311
      // ARCnet broadcast is [8-bit] destination address 0.
8312
0
      return gen_mac8host(cstate, 0, Q_DST, "broadcast");
8313
0
    case DLT_BACNET_MS_TP:
8314
      // MS/TP broadcast is [8-bit] destination address 0xFF.
8315
0
      return gen_mac8host(cstate, 0xFF, Q_DST, "broadcast");
8316
0
    }
8317
0
    return gen_mac48host(cstate, ebroadcast, Q_DST, "broadcast");
8318
    /*NOTREACHED*/
8319
8320
0
  case Q_IP:
8321
    /*
8322
     * We treat a netmask of PCAP_NETMASK_UNKNOWN (0xffffffff)
8323
     * as an indication that we don't know the netmask, and fail
8324
     * in that case.
8325
     */
8326
0
    if (cstate->netmask == PCAP_NETMASK_UNKNOWN)
8327
0
      bpf_error(cstate, "netmask not known, so 'ip broadcast' not supported");
8328
0
    b0 = gen_linktype(cstate, ETHERTYPE_IP);
8329
0
    hostmask = ~cstate->netmask;
8330
0
    b1 = gen_mcmp(cstate, OR_LINKPL, IPV4_DSTADDR_OFFSET, BPF_W,
8331
0
        0, hostmask);
8332
0
    b2 = gen_mcmp(cstate, OR_LINKPL, IPV4_DSTADDR_OFFSET, BPF_W,
8333
0
        hostmask, hostmask);
8334
0
    return gen_and(b0, gen_or(b1, b2));
8335
0
  }
8336
0
  bpf_error(cstate, ERRSTR_INVALID_QUAL, pqkw(proto), "broadcast");
8337
  /*NOTREACHED*/
8338
0
}
8339
8340
/*
8341
 * Generate code to test the low-order bit of a MAC address (that's
8342
 * the bottom bit of the *first* byte).
8343
 */
8344
static struct block *
8345
gen_mac_multicast(compiler_state_t *cstate, int offset)
8346
0
{
8347
0
  struct slist *s;
8348
8349
  /* link[offset] & 1 != 0 */
8350
0
  s = gen_load_a(cstate, OR_LINKHDR, offset, BPF_B);
8351
0
  return gen_set(cstate, 1, s);
8352
0
}
8353
8354
struct block *
8355
gen_multicast(compiler_state_t *cstate, int proto)
8356
0
{
8357
0
  struct block *b0, *b1, *b2;
8358
0
  struct slist *s;
8359
8360
  /*
8361
   * Catch errors reported by us and routines below us, and return NULL
8362
   * on an error.
8363
   */
8364
0
  if (setjmp(cstate->top_ctx))
8365
0
    return (NULL);
8366
8367
0
  switch (proto) {
8368
8369
0
  case Q_DEFAULT:
8370
0
  case Q_LINK:
8371
0
    switch (cstate->linktype) {
8372
0
    case DLT_ARCNET:
8373
0
    case DLT_ARCNET_LINUX:
8374
      // ARCnet multicast is the same as broadcast.
8375
0
      return gen_mac8host(cstate, 0, Q_DST, "multicast");
8376
0
    case DLT_EN10MB:
8377
0
    case DLT_NETANALYZER:
8378
0
    case DLT_NETANALYZER_TRANSPARENT:
8379
0
    case DLT_DSA_TAG_BRCM:
8380
0
    case DLT_DSA_TAG_DSA:
8381
0
      b1 = gen_prevlinkhdr_check(cstate);
8382
      /* ether[0] & 1 != 0 */
8383
0
      b0 = gen_mac_multicast(cstate, 0);
8384
0
      return b1 ? gen_and(b1, b0) : b0;
8385
0
    case DLT_FDDI:
8386
      /*
8387
       * XXX TEST THIS: MIGHT NOT PORT PROPERLY XXX
8388
       *
8389
       * XXX - was that referring to bit-order issues?
8390
       */
8391
      /* fddi[1] & 1 != 0 */
8392
0
      return gen_mac_multicast(cstate, 1);
8393
0
    case DLT_IEEE802:
8394
      /* tr[2] & 1 != 0 */
8395
0
      return gen_mac_multicast(cstate, 2);
8396
0
    case DLT_IEEE802_11:
8397
0
    case DLT_PRISM_HEADER:
8398
0
    case DLT_IEEE802_11_RADIO_AVS:
8399
0
    case DLT_IEEE802_11_RADIO:
8400
0
    case DLT_PPI:
8401
      /*
8402
       * Oh, yuk.
8403
       *
8404
       *  For control frames, there is no DA.
8405
       *
8406
       *  For management frames, DA is at an
8407
       *  offset of 4 from the beginning of
8408
       *  the packet.
8409
       *
8410
       *  For data frames, DA is at an offset
8411
       *  of 4 from the beginning of the packet
8412
       *  if To DS is clear and at an offset of
8413
       *  16 from the beginning of the packet
8414
       *  if To DS is set.
8415
       */
8416
8417
      /*
8418
       * Generate the tests to be done for data frames.
8419
       *
8420
       * First, check for To DS set, i.e. "link[1] & 0x01".
8421
       */
8422
0
      s = gen_load_a(cstate, OR_LINKHDR, 1, BPF_B);
8423
0
      b1 = gen_set(cstate, IEEE80211_FC1_DIR_TODS, s);
8424
8425
      /*
8426
       * If To DS is set, the DA is at 16.
8427
       */
8428
0
      b0 = gen_mac_multicast(cstate, 16);
8429
0
      b0 = gen_and(b1, b0);
8430
8431
      /*
8432
       * Now, check for To DS not set, i.e. check
8433
       * "!(link[1] & 0x01)".
8434
       */
8435
0
      s = gen_load_a(cstate, OR_LINKHDR, 1, BPF_B);
8436
0
      b2 = gen_unset(cstate, IEEE80211_FC1_DIR_TODS, s);
8437
8438
      /*
8439
       * If To DS is not set, the DA is at 4.
8440
       */
8441
0
      b1 = gen_mac_multicast(cstate, 4);
8442
0
      b1 = gen_and(b2, b1);
8443
8444
      /*
8445
       * Now OR together the last two checks.  That gives
8446
       * the complete set of checks for data frames.
8447
       */
8448
0
      b0 = gen_or(b1, b0);
8449
8450
      /*
8451
       * Now check for a data frame.
8452
       * I.e, check "link[0] & 0x08".
8453
       */
8454
0
      s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
8455
0
      b1 = gen_set(cstate, IEEE80211_FC0_TYPE_DATA, s);
8456
8457
      /*
8458
       * AND that with the checks done for data frames.
8459
       */
8460
0
      b0 = gen_and(b1, b0);
8461
8462
      /*
8463
       * If the high-order bit of the type value is 0, this
8464
       * is a management frame.
8465
       * I.e, check "!(link[0] & 0x08)".
8466
       */
8467
0
      s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
8468
0
      b2 = gen_unset(cstate, IEEE80211_FC0_TYPE_DATA, s);
8469
8470
      /*
8471
       * For management frames, the DA is at 4.
8472
       */
8473
0
      b1 = gen_mac_multicast(cstate, 4);
8474
0
      b1 = gen_and(b2, b1);
8475
8476
      /*
8477
       * OR that with the checks done for data frames.
8478
       * That gives the checks done for management and
8479
       * data frames.
8480
       */
8481
0
      b0 = gen_or(b1, b0);
8482
8483
      /*
8484
       * If the low-order bit of the type value is 1,
8485
       * this is either a control frame or a frame
8486
       * with a reserved type, and thus not a
8487
       * frame with an SA.
8488
       *
8489
       * I.e., check "!(link[0] & 0x04)".
8490
       */
8491
0
      s = gen_load_a(cstate, OR_LINKHDR, 0, BPF_B);
8492
0
      b1 = gen_unset(cstate, IEEE80211_FC0_TYPE_CTL, s);
8493
8494
      /*
8495
       * AND that with the checks for data and management
8496
       * frames.
8497
       */
8498
0
      return gen_and(b1, b0);
8499
0
    case DLT_IP_OVER_FC:
8500
0
      return gen_mac_multicast(cstate, 2);
8501
0
    default:
8502
0
      break;
8503
0
    }
8504
0
    fail_kw_on_dlt(cstate, "multicast");
8505
    /*NOTREACHED*/
8506
8507
0
  case Q_IP:
8508
0
    b0 = gen_linktype(cstate, ETHERTYPE_IP);
8509
8510
    /*
8511
     * Compare address with 224.0.0.0/4
8512
     */
8513
0
    b1 = gen_mcmp(cstate, OR_LINKPL, IPV4_DSTADDR_OFFSET, BPF_B,
8514
0
        0xe0, 0xf0);
8515
8516
0
    return gen_and(b0, b1);
8517
8518
0
  case Q_IPV6:
8519
0
    b0 = gen_linktype(cstate, ETHERTYPE_IPV6);
8520
0
    b1 = gen_cmp(cstate, OR_LINKPL, IPV6_DSTADDR_OFFSET, BPF_B, 255);
8521
0
    return gen_and(b0, b1);
8522
0
  }
8523
0
  bpf_error(cstate, ERRSTR_INVALID_QUAL, pqkw(proto), "multicast");
8524
  /*NOTREACHED*/
8525
0
}
8526
8527
#ifdef __linux__
8528
/*
8529
 * This is Linux; we require PF_PACKET support.  If this is a *live* capture,
8530
 * we can look at special meta-data in the filter expression; otherwise we
8531
 * can't because it is either a savefile (rfile != NULL) or a pcap_t created
8532
 * using pcap_open_dead() (rfile == NULL).  Thus check for a flag that
8533
 * pcap_activate() conditionally sets.
8534
 */
8535
static void
8536
require_basic_bpf_extensions(compiler_state_t *cstate, const char *keyword)
8537
0
{
8538
0
  if (cstate->bpf_pcap->bpf_codegen_flags & BPF_SPECIAL_BASIC_HANDLING)
8539
0
    return;
8540
0
  bpf_error(cstate, "not a live capture, '%s' not supported on %s",
8541
0
      keyword,
8542
0
      pcapint_datalink_val_to_string(cstate->linktype));
8543
0
}
8544
#endif // __linux__
8545
8546
struct block *
8547
gen_ifindex(compiler_state_t *cstate, int ifindex)
8548
0
{
8549
  /*
8550
   * Catch errors reported by us and routines below us, and return NULL
8551
   * on an error.
8552
   */
8553
0
  if (setjmp(cstate->top_ctx))
8554
0
    return (NULL);
8555
8556
  /*
8557
   * Only some data link types support ifindex qualifiers.
8558
   */
8559
0
  switch (cstate->linktype) {
8560
0
  case DLT_LINUX_SLL2:
8561
    /* match packets on this interface */
8562
0
    return gen_cmp(cstate, OR_LINKHDR, 4, BPF_W, ifindex);
8563
0
  default:
8564
0
#if defined(__linux__)
8565
0
    require_basic_bpf_extensions(cstate, "ifindex");
8566
    /* match ifindex */
8567
0
    return gen_cmp(cstate, OR_LINKHDR, SKF_AD_OFF + SKF_AD_IFINDEX, BPF_W,
8568
0
                 ifindex);
8569
#else /* defined(__linux__) */
8570
    fail_kw_on_dlt(cstate, "ifindex");
8571
    /*NOTREACHED*/
8572
#endif /* defined(__linux__) */
8573
0
  }
8574
0
}
8575
8576
/*
8577
 * Filter on inbound (outbound == 0) or outbound (outbound == 1) traffic.
8578
 * Outbound traffic is sent by this machine, while inbound traffic is
8579
 * sent by a remote machine (and may include packets destined for a
8580
 * unicast or multicast link-layer address we are not subscribing to).
8581
 * These are the same definitions implemented by pcap_setdirection().
8582
 * Capturing only unicast traffic destined for this host is probably
8583
 * better accomplished using a higher-layer filter.
8584
 */
8585
struct block *
8586
gen_inbound_outbound(compiler_state_t *cstate, const int outbound)
8587
0
{
8588
0
  struct block *b0;
8589
8590
  /*
8591
   * Catch errors reported by us and routines below us, and return NULL
8592
   * on an error.
8593
   */
8594
0
  if (setjmp(cstate->top_ctx))
8595
0
    return (NULL);
8596
8597
  /*
8598
   * Only some data link types support inbound/outbound qualifiers.
8599
   */
8600
0
  switch (cstate->linktype) {
8601
0
  case DLT_SLIP:
8602
0
    return gen_cmp(cstate, OR_LINKHDR, 0, BPF_B,
8603
0
        outbound ? SLIPDIR_OUT : SLIPDIR_IN);
8604
8605
0
  case DLT_IPNET:
8606
0
    return gen_cmp(cstate, OR_LINKHDR, 2, BPF_H,
8607
0
        outbound ? IPNET_OUTBOUND : IPNET_INBOUND);
8608
8609
0
  case DLT_LINUX_SLL:
8610
    /* match outgoing packets */
8611
0
    b0 = gen_cmp(cstate, OR_LINKHDR, 0, BPF_H, LINUX_SLL_OUTGOING);
8612
    // To filter on inbound traffic, invert the match.
8613
0
    return outbound ? b0 : gen_not(b0);
8614
8615
0
  case DLT_LINUX_SLL2:
8616
    /* match outgoing packets */
8617
0
    b0 = gen_cmp(cstate, OR_LINKHDR, 10, BPF_B, LINUX_SLL_OUTGOING);
8618
    // To filter on inbound traffic, invert the match.
8619
0
    return outbound ? b0 : gen_not(b0);
8620
8621
0
  case DLT_PFLOG:
8622
0
    return gen_cmp(cstate, OR_LINKHDR, offsetof(struct pfloghdr, dir), BPF_B,
8623
0
        outbound ? PF_OUT : PF_IN);
8624
8625
0
  case DLT_PPP_PPPD:
8626
0
    return gen_cmp(cstate, OR_LINKHDR, 0, BPF_B, outbound ? PPP_PPPD_OUT : PPP_PPPD_IN);
8627
8628
0
  case DLT_JUNIPER_MFR:
8629
0
  case DLT_JUNIPER_MLFR:
8630
0
  case DLT_JUNIPER_MLPPP:
8631
0
  case DLT_JUNIPER_ATM1:
8632
0
  case DLT_JUNIPER_ATM2:
8633
0
  case DLT_JUNIPER_PPPOE:
8634
0
  case DLT_JUNIPER_PPPOE_ATM:
8635
0
  case DLT_JUNIPER_GGSN:
8636
0
  case DLT_JUNIPER_ES:
8637
0
  case DLT_JUNIPER_MONITOR:
8638
0
  case DLT_JUNIPER_SERVICES:
8639
0
  case DLT_JUNIPER_ETHER:
8640
0
  case DLT_JUNIPER_PPP:
8641
0
  case DLT_JUNIPER_FRELAY:
8642
0
  case DLT_JUNIPER_CHDLC:
8643
0
  case DLT_JUNIPER_VP:
8644
0
  case DLT_JUNIPER_ST:
8645
0
  case DLT_JUNIPER_ISM:
8646
0
  case DLT_JUNIPER_VS:
8647
0
  case DLT_JUNIPER_SRX_E2E:
8648
0
  case DLT_JUNIPER_FIBRECHANNEL:
8649
0
  case DLT_JUNIPER_ATM_CEMIC:
8650
    /* juniper flags (including direction) are stored
8651
     * the byte after the 3-byte magic number */
8652
0
    return gen_mcmp(cstate, OR_LINKHDR, 3, BPF_B, outbound ? 0 : 1, 0x01);
8653
8654
0
  case DLT_DSA_TAG_BRCM:
8655
    /*
8656
     * This DSA tag encodes the frame direction in the three most
8657
     * significant bits of its first octet: 0b000***** ("egress",
8658
     * switch -> CPU) means "inbound" in libpcap terms and
8659
     * 0b001***** ("ingress", CPU -> switch) means "outbound".
8660
     */
8661
0
    return gen_mcmp(cstate, OR_LINKHDR, 6 + 6, BPF_B,
8662
0
                    outbound ? 0x20 : 0x00, 0xe0);
8663
8664
0
  case DLT_DSA_TAG_DSA:
8665
    /*
8666
     * This DSA tag does not encode the frame direction, but it
8667
     * encodes the frame mode, and some modes imply exactly one
8668
     * direction.  The mode is the two most significant bits of the
8669
     * first octet.  0b00****** ("To_CPU ingress") and 0b10******
8670
     * ("To_Sniffer ingress") mean "inbound" in libpcap terms and
8671
     * 0b01****** ("From_CPU egress") means "outbound".  0x11******
8672
     * ("Forward") can mean either direction, so cannot be used for
8673
     * this purpose.
8674
     *
8675
     * So match 0b01****** for outbound and 0b*0****** otherwise.
8676
     */
8677
0
    return gen_mcmp(cstate, OR_LINKHDR, 6 + 6, BPF_B,
8678
0
                    outbound ? 0x40 : 0x00,
8679
0
                    outbound ? 0xc0 : 0x40);
8680
8681
0
  default:
8682
    /*
8683
     * If we have packet meta-data indicating a direction,
8684
     * and that metadata can be checked by BPF code, check
8685
     * it.  Otherwise, give up, as this link-layer type has
8686
     * nothing in the packet data.
8687
     *
8688
     * Currently, the only platform where a BPF filter can
8689
     * check that metadata is Linux with the in-kernel
8690
     * BPF interpreter.  If other packet capture mechanisms
8691
     * and BPF filters also supported this, it would be
8692
     * nice.  It would be even better if they made that
8693
     * metadata available so that we could provide it
8694
     * with newer capture APIs, allowing it to be saved
8695
     * in pcapng files.
8696
     */
8697
0
#if defined(__linux__)
8698
0
    require_basic_bpf_extensions(cstate, outbound ? "outbound" : "inbound");
8699
    /* match outgoing packets */
8700
0
    b0 = gen_cmp(cstate, OR_LINKHDR, SKF_AD_OFF + SKF_AD_PKTTYPE, BPF_H,
8701
0
                 PACKET_OUTGOING);
8702
    // To filter on inbound traffic, invert the match.
8703
0
    return outbound ? b0 : gen_not(b0);
8704
#else /* defined(__linux__) */
8705
    fail_kw_on_dlt(cstate, outbound ? "outbound" : "inbound");
8706
    /*NOTREACHED*/
8707
#endif /* defined(__linux__) */
8708
0
  }
8709
0
}
8710
8711
/* PF firewall log matched interface */
8712
struct block *
8713
gen_pf_ifname(compiler_state_t *cstate, const char *ifname)
8714
43
{
8715
43
  u_int len, off;
8716
8717
  /*
8718
   * Catch errors reported by us and routines below us, and return NULL
8719
   * on an error.
8720
   */
8721
43
  if (setjmp(cstate->top_ctx))
8722
3
    return (NULL);
8723
8724
40
  assert_pflog(cstate, "ifname");
8725
8726
40
  len = sizeof(((struct pfloghdr *)0)->ifname);
8727
40
  off = offsetof(struct pfloghdr, ifname);
8728
40
  if (strlen(ifname) >= len) {
8729
2
    bpf_error(cstate, "ifname interface names can only be %d characters",
8730
2
        len-1);
8731
    /*NOTREACHED*/
8732
2
  }
8733
38
  return gen_bcmp(cstate, OR_LINKHDR, off, (u_int)strlen(ifname),
8734
38
      (const u_char *)ifname);
8735
40
}
8736
8737
/* PF firewall log ruleset name */
8738
struct block *
8739
gen_pf_ruleset(compiler_state_t *cstate, char *ruleset)
8740
18
{
8741
  /*
8742
   * Catch errors reported by us and routines below us, and return NULL
8743
   * on an error.
8744
   */
8745
18
  if (setjmp(cstate->top_ctx))
8746
5
    return (NULL);
8747
8748
13
  assert_pflog(cstate, "ruleset");
8749
8750
13
  if (strlen(ruleset) >= sizeof(((struct pfloghdr *)0)->ruleset)) {
8751
1
    bpf_error(cstate, "ruleset names can only be %ld characters",
8752
1
        (long)(sizeof(((struct pfloghdr *)0)->ruleset) - 1));
8753
    /*NOTREACHED*/
8754
1
  }
8755
8756
12
  return gen_bcmp(cstate, OR_LINKHDR, offsetof(struct pfloghdr, ruleset),
8757
12
      (u_int)strlen(ruleset), (const u_char *)ruleset);
8758
13
}
8759
8760
/* PF firewall log rule number */
8761
struct block *
8762
gen_pf_rnr(compiler_state_t *cstate, int rnr)
8763
19
{
8764
  /*
8765
   * Catch errors reported by us and routines below us, and return NULL
8766
   * on an error.
8767
   */
8768
19
  if (setjmp(cstate->top_ctx))
8769
9
    return (NULL);
8770
8771
10
  assert_pflog(cstate, "rnr");
8772
8773
10
  return gen_cmp(cstate, OR_LINKHDR, offsetof(struct pfloghdr, rulenr), BPF_W,
8774
10
     (bpf_u_int32)rnr);
8775
19
}
8776
8777
/* PF firewall log sub-rule number */
8778
struct block *
8779
gen_pf_srnr(compiler_state_t *cstate, int srnr)
8780
16
{
8781
  /*
8782
   * Catch errors reported by us and routines below us, and return NULL
8783
   * on an error.
8784
   */
8785
16
  if (setjmp(cstate->top_ctx))
8786
1
    return (NULL);
8787
8788
15
  assert_pflog(cstate, "srnr");
8789
8790
15
  return gen_cmp(cstate, OR_LINKHDR, offsetof(struct pfloghdr, subrulenr), BPF_W,
8791
15
      (bpf_u_int32)srnr);
8792
16
}
8793
8794
/* PF firewall log reason code */
8795
struct block *
8796
gen_pf_reason(compiler_state_t *cstate, int reason)
8797
19
{
8798
  /*
8799
   * Catch errors reported by us and routines below us, and return NULL
8800
   * on an error.
8801
   */
8802
19
  if (setjmp(cstate->top_ctx))
8803
9
    return (NULL);
8804
8805
10
  assert_pflog(cstate, "reason");
8806
8807
10
  return gen_cmp(cstate, OR_LINKHDR, offsetof(struct pfloghdr, reason), BPF_B,
8808
10
      (bpf_u_int32)reason);
8809
19
}
8810
8811
/* PF firewall log action */
8812
struct block *
8813
gen_pf_action(compiler_state_t *cstate, int action)
8814
11
{
8815
  /*
8816
   * Catch errors reported by us and routines below us, and return NULL
8817
   * on an error.
8818
   */
8819
11
  if (setjmp(cstate->top_ctx))
8820
10
    return (NULL);
8821
8822
1
  assert_pflog(cstate, "action");
8823
8824
1
  return gen_cmp(cstate, OR_LINKHDR, offsetof(struct pfloghdr, action), BPF_B,
8825
1
      (bpf_u_int32)action);
8826
11
}
8827
8828
/* IEEE 802.11 wireless header */
8829
struct block *
8830
gen_p80211_type(compiler_state_t *cstate, bpf_u_int32 type, bpf_u_int32 mask)
8831
196
{
8832
  /*
8833
   * Catch errors reported by us and routines below us, and return NULL
8834
   * on an error.
8835
   */
8836
196
  if (setjmp(cstate->top_ctx))
8837
7
    return (NULL);
8838
8839
189
  switch (cstate->linktype) {
8840
8841
41
  case DLT_IEEE802_11:
8842
80
  case DLT_PRISM_HEADER:
8843
116
  case DLT_IEEE802_11_RADIO_AVS:
8844
153
  case DLT_IEEE802_11_RADIO:
8845
189
  case DLT_PPI:
8846
189
    return gen_mcmp(cstate, OR_LINKHDR, 0, BPF_B, type, mask);
8847
8848
7
  default:
8849
7
    fail_kw_on_dlt(cstate, "type/subtype");
8850
    /*NOTREACHED*/
8851
189
  }
8852
189
}
8853
8854
struct block *
8855
gen_p80211_fcdir(compiler_state_t *cstate, bpf_u_int32 fcdir)
8856
228
{
8857
  /*
8858
   * Catch errors reported by us and routines below us, and return NULL
8859
   * on an error.
8860
   */
8861
228
  if (setjmp(cstate->top_ctx))
8862
3
    return (NULL);
8863
8864
225
  switch (cstate->linktype) {
8865
8866
41
  case DLT_IEEE802_11:
8867
101
  case DLT_PRISM_HEADER:
8868
139
  case DLT_IEEE802_11_RADIO_AVS:
8869
187
  case DLT_IEEE802_11_RADIO:
8870
225
  case DLT_PPI:
8871
225
    return gen_mcmp(cstate, OR_LINKHDR, 1, BPF_B, fcdir,
8872
225
        IEEE80211_FC1_DIR_MASK);
8873
8874
3
  default:
8875
3
    fail_kw_on_dlt(cstate, "dir");
8876
    /*NOTREACHED*/
8877
225
  }
8878
225
}
8879
8880
static struct block *
8881
gen_vlan_tpid_test(compiler_state_t *cstate)
8882
740
{
8883
740
  struct block *b0, *b1;
8884
8885
  /* check for VLAN, including 802.1ad and QinQ */
8886
740
  b0 = gen_linktype(cstate, ETHERTYPE_8021Q);
8887
740
  b1 = gen_linktype(cstate, ETHERTYPE_8021AD);
8888
740
  b0 = gen_or(b0, b1);
8889
740
  b1 = gen_linktype(cstate, ETHERTYPE_8021QINQ);
8890
8891
740
  return gen_or(b0, b1);
8892
740
}
8893
8894
static struct block *
8895
gen_vlan_vid_test(compiler_state_t *cstate, bpf_u_int32 vlan_num)
8896
119
{
8897
119
  assert_maxval(cstate, "VLAN tag", vlan_num, 0x0fff);
8898
119
  return gen_mcmp(cstate, OR_LINKPL, 0, BPF_H, vlan_num, 0x0fff);
8899
119
}
8900
8901
static struct block *
8902
gen_vlan_no_bpf_extensions(compiler_state_t *cstate, bpf_u_int32 vlan_num,
8903
    int has_vlan_tag)
8904
740
{
8905
740
  struct block *b0, *b1;
8906
8907
740
  b0 = gen_vlan_tpid_test(cstate);
8908
8909
740
  if (has_vlan_tag) {
8910
119
    b1 = gen_vlan_vid_test(cstate, vlan_num);
8911
119
    b0 = gen_and(b0, b1);
8912
119
  }
8913
8914
  /*
8915
   * Both payload and link header type follow the VLAN tags so that
8916
   * both need to be updated.
8917
   */
8918
740
  cstate->off_linkpl.constant_part += 4;
8919
740
  cstate->off_linktype.constant_part += 4;
8920
8921
740
  return b0;
8922
740
}
8923
8924
#if defined(SKF_AD_VLAN_TAG_PRESENT)
8925
/* Add v to variable part of off. */
8926
static void
8927
gen_vlan_vloffset_add(compiler_state_t *cstate, bpf_abs_offset *off,
8928
    bpf_u_int32 v, struct slist *s)
8929
0
{
8930
0
  struct slist *s2;
8931
8932
0
  if (!off->is_variable)
8933
0
    off->is_variable = 1;
8934
0
  if (off->reg == -1)
8935
0
    off->reg = alloc_reg(cstate);
8936
8937
0
  s2 = new_stmt(cstate, BPF_LD|BPF_MEM);
8938
0
  s2->s.k = off->reg;
8939
0
  sappend(s, s2);
8940
0
  s2 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_IMM);
8941
0
  s2->s.k = v;
8942
0
  sappend(s, s2);
8943
0
  s2 = new_stmt(cstate, BPF_ST);
8944
0
  s2->s.k = off->reg;
8945
0
  sappend(s, s2);
8946
0
}
8947
8948
/*
8949
 * Patch block b_tpid (VLAN TPID test) to update variable parts of link payload
8950
 * and link type offsets first.
8951
 */
8952
static void
8953
gen_vlan_patch_tpid_test(compiler_state_t *cstate, struct block *b_tpid)
8954
0
{
8955
0
  struct slist s;
8956
8957
  /* offset determined at run time, shift variable part */
8958
0
  s.next = NULL;
8959
0
  cstate->is_vlan_vloffset = 1;
8960
0
  gen_vlan_vloffset_add(cstate, &cstate->off_linkpl, 4, &s);
8961
0
  gen_vlan_vloffset_add(cstate, &cstate->off_linktype, 4, &s);
8962
8963
  /* we get a pointer to a chain of or-ed blocks, patch first of them */
8964
0
  sprepend_to_block(s.next, b_tpid->head);
8965
0
}
8966
8967
/*
8968
 * Patch block b_vid (VLAN ID test) to load VID value either from packet
8969
 * metadata (using BPF extensions) if SKF_AD_VLAN_TAG_PRESENT is true.
8970
 */
8971
static void
8972
gen_vlan_patch_vid_test(compiler_state_t *cstate, struct block *b_vid)
8973
0
{
8974
0
  struct slist *s, *s2, *sjeq;
8975
0
  unsigned cnt;
8976
8977
0
  s = new_stmt(cstate, BPF_LD|BPF_B|BPF_ABS);
8978
0
  s->s.k = (bpf_u_int32)(SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT);
8979
8980
  /* true -> next instructions, false -> beginning of b_vid */
8981
0
  sjeq = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
8982
0
  sjeq->s.k = 1;
8983
0
  sjeq->s.jf = b_vid->stmts;
8984
0
  sappend(s, sjeq);
8985
8986
0
  s2 = new_stmt(cstate, BPF_LD|BPF_H|BPF_ABS);
8987
0
  s2->s.k = (bpf_u_int32)(SKF_AD_OFF + SKF_AD_VLAN_TAG);
8988
0
  sappend(s, s2);
8989
0
  sjeq->s.jt = s2;
8990
8991
  /* Jump to the test in b_vid. We need to jump one instruction before
8992
   * the end of the b_vid block so that we only skip loading the TCI
8993
   * from packet data and not the 'and' instruction extracting VID.
8994
   */
8995
0
  cnt = 0;
8996
0
  for (s2 = b_vid->stmts; s2; s2 = s2->next)
8997
0
    cnt++;
8998
0
  s2 = new_stmt(cstate, JMP(BPF_JA, BPF_K));
8999
0
  s2->s.k = cnt - 1;
9000
0
  sappend(s, s2);
9001
9002
  /* insert our statements at the beginning of b_vid */
9003
0
  sprepend_to_block(s, b_vid);
9004
0
}
9005
9006
/*
9007
 * Generate check for "vlan" or "vlan <id>" on systems with support for BPF
9008
 * extensions.  Even if kernel supports VLAN BPF extensions, (outermost) VLAN
9009
 * tag can be either in metadata or in packet data; therefore if the
9010
 * SKF_AD_VLAN_TAG_PRESENT test is negative, we need to check link
9011
 * header for VLAN tag.  As the decision is done at run time, we need to
9012
 * update variable part of the offsets.
9013
 */
9014
static struct block *
9015
gen_vlan_bpf_extensions(compiler_state_t *cstate, bpf_u_int32 vlan_num,
9016
    int has_vlan_tag)
9017
0
{
9018
0
  struct block *b0, *b_tpid, *b_vid = NULL;
9019
0
  struct slist *s;
9020
9021
  /* generate new filter code based on extracting packet
9022
   * metadata */
9023
0
  s = new_stmt(cstate, BPF_LD|BPF_B|BPF_ABS);
9024
0
  s->s.k = (bpf_u_int32)(SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT);
9025
9026
0
  b0 = gen_jmp_k(cstate, BPF_JEQ, 1, s);
9027
9028
  /*
9029
   * This is tricky. We need to insert the statements updating variable
9030
   * parts of offsets before the traditional TPID and VID tests so
9031
   * that they are called whenever SKF_AD_VLAN_TAG_PRESENT fails but
9032
   * we do not want this update to affect those checks. That's why we
9033
   * generate both test blocks first and insert the statements updating
9034
   * variable parts of both offsets after that. This wouldn't work if
9035
   * there already were variable length link header when entering this
9036
   * function but gen_vlan_bpf_extensions() isn't called in that case.
9037
   */
9038
0
  b_tpid = gen_vlan_tpid_test(cstate);
9039
0
  if (has_vlan_tag)
9040
0
    b_vid = gen_vlan_vid_test(cstate, vlan_num);
9041
9042
0
  gen_vlan_patch_tpid_test(cstate, b_tpid);
9043
0
  b0 = gen_or(b0, b_tpid);
9044
9045
0
  if (has_vlan_tag) {
9046
0
    gen_vlan_patch_vid_test(cstate, b_vid);
9047
0
    b0 = gen_and(b0, b_vid);
9048
0
  }
9049
9050
0
  return b0;
9051
0
}
9052
#endif
9053
9054
/*
9055
 * support IEEE 802.1Q VLAN trunk over ethernet
9056
 */
9057
struct block *
9058
gen_vlan(compiler_state_t *cstate, bpf_u_int32 vlan_num, int has_vlan_tag)
9059
757
{
9060
757
  struct  block *b0;
9061
9062
  /*
9063
   * Catch errors reported by us and routines below us, and return NULL
9064
   * on an error.
9065
   */
9066
757
  if (setjmp(cstate->top_ctx))
9067
46
    return (NULL);
9068
9069
  /* can't check for VLAN-encapsulated packets inside MPLS */
9070
711
  if (cstate->label_stack_depth > 0)
9071
1
    bpf_error(cstate, "no VLAN match after MPLS");
9072
9073
  /*
9074
   * Check for a VLAN packet, and then change the offsets to point
9075
   * to the type and data fields within the VLAN packet.  Just
9076
   * increment the offsets, so that we can support a hierarchy, e.g.
9077
   * "vlan 100 && vlan 200" to capture VLAN 200 encapsulated within
9078
   * VLAN 100.
9079
   *
9080
   * XXX - this is a bit of a kludge.  If we were to split the
9081
   * compiler into a parser that parses an expression and
9082
   * generates an expression tree, and a code generator that
9083
   * takes an expression tree (which could come from our
9084
   * parser or from some other parser) and generates BPF code,
9085
   * we could perhaps make the offsets parameters of routines
9086
   * and, in the handler for an "AND" node, pass to subnodes
9087
   * other than the VLAN node the adjusted offsets.
9088
   *
9089
   * This would mean that "vlan" would, instead of changing the
9090
   * behavior of *all* tests after it, change only the behavior
9091
   * of tests ANDed with it.  That would change the documented
9092
   * semantics of "vlan", which might break some expressions.
9093
   * However, it would mean that "(vlan and ip) or ip" would check
9094
   * both for VLAN-encapsulated IP and IP-over-Ethernet, rather than
9095
   * checking only for VLAN-encapsulated IP, so that could still
9096
   * be considered worth doing; it wouldn't break expressions
9097
   * that are of the form "vlan and ..." or "vlan N and ...",
9098
   * which I suspect are the most common expressions involving
9099
   * "vlan".  "vlan or ..." doesn't necessarily do what the user
9100
   * would really want, now, as all the "or ..." tests would
9101
   * be done assuming a VLAN, even though the "or" could be viewed
9102
   * as meaning "or, if this isn't a VLAN packet...".
9103
   */
9104
710
  switch (cstate->linktype) {
9105
9106
85
  case DLT_EN10MB:
9107
    /*
9108
     * Newer version of the Linux kernel pass around
9109
     * packets in which the VLAN tag has been removed
9110
     * from the packet data and put into metadata.
9111
     *
9112
     * This requires special treatment.
9113
     */
9114
85
#if defined(SKF_AD_VLAN_TAG_PRESENT)
9115
    /* Verify that this is the outer part of the packet and
9116
     * not encapsulated somehow. */
9117
85
    if (cstate->vlan_stack_depth == 0 && !cstate->off_linkhdr.is_variable &&
9118
20
        cstate->off_linkhdr.constant_part ==
9119
20
        cstate->off_outermostlinkhdr.constant_part) {
9120
      /*
9121
       * Do we need special VLAN handling?
9122
       */
9123
15
      if (cstate->bpf_pcap->bpf_codegen_flags & BPF_SPECIAL_VLAN_HANDLING)
9124
0
        b0 = gen_vlan_bpf_extensions(cstate, vlan_num,
9125
0
            has_vlan_tag);
9126
15
      else
9127
15
        b0 = gen_vlan_no_bpf_extensions(cstate,
9128
15
            vlan_num, has_vlan_tag);
9129
15
    } else
9130
70
#endif
9131
70
      b0 = gen_vlan_no_bpf_extensions(cstate, vlan_num,
9132
70
          has_vlan_tag);
9133
85
    break;
9134
9135
95
  case DLT_NETANALYZER:
9136
168
  case DLT_NETANALYZER_TRANSPARENT:
9137
243
  case DLT_DSA_TAG_BRCM:
9138
315
  case DLT_DSA_TAG_DSA:
9139
386
  case DLT_IEEE802_11:
9140
459
  case DLT_PRISM_HEADER:
9141
529
  case DLT_IEEE802_11_RADIO_AVS:
9142
655
  case DLT_IEEE802_11_RADIO:
9143
    /*
9144
     * These are either Ethernet packets with an additional
9145
     * metadata header (the NetAnalyzer types), or 802.11
9146
     * packets, possibly with an additional metadata header.
9147
     *
9148
     * For the first of those, the VLAN tag is in the normal
9149
     * place, so the special-case handling above isn't
9150
     * necessary.
9151
     *
9152
     * For the second of those, we don't do the special-case
9153
     * handling for now.
9154
     */
9155
655
    b0 = gen_vlan_no_bpf_extensions(cstate, vlan_num, has_vlan_tag);
9156
655
    break;
9157
9158
16
  default:
9159
16
    fail_kw_on_dlt(cstate, "vlan");
9160
    /*NOTREACHED*/
9161
710
  }
9162
9163
711
  cstate->vlan_stack_depth++;
9164
9165
711
  return (b0);
9166
710
}
9167
9168
/*
9169
 * support for MPLS
9170
 *
9171
 * The label_num_arg dance is to avoid annoying whining by compilers that
9172
 * label_num might be clobbered by longjmp - yeah, it might, but *WHO CARES*?
9173
 * It's not *used* after setjmp returns.
9174
 */
9175
static struct block *
9176
gen_mpls_internal(compiler_state_t *cstate, bpf_u_int32 label_num,
9177
    int has_label_num)
9178
292
{
9179
292
  struct  block *b0, *b1;
9180
9181
292
  if (cstate->label_stack_depth > 0) {
9182
95
    b0 = gen_not(gen_just_after_mpls_stack(cstate));
9183
197
  } else {
9184
    /*
9185
     * We're not in an MPLS stack yet, so check the link-layer
9186
     * type against MPLS.
9187
     */
9188
197
    switch (cstate->linktype) {
9189
9190
22
    case DLT_C_HDLC: /* fall through */
9191
47
    case DLT_HDLC:
9192
119
    case DLT_EN10MB:
9193
128
    case DLT_NETANALYZER:
9194
134
    case DLT_NETANALYZER_TRANSPARENT:
9195
138
    case DLT_DSA_TAG_BRCM:
9196
143
    case DLT_DSA_TAG_DSA:
9197
143
      b0 = gen_linktype(cstate, ETHERTYPE_MPLS);
9198
143
      break;
9199
9200
41
    case DLT_PPP:
9201
41
      b0 = gen_linktype(cstate, PPP_MPLS_UCAST);
9202
41
      break;
9203
9204
      /* FIXME add other DLT_s ...
9205
       * for Frame-Relay/and ATM this may get messy due to SNAP headers
9206
       * leave it for now */
9207
9208
13
    default:
9209
13
      fail_kw_on_dlt(cstate, "mpls");
9210
      /*NOTREACHED*/
9211
197
    }
9212
197
  }
9213
9214
  /* If a specific MPLS label is requested, check it */
9215
279
  if (has_label_num) {
9216
120
    assert_maxval(cstate, "MPLS label", label_num, MPLS_LABEL_MAX);
9217
120
    b1 = gen_mcmp(cstate, OR_LINKPL, 0, BPF_W,
9218
120
        label_num << MPLS_LABEL_SHIFT,
9219
120
        MPLS_LABEL_MAX << MPLS_LABEL_SHIFT);
9220
120
    b0 = gen_and(b0, b1);
9221
120
  }
9222
9223
  /*
9224
   * Change the offsets to point to the type and data fields within
9225
   * the MPLS packet.  Just increment the offsets, so that we
9226
   * can support a hierarchy, e.g. "mpls 100000 && mpls 1024" to
9227
   * capture packets with an outer label of 100000 and an inner
9228
   * label of 1024.
9229
   *
9230
   * Increment the MPLS stack depth as well; this indicates that
9231
   * we're checking MPLS-encapsulated headers, to make sure higher
9232
   * level code generators don't try to match against IP-related
9233
   * protocols such as Q_ARP, Q_RARP etc.
9234
   *
9235
   * XXX - this is a bit of a kludge.  See comments in gen_vlan().
9236
   */
9237
279
  cstate->off_nl_nosnap += MPLS_STACKENTRY_LEN;
9238
279
  cstate->off_nl += MPLS_STACKENTRY_LEN;
9239
279
  cstate->label_stack_depth++;
9240
279
  return (b0);
9241
292
}
9242
9243
struct block *
9244
gen_mpls(compiler_state_t *cstate, bpf_u_int32 label_num, int has_label_num)
9245
292
{
9246
  /*
9247
   * Catch errors reported by us and routines below us, and return NULL
9248
   * on an error.
9249
   */
9250
292
  if (setjmp(cstate->top_ctx))
9251
32
    return (NULL);
9252
9253
260
  return gen_mpls_internal(cstate, label_num, has_label_num);
9254
292
}
9255
9256
/*
9257
 * Support PPPOE discovery and session.
9258
 */
9259
struct block *
9260
gen_pppoed(compiler_state_t *cstate)
9261
24
{
9262
  /*
9263
   * Catch errors reported by us and routines below us, and return NULL
9264
   * on an error.
9265
   */
9266
24
  if (setjmp(cstate->top_ctx))
9267
1
    return (NULL);
9268
9269
  /* check for PPPoE discovery */
9270
23
  return gen_linktype(cstate, ETHERTYPE_PPPOED);
9271
24
}
9272
9273
/*
9274
 * RFC 2516 Section 4:
9275
 *
9276
 * The Ethernet payload for PPPoE is as follows:
9277
 *
9278
 *                      1                   2                   3
9279
 *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
9280
 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
9281
 * |  VER  | TYPE  |      CODE     |          SESSION_ID           |
9282
 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
9283
 * |            LENGTH             |           payload             ~
9284
 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
9285
 */
9286
struct block *
9287
gen_pppoes(compiler_state_t *cstate, bpf_u_int32 sess_num, int has_sess_num)
9288
194
{
9289
194
  struct block *b0, *b1;
9290
9291
  /*
9292
   * Catch errors reported by us and routines below us, and return NULL
9293
   * on an error.
9294
   */
9295
194
  if (setjmp(cstate->top_ctx))
9296
5
    return (NULL);
9297
9298
  /*
9299
   * Test against the PPPoE session link-layer type.
9300
   */
9301
189
  b0 = gen_linktype(cstate, ETHERTYPE_PPPOES);
9302
9303
  /* If a specific session is requested, check PPPoE session id */
9304
189
  if (has_sess_num) {
9305
49
    assert_maxval(cstate, "PPPoE session number", sess_num, UINT16_MAX);
9306
49
    b1 = gen_cmp(cstate, OR_LINKPL, 2, BPF_H, sess_num);
9307
49
    b0 = gen_and(b0, b1);
9308
49
  }
9309
9310
  /*
9311
   * Change the offsets to point to the type and data fields within
9312
   * the PPP packet, and note that this is PPPoE rather than
9313
   * raw PPP.
9314
   *
9315
   * XXX - this is a bit of a kludge.  See the comments in
9316
   * gen_vlan().
9317
   *
9318
   * The "network-layer" protocol is PPPoE, which has a 6-byte
9319
   * PPPoE header, followed by a PPP packet.
9320
   *
9321
   * There is no HDLC encapsulation for the PPP packet (it's
9322
   * encapsulated in PPPoES instead), so the link-layer type
9323
   * starts at the first byte of the PPP packet.  For PPPoE,
9324
   * that offset is relative to the beginning of the total
9325
   * link-layer payload, including any 802.2 LLC header, so
9326
   * it's 6 bytes past cstate->off_nl.
9327
   */
9328
189
  PUSH_LINKHDR(cstate, DLT_PPP, cstate->off_linkpl.is_variable,
9329
189
      cstate->off_linkpl.constant_part + cstate->off_nl + 6, /* 6 bytes past the PPPoE header */
9330
189
      cstate->off_linkpl.reg);
9331
9332
189
  cstate->off_linktype = cstate->off_linkhdr;
9333
189
  cstate->off_linkpl.constant_part = cstate->off_linkhdr.constant_part + 2;
9334
9335
189
  cstate->off_nl = 0;
9336
189
  cstate->off_nl_nosnap = 0;  /* no 802.2 LLC */
9337
9338
189
  return b0;
9339
194
}
9340
9341
/* Check that this is Geneve and the VNI is correct if
9342
 * specified. Parameterized to handle both IPv4 and IPv6. */
9343
static struct block *
9344
gen_geneve_check(compiler_state_t *cstate,
9345
    struct block *(*gen_portfn)(compiler_state_t *, const uint16_t, const int, const u_char, const u_char),
9346
    enum e_offrel offrel, bpf_u_int32 vni, int has_vni)
9347
0
{
9348
0
  struct block *b0, *b1;
9349
9350
0
  b0 = gen_portfn(cstate, GENEVE_PORT, IPPROTO_UDP, Q_DST, Q_PORT);
9351
9352
  /* Check that we are operating on version 0. Otherwise, we
9353
   * can't decode the rest of the fields. The version is 2 bits
9354
   * in the first byte of the Geneve header. */
9355
0
  b1 = gen_mcmp(cstate, offrel, 8, BPF_B, 0, 0xc0);
9356
0
  b0 = gen_and(b0, b1);
9357
9358
0
  if (has_vni) {
9359
0
    assert_maxval(cstate, "Geneve VNI", vni, 0xffffff);
9360
0
    vni <<= 8; /* VNI is in the upper 3 bytes */
9361
0
    b1 = gen_mcmp(cstate, offrel, 12, BPF_W, vni, 0xffffff00);
9362
0
    b0 = gen_and(b0, b1);
9363
0
  }
9364
9365
0
  return b0;
9366
0
}
9367
9368
/* The IPv4 and IPv6 Geneve checks need to do two things:
9369
 * - Verify that this actually is Geneve with the right VNI.
9370
 * - Place the IP header length (plus variable link prefix if
9371
 *   needed) into register A to be used later to compute
9372
 *   the inner packet offsets. */
9373
static struct block *
9374
gen_geneve4(compiler_state_t *cstate, bpf_u_int32 vni, int has_vni)
9375
0
{
9376
0
  struct block *b0, *b1;
9377
0
  struct slist *s, *s1;
9378
9379
0
  b0 = gen_geneve_check(cstate, gen_port, OR_TRAN_IPV4, vni, has_vni);
9380
9381
  /* Load the IP header length into A. */
9382
0
  s = gen_loadx_iphdrlen(cstate);
9383
9384
0
  s1 = new_stmt(cstate, BPF_MISC|BPF_TXA);
9385
0
  sappend(s, s1);
9386
9387
  /* Forcibly append these statements to the true condition
9388
   * of the protocol check by creating a new block that is
9389
   * always true and ANDing them. */
9390
0
  b1 = gen_jmp_x(cstate, BPF_JEQ, s);
9391
9392
0
  return gen_and(b0, b1);
9393
0
}
9394
9395
static struct block *
9396
gen_geneve6(compiler_state_t *cstate, bpf_u_int32 vni, int has_vni)
9397
0
{
9398
0
  struct block *b0, *b1;
9399
0
  struct slist *s, *s1;
9400
9401
0
  b0 = gen_geneve_check(cstate, gen_port6, OR_TRAN_IPV6, vni, has_vni);
9402
9403
  /* Load the IP header length. We need to account for a
9404
   * variable length link prefix if there is one. */
9405
0
  s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
9406
0
  if (s) {
9407
0
    s1 = new_stmt(cstate, BPF_LD|BPF_IMM);
9408
0
    s1->s.k = IP6_HDRLEN;
9409
0
    sappend(s, s1);
9410
9411
0
    s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_X);
9412
0
    s1->s.k = 0;
9413
0
    sappend(s, s1);
9414
0
  } else {
9415
0
    s = new_stmt(cstate, BPF_LD|BPF_IMM);
9416
0
    s->s.k = IP6_HDRLEN;
9417
0
  }
9418
9419
  /* Forcibly append these statements to the true condition
9420
   * of the protocol check by creating a new block that is
9421
   * always true and ANDing them. */
9422
0
  s1 = new_stmt(cstate, BPF_MISC|BPF_TAX);
9423
0
  sappend(s, s1);
9424
9425
0
  b1 = gen_jmp_x(cstate, BPF_JEQ, s);
9426
9427
0
  return gen_and(b0, b1);
9428
0
}
9429
9430
/* We need to store three values based on the Geneve header::
9431
 * - The offset of the linktype.
9432
 * - The offset of the end of the Geneve header.
9433
 * - The offset of the end of the encapsulated MAC header. */
9434
static struct slist *
9435
gen_geneve_offsets(compiler_state_t *cstate)
9436
0
{
9437
0
  struct slist *s, *s1, *s_proto;
9438
9439
  /* First we need to calculate the offset of the Geneve header
9440
   * itself. This is composed of the IP header previously calculated
9441
   * (include any variable link prefix) and stored in A plus the
9442
   * fixed sized headers (fixed link prefix, MAC length, and UDP
9443
   * header). */
9444
0
  s = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
9445
0
  s->s.k = cstate->off_linkpl.constant_part + cstate->off_nl + 8;
9446
9447
  /* Stash this in X since we'll need it later. */
9448
0
  s1 = new_stmt(cstate, BPF_MISC|BPF_TAX);
9449
0
  sappend(s, s1);
9450
9451
  /* The EtherType in Geneve is 2 bytes in. Calculate this and
9452
   * store it. */
9453
0
  s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
9454
0
  s1->s.k = 2;
9455
0
  sappend(s, s1);
9456
9457
0
  cstate->off_linktype.reg = alloc_reg(cstate);
9458
0
  cstate->off_linktype.is_variable = 1;
9459
0
  cstate->off_linktype.constant_part = 0;
9460
9461
0
  s1 = new_stmt(cstate, BPF_ST);
9462
0
  s1->s.k = cstate->off_linktype.reg;
9463
0
  sappend(s, s1);
9464
9465
  /* Load the Geneve option length and mask and shift to get the
9466
   * number of bytes. It is stored in the first byte of the Geneve
9467
   * header. */
9468
0
  s1 = new_stmt(cstate, BPF_LD|BPF_IND|BPF_B);
9469
0
  s1->s.k = 0;
9470
0
  sappend(s, s1);
9471
9472
0
  s1 = new_stmt(cstate, BPF_ALU|BPF_AND|BPF_K);
9473
0
  s1->s.k = 0x3f;
9474
0
  sappend(s, s1);
9475
9476
0
  s1 = new_stmt(cstate, BPF_ALU|BPF_MUL|BPF_K);
9477
0
  s1->s.k = 4;
9478
0
  sappend(s, s1);
9479
9480
  /* Add in the rest of the Geneve base header. */
9481
0
  s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
9482
0
  s1->s.k = 8;
9483
0
  sappend(s, s1);
9484
9485
  /* Add the Geneve header length to its offset and store. */
9486
0
  s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_X);
9487
0
  s1->s.k = 0;
9488
0
  sappend(s, s1);
9489
9490
  /* Set the encapsulated type as Ethernet. Even though we may
9491
   * not actually have Ethernet inside there are two reasons this
9492
   * is useful:
9493
   * - The linktype field is always in EtherType format regardless
9494
   *   of whether it is in Geneve or an inner Ethernet frame.
9495
   * - The only link layer that we have specific support for is
9496
   *   Ethernet. We will confirm that the packet actually is
9497
   *   Ethernet at runtime before executing these checks. */
9498
0
  PUSH_LINKHDR(cstate, DLT_EN10MB, 1, 0, alloc_reg(cstate));
9499
9500
0
  s1 = new_stmt(cstate, BPF_ST);
9501
0
  s1->s.k = cstate->off_linkhdr.reg;
9502
0
  sappend(s, s1);
9503
9504
  /* Calculate whether we have an Ethernet header or just raw IP/
9505
   * MPLS/etc. If we have Ethernet, advance the end of the MAC offset
9506
   * and linktype by 14 bytes so that the network header can be found
9507
   * seamlessly. Otherwise, keep what we've calculated already. */
9508
9509
  /* We have a bare jmp so we can't use the optimizer. */
9510
0
  cstate->no_optimize = 1;
9511
9512
  /* Load the EtherType in the Geneve header, 2 bytes in. */
9513
0
  s1 = new_stmt(cstate, BPF_LD|BPF_IND|BPF_H);
9514
0
  s1->s.k = 2;
9515
0
  sappend(s, s1);
9516
9517
  /* Load X with the end of the Geneve header. */
9518
0
  s1 = new_stmt(cstate, BPF_LDX|BPF_MEM);
9519
0
  s1->s.k = cstate->off_linkhdr.reg;
9520
0
  sappend(s, s1);
9521
9522
  /* Check if the EtherType is Transparent Ethernet Bridging. At the
9523
   * end of this check, we should have the total length in X. In
9524
   * the non-Ethernet case, it's already there. */
9525
0
  s_proto = new_stmt(cstate, JMP(BPF_JEQ, BPF_K));
9526
0
  s_proto->s.k = ETHERTYPE_TEB;
9527
0
  sappend(s, s_proto);
9528
9529
0
  s1 = new_stmt(cstate, BPF_MISC|BPF_TXA);
9530
0
  sappend(s, s1);
9531
0
  s_proto->s.jt = s1;
9532
9533
  /* Since this is Ethernet, use the EtherType of the payload
9534
   * directly as the linktype. Overwrite what we already have. */
9535
0
  s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
9536
0
  s1->s.k = 12;
9537
0
  sappend(s, s1);
9538
9539
0
  s1 = new_stmt(cstate, BPF_ST);
9540
0
  s1->s.k = cstate->off_linktype.reg;
9541
0
  sappend(s, s1);
9542
9543
  /* Advance two bytes further to get the end of the Ethernet
9544
   * header. */
9545
0
  s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
9546
0
  s1->s.k = 2;
9547
0
  sappend(s, s1);
9548
9549
  /* Move the result to X. */
9550
0
  s1 = new_stmt(cstate, BPF_MISC|BPF_TAX);
9551
0
  sappend(s, s1);
9552
9553
  /* Store the final result of our linkpl calculation. */
9554
0
  cstate->off_linkpl.reg = alloc_reg(cstate);
9555
0
  cstate->off_linkpl.is_variable = 1;
9556
0
  cstate->off_linkpl.constant_part = 0;
9557
9558
0
  s1 = new_stmt(cstate, BPF_STX);
9559
0
  s1->s.k = cstate->off_linkpl.reg;
9560
0
  sappend(s, s1);
9561
0
  s_proto->s.jf = s1;
9562
9563
0
  cstate->off_nl = 0;
9564
9565
0
  return s;
9566
0
}
9567
9568
/* Check to see if this is a Geneve packet. */
9569
struct block *
9570
gen_geneve(compiler_state_t *cstate, bpf_u_int32 vni, int has_vni)
9571
0
{
9572
0
  struct block *b0, *b1;
9573
9574
  /*
9575
   * Catch errors reported by us and routines below us, and return NULL
9576
   * on an error.
9577
   */
9578
0
  if (setjmp(cstate->top_ctx))
9579
0
    return (NULL);
9580
9581
0
  b0 = gen_geneve4(cstate, vni, has_vni);
9582
0
  b1 = gen_geneve6(cstate, vni, has_vni);
9583
9584
  /* Later filters should act on the payload of the Geneve frame,
9585
   * update all of the header pointers. Attach this code so that
9586
   * it gets executed in the event that the Geneve filter matches. */
9587
0
  struct block *offsets =
9588
0
    sprepend_to_block(gen_geneve_offsets(cstate), gen_true(cstate));
9589
9590
0
  cstate->is_encap = 1;
9591
9592
0
  return gen_and(gen_or(b0, b1), offsets);
9593
0
}
9594
9595
/* Check that this is VXLAN and the VNI is correct if
9596
 * specified. Parameterized to handle both IPv4 and IPv6. */
9597
static struct block *
9598
gen_vxlan_check(compiler_state_t *cstate,
9599
    struct block *(*gen_portfn)(compiler_state_t *, const uint16_t, const int, const u_char, const u_char),
9600
    enum e_offrel offrel, bpf_u_int32 vni, int has_vni)
9601
578
{
9602
578
  struct block *b0, *b1;
9603
9604
578
  b0 = gen_portfn(cstate, VXLAN_PORT, IPPROTO_UDP, Q_DST, Q_PORT);
9605
9606
  /* Check that the VXLAN header has the flag bits set
9607
   * correctly. */
9608
578
  b1 = gen_cmp(cstate, offrel, 8, BPF_B, 0x08);
9609
578
  b0 = gen_and(b0, b1);
9610
9611
578
  if (has_vni) {
9612
146
    assert_maxval(cstate, "VXLAN VNI", vni, 0xffffff);
9613
146
    vni <<= 8; /* VNI is in the upper 3 bytes */
9614
146
    b1 = gen_mcmp(cstate, offrel, 12, BPF_W, vni, 0xffffff00);
9615
146
    b0 = gen_and(b0, b1);
9616
146
  }
9617
9618
578
  return b0;
9619
578
}
9620
9621
/* The IPv4 and IPv6 VXLAN checks need to do two things:
9622
 * - Verify that this actually is VXLAN with the right VNI.
9623
 * - Place the IP header length (plus variable link prefix if
9624
 *   needed) into register A to be used later to compute
9625
 *   the inner packet offsets. */
9626
static struct block *
9627
gen_vxlan4(compiler_state_t *cstate, bpf_u_int32 vni, int has_vni)
9628
295
{
9629
295
  struct block *b0, *b1;
9630
295
  struct slist *s, *s1;
9631
9632
295
  b0 = gen_vxlan_check(cstate, gen_port, OR_TRAN_IPV4, vni, has_vni);
9633
9634
  /* Load the IP header length into A. */
9635
295
  s = gen_loadx_iphdrlen(cstate);
9636
9637
295
  s1 = new_stmt(cstate, BPF_MISC|BPF_TXA);
9638
295
  sappend(s, s1);
9639
9640
  /* Forcibly append these statements to the true condition
9641
   * of the protocol check by creating a new block that is
9642
   * always true and ANDing them. */
9643
295
  b1 = gen_jmp_x(cstate, BPF_JEQ, s);
9644
9645
295
  return gen_and(b0, b1);
9646
295
}
9647
9648
static struct block *
9649
gen_vxlan6(compiler_state_t *cstate, bpf_u_int32 vni, int has_vni)
9650
283
{
9651
283
  struct block *b0, *b1;
9652
283
  struct slist *s, *s1;
9653
9654
283
  b0 = gen_vxlan_check(cstate, gen_port6, OR_TRAN_IPV6, vni, has_vni);
9655
9656
  /* Load the IP header length. We need to account for a
9657
   * variable length link prefix if there is one. */
9658
283
  s = gen_abs_offset_varpart(cstate, &cstate->off_linkpl);
9659
283
  if (s) {
9660
169
    s1 = new_stmt(cstate, BPF_LD|BPF_IMM);
9661
169
    s1->s.k = IP6_HDRLEN;
9662
169
    sappend(s, s1);
9663
9664
169
    s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_X);
9665
169
    s1->s.k = 0;
9666
169
    sappend(s, s1);
9667
169
  } else {
9668
114
    s = new_stmt(cstate, BPF_LD|BPF_IMM);
9669
114
    s->s.k = IP6_HDRLEN;
9670
114
  }
9671
9672
  /* Forcibly append these statements to the true condition
9673
   * of the protocol check by creating a new block that is
9674
   * always true and ANDing them. */
9675
283
  s1 = new_stmt(cstate, BPF_MISC|BPF_TAX);
9676
283
  sappend(s, s1);
9677
9678
283
  b1 = gen_jmp_x(cstate, BPF_JEQ, s);
9679
9680
283
  return gen_and(b0, b1);
9681
283
}
9682
9683
/* We need to store three values based on the VXLAN header:
9684
 * - The offset of the linktype.
9685
 * - The offset of the end of the VXLAN header.
9686
 * - The offset of the end of the encapsulated MAC header. */
9687
static struct slist *
9688
gen_vxlan_offsets(compiler_state_t *cstate)
9689
283
{
9690
283
  struct slist *s, *s1;
9691
9692
  /* Calculate the offset of the VXLAN header itself. This
9693
   * includes the IP header computed previously (including any
9694
   * variable link prefix) and stored in A plus the fixed size
9695
   * headers (fixed link prefix, MAC length, UDP header). */
9696
283
  s = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
9697
283
  s->s.k = cstate->off_linkpl.constant_part + cstate->off_nl + 8;
9698
9699
  /* Add the VXLAN header length to its offset and store */
9700
283
  s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
9701
283
  s1->s.k = 8;
9702
283
  sappend(s, s1);
9703
9704
  /* Push the link header. VXLAN packets always contain Ethernet
9705
   * frames. */
9706
283
  PUSH_LINKHDR(cstate, DLT_EN10MB, 1, 0, alloc_reg(cstate));
9707
9708
283
  s1 = new_stmt(cstate, BPF_ST);
9709
283
  s1->s.k = cstate->off_linkhdr.reg;
9710
283
  sappend(s, s1);
9711
9712
  /* As the payload is an Ethernet packet, we can use the
9713
   * EtherType of the payload directly as the linktype. */
9714
283
  s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
9715
283
  s1->s.k = 12;
9716
283
  sappend(s, s1);
9717
9718
283
  cstate->off_linktype.reg = alloc_reg(cstate);
9719
283
  cstate->off_linktype.is_variable = 1;
9720
283
  cstate->off_linktype.constant_part = 0;
9721
9722
283
  s1 = new_stmt(cstate, BPF_ST);
9723
283
  s1->s.k = cstate->off_linktype.reg;
9724
283
  sappend(s, s1);
9725
9726
  /* Two bytes further is the end of the Ethernet header and the
9727
   * start of the payload. */
9728
283
  s1 = new_stmt(cstate, BPF_ALU|BPF_ADD|BPF_K);
9729
283
  s1->s.k = 2;
9730
283
  sappend(s, s1);
9731
9732
  /* Move the result to X. */
9733
283
  s1 = new_stmt(cstate, BPF_MISC|BPF_TAX);
9734
283
  sappend(s, s1);
9735
9736
  /* Store the final result of our linkpl calculation. */
9737
283
  cstate->off_linkpl.reg = alloc_reg(cstate);
9738
283
  cstate->off_linkpl.is_variable = 1;
9739
283
  cstate->off_linkpl.constant_part = 0;
9740
9741
283
  s1 = new_stmt(cstate, BPF_STX);
9742
283
  s1->s.k = cstate->off_linkpl.reg;
9743
283
  sappend(s, s1);
9744
9745
283
  cstate->off_nl = 0;
9746
9747
283
  return s;
9748
283
}
9749
9750
/* Check to see if this is a VXLAN packet. */
9751
struct block *
9752
gen_vxlan(compiler_state_t *cstate, bpf_u_int32 vni, int has_vni)
9753
295
{
9754
295
  struct block *b0, *b1;
9755
9756
  /*
9757
   * Catch errors reported by us and routines below us, and return NULL
9758
   * on an error.
9759
   */
9760
295
  if (setjmp(cstate->top_ctx))
9761
20
    return (NULL);
9762
9763
  /*
9764
   * This code generates blocks that are known to trigger a bug in the
9765
   * optimizer (see GitHub 1670), so avoid the bug until it gets fixed.
9766
   */
9767
275
  cstate->no_optimize = 1;
9768
9769
275
  b0 = gen_vxlan4(cstate, vni, has_vni);
9770
275
  b1 = gen_vxlan6(cstate, vni, has_vni);
9771
9772
  /* Later filters should act on the payload of the VXLAN frame,
9773
   * update all of the header pointers. Attach this code so that
9774
   * it gets executed in the event that the VXLAN filter matches. */
9775
275
  struct block *offsets =
9776
275
    sprepend_to_block(gen_vxlan_offsets(cstate), gen_true(cstate));
9777
9778
275
  cstate->is_encap = 1;
9779
9780
275
  return gen_and(gen_or(b0, b1), offsets);
9781
295
}
9782
9783
/* Check that the encapsulated frame has a link layer header
9784
 * for Ethernet filters. */
9785
static struct block *
9786
gen_encap_ll_check(compiler_state_t *cstate)
9787
35
{
9788
35
  struct block *b0;
9789
35
  struct slist *s, *s1;
9790
9791
  /* The easiest way to see if there is a link layer present
9792
   * is to check if the link layer header and payload are not
9793
   * the same. */
9794
9795
  /* Geneve always generates pure variable offsets so we can
9796
   * compare only the registers. */
9797
35
  s = new_stmt(cstate, BPF_LD|BPF_MEM);
9798
35
  s->s.k = cstate->off_linkhdr.reg;
9799
9800
35
  s1 = new_stmt(cstate, BPF_LDX|BPF_MEM);
9801
35
  s1->s.k = cstate->off_linkpl.reg;
9802
35
  sappend(s, s1);
9803
9804
35
  b0 = gen_jmp_x(cstate, BPF_JEQ, s);
9805
9806
35
  return gen_not(b0);
9807
35
}
9808
9809
static struct block *
9810
gen_atmfield_code_internal(compiler_state_t *cstate, int atmfield,
9811
    bpf_u_int32 jvalue, int jtype, int reverse)
9812
552
{
9813
552
  assert_atm(cstate, atmkw(atmfield));
9814
9815
552
  switch (atmfield) {
9816
9817
264
  case A_VPI:
9818
264
    assert_maxval(cstate, "VPI", jvalue, UINT8_MAX);
9819
264
    return gen_ncmp(cstate, OR_LINKHDR, cstate->off_vpi, BPF_B,
9820
264
        0xffffffffU, jtype, reverse, jvalue);
9821
9822
278
  case A_VCI:
9823
278
    assert_maxval(cstate, "VCI", jvalue, UINT16_MAX);
9824
278
    return gen_ncmp(cstate, OR_LINKHDR, cstate->off_vci, BPF_H,
9825
278
        0xffffffffU, jtype, reverse, jvalue);
9826
9827
0
  default:
9828
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "atmfield", atmfield);
9829
552
  }
9830
552
}
9831
9832
static struct block *
9833
gen_atm_vpi(compiler_state_t *cstate, const uint8_t v)
9834
92
{
9835
92
  return gen_atmfield_code_internal(cstate, A_VPI, v, BPF_JEQ, 0);
9836
92
}
9837
9838
static struct block *
9839
gen_atm_vci(compiler_state_t *cstate, const uint16_t v)
9840
115
{
9841
115
  return gen_atmfield_code_internal(cstate, A_VCI, v, BPF_JEQ, 0);
9842
115
}
9843
9844
static struct block *
9845
gen_atm_prototype(compiler_state_t *cstate, const uint8_t v)
9846
1.27k
{
9847
1.27k
  return gen_mcmp(cstate, OR_LINKHDR, cstate->off_proto, BPF_B, v, 0x0fU);
9848
1.27k
}
9849
9850
static struct block *
9851
gen_atmtype_llc(compiler_state_t *cstate)
9852
76
{
9853
76
  struct block *b0;
9854
9855
76
  b0 = gen_atm_prototype(cstate, PT_LLC);
9856
76
  cstate->linktype = cstate->prevlinktype;
9857
76
  return b0;
9858
76
}
9859
9860
struct block *
9861
gen_atmfield_code(compiler_state_t *cstate, int atmfield,
9862
    bpf_u_int32 jvalue, int jtype, int reverse)
9863
345
{
9864
  /*
9865
   * Catch errors reported by us and routines below us, and return NULL
9866
   * on an error.
9867
   */
9868
345
  if (setjmp(cstate->top_ctx))
9869
69
    return (NULL);
9870
9871
276
  return gen_atmfield_code_internal(cstate, atmfield, jvalue, jtype,
9872
276
      reverse);
9873
345
}
9874
9875
struct block *
9876
gen_atmtype_abbrev(compiler_state_t *cstate, int type)
9877
168
{
9878
168
  struct block *b0, *b1;
9879
9880
  /*
9881
   * Catch errors reported by us and routines below us, and return NULL
9882
   * on an error.
9883
   */
9884
168
  if (setjmp(cstate->top_ctx))
9885
13
    return (NULL);
9886
9887
155
  assert_atm(cstate, atmkw(type));
9888
9889
155
  switch (type) {
9890
9891
10
  case A_METAC:
9892
    /* Get all packets in Meta signalling Circuit */
9893
10
    b0 = gen_atm_vpi(cstate, 0);
9894
10
    b1 = gen_atm_vci(cstate, 1);
9895
10
    return gen_and(b0, b1);
9896
9897
10
  case A_BCC:
9898
    /* Get all packets in Broadcast Circuit*/
9899
10
    b0 = gen_atm_vpi(cstate, 0);
9900
10
    b1 = gen_atm_vci(cstate, 2);
9901
10
    return gen_and(b0, b1);
9902
9903
10
  case A_OAMF4SC:
9904
    /* Get all cells in Segment OAM F4 circuit*/
9905
10
    b0 = gen_atm_vpi(cstate, 0);
9906
10
    b1 = gen_atm_vci(cstate, 3);
9907
10
    return gen_and(b0, b1);
9908
9909
5
  case A_OAMF4EC:
9910
    /* Get all cells in End-to-End OAM F4 Circuit*/
9911
5
    b0 = gen_atm_vpi(cstate, 0);
9912
5
    b1 = gen_atm_vci(cstate, 4);
9913
5
    return gen_and(b0, b1);
9914
9915
33
  case A_SC:
9916
    /*  Get all packets in connection Signalling Circuit */
9917
33
    b0 = gen_atm_vpi(cstate, 0);
9918
33
    b1 = gen_atm_vci(cstate, 5);
9919
33
    return gen_and(b0, b1);
9920
9921
1
  case A_ILMIC:
9922
    /* Get all packets in ILMI Circuit */
9923
1
    b0 = gen_atm_vpi(cstate, 0);
9924
1
    b1 = gen_atm_vci(cstate, 16);
9925
1
    return gen_and(b0, b1);
9926
9927
86
  case A_LANE:
9928
    /* Get all LANE packets */
9929
86
    b1 = gen_atm_prototype(cstate, PT_LANE);
9930
9931
    /*
9932
     * Arrange that all subsequent tests assume LANE
9933
     * rather than LLC-encapsulated packets, and set
9934
     * the offsets appropriately for LANE-encapsulated
9935
     * Ethernet.
9936
     *
9937
     * We assume LANE means Ethernet, not Token Ring.
9938
     */
9939
86
    PUSH_LINKHDR(cstate, DLT_EN10MB, 0,
9940
86
        cstate->off_payload + 2,  /* Ethernet header */
9941
86
        -1);
9942
86
    cstate->off_linktype.constant_part = cstate->off_linkhdr.constant_part + 12;
9943
86
    cstate->off_linkpl.constant_part = cstate->off_linkhdr.constant_part + 14;  /* Ethernet */
9944
86
    cstate->off_nl = 0;     /* Ethernet II */
9945
86
    cstate->off_nl_nosnap = 3;    /* 802.3+802.2 */
9946
86
    return b1;
9947
9948
0
  default:
9949
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "type", type);
9950
155
  }
9951
155
}
9952
9953
/*
9954
 * Filtering for MTP2 messages based on li value
9955
 * FISU, length is null
9956
 * LSSU, length is 1 or 2
9957
 * MSU, length is 3 or more
9958
 * For MTP2_HSL, sequences are on 2 bytes, and length on 9 bits
9959
 */
9960
struct block *
9961
gen_mtp2type_abbrev(compiler_state_t *cstate, int type)
9962
244
{
9963
244
  struct block *b0, *b1;
9964
9965
  /*
9966
   * Catch errors reported by us and routines below us, and return NULL
9967
   * on an error.
9968
   */
9969
244
  if (setjmp(cstate->top_ctx))
9970
2
    return (NULL);
9971
9972
242
  assert_ss7(cstate, ss7kw(type));
9973
9974
242
  switch (type) {
9975
9976
19
  case M_FISU:
9977
19
    return gen_ncmp(cstate, OR_PACKET, cstate->off_li, BPF_B,
9978
19
        0x3fU, BPF_JEQ, 0, 0U);
9979
9980
139
  case M_LSSU:
9981
139
    b0 = gen_ncmp(cstate, OR_PACKET, cstate->off_li, BPF_B,
9982
139
        0x3fU, BPF_JGT, 1, 2U);
9983
139
    b1 = gen_ncmp(cstate, OR_PACKET, cstate->off_li, BPF_B,
9984
139
        0x3fU, BPF_JGT, 0, 0U);
9985
139
    return gen_and(b1, b0);
9986
9987
47
  case M_MSU:
9988
47
    return gen_ncmp(cstate, OR_PACKET, cstate->off_li, BPF_B,
9989
47
        0x3fU, BPF_JGT, 0, 2U);
9990
9991
7
  case MH_FISU:
9992
7
    return gen_ncmp(cstate, OR_PACKET, cstate->off_li_hsl, BPF_H,
9993
7
        0xff80U, BPF_JEQ, 0, 0U);
9994
9995
16
  case MH_LSSU:
9996
16
    b0 = gen_ncmp(cstate, OR_PACKET, cstate->off_li_hsl, BPF_H,
9997
16
        0xff80U, BPF_JGT, 1, 0x0100U);
9998
16
    b1 = gen_ncmp(cstate, OR_PACKET, cstate->off_li_hsl, BPF_H,
9999
16
        0xff80U, BPF_JGT, 0, 0U);
10000
16
    return gen_and(b1, b0);
10001
10002
14
  case MH_MSU:
10003
14
    return gen_ncmp(cstate, OR_PACKET, cstate->off_li_hsl, BPF_H,
10004
14
        0xff80U, BPF_JGT, 0, 0x0100U);
10005
10006
0
  default:
10007
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "type", type);
10008
242
  }
10009
242
}
10010
10011
/*
10012
 * These maximum valid values are all-ones, so they double as the bitmasks
10013
 * before any bitwise shifting.
10014
 */
10015
242
#define MTP2_SIO_MAXVAL UINT8_MAX
10016
328
#define MTP3_PC_MAXVAL 0x3fffU
10017
416
#define MTP3_SLS_MAXVAL 0xfU
10018
10019
static struct block *
10020
gen_mtp3field_code_internal(compiler_state_t *cstate, int mtp3field,
10021
    bpf_u_int32 jvalue, int jtype, int reverse)
10022
783
{
10023
783
  u_int newoff_sio;
10024
783
  u_int newoff_opc;
10025
783
  u_int newoff_dpc;
10026
783
  u_int newoff_sls;
10027
10028
783
  newoff_sio = cstate->off_sio;
10029
783
  newoff_opc = cstate->off_opc;
10030
783
  newoff_dpc = cstate->off_dpc;
10031
783
  newoff_sls = cstate->off_sls;
10032
10033
783
  assert_ss7(cstate, ss7kw(mtp3field));
10034
10035
783
  switch (mtp3field) {
10036
10037
  /*
10038
   * See UTU-T Rec. Q.703, Section 2.2, Figure 3/Q.703.
10039
   *
10040
   * SIO is the simplest field: the size is one byte and the offset is a
10041
   * multiple of bytes, so the only detail to get right is the value of
10042
   * the [right-to-left] field offset.
10043
   */
10044
97
  case MH_SIO:
10045
97
    newoff_sio += 3; /* offset for MTP2_HSL */
10046
    /* FALLTHROUGH */
10047
10048
242
  case M_SIO:
10049
242
    assert_maxval(cstate, ss7kw(mtp3field), jvalue, MTP2_SIO_MAXVAL);
10050
    // Here the bitmask means "do not apply a bitmask".
10051
242
    return gen_ncmp(cstate, OR_PACKET, newoff_sio, BPF_B, UINT32_MAX,
10052
242
        jtype, reverse, jvalue);
10053
10054
  /*
10055
   * See UTU-T Rec. Q.704, Section 2.2, Figure 3/Q.704.
10056
   *
10057
   * SLS, OPC and DPC are more complicated: none of these is sized in a
10058
   * multiple of 8 bits, MTP3 encoding is little-endian and MTP packet
10059
   * diagrams are meant to be read right-to-left.  This means in the
10060
   * diagrams within individual fields and concatenations thereof
10061
   * bitwise shifts and masks can be noted in the common left-to-right
10062
   * manner until each final value is ready to be byte-swapped and
10063
   * handed to gen_ncmp().  See also gen_dnhostop(), which solves a
10064
   * similar problem in a similar way.
10065
   *
10066
   * Offsets of fields within the packet header always have the
10067
   * right-to-left meaning.  Note that in DLT_MTP2 and possibly other
10068
   * DLTs the offset does not include the F (Flag) field at the
10069
   * beginning of each message.
10070
   *
10071
   * For example, if the 8-bit SIO field has a 3 byte [RTL] offset, the
10072
   * 32-bit standard routing header has a 4 byte [RTL] offset and could
10073
   * be tested entirely using a single BPF_W comparison.  In this case
10074
   * the 14-bit DPC field [LTR] bitmask would be 0x3FFF, the 14-bit OPC
10075
   * field [LTR] bitmask would be (0x3FFF << 14) and the 4-bit SLS field
10076
   * [LTR] bitmask would be (0xF << 28), all of which conveniently
10077
   * correlates with the [RTL] packet diagram until the byte-swapping is
10078
   * done before use.
10079
   *
10080
   * The code below uses this approach for OPC, which spans 3 bytes.
10081
   * DPC and SLS use shorter loads, SLS also uses a different offset.
10082
   */
10083
66
  case MH_OPC:
10084
66
    newoff_opc += 3;
10085
10086
    /* FALLTHROUGH */
10087
175
  case M_OPC:
10088
175
    assert_maxval(cstate, ss7kw(mtp3field), jvalue, MTP3_PC_MAXVAL);
10089
175
    return gen_ncmp(cstate, OR_PACKET, newoff_opc, BPF_W,
10090
175
        PCAP_BSWAP_32(MTP3_PC_MAXVAL << 14), jtype, reverse,
10091
175
        PCAP_BSWAP_32(jvalue << 14));
10092
10093
61
  case MH_DPC:
10094
61
    newoff_dpc += 3;
10095
    /* FALLTHROUGH */
10096
10097
153
  case M_DPC:
10098
153
    assert_maxval(cstate, ss7kw(mtp3field), jvalue, MTP3_PC_MAXVAL);
10099
153
    return gen_ncmp(cstate, OR_PACKET, newoff_dpc, BPF_H,
10100
153
        PCAP_BSWAP_16(MTP3_PC_MAXVAL), jtype, reverse,
10101
153
        PCAP_BSWAP_16(jvalue));
10102
10103
73
  case MH_SLS:
10104
73
    newoff_sls += 3;
10105
    /* FALLTHROUGH */
10106
10107
208
  case M_SLS:
10108
208
    assert_maxval(cstate, ss7kw(mtp3field), jvalue, MTP3_SLS_MAXVAL);
10109
208
    return gen_ncmp(cstate, OR_PACKET, newoff_sls, BPF_B,
10110
208
        MTP3_SLS_MAXVAL << 4, jtype, reverse,
10111
208
        jvalue << 4);
10112
10113
0
  default:
10114
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "mtp3field", mtp3field);
10115
783
  }
10116
783
}
10117
10118
struct block *
10119
gen_mtp3field_code(compiler_state_t *cstate, int mtp3field,
10120
    bpf_u_int32 jvalue, int jtype, int reverse)
10121
783
{
10122
  /*
10123
   * Catch errors reported by us and routines below us, and return NULL
10124
   * on an error.
10125
   */
10126
783
  if (setjmp(cstate->top_ctx))
10127
140
    return (NULL);
10128
10129
643
  return gen_mtp3field_code_internal(cstate, mtp3field, jvalue, jtype,
10130
643
      reverse);
10131
783
}
10132
10133
static struct block *
10134
gen_msg_abbrev(compiler_state_t *cstate, const uint8_t type)
10135
0
{
10136
  /*
10137
   * Q.2931 signalling protocol messages for handling virtual circuits
10138
   * establishment and teardown
10139
   */
10140
0
  return gen_cmp(cstate, OR_LINKHDR, cstate->off_payload + MSG_TYPE_POS,
10141
0
      BPF_B, type);
10142
0
}
10143
10144
struct block *
10145
gen_atmmulti_abbrev(compiler_state_t *cstate, int type)
10146
31
{
10147
31
  struct block *b0, *b1;
10148
10149
  /*
10150
   * Catch errors reported by us and routines below us, and return NULL
10151
   * on an error.
10152
   */
10153
31
  if (setjmp(cstate->top_ctx))
10154
8
    return (NULL);
10155
10156
23
  assert_atm(cstate, atmkw(type));
10157
10158
23
  switch (type) {
10159
10160
12
  case A_OAM:
10161
    /* OAM F4 type */
10162
12
    b0 = gen_atm_vci(cstate, 3);
10163
12
    b1 = gen_atm_vci(cstate, 4);
10164
12
    b1 = gen_or(b0, b1);
10165
12
    b0 = gen_atm_vpi(cstate, 0);
10166
12
    return gen_and(b0, b1);
10167
10168
11
  case A_OAMF4:
10169
    /* OAM F4 type */
10170
11
    b0 = gen_atm_vci(cstate, 3);
10171
11
    b1 = gen_atm_vci(cstate, 4);
10172
11
    b1 = gen_or(b0, b1);
10173
11
    b0 = gen_atm_vpi(cstate, 0);
10174
11
    return gen_and(b0, b1);
10175
10176
0
  case A_CONNECTMSG:
10177
    /*
10178
     * Get Q.2931 signalling messages for switched
10179
     * virtual connection
10180
     */
10181
0
    b0 = gen_msg_abbrev(cstate, SETUP);
10182
0
    b1 = gen_msg_abbrev(cstate, CALL_PROCEED);
10183
0
    b1 = gen_or(b0, b1);
10184
0
    b0 = gen_msg_abbrev(cstate, CONNECT);
10185
0
    b1 = gen_or(b0, b1);
10186
0
    b0 = gen_msg_abbrev(cstate, CONNECT_ACK);
10187
0
    b1 = gen_or(b0, b1);
10188
0
    b0 = gen_msg_abbrev(cstate, RELEASE);
10189
0
    b1 = gen_or(b0, b1);
10190
0
    b0 = gen_msg_abbrev(cstate, RELEASE_DONE);
10191
0
    b1 = gen_or(b0, b1);
10192
0
    b0 = gen_atmtype_abbrev(cstate, A_SC);
10193
0
    return gen_and(b0, b1);
10194
10195
0
  case A_METACONNECT:
10196
0
    b0 = gen_msg_abbrev(cstate, SETUP);
10197
0
    b1 = gen_msg_abbrev(cstate, CALL_PROCEED);
10198
0
    b1 = gen_or(b0, b1);
10199
0
    b0 = gen_msg_abbrev(cstate, CONNECT);
10200
0
    b1 = gen_or(b0, b1);
10201
0
    b0 = gen_msg_abbrev(cstate, RELEASE);
10202
0
    b1 = gen_or(b0, b1);
10203
0
    b0 = gen_msg_abbrev(cstate, RELEASE_DONE);
10204
0
    b1 = gen_or(b0, b1);
10205
0
    b0 = gen_atmtype_abbrev(cstate, A_METAC);
10206
0
    return gen_and(b0, b1);
10207
10208
0
  default:
10209
0
    bpf_error(cstate, ERRSTR_FUNC_VAR_INT, __func__, "type", type);
10210
23
  }
10211
23
}