-
Notifications
You must be signed in to change notification settings - Fork 1
/
bpfobj.cc
107 lines (83 loc) · 2.13 KB
/
bpfobj.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* Copyright (c) 2003 CORE Security Technologies
*
* This software is provided under under a slightly modified version
* of the Apache Software License. See the accompanying LICENSE file
* for more information.
*
* $Id: bpfobj.cc,v 1.4 2003/10/24 18:49:33 jkohen Exp $
*/
#include <pcap.h>
#include <Python.h>
#include "bpfobj.h"
#include "pcapy.h"
// internal bpfobject
typedef struct {
PyObject_HEAD
struct bpf_program bpf;
} bpfobject;
// BPFProgramType
static void
bpfprog_dealloc(register bpfobject* bpf)
{
#ifndef WIN32 // XXX: is this missing from winpcap 2.3?
pcap_freecode(&bpf->bpf);
#endif
PyObject_Del(bpf);
}
// BPFProgram methods
static PyObject* p_filter(register bpfobject* bpf, PyObject* args);
static PyMethodDef bpf_methods[] = {
{"filter", (PyCFunction) p_filter, METH_VARARGS, "filter() filters a given packet"},
{NULL, NULL} /* sentinel */
};
static PyObject*
bpfprog_getattr(bpfobject* pp, char* name)
{
return Py_FindMethod(bpf_methods, (PyObject*)pp, name);
}
PyTypeObject BPFProgramtype = {
PyObject_HEAD_INIT(NULL)
0,
"Bpf",
sizeof(bpfobject),
0,
/* methods */
(destructor)bpfprog_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)bpfprog_getattr, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
};
PyObject*
new_bpfobject(const struct bpf_program &bpfprog)
{
bpfobject *bpf;
bpf = PyObject_New(bpfobject, &BPFProgramtype);
if (bpf == NULL)
return NULL;
bpf->bpf = bpfprog;
return (PyObject*)bpf;
}
static PyObject*
p_filter(register bpfobject* bpf, PyObject* args)
{
int status;
u_char* packet;
unsigned int len;
if (bpf->ob_type != &BPFProgramtype)
{
PyErr_SetString(PcapError, "Not a bpfprogram object");
return NULL;
}
if (!PyArg_ParseTuple(args,"s#:filter",&packet, &len))
return NULL;
status = bpf_filter(bpf->bpf.bf_insns,
packet,
len, len);
return Py_BuildValue("i", status);
}