Coverage Report

Created: 2026-10-17 08:12

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