Skip to content

Commit fe1a9bd

Browse files
spaceonemistotebe
authored andcommitted
feat(ldap.filter): add is_filter() to verify filter syntax
1 parent bfcccb3 commit fe1a9bd

3 files changed

Lines changed: 44 additions & 0 deletions

File tree

Lib/ldap/filter.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
- Tested with Python 2.0+
88
"""
99

10+
import _ldap
1011
from ldap import __version__
1112

1213
from ldap.functions import strf_secs
@@ -89,3 +90,8 @@ def time_span_filter(
8990
until_timestr=strf_secs(until_timestamp),
9091
)
9192
# end of time_span_filter()
93+
94+
95+
def is_filter(ldap_filter: str):
96+
"""Returns True if `ldap_filter' can be parsed as a valid LDAP filter, otherwise False is returned."""
97+
return _ldap.is_filter(ldap_filter)

Modules/functions.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,32 @@ l_ldap_get_option(PyObject *self, PyObject *args)
400400
return LDAP_get_option(NULL, option);
401401
}
402402

403+
404+
/* ldap_is_filter */
405+
static PyObject *l_ldap_is_filter(PyObject *self, PyObject *args)
406+
{
407+
const char *filter;
408+
BerElement *ber;
409+
int rc;
410+
411+
if(!PyArg_ParseTuple(args, "s:is_filter", &filter))
412+
return NULL;
413+
414+
ber = ber_alloc_t(LBER_USE_DER);
415+
if(ber == NULL) {
416+
return PyErr_NoMemory();
417+
}
418+
419+
rc = ldap_pvt_put_filter(ber, filter);
420+
ber_free(ber, 1);
421+
422+
if (rc == 0) {
423+
Py_RETURN_TRUE;
424+
}
425+
Py_RETURN_FALSE;
426+
}
427+
428+
403429
/* methods */
404430

405431
static PyMethodDef methods[] = {
@@ -411,6 +437,7 @@ static PyMethodDef methods[] = {
411437
{"dn2str", (PyCFunction)l_ldap_dn2str, METH_VARARGS},
412438
{"set_option", (PyCFunction)l_ldap_set_option, METH_VARARGS},
413439
{"get_option", (PyCFunction)l_ldap_get_option, METH_VARARGS},
440+
{"is_filter", (PyCFunction)l_ldap_is_filter, METH_VARARGS},
414441
{NULL, NULL}
415442
};
416443

Modules/pythonldap.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,17 @@ LDAP_F(int) ldap_init_fd(ber_socket_t fd, int proto, LDAP_CONST char *url,
4242
LDAP **ldp);
4343
#endif
4444

45+
#if LDAP_VENDOR_VERSION >= 20700
46+
/* openldap.h made ldap_pvt_put_filter() public in 2.7.x
47+
* see https://bugs.openldap.org/show_bug.cgi?id=9393
48+
*/
49+
#else
50+
/* ldap_pvt_put_filter() has existed since OpenLDAP 2.1, but was only
51+
* declared in the private ldap_pvt.h header before OpenLDAP 2.7.
52+
*/
53+
LDAP_F(int) ldap_pvt_put_filter LDAP_P((BerElement *ber, const char *str));
54+
#endif
55+
4556
#if defined(MS_WINDOWS)
4657
#include <winsock.h>
4758
#else /* unix */

0 commit comments

Comments
 (0)