File: exceptions.py

package info (click to toggle)
python-ldap3 0.9.9.3-1~bpo8%2B2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 2,316 kB
  • sloc: python: 19,119; makefile: 3
file content (579 lines) | stat: -rw-r--r-- 16,559 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
"""
"""

# Created on 2014.05.14
#
# Author: Giovanni Cannata
#
# Copyright 2015 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ldap3 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ldap3 in the COPYING and COPYING.LESSER files.
# If not, see <http://www.gnu.org/licenses/>.

from .. import RESULT_OPERATIONS_ERROR, RESULT_PROTOCOL_ERROR, RESULT_TIME_LIMIT_EXCEEDED, RESULT_SIZE_LIMIT_EXCEEDED, \
    RESULT_STRONGER_AUTH_REQUIRED, RESULT_REFERRAL, RESULT_ADMIN_LIMIT_EXCEEDED, RESULT_UNAVAILABLE_CRITICAL_EXTENSION, \
    RESULT_AUTH_METHOD_NOT_SUPPORTED, RESULT_UNDEFINED_ATTRIBUTE_TYPE, RESULT_NO_SUCH_ATTRIBUTE, \
    RESULT_SASL_BIND_IN_PROGRESS, RESULT_CONFIDENTIALITY_REQUIRED, RESULT_INAPPROPRIATE_MATCHING, \
    RESULT_CONSTRAINT_VIOLATION, \
    RESULT_ATTRIBUTE_OR_VALUE_EXISTS, RESULT_INVALID_ATTRIBUTE_SYNTAX, RESULT_NO_SUCH_OBJECT, RESULT_ALIAS_PROBLEM, \
    RESULT_INVALID_DN_SYNTAX, RESULT_ALIAS_DEREFERENCING_PROBLEM, RESULT_INVALID_CREDENTIALS, RESULT_LOOP_DETECTED, \
    RESULT_ENTRY_ALREADY_EXISTS, RESULT_LCUP_SECURITY_VIOLATION, RESULT_CANCELED, RESULT_E_SYNC_REFRESH_REQUIRED, \
    RESULT_NO_SUCH_OPERATION, RESULT_LCUP_INVALID_DATA, RESULT_OBJECT_CLASS_MODS_PROHIBITED, RESULT_NAMING_VIOLATION, \
    RESULT_INSUFFICIENT_ACCESS_RIGHTS, RESULT_OBJECT_CLASS_VIOLATION, RESULT_TOO_LATE, RESULT_CANNOT_CANCEL, \
    RESULT_LCUP_UNSUPPORTED_SCHEME, RESULT_BUSY, RESULT_AFFECT_MULTIPLE_DSAS, RESULT_UNAVAILABLE, \
    RESULT_NOT_ALLOWED_ON_NON_LEAF, \
    RESULT_UNWILLING_TO_PERFORM, RESULT_OTHER, RESULT_LCUP_RELOAD_REQUIRED, RESULT_ASSERTION_FAILED, \
    RESULT_AUTHORIZATION_DENIED, RESULT_LCUP_RESOURCES_EXHAUSTED, RESULT_NOT_ALLOWED_ON_RDN, \
    RESULT_INAPPROPRIATE_AUTHENTICATION
import socket


# LDAPException hierarchy
class LDAPException(Exception):
    pass


class LDAPOperationResult(LDAPException):
    def __new__(cls, result=None, description=None, dn=None, message=None, response_type=None, response=None):
        if cls is LDAPOperationResult and result and result in exception_table:
            exc = super(LDAPOperationResult, exception_table[result]).__new__(
                exception_table[result])  # create an exception of the required result error
            exc.result = result
            exc.description = description
            exc.dn = dn
            exc.message = message
            exc.type = response_type
            exc.response = response
        else:
            exc = super(LDAPOperationResult, cls).__new__(cls)
        return exc

    def __init__(self, result=None, description=None, dn=None, message=None, response_type=None, response=None):
        self.result = result
        self.description = description
        self.dn = dn
        self.message = message
        self.type = response_type
        self.response = response

    def __str__(self):
        s = [self.__class__.__name__,
             str(self.result) if self.result else None,
             self.description if self.description else None,
             self.dn if self.dn else None,
             self.message if self.message else None,
             self.type if self.type else None,
             self.response if self.response else None]

        return ' - '.join([str(item) for item in s if s is not None])

    def __repr__(self):
        return self.__str__()


class LDAPOperationsErrorResult(LDAPOperationResult):
    pass


class LDAPProtocolErrorResult(LDAPOperationResult):
    pass


class LDAPTimeLimitExceededResult(LDAPOperationResult):
    pass


class LDAPSizeLimitExceededResult(LDAPOperationResult):
    pass


class LDAPAuthMethodNotSupportedResult(LDAPOperationResult):
    pass


class LDAPStrongerAuthRequiredResult(LDAPOperationResult):
    pass


class LDAPReferralResult(LDAPOperationResult):
    pass


class LDAPAdminLimitExceededResult(LDAPOperationResult):
    pass


class LDAPUnavailableCriticalExtensionResult(LDAPOperationResult):
    pass


class LDAPConfidentialityRequiredResult(LDAPOperationResult):
    pass


class LDAPSASLBindInProgressResult(LDAPOperationResult):
    pass


class LDAPNoSuchAttributeResult(LDAPOperationResult):
    pass


class LDAPUndefinedAttributeTypeResult(LDAPOperationResult):
    pass


class LDAPInappropriateMatchingResult(LDAPOperationResult):
    pass


class LDAPConstraintViolationResult(LDAPOperationResult):
    pass


class LDAPAttributeOrValueExistsResult(LDAPOperationResult):
    pass


class LDAPInvalidAttributeSyntaxResult(LDAPOperationResult):
    pass


class LDAPNoSuchObjectResult(LDAPOperationResult):
    pass


class LDAPAliasProblemResult(LDAPOperationResult):
    pass


class LDAPInvalidDNSyntaxResult(LDAPOperationResult):
    pass


class LDAPAliasDereferencingProblemResult(LDAPOperationResult):
    pass


class LDAPInappropriateAuthenticationResult(LDAPOperationResult):
    pass


class LDAPInvalidCredentialsResult(LDAPOperationResult):
    pass


class LDAPInsufficientAccessRightsResult(LDAPOperationResult):
    pass


class LDAPBusyResult(LDAPOperationResult):
    pass


class LDAPUnavailableResult(LDAPOperationResult):
    pass


class LDAPUnwillingToPerformResult(LDAPOperationResult):
    pass


class LDAPLoopDetectedResult(LDAPOperationResult):
    pass


class LDAPNamingViolationResult(LDAPOperationResult):
    pass


class LDAPObjectClassViolationResult(LDAPOperationResult):
    pass


class LDAPNotAllowedOnNotLeafResult(LDAPOperationResult):
    pass


class LDAPNotAllowedOnRDNResult(LDAPOperationResult):
    pass


class LDAPEntryAlreadyExistsResult(LDAPOperationResult):
    pass


class LDAPObjectClassModsProhibitedResult(LDAPOperationResult):
    pass


class LDAPAffectMultipleDSASResult(LDAPOperationResult):
    pass


class LDAPOtherResult(LDAPOperationResult):
    pass


class LDAPLCUPResourcesExhaustedResult(LDAPOperationResult):
    pass


class LDAPLCUPSecurityViolationResult(LDAPOperationResult):
    pass


class LDAPLCUPInvalidDataResult(LDAPOperationResult):
    pass


class LDAPLCUPUnsupportedSchemeResult(LDAPOperationResult):
    pass


class LDAPLCUPReloadRequiredResult(LDAPOperationResult):
    pass


class LDAPCanceledResult(LDAPOperationResult):
    pass


class LDAPNoSuchOperationResult(LDAPOperationResult):
    pass


class LDAPTooLateResult(LDAPOperationResult):
    pass


class LDAPCannotCancelResult(LDAPOperationResult):
    pass


class LDAPAssertionFailedResult(LDAPOperationResult):
    pass


class LDAPAuthorizationDeniedResult(LDAPOperationResult):
    pass


class LDAPESyncRefreshRequiredResult(LDAPOperationResult):
    pass


exception_table = {RESULT_OPERATIONS_ERROR: LDAPOperationsErrorResult,
                   RESULT_PROTOCOL_ERROR: LDAPProtocolErrorResult,
                   RESULT_TIME_LIMIT_EXCEEDED: LDAPTimeLimitExceededResult,
                   RESULT_SIZE_LIMIT_EXCEEDED: LDAPSizeLimitExceededResult,
                   RESULT_AUTH_METHOD_NOT_SUPPORTED: LDAPAuthMethodNotSupportedResult,
                   RESULT_STRONGER_AUTH_REQUIRED: LDAPStrongerAuthRequiredResult,
                   RESULT_REFERRAL: LDAPReferralResult,
                   RESULT_ADMIN_LIMIT_EXCEEDED: LDAPAdminLimitExceededResult,
                   RESULT_UNAVAILABLE_CRITICAL_EXTENSION: LDAPUnavailableCriticalExtensionResult,
                   RESULT_CONFIDENTIALITY_REQUIRED: LDAPConfidentialityRequiredResult,
                   RESULT_SASL_BIND_IN_PROGRESS: LDAPSASLBindInProgressResult,
                   RESULT_NO_SUCH_ATTRIBUTE: LDAPNoSuchAttributeResult,
                   RESULT_UNDEFINED_ATTRIBUTE_TYPE: LDAPUndefinedAttributeTypeResult,
                   RESULT_INAPPROPRIATE_MATCHING: LDAPInappropriateMatchingResult,
                   RESULT_CONSTRAINT_VIOLATION: LDAPConstraintViolationResult,
                   RESULT_ATTRIBUTE_OR_VALUE_EXISTS: LDAPAttributeOrValueExistsResult,
                   RESULT_INVALID_ATTRIBUTE_SYNTAX: LDAPInvalidAttributeSyntaxResult,
                   RESULT_NO_SUCH_OBJECT: LDAPNoSuchObjectResult,
                   RESULT_ALIAS_PROBLEM: LDAPAliasProblemResult,
                   RESULT_INVALID_DN_SYNTAX: LDAPInvalidDNSyntaxResult,
                   RESULT_ALIAS_DEREFERENCING_PROBLEM: LDAPAliasDereferencingProblemResult,
                   RESULT_INAPPROPRIATE_AUTHENTICATION: LDAPInappropriateAuthenticationResult,
                   RESULT_INVALID_CREDENTIALS: LDAPInvalidCredentialsResult,
                   RESULT_INSUFFICIENT_ACCESS_RIGHTS: LDAPInsufficientAccessRightsResult,
                   RESULT_BUSY: LDAPBusyResult,
                   RESULT_UNAVAILABLE: LDAPUnavailableResult,
                   RESULT_UNWILLING_TO_PERFORM: LDAPUnwillingToPerformResult,
                   RESULT_LOOP_DETECTED: LDAPLoopDetectedResult,
                   RESULT_NAMING_VIOLATION: LDAPNamingViolationResult,
                   RESULT_OBJECT_CLASS_VIOLATION: LDAPObjectClassViolationResult,
                   RESULT_NOT_ALLOWED_ON_NON_LEAF: LDAPNotAllowedOnNotLeafResult,
                   RESULT_NOT_ALLOWED_ON_RDN: LDAPNotAllowedOnRDNResult,
                   RESULT_ENTRY_ALREADY_EXISTS: LDAPEntryAlreadyExistsResult,
                   RESULT_OBJECT_CLASS_MODS_PROHIBITED: LDAPObjectClassModsProhibitedResult,
                   RESULT_AFFECT_MULTIPLE_DSAS: LDAPAffectMultipleDSASResult,
                   RESULT_OTHER: LDAPOtherResult,
                   RESULT_LCUP_RESOURCES_EXHAUSTED: LDAPLCUPResourcesExhaustedResult,
                   RESULT_LCUP_SECURITY_VIOLATION: LDAPLCUPSecurityViolationResult,
                   RESULT_LCUP_INVALID_DATA: LDAPLCUPInvalidDataResult,
                   RESULT_LCUP_UNSUPPORTED_SCHEME: LDAPLCUPUnsupportedSchemeResult,
                   RESULT_LCUP_RELOAD_REQUIRED: LDAPLCUPReloadRequiredResult,
                   RESULT_CANCELED: LDAPCanceledResult,
                   RESULT_NO_SUCH_OPERATION: LDAPNoSuchOperationResult,
                   RESULT_TOO_LATE: LDAPTooLateResult,
                   RESULT_CANNOT_CANCEL: LDAPCannotCancelResult,
                   RESULT_ASSERTION_FAILED: LDAPAssertionFailedResult,
                   RESULT_AUTHORIZATION_DENIED: LDAPAuthorizationDeniedResult,
                   RESULT_E_SYNC_REFRESH_REQUIRED: LDAPESyncRefreshRequiredResult}


class LDAPExceptionError(LDAPException):
    pass


# configuration exceptions
class LDAPConfigurationError(LDAPExceptionError):
    pass


class LDAPUnknownStrategyError(LDAPConfigurationError):
    pass


class LDAPUnknownAuthenticationMethodError(LDAPConfigurationError):
    pass


class LDAPSSLConfigurationError(LDAPConfigurationError):
    pass


class LDAPDefinitionError(LDAPConfigurationError):
    pass


class LDAPPackageUnavailableError(LDAPConfigurationError, ImportError):
    pass


class LDAPConfigurationParameterError(LDAPConfigurationError):
    pass


# abstract layer exceptions
class LDAPKeyError(LDAPExceptionError, KeyError, AttributeError):
    pass


class LDAPAttributeError(LDAPExceptionError, AttributeError):
    pass


class LDAPEntryError(LDAPExceptionError):
    pass


class LDAPObjectError(LDAPExceptionError, ValueError):
    pass


class LDAPTypeError(LDAPExceptionError, TypeError):
    pass


class LDAPReaderError(LDAPExceptionError):
    pass


# security exceptions
class LDAPSSLNotSupportedError(LDAPExceptionError, ImportError):
    pass


class LDAPInvalidTlsSpecificationError(LDAPExceptionError):
    pass


class LDAPInvalidHashAlgorithmError(LDAPExceptionError, ValueError):
    pass


# connection exceptions
class LDAPBindError(LDAPExceptionError):
    pass


class LDAPInvalidServerError(LDAPExceptionError):
    pass


class LDAPSASLMechanismNotSupportedError(LDAPExceptionError):
    pass


class LDAPConnectionIsReadOnlyError(LDAPExceptionError):
    pass


class LDAPChangesError(LDAPExceptionError, ValueError):
    pass


class LDAPServerPoolError(LDAPExceptionError):
    pass


class LDAPServerPoolExhaustedError(LDAPExceptionError):
    pass


class LDAPInvalidPortError(LDAPExceptionError):
    pass


class LDAPStartTLSError(LDAPExceptionError):
    pass


class LDAPCertificateError(LDAPExceptionError):
    pass


class LDAPPasswordIsMandatoryError(LDAPExceptionError):
    pass


class LDAPInvalidFilterError(LDAPExceptionError):
    pass


class LDAPInvalidScopeError(LDAPExceptionError, ValueError):
    pass


class LDAPInvalidDereferenceAliasesError(LDAPExceptionError, ValueError):
    pass


class LDAPControlsError(LDAPExceptionError, ValueError):
    pass


class LDAPExtensionError(LDAPExceptionError, ValueError):
    pass


class LDAPLDIFError(LDAPExceptionError):
    pass


class LDAPSchemaError(LDAPExceptionError):
    pass


class LDAPSASLPrepError(LDAPExceptionError):
    pass


class LDAPSASLBindInProgressError(LDAPExceptionError):
    pass


class LDAPMetricsError(LDAPExceptionError):
    pass


class LDAPObjectClassError(LDAPExceptionError):
    pass


class LDAPInvalidDnError(LDAPExceptionError):
    pass


class LDAPResponseTimeoutError(LDAPExceptionError):
    pass


# communication exceptions
class LDAPCommunicationError(LDAPExceptionError):
    pass


class LDAPSocketOpenError(LDAPCommunicationError):
    pass


class LDAPSocketCloseError(LDAPCommunicationError):
    pass


class LDAPSocketReceiveError(LDAPCommunicationError, socket.error):
    pass


class LDAPSocketSendError(LDAPCommunicationError, socket.error):
    pass


class LDAPSessionTerminatedByServerError(LDAPCommunicationError):
    pass


class LDAPUnknownResponseError(LDAPCommunicationError):
    pass


class LDAPUnknownRequestError(LDAPCommunicationError):
    pass


class LDAPReferralError(LDAPCommunicationError):
    pass


# pooling exceptions
class LDAPConnectionPoolNameIsMandatoryError(LDAPExceptionError):
    pass


class LDAPConnectionPoolNotStartedError(LDAPExceptionError):
    pass


# restartable strategy
class LDAPMaximumRetriesError(LDAPExceptionError):
    def __str__(self):
        if self.args:
            if isinstance(self.args, tuple):
                if len(self.args) > 0:
                    print('LDAPMaximumRetriesError: ' + self.args[0])
                if len(self.args) > 1:
                    print('Exception history:')
                    for i, exc in enumerate(self.args[1]):  # args[1] contains exception history
                        print(str(i).rjust(5), str(exc[0]), ':', exc[1], '-', exc[2])
                if len(self.args) > 2:
                    print('Maximum number of retries reached: ' + str(self.args[2]))
        else:
            LDAPExceptionError.__str__(self)


# exception factories
def communication_exception_factory(exc_to_raise, exc):
    """
    Generates a new exception class of the requested type (subclass of LDAPCommunication) merged with the exception raised by the interpreter
    """
    if exc_to_raise.__name__ in [cls.__name__ for cls in LDAPCommunicationError.__subclasses__()]:
        return type(exc_to_raise.__name__, (exc_to_raise, type(exc)), dict())
    else:
        raise LDAPExceptionError('unable to generate exception type ' + str(exc_to_raise))


def start_tls_exception_factory(exc_to_raise, exc):
    """
    Generates a new exception class of the requested type (subclass of LDAPCommunication) merged with the exception raised by the interpreter
    """

    if exc_to_raise.__name__ == 'LDAPStartTLSError':
        return type(exc_to_raise.__name__, (exc_to_raise, type(exc)), dict())
    else:
        raise LDAPExceptionError('unable to generate exception type ' + str(exc_to_raise))