Coverage Report

Created: 2026-07-15 07:07

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