suricata
util-bpf.c
Go to the documentation of this file.
1 /* Copyright (C) 2018 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Eric Leblond <eric@regit.org>
22  */
23 
24 #include "suricata-common.h"
25 #include "util-bpf.h"
26 #include "threads.h"
27 
28 #if !defined __OpenBSD__
29 
30 /** protect bpf filter build, as it is not thread safe */
31 static SCMutex bpf_set_filter_lock = SCMUTEX_INITIALIZER;
32 
33 void SCBPFFree(struct bpf_program *program)
34 {
35  if (program)
36  pcap_freecode(program);
37 }
38 
39 int SCBPFCompile(int snaplen_arg, int linktype_arg, struct bpf_program *program,
40  const char *buf,
41  int optimize, uint32_t mask,
42  char *errbuf, size_t errbuf_len)
43 {
44  pcap_t *p;
45  int ret;
46 
47  p = pcap_open_dead(linktype_arg, snaplen_arg);
48  if (p == NULL)
49  return (-1);
50 
51  SCMutexLock(&bpf_set_filter_lock);
52  ret = pcap_compile(p, program, buf, optimize, mask);
53  if (ret == -1) {
54  if (errbuf) {
55  snprintf(errbuf, errbuf_len, "%s", pcap_geterr(p));
56  }
57  pcap_close(p);
58  SCMutexUnlock(&bpf_set_filter_lock);
59  return (-1);
60  }
61  pcap_close(p);
62  SCMutexUnlock(&bpf_set_filter_lock);
63 
64  if (program->bf_insns == NULL) {
65  if (errbuf) {
66  snprintf(errbuf, errbuf_len, "Filter badly setup");
67  }
68  SCBPFFree(program);
69  return (-1);
70  }
71 
72  return (ret);
73 }
74 
75 #endif /* Not __OpenBSD__ */
bpf_program::bf_insns
struct bpf_insn * bf_insns
Definition: source-af-packet.c:82
util-bpf.h
threads.h
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
SCMUTEX_INITIALIZER
#define SCMUTEX_INITIALIZER
Definition: threads-debug.h:121
SCMutexUnlock
#define SCMutexUnlock(mut)
Definition: threads-debug.h:119
suricata-common.h
SCBPFFree
void SCBPFFree(struct bpf_program *program)
Definition: util-bpf.c:33
bpf_program
Definition: source-af-packet.c:80
SCBPFCompile
int SCBPFCompile(int snaplen_arg, int linktype_arg, struct bpf_program *program, const char *buf, int optimize, uint32_t mask, char *errbuf, size_t errbuf_len)
Definition: util-bpf.c:39
SCMutex
#define SCMutex
Definition: threads-debug.h:114