Coverage Report

Created: 2026-10-07 07:40

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