Coverage Report

Created: 2026-09-20 07:25

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