File: api.rst

package info (click to toggle)
python-bonsai 1.5.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,108 kB
  • sloc: python: 6,660; ansic: 5,534; makefile: 169; sh: 90
file content (885 lines) | stat: -rw-r--r-- 31,599 bytes parent folder | download
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
API documentation
*****************

bonsai
======

.. automodule:: bonsai
    :noindex:

:class:`LDAPClient`
-------------------
.. autoclass:: LDAPClient(url, tls=False)
.. automethod:: LDAPClient.connect(is_async=False, timeout=None, **kwargs)
.. automethod:: LDAPClient.get_rootDSE()

    An example of getting the root DSE:
    
    >>> client = bonsai.LDAPClient()
    >>> client.get_rootDSE()
    {'namingContexts': ['dc=bonsai,dc=test'], 'supportedControl': ['2.16.840.1.113730.3.4.18',
    '2.16.840.1.113730.3.4.2', '1.3.6.1.4.1.4203.1.10.1', '1.2.840.113556.1.4.319',
    '1.2.826.0.1.3344810.2.3', '1.3.6.1.1.13.2', '1.3.6.1.1.13.1', '1.3.6.1.1.12'],
    'supportedLDAPVersion': ['3'], 'supportedExtension': ['1.3.6.1.4.1.1466.20037',
    '1.3.6.1.4.1.4203.1.11.1', '1.3.6.1.4.1.4203.1.11.3', '1.3.6.1.1.8'],
    'supportedSASLMechanisms': ['DIGEST-MD5', 'NTLM', 'CRAM-MD5']}

.. automethod:: LDAPClient.set_async_connection_class(conn)

    An example to change the default async connection class to a Gevent-based one:

    >>> import bonsai
    >>> from bonsai.gevent import GeventLDAPConnection
    >>> client = bonsai.LDAPClient()
    >>> client.set_async_connection_class(GeventLDAPConnection)
    >>> client.connect(True)
    <bonsai.gevent.geventconnection.GeventLDAPConnection object at 0x7f9b1789c6d8>

.. automethod:: LDAPClient.set_auto_page_acquire(val)
.. automethod:: LDAPClient.set_ca_cert(name)
.. automethod:: LDAPClient.set_ca_cert_dir(path)
.. automethod:: LDAPClient.set_cert_policy(policy)
.. automethod:: LDAPClient.set_client_cert(name)
.. automethod:: LDAPClient.set_client_key(name)

.. automethod:: LDAPClient.set_credentials(mechanism, user=None, password=None, realm=None, authz_id=None, keytab=None)

    >>> from bonsai import LDAPClient
    >>> client = LDAPClient()
    >>> client.set_credentials("SIMPLE", user="cn=user,dc=bonsai,dc=test", password="secret")
    >>> client.connect()
    <bonsai.LDAPConnection object at 0x7fadf8976440>

.. automethod:: LDAPClient.set_extended_dn(extdn_format)

    An example:

    >>> client = bonsai.LDAPClient()
    >>> client.set_extended_dn(1)
    >>> result = conn.search("ou=nerdherd,dc=bonsai,dc=test", 1)
    >>> result[0].extended_dn
    <GUID=899e4e01-e88d-4dea-ba64-119ed386b61c>;<SID=S-1-5-21-101232111302-1767724339-724445543-12345>;cn=chuck,ou=nerdherd,dc=bonsai,dc=test
    >>> result[0].dn
    <LDAPDN cn=chuck,ou=nerdherd,dc=bonsai,dc=test>

.. note:: If the extended dn control is not supported the LDAPEntry's extended_dn attribute
   will be None. The LDAP_SERVER_EXTENDED_DN_OID is defined as '1.2.840.113556.1.4.529'.

.. automethod:: LDAPClient.set_ignore_referrals(val)

.. automethod:: LDAPClient.set_managedsait(val)

.. automethod:: LDAPClient.set_password_policy(ppolicy)

    An example:

    >>> import bonsai
    >>> client = bonsai.LDAPClient()
    >>> client.set_credentials("SIMPLE", "cn=user,dc=bonsai,dc=test", "secret")
    >>> client.set_password_policy(True)
    >>> conn, ctrl = client.connect()
    >>> conn
    <bonsai.ldapconnection.LDAPConnection object at 0x7fa552ab4e28>
    >>> ctrl
    {'grace': 1, 'expire': 3612, 'oid': '1.3.6.1.4.1.42.2.27.8.5.1'})

.. note:: Password policy control cannot be used on MS Windows with WinLDAP.
   In this case after opening a connection the control dictionary will always be
   `None`.

.. automethod:: LDAPClient.set_raw_attributes(raw_list)

    An example:

    >>> client = bonsai.LDAPClient()
    >>> client.set_raw_attributes(["cn", "sn"])
    >>> conn = client.connect()
    >>> conn.search("cn=jeff,ou=nerdherd,dc=bonsai,dc=test", 0, attrlist=['cn', 'sn', 'gn'])
    [{'dn': <LDAPDN cn=jeff,ou=nerdherd,dc=bonsai,dc=test>, 'sn': [b'Barnes'], 'cn': [b'jeff'],
    'givenName': ['Jeff']}]

.. automethod:: LDAPClient.set_sasl_security_properties(no_anonymous=None, no_dict=None, no_plain=None, forward_sec=None, pass_cred=None, min_ssf=None, max_ssf=None, max_bufsize=None)
.. automethod:: LDAPClient.set_sd_flags(flags)
.. automethod:: LDAPClient.set_server_chase_referrals(val)
.. automethod:: LDAPClient.set_url(url)

.. autoattribute:: LDAPClient.auto_page_acquire
.. autoattribute:: LDAPClient.ca_cert
.. autoattribute:: LDAPClient.ca_cert_dir
.. autoattribute:: LDAPClient.cert_policy
.. autoattribute:: LDAPClient.client_cert
.. autoattribute:: LDAPClient.client_key
.. autoattribute:: LDAPClient.credentials
.. autoattribute:: LDAPClient.extended_dn_format
.. autoattribute:: LDAPClient.ignore_referrals
.. autoattribute:: LDAPClient.managedsait
.. autoattribute:: LDAPClient.mechanism
.. autoattribute:: LDAPClient.password_policy
.. autoattribute:: LDAPClient.raw_attributes
.. autoattribute:: LDAPClient.sd_flags
.. autoattribute:: LDAPClient.server_chase_referrals

    *Changed in version 1.3.0:* Default value from *True* to *False*.

.. autoattribute:: LDAPClient.tls
.. autoattribute:: LDAPClient.url

:class:`LDAPConnection`
-----------------------
.. autoclass:: LDAPConnection

.. method:: LDAPConnection.abandon(msg_id)

    Abandon an ongoing asynchronous operation associated with the given message id.
    Note that there is no guarantee that the LDAP server will be able to honor the request, which
    means the operation could be performed anyway. Nevertheless, it is a good programming paradigm
    to abandon unwanted operations (e.g after a timeout is exceeded).

    :param int msg_id: the ID of an ongoing LDAP operation.

.. automethod:: LDAPConnection.add(entry, timeout=None)

.. method:: LDAPConnection.close()

    Close LDAP connection.
    
.. automethod:: LDAPConnection.delete(dname, timeout=None, recursive=False)

.. method:: LDAPConnection.fileno()

    Return the file descriptor of the underlying socket that is used for the LDAP connection.

    :return: The file descriptor.
    :rtype: int

.. method:: LDAPConnection.get_result(msg_id, timeout=None)

    Get the result of an ongoing asynchronous operation associated with the given message id.
    The method blocks the caller until the given `timeout` parameter is passed or the result
    is arrived. If the operation is not finished until the timeout, it returns None. If the
    `timeout` is None, it returns immediately.

    :param int msg_id: the ID of an ongoing LDAP operation.
    :param float timeout:  time limit in seconds for waiting on the result.
    :return: the result of the operation.
    :rtype: depending on the type of the operation.
    :raises bonsai.InvalidMessageID: if the message ID is invalid or the associated operation is
                                     already finished

.. automethod:: LDAPConnection.open(timeout=None)
.. automethod:: LDAPConnection.modify_password(user=None, new_password=None, old_password=None, timeout=None)
.. seealso::
    RFC about the LDAP Password Modify extended operation `RFC3062`_.

.. _RFC3062: https://www.ietf.org/rfc/rfc3062.txt

.. method:: LDAPConnection.search(base=None, scope=None, filter_exp=None, attrlist=None, timeout=None,\
                                  sizelimit=0, attrsonly=False, sort_order=None)

    Perform a search on the directory server. A base DN and a search scope is always necessary to
    perform a search, but these values - along with the attribute's list and search filter - can
    also be set with the :class:`LDAPClient` LDAP URL parameter. The parameters, which are passed
    to the :meth:`LDAPConnection.search` method will overrule the previously set ones with the
    LDAP URL.

    Setting `sort_order` will invoke server side sorting LDAP control, based on the provided attribute list.

    >>> from bonsai import LDAPClient
    >>> client = LDAPClient("ldap://localhost") # without additional parameters
    >>> conn = client.connect()
    >>> conn.search("ou=nerdherd,dc=bonsai,dc=test", 1, "(cn=ch*)", ["cn", "sn", "gn"])
    [{'dn': <LDAPDN cn=chuck,ou=nerdherd,dc=bonsai,dc=test>, 'sn': ['Bartowski'], 'cn': ['chuck'],
    'givenName': ['Chuck']}]
    >>> client = LDAPClient("ldap://localhost/ou=nerdherd,dc=bonsai,dc=test?cn,sn,gn?one?(cn=ch*)") # with additional parameters
    >>> conn = client.connect()
    >>> conn.search()
    [{'dn': <LDAPDN cn=chuck,ou=nerdherd,dc=bonsai,dc=test>, 'sn': ['Bartowski'], 'cn': ['chuck'],
    'givenName': ['Chuck']}]
    >>> conn.search(filter_exp="(cn=j*)")
    [{'dn': <LDAPDN cn=jeff,ou=nerdherd,dc=bonsai,dc=test>, 'sn': ['Barnes'], 'cn': ['jeff'],
    'givenName': ['Jeff']}]

    :param str base: the base DN of the search.
    :param int scope: the scope of the search. An :class:`LDAPSearchScope` also can be used as
                      value.
    :param str filter_exp: string to filter the search in LDAP search filter syntax.
    :param list attrlist: list of attribute's names to receive only those attributes from the
                          directory server.
    :param float timeout: time limit in seconds for the search.
    :param int sizelimit: the number of entries to limit the search.
    :param bool attrsonly: if it's set True, search result will contain only the name of the
                           attributes without their values.
    :param list sort_order: list of attribute's names to use for server-side ordering, start name
                            with '-' for descending order.
    :return: the search result.
    :rtype: list

.. method:: LDAPConnection.paged_search(base=None, scope=None, filter_exp=None, attrlist=None,\
                                        timeout=None, sizelimit=0, attrsonly=False,\
                                        sort_order=None, page_size=1)

    Perform a search that returns a paged search result. The number of entries on a page is limited
    with the `page_size` parameter. The return value is an :class:`ldapsearchiter` which is an
    iterable object. By default, after returning the last entry on the page it automatically requests
    the next page from the server until the final page is delivered. This functionality can be
    disabled by setting the :attr:`LDAPClient.auto_page_acquire` to `false`. Then the next page
    can be acquired manually by calling the :meth:`ldapsearchiter.acquire_next_page` method.

    :param str base: the base DN of the search.
    :param int scope: the scope of the search. An :class:`LDAPSearchScope` also can be used as
                      value.
    :param str filter_exp: string to filter the search in LDAP search filter syntax.
    :param list attrlist: list of attribute's names to receive only those attributes from the
                          directory server.
    :param float timeout: time limit in seconds for the search.
    :param int sizelimit: the number of entries to limit the search.
    :param bool attrsonly: if it's set True, search result will contain only the name of the
                           attributes without their values.
    :param list sort_order: list of attribute's names to use for server-side ordering, start name
                            with '-' for descending order.
    :param int page_size: the number of entries on a page.
    :return: the search result.
    :rtype: ldapsearchiter

.. method:: LDAPConnection.virtual_list_search(base=None, scope=None, filter_exp=None, attrlist=None,\
                                               timeout=None, sizelimit=0, attrsonly=False,\
                                               sort_order=None, offset=1, before_count=0,\
                                               after_count=0, est_list_count=0, attrvalue=None)

    Perform a search using virtual list view control. To perform the search the server side sort
    control has to be set with `sort_order`. The result set will be shifted to the `offset` or
    `attrvalue` and contains the specific number of entries after and before, set with
    `after_count` and `before_count`. The `est_list_count` is an estimation of the entire searched
    list that helps to the server to position the target entry.

    The result of the operation is a tuple of a list and a dictionary. The dictionary contains
    the VLV server response: the target position and the real list size. Thi list contains the
    searched entries.

    For further details using these controls please see :ref:`ldap-controls`.

    :param str base: the base DN of the search.
    :param int scope: the scope of the search. An :class:`LDAPSearchScope` also can be used as
                      value.
    :param str filter_exp: string to filter the search in LDAP search filter syntax.
    :param list attrlist: list of attribute's names to receive only those attributes from the
                          directory server.
    :param float timeout: time limit in seconds for the search.
    :param int sizelimit: the number of entries to limit the search.
    :param bool attrsonly: if it's set True, search result will contain only the name of the
                           attributes without their values.
    :param list sort_order: list of attribute's names to use for server-side ordering, start name
                            with '-' for descending order.
    :param int offset: an offset of the search result to select a target entry for virtual list
                       view (VLV).
    :param int before_count: the number of entries before the target entry for VLV.
    :param int after_count: the number of entries after the target entry for VLV.
    :param int est_list_count: the estimated content count of the entire list for VLV.
    :param attrvalue: an attribute value (of the attribute that is used for sorting) for
                      identifying the target entry for VLV.
    :return: the search result.
    :rtype: (list, dict)

.. automethod:: LDAPConnection.whoami(timeout=None)
.. seealso::
    RFC about the LDAP Who am I extended operation `RFC4532`_.
    
.. _RFC4532: https://tools.ietf.org/html/rfc4532

.. attribute:: LDAPConnection.closed

    A readonly attribute about the connection's state.

.. attribute:: LDAPConnection.is_async

    A readonly attribute to define that the connections is asynchronous.

:class:`LDAPDN`
---------------

Class for representing LDAP distinguished names.
 
.. seealso:: 
    
    RFC about **LDAP: String Representation of Distinguished Names** `RFC4514`_.

.. _RFC4514: https://tools.ietf.org/html/rfc4514

Example for working with LDAPDN objects.

    >>> import bonsai
    >>> dn = bonsai.LDAPDN("cn=testuser,dc=bonsai,dc=test")
    >>> dn
    <LDAPDN cn=testuser,dc=bonsai,dc=test>
    >>> dn.rdns # Get RDNs in tuple format.
    ((('cn', 'testuser'),), (('dc', 'bonsai'),), (('dc', 'test'),))
    >>> str(dn) # Convert to string.
    'cn=testuser,dc=bonsai,dc=test'
    >>> dn[1] # Get the second RDN.
    'dc=bonsai'
    >>> dn[0] # Get the first RDN.
    'cn=testuser'
    >>> dn[1] = "ou=nerdherd,dc=bonsai" # Change the second RDN.
    >>> dn
    <LDAPDN cn=testuser,ou=nerdherd,dc=bonsai,dc=test>
    >>> other_dn = bonsai.LDAPDN("cn=testuser,ou=nerdherd,dc=bonsai,dc=test")
    >>> dn == other_dn
    True
    >>> dn[1:3] # Get the second and third RDN.
    'ou=nerdherd,dc=bonsai'
    >>> dn[1:3] = 'ou=buymore,dc=bonsai' # Change them.
    >>> dn
    <LDAPDN cn=testuser,ou=buymore,dc=bonsai,dc=test>

.. autoclass:: LDAPDN
.. automethod:: LDAPDN.__getitem__(idx)
.. automethod:: LDAPDN.__setitem__(idx, value)
.. automethod:: LDAPDN.__eq__(other)
.. automethod:: LDAPDN.__str__
.. autoattribute:: LDAPDN.rdns

:class:`LDAPEntry`
------------------
.. class:: LDAPEntry(dn[, conn])

.. automethod:: LDAPEntry.change_attribute(name, optype, *values)

.. note::
    It is possible to create an inconsistent state that the server will reject. To
    get a clean state use :meth:`LDAPEntry.clear_attribute_changes`.

.. automethod:: LDAPEntry.clear
.. automethod:: LDAPEntry.clear_attribute_changes(name)
.. automethod:: LDAPEntry.delete(timeout=None, recursive=False)
.. automethod:: LDAPEntry.get(key, default=None)
.. automethod:: LDAPEntry.items(exclude_dn=False)
.. automethod:: LDAPEntry.keys(exclude_dn=False)

.. note::
    Be aware when the `exclude_dn` argument of :meth:`LDAPEntry.items`, :meth:`LDAPEntry.keys`
    or :meth:`LDAPEntry.values` is set to `True` you lose the benefits of `dict views`_ and
    get a generator object that will be sensitive of adding and removing items to the entry.

.. automethod:: LDAPEntry.modify(timeout=None)
.. automethod:: LDAPEntry.rename(newdn, timeout=None, delete_old_rdn=True)
.. automethod:: LDAPEntry.update(*args, **kwds)
.. automethod:: LDAPEntry.values(exclude_dn=False)

.. attribute:: LDAPEntry.connection

    The LDAPConnection object of the entry. Needs to be set for any LDAP operations.

.. attribute:: LDAPEntry.dn

    The distinguished name of the entry.
    
    >>> from bonsai import LDAPEntry
    >>> anna = LDAPEntry('cn=anna,ou=nerdherd,dc=bonsai,dc=test')
    >>> anna.dn
    <LDAPDN cn=anna,ou=nerdherd,dc=bonsai,dc=test>
    >>> str(anna.dn)
    'cn=anna,ou=nerdherd,dc=bonsai,dc=test'

.. autoattribute:: LDAPEntry.extended_dn


:class:`LDAPModOp`
------------------

.. autoclass:: LDAPModOp

.. autoattribute:: LDAPModOp.ADD
.. autoattribute:: LDAPModOp.DELETE
.. autoattribute:: LDAPModOp.REPLACE

:class:`LDAPReference`
----------------------

.. autoclass:: LDAPReference(client, references)

.. autoattribute:: LDAPReference.client
.. autoattribute:: LDAPReference.references

:class:`LDAPSearchScope`
------------------------

.. autoclass:: LDAPSearchScope

.. autoattribute:: LDAPSearchScope.BASE
.. autoattribute:: LDAPSearchScope.ONELEVEL
.. autoattribute:: LDAPSearchScope.ONE
.. autoattribute:: LDAPSearchScope.SUBTREE
.. autoattribute:: LDAPSearchScope.SUB

:class:`LDAPURL`
----------------
.. seealso:: 
    
    RFC about **LDAP: Uniform Resource Locator** `RFC4516`_.

.. _RFC4516: http://tools.ietf.org/html/rfc4516

.. autoclass:: LDAPURL(str)

    An example of a valid LDAP URL with port number, base DN, list of 
    attributes and search filter:
    
    >>> from bonsai import LDAPURL
    >>> url = LDAPURL("ldap://localhost:789/ou=nerdherd,dc=bonsai,dc=test?cn,sn,gn?sub?(cn=c*)")
    >>> url
    <LDAPURL ldap://localhost:789/ou=nerdherd,dc=bonsai,dc=test?cn,sn,gn?sub?(cn=c*)>
    >>> url.basedn
    <LDAPDN ou=nerdherd,dc=bonsai,dc=test>
    >>> url.attributes
    ['cn', 'sn', 'gn']

.. automethod:: LDAPURL.get_address

   >>> import bonsai
   >>> url = bonsai.LDAPURL("ldaps://example.com/cn=test,dc=bonsai,dc=test??sub")
   >>> url
   <LDAPURL ldaps://example.com:636/cn=test,dc=bonsai,dc=test??sub>
   >>> url.get_address()
   'ldaps://example.com:636'

.. automethod:: LDAPURL.__str__
.. autoattribute:: LDAPURL.attributes
.. autoattribute:: LDAPURL.basedn
.. autoattribute:: LDAPURL.host
.. autoattribute:: LDAPURL.port
.. autoattribute:: LDAPURL.filter_exp
.. autoattribute:: LDAPURL.scope
.. autoattribute:: LDAPURL.scope_num
.. autoattribute:: LDAPURL.scheme

:class:`LDAPValueList`
----------------------

.. autoclass:: LDAPValueList(items)
.. automethod:: LDAPValueList.__contains__(item)
.. automethod:: LDAPValueList.__delitem__(idx)
.. automethod:: LDAPValueList.__setitem__(idx, value)
.. automethod:: LDAPValueList.__add__(other)
.. automethod:: LDAPValueList.__iadd__(other)
.. automethod:: LDAPValueList.__mul__(value)
.. automethod:: LDAPValueList.append(item)
.. automethod:: LDAPValueList.extend(items)
.. automethod:: LDAPValueList.insert(idx, value)
.. automethod:: LDAPValueList.remove(value)
.. automethod:: LDAPValueList.pop(idx=-1)
.. automethod:: LDAPValueList.clear
.. automethod:: LDAPValueList.copy
.. autoattribute:: LDAPValueList.status

bonsai.active_directory
=======================

.. automodule:: bonsai.active_directory

:class:`ACE`
------------

.. autoclass:: ACE(ace_type, flags, mask, trustee_sid, object_type, inherited_object_type, application_data)

.. note::
     For more details, see offical Microsoft docs about `ACE`_.

.. automethod:: ACE.from_binary(data)
.. automethod:: ACE.to_binary()
.. automethod:: ACE.__eq__(other)
.. automethod:: ACE.__str__()
.. automethod:: ACE.set_access_rights(rights)
.. automethod:: ACE.set_application_data(data)
.. automethod:: ACE.set_flags(flags)
.. automethod:: ACE.set_object_type(object_type)
.. automethod:: ACE.set_inherited_object_type(object_type)
.. automethod:: ACE.set_type(ace_type)
.. automethod:: ACE.set_trustee_sid(sid)
.. autoattribute:: ACE.application_data
.. autoattribute:: ACE.flags
.. autoattribute:: ACE.is_inherited
.. autoattribute:: ACE.inherited_object_type
.. autoattribute:: ACE.mask
.. autoattribute:: ACE.object_type
.. autoattribute:: ACE.size
.. autoattribute:: ACE.trustee_sid

:class:`ACEFlag`
----------------

.. autoclass:: ACEFlag
    :members:
    :undoc-members:
    :member-order: bysource

:class:`ACERight`
-----------------

.. autoclass:: ACERight
    :members:
    :undoc-members:
    :member-order: bysource

:class:`ACEType`
----------------

.. autoclass:: ACEType
    :members:
    :undoc-members:
    :member-order: bysource

:class:`ACL`
------------

.. autoclass:: ACL(revision, aces)

.. note::
     For more details, see offical Microsoft docs about `ACL`_.

.. automethod:: ACL.from_binary(data)
.. automethod:: ACL.to_binary()
.. automethod:: ACL.set_aces(aces)
.. autoattribute:: ACL.aces
.. autoattribute:: ACL.revision
.. autoattribute:: ACL.size

:class:`ACLRevision`
--------------------

.. autoclass:: ACLRevision
    :members:
    :undoc-members:
    :member-order: bysource

:class:`SecurityDescriptor`
---------------------------

.. autoclass:: SecurityDescriptor(control, owner_sid, group_sid, sacl, dacl, revision = 1, sbz1 = 0)

.. note::
    For more details, see offical Microsoft docs about `SECURITY_DESCRIPTOR`_.

.. automethod:: SecurityDescriptor.from_binary(data)
.. automethod:: SecurityDescriptor.to_binary()
.. automethod:: SecurityDescriptor.set_control(control)
.. automethod:: SecurityDescriptor.set_owner_sid(owner_sid)
.. automethod:: SecurityDescriptor.set_group_sid(group_sid)
.. automethod:: SecurityDescriptor.set_dacl(dacl)
.. automethod:: SecurityDescriptor.set_sacl(sacl)
.. autoattribute:: SecurityDescriptor.control
.. autoattribute:: SecurityDescriptor.dacl
.. autoattribute:: SecurityDescriptor.group_sid
.. autoattribute:: SecurityDescriptor.owner_sid
.. autoattribute:: SecurityDescriptor.revision
.. autoattribute:: SecurityDescriptor.sacl
.. autoattribute:: SecurityDescriptor.sbz1

:class:`SID`
------------

.. autoclass:: SID(str_rep = None, bytes_le = None)

.. note::
    For more details, see offical Microsoft docs about `SID`_.

.. automethod:: SID.__eq__(other)
.. automethod:: SID.__repr__()
.. automethod:: SID.__str__()
.. autoattribute:: SID.bytes_le
.. autoattribute:: SID.identifier_authority
.. autoattribute:: SID.revision
.. autoattribute:: SID.sddl_alias
.. autoattribute:: SID.size
.. autoattribute:: SID.subauthorities


:class:`UserAccountControl`
---------------------------

.. autoclass:: UserAccountControl(flags)

.. note::
    For more details, see offical Microsoft docs about `UserAccountControl`_.

.. autoattribute:: UserAccountControl.properties
.. autoattribute:: UserAccountControl.value

bonsai.asyncio
==============

.. automodule:: bonsai.asyncio


:class:`AIOLDAPConnection`
--------------------------

.. autoclass:: AIOLDAPConnection

.. note::
    The default asyncio event loop is changed with Python 3.8 on Windows to
    `ProactorEventLoop`. Unfortunately, bonsai's asyncio connection requires
    the old `SelectorEventLoop`. Make sure to change it back before using
    the module:

    .. code-block:: python

        if sys.platform == 'win32':
            import asyncio
            asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    Getting ``NotImplementedError`` from the ``add_reader`` method of the
    event loop may indicate that it has not been properly set.

:class:`AIOConnectionPool`
--------------------------

.. autoclass:: AIOConnectionPool

bonsai.gevent
=============

.. automodule:: bonsai.gevent

:class:`GeventLDAPConnection`
-----------------------------

.. autoclass:: bonsai.gevent.GeventLDAPConnection

bonsai.ldif
===========

.. automodule:: bonsai

:class:`LDIFReader`
-------------------

.. autoclass:: LDIFReader(input_file, autoload=True, max_length=76)

Example of reading an LDIF file:

.. code-block:: python

    import bonsai

    with open("./users.ldif") as fileobj:
        reader = bonsai.LDIFReader(fileobj)
        for entry in reader:
            print(entry.dn)

.. autoattribute:: LDIFReader.autoload
.. autoattribute:: LDIFReader.input_file
.. autoattribute:: LDIFReader.resource_handlers

:class:`LDIFWriter`
-------------------

.. autoclass:: LDIFWriter(output_file, max_length=76)
.. automethod:: LDIFWriter.write_entry(entry)

   >>> import bonsai
   >>> output = open("./out.ldif", "w")
   >>> writer = bonsai.LDIFWriter(output)
   >>> entry = bonsai.LDAPEntry("cn=test")
   >>> entry["cn"] = "test"
   >>> writer.write_entry(entry)

.. automethod:: LDIFWriter.write_entries(entries, write_version=True)

   >>> client = bonsai.LDAPClient()
   >>> conn = client.connect()
   >>> res = conn.search("ou=nerdherd,dc=bonsai,dc=test", bonsai.LDAPSearchScope.ONE)
   >>> output = open("./out.ldif", "w")
   >>> writer = bonsai.LDIFWriter(output)
   >>> writer.write_entries(res)

.. automethod:: LDIFWriter.write_changes(entry)
.. autoattribute:: LDIFWriter.output_file

bonsai.pool
===========

:class:`ConnectionPool`
-----------------------

.. autoclass:: bonsai.pool.ConnectionPool

   >>> import bonsai
   >>> from bonsai.pool import ConnectionPool
   >>> client = bonsai.LDAPClient()
   >>> pool = ConnectionPool(client, 1, 2)
   >>> pool.open()
   >>> conn = pool.get()
   >>> conn.whomai()
   'anonymus'
   >>> pool.put(conn)
   >>> pool.close()

.. automethod:: bonsai.pool.ConnectionPool.close
.. automethod:: bonsai.pool.ConnectionPool.get
.. automethod:: bonsai.pool.ConnectionPool.open
.. automethod:: bonsai.pool.ConnectionPool.put
.. automethod:: bonsai.pool.ConnectionPool.spawn

    Example usage:

.. code-block:: python

    import bonsai
    from bonsai.pool import ConnectionPool

    client = bonsai.LDAPClient()
    pool = ConnectionPool(client)
    with pool.spawn() as conn:
        print(conn.whoami())

:class:`ThreadedConnectionPool`
-------------------------------

.. autoclass:: bonsai.pool.ThreadedConnectionPool
.. automethod:: bonsai.pool.ThreadedConnectionPool.get

bonsai.tornado
==============

:class:`TornadoLDAPConnection`
------------------------------

.. autoclass:: bonsai.tornado.TornadoLDAPConnection

bonsai.trio
==============

:class:`TrioLDAPConnection`
------------------------------

.. autoclass:: bonsai.trio.TrioLDAPConnection

_bonsai
=======

:class:`ldapsearchiter`
-----------------------

Helper class for paged search result.

.. method:: ldapsearchiter.acquire_next_page

    Request the next page of result. Returns with the message ID of the search operation.
    This method can only be used if the :attr:`LDAPClient.auto_page_acquire` is `False`.

    :return: an ID of the next search operation.
    :rtype: int.

Errors
======
.. autoclass:: bonsai.LDAPError
.. autoclass:: bonsai.LDIFError
.. autoclass:: bonsai.AffectsMultipleDSA
.. autoclass:: bonsai.AlreadyExists
.. autoclass:: bonsai.AuthenticationError
.. autoclass:: bonsai.AuthMethodNotSupported
.. autoclass:: bonsai.ConnectionError
.. autoclass:: bonsai.ClosedConnection
.. autoclass:: bonsai.InsufficientAccess
.. autoclass:: bonsai.InvalidDN
.. autoclass:: bonsai.InvalidMessageID
.. autoclass:: bonsai.NoSuchAttribute
.. autoclass:: bonsai.NoSuchObjectError
.. autoclass:: bonsai.NotAllowedOnNonleaf
.. autoclass:: bonsai.ObjectClassViolation
.. autoclass:: bonsai.ProtocolError
.. autoclass:: bonsai.SizeLimitError
.. autoclass:: bonsai.TimeoutError
.. autoclass:: bonsai.TypeOrValueExists
.. autoclass:: bonsai.UnwillingToPerform
.. autoclass:: bonsai.PasswordPolicyError()
.. autoclass:: bonsai.AccountLocked()
.. autoclass:: bonsai.ChangeAfterReset()
.. autoclass:: bonsai.InsufficientPasswordQuality()
.. autoclass:: bonsai.MustSupplyOldPassword()
.. autoclass:: bonsai.PasswordExpired()
.. autoclass:: bonsai.PasswordInHistory()
.. autoclass:: bonsai.PasswordModNotAllowed()
.. autoclass:: bonsai.PasswordTooShort()
.. autoclass:: bonsai.PasswordTooYoung()
.. autoclass:: bonsai.pool.PoolError
.. autoclass:: bonsai.pool.ClosedPool
.. autoclass:: bonsai.pool.EmptyPool

Utility functions
=================
.. autofunction:: bonsai.utils.escape_attribute_value(attrval)

    >>> import bonsai
    >>> bonsai.escape_attribute_value(",cn=escaped")
    '\\,cn\\=escaped'

.. autofunction:: bonsai.utils.escape_filter_exp(filter_exp)

    >>> import bonsai
    >>> filter_exp = "(&(userID={0})(objectClass=user))"
    >>> untrusted_input = "*)(userID=*))(|(userID=*"
    >>> filter_exp.format(untrusted_input)
    '(&(userID=*)(userID=*))(|(userID=*)(objectClass=user))'
    >>> filter_exp.format(bonsai.escape_filter_exp(untrusted_input))
    '(&(userID=\\2A\\29\\28userID=\\2A\\29\\29\\28|\\28userID=\\2A)(objectClass=user))'

.. function:: bonsai.get_tls_impl_name

    Return the identification of the underlying TLS implementation that is used by
    the LDAP library:

    >>> bonsai.get_tls_impl_name()
    "MozNSS"

    The possible return values are: `GnuTLS`, `OpenSSL`, `MozNSS` and `SChannel`.

    :return: A identification of TLS implementation.
    :rtype: str

.. function:: bonsai.get_vendor_info

    Return the vendor's name and the version number of the LDAP library:

    >>> bonsai.get_vendor_info()
    ("OpenLDAP", 20440)

    :return: A tuple of the vendor's name and the library's version.
    :rtype: tuple

.. function:: bonsai.has_krb5_support

    :return: True if the module is built with the optional Kerberos/GSSAPI headers.
    :rtype: bool

.. function:: bonsai.set_connect_async(allow)

    Disable/enable asynchronous connection for the underlying socket, which means
    that the socket is set to be non-blocking when it's enabled. The default setting
    is `False` on every platform. This is an OpenLDAP specific setting (see
    `LDAP_OPT_CONNECT_ASYNC` option in the OpenLDAP documentation for further details).

    :param bool allow: Enabling/disabling async connect mode.

.. warning:: Experience shows that this is a delicate setting. Even with a newer OpenLDAP,
    the TLS library version used by libldap might be unable to handle non-blocking
    sockets correctly.

.. function:: bonsai.set_debug(debug, level=0)

    Set debug mode for the module. Turning it on will provide traceback information
    of C function calls on the standard output.

    If the module uses OpenLDAP, then setting the `level` parameter to a non-zero
    integer will also give additional info about the libldap function calls.

    :param bool debug: Enabling/disabling debug mode.
    :param int level: The debug level (for OpenLDAP only).

.. _dict views: https://docs.python.org/3/library/stdtypes.html#dict-views

.. _ACE: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/d06e5a81-176e-46c6-9cf7-9137aad4455e
.. _ACL: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/20233ed8-a6c6-4097-aafa-dd545ed24428
.. _SECURITY_DESCRIPTOR: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/7d4dac05-9cef-4563-a058-f108abecce1d
.. _SID: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/78eb9013-1c3a-4970-ad1f-2b1dad588a25
.. _UserAccountControl: https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/useraccountcontrol-manipulate-account-properties