Debian Codegraph @

src/_bonsai/ldapconnection.c

raw symbols SCIP
1 #include "ldapconnection.h"
2 #include "ldapentry.h"
3 #include "ldapsearchiter.h"
4 #include "ldapconnectiter.h"
5
6 /* Dealloc the LDAPConnection object. */
7 static void
8 ldapconnection_dealloc(LDAPConnection* self) {
9 DEBUG("ldapconnection_dealloc (self:%p)", self);
10 if (self->ld != NULL) {
11 /* Unbind connection and free resources allocated by the LDAP structure. */
12 ldap_unbind_ext(self->ld, NULL, NULL);
13 }
14 Py_XDECREF(self->client);
15 Py_XDECREF(self->pending_ops);
16 Py_XDECREF(self->socketpair);
17
18 Py_TYPE(self)->tp_free((PyObject*)self);
19 }
20
21 /* Create a new LDAPConnection object. */
22 static PyObject *
23 ldapconnection_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
24 LDAPConnection *self = NULL;
25 PyObject *ts_empty_tuple = PyTuple_New(0);
26 PyObject *ts_empty_dict = PyDict_New();
27
28 if (ts_empty_tuple == NULL || ts_empty_dict == NULL) {
29 Py_XDECREF(ts_empty_tuple);
30 Py_XDECREF(ts_empty_dict);
31 return NULL;
32 }
33
34 self = (LDAPConnection *)PyBaseObject_Type.tp_new(type, ts_empty_tuple,
35 ts_empty_dict);
36 if (self != NULL) {
37 self->client = NULL;
38 self->pending_ops = NULL;
39 self->ld = NULL;
40 /* The connection should be closed. */
41 self->closed = 1;
42 self->async = 0;
43 self->ppolicy = 0;
44 self->csock = -1;
45 self->socketpair = NULL;
46 }
47
48 Py_DECREF(ts_empty_tuple);
49 Py_DECREF(ts_empty_dict);
50 DEBUG("ldapconnection_new [self:%p]", self);
51 return (PyObject *)self;
52 }
53
54 /* Initialise the LDAPConnection. */
55 static int
56 ldapconnection_init(LDAPConnection *self, PyObject *args, PyObject *kwds) {
57 PyObject *client = NULL;
58 PyObject *async = NULL;
59 PyObject *ldapclient_type = NULL;
60 PyObject *tmp = NULL;
61 static char *kwlist[] = {"client", "is_async", NULL};
62
63 DEBUG("ldapconnection_init (self:%p)", self);
64 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO!", kwlist, &client,
65 &PyBool_Type, &async)) {
66 return -1;
67 }
68
69 /* Validate that the Python object parameter is type of an LDAPClient. */
70 ldapclient_type = load_python_object("bonsai.ldapclient", "LDAPClient");
71 if (ldapclient_type == NULL ||
72 !PyObject_IsInstance(client, ldapclient_type)) {
73 PyErr_SetString(PyExc_TypeError, "Type of the client parameter must be an LDAPClient.");
74 return -1;
75 }
76 Py_DECREF(ldapclient_type);
77
78 /* Create a dict for pending LDAP operations. */
79 self->pending_ops = PyDict_New();
80 if (self->pending_ops == NULL) return -1;
81
82 /* Convert PyBool to char and set to async. */
83 self->async = (char)PyObject_IsTrue(async);
84
85 /* Set password policy option. */
86 tmp = PyObject_GetAttrString(client, "password_policy");
87 if (tmp == NULL) return -1;
88 self->ppolicy = (char)PyObject_IsTrue(tmp);
89 Py_DECREF(tmp);
90
91 /* Set manageDsaIT option. */
92 tmp = PyObject_GetAttrString(client, "managedsait");
93 if (tmp == NULL) return -1;
94 self->managedsait = (char)PyObject_IsTrue(tmp);
95 Py_DECREF(tmp);
96
97 /* Set ignore_referrals option. */
98 tmp = PyObject_GetAttrString(client, "ignore_referrals");
99 if (tmp == NULL) return -1;
100 self->ignore_referrals = (char)PyObject_IsTrue(tmp);
101 Py_DECREF(tmp);
102
103 /* Set client object to LDAPConnection. */
104 tmp = self->client;
105 Py_INCREF(client);
106 self->client = client;
107 Py_XDECREF(tmp);
108
109 return 0;
110 }
111
112 /* Check, that the connection is not closed.
113 Set Python exception if it is.
114 */
115 int
116 LDAPConnection_IsClosed(LDAPConnection *self) {
117 /* Connection must be set. */
118 if (self == NULL) return -1;
119 DEBUG("LDAPConnection_IsClosed (self:%p)", self);
120 if (self->closed) {
121 /* The connection is closed. */
122 PyObject *ldaperror = get_error_by_code(-101);
123 PyErr_SetString(ldaperror, "The connection is closed.");
124 Py_DECREF(ldaperror);
125 return -1;
126 }
127 return 0;
128 }
129
130 /* Open a connection to the LDAP server. Initialises LDAP structure.
131 If TLS is true, starts TLS session.
132 */
133 static int
134 connecting(LDAPConnection *self, LDAPConnectIter **conniter) {
135 int rc = -1;
136 char *mech = NULL;
137 SOCKET ssock = -1;
138 PyObject *tmp = NULL;
139 PyObject *creds = NULL;
140 ldap_conndata_t *info = NULL;
141
142 DEBUG("connecting (self:%p)", self);
143 /* Get mechanism and credentials. */
144 creds = PyObject_GetAttrString(self->client, "credentials");
145 if (creds == NULL) return -1;
146
147 tmp = PyObject_GetAttrString(self->client, "mechanism");
148 if (tmp == NULL) {
149 Py_DECREF(creds);
150 return -1;
151 }
152 mech = PyObject2char(tmp);
153 Py_DECREF(tmp);
154
155 if (self->async) {
156 /* Init the socketpair. */
157 rc = get_socketpair(&(self->socketpair), &(self->csock), &ssock);
158 if (rc != 0) {
159 free(mech);
160 return -1;
161 }
162 }
163
164 info = create_conn_info(mech, ssock, creds);
165 Py_DECREF(creds);
166 free(mech);
167 if (info == NULL) return -1;
168
169 *conniter = LDAPConnectIter_New(self, info, ssock);
170 if (*conniter == NULL) return -1;
171
172 return 0;
173 }
174
175 /* Open the LDAP connection. */
176 static PyObject *
177 ldapconnection_open(LDAPConnection *self) {
178 int rc = 0;
179 LDAPConnectIter *iter = NULL;
180
181 DEBUG("ldapconnection_open (self:%p)", self);
182 rc = connecting(self, &iter);
183 if (rc != 0) return NULL;
184
185 /* Add binding operation to the pending_ops. */
186 if (add_to_pending_ops(self->pending_ops, (int)(self->csock),
187 (PyObject *)iter) != 0) {
188 return NULL;
189 }
190
191 return PyLong_FromLong((long int)(self->csock));
192 }
193
194 /* Close the LDAP connection. */
195 static PyObject *
196 ldapconnection_close(LDAPConnection *self, PyObject *args, PyObject *kwds) {
197 int rc;
198 int msgid;
199 char abandon = 0;
200 PyObject *iter, *key, *keys = NULL;
201 PyObject *abandon_obj = NULL;
202 static char *kwlist[] = {"abandon_requests", NULL};
203
204 DEBUG("ldapconnection_close (self:%p)", self);
205 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O!", kwlist, &PyBool_Type,
206 &abandon_obj)) {
207 return NULL;
208 }
209
210 if (abandon_obj != NULL) {
211 abandon = (char)PyObject_IsTrue(abandon_obj);
212 }
213
214 if (self->closed == 1) {
215 /* Connection is already close, nothing to do. */
216 Py_RETURN_NONE;
217 }
218
219 if (abandon == 1) {
220 keys = PyDict_Keys(self->pending_ops);
221 if (keys == NULL) return NULL;
222
223 iter = PyObject_GetIter(keys);
224 Py_DECREF(keys);
225 if (iter == NULL) return NULL;
226
227 for (key = PyIter_Next(iter); key != NULL; key = PyIter_Next(iter)) {
228 msgid = (int)PyLong_AsLong(key);
229 /* Remove item from the dict. */
230 if (PyDict_DelItem(self->pending_ops, key) != 0) {
231 Py_DECREF(iter);
232 Py_DECREF(key);
233 PyErr_BadInternalCall();
234 return NULL;
235 }
236 Py_DECREF(key);
237
238 /* Skip negatives, cause assertion error. */
239 if (msgid <= 0) continue;
240 /* Abandon the pending operations from the server. */
241 rc = ldap_abandon_ext(self->ld, msgid, NULL, NULL);
242 if (rc != LDAP_SUCCESS) {
243 Py_DECREF(iter);
244 set_exception(self->ld, rc);
245 return NULL;
246 }
247 }
248 Py_DECREF(iter);
249 }
250
251 rc = ldap_unbind_ext(self->ld, NULL, NULL);
252 if (rc != LDAP_SUCCESS) {
253 set_exception(self->ld, rc);
254 return NULL;
255 }
256 self->closed = 1;
257 self->ld = NULL;
258 Py_RETURN_NONE;
259 }
260
261 /* Add new LDAPEntry to the server. */
262 static PyObject *
263 ldapconnection_add(LDAPConnection *self, PyObject *args) {
264 PyObject *param = NULL;
265 PyObject *msgid = NULL;
266
267 DEBUG("ldapconnection_add (self:%p, args:%p)", self, args);
268 if (LDAPConnection_IsClosed(self) != 0) return NULL;
269
270 if (!PyArg_ParseTuple(args, "O!", &LDAPEntryType, &param)) return NULL;
271
272 /* Set this connection to the LDAPEntry, before add to the server. */
273 if (LDAPEntry_SetConnection((LDAPEntry *)param, self) == 0) {
274 msgid = LDAPEntry_AddOrModify((LDAPEntry *)param, 0);
275 if (msgid != NULL) {
276 return msgid;
277 }
278 }
279
280 return NULL;
281 }
282
283 /* Delete an entry on the server. */
284 static PyObject *
285 ldapconnection_delentry(LDAPConnection *self, PyObject *args) {
286 int rc = 0;
287 char *dnstr = NULL;
288 int msgid = -1;
289 int num_of_ctrls = 0;
290 PyObject *recursive = NULL;
291 LDAPControl *tree_ctrl = NULL;
292 LDAPControl *mdi_ctrl = NULL;
293 LDAPControl **server_ctrls = NULL;
294 struct berval ctrl_null_value = {0, NULL};
295
296 DEBUG("ldapconnection_delentry (self:%p, args:%p)", self, args);
297 if (LDAPConnection_IsClosed(self) != 0) return NULL;
298
299 if (!PyArg_ParseTuple(args, "s|O!", &dnstr, &PyBool_Type, &recursive)) {
300 return NULL;
301 }
302 if (dnstr == NULL) return NULL;
303
304 if (recursive != NULL && PyObject_IsTrue(recursive)) num_of_ctrls++;
305 if (self->managedsait == 1) num_of_ctrls++;
306
307 if (num_of_ctrls > 0) {
308 server_ctrls = (LDAPControl **)malloc(sizeof(LDAPControl *) *
309 (num_of_ctrls + 1));
310 if (server_ctrls == NULL) return PyErr_NoMemory();
311 num_of_ctrls = 0;
312 }
313
314 if (recursive != NULL && PyObject_IsTrue(recursive)) {
315 /* Create an LDAP_SERVER_TREE_DELETE control . */
316
317 rc = ldap_control_create(LDAP_SERVER_TREE_DELETE_OID, 0, NULL, 1, &tree_ctrl);
318 if (rc != LDAP_SUCCESS) {
319 free(server_ctrls);
320 PyErr_BadInternalCall();
321 return NULL;
322 }
323
324 server_ctrls[num_of_ctrls++] = tree_ctrl;
325 server_ctrls[num_of_ctrls] = NULL;
326 }
327
328 if (self->managedsait == 1) {
329 /* Create ManageDsaIT control. */
330 rc = ldap_control_create(LDAP_CONTROL_MANAGEDSAIT, 0, &ctrl_null_value,
331 1, &mdi_ctrl);
332 if (rc != LDAP_SUCCESS) {
333 if (tree_ctrl != NULL) _ldap_control_free(tree_ctrl);
334 free(server_ctrls);
335 PyErr_BadInternalCall();
336 return NULL;
337 }
338 server_ctrls[num_of_ctrls++] = mdi_ctrl;
339 server_ctrls[num_of_ctrls] = NULL;
340 }
341
342 rc = ldap_delete_ext(self->ld, dnstr, server_ctrls, NULL, &msgid);
343
344 /* Clear the controls. */
345 if (tree_ctrl != NULL) _ldap_control_free(tree_ctrl);
346 if (mdi_ctrl != NULL) _ldap_control_free(mdi_ctrl);
347 free(server_ctrls);
348
349 /* Check the return value of the delete function. */
350 if (rc != LDAP_SUCCESS) {
351 set_exception(self->ld, rc);
352 return NULL;
353 }
354
355 /* Add new delete operation to the pending_ops. */
356 if (add_to_pending_ops(self->pending_ops, msgid, Py_None) != 0) {
357 return NULL;
358 }
359
360 return PyLong_FromLong((long int)msgid);
361 }
362
363 /* Perform an LDAP search using an LDAPSearchIter object that contains
364 the parameters of the search. */
365 int
366 LDAPConnection_Searching(LDAPConnection *self, ldapsearchparams *params_in,
367 PyObject *iterator) {
368 int rc;
369 int msgid = -1;
370 int extdn_format = -1;
371 int sd_flags = -1;
372 unsigned short num_of_ctrls = 0;
373 ldapsearchparams *params = NULL;
374 LDAPControl *page_ctrl = NULL;
375 LDAPControl *sort_ctrl = NULL;
376 LDAPControl *vlv_ctrl = NULL;
377 LDAPControl *edn_ctrl = NULL;
378 LDAPControl *mdi_ctrl = NULL;
379 LDAPControl **server_ctrls = NULL;
380 LDAPSearchIter *search_iter = (LDAPSearchIter *)iterator;
381 struct berval ctrl_null_value = {0, NULL};
382 struct timeval timeout;
383 struct timeval *timeout_p;
384 int tout_ms = 0;
385 PyObject *value = NULL;
386
387 DEBUG("LDAPConnection_Searching (self:%p, params_in:%p, iterator:%p)",
388 self, params_in, iterator);
389 /* Get extended dn format attribute from LDAPClient. */
390 value = PyObject_GetAttrString(self->client, "extended_dn_format");
391 if (value == NULL) return -1;
392 if (value == Py_None) {
393 extdn_format = -1;
394 } else {
395 extdn_format = PyLong_AsLong(value);
396 }
397 Py_DECREF(value);
398
399 /* Get sd flags attribute from LDAPClient. */
400 value = PyObject_GetAttrString(self->client, "sd_flags");
401 if (value == NULL) return -1;
402 if (value == Py_None) {
403 sd_flags = -1;
404 } else {
405 sd_flags = PyLong_AsLong(value);
406 }
407 Py_DECREF(value);
408
409 if (search_iter != NULL) {
410 params = search_iter->params;
411 value = (PyObject *)search_iter;
412 } else {
413 params = params_in;
414 value = Py_None;
415 }
416
417 /* Check the number of server controls and allocate it. */
418 if (extdn_format != -1) num_of_ctrls++;
419 if (sd_flags != -1) num_of_ctrls++;
420 if (self->managedsait == 1) num_of_ctrls++;
421 if (params->sort_list != NULL) num_of_ctrls++;
422 if (search_iter != NULL && search_iter->page_size > 0) num_of_ctrls++;
423 if (search_iter != NULL && search_iter->vlv_info != NULL) num_of_ctrls++;
424 if (num_of_ctrls > 0) {
425 server_ctrls = (LDAPControl **)malloc(sizeof(LDAPControl *) *
426 (num_of_ctrls + 1));
427 if (server_ctrls == NULL) {
428 PyErr_NoMemory();
429 return -1;
430 }
431 num_of_ctrls = 0;
432 }
433
434 if (server_ctrls != NULL) {
435 if (search_iter != NULL && search_iter->page_size > 0) {
436 /* Create page control and add to the server controls. */
437 rc = ldap_create_page_control(self->ld, search_iter->page_size,
438 search_iter->cookie, 0, &page_ctrl);
439 if (rc != LDAP_SUCCESS) {
440 PyErr_BadInternalCall();
441 msgid = -1;
442 goto end;
443 }
444 server_ctrls[num_of_ctrls++] = page_ctrl;
445 server_ctrls[num_of_ctrls] = NULL;
446 }
447
448 if (params->sort_list != NULL) {
449 /* Create sort control. */
450 rc = ldap_create_sort_control(self->ld, params->sort_list, 0,
451 &sort_ctrl);
452 if (rc != LDAP_SUCCESS) {
453 PyErr_BadInternalCall();
454 msgid = -1;
455 goto end;
456 }
457 server_ctrls[num_of_ctrls++] = sort_ctrl;
458 server_ctrls[num_of_ctrls] = NULL;
459 }
460
461 if (search_iter != NULL && search_iter->vlv_info != NULL) {
462 /* Create virtual list value control. */
463 rc = ldap_create_vlv_control(self->ld, search_iter->vlv_info, &vlv_ctrl);
464 if (rc != LDAP_SUCCESS) {
465 PyErr_BadInternalCall();
466 msgid = -1;
467 goto end;
468 }
469 server_ctrls[num_of_ctrls++] = vlv_ctrl;
470 server_ctrls[num_of_ctrls] = NULL;
471 }
472
473 if (extdn_format != -1) {
474 /* Create extended dn control. */
475 rc = _ldap_create_extended_dn_control(self->ld, extdn_format, &edn_ctrl);
476 if (rc != LDAP_SUCCESS) {
477 PyErr_BadInternalCall();
478 msgid = -1;
479 goto end;
480 }
481 server_ctrls[num_of_ctrls++] = edn_ctrl;
482 server_ctrls[num_of_ctrls] = NULL;
483 }
484
485 if (sd_flags != -1) {
486 /* Create sd flags control. */
487 rc = _ldap_create_sd_flags_control(self->ld, sd_flags, &edn_ctrl);
488 if (rc != LDAP_SUCCESS) {
489 PyErr_BadInternalCall();
490 msgid = -1;
491 goto end;
492 }
493 server_ctrls[num_of_ctrls++] = edn_ctrl;
494 server_ctrls[num_of_ctrls] = NULL;
495 }
496
497 if (self->managedsait == 1) {
498 /* Create ManageDsaIT control. */
499 rc = ldap_control_create(LDAP_CONTROL_MANAGEDSAIT, 0,
500 &ctrl_null_value, 1, &mdi_ctrl);
501 if (rc != LDAP_SUCCESS) {
502 PyErr_BadInternalCall();
503 msgid = -1;
504 goto end;
505 }
506 server_ctrls[num_of_ctrls++] = mdi_ctrl;
507 server_ctrls[num_of_ctrls] = NULL;
508 }
509
510 }
511
512 if (params == NULL) {
513 PyErr_BadInternalCall();
514 msgid= -1;
515 goto end;
516 }
517
518 tout_ms = (int)(params->timeout * 1000);
519
520 if (tout_ms > 0) {
521 timeout.tv_sec = tout_ms / 1000;
522 timeout.tv_usec = (tout_ms % 1000) * 1000;
523 timeout_p = &timeout;
524 } else {
525 timeout_p = NULL;
526 }
527
528 rc = ldap_search_ext(self->ld, params->base,
529 params->scope,
530 params->filter,
531 params->attrs,
532 params->attrsonly,
533 server_ctrls, NULL,
534 timeout_p,
535 params->sizelimit, &msgid);
536
537 if (rc != LDAP_SUCCESS) {
538 set_exception(self->ld, rc);
539 msgid = -1;
540 goto end;
541 }
542
543 if (add_to_pending_ops(self->pending_ops, msgid, value) != 0) {
544 msgid = -1;
545 goto end;
546 }
547 end:
548 /* Cleanup. */
549 if (page_ctrl != NULL) ldap_control_free(page_ctrl);
550 if (sort_ctrl != NULL) ldap_control_free(sort_ctrl);
551 if (vlv_ctrl != NULL) ldap_control_free(vlv_ctrl);
552 if (edn_ctrl != NULL) _ldap_control_free(edn_ctrl);
553 if (mdi_ctrl != NULL) _ldap_control_free(mdi_ctrl);
554 free(server_ctrls);
555
556 return msgid;
557 }
558
559 /* Search for LDAP entries. */
560 static PyObject *
561 ldapconnection_search(LDAPConnection *self, PyObject *args, PyObject *kwds) {
562 int rc = 0;
563 int scope = -1;
564 int msgid = -1;
565 int sizelimit = 0, attrsonly = 0;
566 int page_size = 0;
567 int offset = 0, after_count = 0, before_count = 0, list_count = 0;
568 Py_ssize_t len = 0;
569 double timeout = 0;
570 char *basestr = NULL;
571 char *filterstr = NULL;
572 char **attrs = NULL;
573 struct berval *attrvalue = NULL;
574 PyObject *attrlist = NULL;
575 PyObject *attrsonlyo = NULL;
576 PyObject *sort_order = NULL;
577 PyObject *attrvalue_obj = NULL;
578 ldapsearchparams params;
579 LDAPSortKey **sort_list = NULL;
580 LDAPSearchIter *search_iter = NULL;
581 static char *kwlist[] = {"base", "scope", "filter", "attrlist", "timeout",
582 "sizelimit", "attrsonly", "sort_order", "page_size", "offset",
583 "before_count", "after_count", "est_list_count", "attrvalue", NULL};
584
585 DEBUG("ldapconnection_search (self:%p, args:%p, kwds:%p)",
586 self, args, kwds);
587 if (LDAPConnection_IsClosed(self) != 0) return NULL;
588
589 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ziz#O!diO!O!iiiiiO", kwlist,
590 &basestr, &scope, &filterstr, &len, &PyList_Type, &attrlist, &timeout,
591 &sizelimit, &PyBool_Type, &attrsonlyo, &PyList_Type, &sort_order,
592 &page_size, &offset, &before_count, &after_count, &list_count,
593 &attrvalue_obj)) {
594 PyErr_SetString(PyExc_TypeError,
595 "Wrong parameters (base<str|LDAPDN>, scope<int>, filter<str>,"
596 " attrlist<List>, timeout<float>, attrsonly<bool>,"
597 " sort_order<List>, page_size<int>, offset<int>,"
598 " before_count<int>, after_count<int>, est_list_count<int>,"
599 " attrvalue<object>).");
600 return NULL;
601 }
602
603 /* Check that scope's value is not remained the default. */
604 if (scope == -1) {
605 PyErr_SetString(PyExc_ValueError, "Search scope must be set.");
606 return NULL;
607 }
608
609 /* If attrvalue_obj is None, then it is not set.*/
610 if (attrvalue_obj == Py_None) attrvalue_obj = NULL;
611
612 if (sort_order != NULL && PyList_Size(sort_order) > 0) {
613 /* Convert the attribute, reverse order pairs to LDAPSortKey struct. */
614 sort_list = PyList2LDAPSortKeyList(sort_order);
615 if (sort_list == NULL) {
616 PyErr_BadInternalCall();
617 return NULL;
618 }
619 }
620
621 /* Convert Python objects to C types. */
622 if (attrsonlyo != NULL) attrsonly = PyObject_IsTrue(attrsonlyo);
623 if (attrlist != NULL) attrs = PyList2StringList(attrlist);
624
625 if (set_search_params(&params, attrs, attrsonly, basestr,
626 filterstr, len, scope, sizelimit, timeout, sort_list) != 0) {
627 return NULL;
628 }
629
630 if (page_size > 0 || offset != 0 || attrvalue_obj != NULL) {
631 /* Create a SearchIter for storing the search params and result. */
632 search_iter = LDAPSearchIter_New(self);
633 if (search_iter == NULL) return PyErr_NoMemory();
634
635 memcpy(search_iter->params, &params, sizeof(ldapsearchparams));
636
637 /* Create cookie for the page result. */
638 search_iter->cookie = (struct berval *)malloc(sizeof(struct berval));
639 if (search_iter->cookie == NULL) return PyErr_NoMemory();
640
641 search_iter->cookie->bv_len = 0;
642 search_iter->cookie->bv_val = NULL;
643 search_iter->page_size = page_size;
644
645 if (offset != 0 || attrvalue_obj != NULL) {
646 search_iter->vlv_info = (LDAPVLVInfo *)malloc(sizeof(LDAPVLVInfo));
647 if (search_iter->vlv_info == NULL) {
648 Py_DECREF(search_iter);
649 PyErr_NoMemory();
650 return NULL;
651 }
652 search_iter->vlv_info->ldvlv_after_count = after_count;
653 search_iter->vlv_info->ldvlv_before_count = before_count;
654 search_iter->vlv_info->ldvlv_offset = offset;
655 search_iter->vlv_info->ldvlv_context = NULL;
656 search_iter->vlv_info->ldvlv_version = 1;
657 search_iter->vlv_info->ldvlv_count = list_count;
658
659 if (attrvalue_obj != NULL) {
660 attrvalue = (struct berval *)malloc(sizeof(struct berval));
661 if (attrvalue == NULL) {
662 Py_DECREF(search_iter);
663 PyErr_NoMemory();
664 return NULL;
665 }
666 rc = PyObject2char_withlength(attrvalue_obj,
667 &(attrvalue->bv_val), &len);
668 if (rc != 0 || attrvalue->bv_val == NULL) {
669 PyErr_BadInternalCall();
670 free(attrvalue);
671 Py_DECREF(search_iter);
672 return NULL;
673 }
674 attrvalue->bv_len = len;
675 }
676 search_iter->vlv_info->ldvlv_attrvalue = attrvalue;
677 }
678 }
679
680 msgid = LDAPConnection_Searching(self, &params, (PyObject *)search_iter);
681 if (search_iter == NULL) free_search_params(&params);
682
683 if (msgid < 0) return NULL;
684
685 return PyLong_FromLong((long int)msgid);
686 }
687
688 /* Perform an LDAP Who Am I operation. */
689 static PyObject *
690 ldapconnection_whoami(LDAPConnection *self) {
691 int rc = -1;
692 int msgid = -1;
693 PyObject *oid = NULL;
694
695 DEBUG("ldapconnection_whoami (self:%p)", self);
696 if (LDAPConnection_IsClosed(self) != 0) return NULL;
697 /* Start an LDAP Who Am I operation. */
698 rc = ldap_extended_operation(self->ld, "1.3.6.1.4.1.4203.1.11.3", NULL,
699 NULL, NULL, &msgid);
700 if (rc != LDAP_SUCCESS) {
701 set_exception(self->ld, rc);
702 return NULL;
703 }
704
705 /* Add the new operation to the pending_ops with the proper OID. */
706 oid = PyUnicode_FromString("1.3.6.1.4.1.4203.1.11.3");
707 if (oid == NULL) return NULL;
708 if (add_to_pending_ops(self->pending_ops, msgid, oid) != 0) {
709 return NULL;
710 }
711
712 return PyLong_FromLong((long int)msgid);
713 }
714
715 static PyObject *
716 ldapconnection_modpasswd(LDAPConnection *self, PyObject *args, PyObject *kwds) {
717 int rc = -1;
718 int msgid = -1;
719 Py_ssize_t user_len = 0, newpwd_len = 0, oldpwd_len = 0;
720 struct berval user, newpwd, oldpwd;
721 struct berval *data = NULL;
722 BerElement *ber = NULL;
723 PyObject *oid = NULL;
724 LDAPControl *ppolicy_ctrl = NULL;
725 LDAPControl **server_ctrls = NULL;
726 static char *kwlist[] = { "user", "new_password", "old_password", NULL };
727
728 DEBUG("ldapconnection_modpasswd (self:%p, args:%p, kwds:%p)",
729 self, args, kwds);
730 if (LDAPConnection_IsClosed(self) != 0) return NULL;
731
732 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|z#z#z#", kwlist,
733 &user.bv_val, &user_len, &newpwd.bv_val, &newpwd_len,
734 &oldpwd.bv_val, &oldpwd_len)) {
735 return NULL;
736 }
737
738 /* Set lengths. */
739 user.bv_len = user_len;
740 newpwd.bv_len = newpwd_len;
741 oldpwd.bv_len = oldpwd_len;
742
743 ber = ber_alloc_t(LBER_USE_DER);
744 if (ber == NULL) return PyErr_NoMemory();
745
746 /* Create a valid BER object with the provided parameters. */
747 ber_printf(ber, "{");
748 if (user.bv_val != NULL && user.bv_len != 0) {
749 ber_printf(ber, "to", 0x80U, user.bv_val, user.bv_len);
750 }
751 if (oldpwd.bv_val != NULL && oldpwd.bv_len != 0) {
752 ber_printf(ber, "to", 0x81U, oldpwd.bv_val, oldpwd.bv_len);
753 }
754 if (newpwd.bv_val != NULL && newpwd.bv_len != 0) {
755 ber_printf(ber, "to", 0x82U, newpwd.bv_val, newpwd.bv_len);
756 }
757 ber_printf(ber, "}");
758
759 /* Load the BER value into a berval. */
760 rc = ber_flatten(ber, &data);
761 ber_free(ber, 1);
762 if (rc != 0) {
763 set_exception(NULL, LDAP_ENCODING_ERROR);
764 return NULL;
765 }
766
767 if (self->ppolicy == 1) {
768 /* Create password policy control if it is set. */
769 rc = ldap_create_passwordpolicy_control(self->ld, &ppolicy_ctrl);
770 if (rc != LDAP_SUCCESS) {
771 PyErr_BadInternalCall();
772 return NULL;
773 }
774
775 server_ctrls = (LDAPControl **)malloc(sizeof(LDAPControl *) * (1 + 1));
776 if (server_ctrls == NULL) return PyErr_NoMemory();
777
778 server_ctrls[0] = ppolicy_ctrl;
779 server_ctrls[1] = NULL;
780 }
781
782 /* Start an LDAP Password Modify operation. */
783 rc = ldap_extended_operation(self->ld, "1.3.6.1.4.1.4203.1.11.1",
784 data, server_ctrls, NULL, &msgid);
785
786 /* Clear the mess. */
787 ber_bvfree(data);
788 if (ppolicy_ctrl != NULL) ldap_control_free(ppolicy_ctrl);
789 free(server_ctrls);
790
791 if (rc != LDAP_SUCCESS) {
792 set_exception(self->ld, rc);
793 return NULL;
794 }
795
796 /* Add the new operation to the pending_ops with the proper OID. */
797 oid = PyUnicode_FromString("1.3.6.1.4.1.4203.1.11.1");
798 if (oid == NULL) return NULL;
799 if (add_to_pending_ops(self->pending_ops, msgid, oid) != 0) {
800 return NULL;
801 }
802
803 return PyLong_FromLong((long int)msgid);
804 }
805
806 static PyObject *
807 create_reference_object(LDAPConnection *self, char **referrals) {
808 int i = 0;
809 PyObject *list = NULL;
810 PyObject *args = NULL;
811 PyObject *tmp = NULL;
812 PyObject *ldapreference_type = NULL;
813
814 list = PyList_New(0);
815 if (list == NULL) return NULL;
816
817 DEBUG("create_reference_object (self:%p)", self);
818 /* Load LDAPReference Python type. */
819 ldapreference_type = load_python_object("bonsai.ldapreference", "LDAPReference");
820 if (ldapreference_type == NULL) {
821 Py_DECREF(list);
822 return NULL;
823 }
824
825 for (i = 0; referrals[i] != NULL; i++) {
826 tmp = PyUnicode_FromString(referrals[i]);
827 free(referrals[i]);
828 if (tmp == NULL) goto end;
829 if (PyList_Append(list, tmp) != 0) {
830 Py_DECREF(tmp);
831 tmp = NULL;
832 goto end;
833 }
834 Py_DECREF(tmp);
835 }
836
837 tmp = NULL;
838 args = Py_BuildValue("OO", self->client, list);
839 if (args == NULL) goto end;
840
841 /* Create a new LDAPReference. */
842 tmp = PyObject_CallObject(ldapreference_type, args);
843 end:
844 Py_DECREF(ldapreference_type);
845 Py_DECREF(list);
846 return tmp;
847 }
848
849 /* Process the server result after a search request. */
850 static PyObject *
851 parse_search_result(LDAPConnection *self, LDAPMessage *res, PyObject *obj) {
852 int rc = -1;
853 int err = 0;
854 int ref_opt = 0;
855 int target_pos = 0, list_count = 0;
856 char *attr = NULL;
857 char **referrals = NULL;
858 LDAPMessage *entry;
859 FINDCTRL ctrl = NULL;
860 LDAPControl **returned_ctrls = NULL;
861 LDAPEntry *entryobj = NULL;
862 LDAPSearchIter *search_iter = NULL;
863 PyObject *ldaperror = NULL, *errmsg = NULL;
864 PyObject *buffer = NULL;
865 PyObject *ctrl_obj = NULL;
866 PyObject *refobj = NULL;
867 PyObject *retval = NULL;
868
869 DEBUG("parse_search_result (self:%p, res:%p, obj:%p)", self, res, obj);
870
871 if (obj != Py_None) search_iter = (LDAPSearchIter *)obj;
872 buffer = PyList_New(0);
873 if (buffer == NULL) return PyErr_NoMemory();
874
875 /* Iterate over the received LDAP messages. */
876 for (entry = ldap_first_entry(self->ld, res); entry != NULL;
877 entry = ldap_next_entry(self->ld, entry)) {
878 entryobj = LDAPEntry_FromLDAPMessage(entry, self);
879 if (entryobj == NULL) {
880 Py_DECREF(buffer);
881 return NULL;
882 }
883 if (PyList_Append(buffer, (PyObject *)entryobj) != 0) {
884 Py_DECREF(entryobj);
885 Py_DECREF(buffer);
886 return PyErr_NoMemory();
887 }
888 Py_DECREF(entryobj);
889 }
890
891 ldap_get_option(self->ld, LDAP_OPT_REFERRALS, &ref_opt);
892
893 if (ref_opt == 0 && self->ignore_referrals == 0) {
894 /* Iterate over the received referrals. */
895 for (entry = ldap_first_reference(self->ld, res); entry != NULL;
896 entry = ldap_next_reference(self->ld, entry)) {
897 rc = ldap_parse_reference(self->ld, entry, &referrals, NULL, 0);
898 if (rc != LDAP_SUCCESS) {
899 set_exception(self->ld, rc);
900 goto error;
901 }
902 if (referrals != NULL) {
903 refobj = create_reference_object(self, referrals);
904 if (refobj == NULL) goto error;
905 if (PyList_Append(buffer, refobj) != 0) {
906 Py_DECREF(refobj);
907 goto error;
908 }
909 Py_DECREF(refobj);
910 }
911 }
912 }
913
914 /* Check for any error during the searching. */
915 rc = ldap_parse_result(self->ld, res, &err, NULL, NULL, NULL,
916 &returned_ctrls, 1);
917
918 if (rc != LDAP_SUCCESS && rc != LDAP_MORE_RESULTS_TO_RETURN) {
919 set_exception(self->ld, rc);
920 goto error;
921 }
922
923 if (err == LDAP_NO_SUCH_OBJECT && search_iter == NULL) {
924 /* Shortcut for normal search to return empty list. */
925 return buffer;
926 }
927
928 if (err != LDAP_SUCCESS && err != LDAP_PARTIAL_RESULTS && err != LDAP_REFERRAL) {
929 /* Ignore LDAP_REFERRAL error as well. */
930 set_exception(self->ld, err);
931 goto error;
932 }
933
934 ctrl = ldap_control_find(LDAP_CONTROL_SORTRESPONSE, returned_ctrls, NULL);
935 if (ctrl != NULL) {
936 rc = ldap_parse_sortresponse_control(self->ld, ctrl, &err, &attr);
937
938 if (rc != LDAP_SUCCESS || err != LDAP_SUCCESS) {
939 ldaperror = get_error_by_code(err);
940 if (ldaperror == NULL) goto error;
941 if (attr != NULL) {
942 errmsg = PyUnicode_FromFormat("Server side sorting failed "
943 "on attribute '%s'.", attr);
944 ldap_memfree(attr);
945 }
946 if (errmsg != NULL) {
947 PyErr_SetObject(ldaperror, errmsg);
948 Py_DECREF(errmsg);
949 } else {
950 PyErr_SetString(ldaperror, "");
951 }
952 Py_DECREF(ldaperror);
953 goto error;
954 }
955
956 ctrl = NULL;
957 }
958
959 if (search_iter != NULL) {
960 if (search_iter->page_size > 0) {
961 ctrl = ldap_control_find(LDAP_CONTROL_PAGEDRESULTS, returned_ctrls, NULL);
962 if (search_iter->cookie->bv_val != NULL) {
963 #ifndef WIN32
964 /* ber_memfree is unavailable for WinLDAP, simple free causes segfault on Windows. */
965 ber_memfree(search_iter->cookie->bv_val);
966 #endif
967 search_iter->cookie->bv_len = 0;
968 search_iter->cookie->bv_val = NULL;
969 }
970 if (ctrl != NULL) {
971 rc = ldap_parse_pageresponse_control(self->ld, ctrl, NULL,
972 search_iter->cookie);
973 if (rc != LDAP_SUCCESS) {
974 set_exception(self->ld, rc);
975 goto error;
976 }
977 } else {
978 /* No paged result control is received, clear cookie. */
979 ber_bvfree(search_iter->cookie);
980 search_iter->cookie = NULL;
981 }
982 }
983 if (search_iter->vlv_info != NULL) {
984 rc = ldap_parse_vlvresponse_control(self->ld,
985 ldap_control_find(LDAP_CONTROL_VLVRESPONSE, returned_ctrls, NULL),
986 &target_pos, &list_count, NULL, &err);
987
988 if (rc != LDAP_SUCCESS || err != LDAP_SUCCESS) {
989 set_exception(self->ld, err);
990 goto error;
991 }
992
993 /* Create ctrl dict. */
994 ctrl_obj = Py_BuildValue("{s,s,s,i,s,i}",
995 "oid", LDAP_CONTROL_VLVRESPONSE,
996 "target_position", target_pos,
997 "list_count", list_count);
998 if (ctrl_obj == NULL) goto error;
999
1000 /* Create (result, ctrl) tuple as return value. */
1001 retval = Py_BuildValue("(O,O)", buffer, ctrl_obj);
1002 Py_DECREF(ctrl_obj);
1003 if (retval == NULL) {
1004 goto error;
1005 }
1006 Py_DECREF(buffer);
1007 } else {
1008 /* Return LDAPSearchIter for paged search. */
1009 Py_XDECREF(search_iter->buffer);
1010 search_iter->buffer = buffer;
1011 retval = (PyObject *)search_iter;
1012 Py_INCREF(retval);
1013 }
1014
1015 } else {
1016 /* Return simple list for normal search. */
1017 retval = buffer;
1018 }
1019
1020 /* Cleanup. */
1021 if (returned_ctrls != NULL) ldap_controls_free(returned_ctrls);
1022
1023 return retval;
1024 error:
1025 if (returned_ctrls != NULL) ldap_controls_free(returned_ctrls);
1026 Py_DECREF(buffer);
1027 return NULL;
1028 }
1029
1030 /* Process the server response after an extended operation. */
1031 static PyObject *
1032 parse_extended_result(LDAPConnection *self, LDAPMessage *res, PyObject *oid) {
1033 int rc = -1;
1034 int err = 0;
1035 int ppres = 0;
1036 unsigned int pperr = 0;
1037 struct berval *data = NULL;
1038 struct berval *newpasswd = NULL;
1039 char *errstr = NULL, *retoid = NULL;
1040 PyObject *retval = NULL, *ldaperror = NULL, *errmsg = NULL;
1041 PyObject *ctrl_obj = NULL;
1042 LDAPControl **ctrls = NULL;
1043 BerElement *ber = NULL;
1044 ber_tag_t tag;
1045
1046 DEBUG("parse_extended_result (self:%p, res:%p, oid:%p)",
1047 self, res, oid);
1048
1049 rc = ldap_parse_result(self->ld, res, &err, NULL, &errstr, NULL, &ctrls, 0);
1050
1051 ppres = create_ppolicy_control(self->ld, ctrls, &ctrl_obj, &pperr);
1052 if (ctrls != NULL) ldap_controls_free(ctrls);
1053 if (ppres == -1) return NULL;
1054
1055 if (rc != LDAP_SUCCESS || err != LDAP_SUCCESS) {
1056 if (ppres == 1 && pperr != 65535) {
1057 set_ppolicy_err(pperr, ctrl_obj);
1058 } else {
1059 ldaperror = get_error_by_code(err);
1060 if (ldaperror == NULL) return NULL;
1061 if (errstr != NULL) errmsg = PyUnicode_FromFormat("%s.", errstr);
1062 if (errmsg != NULL) {
1063 PyErr_SetObject(ldaperror, errmsg);
1064 Py_DECREF(errmsg);
1065 } else PyErr_SetString(ldaperror, "");
1066 Py_DECREF(ldaperror);
1067 }
1068
1069 return NULL;
1070 }
1071
1072 rc = ldap_parse_extended_result(self->ld, res, &retoid, &data, 1);
1073 ldap_memfree(retoid);
1074
1075 if (rc != LDAP_SUCCESS) {
1076 set_exception(self->ld, rc);
1077 return NULL;
1078 }
1079 /* LDAP Who Am I operation. */
1080 if (PyUnicode_CompareWithASCIIString(oid,
1081 "1.3.6.1.4.1.4203.1.11.3") == 0) {
1082 if (data == NULL) return PyUnicode_FromString("anonymous");
1083
1084 if(data->bv_len == 0) {
1085 data->bv_val = strdup("anonymous");
1086 data->bv_len = 9;
1087 }
1088
1089 retval = PyUnicode_FromStringAndSize(data->bv_val, data->bv_len);
1090 /* LDAP Password Modify operation. */
1091 } else if (PyUnicode_CompareWithASCIIString(oid,
1092 "1.3.6.1.4.1.4203.1.11.1") == 0) {
1093 if (data == NULL) Py_RETURN_TRUE;
1094
1095 ber = ber_init(data);
1096 if (ber == NULL) {
1097 ber_bvfree(data);
1098 return PyErr_NoMemory();
1099 }
1100
1101 tag = ber_scanf(ber, "{O}", &newpasswd);
1102 ber_free(ber, 1);
1103
1104 if (tag == LBER_ERROR) {
1105 set_exception(NULL, LDAP_DECODING_ERROR);
1106 ber_bvfree(data);
1107 return NULL;
1108 }
1109 retval = PyUnicode_FromStringAndSize(newpasswd->bv_val, newpasswd->bv_len);
1110 ber_bvfree(newpasswd);
1111 }
1112 ber_bvfree(data);
1113 return retval;
1114 }
1115
1116 /* Poll and process the result of an ongoing asynchronous LDAP operation. */
1117 PyObject *
1118 LDAPConnection_Result(LDAPConnection *self, int msgid, int millisec) {
1119 int rc = -1;
1120 int err = 0;
1121 int ppres = 0;
1122 unsigned int pperr = 0;
1123 LDAPMessage *res;
1124 LDAPControl **returned_ctrls = NULL;
1125 LDAPModList *mods = NULL;
1126 LDAPEntry *entry = NULL;
1127 struct timeval timeout;
1128 PyObject *obj = NULL;
1129 PyObject *newdn = NULL;
1130 PyObject *retval = NULL;
1131 PyObject *ctrl_obj = NULL;
1132
1133 DEBUG("LDAPConnection_Result (self:%p, msgid:%d, millisec:%d)",
1134 self, msgid, millisec);
1135
1136 obj = get_from_pending_ops(self->pending_ops, msgid);
1137 if (obj == NULL) {
1138 PyObject *ldaperror = get_error_by_code(-100);
1139 PyErr_SetString(ldaperror, "Given message ID is invalid or the"
1140 " associated operation is already finished.");
1141 Py_DECREF(ldaperror);
1142 return NULL;
1143 }
1144
1145 if (self->closed) {
1146 /* The function is called on a initialising and binding procedure. */
1147 /* Check, that we get the right object. */
1148 if (!PyObject_IsInstance(obj, (PyObject *)&LDAPConnectIterType)) {
1149 Py_DECREF(obj);
1150 PyErr_BadInternalCall();
1151 return NULL;
1152 }
1153 retval = LDAPConnectIter_Next((LDAPConnectIter *)obj, millisec);
1154 Py_DECREF(obj);
1155 if (retval == Py_None) {
1156 Py_DECREF(retval);
1157 Py_RETURN_NONE;
1158 } else {
1159 /* The init and bind are finished either success or error. */
1160 /* Remove operations from pending_ops. */
1161 if (del_from_pending_ops(self->pending_ops, msgid) != 0) {
1162 Py_XDECREF(retval);
1163 return NULL;
1164 } else return retval; /* Return with the result of the connectiter. */
1165 }
1166 }
1167
1168 if (millisec >= 0) {
1169 timeout.tv_sec = millisec / 1000;
1170 timeout.tv_usec = (millisec % 1000) * 1000;
1171 } else {
1172 timeout.tv_sec = 0L;
1173 timeout.tv_usec = 0L;
1174 }
1175
1176 if (self->async == 0) {
1177 /* The ldap_result will block, and wait for server response or timeout. */
1178 Py_BEGIN_ALLOW_THREADS
1179 if (millisec >= 0) {
1180 rc = ldap_result(self->ld, msgid, LDAP_MSG_ALL, &timeout, &res);
1181 } else {
1182 /* Wait until response or global timeout. */
1183 rc = ldap_result(self->ld, msgid, LDAP_MSG_ALL, NULL, &res);
1184 }
1185 Py_END_ALLOW_THREADS
1186 } else {
1187 rc = ldap_result(self->ld, msgid, LDAP_MSG_ALL, &timeout, &res);
1188 }
1189
1190 switch (rc) {
1191 case -1:
1192 /* Error occurred during the operation. */
1193 /* Call set_exception with 0 param to get error code from session. */
1194 set_exception(self->ld, 0);
1195 return NULL;
1196 case 0:
1197 /* Timeout exceeded.*/
1198 if (self->async == 0) {
1199 /* Set TimeoutError. */
1200 set_exception(self->ld, -5);
1201 /* Abandon the operation on the server. */
1202 rc = ldap_abandon_ext(self->ld, msgid, NULL, NULL);
1203 if (rc != LDAP_SUCCESS) {
1204 set_exception(self->ld, rc);
1205 }
1206
1207 if (obj != Py_None && !PyUnicode_Check(obj)) {
1208 mods = (LDAPModList *)obj;
1209 /* LDAP add or modify operation is failed,
1210 then rollback the changes. */
1211 if (LDAPEntry_Rollback((LDAPEntry *)mods->entry, mods) != 0) {
1212 Py_DECREF(obj);
1213 return NULL;
1214 }
1215 Py_DECREF(obj);
1216 }
1217 /* Remove operations from pending_ops. */
1218 del_from_pending_ops(self->pending_ops, msgid);
1219
1220 return NULL;
1221 }
1222 break;
1223 case LDAP_RES_SEARCH_ENTRY:
1224 /* Received one of the entries from the server. */
1225 /* Only matters when ldap_result is set with LDAP_MSG_ONE. */
1226 break;
1227 case LDAP_RES_SEARCH_RESULT:
1228 retval = parse_search_result(self, res, obj);
1229 Py_DECREF(obj);
1230 if (del_from_pending_ops(self->pending_ops, msgid) != 0) {
1231 Py_XDECREF(retval);
1232 return NULL;
1233 }
1234 return retval;
1235 case LDAP_RES_EXTENDED:
1236 retval = parse_extended_result(self, res, obj);
1237 Py_DECREF(obj);
1238 if (del_from_pending_ops(self->pending_ops, msgid) != 0) {
1239 Py_XDECREF(retval);
1240 return NULL;
1241 }
1242 if (retval == NULL && PyErr_Occurred()) return NULL;
1243 if (retval != NULL) return retval;
1244 break;
1245 case LDAP_RES_MODRDN:
1246 /* Rename an LDAP entry. */
1247 rc = ldap_parse_result(self->ld, res, &err, NULL, NULL, NULL, NULL, 1);
1248 /* Remove operations from pending_ops. */
1249 if (del_from_pending_ops(self->pending_ops, msgid) != 0) {
1250 Py_DECREF(obj);
1251 return NULL;
1252 }
1253
1254 if (rc != LDAP_SUCCESS || err != LDAP_SUCCESS) {
1255 set_exception(self->ld, err);
1256 Py_DECREF(obj);
1257 return NULL;
1258 }
1259
1260 if (PyArg_ParseTuple(obj, "OO", &entry, &newdn)) {
1261 /* Validate and set new LDAP DN. */
1262 if (LDAPEntry_SetDN(entry, newdn) != 0) {
1263 Py_DECREF(obj);
1264 return NULL;
1265 }
1266 Py_DECREF(obj);
1267 } else {
1268 Py_DECREF(obj);
1269 return NULL;
1270 }
1271 Py_DECREF(obj);
1272
1273 Py_RETURN_TRUE;
1274 default:
1275 rc = ldap_parse_result(self->ld, res, &err, NULL, NULL, NULL,
1276 &returned_ctrls, 1);
1277
1278 /* Remove operations from pending_ops. */
1279 if (del_from_pending_ops(self->pending_ops, msgid) != 0) {
1280 Py_DECREF(obj);
1281 return NULL;
1282 }
1283
1284 ppres = create_ppolicy_control(self->ld, returned_ctrls, &ctrl_obj, &pperr);
1285 if (returned_ctrls != NULL) ldap_controls_free(returned_ctrls);
1286 if (ppres == -1) {
1287 Py_DECREF(obj);
1288 return NULL;
1289 }
1290
1291 if (rc != LDAP_SUCCESS || err != LDAP_SUCCESS) {
1292 mods = (LDAPModList *)obj;
1293 /* LDAP add or modify operation is failed,
1294 then rollback the changes. */
1295 if (LDAPEntry_Rollback((LDAPEntry *)mods->entry, mods) != 0) {
1296 Py_DECREF(obj);
1297 return NULL;
1298 }
1299 Py_DECREF(obj);
1300 /* Set Python error. */
1301 if (ppres == 1 && pperr != 65535) set_ppolicy_err(pperr, ctrl_obj);
1302 else set_exception(self->ld, err);
1303
1304 return NULL;
1305 }
1306
1307 Py_DECREF(obj);
1308 Py_RETURN_TRUE;
1309 }
1310 Py_RETURN_NONE;
1311 }
1312
1313 /* Check the result of an ongoing asynchronous LDAP operation. */
1314 static PyObject *
1315 ldapconnection_result(LDAPConnection *self, PyObject *args, PyObject *kwds) {
1316 int msgid = 0;
1317 int timeout = -1;
1318 PyObject *timeout_obj = NULL;
1319 PyObject *tmp = NULL;
1320
1321 static char *kwlist[] = {"msgid", "timeout", NULL};
1322
1323 if (!PyArg_ParseTupleAndKeywords(args, kwds, "i|O", kwlist, &msgid,
1324 &timeout_obj)) {
1325 PyErr_SetString(PyExc_TypeError, "Wrong parameter.");
1326 return NULL;
1327 }
1328
1329 DEBUG("ldapconnection_result (self:%p, args:%p, kwds:%p)[msgid:%d]",
1330 self, args, kwds, msgid);
1331 if (timeout_obj == Py_None || timeout_obj == NULL) {
1332 timeout = -1;
1333 } else if (PyNumber_Check(timeout_obj) && !PyBool_Check(timeout_obj)) {
1334 tmp = PyNumber_Float(timeout_obj);
1335 if (tmp == NULL) return NULL;
1336
1337 timeout = (int)(PyFloat_AsDouble(tmp) * 1000);
1338 if (timeout < 0) {
1339 PyErr_SetString(PyExc_ValueError, "Wrong timeout parameter. "
1340 "Timeout must be non-negative.");
1341 return NULL;
1342 }
1343 Py_DECREF(tmp);
1344 } else {
1345 PyErr_SetString(PyExc_TypeError, "Wrong timeout parameter.");
1346 return NULL;
1347 }
1348
1349 return LDAPConnection_Result(self, msgid, timeout);
1350 }
1351
1352 /* Abandon an ongoing LDAP operation. */
1353 static PyObject *
1354 ldapconnection_abandon(LDAPConnection *self, PyObject *args) {
1355 int msgid = -1;
1356 int rc = 0;
1357
1358 if (!PyArg_ParseTuple(args, "i", &msgid)) {
1359 return NULL;
1360 }
1361 DEBUG("ldapconnection_abandon (self:%p, args:%p)[msgid:%d]",
1362 self, args, msgid);
1363
1364 rc = ldap_abandon_ext(self->ld, msgid, NULL, NULL);
1365 if (rc != LDAP_SUCCESS) {
1366 set_exception(self->ld, rc);
1367 return NULL;
1368 }
1369
1370 /* Remove message id from the pending_ops. */
1371 if (del_from_pending_ops(self->pending_ops, msgid) != 0) {
1372 return NULL;
1373 }
1374
1375 Py_RETURN_NONE;
1376 }
1377
1378 /* Get the underlying socket descriptor of the LDAP connection. */
1379 static PyObject *
1380 ldapconnection_fileno(LDAPConnection *self) {
1381 int rc = 0;
1382 int desc = 0;
1383
1384 /* For ongoing initialisation return the dummy socket descriptor,
1385 that will be pinged when the init thread is finished. */
1386 if (self->closed && self->csock != -1) {
1387 DEBUG("ldapconnection_fileno (self:%p)[desc:%d, dummy]", self, desc);
1388 return PyLong_FromLong((long int)self->csock);
1389 }
1390
1391 rc = ldap_get_option(self->ld, LDAP_OPT_DESC, &desc);
1392 if (rc != LDAP_SUCCESS) {
1393 set_exception(self->ld, rc);
1394 return NULL;
1395 }
1396 DEBUG("ldapconnection_fileno (self:%p)[desc:%d, ldap_opt_desc]", self, desc);
1397 return PyLong_FromLong((long int)desc);
1398 }
1399
1400 static PyMemberDef ldapconnection_members[] = {
1401 {"is_async", T_BOOL, offsetof(LDAPConnection, async), READONLY,
1402 "Asynchronous connection"},
1403 {"closed", T_BOOL, offsetof(LDAPConnection, closed), READONLY,
1404 "Connection is closed"},
1405 {NULL} /* Sentinel */
1406 };
1407
1408 static PyMethodDef ldapconnection_methods[] = {
1409 {"abandon", (PyCFunction)ldapconnection_abandon, METH_VARARGS,
1410 "Abandon ongoing operation associated with the given message id." },
1411 {"add", (PyCFunction)ldapconnection_add, METH_VARARGS,
1412 "Add new LDAPEntry to the LDAP server."},
1413 {"close", (PyCFunction)ldapconnection_close, METH_VARARGS | METH_KEYWORDS,
1414 "Close connection with the LDAP Server."},
1415 {"delete", (PyCFunction)ldapconnection_delentry, METH_VARARGS,
1416 "Delete an LDAPEntry with the given distinguished name."},
1417 {"fileno", (PyCFunction)ldapconnection_fileno, METH_NOARGS,
1418 "Get the socket descriptor that belongs to the connection."},
1419 {"get_result", (PyCFunction)ldapconnection_result, METH_VARARGS | METH_KEYWORDS,
1420 "Poll the status of the operation associated with the given message id from LDAP server."},
1421 {"open", (PyCFunction)ldapconnection_open, METH_NOARGS,
1422 "Open connection with the LDAP Server."},
1423 {"modify_password", (PyCFunction)ldapconnection_modpasswd, METH_VARARGS | METH_KEYWORDS,
1424 "Modify password for the user."},
1425 {"search", (PyCFunction)ldapconnection_search, METH_VARARGS | METH_KEYWORDS,
1426 "Search for LDAP entries."},
1427 {"whoami", (PyCFunction)ldapconnection_whoami, METH_NOARGS,
1428 "LDAPv3 Who Am I operation."},
1429 {NULL, NULL, 0, NULL} /* Sentinel */
1430 };
1431
1432 PyTypeObject LDAPConnectionType = {
1433 PyVarObject_HEAD_INIT(NULL, 0)
1434 "_bonsai.ldapconnection", /* tp_name */
1435 sizeof(LDAPConnection), /* tp_basicsize */
1436 0, /* tp_itemsize */
1437 (destructor)ldapconnection_dealloc, /* tp_dealloc */
1438 0, /* tp_print */
1439 0, /* tp_getattr */
1440 0, /* tp_setattr */
1441 0, /* tp_reserved */
1442 0, /* tp_repr */
1443 0, /* tp_as_number */
1444 0, /* tp_as_sequence */
1445 0, /* tp_as_mapping */
1446 0, /* tp_hash */
1447 0, /* tp_call */
1448 0, /* tp_str */
1449 0, /* tp_getattro */
1450 0, /* tp_setattro */
1451 0, /* tp_as_buffer */
1452 Py_TPFLAGS_DEFAULT |
1453 Py_TPFLAGS_BASETYPE, /* tp_flags */
1454 "ldapconnection object, implemented in C.", /* tp_doc */
1455 0, /* tp_traverse */
1456 0, /* tp_clear */
1457 0, /* tp_richcompare */
1458 0, /* tp_weaklistoffset */
1459 0, /* tp_iter */
1460 0, /* tp_iternext */
1461 ldapconnection_methods, /* tp_methods */
1462 ldapconnection_members, /* tp_members */
1463 0, /* tp_getset */
1464 0, /* tp_base */
1465 0, /* tp_dict */
1466 0, /* tp_descr_get */
1467 0, /* tp_descr_set */
1468 0, /* tp_dictoffset */
1469 (initproc)ldapconnection_init, /* tp_init */
1470 0, /* tp_alloc */
1471 ldapconnection_new, /* tp_new */
1472 };